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

This deliverable provides comprehensive, detailed, and professional code examples and explanations that would be integrated into high-quality API documentation. The generated code covers various aspects including endpoint requests in multiple languages, authentication methods, and hypothetical SDK usage, ensuring clarity and ease of use for developers consuming the API.


API Documentation Code Generation: PantheraHive User Management API

This section provides production-ready code snippets and explanations designed to be directly embedded into the API documentation for the PantheraHive User Management API. These examples cover common API interactions, authentication patterns, and SDK usage across popular programming languages.


1. API Overview (Hypothetical)

The PantheraHive User Management API provides a robust set of endpoints for managing user accounts, profiles, and roles within the PantheraHive ecosystem. It is a RESTful API that uses standard HTTP methods and status codes, and returns JSON-formatted responses.

Base URL: https://api.pantherahive.com/v1


2. Authentication Methods

The PantheraHive User Management API supports two primary authentication methods: API Key for simple server-to-server integrations, and OAuth 2.0 (Bearer Token) for more secure and delegated access.

2.1. API Key Authentication

For quick and simple integrations, you can authenticate using an API Key. This key should be passed in the X-API-Key HTTP header for every request.

Example (Python):

text • 364 chars
---

## 3. Endpoint Examples

This section provides detailed examples for interacting with key endpoints of the PantheraHive User Management API.

### 3.1. List All Users

Retrieves a paginated list of all user accounts.

*   **HTTP Method:** `GET`
*   **Path:** `/users`
*   **Authentication:** Required (API Key or OAuth 2.0)

**Request Examples:**

**cURL:**

Sandboxed live preview

This document outlines the architectural plan for the "API Documentation Generator," a system designed to produce professional, comprehensive, and user-friendly API documentation from various input sources. This plan details the core components, technology recommendations, data flow, and an accompanying implementation & learning roadmap to guide development.


API Documentation Generator: Architecture Plan

1. Introduction

The API Documentation Generator aims to streamline the creation of high-quality API documentation. It will transform raw API specifications (e.g., OpenAPI, Postman Collections) and related assets into structured, readable, and interactive documentation, suitable for developers, integrators, and product managers. The generated documentation will include detailed endpoint descriptions, request/response examples, authentication guides, and SDK usage examples, ensuring a consistent and professional presentation.

2. Core Architectural Components

The system will be composed of several distinct, interacting layers to ensure modularity, maintainability, and extensibility.

2.1. Input Layer

This layer is responsible for ingesting, validating, and normalizing various API specification formats.

  • Parsers: Modules dedicated to interpreting different API definition formats (e.g., OpenAPI/Swagger JSON/YAML, Postman Collections, RAML).
  • Validators: Ensures the input specifications adhere to their respective schemas and are syntactically and semantically correct.
  • Asset Ingester: Handles supplementary assets like markdown files for overview/guides, images, or custom CSS/JS.

2.2. Core Processing & Data Model Layer

This is the heart of the generator, responsible for creating a unified, internal representation of the API and enriching it with additional context.

  • Internal Data Model: A canonical, technology-agnostic data structure that represents the API's endpoints, schemas, security schemes, and other elements. This model acts as the single source of truth for the rendering process.
  • Transformation Engine: Converts the parsed input data into the Internal Data Model. It handles schema resolution, inheritance, and normalization.
  • Enrichment Engine: Augments the core API data with additional information:

* Authentication Guides: Integrates explanations and examples for various authentication methods (API Key, OAuth2, JWT).

* SDK Usage Examples: Generates or includes code snippets demonstrating API usage in different programming languages.

* Custom Content Integration: Merges user-provided markdown for introductory sections, tutorials, or FAQs.

2.3. Output & Rendering Layer

This layer focuses on converting the Internal Data Model into the final documentation artifacts.

  • Templating Engine: Utilizes a flexible templating system to render the internal data model into various output formats (e.g., HTML, Markdown, PDF).
  • Theme Management: Allows for selection and application of pre-defined themes or custom CSS/JS for branding and styling.
  • Static Site Generator (SSG) Integration: If generating static HTML, this component orchestrates the SSG to build the final, deployable documentation site.
  • Output Formatter: Handles the final formatting and packaging of the documentation (e.g., compressing static assets, generating PDF).

