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

This document provides comprehensive and detailed professional API documentation for the PantheraHive Widget Management API. It includes endpoint descriptions, request/response examples, authentication guides, and SDK usage examples to help developers quickly integrate and utilize our services.


PantheraHive Widget Management API Documentation

Welcome to the PantheraHive Widget Management API documentation! This API allows you to programmatically manage your widgets, including creating, retrieving, updating, and deleting them. Our API is designed to be RESTful, predictable, and easy to use, enabling seamless integration with your applications.

Table of Contents

  1. [Introduction](#1-introduction)
  2. [Base URL](#2-base-url)
  3. [Authentication](#3-authentication)

* [API Key Authentication](#api-key-authentication)

* [Generating an API Key](#generating-an-api-key)

  1. [Error Handling](#4-error-handling)
  2. [Rate Limiting](#5-rate-limiting)
  3. [Data Models](#6-data-models)

* [Widget Object](#widget-object)

* [Error Object](#error-object)

  1. [Endpoints](#7-endpoints)

* [Widgets](#widgets)

* [GET /widgets](#get-widgets)

* [POST /widgets](#post-widgets)

* [GET /widgets/{widgetId}](#get-widgets-widgetid)

* [PUT /widgets/{widgetId}](#put-widgets-widgetid)

* [DELETE /widgets/{widgetId}](#delete-widgets-widgetid)

  1. [SDK Usage Examples](#8-sdk-usage-examples)

* [Python](#python)

* [JavaScript (Node.js)](#javascript-nodejs)

  1. [Support](#9-support)

1. Introduction

The PantheraHive Widget Management API provides a robust and secure way to interact with your widget resources. You can perform standard CRUD (Create, Read, Update, Delete) operations on individual widgets and manage collections of widgets. All API requests and responses are formatted as JSON.

2. Base URL

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

https://api.pantherahive.com/v1

3. Authentication

The PantheraHive Widget Management API uses API Key authentication. All requests to protected endpoints must include your API key in the X-API-Key HTTP header.

API Key Authentication

To authenticate your requests, include the X-API-Key header with your secret API key.

Example Request Header:

text • 31 chars
X-API-Key: YOUR_SECRET_API_KEY
Sandboxed live preview

API Documentation Generator: Architecture Plan

This document outlines the detailed architecture plan for a robust, professional API Documentation Generator. The goal is to create a system capable of ingesting various API definitions and generating high-quality, comprehensive, and user-friendly documentation in multiple formats.

1. Overall System Goal & Vision

Goal: To provide a versatile and automated solution for generating professional API documentation that is clear, accurate, and easy to maintain. It aims to reduce the manual effort involved in documentation, ensure consistency, and improve the developer experience for API consumers.

Vision: A tool that acts as the single source of truth for API documentation, integrating seamlessly into CI/CD pipelines and supporting a wide array of input formats and output styles, ultimately fostering better API adoption and understanding.

2. Core Architectural Components

The system will be composed of several interconnected modules, each responsible for a specific function:

2.1. Input Layer (Data Ingestion & Parsing)

This layer is responsible for accepting and interpreting various API definition formats.

  • OpenAPI/Swagger Parser:

* Functionality: Reads and validates OpenAPI (v2, v3, v3.1) or Swagger specifications (YAML/JSON).

* Output: Converts the raw specification into a standardized internal data model.

* Key Features: Schema validation, error reporting for malformed definitions.

  • Markdown/Custom Content Processor:

* Functionality: Ingests additional documentation content (e.g., introduction, getting started guides, tutorials, custom sections) written in Markdown or a similar markup language.

* Output: Parses Markdown into an abstract syntax tree (AST) or structured HTML fragments.

* Key Features: Support for common Markdown extensions (tables, code blocks, admonitions).

  • Code Annotation Extractor (Optional but Recommended):

* Functionality: Scans source code (e.g., JSDoc, PHPDoc, GoDoc, JavaDoc) to extract endpoint descriptions, parameter details, and example usage directly from comments.

* Output: Structured data to augment or generate parts of the API definition.

* Key Features: Language-specific parsers, configurable annotation patterns.

  • Configuration Loader:

* Functionality: Reads system-wide and project-specific configuration files (e.g., output formats, branding, template selection, custom fields).

* Output: Configuration objects for the generator core.

2.2. Documentation Generator Core (Processing & Templating)

This is the central processing unit that transforms parsed input into renderable content.

  • Internal Data Model Normalizer:

* Functionality: Consolidates data from all input sources (OpenAPI, Markdown, code annotations, configuration) into a consistent, unified, and technology-agnostic internal data model. This model represents all aspects of the API documentation (endpoints, parameters, responses, authentication, examples, custom pages).

* Key Features: Data merging, conflict resolution, data enrichment (e.g., inferring examples).

  • Templating Engine:

* Functionality: Applies predefined or custom templates to the normalized internal data model to generate the final documentation content.

* Key Features: Support for various template languages (e.g., Jinja2, Handlebars), conditional rendering, partials/includes, custom helpers.

  • Content Renderer:

* Functionality: Converts structured content (e.g., Markdown AST, internal data model objects) into the desired intermediate format (e.g., HTML fragments).

* Key Features: Syntax highlighting for code examples, Mermaid diagram rendering, mathematical notation support.

2.3. Output Layer (Format Generation & Delivery)

This layer is responsible for producing the final documentation in various requested formats.

  • Static HTML/CSS/JS Generator:

* Functionality: Generates a complete, self-contained static website for the API documentation.

* Key Features: Responsive design, search functionality, navigation (sidebar, table of contents), customizable themes, integration of external assets (fonts, icons).

  • PDF Generator:

* Functionality: Renders the documentation into a printable PDF document.

* Key Features: Customizable cover page, table of contents, pagination, consistent styling with web output.

  • Markdown Exporter:

* Functionality: Exports the entire documentation content back into a structured Markdown format, suitable for Git repositories or other Markdown-based systems.

  • OpenAPI UI Integrator:

* Functionality: Integrates with existing tools like Swagger UI or Redoc to display the OpenAPI specification interactively.

* Key Features: Provides "Try It Out" functionality for endpoints.

  • Version Control Integration:

* Functionality: Publishes generated documentation to a specified Git repository or static hosting service.

2.4. User Interface (Optional - for Management & Configuration)

A web-based UI or robust CLI for interacting with the generator.

  • Web-based UI (Recommended for ease of use):

* Functionality: Provides a dashboard for managing API projects, configuring generation settings, previewing documentation, and triggering builds.

* Key Features: Project management, template selection, custom branding upload, live preview, user management (if hosted).

  • Command Line Interface (CLI):

* Functionality: Allows developers to programmatically trigger documentation generation as part of CI/CD pipelines.

* Key Features: Configuration via arguments/files, exit codes for success/failure.

2.5. Storage & Persistence

Manages the storage of configurations, templates, and generated outputs.

  • Configuration Storage: Database (e.g., PostgreSQL, MongoDB) or file system for templates and settings.
  • Asset Storage: Cloud storage (e.g., AWS S3, Azure Blob Storage, Google Cloud Storage) or local file system for generated documentation artifacts.

3. Data Flow

  1. Input Collection: User provides API definitions (OpenAPI JSON/YAML, Markdown files, configuration) via CLI or Web UI.
  2. Parsing: The Input Layer's parsers (OpenAPI Parser, Markdown Processor, Code Annotation Extractor) process the raw input into a structured, preliminary data representation.
  3. Normalization: The Internal Data Model Normalizer in the Generator Core merges and transforms all parsed data into a unified, consistent internal data model.
  4. Templating: The Templating Engine iterates over the internal data model, applying chosen templates to generate raw content (e.g., HTML fragments, Markdown strings).
  5. Rendering: The Content Renderer processes the raw content, converting Markdown to HTML, applying syntax highlighting, and embedding interactive elements.
  6. Output Generation: The Output Layer takes the rendered content and packages it into the specified final formats (e.g., static HTML files, PDF, Markdown files).
  7. Delivery/Storage: Generated outputs are stored in the Asset Storage, deployed to a static hosting service, or served directly via the UI.

4. Key Technologies & Framework Recommendations

  • Backend (Generator Core & API):

* Primary Choice: Python with FastAPI (for speed and modern async support) or Django (for comprehensive features and ORM).

* Alternatives: Node.js with Express/NestJS, Go with Gin/Echo, Java with Spring Boot.

  • Frontend (for Web UI):

* Primary Choice: React or Vue.js (for reactive, component-based UI development).

* Alternatives: Angular.

  • OpenAPI Parsing:

* Python: openapi-spec-validator, PyYAML.

* Node.js: swagger-parser, js-yaml.

  • Templating Engine:

* Python: Jinja2.

* Node.js: Handlebars, Nunjucks.

* Go: text/template, html/template.

  • Markdown Rendering:

* Python: markdown-it-py, CommonMark.

* Node.js: markdown-it.

  • PDF Generation:

* wkhtmltopdf (via wrapper like pdfkit in Python) or headless browser solutions like Puppeteer (Node.js) for more control over styling.

  • Static Site Generation (for HTML output framework):

* Consider using frameworks like Next.js, Gatsby, or Hugo to serve the generated static HTML efficiently, or generate pure HTML/CSS/JS.

  • Database (for Configuration/User Management):

* PostgreSQL (relational, robust) or MongoDB (NoSQL, flexible schema).

  • Containerization: Docker for packaging, Kubernetes for orchestration.
  • CI/CD: GitHub Actions, GitLab CI, Jenkins for automated build and deployment.

5. Scalability & Performance Considerations

  • Stateless Generator: Ensure the core generation process is stateless to allow for horizontal scaling of generator instances.
  • Asynchronous Processing: Utilize asynchronous programming models (e.g., Python's asyncio, Node.js event loop) for I/O-bound operations like file parsing and generation.
  • Caching: Implement caching for frequently accessed configurations, templates, and potentially generated documentation artifacts.
  • CDN for Static Docs: Deploy generated static HTML documentation to a Content Delivery Network (CDN) for fast global access and reduced server load.
  • Microservices (Long-term): As the system grows, consider breaking down components (e.g., parser, renderer, output generator) into separate microservices.

6. Security Considerations

  • Input Validation: Strictly validate all input (OpenAPI specs, Markdown, configuration) to prevent injection attacks (e.g., XSS in generated HTML, path traversal).
  • Access Control (if hosted): Implement robust authentication (e.g., OAuth2, JWT) and authorization (RBAC) for the Web UI and API endpoints.
  • Sensitive Data Handling: If the generator interacts with live APIs or requires API keys for examples, ensure secure storage and handling of credentials (e.g., environment variables, secret management services).
  • Dependency Scanning: Regularly scan third-party libraries for known vulnerabilities.
  • Least Privilege: Run generator processes with the minimum necessary permissions.
  • Content Security Policy (CSP): Implement CSP headers for generated HTML documentation to mitigate XSS risks.

7. Deployment Strategy

  • Containerized Deployment: Package the generator application (backend, frontend) into Docker containers.
  • Cloud Agnostic: Design for deployment on major cloud providers (AWS, Azure, GCP) using services like:

* Compute: AWS ECS/EKS, Azure Kubernetes Service, Google GKE/Cloud Run.

* Database: AWS RDS, Azure SQL Database, Google Cloud SQL.

* Storage: AWS S3, Azure Blob Storage, Google Cloud Storage for generated artifacts.

  • CI/CD Integration: Automate the build, test, and deployment process using CI/CD pipelines (e.g., GitHub Actions, GitLab CI) to trigger documentation generation on code commits or scheduled intervals.
  • Static Hosting: Serve the generated HTML documentation via static site hosting services (e.g., Netlify, Vercel, AWS S3 with CloudFront).

8. Future Enhancements & Roadmap

  • API Linter Integration: Automatically check API definitions for best practices and consistency.
  • Automated SDK Generation: Generate client SDKs (e.g., Python, Java, JavaScript) directly from the OpenAPI specification.
  • Interactive API Console/Tester: Embed a fully functional API console within the documentation, allowing users to make live API calls.
  • Multi-version Documentation Support: Manage and display documentation for multiple API versions simultaneously.
  • Localization (i18n): Support for generating documentation in multiple languages.
  • AI-powered Content Refinement: Utilize AI to suggest improvements to descriptions, generate example usage, or summarize complex sections.
  • Custom Theme/Branding Editor: A visual editor within the UI to customize documentation themes without coding.
  • Analytics Integration: Track usage of the documentation to identify popular sections and areas for improvement.

Important: Keep your API keys secure and never expose them in client-side code, public repositories, or other insecure locations.

Generating an API Key

You can generate and manage your API keys from your PantheraHive developer dashboard:

  1. Log in to your PantheraHive account.
  2. Navigate to the "Developer Settings" or "API Keys" section.
  3. Click "Generate New API Key".
  4. Copy your API key immediately as it will only be shown once.

4. Error Handling

The API uses standard HTTP status codes to indicate the success or failure of an API request. In case of an error, the response body will contain a JSON object with more details about the error.

| HTTP Status Code | Meaning | Description

gemini Output

PantheraHive Product Catalog API Documentation

Welcome to the PantheraHive Product Catalog API documentation! This document provides a comprehensive guide to interacting with our Product Catalog API, enabling you to programmatically manage products, retrieve product information, and integrate product data into your applications.

Our API is designed to be RESTful, making it easy to understand and use. All requests and responses are handled in JSON format.


Table of Contents

  1. [Introduction](#1-introduction)
  2. [Getting Started](#2-getting-started)
  3. [Authentication](#3-authentication)

* [API Key](#api-key)

  1. [Error Handling](#4-error-handling)
  2. [Endpoints Reference](#5-endpoints-reference)

* [Products](#products)

* [GET /products](#get-products)

* [GET /products/{id}](#get-productsid)

* [POST /products](#post-products)

  1. [SDK Usage Examples](#6-sdk-usage-examples)

* [Python SDK](#python-sdk)

* [JavaScript SDK](#javascript-sdk)

  1. [Rate Limiting](#7-rate-limiting)
  2. [Support](#8-support)
  3. [Changelog](#9-changelog)

1. Introduction

The PantheraHive Product Catalog API provides a robust interface for managing your product inventory. You can use this API to:

  • Retrieve lists of products.
  • Fetch detailed information for specific products.
  • Create new products.
  • Update existing products (not covered in this sample, but typically available).
  • Delete products (not covered in this sample, but typically available).

Our goal is to provide a seamless and efficient way to integrate product management into your workflows and applications.


2. Getting Started

All API requests are made to the base URL:

https://api.pantherahive.com/v1

To use the API, you will need an API Key, which must be included in every request for authentication. See the [Authentication](#3-authentication) section for details.

All requests should use Content-Type: application/json for POST/PUT requests, and responses will also be in JSON format.


3. Authentication

The PantheraHive Product Catalog API uses API Key authentication.

API Key

To authenticate your requests, you must include your unique API Key in the X-API-Key HTTP header. If the API Key is missing or invalid, the API will return a 401 Unauthorized error.

How to obtain your API Key:

Your API Key can be generated and managed from your PantheraHive developer dashboard under the "API Keys" section. Treat your API Key like a password and keep it secure. Do not expose it in client-side code or public repositories.

Example Request Header:


X-API-Key: YOUR_API_KEY_HERE
Content-Type: application/json

4. Error Handling

The API uses standard HTTP status codes to indicate the success or failure of an API request. In case of an error, the response body will contain a JSON object with more details about the error.

| Status Code | Meaning | Description | Example Error Response |

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

| 200 OK | Success | The request was successful. | { "message": "Success", ... } |

| 201 Created | Resource Created | The resource was successfully created. | { "message": "Product created successfully", ... } |

| 400 Bad Request | Invalid Request | The request was malformed or missing required parameters. | { "error": "Bad Request", "details": "Name field is required." } |

| 401 Unauthorized | Authentication Failed | No valid API Key provided, or the API Key is invalid. | { "error": "Unauthorized", "details": "Invalid API Key." } |

| 403 Forbidden | Access Denied | You do not have permission to access the requested resource. | { "error": "Forbidden", "details": "Insufficient permissions." } |

| 404 Not Found | Resource Not Found | The requested resource could not be found. | { "error": "Not Found", "details": "Product with ID 'xyz' not found." } |

| 429 Too Many Requests | Rate Limit Exceeded | You have sent too many requests in a given amount of time. See [Rate Limiting](#7-rate-limiting). | { "error": "Too Many Requests", "details": "Rate limit exceeded. Try again in 60 seconds." } |

| 500 Internal Server Error | Server Error | An unexpected error occurred on the server. Please try again later or contact support. | { "error": "Internal Server Error", "details": "An unexpected error occurred." } |


5. Endpoints Reference

Products

The /products endpoint allows you to manage your product catalog.


##### GET /products

Retrieves a list of all products in the catalog. You can filter and paginate the results using query parameters.

HTTP Method: GET

Path: /products

Description:

Returns an array of product objects. By default, it returns the first 10 products.

Query Parameters:

| Name | Type | Description | Required | Example |

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

| limit | integer | Maximum number of products to return. Default is 10, max is 100. | No | limit=20 |

| offset | integer | Number of products to skip before starting to return results. Default is 0. | No | offset=10 |

| category| string | Filter products by category. | No | category=Electronics |

| search | string | Search products by name or description. | No | search=laptop |

Request Example (cURL):


curl -X GET \
  'https://api.pantherahive.com/v1/products?limit=2&category=Electronics' \
  -H 'X-API-Key: YOUR_API_KEY_HERE'

Request Example (Python):


import requests

api_key = "YOUR_API_KEY_HERE"
base_url = "https://api.pantherahive.com/v1"

headers = {
    "X-API-Key": api_key,
    "Content-Type": "application/json"
}
params = {
    "limit": 2,
    "category": "Electronics"
}

response = requests.get(f"{base_url}/products", headers=headers, params=params)

if response.status_code == 200:
    print(response.json())
else:
    print(f"Error: {response.status_code} - {response.json()}")

Request Example (Node.js):


const fetch = require('node-fetch'); // For Node.js environments

const apiKey = "YOUR_API_KEY_HERE";
const baseUrl = "https://api.pantherahive.com/v1";

async function getProducts() {
    const headers = {
        "X-API-Key": apiKey,
        "Content-Type": "application/json"
    };
    const params = new URLSearchParams({
        limit: 2,
        category: "Electronics"
    }).toString();

    try {
        const response = await fetch(`${baseUrl}/products?${params}`, { headers });
        const data = await response.json();
        if (response.ok) {
            console.log(data);
        } else {
            console.error(`Error: ${response.status} - ${JSON.stringify(data)}`);
        }
    } catch (error) {
        console.error("Network or parsing error:", error);
    }
}

getProducts();

Successful Response (200 OK):


[
  {
    "id": "prod_abc123",
    "name": "Panthera Smart Watch",
    "description": "A sleek smart watch with health tracking features.",
    "price": 199.99,
    "category": "Electronics",
    "stock": 50,
    "created_at": "2023-10-26T10:00:00Z",
    "updated_at": "2023-10-26T10:00:00Z"
  },
  {
    "id": "prod_def456",
    "name": "Ergonomic Office Chair",
    "description": "Comfortable and adjustable chair for long working hours.",
    "price": 349.00,
    "category": "Furniture",
    "stock": 20,
    "created_at": "2023-10-25T14:30:00Z",
    "updated_at": "2023-10-25T14:30:00Z"
  }
]

Error Response (401 Unauthorized):


{
  "error": "Unauthorized",
  "details": "Invalid API Key."
}

##### GET /products/{id}

Retrieves detailed information for a specific product by its unique ID.

HTTP Method: GET

Path: /products/{id}

Description:

Returns a single product object matching the provided id.

Path Parameters:

| Name | Type | Description | Required | Example |

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

| id | string | The unique ID of the product to retrieve. | Yes | prod_abc123 |

Request Example (cURL):


curl -X GET \
  'https://api.pantherahive.com/v1/products/prod_abc123' \
  -H 'X-API-Key: YOUR_API_KEY_HERE'

Request Example (Python):


import requests

api_key = "YOUR_API_KEY_HERE"
base_url = "https://api.pantherahive.com/v1"
product_id = "prod_abc123"

headers = {
    "X-API-Key": api_key,
    "Content-Type": "application/json"
}

response = requests.get(f"{base_url}/products/{product_id}", headers=headers)

if response.status_code == 200:
    print(response.json())
else:
    print(f"Error: {response.status_code} - {response.json()}")

Request Example (Node.js):


const fetch = require('node-fetch');

const apiKey = "YOUR_API_KEY_HERE";
const baseUrl = "https://api.pantherahive.com/v1";
const productId = "prod_abc123";

async function getProductById() {
    const headers = {
        "X-API-Key": apiKey,
        "Content-Type": "application/json"
    };

    try {
        const response = await fetch(`${baseUrl}/products/${productId}`, { headers });
        const data = await response.json();
        if (response.ok) {
            console.log(data);
        } else {
            console.error(`Error: ${response.status} - ${JSON.stringify(data)}`);
        }
    } catch (error) {
        console.error("Network or parsing error:", error);
    }
}

getProductById();

Successful Response (200 OK):


{
  "id": "prod_abc123",
  "name": "Panthera Smart Watch",
  "description": "A sleek smart watch with health tracking features.",
  "price": 199.99,
  "category": "Electronics",
  "stock": 50,
  "created_at": "2023-10-26T10:00:00Z",
  "updated_at": "2023-10-26T10:00:00Z"
}

Error Response (404 Not Found):


{
  "error": "Not Found",
  "details": "Product with ID 'prod_xyz999' not found."
}

##### POST /products

Creates a new product in the catalog.

HTTP Method: POST

Path: /products

Description:

Adds a new product to the catalog. The name, price, and category fields are required. Upon successful creation, returns the newly created product object.

Request Body (JSON):

| Name | Type | Description | Required | Example |

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

| name | string | The name of the product. | Yes | "Wireless Headphones" |

| description| string | A detailed description of the product. | No | "High-fidelity audio with noise cancellation." |

| price | number | The price of the product. | Yes | 129.99 |

| category | string | The category the product belongs to. | Yes | "Electronics" |

| stock | integer | The current stock quantity of the product. Default is 0. | No | 100 |

Request Example (cURL):


curl -X POST \
  'https://api.pantherahive.com/v1/products' \
  -H 'X-API-Key: YOUR_API_KEY_HERE' \
  -H 'Content-Type: application
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);}});}