API Documentation Generator
Run ID: 69cca3bc3e7fb09ff16a3be02026-04-01Development
PantheraHive BOS
BOS Dashboard

Architecture Plan: API Documentation Generator

This document outlines the detailed architecture for the "API Documentation Generator," a system designed to produce professional, comprehensive API documentation. The architecture focuses on modularity, extensibility, and the ability to generate high-quality documentation covering endpoint descriptions, request/response examples, authentication guides, and SDK usage examples.


1. Introduction

The API Documentation Generator aims to automate and streamline the creation of API documentation from various sources. By transforming raw API definitions into structured, user-friendly, and visually appealing documentation, it enhances developer experience, reduces manual effort, and ensures consistency across API versions. This architecture plan details the core components, their interactions, recommended technologies, and key design principles to achieve these goals.


2. High-Level Architecture Overview

The system follows a pipeline-based architecture, ingesting API definitions, processing them into a standardized internal model, and then rendering this model into various documentation formats using customizable templates.

text • 1,715 chars
+-------------------+     +-------------------------+     +-------------------------------+     +---------------------------+
| Input Source(s)   |     | API Definition Parser   |     | Internal API Model            |     | Documentation Generation  |
| (OpenAPI, RAML,   +-----> (Validation, Schema     +-----> (Standardized, Enriched)      +-----> Engine                  |
| Code Annotations, |     | Transformation)         |     |                               |     | (Template Application,    |
| Postman Collections)|     |                         |     |                               |     | Content Rendering)        |
+-------------------+     +-------------------------+     +-------------------------------+     +---------------------------+
         |                                                                                                   |
         |                                                                                                   |
         v                                                                                                   v
+-------------------+     +-------------------------+     +-------------------------------+     +---------------------------+
| SDK Usage Example |     | Authentication Guide    |     | Output Formatter/Renderer     |     | Generated Documentation   |
| Generator         |     | Generator               |     | (HTML, Markdown, PDF, ReDoc,  |     | (Static Files, Web App,   |
| (Code snippets)   +-----> (Flows, Token Handling) +-----> Swagger UI JSON)              +-----> Versioned Archives)   |
+-------------------+     +-------------------------+     +-------------------------------+     +---------------------------+
Sandboxed live preview

3. Core Components and Modules

3.1. Input Processing Module

This module is responsible for ingesting API definitions from various sources and formats.

  • API Definition Parsers:

* Functionality: Read and parse API definition files (e.g., OpenAPI/Swagger JSON/YAML, RAML, Postman Collections, API Blueprint).

* Validation: Validate the input against its respective schema (e.g., OpenAPI Specification) to ensure correctness and completeness.

* Normalization: Convert diverse input formats into a common, intermediate representation before feeding it to the Internal API Model.

* Extensibility: Designed to easily integrate new parser modules for additional API definition formats.

  • Code Annotation Scanners (Optional):

* Functionality: If supported, this component will scan source code (e.g., Javadoc, PHPDoc, Python docstrings, Go comments) to extract API endpoint information, parameters, and descriptions directly from the code.

* Language-Specific Adapters: Requires adapters for each programming language to correctly parse annotations.

3.2. Internal API Model

A language-agnostic, standardized data structure that holds the entire API definition in a consistent format.

  • Canonical Representation: A rich, object-oriented model that encapsulates all aspects of the API:

* Endpoints: Paths, HTTP methods, summaries, descriptions.

* Parameters: Path, query, header, cookie parameters; their types, descriptions, required status, examples.

* Request Bodies: Media types, schemas, examples.

* Responses: Status codes, media types, schemas, examples, headers.

* Schemas: Data models, components, definitions.

* Security Schemes: Authentication methods (API Key, OAuth2, JWT, Basic Auth), their types, flows, scopes.

* Tags & Groups: For organizing endpoints.

* Servers: Base URLs.

* Metadata: Title, version, description, contact information.

  • Enrichment Layer: Can be extended to add computed properties or derived information not directly present in the source definition (e.g., cross-references, simplified type names).

