API Documentation Generator
Run ID: 69cbc9ee61b1021a29a8c5032026-03-31Development
PantheraHive BOS
BOS Dashboard

We are pleased to present the comprehensive API Documentation for the Product Catalog Management API. This documentation provides detailed information on how to integrate with our services, manage product data, and leverage our platform's capabilities.


Product Catalog Management API Documentation

Table of Contents

  1. Introduction
  2. Base URL
  3. Authentication
  4. Error Handling
  5. Rate Limiting
  6. Endpoints

* 6.1. Get All Products (GET /products)

* 6.2. Get Product by ID (GET /products/{productId})

* 6.3. Create New Product (POST /products)

* 6.4. Update Product (PUT /products/{productId})

* 6.5. Delete Product (DELETE /products/{productId})

  1. Data Models

* 7.1. Product Object

* 7.2. Error Object

  1. SDK Usage Examples
  2. Support & Feedback

1. Introduction

The Product Catalog Management API provides a robust and flexible way to programmatically manage your product catalog. With this API, you can list, retrieve, create, update, and delete product information, including details like name, description, price, and category. This documentation will guide you through the process of integrating your applications with our API.

2. Base URL

All API requests should be made to the following base URL:

https://api.yourcompany.com/v1

3. Authentication

The Product Catalog Management API uses API Keys for authentication. To authenticate your requests, you must include your API Key in the X-API-Key header for every request.

Example:

