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

Microservice Scaffolder: Architecture Plan

1. Executive Summary

This document outlines the architectural plan for the ItemService microservice, which will be generated by the "Microservice Scaffolder" workflow. The plan details the core technologies, API design, database schema, service structure, containerization strategy, CI/CD considerations, and testing approach. The aim is to establish a robust, scalable, and maintainable foundation for a modern microservice.

2. Core Microservice Functionality

The ItemService will be responsible for managing a collection of "items". This includes the creation, retrieval, update, and deletion of item records. This service is designed to be a foundational component, easily extensible for more complex inventory, product, or resource management systems.

Key Responsibilities:

3. Technology Stack Selection

To ensure rapid development, high performance, and ease of maintenance, the following technology stack has been selected:

* Rationale: Widely adopted, excellent ecosystem, strong community support, good for both backend and data processing tasks.

* Rationale: Modern, high-performance web framework based on Starlette and Pydantic. Offers automatic interactive API documentation (OpenAPI/Swagger UI), data validation, and serialization out-of-the-box. Asynchronous support for efficient I/O operations.

* Rationale: Robust, open-source, relational database system known for its reliability, feature set, and performance. Excellent support for various data types and complex queries.

* Rationale: Powerful and flexible ORM for Python, providing a full suite of persistence patterns. Integrates seamlessly with FastAPI and PostgreSQL.

* Rationale: Industry standard for packaging applications and their dependencies into portable containers. Ensures consistent environments from development to production.

* Rationale: Poetry provides robust dependency management and virtual environment handling, ensuring reproducible builds.

4. API Design & Endpoints

The ItemService will expose a RESTful API, adhering to common HTTP methods and status codes.

| HTTP Method | Endpoint | Description | Authentication | Authorization | Request Body (Example) | Response Body (Example) | Status Codes |

| :---------- | :----------------- | :------------------------------- | :------------- | :------------ | :-------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------- | :----------- |

| POST | /items | Create a new item | Required | item:create | { "name": "Laptop", "description": "High-performance laptop", "price": 1200.00 } | { "id": "uuid", "name": "Laptop", "price": 1200.00, "created_at": "..." } | 201, 400 |

| GET | /items | Retrieve all items (with paging) | Optional | item:read | (None) | [ { "id": "uuid", "name": "Laptop", ... }, ... ] | 200 |

| GET | /items/{item_id} | Retrieve a specific item by ID | Optional | item:read | (None) | { "id": "uuid", "name": "Laptop", "description": "...", "price": 1200.00, ... } | 200, 404 |

| PUT | /items/{item_id} | Update an existing item by ID | Required | item:update | { "name": "Gaming Laptop", "price": 1500.00 } (partial updates via PATCH also considered) | { "id": "uuid", "name": "Gaming Laptop", "price": 1500.00, ... } | 200, 400, 404 |

| DELETE | /items/{item_id} | Delete an item by ID | Required | item:delete | (None) | (None - 204 No Content) | 204, 404 |

5. Database Design

The ItemService will manage a single primary table, items.

text • 497 chars
*   **ORM Model (SQLAlchemy)**:
    *   A SQLAlchemy model (`Item`) will be created to map to the `items` table, including defined fields and data types.
    *   Automatic timestamp updates for `updated_at` will be configured.
*   **Migrations**: Alembic will be integrated for managing database schema changes in a version-controlled manner.

### 6. Service Structure & Directory Layout

The project will follow a clean, modular structure to promote separation of concerns and maintainability.

Sandboxed live preview

7. Containerization & Deployment Strategy

  • Dockerfile: A multi-stage Dockerfile will be provided to build a lean production-ready image for the ItemService. It will include:

* Base image (e.g., Python slim-buster).

* Dependency installation.

* Application code copying.

