API Documentation Writer
Run ID: 69bcaa0477c0421c0bf4a4ec2026-03-29Development
PantheraHive BOS
BOS Dashboard

API Documentation: Generic Resource Management API (Draft)

This document provides a comprehensive draft of API documentation based on your request. It covers essential sections for a typical RESTful API, offering a foundational structure and content that can be further refined and customized. This output serves as the "generate" step, providing the initial detailed content for your API.


1. Introduction

Welcome to the documentation for the Generic Resource Management API. This API provides a robust and flexible way to programmatically interact with and manage various resources within our system. It is designed to be intuitive, consistent, and scalable, enabling developers to build powerful applications and integrations.

This documentation will guide you through the process of authentication, available endpoints, data models, error handling, and best practices for integrating with our API.

Key Features:

2. API Overview

The Generic Resource Management API allows you to perform standard CRUD (Create, Read, Update, Delete) operations on various "resources" (e.g., items, users, products, etc.). For the purpose of this documentation, we will use a generic Item resource as an example.

Base URL:

All API requests should be prefixed with the following base URL:

https://api.example.com/v1

Versioning:

The API is versioned to ensure backward compatibility. The current version is v1. We recommend specifying the version in your requests.

3. Authentication

Access to the Generic Resource Management API requires authentication. We support API Key Authentication for server-to-server integrations and OAuth 2.0 (Client Credentials Grant) for more complex application scenarios.

3.1. API Key Authentication

For quick and simple integrations, you can use an API Key. Your API Key must be included in the Authorization header of every request.

How to obtain your API Key:

Request Header Example:

text • 1,007 chars
**Specific Recommendation:**
*   Implement proper token caching and refresh mechanisms to avoid requesting new tokens for every API call.
*   Ensure your `client_secret` is handled with the same security precautions as an API key.

## 4. Endpoints

This section details the available API endpoints. All examples assume you have successfully authenticated.

### 4.1. Item Resource

The `Item` resource represents a fundamental entity in our system.

#### 4.1.1. Get All Items

Retrieves a list of all items.

*   **Method:** `GET`
*   **Path:** `/items`
*   **Description:** Returns an array of item objects.
*   **Query Parameters:**
    *   `limit` (optional, integer): Maximum number of items to return. Default: `100`. Max: `500`.
    *   `offset` (optional, integer): Number of items to skip from the beginning. Default: `0`.
    *   `status` (optional, string): Filter items by their status (e.g., `active`, `inactive`, `archived`).
*   **Response (200 OK):**
    *   **Body:** `application/json`
    
Sandboxed live preview

Common HTTP Status Codes and Error Codes:

| HTTP Status Code | Error Code | Description | Actionable Detail |

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

| 200 OK | N/A | Request successful. | No action needed. |

| 201 Created | N/A | Resource successfully created. | No action needed. |

| 204 No Content | N/A | Request successful, no content to return (e.g., DELETE). | No action needed. |

| 400 Bad Request| INVALID_INPUT | The request body or parameters contain invalid or missing data. | Check the details array in the response for specific field validation errors. |

| 401 Unauthorized| UNAUTHORIZED | Authentication credentials were not provided or are invalid. | Ensure your API Key or OAuth 2.0 token is correctly included in the Authorization header and is valid. |

| 403 Forbidden | FORBIDDEN | The authenticated user does not have permission to access the requested resource or perform the action. | Verify the scope of your access token or the permissions associated with your API Key. |

| 404 Not Found | RESOURCE_NOT_FOUND| The requested resource could not be found. | Check the resource ID or path for typos. The resource may have been deleted. |

| 405 Method Not Allowed| METHOD_NOT_ALLOWED| The HTTP method used is not supported for this endpoint. | Ensure you are using the correct HTTP method (e.g., GET, POST, PUT, DELETE) for the specific endpoint. |

| 429 Too Many Requests| RATE_LIMIT_EXCEEDED| You have sent too many requests in a given amount of time. | Implement exponential backoff and retry logic. Check Rate-Limit-* headers for details. |

| 500 Internal Server Error| INTERNAL_SERVER_ERROR| An unexpected error occurred on the server. | This is a server-side issue. Report the issue to support with the request ID if available. |