3.3. Documentation Generation Engine

The core logic that orchestrates the transformation of the Internal API Model into documentation content.

  • Content Assembly: Iterates through the Internal API Model, selecting relevant data points for documentation.
  • Template Processor Integration: Feeds the structured API data into the chosen templating engine.
  • Cross-Referencing: Automatically generates links between related sections (e.g., linking an endpoint to a shared schema definition).
  • Conditional Rendering: Logic to include/exclude sections based on configuration or presence of data.

3.4. Templating and Styling Module

Enables customization of the documentation's appearance and structure.

  • Templating Engine:

* Functionality: Interprets template files (e.g., Handlebars, Jinja2, Liquid) and injects data from the Internal API Model.

* Pre-built Templates: A library of professional, responsive templates for common documentation layouts.

* Custom Template Support: Allows users to provide their own templates for complete control over the output.

  • Styling (CSS/SASS):

* Functionality: Manages the visual styling of the generated documentation.

* Default Themes: Provides a set of default, modern themes.

* Custom CSS/SASS Injection: Allows users to override default styles or inject entirely new stylesheets.

* Asset Management: Handles images, fonts, and other static assets required by the documentation.

3.5. Output Formatting and Rendering Module

Responsible for converting the templated content into the final documentation formats.

  • HTML Renderer:

* Functionality: Generates static HTML files, suitable for web hosting. Includes features like syntax highlighting for code blocks.

* Static Site Generation: Outputs a complete set of HTML, CSS, JS, and asset files.

  • Markdown Renderer:

* Functionality: Produces documentation in Markdown format (e.g., GitHub Flavored Markdown), useful for READMEs, wikis, or further processing.

  • PDF Renderer (Optional):

* Functionality: Converts HTML output into print-ready PDF documents. (e.g., using headless browser like Puppeteer or tools like wkhtmltopdf).

  • Interactive Documentation Viewers (Optional Adapters):

* ReDoc Adapter: Transforms the Internal API Model (or a normalized OpenAPI spec) into a format consumable by ReDoc for beautiful, interactive documentation.

* Swagger UI Adapter: Transforms the Internal API Model into a format consumable by Swagger UI for interactive API exploration and testing.

3.6. Authentication & SDK Example Generation Module

Crucial for providing actionable guidance to developers.

  • Authentication Guide Generator:

* Functionality: Based on the security schemes defined in the Internal API Model, generates comprehensive guides on how to authenticate with the API (e.g., obtaining an API key, OAuth2 flows, generating JWTs).

* Code Snippets: Provides language-specific code examples for common authentication methods.

  • SDK Usage Example Generator:

* Functionality: Generates code snippets demonstrating how to use the API endpoints with various SDKs (or generic HTTP clients).

* Language Adapters: Supports multiple programming languages (e.g., Python, JavaScript, Java, Go, cURL).

* Dynamic Example Generation: Can derive examples from the request/response examples defined in the API specification.

* SDK Integration (Optional): If an SDK generation pipeline exists, this module can directly leverage generated SDKs to produce examples.

3.7. User Interface / API (Optional - for a web-based generator)

If the generator is to be offered as a service or a web application.

  • Web Interface (Frontend):

* Functionality: Allows users to upload API definition files, configure generation options (templates, themes, output formats), trigger documentation generation, and view/download generated documentation.

* Technologies: React, Vue.js, Angular.

  • Backend API:

* Functionality: Exposes endpoints for uploading definitions, managing projects, triggering generation, and retrieving results.

* Technologies: Node.js (Express), Python (FastAPI/Django), Go (Gin), Java (Spring Boot).

3.8. Persistence Layer (Optional - for a web-based generator)

For storing configurations, generated documentation, and audit logs.

  • Database: Stores project configurations, user settings, metadata about generated documentation.

* Technologies: PostgreSQL, MongoDB, MySQL.

  • File Storage: Stores input API definition files, generated documentation artifacts, custom templates, and assets.

