Error Handling System
Run ID: 69cd12533e7fb09ff16a7a8c2026-04-01Development
PantheraHive BOS
BOS Dashboard

Step 2: Error Handling System - Code Generation and Detailed Implementation

This document provides a comprehensive and detailed output for implementing a robust Error Handling System. It focuses on generating clean, well-commented, production-ready code examples, primarily using Python, alongside architectural considerations and best practices. This output is designed to be directly actionable and serve as a foundational deliverable for your system.


1. Introduction: The Imperative of Robust Error Handling

A well-designed error handling system is critical for the stability, reliability, and maintainability of any software application. It transforms unexpected failures into manageable events, providing crucial insights for debugging, ensuring a positive user experience, and safeguarding system integrity. This document outlines the core principles, components, and practical code implementations for building such a system.

2. Core Principles of Effective Error Handling

Before diving into implementation, understanding the guiding principles is essential:

3. Components of a Comprehensive Error Handling System

An effective system typically comprises several interconnected components:

4. Code Implementation Examples (Python)

This section provides production-ready code examples demonstrating key aspects of an error handling system using Python.

4.1. Custom Exception Classes

Defining custom exceptions provides semantic meaning to errors, making code more readable and allowing for more granular error handling.

text • 1,076 chars
**Explanation:**
*   **`ApplicationError` (Base Class):** Provides a common interface for all custom application errors, including a standardized `error_code`, a user-friendly `message`, and a `details` dictionary for additional context. The `to_dict()` method is useful for generating consistent API error responses.
*   **Specific Error Classes:** `DatabaseError`, `ServiceUnavailableError`, and `InvalidInputError` inherit from `ApplicationError`, adding specific attributes relevant to their error type (e.g., `original_exception` for `DatabaseError`, `service_name` for `ServiceUnavailableError`). This allows for targeted exception handling and more informative logging.
*   **Example Usage:** The `process_data` function demonstrates how these custom exceptions can be raised based on different conditions, providing clear and structured error information.

#### 4.2. Structured Logging with Context

Effective error logging captures not just the error message but also crucial contextual information (e.g., request ID, user ID, specific parameters) to aid debugging.

Sandboxed live preview

This document outlines a comprehensive architecture plan for an "Error Handling System," designed to ensure the reliability, stability, and observability of your applications and services. Following this, a detailed study plan is provided to equip your team with the necessary knowledge and skills for its successful implementation and maintenance.


Part 1: Architecture Plan for the Error Handling System

An effective Error Handling System is foundational for maintaining the health and performance of modern software. This plan details a robust, scalable, and observable architecture for systematically managing errors across your entire ecosystem.

1. Introduction and Purpose

The primary goal of this Error Handling System is to provide a centralized, reliable, and actionable mechanism for capturing, processing, storing, notifying, and visualizing errors and exceptions. This system will enable rapid detection, diagnosis, and

python

import logging

import uuid

import sys

from functools import wraps

--- Centralized Logging Configuration ---

def configure_logging():

"""Configures a structured logger for the application."""

# Production-ready logging often uses external handlers like ELK stack, Splunk, etc.

# For demonstration, we'll use a console handler with structured output.

# Custom Formatter for JSON-like output (or use a dedicated library like python-json-logger)

class JsonFormatter(logging.Formatter):

def format(self, record):

log_entry = {

"timestamp": self.formatTime(record, self.datefmt),

"level": record.levelname,

"name": record.name,

"message": record.getMessage(),

"trace_id": getattr(record, 'trace_id', 'N/A'),

"user_id": getattr(record, 'user_id', 'N/A'),

"filename": record.filename,

"lineno": record.lineno,

"funcName": record.funcName,

}

if record.exc_info:

log_entry["exception"] = self.formatException(record.exc_info)

if record.stack_info:

log_entry["stack_info"] = self.formatStack(record.stack_info)

# Add any extra attributes passed to the logger

for key, value in record.__dict__.items():

