Microservice Scaffolder
Run ID: 69cc1eaf04066a6c4a16987a2026-03-31Development
PantheraHive BOS
BOS Dashboard

As part of the "Microservice Scaffolder" workflow, this deliverable provides a complete, production-ready microservice scaffold. This includes the core application code, Docker setup for containerization, a comprehensive testing suite, a CI/CD pipeline configuration, and basic deployment scripts.

The microservice is designed around a common "Product Service" example, demonstrating CRUD (Create, Read, Update, Delete) operations for products. It utilizes Python with FastAPI for the API, PostgreSQL as the database, and SQLAlchemy for ORM.


Microservice Scaffolding: Product Service

This section details the generated code and configurations for your new microservice.

1. Project Structure

The generated project follows a standard, organized structure to enhance maintainability and scalability.

text • 1,520 chars
.
├── .github/
│   └── workflows/
│       └── ci.yml                 # GitHub Actions CI/CD pipeline configuration
├── app/
│   ├── api/
│   │   └── v1/
│   │       └── endpoints/
│   │           └── products.py    # API endpoints for product CRUD operations
│   ├── crud/
│   │   └── product.py             # CRUD operations for database interaction
│   ├── models/
│   │   └── product.py             # SQLAlchemy ORM model for Product
│   ├── schemas/
│   │   └── product.py             # Pydantic schemas for data validation
│   ├── __init__.py                # Python package init
│   ├── config.py                  # Application configuration
│   └── database.py                # Database connection and session management
├── scripts/
│   └── deploy.sh                  # Basic deployment script
├── tests/
│   ├── __init__.py
│   ├── conftest.py                # Pytest fixtures for database and client setup
│   ├── test_main.py               # Basic application health check tests
│   └── test_products.py           # API integration tests for product endpoints
├── .dockerignore                  # Files to ignore when building Docker image
├── Dockerfile                     # Docker configuration for the application
├── docker-compose.yml             # Docker Compose for local development (app + db)
├── main.py                        # Main FastAPI application entry point
├── requirements.txt               # Python dependencies
└── README.md                      # Project README and setup instructions
Sandboxed live preview

This document outlines the architectural plan for a robust microservice and provides a comprehensive study plan for understanding and implementing such services. This output serves as a foundational deliverable for the "Microservice Scaffolder" workflow, specifically detailing the design principles and technology choices for the generated microservice, followed by a learning path to master these concepts.


Part 1: Microservice Architectural Plan

This section details the proposed architecture for a high-performance, scalable, and maintainable microservice. This plan will guide the scaffolding process, ensuring all generated components adhere to industry best practices.

Target Technology Stack:

  • Language & Framework: Python 3.10+ with FastAPI (for high performance and async capabilities)
  • Database: PostgreSQL (for robust relational data management)
  • ORM: SQLAlchemy 2.0+ (for flexible and powerful database interaction)
  • Containerization: Docker
  • CI/CD: GitHub Actions
  • Deployment: Kubernetes (via Helm charts and optionally Terraform for infrastructure)
  • API Documentation: OpenAPI (integrated with FastAPI)
  • Testing: Pytest

1. Core Microservice Structure

The generated microservice will follow a clean, modular project structure designed for clarity and maintainability.

  • Project Root (/): Contains configuration files, Dockerfiles, CI/CD workflows, and top-level scripts.
  • src/: The main application source code.

* main.py: FastAPI application entry point, defining global dependencies and routers.

* api/: Contains API routers, each representing a logical resource or domain.

* v1/: Versioned API endpoints.

* items/: router.py for /items endpoints.

* users/: router.py for /users endpoints.

* services/: Business logic layer, orchestrating data access and external interactions.

* item_service.py: Logic for item-related operations.

* user_service.py: Logic for user-related operations.

* models/: Database models (SQLAlchemy ORM definitions).

* base.py: Base class for declarative models.

* item.py: Item model definition.

* user.py: User model definition.

* schemas/: Pydantic models for request/response validation and serialization.

* item_schema.py: Pydantic models for Item requests/responses.

* user_schema.py: Pydantic models for User requests/responses.

* dependencies/: Common dependencies (e.g., database session, authentication).