| 503 Service Unavailable| SERVICE_UNAVAILABLE| The server is currently unable to handle the request due to temporary overload or maintenance. | Retry the request after a short delay. |

6. Rate Limiting

To ensure fair usage and maintain API stability, requests are subject to rate limiting. If you exceed the allocated rate limits, you will receive a 429 Too Many Requests HTTP status code.

Rate Limit Headers:

| Header | Description |

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

| RateLimit-Limit | The maximum number of requests allowed in the current rate limit window. |

| RateLimit-Remaining| The number of requests remaining in the current rate limit window. |

| RateLimit-Reset | The time (in UTC epoch seconds) when the current rate limit window resets. |

Specific Recommendation:

  • Implement client-side logic to respect these headers. When a 429 is received, pause requests and retry only after the RateLimit-Reset time, or implement an exponential backoff strategy.

7. Best Practices & Further Recommendations

  • Idempotency: For POST requests that create resources, consider implementing idempotency keys to prevent duplicate creations if a request is retried.
  • Webhooks: For events that occur asynchronously (e.g., item status changes, long-running processes), consider using webhooks to notify your application rather than polling the API.
  • Client Libraries/SDKs: Develop and provide official client libraries (SDKs) in popular programming languages (e.g., Python, Node.js, Ruby, Java) to simplify integration for developers.
  • OpenAPI/Swagger Specification: Generate an OpenAPI (formerly Swagger) specification file (.yaml or .json) for your API. This provides a machine-readable description of your API, enabling automatic client generation, interactive documentation (like Swagger UI), and API testing tools (like Postman).
  • Postman Collection: Provide a Postman Collection for easy testing and exploration of the API endpoints.
  • Changelog: Maintain a detailed changelog to inform developers about new features, bug fixes, and breaking changes.
  • Support & Feedback: Clearly define channels for developers to get support or provide feedback (e.g., email, community forum, GitHub issues).

8. Next Steps (for the user)

This generated output is a comprehensive draft based on a generic API. To make it specific and fully actionable for your actual API, please proceed with the following:

  1. Replace Generic Examples: Update all generic examples (e.g., api.example.com, item_123, YOUR_API_KEY) with your actual API details.
  2. Define Your Resources: Replace the Item resource with your specific resources (e.g., User, Product, Order) and define their properties accurately.
  3. Specify Endpoints: Detail all your specific endpoints, their HTTP methods, path/query/body parameters, and expected responses (including all possible status codes).
  4. Refine Data Models: Provide precise data types, constraints, and examples for all request and response bodies.
  5. Tailor Authentication: Adjust the authentication section to reflect the exact methods your API supports.
  6. Add Specific Error Codes: Expand the error handling section with specific error codes relevant to your business logic.
  7. Implement Recommendations: Consider implementing the "Best Practices & Further Recommendations" that are relevant to your API.
  8. Review and Test: Thoroughly review all sections for accuracy, clarity, and completeness. Test all examples to ensure they work as described.

This document is now ready for the next step in the workflow: refinement and customization.

Step 2: projectmanager

The API Documentation Writer workflow has successfully generated a comprehensive API documentation based on your input description.

Given the input: "This is a test input for the API Documentation Writer workflow. Please generate comprehensive output.", the system has created a detailed documentation structure for a hypothetical "PantheraHive Resource Management API" to demonstrate a complete and professional output. This documentation serves as a template, showcasing best practices for clarity, structure, and actionable content.


PantheraHive Resource Management API Documentation

1. Introduction

Welcome to the PantheraHive Resource Management API documentation. This API provides a robust and flexible interface for programmatically managing various resources within the PantheraHive ecosystem. It allows developers to integrate resource creation, retrieval, updating, and deletion functionalities into their applications, enhancing automation and data synchronization capabilities.

Key Features:

  • RESTful Design: Predictable, resource-oriented URLs.
  • JSON Payloads: Standardized data exchange format.
  • Secure Authentication: Industry-standard OAuth 2.0 for secure access.
  • Comprehensive Error Handling: Clear error messages for easier debugging.

2. Getting Started

To begin using the PantheraHive Resource Management API, follow these quick steps:

  1. Obtain API Credentials: Register your application on the PantheraHive Developer Portal to receive your client_id and client_secret.
  2. Authenticate: Use your credentials to acquire an access token via the OAuth 2.0 Client Credentials flow.
  3. Make Your First Request: Use the access token to call an endpoint, such as listing all resources.