2.4. User Interface / CLI

Provides the interface for users to interact with the generator.

  • Command Line Interface (CLI): For programmatic invocation, configuration, and integration into CI/CD pipelines.
  • Optional Web User Interface (Web UI): A browser-based interface for easier configuration, previewing, and managing documentation projects (e.g., selecting input files, themes, generating output).

2.5. Storage Layer (Optional, for Web UI/Persisted Configurations)

If a Web UI is implemented, this layer manages persistent data.

  • Configuration Storage: Stores generator settings, project definitions, custom themes, and user preferences.
  • Generated Docs Cache: Optionally caches generated documentation for faster retrieval or deployment.

3. Key Architectural Decisions & Considerations

  • Input Format Priority: Prioritize OpenAPI 3.x as the primary input format due to its widespread adoption and rich schema capabilities. Provide extensibility for other formats.
  • Static Site Generation: Focus on generating static HTML documentation for performance, security, and ease of deployment.
  • Extensibility: Design for a plugin-based architecture for parsers, custom content, and output formats to allow for future expansion without modifying core logic.
  • Modularity: Ensure clear separation of concerns between layers to facilitate independent development, testing, and maintenance.
  • Performance: Optimize parsing, transformation, and rendering processes to handle large API specifications efficiently.
  • Developer Experience: Provide clear error messages, comprehensive logging, and a user-friendly CLI/Web UI.

4. Conceptual Data Flow

  1. Input Acquisition: User provides API specification files (e.g., openapi.yaml) and supplementary content (e.g., overview.md) via CLI or Web UI.
  2. Parsing & Validation: Input Layer's Parsers interpret the specification, and Validators ensure its correctness.
  3. Internal Model Creation: Core Processing Layer's Transformation Engine converts the parsed data into the Internal Data Model.
  4. Content Enrichment: Enrichment Engine adds authentication guides, SDK examples, and integrates custom markdown content into the Internal Data Model.
  5. Rendering: The Output Layer's Templating Engine, using a selected Theme, renders the enriched Internal Data Model into raw HTML/Markdown files.
  6. Static Site Generation (Optional): If targeting a static site, an SSG integrates the rendered files, assets, and navigation, building the final static website.
  7. Output Delivery: The Output Formatter packages the final documentation (e.g., a dist folder for static HTML, a PDF file) to the user-specified output location.

5. Recommended Technology Stack (Example)

The choice of specific technologies can be adapted based on team expertise and project requirements.

  • Core Logic (Parsing, Transformation, Internal Model):

* Language: Python (rich ecosystem for data processing, YAML/JSON parsing) or Node.js (strong for CLI tools, web development).

* Libraries: PyYAML, jsonschema, openapi-spec-validator (Python); yaml, json-schema, swagger-parser (Node.js).

  • Templating & Rendering:

* Language: Same as Core Logic.

* Libraries: Jinja2 (Python), Handlebars/Nunjucks (Node.js).

  • Static Site Generation (if external SSG is used):

* Hugo, Jekyll, Next.js (for static export), Docusaurus.

  • Search Functionality:

* Lunr.js (client-side search), Algolia (hosted search).

  • CLI Framework:

* Click (Python), Commander.js/Yargs (Node.js).

  • Web UI (Optional):

* Frontend: React, Vue, Angular.

* Backend (for UI API): Flask/Django (Python), Express.js (Node.js).

  • Documentation Hosting:

* GitHub Pages, Netlify, Vercel, AWS S3 + CloudFront.

6. Integration Points

  • Version Control Systems (VCS): Integrate with Git for managing API specifications, custom content, and generator configurations.
  • CI/CD Pipelines: Automate documentation generation and deployment as part of the API development lifecycle (e.g., GitHub Actions, GitLab CI, Jenkins).
  • API Gateways/Management Platforms: Potentially integrate to pull API specs directly or push generated documentation.