* core/: Core utilities, settings, exceptions, and logging configuration.

* config.py: Centralized application settings (using Pydantic's BaseSettings).

* database.py: Database engine and session management.

* exceptions.py: Custom application exceptions.

* tests/: Unit and integration tests.

* conftest.py: Pytest fixtures.

* unit/: Unit tests for services, models, schemas.

* integration/: Integration tests for API endpoints.

  • migrations/: Alembic scripts for database schema migrations.
  • docs/: Additional documentation (e.g., API usage examples, architectural decisions).

2. API Design and Definition

  • RESTful Principles: API endpoints will adhere to RESTful conventions (e.g., /items, /items/{id}, using standard HTTP methods like GET, POST, PUT, DELETE).
  • Versioned APIs: All APIs will be versioned (e.g., /api/v1/items) to allow for backward compatibility and graceful evolution.
  • OpenAPI Documentation: FastAPI automatically generates OpenAPI (Swagger) documentation, providing an interactive UI for API exploration (/docs). This will be enhanced with descriptive summaries and examples.
  • Request/Response Validation: Pydantic models will be used extensively for automatic request body validation, query parameter validation, and response serialization, ensuring data integrity and clear API contracts.
  • Asynchronous Operations: Leveraging FastAPI's async capabilities for non-blocking I/O operations, improving concurrency and throughput.

3. Data Layer

  • Database Choice: PostgreSQL is chosen for its robustness, ACID compliance, and extensive feature set, suitable for most microservice data needs.
  • ORM: SQLAlchemy 2.0+ will be used for object-relational mapping, providing a Pythonic way to interact with the database.

* Declarative Models: Database tables will be defined as Python classes.

* Session Management: Database sessions will be managed using FastAPI's dependency injection system, ensuring proper connection handling and transaction isolation.

  • Database Migrations: Alembic will be integrated to manage database schema changes, allowing for controlled evolution of the database alongside code changes.
  • Connection Pooling: SQLAlchemy's connection pooling will be configured to efficiently manage database connections.

4. Containerization (Docker)

  • Dockerfile: A lean, multi-stage Dockerfile will be provided to build a production-ready container image for the microservice.

* Base Image: Official Python slim image.

* Dependencies: poetry for dependency management, or pip with requirements.txt.

* Application Code: Copying application code.

* Entrypoint: Uvicorn with Gunicorn for production-grade ASGI server.

  • Docker Compose: A docker-compose.yml file will be generated for local development, enabling quick setup of the microservice along with a local PostgreSQL database and potentially other services (e.g., adminer for database GUI).

5. Testing Strategy

A comprehensive testing suite is crucial for microservice reliability.

  • Unit Tests: Pytest will be used to test individual functions, classes, and components (e.g., services, models, schemas) in isolation. Mocking will be used for external dependencies.
  • Integration Tests: Testing the interaction between components, such as API endpoints with the database. A test database (e.g., a separate PostgreSQL instance or an in-memory SQLite for simpler cases) will be used.
  • End-to-End (E2E) Tests: (Optional, but recommended for critical paths) Testing the entire flow from client request to database interaction and response. This might involve tools like Playwright or Selenium, or simply extended integration tests.
  • Test Coverage: Code coverage reports (e.g., using pytest-cov) will be integrated into the CI/CD pipeline to ensure adequate test coverage.

6. CI/CD Pipeline Configuration (GitHub Actions)

A /.github/workflows/main.yml file will define the CI/CD pipeline.

  • Continuous Integration (CI):

* Triggers: On push to main and feature branches, and pull requests.

* Steps:

1. Checkout code.

2. Set up Python environment.

3. Install dependencies.

4. Run linters (e.g., Black, Flake8, MyPy).

5. Run unit and integration tests.

6. Generate test coverage report.

7. Build Docker image.

8. Push Docker image to container registry (e.g., GitHub Container Registry, Docker Hub, ECR).

  • Continuous Deployment (CD): (Triggered on push to main or specific tags)

* Steps:

1. Pull the latest Docker image.

2. Update Kubernetes deployment (via Helm or kubectl).

3. Run database migrations (if applicable, using a dedicated job).

4. Health checks.

7. Deployment Strategy

  • Container Orchestration: Kubernetes is the default choice for production deployment due to its scalability, self-healing, and resource management capabilities.
  • Helm Charts: A Helm chart will be generated to simplify the deployment and management of the microservice on Kubernetes. This includes:

* Deployment (for the application pods).

* Service (for internal/external access).

* Ingress (for external HTTP/HTTPS access).

* Horizontal Pod Autoscaler (HPA) definition.

* Resource limits and requests.

  • Infrastructure as Code (IaC): (Optional, but recommended) Terraform scripts can be provided to provision the underlying cloud infrastructure (e.g., EKS cluster on AWS, GKE on GCP, AKS on Azure), database instances, and networking components.
  • Environment Configuration: Configuration will be managed via Kubernetes Secrets for sensitive data and ConfigMaps for non-sensitive settings, injected into the application as environment variables.

8. Observability

  • Logging: Structured logging (e.g., using python-json-logger) to stdout/stderr, allowing collection by external log aggregators (e.g., ELK Stack, Splunk, CloudWatch Logs). Log levels will be configurable.
  • Monitoring:

* Metrics: Exposing Prometheus-compatible metrics (e.g., using prometheus-client or fastapi-prometheus) for request rates, error rates, latency, and custom business metrics.

* Health Checks: Standard /health and /ready endpoints for Kubernetes liveness and readiness probes.

  • Tracing: (Optional, but recommended for complex systems) Integration with OpenTelemetry to enable distributed tracing, providing visibility into request flows across multiple services.

9. Security

  • Authentication: JWT-based authentication using OAuth2 bearer tokens, integrated via FastAPI's security dependencies.
  • Authorization: Role-Based Access Control (RBAC) implemented through custom FastAPI dependencies, checking user roles/permissions against requested resources.
  • Secrets Management: Environment variables for local development, and Kubernetes Secrets / cloud-specific secret managers (e.g., AWS Secrets Manager, GCP Secret Manager) for production.
  • Input Validation: Strict Pydantic validation on all incoming API requests.
  • Dependency Scanning: Integration of tools like Dependabot or Snyk into the CI/CD pipeline to identify and mitigate known vulnerabilities in dependencies.

10. Configuration Management

  • Centralized Configuration: All application settings will be managed via Pydantic's `Base

app/database.py - Database Connection and Session

gemini Output

Microservice Scaffolding Complete: Comprehensive Deliverable

We are pleased to present the complete microservice scaffold, meticulously generated to provide a robust, scalable, and production-ready foundation for your new service. This deliverable includes the core application code, Dockerization, a comprehensive testing suite, CI/CD pipeline configuration, and initial deployment scripts, all designed for efficiency and ease of use.


1. Introduction and Overview

This package provides a fully functional microservice template, developed using Python 3.10+ and the FastAPI framework, backed by PostgreSQL (via SQLAlchemy). It adheres to modern best practices for development, testing, and deployment, ensuring a solid starting point for your project.

Key Features:

  • API-First Design: Clear, well-defined RESTful API endpoints.
  • Containerized: Docker support for consistent development and deployment environments.
  • Database Integration: ORM models with migrations for PostgreSQL.
  • Automated Testing: Unit and integration tests to ensure code quality.
  • CI/CD Ready: Pre-configured GitHub Actions pipeline for continuous integration and deployment.
  • Deployment Assets: Kubernetes manifests and cloud-agnostic deployment scripts.
  • Comprehensive Documentation: Auto-generated API docs and project README.

2. Core Microservice Application (Python/FastAPI)

The application is structured for clarity and maintainability, separating concerns into distinct modules.

2.1 Project Structure


├── my_microservice/
│   ├── api/
│   │   ├── __init__.py
│   │   └── endpoints/
│   │       ├── __init__.py
│   │       ├── items.py      # Example API routes for 'items'
│   │       └── users.py      # Example API routes for 'users'
│   ├── crud/                 # Create, Read, Update, Delete operations
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   ├── database/
│   │   ├── __init__.py
│   │   ├��─ base.py           # Base for SQLAlchemy models
│   │   ├── session.py        # Database session management
│   │   └── models.py         # SQLAlchemy ORM models
│   ├── schemas/              # Pydantic models for request/response validation
│   │   ├── __init__.py
│   │   ├── items.py
│   │   └── users.py
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py         # Application configuration settings
│   │   └── security.py       # Security utilities (e.g., JWT, password hashing)
│   ├── main.py               # FastAPI application entry point
│   └── dependencies.py       # Common dependencies for API routes
├── alembic/                  # Database migration scripts
│   ├── versions/
│   └── env.py
│   └── script.py.mako
├── tests/
│   ├── __init__.py
│   ├── unit/
│   │   ├── test_models.py
│   │   └── test_crud.py
│   ├── integration/
│   │   └── test_api_items.py
│   │   └── test_api_users.py
├── .github/
│   └── workflows/
│       └── ci-cd.yml         # GitHub Actions pipeline
├── kubernetes/
│   ├── deployment.yml
│   ├── service.yml
│   └── ingress.yml (optional)
├── scripts/
│   ├── deploy_to_cloud.sh    # Generic cloud deployment script
│   └── build_and_push.sh     # Script to build Docker image and push to registry
├── .env.example              # Example environment variables
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
├── README.md
└── alembic.ini

2.2 API Routes and Schemas

The application includes example API routes for items and users, demonstrating standard CRUD operations.

Example Endpoints:

  • Items:

* POST /api/v1/items/ - Create a new item.

* GET /api/v1/items/ - Retrieve all items.

* GET /api/v1/items/{item_id} - Retrieve a specific item.

* PUT /api/v1/items/{item_id} - Update an item.

* DELETE /api/v1/items/{item_id} - Delete an item.

  • Users:

* POST /api/v1/users/ - Register a new user.

* GET /api/v1/users/ - Retrieve all users.

* GET /api/v1/users/{user_id} - Retrieve a specific user.

* PUT /api/v1/users/{user_id} - Update a user.

* DELETE /api/v1/users/{user_id} - Delete a user.

* POST /api/v1/login/access-token - User authentication (JWT token generation).

Pydantic Schemas (my_microservice/schemas/):

These define the data structures for API requests and responses, ensuring robust data validation and clear API contracts.

  • ItemBase, ItemCreate, ItemUpdate, ItemInDB, Item
  • UserBase, UserCreate, UserUpdate, UserInDB, User
  • Token, TokenData for authentication.

2.3 Database Models (SQLAlchemy/Alembic)

The my_microservice/database/models.py file defines the SQLAlchemy ORM models that map to your PostgreSQL database tables.

Example Models:

  • User Model:

* id (UUID, Primary Key)

* email (String, Unique)

* hashed_password (String)

* is_active (Boolean, default True)

* created_at (DateTime)

* updated_at (DateTime)

* items (Relationship to Item model)

  • Item Model:

* id (UUID, Primary Key)

* title (String)

* description (String, Optional)

* owner_id (UUID, Foreign Key to User)

* created_at (DateTime)

* updated_at (DateTime)

* owner (Relationship to User model)

Database Migrations (Alembic):

Alembic is configured for managing database schema changes.

  • To generate a new migration: alembic revision --autogenerate -m "Add new table"
  • To apply migrations: alembic upgrade head

2.4 Configuration (my_microservice/core/config.py)

Application settings are managed using Pydantic's BaseSettings, allowing for environment variable overrides.

Key configurations include:

  • PROJECT_NAME
  • DATABASE_URL
  • SECRET_KEY for JWT
  • ACCESS_TOKEN_EXPIRE_MINUTES
  • API_V1_STR (e.g., /api/v1)

3. Dockerization

The project includes all necessary files to containerize your microservice, providing a consistent environment across development, testing, and production.

3.1 Dockerfile

Defines the steps to build a Docker image for your application.

  • Uses a multi-stage build for smaller final images.
  • Installs dependencies, copies application code, and sets up the entrypoint.
  • Optimized for Python applications.

3.2 docker-compose.yml

Facilitates local development by orchestrating the application and its dependencies (e.g., PostgreSQL database).

Services Defined:

  • app: Your FastAPI microservice.
  • db: A PostgreSQL database instance.
  • adminer (optional): A web-based database management tool for easy access during development.

Usage:

  • Start services: docker-compose up --build
  • Run migrations within the container: docker-compose exec app alembic upgrade head
  • Access the application: http://localhost:8000 (or configured port)
  • Access auto-generated API docs (Swagger UI): http://localhost:8000/docs
  • Access auto-generated API docs (ReDoc): http://localhost:8000/redoc

4. Testing Suite

A comprehensive testing suite is provided using pytest to ensure the reliability and correctness of your microservice.

4.1 Test Structure (tests/)

  • unit/: Contains tests for individual components, functions, and ORM models, isolated from external dependencies (e.g., database).

* test_models.py: Tests ORM model definitions and methods.

* test_crud.py: Tests CRUD operations logic in my_microservice/crud/.

  • integration/: Contains tests that verify the interaction between different components, including API endpoints and database interactions.

* test_api_items.py: Tests the /api/v1/items endpoints.

* test_api_users.py: Tests the /api/v1/users and authentication endpoints.

4.2 Test Runner (pytest)

pytest is configured with fixtures for database setup (e.g., an in-memory SQLite for unit tests or a dedicated test PostgreSQL for integration tests via docker-compose).

How to Run Tests:

  1. Ensure development environment is set up (e.g., pip install -r requirements.txt).
  2. Run all tests: pytest
  3. Run specific tests: pytest tests/unit/test_models.py
  4. Run tests with coverage report: pytest --cov=my_microservice --cov-report=term-missing

5. CI/CD Pipeline Configuration (GitHub Actions)

A pre-configured CI/CD pipeline using GitHub Actions is provided to automate the build, test, and deployment process for your microservice.

5.1 Pipeline File (.github/workflows/ci-cd.yml)

Stages:

  1. Build & Test:

* Triggers on push to main branch and pull_request to main.

* Sets up Python environment.

* Installs dependencies.

* Lints code (flake8, black).

* Runs pytest with coverage.

* Builds the Docker image.

  1. Push to Container Registry:

* Triggers on push to main branch.

* Logs into a specified container registry (e.g., Docker Hub, AWS ECR, GCP GCR).

* Pushes the built Docker image with appropriate tags (e.g., latest, commit SHA).

* Actionable: Configure DOCKER_USERNAME, DOCKER_PASSWORD (or cloud provider credentials) as GitHub Secrets.

  1. Deploy to Kubernetes (Example):

* Triggers on successful push to main branch.

* Uses kubectl to apply the Kubernetes manifests from the kubernetes/ directory.

* Actionable: Configure KUBECONFIG or cloud provider authentication (e.g., AWS IAM roles, GCP Workload Identity) as GitHub Secrets. This step is a placeholder and may require customization based on your specific Kubernetes cluster setup and cloud provider.


6. Deployment Scripts

Initial deployment scripts are provided to assist with pushing your container image and deploying to a target environment.

6.1 scripts/build_and_push.sh

A simple shell script to build your Docker image and push it to a specified container registry.

Usage:


./scripts/build_and_push.sh my-registry/my-microservice:v1.0.0
  • Actionable: Update the script with your specific registry login command if not using default Docker Hub.

6.2 kubernetes/ Manifests

Contains basic Kubernetes manifests for deploying your microservice to a Kubernetes cluster.

  • deployment.yml: Defines the desired state for your application (number of replicas, container image, ports, environment variables).
  • service.yml: Defines how to access your application within the cluster (e.g., ClusterIP, NodePort, LoadBalancer).
  • ingress.yml (optional): Defines external access to your service via an Ingress controller.

Usage (assuming kubectl is configured):


kubectl apply -f kubernetes/deployment.yml
kubectl apply -f kubernetes/service.yml
# kubectl apply -f kubernetes/ingress.yml
  • Actionable: Review and customize these manifests (e.g., resource requests/limits, probes, environment variables, image pull secrets) for your production environment.

6.3 scripts/deploy_to_cloud.sh (Generic Example)

This is a placeholder script for a generic cloud deployment. It demonstrates the conceptual steps.

Example Conceptual Steps:

  1. Build Docker image.
  2. Push to cloud container registry (e.g., AWS ECR, GCP GCR, Azure ACR).
  3. Update/create cloud resources (e.g., AWS ECS Task Definition/Service, GCP Cloud Run service, Azure App Service).
  • Actionable: This script requires significant customization based on your chosen cloud provider and specific deployment strategy (e.g., AWS ECS Fargate, GCP Cloud Run, Azure Kubernetes Service, etc.). We recommend integrating this logic directly into your CI/CD pipeline.

7. Documentation

7.1 README.md

A comprehensive README.md is included at the project root, covering:

  • Project description.
  • Local setup instructions (Python environment, Docker Compose).
microservice_scaffolder.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
\n\n\n"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport './index.css'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n \n \n \n)\n"); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react'\nimport './App.css'\n\nfunction App(){\n return(\n
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n
\n )\n}\nexport default App\n"); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e}\n.app{min-height:100vh;display:flex;flex-direction:column}\n.app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px}\nh1{font-size:2.5rem;font-weight:700}\n"); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\n## Open in IDE\nOpen the project folder in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "type": "module",\n "scripts": {\n "dev": "vite",\n "build": "vue-tsc -b && vite build",\n "preview": "vite preview"\n },\n "dependencies": {\n "vue": "^3.5.13",\n "vue-router": "^4.4.5",\n "pinia": "^2.3.0",\n "axios": "^1.7.9"\n },\n "devDependencies": {\n "@vitejs/plugin-vue": "^5.2.1",\n "typescript": "~5.7.3",\n "vite": "^6.0.5",\n "vue-tsc": "^2.2.0"\n }\n}\n'); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite'\nimport vue from '@vitejs/plugin-vue'\nimport { resolve } from 'path'\n\nexport default defineConfig({\n plugins: [vue()],\n resolve: { alias: { '@': resolve(__dirname,'src') } }\n})\n"); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}\n'); zip.file(folder+"tsconfig.app.json",'{\n "compilerOptions":{\n "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"],\n "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true,\n "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue",\n "strict":true,"paths":{"@/*":["./src/*"]}\n },\n "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"]\n}\n'); zip.file(folder+"env.d.ts","/// \n"); zip.file(folder+"index.html","\n\n\n \n \n "+slugTitle(pn)+"\n\n\n
\n \n\n\n"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue'\nimport { createPinia } from 'pinia'\nimport App from './App.vue'\nimport './assets/main.css'\n\nconst app = createApp(App)\napp.use(createPinia())\napp.mount('#app')\n"); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue","\n\n\n\n\n"); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547}\n"); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nnpm run dev\n\`\`\`\n\n## Build\n\`\`\`bash\nnpm run build\n\`\`\`\n\nOpen in VS Code or WebStorm.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n"); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{\n "name": "'+pn+'",\n "version": "0.0.0",\n "scripts": {\n "ng": "ng",\n "start": "ng serve",\n "build": "ng build",\n "test": "ng test"\n },\n "dependencies": {\n "@angular/animations": "^19.0.0",\n "@angular/common": "^19.0.0",\n "@angular/compiler": "^19.0.0",\n "@angular/core": "^19.0.0",\n "@angular/forms": "^19.0.0",\n "@angular/platform-browser": "^19.0.0",\n "@angular/platform-browser-dynamic": "^19.0.0",\n "@angular/router": "^19.0.0",\n "rxjs": "~7.8.0",\n "tslib": "^2.3.0",\n "zone.js": "~0.15.0"\n },\n "devDependencies": {\n "@angular-devkit/build-angular": "^19.0.0",\n "@angular/cli": "^19.0.0",\n "@angular/compiler-cli": "^19.0.0",\n "typescript": "~5.6.0"\n }\n}\n'); zip.file(folder+"angular.json",'{\n "$schema": "./node_modules/@angular/cli/lib/config/schema.json",\n "version": 1,\n "newProjectRoot": "projects",\n "projects": {\n "'+pn+'": {\n "projectType": "application",\n "root": "",\n "sourceRoot": "src",\n "prefix": "app",\n "architect": {\n "build": {\n "builder": "@angular-devkit/build-angular:application",\n "options": {\n "outputPath": "dist/'+pn+'",\n "index": "src/index.html",\n "browser": "src/main.ts",\n "tsConfig": "tsconfig.app.json",\n "styles": ["src/styles.css"],\n "scripts": []\n }\n },\n "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"}\n }\n }\n }\n}\n'); zip.file(folder+"tsconfig.json",'{\n "compileOnSave": false,\n "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]},\n "references":[{"path":"./tsconfig.app.json"}]\n}\n'); zip.file(folder+"tsconfig.app.json",'{\n "extends":"./tsconfig.json",\n "compilerOptions":{"outDir":"./dist/out-tsc","types":[]},\n "files":["src/main.ts"],\n "include":["src/**/*.d.ts"]\n}\n'); zip.file(folder+"src/index.html","\n\n\n \n "+slugTitle(pn)+"\n \n \n \n\n\n \n\n\n"); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\n\nbootstrapApplication(AppComponent, appConfig)\n .catch(err => console.error(err));\n"); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; }\nbody { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; }\n"); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core';\nimport { RouterOutlet } from '@angular/router';\n\n@Component({\n selector: 'app-root',\n standalone: true,\n imports: [RouterOutlet],\n templateUrl: './app.component.html',\n styleUrl: './app.component.css'\n})\nexport class AppComponent {\n title = '"+pn+"';\n}\n"); zip.file(folder+"src/app/app.component.html","
\n
\n

"+slugTitle(pn)+"

\n

Built with PantheraHive BOS

\n
\n \n
\n"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1}\n"); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';\nimport { provideRouter } from '@angular/router';\nimport { routes } from './app.routes';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n provideZoneChangeDetection({ eventCoalescing: true }),\n provideRouter(routes)\n ]\n};\n"); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router';\n\nexport const routes: Routes = [];\n"); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\nng serve\n# or: npm start\n\`\`\`\n\n## Build\n\`\`\`bash\nng build\n\`\`\`\n\nOpen in VS Code with Angular Language Service extension.\n"); zip.file(folder+".gitignore","node_modules/\ndist/\n.env\n.DS_Store\n*.local\n.angular/\n"); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join("\n"):"# add dependencies here\n"; zip.file(folder+"main.py",src||"# "+title+"\n# Generated by PantheraHive BOS\n\nprint(title+\" loaded\")\n"); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\npython3 -m venv .venv\nsource .venv/bin/activate\npip install -r requirements.txt\n\`\`\`\n\n## Run\n\`\`\`bash\npython main.py\n\`\`\`\n"); zip.file(folder+".gitignore",".venv/\n__pycache__/\n*.pyc\n.env\n.DS_Store\n"); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^\`\`\`[\w]*\n?/m,"").replace(/\n?\`\`\`$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+"\n"; zip.file(folder+"package.json",pkgJson); var fallback="const express=require(\"express\");\nconst app=express();\napp.use(express.json());\n\napp.get(\"/\",(req,res)=>{\n res.json({message:\""+title+" API\"});\n});\n\nconst PORT=process.env.PORT||3000;\napp.listen(PORT,()=>console.log(\"Server on port \"+PORT));\n"; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000\n"); zip.file(folder+".gitignore","node_modules/\n.env\n.DS_Store\n"); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Setup\n\`\`\`bash\nnpm install\n\`\`\`\n\n## Run\n\`\`\`bash\nnpm run dev\n\`\`\`\n"); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:"\n\n\n\n\n"+title+"\n\n\n\n"+code+"\n\n\n\n"; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */\n*{margin:0;padding:0;box-sizing:border-box}\nbody{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e}\n"); zip.file(folder+"script.js","/* "+title+" — scripts */\n"); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\n## Open\nDouble-click \`index.html\` in your browser.\n\nOr serve locally:\n\`\`\`bash\nnpx serve .\n# or\npython3 -m http.server 3000\n\`\`\`\n"); zip.file(folder+".gitignore",".DS_Store\nnode_modules/\n.env\n"); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/\.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/\*\*(.+?)\*\*/g,"$1"); hc=hc.replace(/\n{2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+"\n\nGenerated by PantheraHive BOS.\n\nFiles:\n- "+app+".md (Markdown)\n- "+app+".html (styled HTML)\n"); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); } function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}