Example Authentication Request (cURL):


curl -X POST \
  https://api.pantherahive.com/oauth/token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET'

Example Response (Access Token):


{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 3600,
  "scope": "resources:read resources:write"
}

Example API Request (cURL):


curl -X GET \
  https://api.pantherahive.com/v1/resources \
  -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' \
  -H 'Accept: application/json'

3. Authentication

The PantheraHive Resource Management API uses OAuth 2.0 Client Credentials Grant for application-level authentication. This method is suitable for server-to-server communication where a client application needs to access resources without an end-user's direct involvement.

3.1. Obtaining Client Credentials

  1. Navigate to the [PantheraHive Developer Portal](https://developer.pantherahive.com/apps).
  2. Register a new application.
  3. Upon registration, you will be provided with a unique client_id and client_secret. Keep these credentials secure.

3.2. Acquiring an Access Token

To authenticate your requests, you must first obtain an access_token by making a POST request to the token endpoint.

  • Endpoint: POST https://api.pantherahive.com/oauth/token
  • Content-Type: application/x-www-form-urlencoded

Request Parameters:

| Parameter | Type | Required | Description |

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

| grant_type | string | Yes | Must be client_credentials. |

| client_id | string | Yes | Your application's client ID. |

| client_secret | string | Yes | Your application's client secret. |

| scope (optional)| string | No | A space-separated list of desired scopes (e.g., resources:read resources:write). If omitted, default scopes are applied. |

Example Request:


POST /oauth/token HTTP/1.1
Host: api.pantherahive.com
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&scope=resources:read%20resources:write

Example Success Response (HTTP 200 OK):


{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "expires_in": 3600,
  "scope": "resources:read resources:write",
  "created_at": 1678886400
}

The expires_in field indicates the token's lifetime in seconds. You should refresh the token before it expires.

3.3. Using the Access Token

Once you have an access_token, include it in the Authorization header of all subsequent API requests as a Bearer token.

Header: Authorization: Bearer YOUR_ACCESS_TOKEN

Example:


GET /v1/resources HTTP/1.1
Host: api.pantherahive.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json

4. Base URL

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

https://api.pantherahive.com/v1

5. Endpoints

The PantheraHive Resource Management API is organized around RESTful resources. All requests and responses are JSON formatted.

5.1. Resource Object

The primary data model for this API is the Resource object.

| Field | Type | Description |

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

| id | string | Unique identifier for the resource. (Read-only) |

| name | string | The name of the resource. |

| type | string | The category or type of the resource. |

| status | string | Current status of the resource (e.g., active, inactive, pending). |

| owner_id | string | The ID of the user or entity that owns the resource. |

| created_at| datetime| Timestamp when the resource was created. (Read-only) |

| updated_at| datetime| Timestamp when the resource was last updated. (Read-only) |

Example Resource Object:


{
  "id": "res_abc123xyz",
  "name": "Project Alpha Server",
  "type": "server",
  "status": "active",
  "owner_id": "usr_789def",
  "created_at": "2023-03-15T10:00:00Z",
  "updated_at": "2023-03-15T10:30:00Z"
}

5.2. List Resources

Retrieve a list of all resources.

  • Endpoint: GET /resources
  • Scope Required: resources:read

Query Parameters:

| Parameter | Type | Required | Description |

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

| limit | integer| No | Maximum number of resources to return. Default is 10, Max is 100. |

| offset | integer| No | Number of resources to skip for pagination. Default is 0. |

| type | string | No | Filter resources by their type. |

| status | string | No | Filter resources by their status. |

| owner_id | string | No | Filter resources by owner ID. |

Example Request:


GET /v1/resources?limit=50&type=server HTTP/1.1
Host: api.pantherahive.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json

Example Success Response (HTTP 200 OK):


{
  "data": [
    {
      "id": "res_abc123xyz",
      "name": "Project Alpha Server",
      "type": "server",
      "status": "active",
      "owner_id": "usr_789def",
      "created_at": "2023-03-15T10:00:00Z",
      "updated_at": "2023-03-15T10:30:00Z"
    },
    {
      "id": "res_def456uvw",
      "name": "Development Database",
      "type": "database",
      "status": "inactive",
      "owner_id": "usr_789def",
      "created_at": "2023-03-14T15:00:00Z",
      "updated_at": "2023-03-14T15:00:00Z"
    }
  ],
  "meta": {
    "total": 2,
    "limit": 50,
    "offset": 0
  }
}

5.3. Get a Specific Resource

Retrieve details for a single resource by its ID.

  • Endpoint: GET /resources/{resource_id}
  • Scope Required: resources:read

Path Parameters:

| Parameter | Type | Required | Description |

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

| resource_id | string | Yes | The unique ID of the resource. |

Example Request:


GET /v1/resources/res_abc123xyz HTTP/1.1
Host: api.pantherahive.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Accept: application/json

Example Success Response (HTTP 200 OK):


{
  "id": "res_abc123xyz",
  "name": "Project Alpha Server",
  "type": "server",
  "status": "active",
  "owner_id": "usr_789def",
  "created_at": "2023-03-15T10:00:00Z",
  "updated_at": "2023-03-15T10:30:00Z"
}

Example Error Response (HTTP 404 Not Found):


{
  "error": {
    "code": "resource_not_found",
    "message": "The resource with ID 'res_unknown' could not be found."
  }
}

5.4. Create a New Resource

Create a new resource.

  • Endpoint: POST /resources
  • Scope Required: resources:write
  • Content-Type: application/json

Request Body Parameters:

| Parameter | Type | Required | Description |

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

| name | string | Yes | The name of the new resource. |

| type | string | Yes | The category or type of the resource. |

| status | string | No | Initial status of the resource. Default is pending. |

| owner_id | string | Yes | The ID of the user or entity that will own the resource. |

Example Request:


POST /v1/resources HTTP/1.1
Host: api.pantherahive.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
Accept: application/json

{
  "name": "New Web Service Instance",
  "type": "service",
  "owner_id": "usr_123abc"
}

Example Success Response (HTTP 201 Created):


{
  "id": "res_ghij789klm",
  "name": "New Web Service Instance",
  "type": "service",
  "status": "pending",
  "owner_id": "usr_123abc",
  "created_at": "2023-03-15T11:00:00Z",
  "updated_at": "2023-03-15T11:00:00Z"
}

Example Error Response (HTTP 400 Bad Request):


{
  "error": {
    "code": "invalid_parameters",
    "message": "Missing required field: 'name'.",
    "details": [
      {
        "field": "name",
        "issue": "is missing"
      }
    ]
  }
}

5.5. Update a Resource

Update an existing resource by its ID. Only fields provided in the request body will be updated.

  • Endpoint: PUT /resources/{resource_id}
  • Scope Required: resources:write
  • Content-Type: application/json

Path Parameters:

| Parameter | Type | Required | Description |

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

| resource_id | string | Yes | The unique ID of the resource. |

Request Body Parameters:

| Parameter | Type | Required | Description |

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

| name | string | No | The new name for the resource. |

| type | string | No | The new type for the resource. |

| status | string | No | The new status for the resource. |

| owner_id | string | No | The new owner ID for the resource. |

Example Request:


PUT /v1/resources/res_abc123xyz HTTP/1.1
Host: api.pantherahive.com
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
Accept: application/json

{
  "status": "inactive",
  "name": "Archived Project Alpha Server"
}

Example Success Response (HTTP 200 OK):


{
  "id": "res_abc123xyz",
  "name": "Archived Project Alpha Server",
  "type": "server",
  "status": "inactive",
  "owner_id": "usr_789def",
  "created_at": "2023-03-15T10:00:00Z",
  "updated_at": "2023-03-15T11:30:00Z"
}

5.6. Delete a Resource

Delete a resource by its ID. This action is irreversible.

  • Endpoint: DELETE /resources/{resource_id}
  • Scope Required: resources:write

Path Parameters:

| Parameter | Type | Required | Description |

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

| resource_id | string | Yes | The unique ID of the resource. |

Example Request:


DELETE /v1/resources/res_def456uvw HTTP/1.1
Host: api.pantherahive.com
Authorization: Bearer YOUR_ACCESS_TOKEN

Example Success Response (HTTP 204 No Content):

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

Example Error Response (HTTP 404 Not Found):


{
  "error": {
    "code": "resource_not_found",
    "message": "The resource with ID 'res_unknown' could not be found for deletion."
  }
}

6. Error Handling

The PantheraHive Resource Management API uses standard HTTP status codes to indicate the success or failure of an API request. In case of an error (status code 4xx or 5xx), the API will return a JSON response body containing an error object with details about the issue.

6.1. General Error Structure


{
  "error": {
    "code": "error_code_string",
    "message": "A human-readable description of the error.",
    "details": [
      {
        "field": "parameter_name",
        "issue": "specific reason for the error"
      }
    ]
  }
}

6.2. Common HTTP Status Codes and Error Codes

| HTTP Status Code | Error Code | Description | Actionable Advice |

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

| 200 OK | | Request successful. | |

| 201 Created | | Resource successfully created. | |

| 204 No Content | | Request successful, no content to return (e.g., DELETE). | |

| 400 Bad Request| invalid_parameters | The request body or query parameters are invalid or missing. | Check request body/query against documentation. |

| 401 Unauthorized| authentication_failed| Authentication credentials are missing or invalid. | Ensure Authorization header is correct and token is valid. |

| 403 Forbidden | permission_denied | The authenticated client does not have the necessary permissions (scopes) to perform this action. | Verify your application's scopes and ensure they include the required permissions. |

| 404 Not Found | resource_not_found | The requested resource does not exist. | Check the resource_id or path for accuracy. |

| 405 Method Not Allowed| method_not_allowed| The HTTP method used is not supported for this endpoint. | Use the correct HTTP method (GET, POST, PUT, DELETE). |

| 429 Too Many Requests| rate_limit_exceeded| The client has sent too many requests in a given time frame. | Implement exponential backoff and respect Retry-After header. |

| 500 Internal Server Error| internal_error| An unexpected error occurred on the server. | This is a server-side issue. Report to support if persistent. |

| 503 Service Unavailable| service_unavailable| The service is temporarily unable to handle the request. | Retry the request after a short delay. |

7. Rate Limiting

To ensure fair usage and maintain API stability, the PantheraHive Resource Management API enforces rate limits.

  • Limit: 100 requests per minute per authenticated application.
  • Exceeding the limit: Will result in an HTTP 429 Too Many Requests response.

7.1. Rate Limit Headers

Responses include the following headers to help you manage your request rates:

| Header | Description |

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

| X-RateLimit-Limit| The maximum number of requests allowed in the current window. |

| X-RateLimit-Remaining| The number of requests remaining in the current window. |

| X-RateLimit-Reset| The Unix timestamp indicating when the current rate limit window resets. |

| Retry-After | (Only on 429 responses) The number of seconds to wait before making another request. |

Recommendation: Implement retry logic with exponential backoff and honor the Retry-After header to prevent your application from being blocked.

8. Versioning

The PantheraHive Resource Management API uses URL-based versioning. The current version is v1.

Example: https://api.pantherahive.com/v1/resources

Future breaking changes will be introduced under a new version (e.g., /v2). Non-breaking changes (e.g., adding new fields, adding new endpoints) will be applied to the current version without incrementing it.

Actionable Detail: Always specify the version in your API calls to ensure compatibility.

9. SDKs and Libraries

While official SDKs are under development, you can use any standard HTTP client library in your preferred programming language to interact with the API.

Specific Recommendation:

  • Python: requests library
  • Node.js: axios or built-in https module
  • Java: OkHttp or HttpClient
  • Ruby: faraday

10. Changelog

This section outlines significant changes and updates to the PantheraHive Resource Management API.

v1.0.0 - 2023-03-15

  • Initial release of the Resource Management API.
  • Endpoints for listing, retrieving, creating, updating, and deleting resources.
  • OAuth 2.0 Client Credentials authentication implemented.
  • Rate limiting introduced.

11. Support

If you encounter any issues, have questions, or require assistance with the PantheraHive Resource Management API, please refer to the following resources:

  • Developer Portal: [https://developer.pantherahive.com](https://developer.pantherahive.com)
  • Support Forum: [https://community.pantherahive.com/api-support](https://community.pantherahive.com/api-support)
  • Contact Support: For urgent issues, open a ticket via our [Support Page](https://support.pantherahive.com/contact).
  • Email: api-support@pantherahive.com

api_documentation_writer.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);}});}