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

This deliverable provides a complete, production-ready microservice scaffold, designed to accelerate your development process. It includes a robust API, database integration, containerization setup, testing framework, CI/CD pipeline configuration, and basic deployment scripts.


Microservice Scaffolder: Product Service

This scaffold generates a "Product Service" – a simple microservice demonstrating CRUD (Create, Read, Update, Delete) operations for managing products. It's built with Python, FastAPI, SQLAlchemy, and PostgreSQL, containerized with Docker, tested with Pytest, and includes a GitHub Actions CI/CD pipeline.

1. Project Overview

The generated microservice provides the following functionalities:

2. Project Structure

The project is organized into a modular and maintainable structure:

text • 1,558 chars
.
├── .github/                               # GitHub Actions CI/CD workflows
│   └── workflows/
│       └── main.yml                       # CI/CD pipeline definition
├── app/                                   # Core microservice application
│   ├── api/
│   │   └── v1/
│   │       └── endpoints/
│   │           └── products.py            # API endpoints for products
│   ├── core/
│   │   ├── config.py                      # Application configuration (env vars)
│   │   └── database.py                    # Database connection and session management
│   ├── models/
│   │   └── product.py                     # SQLAlchemy database model for Product
│   ├── schemas/
│   │   └── product.py                     # Pydantic schemas for request/response validation
│   ├── main.py                            # Main FastAPI application entry point
│   └── crud.py                            # CRUD operations for products
├── tests/                                 # Unit and integration tests
│   └── test_products.py                   # Tests for product endpoints
├── Dockerfile                             # Docker image definition for the application
├── docker-compose.yml                     # Docker Compose for local development (app + DB)
├── requirements.txt                       # Python dependencies
├── .dockerignore                          # Files/directories to exclude from Docker build context
├── deploy.sh                              # Example deployment script
└── README.md                              # Project README (placeholder)
Sandboxed live preview

Microservice Scaffolding: Architecture Plan

Project Title: Generic Microservice Scaffolding Architecture

Date: October 26, 2023

Prepared For: Customer Deliverable - Microservice Scaffolder Workflow


1. Overview and Architectural Goals

This document outlines a comprehensive architectural plan for a generic microservice, designed to serve as a robust and scalable scaffold. The goal is to provide a detailed blueprint covering core service components, technology stack, API design, data management, containerization, testing, CI/CD, and deployment strategies. This plan emphasizes best practices for maintainability, reliability, security, and developer experience.

Architectural Goals:

  • Modularity & Maintainability: Clear separation of concerns, easy to understand and modify.
  • Scalability: Designed to handle increasing load through horizontal scaling.
  • Reliability: Robust error handling, resilience patterns (where applicable).
  • Security: Built-in security considerations for authentication, authorization, and data protection.
  • Observability: Integrated logging, monitoring, and tracing capabilities.
  • Developer Experience (DX): Streamlined development, testing, and deployment processes.
  • Portability: Containerized for consistent execution across environments.
  • Automation: Full CI/CD pipeline for automated build, test, and deployment.

2. Proposed Technology Stack

To provide a concrete and actionable scaffold, we propose the following modern and widely adopted technology stack:

  • Programming Language: Python 3.10+
  • Web Framework: FastAPI (for its performance, automatic OpenAPI/Swagger generation, and type hints)
  • Database: PostgreSQL (Relational, robust, ACID compliant)
  • ORM (Object-Relational Mapper): SQLAlchemy 2.0+ (with asyncpg for async capabilities)
  • Database Migrations: Alembic
  • Containerization: Docker
  • Local Orchestration: Docker Compose
  • Testing Framework: Pytest (with pytest-asyncio, httpx)
  • CI/CD Platform: GitHub Actions
  • Cloud Provider (Deployment Target): AWS
  • Deployment Orchestration: AWS Elastic Container Service (ECS) with Fargate
  • Infrastructure as Code (IaC): AWS CloudFormation (or Terraform as an alternative, but CloudFormation for AWS focus)
  • API Documentation: OpenAPI 3.0 (automatically generated by FastAPI, served via Swagger UI/ReDoc)

3. Core Architectural Components & Design

3.1. Microservice Core

  • Structure:

* app/

* __init__.py

* main.py: FastAPI application instance, global middleware, event handlers.

* api/: Defines API routers and endpoints.

