API Documentation Writer
Run ID: 69cae61dc8ebe3066ba6f33d2026-03-30Development
PantheraHive BOS
BOS Dashboard

As part of your "API Documentation Writer" workflow, we are pleased to present the comprehensive and professionally crafted API documentation. This output, generated by the Gemini model, exemplifies the detailed, accurate, and user-friendly content you can expect, designed to accelerate developer onboarding and ensure seamless API integration.


Deliverable: High-Quality API Documentation Draft

This document provides a detailed, ready-to-publish draft for a hypothetical "Product Catalog API". It covers essential sections from authentication to specific endpoint usage, complete with examples.


Product Catalog API Documentation

Welcome to the Product Catalog API!

The Product Catalog API provides a robust and intuitive way to manage and retrieve product information for your e-commerce platform or application. Designed for developers, this API allows you to access product listings, details, search functionality, and more, enabling you to build rich, dynamic user experiences.

Our goal is to make product data easily accessible and manageable. This documentation will guide you through the process of authenticating, making requests, understanding responses, and handling potential errors.

Key Features:


1. Getting Started

To begin using the Product Catalog API, you will need an API Key. Follow the authentication steps below to ensure your requests are authorized.

1.1 Base URL

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

https://api.yourcompany.com/v1

1.2 Authentication

The Product Catalog API uses API Key authentication. You must include your unique API key in the Authorization header of every request.

Header Format:

Authorization: Bearer YOUR_API_KEY

Example:

text • 1,633 chars
---

## 3. Rate Limiting

To ensure fair usage and system stability, the Product Catalog API enforces rate limits.
*   **100 requests per minute** per API key.

If you exceed the rate limit, you will receive a `429 Too Many Requests` HTTP status code. The response headers will include details about your current rate limit status:

*   `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 UTC epoch timestamp when the current rate limit window resets.

Consider implementing retry logic with exponential backoff in your application to handle rate limit errors gracefully.

---

## 4. Endpoints

This section details the available API endpoints.

### 4.1 Get All Products

Retrieves a paginated list of all products in the catalog.

`GET /products`

#### Parameters

| Name      | Type     | Required | Description                                                                 |
| :-------- | :------- | :------- | :-------------------------------------------------------------------------- |
| `limit`   | `integer` | No       | Maximum number of products to return per page. Default: 10, Max: 100.       |
| `offset`  | `integer` | No       | The number of products to skip before starting to collect the result set.   |
| `category` | `string` | No       | Filter products by category slug (e.g., `electronics`, `books`).            |
| `search`  | `string` | No       | Search products by name or description.                                     |

#### Request Example

**cURL:**

Sandboxed live preview

As an AI assistant executing Step 1 of 3 for the "API Documentation Writer" workflow, the following research topic has been thoroughly investigated: API Documentation Writer.

This output provides a comprehensive and detailed overview, suitable for direct delivery to the customer. It covers the core aspects of the role, its importance, required skills, tools, and best practices.


Research Topic: API Documentation Writer

1. Introduction to the API Documentation Writer Role

An API Documentation Writer is a specialized technical writer focused on creating clear, accurate, and user-friendly documentation for Application Programming Interfaces (APIs). This role is critical for the successful adoption and integration of APIs, acting as a bridge between complex technical systems and the developers, partners, and internal teams who need to use them.

The core purpose of an API Documentation Writer is to demystify APIs, providing all necessary information for users to understand what an API does, how to interact with it, and how to troubleshoot common issues. Effective API documentation is not just a reference; it's a vital tool for developer experience, product success, and reducing support overhead.

2. Key Responsibilities and Activities

The responsibilities of an API Documentation Writer extend beyond simply writing and include a range of activities throughout the API development lifecycle:

  • Understanding the API: Collaborating with API developers, product managers, and architects to gain a deep understanding of the API's functionality, architecture, endpoints, data models, authentication methods, and use cases.
  • Planning and Strategy: Defining the scope, structure, and target audience for the documentation. This includes choosing appropriate documentation tools and formats.
  • Content Creation:

* Writing clear, concise, and accurate API reference documentation (endpoints, parameters, request/response examples).

* Developing "Getting Started" guides, tutorials, and quick-start examples.

* Creating conceptual overviews, authentication guides, and error code explanations.

* Documenting SDKs (Software Development Kits) and client libraries.

  • Code Examples: Developing or working with developers to create accurate and runnable code examples in various programming languages (e.g., cURL, Python, JavaScript, Java).
  • Collaboration: Working closely with engineering teams for technical accuracy, product teams for feature understanding, and support teams for identifying common user pain points.
  • Testing and Validation: Verifying the accuracy of documentation against the actual API behavior, often using API testing tools.
  • Maintenance and Updates: Regularly updating documentation to reflect API changes, new features, deprecations, and user feedback. Managing versioning of documentation alongside API versions.
  • Information Architecture: Designing intuitive navigation and search capabilities within the documentation portal.
  • User Feedback Integration: Collecting and acting on feedback from developers and users to continuously improve documentation quality and usability.

3. Essential Skills and Competencies

To excel in this role, an API Documentation Writer requires a unique blend of technical, writing, and interpersonal skills:

  • Technical Acumen:

* Understanding of Web Technologies: HTTP/HTTPS, REST, SOAP, GraphQL, JSON, XML.

* Basic Programming Knowledge: Ability to read and understand code snippets (e.g., Python, JavaScript, Java, cURL) and potentially write simple scripts for testing or examples.

* API Concepts: Deep understanding of endpoints, parameters, request/response cycles, authentication (OAuth, API Keys, JWT), error handling, webhooks.

* Version Control: Familiarity with Git and platforms like GitHub/GitLab for managing documentation source code.

  • Exceptional Writing and Communication Skills:

* Clarity and Conciseness: Ability to explain complex technical concepts in simple, unambiguous language.

* Audience Awareness: Tailoring content for different technical levels (e.g., novice vs. expert developers).

* Grammar and Style: Adherence to style guides and best practices for technical writing.

* Information Architecture: Structuring information logically for easy navigation and comprehension.

  • API Knowledge: Practical experience consuming and testing APIs.
  • Tools Proficiency: Familiarity with documentation tools, API specification formats, and content management systems.
  • User Empathy: Ability to put oneself in the shoes of the API consumer to anticipate their needs, questions, and pain points.
  • Attention to Detail: Ensuring accuracy in every detail, from parameter names to error messages.
  • Problem-Solving: Identifying gaps in information and proactively seeking solutions.

4. Common Tools and Technologies Utilized

API Documentation Writers leverage a variety of tools to create, manage, and publish high-quality documentation:

  • API Specification Formats:

* OpenAPI/Swagger: Widely used for defining RESTful APIs. Tools can generate interactive documentation directly from these specifications.

* AsyncAPI: For event-driven architectures and message-based APIs.

* RAML (RESTful API Modeling Language): Another specification for defining RESTful APIs.

  • Documentation Generators/Platforms:

* Swagger UI/Editor: Generates interactive documentation from OpenAPI specifications.

* Postman: Beyond API testing, Postman can generate basic documentation from collections.

* Stoplight Studio/Elements: Advanced tools for designing, documenting, and testing APIs using OpenAPI.

* Redoc: Creates beautiful, human-friendly API documentation from OpenAPI specifications.

* MkDocs, Docusaurus, Sphinx: Static site generators often used for conceptual guides and tutorials, sometimes integrated with API reference tools.

* ReadMe.io, GitBook, DocuSign DevCenter: Hosted documentation platforms offering features like analytics, interactive explorers, and versioning.

  • Version Control Systems:

* Git: Essential for managing documentation as code, enabling collaboration, tracking changes, and reverting to previous versions.

* GitHub, GitLab, Bitbucket: Platforms for hosting Git repositories and often integrating with CI/CD pipelines for documentation deployment.

  • API Testing Tools:

* Postman, Insomnia: Used to test API endpoints, generate example requests/responses, and validate documentation accuracy.

* cURL: Command-line tool for making HTTP requests, often used for example code.

  • Content Management Systems (CMS): For managing and publishing broader developer portal content alongside API reference.
  • Diagramming Tools: Lucidchart, draw.io for illustrating API workflows and architecture.

5. Best Practices for Effective API Documentation

High-quality API documentation adheres to several key best practices:

  • Clarity and Accuracy: Every piece of information must be correct and easy to understand. Ambiguity leads to frustration and errors.
  • Comprehensive Coverage: Document all endpoints, parameters, data types, authentication methods, error codes, and rate limits.
  • Structured and Navigable: Organize documentation logically with a clear hierarchy, table of contents, search functionality, and internal links.
  • Audience-Centric Design: Tailor the language and depth of information to the target audience (e.g., quick-start guides for new users, detailed references for experienced developers).
  • Actionable Examples: Provide runnable code examples for common use cases in multiple popular programming languages. Include full request and response examples.
  • Getting Started Guides and Tutorials: Offer step-by-step instructions for initial setup and common workflows to accelerate adoption.
  • Error Handling and Troubleshooting: Document all possible error codes with clear explanations and suggested resolutions.
  • Versioning and Changelogs: Clearly indicate API versions and maintain a detailed changelog for all updates, deprecations, and breaking changes.
  • Maintainability: Treat documentation as code, using version control and automation to streamline updates and ensure consistency.
  • Feedback Mechanisms: Provide a way for users to submit feedback, report errors, or ask questions to foster continuous improvement.

6. Typical Deliverables

An API Documentation Writer is responsible for producing various types of documentation, including:

  • API Reference Documentation: Detailed descriptions of endpoints, methods, parameters, request/response bodies, headers, and authentication.
  • Getting Started Guides/Tutorials: Step-by-step instructions for initial setup, authentication, and making the first API call.
  • Conceptual Guides: Overviews of the API's architecture, design principles, and core concepts.
  • Authentication Guides: Detailed instructions on how to authenticate with the API using various methods.
  • SDK Documentation: Guides and examples for using official or community-contributed Software Development Kits.
  • Use Case/Solution Guides: Demonstrations of how to achieve specific business outcomes using the API.
  • Error Code Reference: A comprehensive list of all possible error codes with explanations and troubleshooting steps.
  • Changelogs and Release Notes: Records of all changes, new features, improvements, and deprecations for each API version.
  • Frequently Asked Questions (FAQs): Answers to common questions posed by API consumers.

7. Value Proposition

The role of an API Documentation Writer is invaluable for several reasons:

  • Enhanced Developer Experience (DX): Great documentation makes APIs easier and more enjoyable to use, fostering a positive developer experience.
  • Accelerated Adoption: Clear documentation significantly reduces the learning curve, allowing developers to integrate APIs faster and more efficiently.
  • Reduced Support Burden: Comprehensive documentation empowers users to self-serve, answering their own questions and troubleshooting issues, thereby reducing the load on support teams.
  • Improved Product Quality and Usability: The process of documenting an API often reveals inconsistencies, ambiguities, or design flaws, leading to a better-designed API overall.
  • Increased API Value: Well-documented APIs are perceived as more professional, reliable, and trustworthy, increasing their perceived value and market adoption.
  • Scalability: Good documentation allows a product to scale without an exponential increase in support resources.


5. Support & Feedback

We are committed to providing a reliable and easy-to-use API. If you encounter any issues, have questions, or would like to provide feedback, please reach out to our support team.

  • Email: support@yourcompany.com
  • Developer Forum: https://community.yourcompany.com/dev

gemini Output

Polished & Formatted API Documentation: Acme Corp Product Management API

This document presents the comprehensive, polished, and professionally formatted API documentation for the Acme Corp Product Management API. It is designed to provide developers with all the necessary information to seamlessly integrate with and utilize our product management functionalities.


1. API Overview

The Acme Corp Product Management API provides a robust and intuitive interface for managing products within the Acme Corp ecosystem. Developers can leverage this API to programmatically create, retrieve, update, and delete product information, offering seamless integration with various applications, e-commerce platforms, and internal systems.

  • Purpose: To enable external and internal systems to manage product data efficiently and programmatically.
  • Key Features:

* Product Lifecycle Management: Full CRUD (Create, Read, Update, Delete) operations for products.

* Detailed Product Information: Manage product names, descriptions, SKUs, prices, stock levels, categories, and more.

* Secure Access: Authenticated access ensuring data integrity and security.

* RESTful Design: Predictable, resource-oriented URLs, and standard HTTP response codes.

  • Audience: Developers, system integrators, and technical teams looking to build applications that interact with Acme Corp's product data.
  • Getting Started: To begin, obtain your API Key from the Acme Corp Developer Portal and ensure you understand the authentication mechanism detailed below.

2. Authentication

The Acme Corp Product Management API uses API Key authentication for secure access. Your API Key must be included in the Authorization header of every request.

  • Method: API Key
  • How to Obtain Credentials:

1. Log in to the Acme Corp Developer Portal.

2. Navigate to the "API Keys" section.

3. Generate a new API Key for your application.

4. Important: Treat your API Key as a sensitive password. Do not expose it in client-side code, public repositories, or unsecured environments.

  • Using Credentials in Requests:

Include your API Key in the Authorization header with the Bearer scheme.

Example Request Header:


    Authorization: Bearer YOUR_API_KEY
    Content-Type: application/json

Replace YOUR_API_KEY with the actual API Key you obtained from the Developer Portal.

3. Base URL & Environments

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

  • Production Environment: https://api.acmecorp.com/v1
  • Sandbox/Testing Environment: https://sandbox.api.acmecorp.com/v1

We recommend using the Sandbox environment for development and testing to avoid impacting live production data.

4. Error Handling

The API uses standard HTTP status codes to indicate the success or failure of an API request. In cases of failure, a detailed error response body will be provided in JSON format.

  • Standard Error Response Format:

    {
      "code": "ERROR_CODE",
      "message": "A human-readable description of the error.",
      "details": {
        "field_name": "Specific details about the field error"
      }
    }
  • Common HTTP Status Codes:

* 200 OK: The request was successful.

* 201 Created: The request was successful, and a new resource was created.

* 204 No Content: The request was successful, but there is no content to send back (e.g., successful deletion).

* 400 Bad Request: The request was malformed or invalid. Check the details field for specific validation errors.

* 401 Unauthorized: Authentication credentials were missing or invalid.

* 403 Forbidden: The authenticated user does not have the necessary permissions to perform the action.

* 404 Not Found: The requested resource could not be found.

* 429 Too Many Requests: Rate limit exceeded.

* 500 Internal Server Error: An unexpected error occurred on the server.

5. Rate Limiting

To ensure fair usage and system stability, the Acme Corp Product Management API enforces rate limits.

  • Limit: 100 requests per minute per API Key.
  • Headers: The following headers are returned with every response to help you manage your request rates:

* 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 UTC epoch timestamp when the current rate limit window resets.

  • Exceeding the Limit: If you exceed the rate limit, the API will return a 429 Too Many Requests status code. You should implement exponential backoff or wait until the X-RateLimit-Reset time before retrying.

6. Endpoints

This section details all available endpoints, including their methods, paths, parameters, request/response structures, and examples.


6.1. Get All Products

Retrieves a list of all products, with optional filtering and pagination.

  • Method: GET
  • Path: /products
  • Description: Returns an array of product objects.
  • Request Headers:

* Authorization: Bearer YOUR_API_KEY (Required)

  • Query Parameters:

* limit (Optional, Integer): Maximum number of products to return per page. Default is 10, Max is 100.

* offset (Optional, Integer): Number of products to skip before starting to collect the result set. Default is 0.

* category (Optional, String): Filter products by a specific category name.

* status (Optional, Enum: active, inactive): Filter products by their status.

  • Request Example (cURL):

    curl -X GET "https://api.acmecorp.com/v1/products?limit=50&category=Electronics" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json"
  • Successful Response (200 OK):

    {
      "data": [
        {
          "id": "prod_abc123",
          "name": "Acme Widget Pro",
          "description": "The professional-grade widget for all your needs.",
          "sku": "AWP-001",
          "price": 99.99,
          "currency": "USD",
          "stock": 150,
          "category": "Electronics",
          "status": "active",
          "created_at": "2023-01-15T10:00:00Z",
          "updated_at": "2023-01-20T14:30:00Z"
        },
        {
          "id": "prod_def456",
          "name": "Acme Gadget Lite",
          "description": "A lightweight and portable gadget.",
          "sku": "AGL-001",
          "price": 29.99,
          "currency": "USD",
          "stock": 300,
          "category": "Accessories",
          "status": "active",
          "created_at": "2023-02-01T09:00:00Z",
          "updated_at": "2023-02-05T11:00:00Z"
        }
      ],
      "meta": {
        "total": 2,
        "limit": 50,
        "offset": 0
      }
    }
  • Possible Status Codes:

* 200 OK

* 400 Bad Request (e.g., invalid limit or offset)

* 401 Unauthorized

* 403 Forbidden


6.2. Create a New Product

Adds a new product to the system.

  • Method: POST
  • Path: /products
  • Description: Creates a new product entry with the provided details.
  • Request Headers:

* Authorization: Bearer YOUR_API_KEY (Required)

* Content-Type: application/json (Required)

  • Request Body (JSON):

* name (String, Required): The name of the product.

* description (String, Optional): A detailed description of the product.

* sku (String, Required): Stock Keeping Unit, must be unique.

* price (Number, Required): The price of the product. Must be positive.

* currency (String, Required): The currency code (e.g., "USD", "EUR").

* stock (Integer, Required): Current stock level. Must be non-negative.

* category (String, Optional): The product category.

* status (Enum: active, inactive, Optional): Initial status of the product. Default is active.

Example Request Body:


    {
      "name": "Acme Super Charger",
      "description": "A rapid charger for all Acme devices.",
      "sku": "ASC-005",
      "price": 39.99,
      "currency": "USD",
      "stock": 500,
      "category": "Accessories",
      "status": "active"
    }
  • Request Example (cURL):

    curl -X POST "https://api.acmecorp.com/v1/products" \
         -H "Authorization: Bearer YOUR_API_KEY" \
         -H "Content-Type: application/json" \
         -d '{
               "name": "Acme Super Charger",
               "description": "A rapid charger for all Acme devices.",
               "sku": "ASC-005",
               "price": 39.99,
               "currency": "USD",
               "stock": 500,
               "category": "Accessories",
               "status": "active"
             }'
  • Successful Response (201 Created):

    {
      "id": "prod_xyz789",
      "name": "Acme Super Charger",
      "description": "A rapid charger for all Acme devices.",
      "sku": "ASC-005",
      "price": 39.99,
      "currency": "USD",
      "stock": 500,
      "category": "Accessories",
      "status": "active",
      "created_at": "2023-03-10T11:22:33Z",
      "updated_at": "2023-03-10T11:22:33Z"
    }
  • Possible Status Codes:

* 201 Created

* 400 Bad Request (e.g., missing required fields, invalid price, duplicate sku)

* 401 Unauthorized

* 403 Forbidden


6.3. Get Product by ID

Retrieves details for a specific product using its unique ID.

  • Method: GET
  • Path: /products/{product_id}
  • Description: Returns a single product object identified by product_id.
  • Request Headers:

* Authorization: Bearer YOUR_API_KEY (Required)

  • Path Parameters:

* product_id (String, Required): The unique identifier of the product.

  • Request Example (cURL):

    curl -X GET "https://api.acmecorp.com/v1/products/prod_abc123" \
         -H "Authorization: Bearer YOUR_API_KEY"
  • Successful Response (200 OK):

    {
      "id": "prod_abc123",
      "name": "Acme Widget Pro",
      "description": "The professional-grade widget for all your needs.",
      "sku": "AWP-001",
      "price": 99.99,
      "currency": "USD",
      "stock": 150,
      "category": "Electronics",
      "status": "active",
      "created_at": "2023-01-15T10:00:00Z",
      "updated_at": "2023-01-20T14:30:00Z"
    }
  • Possible Status Codes:

* 200 OK

* 401 Unauthorized

* 403 Forbidden

* 404 Not Found (if product_id does not exist)


6.4. Update a Product

Modifies an existing product's details

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