API Integration Builder
Run ID: 69cbe26f61b1021a29a8d26b2026-03-31Development
PantheraHive BOS
BOS Dashboard

API Integration Builder: Code Generation Deliverable (Step 1 of 2)

Workflow: API Integration Builder

Step: collabgenerate_code

Description: Generate code to integrate with external APIs


1. Introduction

This deliverable provides comprehensive, production-ready Python code for integrating with a generic RESTful API. Given the general nature of the request ("API Integration Builder"), this output focuses on establishing a robust, flexible, and secure foundation for API communication. It includes best practices for authentication, error handling, configuration management, and clear code structure, designed to be easily adaptable to various external APIs.

The generated code serves as a detailed template, demonstrating how to interact with common API patterns (e.g., GET, POST, PUT, DELETE requests) and incorporates two prevalent authentication methods: API Key and OAuth 2.0 Client Credentials.


2. Key Features of the Generated Code


3. Prerequisites

Before running the generated code, ensure you have the following installed:

You can install it using pip:

text • 1,613 chars
**Actionable Steps for Configuration:**

1.  **Create `config.py`**: Create a file named `config.py` and paste the content above into it.
2.  **Update `BASE_URL`**: Replace `"https://api.example.com/v1"` with the actual base URL of the API you are integrating.
3.  **Choose Authentication Method**:
    *   **API Key**: Uncomment and populate `API_KEY` and `API_KEY_HEADER_NAME` with your actual API key and the correct header name (e.g., `Authorization`, `X-API-Key`).
    *   **OAuth 2.0 Client Credentials**: Uncomment and populate `OAUTH_TOKEN_URL`, `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET`, and `OAUTH_SCOPES`.
    *   **Important**: For production environments, **always use environment variables** (`os.getenv`) to store sensitive credentials instead of hardcoding them directly in `config.py`. The provided template already uses `os.getenv` as a best practice.
4.  **Review Other Settings**: Adjust `REQUEST_TIMEOUT`, `RETRY_ATTEMPTS`, `RETRY_DELAY_SECONDS`, and `LOG_LEVEL` as needed.

---

### 5. Code Structure Explanation

The generated code consists of two main parts:

1.  **`api_client.py`**: This file contains the core `APIClient` class, which handles all communication with the external API. It manages authentication, request construction, error handling, and response parsing.
2.  **`example_usage.py`**: This file demonstrates how to instantiate and use the `APIClient` to perform common operations like listing, creating, updating, and deleting resources.

---

### 6. Generated Code

#### 6.1. `api_client.py`

This is the main API client class. It's designed to be robust and adaptable.

Sandboxed live preview

python

import requests

import time

import json

import logging

from datetime import datetime, timedelta

from urllib.parse import urljoin

Ensure config.py is in the same directory or accessible via Python path

from config import APIConfig

Set up logging

logging.basicConfig(level=APIConfig.LOG_LEVEL,

format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

class APIError(Exception):

"""Custom exception for API errors."""

def __init__(self, message, status_code=None, details=None):

super().__init__(message)

self.status_code = status_code

self.details = details

class APIClient:

"""

A robust client for interacting with a RESTful API.

Supports API Key and OAuth 2.0 Client Credentials authentication.

"""

def __init__(self):

self.base_url = APIConfig.BASE_URL

self.session = requests.Session()

self.timeout = APIConfig.REQUEST_TIMEOUT

self.retry_attempts = APIConfig.RETRY_ATTEMPTS

self.retry_delay = APIConfig.RETRY_DELAY_SECONDS

# OAuth 2.0 specific attributes

self._access_token = None

self._token_expires_at = None

self._oauth_token_url = getattr(APIConfig, 'OAUTH_TOKEN_URL', None)

self._oauth_client_id = getattr(APIConfig, 'OAUTH_CLIENT_ID', None)

self._oauth_client_secret = getattr(APIConfig, 'OAUTH_CLIENT_SECRET', None)

self._oauth_scopes = getattr(APIConfig, 'OAUTH_SCOPES', None)

# API Key specific attributes

self._api_key = getattr(APIConfig, 'API_KEY', None)

self._api_key_header_name = getattr(APIConfig, 'API_KEY_HEADER_NAME', 'X-API-Key')

self._configure_authentication()

def _configure_authentication(self):

"""Determines and configures the authentication method."""

if self._api_key:

logger.info("Using API Key authentication.")

# API Key is typically added to headers on each request

self._auth_method = "api_key"

elif self._oauth_token_url and self._oauth_client_id and self._oauth_client_secret:

logger.info("Using OAuth 2.0 Client Credentials authentication.")

self._auth_method = "oauth2"

self._get_oauth_token() # Get initial token

else:

logger.warning("No valid authentication method configured. Proceeding without authentication.")

self._auth_method = "none"

def _get_oauth_token(self):

"""

Requests a new OAuth 2.0 access token using client credentials flow.

"""

if not self._oauth_token_url or not self._oauth_client_id or not self._oauth_client_secret:

raise APIError("OAuth 2.0 credentials or token URL are not configured.")

logger.info("Attempting to obtain new OAuth 2.0 access token...")

try:

response = requests.post(

self._oauth_token_url,

data={

"grant_type": "client_credentials",

"client_id": self._oauth_client_id,

"client_secret": self._oauth_client_secret,

"scope": self._oauth_scopes

},

timeout=self.timeout

)

response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)