API Documentation Generator: Implementation & Learning Roadmap

This roadmap outlines a phased approach for developing the API Documentation Generator, incorporating learning objectives, recommended resources, milestones, and assessment strategies for each phase. This serves as a structured plan for a development team.

Phase 1: Foundation & OpenAPI Input Processing (Weeks 1-2)

  • Learning Objectives:

* Deep understanding of OpenAPI Specification (OAS 3.x) structure and best practices.

* Proficiency in chosen language's YAML/JSON parsing and schema validation libraries.

* Ability to design a foundational, technology-agnostic internal data model.

  • Recommended Resources:

* OpenAPI Specification official documentation (swagger.io/specification).

* JSON Schema documentation.

* Language-specific parsing libraries (e.g., PyYAML, jsonschema for Python; yaml, json-schema for Node.js).

* Examples of well-structured OpenAPI documents.

  • Milestones:

* End of Week 1: Functional parser for basic OpenAPI 3.x YAML/JSON into raw Python/JS objects.

* End of Week 2: Initial version of the Internal Data Model defined. Successful transformation of a simple OpenAPI spec (paths, operations, basic schemas) into the Internal Data Model.

  • Assessment Strategies:

* Unit tests for parser robustness against valid and invalid OpenAPI specs.

* Validation tests ensuring the Internal Data Model correctly reflects the source spec.

* Code reviews for data model design and parsing logic.

Phase 2: Core Logic & Internal Data Model Enrichment (Weeks 3-4)

  • Learning Objectives:

* Advanced data modeling techniques (inheritance, polymorphism within the internal model).

* Strategies for integrating external content (markdown, code examples) into the internal model.

* Understanding of common API authentication methods (API Key, OAuth2, JWT).

  • Recommended Resources:

* Design patterns for data transformation and object-oriented design.

* Documentation on common authentication protocols.

* Examples of SDK usage for popular APIs.

  • Milestones:

* End of Week 3: Internal Data Model extended to support complex schemas, security definitions, and external references.

* End of Week 4: Enrichment Engine capable of integrating placeholder authentication guides and basic SDK usage examples into the Internal Data Model.

  • Assessment Strategies:

* Integration tests verifying the correct merging of external content.

* Peer review of the enriched Internal Data Model structure.

* Functional tests using complex OpenAPI specs with security and example data.

Phase 3: Output Generation & Basic Theming (Weeks 5-7)

  • Learning Objectives:

* Proficiency with chosen templating engine (e.g., Jinja2, Handlebars).

* Fundamentals of static site generation and asset management (CSS, JS).

* Basic UI/UX principles for API documentation.

  • Recommended Resources:

* Official documentation for the selected templating engine.

* Tutorials on static site generators (e.g., Hugo, Jekyll, Docusaurus if used as inspiration).

* MDN Web Docs for HTML/CSS best practices.

  • Milestones:

* End of Week 5: Basic templating setup complete; ability to render a minimal HTML page from the Internal Data Model.