* Technologies: Local filesystem, S3-compatible object storage (AWS S3, Google Cloud Storage, Azure Blob Storage).


4. Data Flow and Interactions

  1. Input Ingestion: User provides API definition file(s) (via UI upload, CLI argument, or file system monitor).
  2. Parsing & Validation: The Input Processing Module reads the file, parses its content (e.g., OpenAPI JSON), and validates it against the spec.
  3. Internal Model Creation: The validated data is transformed into the Internal API Model. This is the canonical source of truth for the API.
  4. Content Generation: The Documentation Generation Engine iterates through the Internal API Model.

* It invokes the Authentication Guide Generator and SDK Usage Example Generator to enrich the model with code snippets and guides.

* It then passes the enriched data to the Templating Engine.

  1. Templating & Styling: The Templating Engine applies chosen templates and styles (from the Templating and Styling Module) to the Internal API Model data, producing raw HTML, Markdown, or other intermediate content.
  2. Output Rendering: The Output Formatting and Rendering Module takes the intermediate content and converts it into the final desired formats (e.g., static HTML files, PDF, Markdown files).
  3. Storage & Delivery: The generated documentation files are stored (e.g., in an object storage bucket or local directory) and made available for download or deployment (e.g., served via a web server).

5. Technology Stack Recommendations

  • Primary Programming Language: Python or Node.js (due to rich ecosystem for parsing, templating, and web development). Go is also an excellent choice for performance and concurrency.
  • API Definition Parsing:

* OpenAPI: swagger-parser (JS), pyyaml + custom schema validation (Python), go-swagger/go-swagger (Go).

* RAML: raml-js-parser-2 (JS).

  • Internal API Model: Custom Python/JS/Go objects/structs, potentially leveraging dataclasses (Python) or typescript interfaces.
  • Templating Engines:

* JavaScript: Handlebars.js, Nunjucks, Liquid.js.

* Python: Jinja2.

* Go: html/template, text/template.

  • Markdown Rendering: marked.js (JS), markdown-it (JS), Mistune (Python).
  • HTML/PDF Rendering:

* HTML: Static site generators (e.g., Eleventy, Hugo, Sphinx with ReadTheDocs theme).

* PDF: Puppeteer (Node.js for headless Chrome), wkhtmltopdf (external tool).

  • Interactive Viewers: ReDoc, Swagger UI (integrating their JS libraries).
  • Code Snippet Generation: Custom logic based on language-specific syntax, potentially using libraries like highlight.js for syntax highlighting.
  • Web Framework (if applicable):

* Frontend: React (with Next.js) or Vue.js (with Nuxt.js).

* Backend: FastAPI (Python), Express.js (Node.js), Gin (Go).

  • Database (if applicable): PostgreSQL (relational), MongoDB (document).
  • File Storage (if applicable): AWS S3, Google Cloud Storage, Azure Blob Storage.

6. Key Design Principles

  • Modularity: Each component (parser, generator, renderer) is a distinct module, allowing for independent development, testing, and replacement.
  • Extensibility: Easy to add support for new input formats, output formats, templating engines, or programming languages for SDK examples.
  • Configuration-driven: Behavior is controlled via configuration files (YAML/JSON) rather than code changes, enabling flexible customization.
  • Separation of Concerns: Clear boundaries between data parsing, internal representation, content generation, and rendering.
  • Testability: Each module should be independently testable with clear inputs and outputs.
  • Performance: Optimized for efficient processing of large API definitions and fast generation of documentation.
  • User Experience (Developer & Reader): Prioritize clear, intuitive documentation for readers and a straightforward generation process for developers.

7. Future Considerations and Extensibility

  • Version Control Integration: Direct integration with Git repositories
gemini Output

The gemini → generate_code step focuses on producing the core code for the API Documentation Generator. This output provides a robust, modular, and extensible Python solution that leverages Pydantic for data modeling and generates professional Markdown documentation.

API Documentation Generator: Core Code Implementation