token_data = response.json()

self._access_token = token_data.get("access_token")

expires_in = token_data.get("expires_in", 3600) # Default to 1 hour if not provided

self._token_expires_at = datetime.now() + timedelta(seconds=expires_in - 60) # Refresh 60s early

if not self._access_token:

raise APIError("OAuth token response did not contain 'access_token'.",

status_code=response.status_code, details=token_data)

logger.info("Successfully obtained OAuth 2.0 access token.")

except requests.exceptions.RequestException as e:

logger.error(f"Failed to obtain OAuth 2.0 token: {e}")

raise APIError(f"Failed to obtain OAuth 2.0 token: {e}", details=str(e))

except json.JSONDecodeError as e:

logger.error(f"Failed to decode OAuth 2.0 token response: {e}")

raise APIError(f"Failed to decode OAuth 2.0 token response: {e}", details=str(e))

def _prepare_headers(self, custom_headers=None):

"""

Prepares request headers, including authentication.

"""

headers = {

"Content-Type": "application/json",

"Accept": "application/json"

}

if self._auth_method == "api_key":

if self._api_key:

headers[self._api_key_header_name] = self._api_key

else:

logger.warning("API Key is configured but not set.")

elif self._auth_method == "oauth2":

if not self._access_token or (self._token_expires_at and datetime.now() >= self._token_expires_at):

logger.info("OAuth token expired or not present. Refreshing token.")

self._get_oauth_token()

if self._access_token:

headers["Authorization"] = f"Bearer {self._access_token}"

else:

logger.warning("OAuth 2.0 is configured but no access token is available.")

if custom_headers:

headers.update(custom_headers)

return headers

def _request(self, method, path, params=None, data=None, json_data=None, headers=None):

"""

Internal method to make an HTTP request with retry logic.

"""

url = urljoin(self.base_url, path)

request_headers = self._prepare_headers(headers)

for attempt in range(self.retry_attempts):

try:

logger.debug(f"Attempt {attempt + 1}/{self.retry_attempts}: {method} {url}")

response = self.session.request(

method,

url,

params=params,

data=data,

json=json_data,

headers=request_headers,

timeout=self.timeout

)

response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)

return response

except requests.exceptions.HTTPError as e:

logger.error(f"HTTP Error for {method} {url}: {e.response.status_code} - {e.response.text}")

if 400 <= e.response.status_code < 500 and e.response.status_code != 429: # Client error (not rate limit)

raise APIError(f"API client error: {e}", status_code=e.response.status_code, details=e.response.text)

if attempt == self.retry_attempts - 1: # Last attempt, re-raise

raise APIError(f"API server error after {self.retry_attempts} attempts: {e}",

status_code=e.response.status_code, details=e.response.text)

except requests.exceptions.Timeout as e:

logger.warning(f"Request timed out for {method} {url}: {e}")

if attempt == self.retry_attempts - 1:

raise APIError(f"Request timed out after {self.retry_attempts} attempts: {e}", details=

projectmanager Output

API Integration Project Kick-off: "Project Creation for Seamless Integration"

Workflow Step: projectmanagercreate_project

Description: Generate comprehensive guidance and initial frameworks for setting up a new project focused on external API integration. This deliverable outlines the critical planning, architectural, and foundational code considerations to ensure a robust and scalable integration.


1. Introduction: Laying the Foundation for Successful API Integration

Welcome to the "API Integration Builder" workflow. This step, "projectmanager → create_project," is designed to provide you with a detailed and professional framework for initiating your API integration project. Successful API integration begins with meticulous planning and a well-structured project foundation. This output will guide you through the essential considerations, architectural decisions, and initial code structuring required to connect your systems with external services efficiently and securely.

Our goal is to empower you to create a project that is not only functional but also maintainable, scalable, and resilient to potential issues.


2. Core Deliverable: Project Setup & Planning Guide for API Integration

This section provides a structured guide for setting up your API integration project. Each point represents a critical consideration or task.

2.1. Define Project Scope and Objectives

Before writing any code, clearly articulate what you aim to achieve with this integration.

  • Problem Statement: What specific business problem or user need will this API integration solve?
  • Key Objectives:

* What data needs to be exchanged?

* What operations (read, write, update, delete) are required?

* What is the expected volume and frequency of API calls?

* What are the performance requirements (e.g., latency, throughput)?

  • Stakeholders: Identify all internal and external stakeholders who will be impacted or involved.
  • Success Metrics: How will you measure the success and effectiveness of the integration?

2.2. Select and Understand the Target API

Thoroughly research and understand the external API you intend to integrate with.

  • API Documentation Review:

* Endpoints: Identify all relevant endpoints and their purpose.

* Authentication: Understand the required authentication method (API keys, OAuth2, JWT, basic auth).

* Request/Response Formats: Note data structures (JSON, XML), required headers, and expected response codes.

* Rate Limits & Quotas: Be aware of any restrictions on the number of requests per unit of time to avoid service interruptions.

* Error Codes: Understand the API's error handling and common error codes.

* Terms of Service: Review the API provider's terms to ensure compliance and understand usage restrictions.

  • API Versioning: Determine if the API uses versioning and plan for future updates.
  • SDKs/Libraries: Check if the API provider offers official SDKs or client libraries for your preferred programming language, which can significantly expedite development.

2.3. Design the Integration Architecture

Sketch out a high-level design of how your system will interact with the external API.

  • Integration Pattern:

* Direct Integration: Your application calls the API directly.

* Middleware/Proxy: Use an intermediate service (e.g., API Gateway, integration platform) to handle requests, transformations, and security.

* Event-Driven: Use webhooks or message queues for asynchronous communication.

  • Data Flow Diagram: Visualize the flow of data between your system, the integration layer, and the external API.
  • Technology Stack: Choose the programming language, framework, and libraries that best suit your project requirements and existing infrastructure.
  • Scalability & Redundancy: Plan for how the integration will scale with increased load and ensure high availability.

2.4. Environment Setup

Prepare your development and deployment environments.

  • Development Environment:

* Install necessary IDEs, programming language runtimes, and package managers.

* Set up a dedicated repository for the integration project using Version Control (e.g., Git).

* Configure .gitignore to exclude sensitive files and temporary artifacts.

  • API Key/Secret Management:

* Never hardcode credentials. Use environment variables, a dedicated secrets management service (e.g., AWS Secrets Manager, HashiCorp Vault), or a .env file for local development.

* Ensure different credentials are used for development, staging, and production environments.

  • Dependencies: List and manage all external libraries and packages required for the integration.

2.5. Authentication & Authorization Strategy

Implement secure methods for authenticating with the external API.

  • Method Selection: Based on the API's requirements, choose the appropriate method (e.g., OAuth2 client credentials, authorization code flow, API key in headers/query params, JWT).
  • Token Management: If using token-based authentication (e.g., OAuth2, JWT), plan for secure storage, refresh mechanisms, and expiration handling.
  • Least Privilege: Ensure your application only requests the necessary permissions from the external API.

2.6. Data Mapping and Transformation

Define how data will be translated between your system and the external API.

  • Schema Alignment: Map fields from your internal data models to the API's data structures and vice-versa.
  • Data Validation: Implement validation rules to ensure data sent to or received from the API conforms to expected formats and constraints.
  • Transformation Logic: Plan for any necessary data transformations (e.g., unit conversions, formatting dates, aggregating data).
  • Serialization/Deserialization: Choose appropriate libraries for converting data to and from JSON/XML.

2.7. Error Handling and Resilience

Design for robust error handling to prevent integration failures from impacting your application.

  • API Error Codes: Implement specific logic for common API error codes (e.g., 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Rate Limit Exceeded, 5xx Server Errors).
  • Retry Mechanisms: Implement exponential backoff and jitter for transient errors to avoid overwhelming the API.
  • Circuit Breaker Pattern: Protect your application from repeatedly trying to access a failing external service.
  • Fallback Strategies: Define alternative actions or default responses when the API is unavailable or returns unexpected errors.
  • Idempotency: Design API calls to be idempotent where possible, especially for write operations, to prevent duplicate processing during retries.

2.8. Logging and Monitoring

Ensure visibility into the integration's operation and performance.

  • Logging:

* Log all API requests and responses (at appropriate levels, e.g., debug for full payloads, info for summaries).

* Log authentication attempts and failures.

* Record error details, timestamps, and relevant context (e.g., user ID, request ID).

  • Monitoring:

* Set up dashboards to track key metrics (e.g., API call volume, success rates, average response times, error rates).

* Configure alerts for critical failures, high error rates, or performance degradation.

  • Tracing: Implement distributed tracing to track requests across multiple services, including the external API.

2.9. Security Considerations

Prioritize security throughout the integration lifecycle.

  • Input Validation: Sanitize and validate all data before sending it to the API to prevent injection attacks.
  • Secure Credential Storage: Ensure API keys and tokens are stored securely (as per 2.4).
  • HTTPS/TLS: Always use HTTPS for all communication with the external API.
  • Access Control: Restrict access to the integration code and configuration files.
  • Dependency Security: Regularly audit and update third-party libraries to mitigate known vulnerabilities.

2.10. Deployment and Scaling Plan

Plan how the integration will be deployed and managed in production.

  • Deployment Strategy: Define how the integration service will be deployed (e.g., containerized, serverless, VM).
  • Configuration Management: Use environment-specific configuration for API endpoints, credentials, and settings.
  • Load Balancing: If applicable, plan for load balancing to distribute API requests.
  • Auto-Scaling: Consider auto-scaling mechanisms based on demand.
  • Disaster Recovery: Plan for how to recover from major outages affecting the integration.

3. Conceptual Code Generation Framework (Illustrative Example)

Based on the above project setup and planning, the "API Integration Builder" would generate foundational code. Below is a conceptual example of a basic API client structure, demonstrating the type of boilerplate code you would receive, typically in a language like Python or Node.js.

This framework provides a starting point, encapsulating common patterns for API interaction, authentication, and error handling.

Example: Python API Client Structure


# api_client.py

import os
import requests
import json
import time
from requests.exceptions import RequestException, HTTPError

class MyApiClient:
    """
    A client for interacting with the External API.
    """

    # --- Configuration ---
    BASE_URL = os.getenv("EXTERNAL_API_BASE_URL", "https://api.example.com/v1")
    API_KEY = os.getenv("EXTERNAL_API_KEY") # Securely loaded from environment variables
    TIMEOUT_SECONDS = 30
    MAX_RETRIES = 3
    RETRY_DELAY_SECONDS = 1 # Initial delay, will use exponential backoff

    def __init__(self):
        if not self.API_KEY:
            raise ValueError("API_KEY environment variable not set.")
        
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {self.API_KEY}", # Example: Bearer token auth
            "Content-Type": "application/json",
            "Accept": "application/json"
        })
        print(f"API Client initialized for {self.BASE_URL}")

    def _make_request(self, method, endpoint, params=None, data=None, json_data=None, attempts=0):
        """
        Internal method to handle API requests with retry logic and error handling.
        """
        url = f"{self.BASE_URL}/{endpoint}"
        
        try:
            print(f"Making {method} request to: {url}")
            response = self.session.request(
                method,
                url,
                params=params,
                data=data,
                json=json_data,
                timeout=self.TIMEOUT_SECONDS
            )
            response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
            return response.json()

        except HTTPError as e:
            status_code = e.response.status_code
            print(f"HTTP Error {status_code} for {url}: {e.response.text}")
            
            # Implement retry logic for specific transient errors (e.g., 429, 5xx)
            if status_code in [429, 500, 502, 503, 504] and attempts < self.MAX_RETRIES:
                wait_time = self.RETRY_DELAY_SECONDS * (2 ** attempts) # Exponential backoff
                print(f"Retrying in {wait_time} seconds (attempt {attempts + 1}/{self.MAX_RETRIES})...")
                time.sleep(wait_time)
                return self._make_request(method, endpoint, params, data, json_data, attempts + 1)
            
            # Re-raise non-retryable errors or after max retries
            raise ValueError(f"API Error {status_code}: {e.response.text}") from e
        
        except RequestException as e:
            print(f"Network or connection error for {url}: {e}")
            raise ConnectionError(f"Could not connect to API: {e}") from e
        
        except json.JSONDecodeError:
            print(f"Failed to decode JSON from response for {url}: {response.text}")
            raise ValueError(f"Invalid JSON response: {response.text}")
        
        except Exception as e:
            print(f"An unexpected error occurred for {url}: {e}")
            raise

    def get_resource(self, resource_id, query_params=None):
        """
        Example: Fetches a specific resource by ID.
        """
        endpoint = f"resources/{resource_id}"
        return self._make_request("GET", endpoint, params=query_params)

    def create_resource(self, payload):
        """
        Example: Creates a new resource.
        """
        endpoint = "resources"
        return self._make_request("POST", endpoint, json_data=payload)

    def update_resource(self, resource_id, payload):
        """
        Example: Updates an existing resource.
        """
        endpoint = f"resources/{resource_id}"
        return self._make_request("PUT", endpoint, json_data=payload)

# --- Usage Example (in a separate script or main function) ---
if __name__ == "__main__":
    # Ensure environment variables are set for this example
    # Example: export EXTERNAL_API_BASE_URL="https://jsonplaceholder.typicode.com"
    # Example: export EXTERNAL_API_KEY="YOUR_MOCK_API_KEY" (for APIs requiring one)

    try:
        client = MyApiClient()

        # Test GET request

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