* End of Week 6: Generation of a complete, but unstyled, API documentation site (endpoints,

json

{

"id": "usr_xyz789",

"username": "new.user",

"email": "new.user

gemini Output

API Documentation: PantheraHive Core API

This document provides comprehensive, detailed professional output for the PantheraHive Core API. It serves as a definitive guide for developers to integrate with our services, covering everything from authentication to specific endpoint interactions and SDK usage.


1. Introduction

Welcome to the PantheraHive Core API documentation! This API provides programmatic access to manage your PantheraHive resources, including users, projects, and data analytics. Our goal is to offer a robust, secure, and easy-to-use interface for extending and automating your PantheraHive experience.

  • Base URL: https://api.pantherahive.com/v1
  • API Version: v1
  • Data Format: All requests and responses are handled in application/json.
  • Rate Limiting: Currently, the API has a rate limit of 100 requests per minute per IP address. Exceeding this limit will result in a 429 Too Many Requests response.
  • Support: For any questions or issues, please contact our support team at support@pantherahive.com.

2. Authentication

All requests to the PantheraHive Core API must be authenticated. We currently support API Key authentication.

2.1 API Key Authentication

To authenticate your requests, you must include your unique API Key in the Authorization header of every request.

  • Header Name: Authorization
  • Header Value Format: Bearer YOUR_API_KEY

Example:


Authorization: Bearer ph_sk_YOUR_SECRET_API_KEY

2.2 Obtaining Your API Key

  1. Log in to your PantheraHive dashboard.
  2. Navigate to "Settings" > "API Keys".
  3. Click "Generate New API Key".
  4. Important: Your API Key will only be shown once. Copy it immediately and store it securely. If you lose it, you will need to generate a new one.

3. Error Handling

The PantheraHive Core API uses standard HTTP status codes to indicate the success or failure of an API request. In case of an error, the API will return a JSON object containing an error field with a code and message describing the issue.

3.1 Common HTTP Status Codes

| Status Code | Description | Error Object Example |

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

| 200 OK | The request was successful. | N/A |

| 201 Created | The resource was successfully created. | N/A |

| 204 No Content | The request was successful, no content to return. | N/A |

| 400 Bad Request | The request was malformed or invalid. | {"error": {"code": "invalid_request", "message": "Missing required field: name"}} |

| 401 Unauthorized | Authentication failed or not provided. | {"error": {"code": "unauthorized", "message": "Invalid or missing API key"}} |

| 403 Forbidden | The authenticated user does not have permission. | {"error": {"code": "forbidden", "message": "Insufficient permissions to access this resource"}} |

| 404 Not Found | The requested resource does not exist. | {"error": {"code": "not_found", "message": "User with ID 'usr_abc123' not found"}} |

| 409 Conflict | The request conflicts with the current state of the resource. | {"error": {"code": "conflict", "message": "User with this email already exists"}} |

| 429 Too Many Requests | Rate limit exceeded. | {"error": {"code": "rate_limited", "message": "Too many requests. Please try again later."}} |

| 500 Internal Server Error | An unexpected error occurred on our servers. | {"error": {"code": "server_error", "message": "An unexpected error occurred. Please try again."}} |


4. Endpoints Reference

This section details all available API endpoints, including their methods, paths, parameters, and example requests/responses.

4.1 Users

Manage user accounts within your PantheraHive organization.

##### 4.1.1 List All Users

Retrieves a list of all users in your organization.

  • Method: GET
  • Path: /users
  • Description: Fetches a paginated list of users.
  • Query Parameters:

* limit (integer, optional): Maximum number of users to return. Default is 10, max is 100.

* offset (integer, optional): Number of users to skip before starting to return results. Default is 0.

* email (string, optional): Filter users by email address (exact match).

Request Example:


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

Response Example (200 OK):


{
  "data": [
    {
      "id": "usr_abc123",
      "email": "alice@example.com",
      "name": "Alice Smith",
      "role": "admin",
      "status": "active",
      "created_at": "2023-01-15T10:00:00Z",
      "updated_at": "2023-01-15T10:00:00Z"
    },
    {
      "id": "usr_def456",
      "email": "bob@example.com",
      "name": "Bob Johnson",
      "role": "member",
      "status": "active",
      "created_at": "2023-01-16T11:30:00Z",
      "updated_at": "2023-01-16T11:30:00Z"
    }
  ],
  "meta": {
    "total": 25,
    "limit": 5,
    "offset": 0
  }
}

Response Example (401 Unauthorized):


{
  "error": {
    "code": "unauthorized",
    "message": "Invalid or missing API key"
  }
}

##### 4.1.2 Retrieve a Specific User

Retrieves details for a single user by their ID.

  • Method: GET
  • Path: /users/{id}
  • Description: Fetches details of a specific user.
  • Path Parameters:

* id (string, required): The unique identifier of the user (e.g., usr_abc123).

Request Example:


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

Response Example (200 OK):


{
  "id": "usr_abc123",
  "email": "alice@example.com",
  "name": "Alice Smith",
  "role": "admin",
  "status": "active",
  "created_at": "2023-01-15T10:00:00Z",
  "updated_at": "2023-01-15T10:00:00Z"
}

Response Example (404 Not Found):


{
  "error": {
    "code": "not_found",
    "message": "User with ID 'usr_xyz789' not found"
  }
}

##### 4.1.3 Create a New User

Creates a new user in your organization.

  • Method: POST
  • Path: /users
  • Description: Adds a new user.
  • Request Body Parameters:

* email (string, required): The user's email address. Must be unique.

* name (string, required): The user's full name.

* role (string, optional): The user's role. Can be admin or member. Defaults to member.

Request Example:


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

Response Example (201 Created):


{
  "id": "usr_ghi789",
  "email": "charlie@example.com",
  "name": "Charlie Brown",
  "role": "member",
  "status": "pending",
  "created_at": "2023-07-20T14:30:00Z",
  "updated_at": "2023-07-20T14:30:00Z"
}

Response Example (400 Bad Request):


{
  "error": {
    "code": "invalid_request",
    "message": "Missing required field: email"
  }
}

Response Example (409 Conflict):


{
  "error": {
    "code": "conflict",
    "message": "User with email 'alice@example.com' already exists"
  }
}

##### 4.1.4 Update an Existing User

Updates details for an existing user.

  • Method: PUT
  • Path: /users/{id}
  • Description: Modifies an existing user's information.
  • Path Parameters:

* id (string, required): The unique identifier of the user.

  • Request Body Parameters:

* email (string, optional): The user's updated email address. Must be unique if provided.

* name (string, optional): The user's updated full name.

* role (string, optional): The user's updated role. Can be admin or member.

* status (string, optional): The user's updated status. Can be active, inactive.

Request Example:


curl -X PUT \
  'https://api.pantherahive.com/v1/users/usr_abc123' \
  -H 'Authorization: Bearer ph_sk_YOUR_SECRET_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "Alice M. Smith",
        "role": "admin"
      }'

Response Example (200 OK):


{
  "id": "usr_abc123",
  "email": "alice@example.com",
  "name": "Alice M. Smith",
  "role": "admin",
  "status": "active",
  "created_at": "2023-01-15T10:00:00Z",
  "updated_at": "2023-07-20T15:00:00Z"
}

##### 4.1.5 Delete a User

Deletes a user from your organization.

  • Method: DELETE
  • Path: /users/{id}
  • Description: Removes a user. This action is irreversible.
  • Path Parameters:

* id (string, required): The unique identifier of the user to delete.

Request Example:


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

Response Example (204 No Content):


(No response body)

Response Example (404 Not Found):


{
  "error": {
    "code": "not_found",
    "message": "User with ID 'usr_xyz789' not found"
  }
}

4.2 Projects

Manage projects within your PantheraHive organization.

(Similar detailed sections for List, Retrieve, Create, Update, Delete Project endpoints would follow, mirroring the structure of the Users section.)


5. SDK Usage Examples

To simplify integration, PantheraHive provides official SDKs for popular programming languages.

5.1 Python SDK

The PantheraHive Python SDK allows you to interact with the API using idiomatic Python code.

Installation:


pip install pantherahive

Initialization:


from pantherahive import PantheraHiveClient

client = PantheraHiveClient(api_key="ph_sk_YOUR_SECRET_API_KEY")

Examples:

##### 5.1.1 List All Users


from pantherahive import PantheraHiveClient

client = PantheraHiveClient(api_key="ph_sk_YOUR_SECRET_API_KEY")

try:
    users = client.users.list(limit=5)
    for user in users.data:
        print(f"User ID: {user.id}, Email: {user.email}, Name: {user.name}")
except Exception as e:
    print(f"Error listing users: {e}")

##### 5.1.2 Create a New User


from pantherahive import PantheraHiveClient

client = PantheraHiveClient(api_key="ph_sk_YOUR_SECRET_API_KEY")

try:
    new_user = client.users.create(
        email="diana@example.com",
        name="Diana Prince",
        role="member"
    )
    print(f"Created user: {new_user.id}, Email: {new_user.email}")
except Exception as e:
    print(f"Error creating user: {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);}});}