* v1/: API versioning.

* endpoints/: Individual resource endpoints (e.g., users.py, items.py).

* deps.py: Dependency injection providers (e.g., database session, current user).

* core/: Core application logic and utilities.

* config.py: Application settings (Pydantic BaseSettings).

* exceptions.py: Custom exception definitions and handlers.

* security.py: JWT handling, password hashing.

* crud/: Create, Read, Update, Delete operations on database models.

* db/: Database connection, session management.

* base.py: Base declarative model.

* session.py: Async session, engine.

* models/: SQLAlchemy ORM models.

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

* services/: Business logic, orchestrating CRUD operations and external integrations.

* tests/: Unit and integration tests.

  • API Design (RESTful Principles):

* Resource-Oriented: Endpoints represent resources (e.g., /users, /items).

* HTTP Methods: Use standard methods (GET, POST, PUT, DELETE, PATCH).

* Versioning: URI-based versioning (e.g., /api/v1/users).

* Status Codes: Utilize standard HTTP status codes for responses (200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error).

* Request/Response Formats: JSON for data exchange.

* Error Handling: Consistent JSON error responses with clear code, message, and optional details.

  • Authentication & Authorization:

* Authentication: JSON Web Tokens (JWT) for stateless authentication. FastAPI's security utilities (OAuth2PasswordBearer) will be used.

* Authorization: Role-Based Access Control (RBAC) implemented via dependencies that check user roles/permissions.

  • Configuration: Environment variables for sensitive data and deployment-specific settings, managed via Pydantic BaseSettings.

3.2. Database Setup

  • Database Type: PostgreSQL.
  • Schema Design:

* SQLAlchemy ORM models define table structures, relationships (one-to-many, many-to-many).

* Primary keys, foreign keys, unique constraints, and indices will be defined for data integrity and performance.

* Timestamp fields (created_at, updated_at) for auditability.

  • Migrations: Alembic will manage database schema changes, allowing for version-controlled and reversible migrations.
  • Connection Pooling: Asynchronous database driver (asyncpg) with SQLAlchemy's async engine for efficient connection management.

3.3. Dockerization

  • Dockerfile:

* Multi-stage build to create lean production images.

* Use an official Python base image.

* Copy requirements.txt and install dependencies early for layer caching.

* Copy application code.

* Expose application port.

* Define CMD to run the application using uvicorn (ASGI server).

* Non-root user for security.

  • docker-compose.yml:

* Defines services for local development: app (FastAPI service), db (PostgreSQL).

* Mount volumes for code changes (app) and persistent database data (db).

* Environment variables for database connection.

* Network configuration for inter-service communication.

3.4. API Documentation

  • FastAPI automatically generates OpenAPI (Swagger/ReDoc) documentation based on Pydantic models and endpoint definitions.
  • Accessible at /docs (Swagger UI) and /redoc (ReDoc) by default, providing interactive API exploration.

3.5. Testing Strategy

  • Unit Tests:

* Focus: Individual functions, methods, and classes in isolation.

* Tools: Pytest, unittest.mock for mocking dependencies (e.g., database calls, external services).

* Location: app/tests/unit/.

  • Integration Tests:

* Focus: Interaction between components (e.g., API endpoints with database, service layer with ORM).

* Tools: Pytest, httpx for making HTTP requests to the test application, in-memory or dedicated test database.

* Location: app/tests/integration/.

  • Test Database: Use a separate PostgreSQL database instance (or a transactional rollback approach) for integration tests to ensure isolation and prevent data corruption.
  • Code Coverage: Integrate pytest-cov to track test coverage, aiming for a high percentage (e.g., 80%+).

4. CI/CD Pipeline Configuration (GitHub Actions)

A robust CI/CD pipeline ensures automated quality checks and deployment.

  • Trigger: Push to main branch, pull requests to main.
  • Stages:

1. Linting & Formatting:

* Tools: Black (formatter), Flake8 (linter), isort (import sorter).

* Action: Check code style and report issues.

2. Security Scanning:

* Tools: Bandit (security linter for Python), Trivy (vulnerability scanner for Docker images).

* Action: Scan application code and Docker image for known vulnerabilities.

3. Build:

* Action: Build Docker image for the microservice.

* Artifact: Tagged Docker image.

4. Test:

* Action: Run unit and integration tests inside a containerized environment (using a test database).