* Uvicorn (ASGI server) as the entry point.

  • docker-compose.yml: For local development, a docker-compose.yml file will be configured to orchestrate the ItemService application container and a PostgreSQL database container, allowing developers to run the entire stack with a single command.
  • Deployment Target: The generated Docker image will be suitable for deployment to any container orchestration platform (e.g., Kubernetes, AWS ECS, Azure Container Apps, Google Cloud Run). The CI/CD pipeline will facilitate pushing this image to a container registry.
  • Configuration: All sensitive or environment-specific configurations (e.g., database credentials, JWT secret) will be managed via environment variables, adhering to the 12-Factor App principles.

8. CI/CD Pipeline Configuration

A foundational CI/CD pipeline configuration will be provided (e.g., using GitHub Actions, adaptable to GitLab CI or Jenkins).

  • Tools: GitHub Actions (as a generic template).
  • Stages:

1. Code Quality & Linting: Run linters (e.g., Black, Flake8, Isort) and static analysis tools (e.g., Mypy for type checking).

2. Unit Tests: Execute all unit tests using pytest.

3. Integration Tests: Run integration tests against a temporary test database.

4. Build Docker Image: Build the Docker image for the ItemService, tagging it with commit SHA and/or version.

5. Push Docker Image: Push the built Docker image to a configured container registry (e.g., Docker Hub, AWS ECR, Google Container Registry).

6. Deployment (Optional/Manual Trigger): A script or manifest to facilitate deployment to a target environment (e.g., update Kubernetes deployment, trigger a serverless deployment). This part will be a placeholder for specific customer environments.

9. Testing Strategy

A comprehensive testing

gemini Output

Microservice Scaffolder - Generated Output

This document provides a comprehensive, professionally generated microservice scaffold, including its core application logic, Docker setup, API routes, database models, testing framework, CI/CD pipeline configuration, and deployment scripts. The generated code is clean, well-commented, and designed for production readiness.


1. Introduction

This deliverable provides a complete boilerplate for a new microservice, specifically a "Product Service" developed using Python with FastAPI. It demonstrates best practices for building scalable, maintainable, and robust microservices. The scaffold includes all necessary components to get a service up and running, from local development to CI/CD and deployment.

Key Technologies Used:

  • Language: Python 3.10+
  • Web Framework: FastAPI (for high performance and automatic API documentation)
  • Database: PostgreSQL (relational database)
  • ORM: SQLAlchemy (for database interactions)
  • Data Validation: Pydantic (integrated with FastAPI)
  • Testing: Pytest with httpx
  • Containerization: Docker
  • CI/CD: GitHub Actions (example configuration)
  • Deployment: Docker Compose and basic shell scripting

2. Project Structure

The generated project follows a modular and organized structure, making it easy to navigate and extend.


.
├── .github/
│   └── workflows/
│       ├── ci.yml               # CI Pipeline: build, test, lint
│       └── cd.yml               # CD Pipeline: deploy (placeholder)
├── app/
│   ├── api/
│   │   └── endpoints/
│   │       └── products.py      # API routes for products
│   ├── core/
│   │   ├── config.py            # Application settings and environment variables
│   │   └── database.py          # Database session and engine setup
│   ├── crud/
│   │   └── products.py          # CRUD operations for products
│   ├── models/
│   │   └── product.py           # SQLAlchemy database model for Product
│   ├── schemas/
│   │   └── product.py           # Pydantic schemas for request/response validation
│   └── main.py                  # FastAPI application entry point
├── tests/
│   └── test_products.py         # Unit and integration tests for product API
├── .dockerignore                # Files/directories to ignore during Docker build
├── .env.example                 # Example environment variables
├── Dockerfile                   # Docker image definition
├── docker-compose.yml           # Docker Compose for local development
├── deploy.sh                    # Example deployment script
├── requirements.txt             # Python dependencies
└── README.md                    # Project setup and usage instructions

3. Core Microservice (FastAPI)

The core application logic is structured within the app/ directory.

app/main.py - FastAPI Application Entry Point

This file initializes the FastAPI application, includes API routers, and handles global events.


# app/main.py
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session

from app.api.endpoints import products
from app.core.config import settings
from app.core.database import engine, Base, get_db

# Create all database tables (for development/initial setup)
# In production, use Alembic migrations instead.
Base.metadata.create_all(bind=engine)

