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

Microservice Scaffolding Complete: "Item Management Service"

This document details the complete generation of your microservice, named "Item Management Service," covering all requested components from API routes and database models to Docker setup, testing, CI/CD configurations, and deployment scripts.

Technology Stack Chosen:


1. Project Overview and Structure

The generated microservice provides a basic CRUD (Create, Read, Update, Delete) API for managing "Items." It's designed with a clean, modular architecture to facilitate scalability and maintainability.

Core Features:

Generated Project Structure:

text • 2,051 chars
item-management-service/
├── .github/
│   └── workflows/
│       ├── ci.yml               # GitHub Actions CI pipeline
│       └── cd.yml               # GitHub Actions CD pipeline (placeholder)
├── app/
│   ├── api/
│   │   └── v1/
│   │       └── endpoints/
│   │           └── items.py     # API routes for Item resource
│   ├── crud/
│   │   └── item_crud.py         # CRUD operations for Item model
│   ├── database.py              # Database engine and session setup
│   ├── main.py                  # FastAPI application entry point
│   ├── models/
│   │   └── item.py              # SQLAlchemy ORM model for Item
│   ├── schemas/
│   │   └── item.py              # Pydantic schemas for request/response validation
│   └── services/
│       └── item_service.py      # Business logic for Item operations
├── alembic/                     # Alembic migration environment
│   ├── versions/
│   │   └── <timestamp>_initial_migration.py # Initial migration script
│   └── env.py
│   └── script.py.mako
├── alembic.ini                  # Alembic configuration file
├── deploy/
│   ├── kubernetes/
│   │   ├── deployment.yaml      # Kubernetes Deployment manifest
│   │   └── service.yaml         # Kubernetes Service manifest
│   └── scripts/
│       └── deploy_to_vm.sh      # Example script for VM deployment
├── tests/
│   ├── conftest.py              # Pytest fixtures
│   ├── test_api_items.py        # Integration tests for API endpoints
│   └── test_crud_items.py       # Unit tests for CRUD operations
├── .dockerignore                # Files to ignore in Docker build context
├── .env.example                 # Example environment variables
├── Dockerfile                   # Dockerfile for the FastAPI application
├── docker-compose.yml           # Docker Compose for local development (app + db)
├── Makefile                     # Helper commands for development
├── README.md                    # Project README
├── requirements.txt             # Production dependencies
└── requirements-dev.txt         # Development/testing dependencies
Sandboxed live preview

Microservice Scaffolder: Architectural Plan

This document outlines the comprehensive architectural plan for generating a complete microservice, focusing on a robust, scalable, and maintainable structure. This plan covers the core service components, recommended technology stack, infrastructure considerations, and a detailed project execution strategy.


1. Core Microservice Architecture Principles

The microservice architecture will adhere to the following principles to ensure high quality and operational efficiency:

  • Single Responsibility Principle: Each microservice will be designed to do one thing well, encapsulating a specific business capability.
  • API-First Design: RESTful APIs using JSON for communication, with clear contracts and OpenAPI documentation.
  • Statelessness: Services will be stateless to enable easy scaling and resilience.
  • Database per Service: Each service will manage its own data store, promoting loose coupling and independent evolution.
  • Asynchronous Communication (Optional but Recommended): Event-driven patterns using message queues for inter-service communication where eventual consistency or fan-out is required.
  • Observability: Built-in mechanisms for logging, metrics, and tracing to monitor service health and performance.
  • Resilience: Implementation of patterns like circuit breakers, retries, and timeouts to handle failures gracefully.
  • Security: Robust authentication and authorization mechanisms.

2. Recommended Technology Stack (Default)

To provide a concrete and professional scaffold, we recommend the following technology stack. This stack is modern, widely adopted, and offers excellent developer experience and performance.

  • Language & Framework: Python 3.10+ with FastAPI

Rationale*: High performance, asynchronous support, automatic interactive API documentation (Swagger UI/ReDoc), Pydantic for data validation, and strong type hinting.

  • Database: PostgreSQL