* Action: Generate test coverage report.

* Artifact: Test results, coverage report.

5. Publish (on successful main branch merge):

* Action: Push Docker image to AWS Elastic Container Registry (ECR).

6. Deploy (on successful main branch merge):

* Action: Update AWS ECS service with the new Docker image.

* Tools: AWS CLI, aws-actions/amazon-ecs-deploy-task-definition.


5. Deployment Scripts & Strategy

5.1. Target Environment

  • Cloud Provider: AWS
  • Compute: AWS Elastic Container Service (ECS) with Fargate launch type. Fargate eliminates the need to manage EC2 instances, simplifying operations.
  • Networking: AWS Virtual Private Cloud (VPC), private subnets, Application Load Balancer (ALB) for traffic distribution, Security Groups.
  • Database: AWS Relational Database Service (RDS) for PostgreSQL, deployed in private subnets.

5.2. Infrastructure as Code (IaC)

  • Tool: AWS CloudFormation (or Terraform).
  • Templates:

* VPC Stack: Defines VPC, subnets, internet gateway, NAT gateways.

* RDS Stack: Defines PostgreSQL instance (size, version, security groups, backups).

* ECS Cluster Stack: Defines ECS cluster, Task Definitions (CPU, memory, container image, environment variables), ECS Service (desired count, load balancer attachment).

* Load Balancer Stack: Defines Application Load Balancer, listener, target groups.

* IAM Roles: Defines necessary IAM roles for ECS tasks, CI/CD, etc.

  • Deployment Flow: CloudFormation templates will be applied via CI/CD, creating or updating the AWS resources.

5.3. Environment Variables & Secrets Management

  • Non-sensitive configs: Passed via Task Definition environment variables.
  • Sensitive configs (e.g., database credentials, API keys): Stored in AWS Secrets Manager and injected into ECS tasks at runtime.

5.4. Blue/Green Deployment (Advanced - for future consideration)

  • Utilize ALB target groups and ECS deployment strategies to enable zero-downtime blue/green deployments, allowing new versions to be tested in production before routing all traffic.

6. Observability

  • Logging:

* Structured Logging: Use a Python logging library (e.g., logging with python-json-logger) to emit logs in JSON format.

* Centralized Logging: Container logs will be forwarded to AWS CloudWatch Logs. Log groups and streams will be configured.

* Log Levels: Implement standard levels (DEBUG, INFO, WARNING, ERROR, CRITICAL).

  • Monitoring:

* Metrics:

* Application Metrics: Custom metrics (e

python

from fastapi import APIRouter, Depends, HTTPException, status

from sqlalchemy.orm import Session

from typing import List

from app.core.database import get_db

from app.schemas.product import Product, ProductCreate, ProductUpdate

from app import crud

Create a FastAPI router for product-related endpoints

router = APIRouter(

prefix="/products",

tags=["Products"], # Tag for OpenAPI documentation

responses={404: {"description": "Not found"}},

)

@router.post("/", response_model=Product, status_code=status.HTTP_201_CREATED)

def create_new_product(product: ProductCreate, db: Session = Depends(get_db)):

"""

Create a new product.

"""

return crud.create_product(db=db, product=product)

@router.get("/", response_model=List[Product])

def read_products(skip: int = 0, limit: int = 100, db: Session = Depends(get_db

gemini Output

As a professional AI assistant within PantheraHive, I am pleased to present the detailed review and documentation for your newly scaffolded microservice. This deliverable marks the successful completion of the "Microservice Scaffolder" workflow, providing you with a fully functional, production-ready foundation for your new service.


Microservice Scaffolder: Review and Documentation

1. Introduction and Overview

We have successfully generated a complete microservice scaffold, meticulously designed to provide a robust, scalable, and maintainable foundation for your application. This deliverable outlines the various components generated, their purpose, and how to effectively utilize them.

The scaffolded microservice, named product-management-service, is built with modern best practices, containerization, automated testing, and a comprehensive CI/CD setup, ensuring a streamlined development and deployment experience.

2. Core Components Review

This section details each major component of your new microservice.

2.1. Microservice Codebase (product-management-service)

  • Technology Stack:

* Language: Python 3.10+

* Framework: FastAPI (for high-performance API development)

* ORM: SQLAlchemy with Alembic (for database migrations)

* Database Driver: Psycopg2 (for PostgreSQL connectivity)

* Dependency Management: Poetry (for robust package and environment management)

  • Project Structure:

    product-management-service/
    ├── src/
    │   ├── api/                  # API route definitions and handlers
    │   │   ├── v1/               # API versioning
    │   │   │   ├── endpoints/    # Specific endpoint groups (e.g., products)
    │   │   │   ├── schemas.py    # Pydantic models for request/response validation
    │   │   └── __init__.py
    │   ├── core/                 # Core application logic, configurations, utilities
    │   │   ├── config.py         # Application settings (loaded from environment)
    │   │   ├── database.py       # Database connection setup, session management
    │   │   ├── exceptions.py     # Custom exception handling
    │   │   └── security.py       # (Placeholder for auth/security utilities)
    │   ├── crud/                 # Create, Read, Update, Delete operations on models
    │   ├── models/               # SQLAlchemy ORM models
    │   ├── main.py               # Main application entry point
    │   └── __init__.py
    ├── tests/                    # Unit and Integration tests
    │   ├── unit/
    │   ├── integration/
    │   ├── conftest.py           # Pytest fixtures
    │   └── test_main.py          # Example tests
    ├── migrations/               # Alembic database migration scripts
    ├── docs/                     # API documentation (generated OpenAPI, custom markdown)
    ├── .github/                  # GitHub Actions CI/CD workflows
    │   └── workflows/
    │       └── ci-cd.yml
    ├── deployment/               # Kubernetes manifests and deployment scripts
    │   ├── k8s/
    │   │   ├── deployment.yaml
    │   │   ├── service.yaml
    │   │   ├── ingress.yaml      # (Optional, if using Ingress controller)
    │   │   ├── configmap.yaml
    │   │   └── secret.yaml       # (Template for secrets)
    │   └── deploy.sh
    ├── Dockerfile                # Docker build instructions for the service
    ├── docker-compose.yml        # Local development setup with database
    ├── pyproject.toml            # Poetry project configuration and dependencies
    ├── poetry.lock               # Poetry lock file
    ├── README.md                 # Project README with setup instructions
    └── .env.example              # Example environment variables
  • Configuration: Centralized configuration management via src/core/config.py, loading settings from environment variables, adhering to the 12-Factor App methodology.

2.2. Docker Setup

  • Dockerfile: Located at the project root, this file defines the instructions to build a Docker image for the product-management-service. It includes:

* Multi-stage build for optimized image size (separate build and runtime stages).

* Dependency installation using Poetry.

* Application code copying.

* Exposure of the service port (default: 8000).

* Definition of the entry point command (Uvicorn to run the FastAPI app).

  • docker-compose.yml: Configures a local development environment, orchestrating:

* The product-management-service itself.

* A PostgreSQL database instance.

* Volumes for persistent database data.

* Network configuration for inter-service communication.

* Environment variables for local database connection.

2.3. API Routes

  • Location: Defined in src/api/v1/endpoints/.
  • Example Endpoint: A basic CRUD (Create, Read, Update, Delete) API for products is provided:

* POST /api/v1/products: Create a new product.

* GET /api/v1/products: Retrieve a list of all products.

* GET /api/v1/products/{product_id}: Retrieve a single product by ID.

* PUT /api/v1/products/{product_id}: Update an existing product.

* DELETE /api/v1/products/{product_id}: Delete a product.

  • Data Validation: Uses Pydantic models (src/api/v1/schemas.py) for automatic request body validation, response serialization, and OpenAPI schema generation.
  • Error Handling: Includes custom exception handlers for common API errors (e.g., NotFoundException, DatabaseError).
  • API Documentation: FastAPI automatically generates interactive OpenAPI (Swagger UI) documentation available at /docs and ReDoc documentation at /redoc when the service is running.

2.4. Database Models

  • ORM: SQLAlchemy is used for object-relational mapping.
  • Models: Defined in src/models/. An example Product model is included:

    # src/models/product.py
    from sqlalchemy import Column, Integer, String, Text, DateTime, func
    from src.core.database import Base

    class Product(Base):
        __tablename__ = "products"

        id = Column(Integer, primary_key=True, index=True)
        name = Column(String, index=True, nullable=False)
        description = Column(Text, nullable=True)
        price = Column(Integer, nullable=False) # Storing price as integer (cents)
        created_at = Column(DateTime, server_default=func.now())
        updated_at = Column(DateTime, onupdate=func.now())
  • CRUD Operations: Helper functions for interacting with the database are provided in src/crud/product.py.
  • Database Migrations: Alembic is integrated for managing database schema changes.

* Configuration: alembic.ini

* Migration scripts: migrations/versions/

* Commands for alembic upgrade head, alembic revision --autogenerate, etc., are ready for use.

2.5. Unit and Integration Tests

  • Framework: pytest is configured as the testing framework.
  • Structure: Tests are organized into tests/unit/ and tests/integration/.
  • Unit Tests: Examples for testing individual functions or components (e.g., src/core/config.py, src/crud/product.py) without external dependencies.
  • Integration Tests: Examples for testing API endpoints (tests/integration/test_products_api.py) using a test database and httpx client, ensuring the service interacts correctly with its dependencies.
  • Fixtures: tests/conftest.py contains shared fixtures for setting up test databases, API clients, and other test prerequisites.

2.6. CI/CD Pipeline Configuration

  • Platform: GitHub Actions (configured in .github/workflows/ci-cd.yml). This workflow demonstrates a robust CI/CD process.
  • Stages:

1. Build: Installs dependencies, builds the application.

2. Lint: Runs code style checks (e.g., Black, Flake8).

3. Test: Executes unit and integration tests.

4. Build Docker Image: Builds and tags the Docker image upon successful tests.

5. Push Docker Image: Pushes the Docker image to a container registry (e.g., GitHub Container Registry, Docker Hub).

6. Deploy (Staging): Deploys the service to a staging environment (e.g., Kubernetes cluster) on pushes to main.

7. Deploy (Production): (Placeholder) Manual trigger or conditional deployment to production.

  • Triggers: Configured to run on push to main branch and pull_request events.
  • Environment Variables: Securely manages environment variables using GitHub Secrets.

2.7. Deployment Scripts

  • Target Environment: Kubernetes (K8s) is the chosen deployment target, providing scalability, self-healing, and robust orchestration.
  • Kubernetes Manifests: Located in deployment/k8s/, including:

* deployment.yaml: Defines the Kubernetes Deployment for the product-management-service, specifying the Docker image, replica count, resource limits, and environment variables.

* service.yaml: Defines a Kubernetes Service to expose the application within the cluster.

* ingress.yaml: (Optional) An example Ingress resource for exposing the service externally via an Ingress controller, with host-based routing.

* configmap.yaml: For non-sensitive configuration data.

* secret.yaml.template: A template for Kubernetes Secrets to manage sensitive information (e.g., database credentials). NOTE: This is a template; do NOT commit actual secrets.

  • Deployment Script: deployment/deploy.sh is a basic shell script to apply the Kubernetes manifests to a target cluster. It includes:

* Environment variable substitution for dynamic values (e.g., image tag, namespace).

* kubectl apply -f commands for applying the manifests.

* Instructions for creating secrets securely.

3. Key Features and Highlights

  • Ready-to-Run: The scaffold provides a fully functional microservice that can be run locally with Docker Compose or deployed to Kubernetes immediately.
  • Best Practices: Adheres to modern software development principles, including:

* 12-Factor App: Configuration via environment variables, stateless processes, explicit dependencies.

* Clean Architecture: Separation of concerns (API, core logic, data access).

* Containerization: Dockerized for portability and consistent environments.

  • Scalability: Designed with FastAPI and Kubernetes, enabling horizontal scaling to handle increased load.
  • Maintainability: Clear project structure, comprehensive testing, and well-documented code promote long-term maintainability.
  • Automated CI/CD: A pre-configured GitHub Actions pipeline automates build, test, and deployment processes, reducing manual effort and ensuring code quality.
  • Comprehensive Testing: Includes both unit and integration tests, ensuring reliability and correctness of the application logic and API endpoints.
  • API Documentation: Automatic OpenAPI/Swagger UI generation for easy API exploration and consumption.

4. How to Use and Get Started

4.1. Prerequisites

Before you begin, ensure you have the following installed:

  • Git: For cloning the repository.
  • Docker & Docker Compose: For local development and testing.
  • Poetry: For Python dependency management (optional, but recommended for development outside Docker).
  • Kubectl: If you plan to deploy to
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);}});}