text • 1,146 chars
*Refer to the [Error Object](#72-error-object) data model for more details.*

### 5. Rate Limiting

To ensure fair usage and maintain API performance, requests are subject to rate limiting.
*   **Limit:** 100 requests per minute per API Key.
*   **Exceeding the limit:** If you exceed the rate limit, the API will return a `429 Too Many Requests` HTTP status code.

We recommend implementing retry logic with exponential backoff for your API calls to gracefully handle rate limit excursions and temporary network issues.

### 6. Endpoints

#### 6.1. Get All Products (`GET /products`)

Retrieves a list of all products in the catalog.

*   **Method:** `GET`
*   **Path:** `/products`
*   **Description:** Returns a paginated list of product objects.
*   **Query Parameters:**
    *   `limit` (optional, integer): Maximum number of products to return per page. Default is 20, max is 100.
    *   `offset` (optional, integer): Number of products to skip before starting to return results. Default is 0.
    *   `category` (optional, string): Filter products by category name.
*   **Responses:**
    *   `200 OK`: A list of product objects.
        
Sandboxed live preview

API Documentation Generator: Architecture Plan

This document outlines the detailed architecture plan for the "API Documentation Generator," a system designed to produce professional, comprehensive API documentation. This plan focuses on the core components, input/output mechanisms, feature implementation strategies, and underlying principles to ensure a robust, scalable, and user-friendly solution.


1. Introduction & Project Goals

The primary goal of the API Documentation Generator is to automate the creation of high-quality, interactive API documentation. This solution aims to reduce manual effort, ensure consistency, and provide a superior experience for API consumers by delivering clear endpoint descriptions, practical request/response examples, precise authentication guides, and actionable SDK usage snippets.

Key Objectives:

  • Automate documentation generation from various API definition sources.
  • Produce human-readable and machine-readable documentation formats.
  • Support rich content including code examples, schemas, and usage guides.
  • Ensure documentation is always up-to-date with API changes.
  • Provide a customizable and extensible platform for diverse API projects.

2. Core Architectural Principles

The architecture will adhere to the following principles:

  • Modularity: Components will be self-contained and loosely coupled to facilitate independent development, testing, and maintenance.
  • Extensibility: The system will be designed to easily integrate new input formats, output templates, and additional features.
  • Scalability: Capable of handling documentation for a large number of APIs and complex API definitions without performance degradation.
  • Configurability: Allow users to customize documentation appearance, content, and generation parameters.
  • Data-Driven: Rely on structured API definitions as the single source of truth for generating documentation.
  • Developer Experience (DX): Optimize for ease of use for both API developers (who provide the input) and API consumers (who read the output).

3. Key Components & Modules

The API Documentation Generator will consist of several interconnected modules, each responsible for a specific phase of the documentation generation process:

3.1. Input Layer: API Definition Parser

This module is responsible for ingesting API definitions from various sources and converting them into a standardized internal representation.

  • Sub-components:

* OpenAPI/Swagger Parser: Handles YAML and JSON files conforming to OpenAPI Specification (OAS) versions 2.0 and 3.x.

* RAML Parser: Processes RAML (RESTful API Modeling Language) definitions.

* API Blueprint Parser: Supports API Blueprint markdown-based definitions.

* Code Annotation Scanner (Optional/Future): Scans source code (e.g., JSDoc, PHPDoc, GoDoc annotations) to extract API metadata.

  • Functionality:

* Validate input schema against respective specifications.

* Parse and extract all relevant API metadata: endpoints, methods, parameters, request bodies, responses, security schemes, tags, descriptions.

3.2. Data Model Layer: Intermediate Representation (IR)

A central, language-agnostic data structure that holds the parsed API information in a standardized, normalized format. This decouples the input parsers from the output renderers.

  • Structure:

* API Metadata (title, version, description, base URL)

* Endpoint Objects (path, method, summary, description, tags)

* Parameter Objects (name, in, type, required, schema, description)

* Request Body Objects (content types, schema, examples)

* Response Objects (status codes, content types, schema, examples)

* Schema Definitions (reusable data structures)

* Security Scheme Definitions (type, description, flow)

* Server Definitions

* External Documentation Links

3.3. Transformation & Enrichment Layer

This module enriches the IR with additional data, processes specific documentation requirements, and prepares the data for rendering.

  • Sub-components:

* Example Generator: Automatically generates realistic request/response examples based on defined schemas (e.g., using Faker libraries for data types, or extracting provided examples).

* Authentication Guide Generator: Interprets security scheme definitions from the IR and generates standardized instructions for various authentication types (API Key, OAuth2, Bearer Token).

* SDK Snippet Generator: Creates language-specific code examples (cURL, Python, JavaScript, Ruby, PHP, Java, etc.) for each endpoint, demonstrating how to make requests, including authentication.

* Markdown/HTML Processor: Converts any embedded Markdown in descriptions into the desired output format's equivalent.

* Cross-referencer: Resolves internal links and references within the documentation (e.g., linking to schema definitions from endpoint parameters).

3.4. Templating & Rendering Layer

This is the core of the documentation generation, using the enriched IR to populate predefined templates for various output formats.

  • Sub-components:

* Template Engine: A robust templating system (e.g., Jinja2, Handlebars.js, Liquid) capable of iterating over the IR and inserting data.

* Theming/Styling Engine: Manages CSS, JavaScript, and other assets for different documentation themes.

* Interactive Components: Integrates elements like "Try It Out" buttons, syntax highlighting, collapsible sections, and search functionality.

3.5. Output Layer

Responsible for finalizing and delivering the generated documentation in the specified format(s).

  • Sub-components:

* Static Site Generator Integration: Publishes documentation as a static website (HTML, CSS, JS).

* Markdown/PDF Exporter: Converts documentation into plain Markdown files or generates PDF documents.

* Version Control Integrator: Optionally pushes generated documentation to a Git repository (e.g., GitHub Pages).


4. Input Sources & Supported Formats

The generator will prioritize industry-standard API description formats:

  • OpenAPI Specification (OAS/Swagger):

* Versions: 2.0, 3.0.x, 3.1.x

* File Formats: JSON, YAML

  • RAML (RESTful API Modeling Language):

* Versions: 0.8, 1.0

  • API Blueprint:

* Latest stable version

  • Future Considerations: GraphQL Schema Definition Language (SDL), gRPC ProtoBuf definitions.

5. Output Formats & Customization

The generator will support multiple output formats to cater to diverse needs:

  • Interactive HTML Website (Primary):

* A fully navigable, searchable, and interactive static website.

* Features: "Try It Out" console, syntax highlighting, dark mode, responsive design.

* Theming: Customizable themes, logos, color schemes, and CSS.

  • Markdown:

* Generates a collection of Markdown files, suitable for integration into existing documentation platforms (e.g., GitBook, Docusaurus).

  • PDF:

* Print-ready PDF documents for offline consumption.

  • Future Considerations: Postman Collection, OpenAPI Definition (regenerated/validated).

6. Feature Implementation Details

6.1. Endpoint Descriptions

  • Extraction: Descriptions will be directly extracted from the summary and description fields within the API definition for each path and HTTP method.
  • Rich Text Support: Markdown within descriptions will be rendered as HTML in the web output, supporting bold, italics, lists, code blocks, and links.
  • Clarity: Emphasis will be placed on presenting descriptions clearly at the top of each endpoint section.

6.2. Request/Response Examples

  • Automatic Generation: If no explicit examples are provided in the API definition, the generator will infer and create examples based on schema types (e.g., string -> "example string", integer -> 123, array -> [item1, item2]).
  • Schema-Driven Examples: For complex objects, examples will respect nested schemas and data constraints.
  • User-Provided Examples: Prioritize examples explicitly defined in the OpenAPI examples or x-examples fields.
  • Format Options: Display examples in both JSON and XML formats where applicable, with easy toggling.
  • Code Blocks: Examples will be presented in syntax-highlighted code blocks for readability.

6.3. Authentication Guides

  • Detection: Automatically identify security schemes defined in the API specification (e.g., apiKey, http (Bearer, Basic), oauth2, openIdConnect).
  • Standardized Instructions: Generate clear, step-by-step instructions for each authentication method:

* API Key: How to obtain the key, where to include it (header, query parameter), and example usage.

* OAuth2: Overview of flow types (authorization code, implicit, client credentials, password), how to get an access token, and how to use it in requests.

* Bearer Token: How to include the token in the Authorization header.

* Basic Auth: How to encode credentials and include them.

  • Contextual Guides: Authentication details will be linked from relevant endpoints that require specific security schemes.

6.4. SDK Usage Examples

  • Multi-language Snippets: Generate code snippets for popular programming languages (Python, JavaScript/Node.js, Ruby, PHP, Java, Go, C#) and generic cURL commands.
  • Dynamic Parameterization: Snippets will dynamically include path parameters, query parameters, headers, and request body based on the endpoint definition.
  • Authentication Integration: Code examples will demonstrate how to correctly include authentication credentials (e.g., setting Authorization headers, passing API keys).
  • "Try It Out" Functionality: For web output, an interactive console will allow users to modify parameters and make live API calls directly from the documentation (requires CORS configuration on the API server).

6.5. Navigation & Search

  • Hierarchical Navigation: A sidebar navigation will list API tags, endpoints, and schemas, allowing for quick access.
  • Full-Text Search: Implement a client-side search engine (e.g., Lunr.js, FlexSearch.js) to enable fast searching across all documentation content.
  • Table of Contents: Automatically generated table of contents for long sections.

6.6. Version Control & Publishing

  • Git Integration: Support for integrating with Git repositories (e.g., generating documentation directly into a docs/ folder, or pushing to a gh-pages branch).
  • Semantic Versioning: Clearly display the API version in the documentation and potentially support versioned documentation (e.g., v1.0, v2.0).

7. Conceptual Technology Stack

This section outlines potential technologies that could be used to implement the architecture.

  • Core Language: Python (for its robust ecosystem of parsing and templating libraries) or JavaScript/TypeScript (for web-native tooling).
  • API Definition Parsing:

* Python: openapi-spec-validator, pyyaml, jsonschema

* JavaScript: swagger-parser, @redocly/openapi-core

  • Intermediate Representation: Custom Python/JavaScript objects or Pydantic models.
  • Templating Engine:

* Python: Jinja2

* JavaScript: Handlebars.js, Nunjucks

  • Static Site Generation (for HTML Output):

* Python: MkDocs, Sphinx (with OpenAPI extensions)

* JavaScript: Docusaurus, Next.js (static export), VuePress

  • Syntax Highlighting: Prism.js, Highlight.js
  • "Try It Out" Functionality: fetch API, Axios (client-side)
  • Search: Lunr.js, FlexSearch.js
  • PDF Generation: WeasyPrint (Python), Puppeteer (Node.js)

8. Workflow & Process

The typical workflow for generating documentation will be as follows:

  1. Input API Definition: User provides an API definition file (e.g., openapi.yaml) and configuration (e.g., output format, theme).
  2. Parse & Validate: The Input Layer parses and validates the definition against its schema.
  3. Create Intermediate Representation: Parsed data is converted into the standardized IR.
  4. Enrich Data: The Transformation Layer generates examples, SDK snippets, and authentication instructions, adding them to the IR.
  5. Apply Templates: The Templating Layer uses the enriched IR to populate chosen templates (e.g., HTML, Markdown).
  6. Generate Output: The Output Layer compiles the rendered templates into the final documentation artifact (e.g., a static HTML site, a collection of Markdown files, a PDF).
  7. Publish/Save: The generated documentation is saved to a specified directory or published to a hosting service.

9. Scalability, Maintainability & Extensibility

  • Scalability: The modular design allows for parallel processing of multiple API definitions. The use of static site generation ensures that the serving of documentation is highly scalable and low-cost.
  • Maintainability: Clear separation of
gemini Output

As part of the "API Documentation Generator" workflow, this step focuses on generating the core technical documentation in a machine-readable, industry-standard format, along with practical code examples for interaction.

The output below provides a comprehensive OpenAPI 3.0 Specification (YAML) for a hypothetical E-commerce Product API. This specification serves as the definitive contract for your API, detailing every endpoint, parameter, request/response structure, and authentication mechanism. It is the foundation for generating interactive documentation (e.g., Swagger UI), client SDKs in various languages, and server stubs.

Additionally, we provide well-commented, production-ready code examples demonstrating how to interact with an API defined by this specification, covering basic requests, authentication, and simulating SDK usage.


E-

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