This section provides a Python implementation for an API Documentation Generator. It consists of:

  1. Pydantic Data Models: Structured classes to define the schema of API documentation, including endpoints, parameters, authentication, and examples.
  2. DocumentationGenerator Class: A class responsible for taking the Pydantic data model and rendering it into a well-formatted Markdown string.
  3. Example Usage: A demonstration of how to populate the data models and use the generator to produce
gemini Output

PantheraHive User Management API Documentation

Welcome to the PantheraHive User Management API documentation! This guide provides comprehensive information on how to integrate with our API to manage user accounts efficiently. You'll find details on authentication, available endpoints, request/response formats, error handling, and SDK usage examples.

Our User Management API allows you to programmatically create, retrieve, update, and delete user accounts within the PantheraHive ecosystem.

  • Base URL: https://api.pantherahive.com/v1
  • API Version: v1
  • Data Format: JSON

1. Authentication

Access to the PantheraHive User Management API requires authentication using an API Key. This key must be included in every request header.

1.1 Obtaining Your API Key

  1. Log in to your PantheraHive Developer Portal.
  2. Navigate to the "API Keys" section.
  3. Generate a new API Key if you don't have one, or use an existing one.
  4. Keep your API Key secure and do not expose it in client-side code or public repositories.

1.2 Using Your API Key

Include your API Key in the Authorization header of your HTTP requests, prefixed with Bearer.

Header Example:


Authorization: Bearer YOUR_API_KEY

cURL Example:


curl -X GET \
  https://api.pantherahive.com/v1/users \
  -H 'Authorization: Bearer YOUR_API_KEY'

2. Endpoints

This section details all available endpoints for managing user accounts, including their methods, URLs, parameters, and request/response examples.

2.1 List All Users

Retrieves a paginated list of all registered users.

  • Method: GET
  • URL: /users

Query Parameters:

| Parameter | Type | Description | Required | Default |

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

| limit | Integer | Maximum number of users to return per page (max 100). | No | 20 |

| offset | Integer | The number of users to skip before starting to collect the result set. | No | 0 |

Request Example:


curl -X GET \
  'https://api.pantherahive.com/v1/users?limit=10&offset=0' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Successful Response (200 OK):


{
  "data": [
    {
      "id": "usr_abc123",
      "name": "Alice Smith",
      "email": "alice.smith@example.com",
      "createdAt": "2023-01-15T10:00:00Z",
      "updatedAt": "2023-01-15T10:00:00Z"
    },
    {
      "id": "usr_def456",
      "name": "Bob Johnson",
      "email": "bob.johnson@example.com",
      "createdAt": "2023-01-16T11:30:00Z",
      "updatedAt": "2023-01-16T11:30:00Z"
    }
  ],
  "total": 50,
  "limit": 10,
  "offset": 0
}

Error Response (401 Unauthorized):


{
  "code": "UNAUTHORIZED",
  "message": "Authentication required or invalid API Key."
}

2.2 Get User by ID

Retrieves detailed information for a single user by their unique identifier.

  • Method: GET
  • URL: /users/{id}

Path Parameters:

| Parameter | Type | Description | Required |

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

| id | String | The unique ID of the user. | Yes |

Request Example:


curl -X GET \
  'https://api.pantherahive.com/v1/users/usr_abc123' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Successful Response (200 OK):


{
  "id": "usr_abc123",
  "name": "Alice Smith",
  "email": "alice.smith@example.com",
  "createdAt": "2023-01-15T10:00:00Z",
  "updatedAt": "2023-01-15T10:00:00Z"
}

Error Response (404 Not Found):


{
  "code": "NOT_FOUND",
  "message": "User with ID 'usr_nonexistent' not found."
}

2.3 Create New User

Creates a new user account with the provided details.

  • Method: POST
  • URL: /users

Request Body (application/json):

| Parameter | Type | Description | Required |

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

| name | String | The full name of the user. | Yes |

| email | String | The user's unique email address. | Yes |

| password | String | The user's password (min 8 characters). | Yes |

Request Example:


curl -X POST \
  https://api.pantherahive.com/v1/users \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "Charlie Brown",
        "email": "charlie.brown@example.com",
        "password": "SecurePassword123!"
      }'

Successful Response (201 Created):


{
  "id": "usr_ghi789",
  "name": "Charlie Brown",
  "email": "charlie.brown@example.com",
  "createdAt": "2023-07-20T14:30:00Z",
  "updatedAt": "2023-07-20T14:30:00Z"
}

Error Response (400 Bad Request):


{
  "code": "INVALID_INPUT",
  "message": "Validation failed: 'email' must be a valid email address."
}

Error Response (409 Conflict):


{
  "code": "CONFLICT",
  "message": "A user with this email address already exists."
}

2.4 Update User

Updates an existing user's details. Only the fields provided in the request body will be updated.

  • Method: PUT
  • URL: /users/{id}

Path Parameters:

| Parameter | Type | Description | Required |

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

| id | String | The unique ID of the user to update. | Yes |

Request Body (application/json):

| Parameter | Type | Description | Required |

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

| name | String | The new full name of the user. | No |

| email | String | The user's new unique email address. | No |

| password | String | The user's new password (min 8 characters). | No |

Request Example:


curl -X PUT \
  'https://api.pantherahive.com/v1/users/usr_abc123' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "Alice Wonderland",
        "email": "alice.wonderland@example.com"
      }'

Successful Response (200 OK):


{
  "id": "usr_abc123",
  "name": "Alice Wonderland",
  "email": "alice.wonderland@example.com",
  "createdAt": "2023-01-15T10:00:00Z",
  "updatedAt": "2023-07-20T15:00:00Z"
}

Error Response (404 Not Found):


{
  "code": "NOT_FOUND",
  "message": "User with ID 'usr_nonexistent' not found."
}

2.5 Delete User

Deletes a user account permanently. This action is irreversible.

  • Method: DELETE
  • URL: /users/{id}

Path Parameters:

| Parameter | Type | Description | Required |

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

| id | String | The unique ID of the user to delete. | Yes |

Request Example:


curl -X DELETE \
  'https://api.pantherahive.com/v1/users/usr_ghi789' \
  -H 'Authorization: Bearer YOUR_API_KEY'

Successful Response (204 No Content):

A successful deletion will return an empty response body with a 204 No Content status code.

Error Response (404 Not Found):


{
  "code": "NOT_FOUND",
  "message": "User with ID 'usr_nonexistent' not found."
}

3. SDK Usage Examples

Using SDKs (Software Development Kits) can simplify interaction with the PantheraHive API by handling HTTP requests, authentication, and response parsing. Here are examples for common languages.

3.1 Python

This example uses the requests library to list and create users.


import requests
import json

API_KEY = "YOUR_API_KEY"  # Replace with your actual API key
BASE_URL = "https://api.pantherahive.com/v1"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# --- List all users ---
print("--- Listing Users ---")
try:
    response = requests.get(f"{BASE_URL}/users", headers=headers, params={"limit": 5})
    response.raise_for_status() # Raise an exception for HTTP errors
    users = response.json()
    print(json.dumps(users, indent=2))
except requests.exceptions.RequestException as e:
    print(f"Error listing users: {e}")
    if e.response:
        print(e.response.json())

# --- Create a new user ---
print("\n--- Creating New User ---")
new_user_data = {
    "name": "David Lee",
    "email": "david.lee@example.com",
    "password": "SuperSecretPassword!"
}
try:
    response = requests.post(f"{BASE_URL}/users", headers=headers, data=json.dumps(new_user_data))
    response.raise_for_status()
    created
api_documentation_generator.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
"); 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' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( ) "); 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' import './App.css' function App(){ return(

"+slugTitle(pn)+"