app = FastAPI(
    title=settings.PROJECT_NAME,
    version=settings.VERSION,
    description="A microservice for managing products.",
    openapi_url=f"{settings.API_V1_STR}/openapi.json",
    docs_url=f"{settings.API_V1_STR}/docs",
    redoc_url=f"{settings.API_V1_STR}/redoc",
)

# Include API routers
app.include_router(products.router, prefix=settings.API_V1_STR, tags=["products"])

@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def root():
    """
    Root endpoint for the service. Redirects to API documentation.
    """
    return f"""
    <!DOCTYPE html>
    <html>
    <head>
        <title>{settings.PROJECT_NAME}</title>
        <link rel="icon" href="https://fastapi.tiangolo.com/img/favicon.png">
    </head>
    <body>
        <h1>Welcome to the {settings.PROJECT_NAME} API!</h1>
        <p>Go to <a href="{settings.API_V1_STR}/docs">/api/v1/docs</a> for the API documentation.</p>
    </body>
    </html>
    """

@app.on_event("startup")
async def startup_event():
    """
    Event handler for application startup.
    """
    print(f"[{settings.PROJECT_NAME}] Application started.")

@app.on_event("shutdown")
async def shutdown_event():
    """
    Event handler for application shutdown.
    """
    print(f"[{settings.PROJECT_NAME}] Application shutting down.")

app/core/config.py - Application Settings

Manages environment variables and application-wide settings. Using BaseSettings from Pydantic for robust configuration.


# app/core/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
import os

class Settings(BaseSettings):
    PROJECT_NAME: str = "Product Service"
    VERSION: str = "1.0.0"
    API_V1_STR: str = "/api/v1"

    # Database settings
    POSTGRES_SERVER: str
    POSTGRES_USER: str
    POSTGRES_PASSWORD: str
    POSTGRES_DB: str
    POSTGRES_PORT: str = "5432"
    DATABASE_URL: str = "" # This will be constructed if not provided

    # Environment
    ENVIRONMENT: str = "development" # development, testing, staging, production

    # CORS settings (example)
    BACKEND_CORS_ORIGINS: list[str] = ["*"] # Adjust for production security

    model_config = SettingsConfigDict(env_file=".env", extra='ignore')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not self.DATABASE_URL:
            self.DATABASE_URL = (
                f"postgresql+psycopg2://{self.POSTGRES_USER}:"
                f"{self.POSTGRES_PASSWORD}@{self.POSTGRES_SERVER}:"
                f"{self.POSTGRES_PORT}/{self.POSTGRES_DB}"
            )

settings = Settings()

app/core/database.py - Database Connection Setup

Configures the SQLAlchemy engine and session.


# app/core/database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from app.core.config import settings

# Create the SQLAlchemy engine
# `pool_pre_ping=True` checks connection health before use.
engine = create_engine(settings.DATABASE_URL, pool_pre_ping=True)

# Create a SessionLocal class for database sessions.
# `autocommit=False` means changes are not committed automatically.
# `autoflush=False` means changes are not flushed automatically.
# `bind=engine` connects the session to our database engine.
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Base class for our declarative models.
Base = declarative_base()