Rationale*: Robust, open-source relational database, ACID compliant, widely supported, and suitable for transactional data.

  • Object-Relational Mapper (ORM): SQLAlchemy

Rationale*: Powerful and flexible ORM for Python, providing a high degree of control over database interactions.

  • Containerization: Docker

Rationale*: Standard for packaging applications with their dependencies, ensuring consistency across environments.

  • Testing Framework: Pytest

Rationale*: Simple, yet powerful testing framework for Python, with a rich plugin ecosystem.

  • CI/CD Platform: GitHub Actions

Rationale*: Fully integrated with GitHub repositories, easy to configure, and supports complex workflows.

  • Cloud Provider (for Deployment Examples): AWS

Rationale*: Market leader with comprehensive services for compute (EKS), database (RDS), container registry (ECR), and networking (VPC).

  • Infrastructure as Code (IaC): Terraform

Rationale*: Declarative language for provisioning and managing cloud resources across various providers.

  • API Gateway (Optional but Common): AWS API Gateway / NGINX Ingress (Kubernetes)

Rationale*: For managing traffic, security, and routing to multiple microservices.


3. Detailed Component Breakdown

3.1. Microservice Application (src/)

  • API Layer (src/api/):

* FastAPI Application: Main entry point for HTTP requests.

* Routers: Modular organization of API endpoints (e.g., users.py, items.py) using APIRouter.

* Pydantic Models: Define request body schemas, response schemas, and data validation.

* Dependency Injection: Manages database sessions, authentication, and other common dependencies.

* OpenAPI/Swagger UI: Auto-generated interactive API documentation.

  • Business Logic Layer (src/services/):

* Service Classes: Encapsulate core domain logic and orchestrate interactions between the API layer and the Data Access Layer.

* Helper Functions: Utility functions for specific business rules.

  • Data Access Layer (src/db/):

* SQLAlchemy Models: Define database table schemas (e.g., User, Item).

* Repository Pattern: Abstract database operations (CRUD) for each model, providing a clean interface to the business logic.

* Asynchronous Database Sessions: Integration with asyncpg for non-blocking database operations.

  • Configuration (src/config.py):

* Manages application settings using environment variables (e.g., database connection strings, secret keys). Leverages pydantic-settings.

  • Authentication & Authorization (src/auth/):

* JWT-based Authentication: Securely identifies users.

* Dependencies/Middleware: For token validation, user retrieval, and role-based access control (RBAC).

  • Error Handling (src/exceptions/, src/middleware/):

* Centralized exception handling middleware to catch and format errors consistently (e.g., HTTPException).

* Custom exception types for specific business errors.

  • Logging (src/logger.py):

* Structured logging setup (e.g., loguru or standard logging) for consistent log output.

3.2. Infrastructure as Code (IaC) (infra/)

  • Terraform Modules:

* VPC: Network setup (VPC, subnets, internet gateway, route tables, security groups).

* EKS Cluster: Kubernetes cluster provisioning (control plane, worker nodes, IAM roles).

* RDS PostgreSQL: Managed PostgreSQL database instance.

* ECR Repository: Docker image registry for the microservice.

* IAM Roles: Permissions for EKS, ECR, RDS, etc.

  • Kubernetes Manifests (k8s/):

* Deployment: Defines the desired state for the microservice pods.

* Service: Exposes the microservice within the cluster.

* Ingress: Manages external access to the service (e.g., via NGINX Ingress Controller or AWS ALB Ingress Controller).

* ConfigMap: Stores non-sensitive configuration data.

* Secret: Stores sensitive data (e.g., database credentials).

* Horizontal Pod Autoscaler (HPA): Automatically scales the number of pods based on CPU/memory usage.

3.3. Docker Setup (./)

  • Dockerfile: Defines the build process for the microservice Docker image.

* Multi-stage build for smaller, more secure production images.

* Includes dependencies, application code, and entrypoint.

  • docker-compose.yml: For local development and testing.

* Orchestrates the microservice, PostgreSQL database, and potentially other services (e.g., Redis, message queue).