Built with PantheraHive BOS

) } export default App "); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e} .app{min-height:100vh;display:flex;flex-direction:column} .app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px} h1{font-size:2.5rem;font-weight:700} "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` ## Open in IDE Open the project folder in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- 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",'{ "name": "'+pn+'", "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" }, "dependencies": { "vue": "^3.5.13", "vue-router": "^4.4.5", "pinia": "^2.3.0", "axios": "^1.7.9" }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.3", "vite": "^6.0.5", "vue-tsc": "^2.2.0" } } '); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname,'src') } } }) "); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]} '); zip.file(folder+"tsconfig.app.json",'{ "compilerOptions":{ "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"], "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true, "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue", "strict":true,"paths":{"@/*":["./src/*"]} }, "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"] } '); zip.file(folder+"env.d.ts","/// "); zip.file(folder+"index.html"," "+slugTitle(pn)+"
"); 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' import { createPinia } from 'pinia' import App from './App.vue' import './assets/main.css' const app = createApp(App) app.use(createPinia()) app.mount('#app') "); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue"," "); 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} "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` Open in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- 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",'{ "name": "'+pn+'", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test" }, "dependencies": { "@angular/animations": "^19.0.0", "@angular/common": "^19.0.0", "@angular/compiler": "^19.0.0", "@angular/core": "^19.0.0", "@angular/forms": "^19.0.0", "@angular/platform-browser": "^19.0.0", "@angular/platform-browser-dynamic": "^19.0.0", "@angular/router": "^19.0.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.15.0" }, "devDependencies": { "@angular-devkit/build-angular": "^19.0.0", "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "typescript": "~5.6.0" } } '); zip.file(folder+"angular.json",'{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "'+pn+'": { "projectType": "application", "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/'+pn+'", "index": "src/index.html", "browser": "src/main.ts", "tsConfig": "tsconfig.app.json", "styles": ["src/styles.css"], "scripts": [] } }, "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"} } } } } '); zip.file(folder+"tsconfig.json",'{ "compileOnSave": false, "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"]}, "references":[{"path":"./tsconfig.app.json"}] } '); zip.file(folder+"tsconfig.app.json",'{ "extends":"./tsconfig.json", "compilerOptions":{"outDir":"./dist/out-tsc","types":[]}, "files":["src/main.ts"], "include":["src/**/*.d.ts"] } '); zip.file(folder+"src/index.html"," "+slugTitle(pn)+" "); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig) .catch(err => console.error(err)); "); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; } "); 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'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = '"+pn+"'; } "); zip.file(folder+"src/app/app.component.html","

"+slugTitle(pn)+"

Built with PantheraHive BOS

"); 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} "); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] }; "); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router'; export const routes: Routes = []; "); 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)+" Generated by PantheraHive BOS. ## Setup ```bash npm install ng serve # or: npm start ``` ## Build ```bash ng build ``` Open in VS Code with Angular Language Service extension. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local .angular/ "); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/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(" "):"# add dependencies here "; zip.file(folder+"main.py",src||"# "+title+" # Generated by PantheraHive BOS print(title+" loaded") "); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` ## Run ```bash python main.py ``` "); zip.file(folder+".gitignore",".venv/ __pycache__/ *.pyc .env .DS_Store "); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/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)+" "; zip.file(folder+"package.json",pkgJson); var fallback="const express=require("express"); const app=express(); app.use(express.json()); app.get("/",(req,res)=>{ res.json({message:""+title+" API"}); }); const PORT=process.env.PORT||3000; app.listen(PORT,()=>console.log("Server on port "+PORT)); "; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000 "); zip.file(folder+".gitignore","node_modules/ .env .DS_Store "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash npm install ``` ## Run ```bash npm run dev ``` "); } /* --- 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:" "+title+" "+code+" "; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */ *{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e} "); zip.file(folder+"script.js","/* "+title+" — scripts */ "); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Open Double-click `index.html` in your browser. Or serve locally: ```bash npx serve . # or python3 -m http.server 3000 ``` "); zip.file(folder+".gitignore",".DS_Store node_modules/ .env "); } /* ===== 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(/ {2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. Files: - "+app+".md (Markdown) - "+app+".html (styled HTML) "); } 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);}});}