if key not in log_entry and not key.startswith('_') and key not in ['args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'funcName', 'levelname', 'levelno', 'lineno', 'module', 'msecs', 'message', 'name', 'pathname', 'process', 'processName', 'relativeCreated', 'stack_info', 'thread', 'threadName']:

log_entry[key] = value

import json

return json.dumps(log_entry)

logger = logging.getLogger("app_logger")

logger.setLevel(logging.INFO) # Default level

# Ensure handlers are not duplicated if called multiple times

if not logger.handlers:

handler = logging.StreamHandler(sys.stdout)

handler.setFormatter(JsonFormatter())

logger.addHandler(handler)

return logger

app_logger = configure_logging()

--- Context Manager for Request-Specific Context ---

class RequestContext:

"""A simple thread-local context manager for request-specific data."""

_current = None

def __init__(self, trace_id=None, user_id=None):

self.trace_id = trace_id if trace_id else str(uuid.uuid4())

self.user_id = user_id

self._previous = RequestContext._current # Store previous context for nesting

def __enter__(self):

RequestContext._current = self

return self

def __exit__(self, exc_type, exc_val, exc_tb):

RequestContext._current = self._previous # Restore previous context

@staticmethod

def current():

return RequestContext._current

--- Error Logging Function ---

def log_error(exception: Exception, level=logging.ERROR, extra_context: dict = None):

"""

Logs an exception with structured context.

Args:

exception: The exception object to log.

level: The logging level (e.g., logging.ERROR, logging.WARNING).

extra_context: Additional dictionary of key-value pairs to include in the log.

"""

current_context = RequestContext.current()

log_data = {}

if current_context:

log_data['trace_id'] = current_context.trace_id

log_data['user_id'] = current_context.user_id

if extra_context:

log_data.update(extra_context)

# If it's a custom ApplicationError, add its structured details

if isinstance(exception, ApplicationError):

log_data['error_code'] = exception.error_code

log_data['app_error_message'] = exception.message

log_data['app_error_details'] = exception.details

app_logger.log(level, f"Unhandled exception: {exception}", exc_info=True, extra=log_data)

--- Example Usage with RequestContext ---

def simulate_api_request(user_id, endpoint_data):

# Simulate a web request starting

trace_id = str(uuid.uuid4())

with RequestContext(trace_id=trace_id, user_id=user_id):

app_logger.info("Request started.", extra={'trace_id': trace_id, 'user_id': user_id, 'endpoint': endpoint_data.get('path')})

try:

result = process_data(endpoint_data) # Using process_data from previous example

app_logger.info(f"Request completed successfully: {result}", extra={'trace_id': trace_id, 'user_id': user_id})

return {"status": "success", "data": result}

except ApplicationError as e:

log_error(e, extra_context={'endpoint': endpoint_data.get('path'), 'request_body': endpoint_data})

return {"status": "error", "message": e.message, "error_code": e.error_code, "details": e.details}

except Exception as e:

# Catch any other unexpected errors

log_error(e, level=logging.CRITICAL, extra_context={'endpoint': endpoint_data.get('path'), 'request_body': endpoint_data})

return {"status": "error", "message": "An unexpected internal server error occurred.", "error_

gemini Output

Error Handling System: Comprehensive Deliverable

This document provides a comprehensive overview and detailed specifications for the proposed Error Handling System. Designed for robustness, maintainability, and operational efficiency, this system aims to significantly improve application stability, accelerate issue resolution, and enhance user experience by proactively managing and responding to errors.


1. Introduction and System Goals

The Error Handling System is a critical component designed to detect, log, notify, and facilitate the resolution of unexpected events or failures within our applications and infrastructure. Its primary goals are to:

  • Improve System Stability: Minimize the impact of errors on system availability and performance.
  • Accelerate Issue Resolution: Provide clear, actionable information to development and operations teams, enabling faster diagnosis and remediation.
  • Enhance User Experience: Reduce instances of unhandled errors visible to end-users and ensure graceful degradation.
  • Facilitate Proactive Monitoring: Enable early detection of anomalies and potential failures before they escalate.
  • Support Continuous Improvement: Provide data-driven insights into error patterns for root cause analysis and preventative measures.
  • Ensure Data Integrity: Implement mechanisms to prevent data corruption or loss due to errors.

2. Core Components and Architecture

The Error Handling System is structured around several interconnected components, working in tandem to provide end-to-end error management.

2.1. Error Detection & Interception

  • Purpose: Identify and capture errors as close to their origin as possible.
  • Mechanisms:

* Application-Level: Try-catch blocks, global exception handlers, middleware (e.g., for API errors).

* Framework-Level: Built-in error handling provided by application frameworks (e.g., Spring Boot, Node.js Express, React error boundaries).

* Infrastructure-Level: Monitoring agents (e.g., Prometheus exporters, ELK stack agents) for system-level errors (resource exhaustion, network issues).

* API Gateways: Centralized error handling for microservice communication.

2.2. Error Logging

  • Purpose: Record detailed information about detected errors for analysis and auditing.
  • Key Features:

* Structured Logging: JSON or similar format for easy parsing and querying.

* Contextual Data: Inclusion of relevant information (user ID, request ID, transaction ID, service name, hostname, timestamp, log level).

* Stack Traces: Full stack traces for code-related errors.

* Centralized Logging Platform: Aggregation of logs from all services into a single system (e.g., ELK Stack, Splunk, Datadog Logs).

2.3. Error Classification & Prioritization

  • Purpose: Categorize errors based on type, severity, and impact to inform appropriate responses.
  • Classification Criteria:

* Type: Application error (code bug), Infrastructure error (DB connection, network), Configuration error, External service error, User input error.

* Severity: Critical, High, Medium, Low, Informational.

* Impact: Business critical functionality, Data integrity, Performance degradation, User experience.

  • Prioritization: Automated rules based on severity, frequency, and affected components.

2.4. Notification & Alerting

  • Purpose: Inform relevant stakeholders about significant errors in a timely manner.
  • Channels:

* Internal Communication: Slack, Microsoft Teams, Email.

* On-Call Rotation: PagerDuty, Opsgenie, VictorOps for critical alerts.

* Ticketing Systems: Jira, ServiceNow for tracking and assignment.

  • Triggers: Configurable thresholds (e.g., X errors in Y minutes), specific error types, or severity levels.
  • Escalation Policies: Automated escalation paths for unacknowledged or unresolved critical alerts.

2.5. Recovery & Remediation Strategies

  • Purpose: Define actions to mitigate or resolve errors, both automatically and manually.
  • Automated Recovery:

* Retries: Idempotent operations can be retried with exponential backoff.

* Circuit Breakers: Prevent cascading failures by quickly failing requests to unhealthy services.

* Fallback Mechanisms: Provide default responses or alternative functionality when primary services fail.

* Rollbacks: Automated deployment rollbacks for critical errors introduced by new releases.

  • Manual Remediation:

* Runbooks: Documented procedures for common error scenarios.

* Debug Tools: Access to logs, metrics, and tracing for investigation.

* Hotfixes/Patches: Rapid deployment of code corrections.

2.6. Monitoring & Reporting

  • Purpose: Visualize error trends, track performance, and provide insights for continuous improvement.
  • Tools: Dashboards (Grafana, Kibana, Datadog), custom reports.
  • Metrics Tracked:

* Error rates (per service, per endpoint).

* Mean Time To Detect (MTTD).

* Mean Time To Resolve (MTTR).

* Top N error types/locations.

* Number of unhandled exceptions.


3. Error Classification and Severity Matrix

A standardized classification and severity matrix ensures consistent handling and prioritization of errors.

| Classification Category | Description | Severity | Impact | Notification Channel | Remediation Strategy | Example |

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

| Critical | System outage, data loss, major security breach, core functionality unavailable. | High | Immediate, widespread business impact. Service completely unavailable, critical data compromised, significant financial loss, legal/compliance implications. | PagerDuty/Opsgenie (On-call), Slack/Teams (Critical), Email, Jira (P1) | Immediate investigation (SRE/DevOps), hotfix deployment, incident management process, potential rollback. | Database server down, complete API gateway failure, critical user authentication service outage. |

| Major | Significant functionality impaired, performance degradation, partial data loss. | High | Significant localized or partial business impact. Key features unavailable for a subset of users, severe performance issues, potential data inconsistency, customer dissatisfaction. | PagerDuty/Opsgenie (On-call), Slack/Teams (High), Email, Jira (P2) | Urgent investigation, workaround if possible, hotfix deployment, data recovery plan. | Payment gateway integration failure, slow response times for core user flows, specific microservice returning 5xx errors for a region. |

| Minor | Non-critical functionality affected, minor data inconsistencies, degraded UX. | Medium | Limited business impact. Non-essential features broken, minor UI glitches, minor data sync issues, isolated user experience degradation. | Slack/Teams (Medium), Email, Jira (P3) | Scheduled investigation, workaround if simple, fix in next release cycle. | Report generation failure, specific search filter not working, infrequent UI layout issues on a particular browser. |

| Warning | Potential issue, unusual behavior, resource nearing limits, non-fatal errors. | Low | No immediate business impact, but potential for future issues. Indicates a condition that might lead to an error if not addressed, or an expected but non-critical failure (e.g., external API rate limit hit, retry successful after first failure). | Slack/Teams (Low), Email, Jira (P4) | Monitor trends, investigate during regular maintenance windows, address in future sprints. | High CPU usage for a short period, external API returning 4xx for invalid input, a non-critical background job failing occasionally but retrying successfully. |

| Informational | Expected events, successful operations, debug messages. | Info | No business impact. Used for auditing, tracing, and understanding system flow. | Centralized Logging Only | No specific action required, primarily for debugging and auditing. | User login successful, data record created, API request processed successfully. |


4. Implementation Details and Best Practices

4.1. Structured Logging Standards

  • Format: Standardize on JSON for all application logs.
  • Mandatory Fields:

* timestamp: ISO 8601 format.

* level: (e.g., INFO, WARN, ERROR, CRITICAL).

* service_name: Name of the microservice/application.

* host_name: Host where the log originated.

* message: A human-readable summary of the event.

* error_code: A unique identifier for the error type (if applicable).

* stack_trace: Full stack trace for exceptions.

* request_id: Unique ID for a request/transaction, propagated across services.

* user_id: Identifier for the user associated with the request (if authenticated).

* correlation_id: For tracing across distributed systems.

  • Sensitive Data: Ensure no Personally Identifiable Information (PII) or sensitive data is logged without proper masking or encryption.

4.2. Centralized Logging Solution

  • Recommendation: Implement a centralized logging solution (e.g., ELK Stack - Elasticsearch, Logstash, Kibana; Splunk; Datadog Logs).
  • Benefits:

* Single pane of glass for all logs.

* Advanced searching, filtering, and aggregation capabilities.

* Real-time dashboards and visualization of error trends.

* Long-term retention for historical analysis and compliance.

4.3. Monitoring and Alerting Configuration

  • Alerting Rules:

* Error Rate Thresholds: Alert when error rate (e.g., 5xx status codes) exceeds a defined percentage or absolute count within a time window.

* Specific Error Patterns: Alert on critical keywords or error codes in logs.

* Resource Exhaustion: Alerts for high CPU, memory, disk I/O, or network utilization that might precede errors.

* Service Unavailability: Pings or health checks failing.

  • Dashboard Creation: Create dedicated dashboards for error overview, critical errors, and service-specific error metrics.
  • Runbooks Integration: Link alerts directly to relevant runbooks for quick troubleshooting.

4.4. Error Handling in Code

  • Explicit Error Handling: Use try-catch blocks for expected error conditions (e.g., file not found, invalid input).
  • Graceful Degradation: Implement fallback mechanisms for non-critical failures (e.g., show cached data, disable a feature).
  • Idempotency: Design operations to be idempotent where retries are possible without adverse side effects.
  • Custom Exception Types: Define custom exceptions for domain-specific errors to provide clearer context.
  • Error Boundaries (Frontend): Utilize error boundaries in frontend frameworks (e.g., React) to contain UI crashes and provide fallback UIs.

4.5. Incident Management Workflow

  • Tooling: Integrate with an Incident Management System (e.g., PagerDuty, Opsgenie) for on-call rotation, escalation policies, and incident tracking.
  • Playbooks: Develop clear playbooks for different incident types, outlining steps for diagnosis, communication, and resolution.
  • Post-Mortems: Conduct blameless post-mortems for all critical incidents to identify root causes and implement preventative actions.

5. Actionable Next Steps

To successfully implement and operationalize the Error Handling System, we recommend the following phased approach:

  1. Phase 1: Tooling and Infrastructure Setup (Weeks 1-2)

* Action: Finalize and deploy the chosen Centralized Logging Platform (e.g., ELK Stack, Splunk, Datadog).

* Action: Integrate with an Incident Management System (e.g., PagerDuty).

* Action: Set up initial monitoring dashboards and basic alerting rules.

  1. Phase 2: Application Integration - Pilot Services (Weeks 3-5)

* Action: Identify 1-2 critical pilot services for initial integration.

* Action: Implement structured logging standards within these pilot services.

* Action: Integrate application-level error detection and reporting to the centralized logging platform.

* Action: Define and configure specific alerts for these pilot services based on the Severity Matrix.

  1. Phase 3: Documentation and Training (Week 6)

* Action: Develop comprehensive documentation for the Error Handling System, including logging standards, alert definitions, and incident response procedures.

* Action: Conduct training sessions for development, operations, and SRE teams on using the new system, understanding alerts, and following remediation strategies.

  1. Phase 4: Rollout and Refinement (Ongoing)

* Action: Incrementally roll out integration to all remaining services and applications.

* Action: Continuously review and refine alert thresholds, escalation policies, and runbooks based on operational experience.

* Action: Regularly review error reports and conduct post-mortems to drive continuous improvement in system reliability and error prevention.


This Error Handling System is designed to be a living system, evolving with our applications and infrastructure. By adopting these standards and practices, we will significantly enhance our ability to deliver reliable, high-quality services to our users.

error_handling_system.txt
Download source file
Copy all content
Full output as text
Download ZIP
IDE-ready project ZIP
Copy share link
Permanent URL for this run
Get Embed Code
Embed this result on any website
Print / Save PDF
Use browser print dialog
"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( ) "); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react' import './App.css' function App(){ return(

"+slugTitle(pn)+"

Built with PantheraHive BOS

) } export default App "); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e} .app{min-height:100vh;display:flex;flex-direction:column} .app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px} h1{font-size:2.5rem;font-weight:700} "); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` ## Open in IDE Open the project folder in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{ "name": "'+pn+'", "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" }, "dependencies": { "vue": "^3.5.13", "vue-router": "^4.4.5", "pinia": "^2.3.0", "axios": "^1.7.9" }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.3", "vite": "^6.0.5", "vue-tsc": "^2.2.0" } } '); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname,'src') } } }) "); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]} '); zip.file(folder+"tsconfig.app.json",'{ "compilerOptions":{ "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"], "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true, "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue", "strict":true,"paths":{"@/*":["./src/*"]} }, "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"] } '); zip.file(folder+"env.d.ts","/// "); zip.file(folder+"index.html"," "+slugTitle(pn)+"
"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import './assets/main.css' const app = createApp(App) app.use(createPinia()) app.mount('#app') "); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue"," "); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547} "); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` Open in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{ "name": "'+pn+'", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test" }, "dependencies": { "@angular/animations": "^19.0.0", "@angular/common": "^19.0.0", "@angular/compiler": "^19.0.0", "@angular/core": "^19.0.0", "@angular/forms": "^19.0.0", "@angular/platform-browser": "^19.0.0", "@angular/platform-browser-dynamic": "^19.0.0", "@angular/router": "^19.0.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.15.0" }, "devDependencies": { "@angular-devkit/build-angular": "^19.0.0", "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "typescript": "~5.6.0" } } '); zip.file(folder+"angular.json",'{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "'+pn+'": { "projectType": "application", "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/'+pn+'", "index": "src/index.html", "browser": "src/main.ts", "tsConfig": "tsconfig.app.json", "styles": ["src/styles.css"], "scripts": [] } }, "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"} } } } } '); zip.file(folder+"tsconfig.json",'{ "compileOnSave": false, "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]}, "references":[{"path":"./tsconfig.app.json"}] } '); zip.file(folder+"tsconfig.app.json",'{ "extends":"./tsconfig.json", "compilerOptions":{"outDir":"./dist/out-tsc","types":[]}, "files":["src/main.ts"], "include":["src/**/*.d.ts"] } '); zip.file(folder+"src/index.html"," "+slugTitle(pn)+" "); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig) .catch(err => console.error(err)); "); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; } "); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = '"+pn+"'; } "); zip.file(folder+"src/app/app.component.html","

"+slugTitle(pn)+"

Built with PantheraHive BOS

"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1} "); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] }; "); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router'; export const routes: Routes = []; "); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install ng serve # or: npm start ``` ## Build ```bash ng build ``` Open in VS Code with Angular Language Service extension. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local .angular/ "); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join(" "):"# add dependencies here "; zip.file(folder+"main.py",src||"# "+title+" # Generated by PantheraHive BOS print(title+" loaded") "); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` ## Run ```bash python main.py ``` "); zip.file(folder+".gitignore",".venv/ __pycache__/ *.pyc .env .DS_Store "); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+" "; zip.file(folder+"package.json",pkgJson); var fallback="const express=require("express"); const app=express(); app.use(express.json()); app.get("/",(req,res)=>{ res.json({message:""+title+" API"}); }); const PORT=process.env.PORT||3000; app.listen(PORT,()=>console.log("Server on port "+PORT)); "; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000 "); zip.file(folder+".gitignore","node_modules/ .env .DS_Store "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash npm install ``` ## Run ```bash npm run dev ``` "); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:" "+title+" "+code+" "; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */ *{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e} "); zip.file(folder+"script.js","/* "+title+" — scripts */ "); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Open Double-click `index.html` in your browser. Or serve locally: ```bash npx serve . # or python3 -m http.server 3000 ``` "); zip.file(folder+".gitignore",".DS_Store node_modules/ .env "); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/**(.+?)**/g,"$1"); hc=hc.replace(/ {2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. Files: - "+app+".md (Markdown) - "+app+".html (styled HTML) "); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); }function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}