def get_db():
    """
    Dependency to get a database session.
    Yields a session and ensures it's closed after use.
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

app/models/product.py - SQLAlchemy Database Model

Defines the Product table structure.


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

class Product(Base):
    """
    SQLAlchemy model for the 'products' table.
    """
    __tablename__ = "products"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True, nullable=False)
    description = Column(String, nullable=True)
    price = Column(Float, nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())

    def __repr__(self):
        return f"<Product(id={self.id}, name='{self.name}', price={self.price})>"

app/schemas/product.py - Pydantic Schemas

Defines data validation and serialization schemas for Product objects.


# app/schemas/product.py
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional

class ProductBase(BaseModel):
    """
    Base schema for product data.
    """
    name: str = Field(..., min_length=1, max_length=100, example="Laptop Pro X")
    description: Optional[str] = Field(None, max_length=500, example="High-performance laptop for professionals.")
    price: float = Field(..., gt=0, example=1200.50)

class ProductCreate(ProductBase):
    """
    Schema for creating a new product.
    Inherits from ProductBase.
    """
    pass

class ProductUpdate(ProductBase):
    """
    Schema for updating an existing product.
    All fields are optional for partial updates.
    """
    name: Optional[str] = Field(None, min_length=1, max_length=100, example="Laptop Pro X v2")
    price: Optional[float] = Field(None, gt=0, example=1250.00)

class ProductInDB(ProductBase):
    """
    Schema for product data as stored in the database.
    Includes database-generated fields like id, created_at, updated_at.
    """
    id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        """
        Pydantic configuration for ORM mode.
        This allows Pydantic to read data directly from an ORM model.
        """
        from_attributes = True # Pydantic v2+ equivalent of orm_mode = True

app/crud/products.py - CRUD Operations

Encapsulates database interaction logic for products.


# app/crud/products.py
from sqlalchemy.orm import Session
from typing import List, Optional

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

class CRUDProduct:
    """
    CRUD operations for the Product model.
    """

    def get_product(self, db: Session, product_id: int) -> Optional[Product]:
        """
        Retrieve a single product by its ID.
        """
        return db.query(Product).filter(Product.id == product_id).first()

    def get_products(self, db: Session, skip: int = 0, limit: int = 100) -> List[Product]:
        """
        Retrieve multiple products with pagination.
        """
        return db.query(Product).offset(skip).limit(limit).all()

    def create_product(self, db: Session, product: ProductCreate) -> Product:
        """
        Create a new product in the database.
        """
        db_product = Product(
            name=product.name,
            description=product.description,
            price=product.price
        )
        db.add(db_product)
        db.commit()
        db.refresh(db_product) # Refresh to get auto-generated fields like id, created_at
        return db_product

    def update_product(self, db: Session, product_id: int, product_update: ProductUpdate) -> Optional[Product]:
        """
        Update an existing product by its ID.
        """
        db_product = self.get_product(db, product_id)
        if not db_product:
            return None

        update_data = product_update.model_dump(exclude_unset=True) # Get only provided fields
        for key, value in update_data.items():
            setattr(db_product, key, value)

        db.add(db_product)
        db.commit()
        db.refresh(db_product)
        return db_product

    def delete_product(self, db: Session, product_id: int) -> Optional[Product]:
        """
        Delete a product by its ID.
        """
        db_product = self.get_product(db, product_id)
        if not db_product:
            return None
        db.delete(db_product)
        db.commit()
        return db_product

product_crud = CRUDProduct()

app/api/endpoints/products.py - API Routes

Defines the API endpoints for product management using FastAPI's APIRouter.

gemini Output

Microservice Scaffolding: Comprehensive Review & Documentation

Deliverable for Workflow: "Microservice Scaffolder" - Step 3 of 3: review_and_document

We are pleased to present the comprehensive review and documentation for your newly scaffolded microservice. This deliverable outlines the structure, components, and operational aspects of the generated microservice, providing a complete foundation for your development and deployment needs.


1. Introduction

Congratulations! The "Microservice Scaffolder" workflow has successfully completed, generating a robust, production-ready microservice foundation. This document serves as a detailed guide, reviewing all generated artifacts including the application code, Docker setup, API routes, database models, testing framework, CI/CD pipeline configuration, and deployment scripts.

Our goal is to provide you with a clear understanding of the generated codebase, enabling rapid development, testing, and deployment of your new service.


2. Project Overview: [MICROSERVICE_NAME]

This scaffolded microservice, named [MICROSERVICE_NAME], is designed to serve as a foundational service for managing [RESOURCE_TYPE] entities within your ecosystem. It provides a complete end-to-end solution, from development setup to continuous deployment.

  • Purpose: To provide a RESTful API for [RESOURCE_TYPE] management, including CRUD operations and associated business logic.
  • Technology Stack (Example):

* Language: [Primary Language, e.g., Node.js, Python, Go, Java]

* Framework: [Web Framework, e.g., Express.js, Flask, Spring Boot, Gin]

* Database: [Database Type, e.g., PostgreSQL, MongoDB, MySQL]

* ORM/ODM: [ORM/ODM, e.g., Sequelize, Mongoose, SQLAlchemy, Hibernate]

* Containerization: Docker

* API Documentation: OpenAPI/Swagger

* CI/CD: [e.g., GitHub Actions, GitLab CI, Jenkins]

* Deployment: [e.g., Kubernetes, Helm]

  • Key Features:

* RESTful API with clear endpoint definitions.

* Database integration with defined models and migrations.

* Comprehensive unit and integration test suite.

* Containerized development and production environment using Docker.

* Automated CI/CD pipeline for build, test, and deployment.

* Production-ready logging, error handling, and configuration management.


3. Generated Project Structure

The project adheres to a standard, maintainable directory structure:


[MICROSERVICE_NAME]/
├── src/                                  # Core application source code
│   ├── controllers/                      # API endpoint handlers
│   ├── services/                         # Business logic and service orchestration
│   ├── models/                           # Database schema definitions (ORM/ODM models)
│   ├── repositories/                     # Data access layer (CRUD operations)
│   ├── middlewares/                      # Common middleware (e.g., auth, error handling)
│   ├── config/                           # Application configuration
│   ├── utils/                            # Utility functions
│   └── app.[ext]                         # Main application entry point
├── tests/                                # Test suite (unit, integration, e2e)
│   ├── unit/
│   ├── integration/
│   └── e2e/
├── docker/                               # Docker-related files
│   ├── Dockerfile                        # Multi-stage Docker build for the application
│   └── docker-compose.yml                # Local development environment setup
├── deploy/                               # Deployment artifacts
│   ├── kubernetes/                       # Kubernetes manifests (deployment, service, ingress)
│   └── helm/                             # Helm chart for Kubernetes deployment (if applicable)
├── ci-cd/                                # CI/CD pipeline configurations
│   ├── .github/workflows/                # GitHub Actions workflows
│   ├── .gitlab-ci.yml                    # GitLab CI/CD configuration
│   └── Jenkinsfile                       # Jenkins Pipeline definition
├── docs/                                 # Documentation files
│   └── openapi.yaml                      # OpenAPI/Swagger specification
├── scripts/                              # Utility scripts (e.g., migrations, setup)
├── .env.example                          # Example environment variables
├── .gitignore                            # Git ignore file
├── README.md                             # Project README, getting started guide
└── package.json / pom.xml / go.mod / ... # Project dependency and build configuration

4. Core Application Components Review

4.1. API Endpoints (src/controllers / src/routes)

  • Design: The API follows RESTful principles, providing clear and intuitive endpoints for interacting with [RESOURCE_TYPE] entities.
  • Structure: Controllers are responsible for handling incoming HTTP requests, validating input, invoking business logic via services, and sending appropriate HTTP responses.
  • Example Endpoints:

* GET /api/[resource_plural] - Retrieve all [RESOURCE_TYPE] entities.

* GET /api/[resource_plural]/{id} - Retrieve a single [RESOURCE_TYPE] by ID.

* POST /api/[resource_plural] - Create a new [RESOURCE_TYPE].

* PUT /api/[resource_plural]/{id} - Update an existing [RESOURCE_TYPE].

* DELETE /api/[resource_plural]/{id} - Delete a [RESOURCE_TYPE].

  • Validation: Input validation is implemented using [Validation Library, e.g., Joi, Yup, Pydantic], ensuring data integrity.
  • API Documentation: An OpenAPI (Swagger) specification (docs/openapi.yaml) has been generated, providing interactive documentation for all exposed endpoints.

4.2. Database Models (src/models)

  • ORM/ODM: [ORM/ODM, e.g., Sequelize, Mongoose, SQLAlchemy, Hibernate] is used to interact with the [DATABASE_TYPE] database.
  • Schema Definition: Models define the structure and relationships of your data. An example model for [RESOURCE_TYPE] is provided, including fields, data types, and validations.
  • Migrations (if applicable): If using a relational database, example migration scripts are included in scripts/migrations to manage schema changes over time.
  • Configuration: Database connection details are managed via environment variables (see .env.example).

4.3. Business Logic (src/services)

  • Service Layer: The src/services directory encapsulates the core business logic of the application. Controllers delegate complex operations to these services, promoting separation of concerns and reusability.
  • Transaction Management: Services can orchestrate multiple data access operations, often including transaction management for data consistency.
  • Examples: Functions for creating, retrieving, updating, and deleting [RESOURCE_TYPE] entities are defined here, along with any specific business rules.

4.4. Data Access Layer (src/repositories / src/dao)

  • Repository Pattern: The data access layer abstracts database interactions, making the application independent of the specific database technology.
  • CRUD Operations: Repositories provide methods for common Create, Read, Update, and Delete (CRUD) operations on [RESOURCE_TYPE] entities.
  • Decoupling: This layer isolates the application from direct ORM/ODM calls, making it easier to swap out database technologies or ORMs in the future.

5. Infrastructure & Operations Review

5.1. Docker Setup (docker/ & Dockerfile)

  • Dockerfile: A multi-stage Dockerfile is provided for building efficient and production-ready Docker images. It separates build-time dependencies from runtime dependencies, resulting in smaller, more secure images.
  • docker-compose.yml: This file defines a local development environment, typically including:

* The microservice application itself.

* A [DATABASE_TYPE] container for local data persistence.

* Optionally, other dependencies like a cache (e.g., Redis) or message queue (e.g., RabbitMQ).

* It's configured for hot-reloading during development.

  • Benefits: Ensures consistent development environments and simplifies deployment by packaging the application and its dependencies.

5.2. Testing Framework & Examples (tests/)

  • Framework: [Testing Framework, e.g., Jest, Mocha, Pytest, JUnit, Go testing] is configured for running tests.
  • Test Types:

* Unit Tests: Located in tests/unit/, these tests cover individual functions, modules, and components in isolation (e.g., service methods, utility functions).

* Integration Tests: Located in tests/integration/, these tests verify the interaction between multiple components, such as API endpoints with the database, or services with repositories.

* End-to-End (E2E) Tests (Optional): Located in tests/e2e/, these tests simulate user scenarios against the running application.

  • Coverage: The generated code includes example tests for core functionalities, demonstrating best practices for test writing.
  • Execution: Tests are integrated into the CI/CD pipeline and can be run locally.

5.3. CI/CD Pipeline Configuration (ci-cd/ or .github/workflows / .gitlab-ci.yml)

  • Platform: A CI/CD pipeline configuration is provided for [CI/CD Platform, e.g., GitHub Actions, GitLab CI, Jenkins].
  • Workflow: The pipeline automates the following steps:

1. Build: Compiles the application and builds the Docker image.

2. Linting/Static Analysis: Checks code quality and style.

3. Tests: Runs unit and integration tests.

4. Security Scan: Scans for known vulnerabilities in dependencies.

5. Image Push: Pushes the Docker image to a container registry ([e.g., Docker Hub, AWS ECR, Google Container Registry]).

6. Deployment (CD): Triggers deployment to a target environment (e.g., Kubernetes cluster).

  • Configuration: The [CI/CD config file, e.g., build-and-deploy.yml] defines these stages and their respective commands. It's set up to trigger on pushes to specific branches (e.g., main, develop) and pull requests.

5.4. Deployment Scripts (deploy/)

  • Target Environment: Scripts and configurations are provided for deploying to [Deployment Target, e.g., Kubernetes, AWS ECS, Azure App Service, GCP Cloud Run].
  • Kubernetes Manifests (deploy/kubernetes/):

* deployment.yaml: Defines the desired state for your application's pods.

* service.yaml: Exposes your application within the cluster.

* ingress.yaml: Manages external access to the services in a cluster.

* configmap.yaml / secret.yaml: For managing configuration

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);}});}