* Facilitates easy setup and teardown of

python

app/services/item_service.py

from typing import List, Optional

from sqlalchemy.orm import Session

from app.crud import item_crud

from app.schemas.item import ItemCreate, ItemUpdate

from app.models.item import Item as ItemModel

def get_item(db: Session, item_id: int) -> Optional[ItemModel]:

"""

Retrieves a single item by its ID.

"""

return item_crud.get_item(db, item_id=item_id)

def get_item_by_name(db: Session, name: str) -> Optional[ItemModel]:

"""

Retrieves a single item by its name.

"""

return item_crud.get_item_by_name(db, name=name)

def get_items(db: Session, skip: int = 0, limit

gemini Output

Microservice Scaffolder: Comprehensive Deliverable

We are pleased to present the complete microservice scaffold, meticulously generated to provide a robust, scalable, and production-ready foundation for your application. This deliverable includes all essential components, from API routes and database models to Docker setup, testing, and CI/CD pipeline configurations, ensuring a streamlined development and deployment experience.


1. Introduction and Overview

This package provides a fully functional starter microservice, named [YOUR_MICROSERVICE_NAME], designed for rapid development and deployment. It adheres to modern best practices in software architecture, containerization, and automated workflows. The scaffold is built using FastAPI (Python) for the API, PostgreSQL for the database, and is containerized with Docker. Automated testing is implemented with Pytest, and a CI/CD pipeline is configured using GitHub Actions, with deployment manifests for Kubernetes.

Key Highlights:

  • FastAPI: High-performance, easy-to-use web framework.
  • SQLAlchemy ORM: Robust and flexible database interaction.
  • Docker & Docker Compose: Consistent development and production environments.
  • Pytest: Comprehensive testing framework for unit and integration tests.
  • GitHub Actions: Automated build, test, and deployment workflows.
  • Kubernetes Manifests: Production-grade deployment configuration.
  • OpenAPI/Swagger UI: Automatically generated interactive API documentation.

2. Project Structure & Generated Components

The generated project follows a clear and modular structure, promoting maintainability and scalability. Below is an overview of the directory structure and a detailed description of each component.


[YOUR_MICROSERVICE_NAME]/
├── .github/
│   └── workflows/
│       └── main.yml           # GitHub Actions CI/CD pipeline
├── app/
│   ├── api/
│   │   ├── __init__.py
│   │   └── v1/
│   │       ├── __init__.py
│   │       └── endpoints/
│   ���           ├── __init__.py
│   │           └── users.py   # Example API routes (e.g., /users)
│   ├── core/
│   │   ├── __init__.py
│   │   ├── config.py          # Application settings and environment variables
│   │   └── database.py        # Database connection and session management
│   ├── crud/
│   │   ├── __init__.py
│   │   └── users.py           # CRUD operations for database models
│   ├── models/
│   │   ├── __init__.py
│   │   └── user.py            # SQLAlchemy database models (e.g., User)
│   ├── schemas/
│   │   ├── __init__.py
│   │   └── user.py            # Pydantic schemas for API request/response validation
│   ├── main.py                # FastAPI application entry point
│   └── __init__.py
├── tests/
│   ├── __init__.py
│   ├── conftest.py            # Pytest fixtures for testing
│   ├── test_api.py            # API integration tests
│   └── test_models.py         # Unit tests for database models
├── kubernetes/
│   ├── deployment.yaml        # Kubernetes Deployment manifest
│   └── service.yaml           # Kubernetes Service manifest
├── .env.example               # Example environment variables
├── Dockerfile                 # Docker build instructions for the microservice
├── docker-compose.yml         # Docker Compose for local development (app + db)
├── Makefile                   # Common development commands
├── README.md                  # Project documentation
├── requirements.txt           # Python dependencies
└── poetry.lock                # (Optional, if using Poetry)

2.1. API (FastAPI)

  • app/main.py: The main FastAPI application instance, responsible for including routers and setting up global middleware.
  • app/api/v1/endpoints/users.py: Contains example RESTful API endpoints for managing User resources (e.g., GET /users, POST /users, GET /users/{id}, PUT /users/{id}, DELETE /users/{id}). These endpoints demonstrate dependency injection for database sessions and request validation using Pydantic schemas.
  • app/schemas/user.py: Pydantic models defining the structure for API request bodies and response payloads. This ensures data validation and clear API contracts.

2.2. Database (PostgreSQL & SQLAlchemy)

  • app/models/user.py: Defines the SQLAlchemy ORM model for the User table, mapping Python objects to database tables and columns.
  • app/crud/users.py: Implements Create, Read, Update, Delete (CRUD) operations for the User model, abstracting database interactions from the API layer.
  • app/core/database.py: Manages the database connection, SQLAlchemy engine, session factory, and provides a dependency for obtaining a database session within API endpoints.
  • docker-compose.yml: Includes a PostgreSQL service for local development, pre-configured with necessary environment variables.

2.3. Dockerization

  • Dockerfile: Defines the instructions for building a Docker image of your microservice. It includes dependency installation, application code copying, and defines the entry point for the FastAPI application using Gunicorn and Uvicorn.
  • docker-compose.yml: Orchestrates a multi-container environment for local development, including the FastAPI application and a PostgreSQL database. It simplifies setting up and running the entire stack with a single command.

2.4. Testing (Pytest)

  • tests/: Directory containing unit and integration tests.
  • tests/conftest.py: Contains Pytest fixtures, such as an in-memory test database, a test client for FastAPI, and mock data, to facilitate isolated and efficient testing.
  • tests/test_api.py: Examples of integration tests that interact with the FastAPI endpoints, verifying correct behavior and data flow.
  • tests/test_models.py: Examples of unit tests for the SQLAlchemy models and CRUD operations, ensuring data integrity and business logic.

2.5. CI/CD Pipeline Configuration (GitHub Actions)

  • .github/workflows/main.yml: A comprehensive GitHub Actions workflow that automates the following stages:

* Build: Checks out code and sets up the Python environment.

* Lint: Runs linters (e.g., Flake8, Black) to enforce code style and quality.

* Test: Executes all Pytest tests (unit and integration).

* Build Docker Image: Builds the Docker image of the microservice.

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

Deploy: (Optional/Placeholder) Triggers deployment to a target environment (e.g., Kubernetes, AWS ECS) using the generated Kubernetes manifests. Note: Deployment credentials and specific environment variables will need to be configured in GitHub Secrets.*

2.6. Deployment Scripts (Kubernetes)

  • kubernetes/deployment.yaml: A Kubernetes Deployment manifest that defines how your microservice containers should be run, scaled, and updated within a Kubernetes cluster. It includes container image, resource requests/limits, environment variables, and replica count.
  • kubernetes/service.yaml: A Kubernetes Service manifest that defines how to access your microservice within the cluster and potentially expose it externally. It typically uses a LoadBalancer, NodePort, or ClusterIP type.

3. Getting Started Locally

Follow these steps to set up and run your microservice locally using Docker Compose.

3.1. Prerequisites

  • Git: For cloning the repository.
  • Docker Desktop: Includes Docker Engine and Docker Compose.

3.2. Clone the Repository


git clone [YOUR_PROJECT_REPO_URL]
cd [YOUR_MICROSERVICE_NAME]

3.3. Configure Environment Variables

Copy the example environment file and update it with your specific settings.


cp .env.example .env

Open .env and review the variables. For local development, the defaults usually suffice.

3.4. Run with Docker Compose

Navigate to the root directory of the project and start the services:


docker-compose up --build -d
  • --build: Rebuilds the Docker images (useful for fresh setup or code changes).
  • -d: Runs the containers in detached mode (in the background).

3.5. Verify Services

Check the status of your containers:


docker-compose ps

You should see [YOUR_MICROSERVICE_NAME] and db containers in Up status.

3.6. Access the API

Once the services are up, the FastAPI application will be accessible at:

  • API Documentation (Swagger UI): http://localhost:8000/docs
  • Redoc: http://localhost:8000/redoc

You can now interact with the example /users endpoints via the Swagger UI or any API client.

3.7. Stop Services

To stop and remove the containers:


docker-compose down

4. Running Tests

The scaffold includes a robust testing suite using Pytest.

4.1. Run Tests Locally (within Docker)

The easiest way to run tests is within the Docker environment to ensure consistent dependencies:


docker-compose exec [YOUR_MICROSERVICE_NAME] pytest tests/

This command executes all tests found in the tests/ directory within the application container.

4.2. Run Tests Locally (on Host - requires Python setup)

If you prefer to run tests directly on your host machine, you'll need to set up a Python virtual environment and install dependencies:


# Assuming Python 3.9+ is installed
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
pytest tests/

Note: Ensure your .env is configured correctly for the test environment, or use environment variables specific to testing.


5. CI/CD Pipeline Overview (GitHub Actions)

The .github/workflows/main.yml file defines an automated CI/CD pipeline that triggers on push and pull_request events to the main branch.

Workflow Stages:

  1. Checkout Code: Retrieves the repository content.
  2. Setup Python: Configures the Python environment.
  3. Install Dependencies: Installs requirements.txt.
  4. Lint Code: Runs linters to maintain code quality.
  5. Run Tests: Executes all Pytest tests, including unit and integration tests against a temporary database.
  6. Build Docker Image: Creates a Docker image for the microservice.
  7. Push Docker Image: Pushes the built image to a configured container registry.
  8. Deploy to Kubernetes (Placeholder):

* This step is a placeholder for your actual deployment logic.

* It typically involves authenticating with your Kubernetes cluster and applying the manifests from the kubernetes/ directory.

* Action Required: You will need to configure GitHub Secrets (e.g., KUBERNETES_CLUSTER_URL, KUBERNETES_TOKEN, DOCKER_USERNAME, DOCKER_PASSWORD) for this step to function correctly.

This pipeline ensures that every code change is automatically validated and can be deployed efficiently, reducing manual errors and accelerating delivery.


6. Deployment Configuration (Kubernetes)

The kubernetes/ directory contains essential manifests for deploying your microservice to a Kubernetes cluster.

  • kubernetes/deployment.yaml:

* Defines a Deployment named [YOUR_MICROSERVICE_NAME]-deployment.

* Specifies 3 replicas (can be scaled up/down).

* Uses the Docker image [YOUR_DOCKER_REGISTRY]/[YOUR_MICROSERVICE_NAME]:latest (update this with your actual image).

* Configures resource limits and requests for CPU and memory.

* Mounts environment variables from a Kubernetes Secret (e.g., [YOUR_MICROSERVICE_NAME]-secret) for sensitive data like database credentials.

  • kubernetes/service.yaml:

* Defines a Service named [YOUR_MICROSERVICE_NAME]-service.

* Exposes the application on port 80 (mapping to container port 8000).

* Configured as a LoadBalancer type, which will provision an external IP address for access in cloud environments. For internal access, ClusterIP can be used.

6.1. How to Deploy to Kubernetes

  1. Build and Push Docker Image: Ensure your Docker image is built and pushed to a registry accessible by your Kubernetes cluster (this is handled by the CI/CD pipeline).
  2. Create Kubernetes Secret: Create a Kubernetes Secret for your environment variables (e.g., database credentials).

    kubectl create secret generic [YOUR_MICROSERVICE_NAME]-secret \
      --from-literal=DATABASE_URL="postgresql://user:password@db-host:5432/db_name" \
      --from-literal=SECRET_KEY="your_super_secret_key"
    # ... add other secrets as needed
  1. Apply Manifests: Apply the deployment and service manifests to your Kubernetes cluster:

    kubectl apply -f kubernetes/deployment.yaml
    kubectl apply -f kubernetes/service.yaml
  1. Verify Deployment: Check the status of your pods and services:

    kubectl get deployments
    kubectl get pods
    kubectl get services
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);}});}