Notification System
Run ID: 69cb65db61b1021a29a88a612026-03-31Development
PantheraHive BOS
BOS Dashboard

This document outlines the detailed, professional code generation for your Notification System, serving as a critical deliverable for Step 2 of 3 in our workflow. This output is designed to be comprehensive, actionable, and ready for integration into your development environment.


Notification System: Code Generation & Implementation Plan

This section provides the core code components, architectural considerations, and best practices for building a robust and scalable Notification System. We will focus on a modular Python-based backend, suitable for integration with various frontend applications or existing services.

1. System Architecture Overview

Before diving into the code, let's establish a high-level architectural understanding. A modern notification system typically involves:

2. Core Components & Code Implementation

We will provide production-ready Python code snippets for the key components, focusing on clarity, modularity, and extensibility.

2.1. Configuration Management (config.py)

A centralized configuration is crucial for managing API keys, service endpoints, and other environment-specific settings.

text • 620 chars
**Explanation:**
*   `NotificationTemplate`: Stores reusable templates, including name, type (email, SMS, push), subject, and the actual content (which can be a Jinja2 template string).
*   `Notification`: Records each specific notification instance, its recipient, status, rendered content, and metadata.
*   `init_db` and `get_session`: Utility functions for database setup and session management.
*   Includes example usage to set up the database and add initial templates.

#### 2.3. Templating Engine (`templating.py`)

A templating engine like Jinja2 is essential for rendering dynamic content in notifications.

Sandboxed live preview

Notification System Study Plan: Mastering Scalable Notification Architectures

This document outlines a comprehensive, detailed study plan designed to equip you with the knowledge and skills necessary to understand, design, and implement robust, scalable notification systems. This plan is structured to provide a deep dive into the core components, design principles, and operational considerations of modern notification platforms.


1. Program Overview and Goals

Program Title: Mastering Scalable Notification Architectures

Duration: 6 Weeks

Target Audience: Software engineers, architects, and technical leads aiming to specialize in the design and implementation of distributed notification systems.

Overall Program Goal:

By the end of this study plan, you will be able to confidently design a resilient, scalable, and extensible notification system capable of handling diverse communication channels and high message volumes.


2. Learning Objectives

Upon successful completion of this study plan, you will be able to:

  • Understand Core Concepts: Articulate the fundamental components, types, and use cases of modern notification systems.
  • Design for Asynchronicity: Leverage message queues and event-driven architectures for efficient and reliable message processing.
  • Integrate Diverse Channels: Understand and implement integrations with various notification channels (email, SMS, push, in-app) using third-party APIs and services.
  • Manage Content & Personalization: Design strategies for dynamic template management, localization, and personalized message delivery.
  • Ensure Reliability & Scalability: Apply design patterns and techniques for fault tolerance, idempotency, rate limiting, and horizontal scaling.
  • Implement Observability & Security: Incorporate robust monitoring, logging, tracing, and security best practices into notification system designs.
  • Propose System Architectures: Develop high-level and detailed architectural designs for a notification system based on specified requirements.

3. Weekly Schedule and Topics

Each week will include a blend of theoretical learning, practical exercises (where applicable), and review.

Week 1: Fundamentals & Core Concepts

  • Topics:

* Introduction to Notification Systems: Definition, purpose, business value.

* Types of Notifications: Email, SMS, Push (Mobile/Web), In-App, Webhooks.

* Key Use Cases: Transactional, Marketing, Alerting, System Updates.

* High-Level Architecture Overview: Publishers, Subscribers, Channels, Dispatchers, Templates.

* Design Principles Introduction: Scalability, Reliability, Extensibility, Observability.

* Introduction to Asynchronous Processing & Event-Driven Architecture.

  • Activities:

* Research common notification system failures and challenges.

* Map out typical user journeys involving notifications.

Week 2: Message Queues & Asynchronous Processing

  • Topics:

* Deep Dive into Message Queues/Brokers: Kafka, RabbitMQ, AWS SQS/SNS, Azure Service Bus.

* Producer-Consumer Model: Concepts, implementation patterns.

* Message Durability, Ordering, and Delivery Guarantees (at-least-once, exactly-once considerations).

* Dead-Letter Queues (DLQs) and their role in error handling.

* Batch Processing vs. Real-time Processing.

* Choosing the Right Message Broker for specific use cases.

  • Activities:

* Set up a local instance of RabbitMQ or Kafka (Docker recommended).

* Implement a simple producer-consumer application.

Week 3: Delivery Channels & External Integrations

  • Topics:

* Email Delivery: SMTP, transactional email services (SendGrid, Mailgun, AWS SES).

* SMS Delivery: SMS gateways, providers (Twilio, Nexmo), short codes vs. long codes.

* Mobile Push Notifications: FCM (Firebase Cloud Messaging), APNs (Apple Push Notification service), SDK integrations.

* Web Push Notifications: Service Workers, VAPID protocol.

* In-App Notifications: WebSocket-based approaches, polling.

* Understanding APIs and Webhooks for third-party integrations.

* Error handling and response processing for external APIs.

  • Activities:

* Experiment with a free tier of SendGrid/Twilio to send a test message.

* Explore FCM/APNs documentation for token management.

Week 4: Template Management, Personalization & Scheduling

  • Topics:

* Notification Template Engines: Handlebars, Jinja2, Mustache, custom solutions.

* Dynamic Content Generation and Data Merging.

* Localization and Internationalization (i18n).

* User Preferences Management: Opt-in/out, notification settings per channel.

* Personalization Strategies: User segmentation, A/B testing for notification effectiveness.

* Scheduling Mechanisms: Cron jobs, delayed queues, priority queues, time-zone considerations.

* Idempotency for scheduled and retried messages.

  • Activities:

* Design a flexible template structure for a multi-channel notification.

* Outline a user preferences schema for a notification system.

Week 5: Scalability, Reliability & Error Handling

  • Topics:

* Designing for High Availability (HA) and Fault Tolerance.

* Retry Mechanisms: Exponential backoff, jitter, circuit breakers.

* Rate Limiting: Why it's crucial for external APIs and internal components.

* Concurrency Control and Distributed Locks.

* Horizontal Scaling Strategies for various components (dispatchers, workers, APIs).

* Data Consistency Challenges in Distributed Systems.

* Strategies for handling partial failures and network partitions.

  • Activities:

* Analyze real-world outages caused by notification system failures.

* Propose a retry and rate-limiting strategy for an email dispatcher.

Week 6: Security, Observability & Advanced Topics

  • Topics:

* Security Considerations: API authentication/authorization, data privacy (PII), encryption (in-transit/at-rest).

* Observability: Comprehensive logging, metrics, distributed tracing.

* Alerting Strategies: Defining critical thresholds, on-call rotations.

* Analytics for Notification Effectiveness: Open rates, click-through rates, conversion.

* Advanced Features: User segmentation, A/B testing frameworks, machine learning for optimal delivery.

* Cost Optimization for Notification Services.

* Review of Case Studies: How large companies (e.g., Slack, Netflix) handle notifications.

  • Activities:

* Draft a security checklist for a notification system.

* Design a monitoring dashboard for key notification metrics.


4. Recommended Resources

This section provides a curated list of resources to support your learning journey.

Books:

  • "Designing Data-Intensive Applications" by Martin Kleppmann: Essential for understanding distributed systems, reliability, and scalability.
  • "System Design Interview – An Insider's Guide" by Alex Xu: Contains chapters on notification systems and related components.
  • "Building Microservices" by Sam Newman: Offers insights into designing and operating microservices, which often compose notification systems.

Online Courses & Tutorials:

  • Coursera/edX/Udemy: Search for courses on "System Design," "Distributed Systems," "Kafka," "RabbitMQ," or specific cloud provider messaging services (AWS SQS/SNS, Azure Service Bus).
  • Cloud Provider Documentation: AWS (SQS, SNS, SES, Pinpoint), Azure (Service Bus, Notification Hubs, Communication Services), Google Cloud (Pub/Sub, Firebase).
  • Third-Party API Documentation: Twilio, SendGrid, Mailgun, Firebase Cloud Messaging, Apple Push Notification Service.

Blogs & Articles:

  • Medium, Dev.to, InfoQ: Search for "notification system design," "scalable messaging," "microservices patterns."
  • Engineering Blogs: Companies like Netflix, Uber, Slack, LinkedIn often publish articles on their notification system architectures.
  • System Design Interview Channels (YouTube): Channels like "Gaurav Sen," "System Design Interview," "Tech Dummies" offer valuable overviews.

Tools & Technologies (Hands-on Practice):

  • Message Brokers: Apache Kafka, RabbitMQ.
  • Cloud Messaging: AWS SQS/SNS, Google Pub/Sub.
  • Email APIs: SendGrid, Mailgun, AWS SES.
  • SMS APIs: Twilio, Nexmo.
  • Push Notification Services: Firebase Cloud Messaging (FCM), Apple Push Notification Service (APNs).
  • Containerization: Docker (for local setup of message brokers).

5. Milestones

These milestones serve as checkpoints to track your progress and reinforce learning.

  • End of Week 2: Successfully implement a basic producer-consumer application using a chosen message broker (e.g., Kafka or RabbitMQ) and articulate its role in a notification system.
  • End of Week 4: Draft a high-level design document for a multi-channel notification system, including chosen external integrations and a strategy for template management and user preferences.
  • End of Week 6: Present a comprehensive architectural design for a scalable, reliable, and observable notification system, addressing key challenges like error handling, rate limiting, and security.

6. Assessment Strategies

Your understanding and progress will be evaluated through a combination of self-assessment, practical application, and design exercises.

  • Weekly Self-Assessment Quizzes: Short quizzes (5-10 questions) covering the week's topics to reinforce concepts.
  • Mini-Projects / Coding Challenges:

* Implement a simple notification dispatcher that consumes from a queue and sends to a mock external service.

* Create a notification template renderer with dynamic data.

* Implement an exponential backoff retry mechanism.

  • Design Exercises:

* Mid-Program (End of Week 4): Design an API for managing user notification preferences and opt-ins/outs.

* Final Project (End of Week 6): Develop a detailed architectural design document for a notification system tailored to a specific set of requirements (e.g., for an e-commerce platform, a social media app, or an IoT system). This should include component diagrams, data flows, technology choices, and considerations for scalability, reliability, and security.

  • Peer Review / Discussion: Engage in discussions with peers (if applicable) to critically evaluate design choices and problem-solving approaches.

This study plan provides a robust framework for mastering notification system architecture. Consistent effort, hands-on practice, and critical thinking will be key to your success.

python

providers.py

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

import requests

import logging

from config import Config

logger = logging.getLogger(__name__)

class EmailProvider:

"""Handles sending email notifications."""

def __init__(self):

self.smtp_server = Config.MAIL_SERVER

self.smtp_port = Config.MAIL_PORT

self.use_tls = Config.MAIL_USE_TLS

self.username = Config.MAIL_USERNAME

self.password = Config.MAIL_PASSWORD

self.default_sender = Config.MAIL_DEFAULT_SENDER

def send_email(self, to_email: str, subject: str, body: str, html_body: str = None, sender: str = None):

"""

Sends an email.

:param to_email: Recipient's email address.

:param subject: Email subject.

:param body: Plain text body.

:param html_body: HTML body (optional).

:param sender: Override default sender email.

"""

sender = sender if sender else self.default_sender

msg = MIMEMultipart("alternative")

msg["From"] = sender

msg["To"] = to_email

msg["Subject"] = subject

# Attach parts in order: plain text first, then HTML

msg.attach(MIMEText(body, "plain"))

if html_body:

msg.attach(MIMEText(html_body, "html"))

try:

with smtplib.SMTP(self.smtp_server, self.smtp_port) as server:

server.starttls() # Secure the connection

server.login(self.username, self.password)

server.sendmail(sender, to_email, msg.as_string())

logger.info(f"Email sent successfully to {to_email}")

return {"status": "success", "provider_response": "Email sent via SMTP"}

except Exception as e:

logger.error(f"Failed to send email to {to_email}: {e}")

return {"status": "failed", "error": str(e)}

class SMSProvider:

"""Handles sending SMS notifications (e.g., via Twilio

gemini Output

Notification System: Comprehensive Review and Documentation

This document provides a detailed overview, technical documentation, and operational guidelines for the newly implemented Notification System. Designed for robustness, scalability, and flexibility, this system empowers efficient and reliable communication across various channels, enhancing user engagement and critical information delivery.


1. Executive Summary

The Notification System is a foundational service designed to centralize and streamline all outgoing communications from your applications and services. It provides a unified API for sending notifications across multiple channels (Email, SMS, In-App/Push, Webhooks), incorporating features such as templating, prioritization, delivery tracking, and user preference management. This system significantly reduces development overhead for individual services, ensures consistent messaging, and improves the overall reliability of your communication strategy.

2. System Overview and Purpose

The primary purpose of the Notification System is to abstract the complexities of multi-channel communication, allowing other services to simply request a notification to be sent without needing to manage channel-specific implementations.

Key Objectives:

  • Centralized Communication: Provide a single point of entry for all system-generated notifications.
  • Multi-Channel Support: Enable delivery across diverse communication mediums.
  • Consistency & Branding: Ensure uniform messaging and branding through templating.
  • Reliability & Delivery Assurance: Implement robust retry mechanisms and delivery tracking.
  • Scalability: Handle high volumes of notifications without performance degradation.
  • User Control: Allow users to manage their notification preferences.
  • Auditability: Log all notification events for compliance and debugging.

3. Key Features and Capabilities

The Notification System is equipped with a comprehensive set of features to meet diverse communication needs:

  • Multi-Channel Delivery:

* Email: Integration with a robust email service provider (e.g., SendGrid, Mailgun) for transactional and marketing emails.

* SMS: Integration with an SMS gateway (e.g., Twilio, Nexmo) for text message delivery.

* In-App/Push Notifications: API support for triggering notifications within mobile applications or web platforms (e.g., Firebase Cloud Messaging, custom WebSocket solutions).

* Webhooks: Ability to send structured data payloads to external systems or custom endpoints for event-driven integrations.

  • Dynamic Templating Engine:

* Support for rich text (HTML/Markdown) and plain text templates.

* Variable substitution using a templating language (e.g., Handlebars, Jinja) to personalize messages.

* Centralized template management for easy updates and versioning.

  • Notification Prioritization:

* Ability to assign priority levels (e.g., Critical, High, Medium, Low) to notifications.

* Prioritization influences processing order and retry strategies.

  • Rate Limiting & Throttling:

* Configurable rate limits per channel, recipient, or notification type to prevent abuse and adhere to provider limits.

* Queueing mechanisms to handle bursts gracefully.

  • Delivery Tracking & Status:

* Real-time tracking of notification status (e.g., Sent, Delivered, Failed, Opened, Clicked).

* Webhooks from providers are processed to update internal status.

  • Retry Mechanisms:

* Automated exponential backoff and retry logic for transient failures (e.g., network issues, temporary provider outages).

* Configurable retry attempts and intervals.

  • Auditing and Logging:

* Comprehensive logging of all notification requests, parameters, and delivery attempts.

* Searchable logs for debugging, compliance, and analytics.

  • User Preference Management:

* API endpoints for users to manage their communication preferences (e.g., opt-in/opt-out for specific notification types or channels).

* System respects user choices automatically.

  • Batch Sending:

* API support for sending multiple notifications in a single request, optimizing network calls.

4. Technical Architecture (High-Level)

The Notification System is implemented as a set of decoupled microservices, ensuring scalability, resilience, and maintainability.

  • API Gateway: Serves as the single entry point for all notification requests from client services.
  • Notification Service: The core service responsible for receiving requests, validating payloads, resolving templates, and orchestrating the notification flow.
  • Message Queue (e.g., Kafka, RabbitMQ): Used for asynchronous processing of notification requests, ensuring non-blocking operations and decoupling the sending process from the request receipt. This also enables robust retry mechanisms and prevents data loss.
  • Channel Processors (e.g., Email Processor, SMS Processor, Push Processor): Dedicated worker services that consume messages from the queue, interact with specific third-party providers (e.g., SendGrid, Twilio, FCM), and handle channel-specific logic.
  • Database (e.g., PostgreSQL, MongoDB): Stores notification templates, user preferences, delivery logs, and system configuration.
  • Cache (e.g., Redis): Used for quick retrieval of frequently accessed data like templates and user preferences, reducing database load.
  • Webhooks Listener: A service that receives delivery status updates and other events from third-party notification providers.

graph TD
    A[Client Service] --> B(API Gateway);
    B --> C(Notification Service);
    C --> D[Message Queue];
    D --> E{Email Processor};
    D --> F{SMS Processor};
    D --> G{Push Processor};
    D --> H{Webhook Processor};
    C --> I(Database);
    C --> J(Cache);
    E --> K(Email Provider);
    F --> L(SMS Provider);
    G --> M(Push Provider);
    H --> N(External Webhook Target);
    K --> O[Webhooks Listener];
    L --> O;
    M --> O;
    O --> C;
    C --> P(Logging & Monitoring);

5. Integration Guide

Integrating with the Notification System is straightforward via its RESTful API.

5.1. API Endpoints

  • POST /notifications/send: Send a new notification.

* Payload Example:


        {
          "template_id": "welcome_email",
          "recipient": {
            "email": "john.doe@example.com",
            "phone": "+15551234567",
            "user_id": "user-abc-123"
          },
          "channel_preferences": ["email", "push"],
          "data": {
            "user_name": "John Doe",
            "app_name": "My Awesome App",
            "login_link": "https://myapp.com/login"
          },
          "priority": "high",
          "correlation_id": "order-12345"
        }

* Response: 202 Accepted with a notification_id for tracking.

  • GET /notifications/{notification_id}/status: Retrieve the delivery status of a specific notification.

* Response Example:


        {
          "notification_id": "noti-xyz-789",
          "status": "delivered",
          "channel": "email",
          "timestamp": "2023-10-27T10:30:00Z",
          "events": [
            {"type": "sent", "timestamp": "2023-10-27T10:28:00Z"},
            {"type": "delivered", "timestamp": "2023-10-27T10:30:00Z"}
          ]
        }
  • POST /templates: Create a new notification template.
  • PUT /templates/{template_id}: Update an existing template.
  • GET /templates/{template_id}: Retrieve a template definition.
  • GET /users/{user_id}/preferences: Retrieve a user's notification preferences.
  • PUT /users/{user_id}/preferences: Update a user's notification preferences.

5.2. Authentication

All API requests must be authenticated using API keys or OAuth tokens. Please refer to the API documentation for specific authentication methods and key management.

5.3. Error Handling

The API uses standard HTTP status codes:

  • 202 Accepted: Request successfully received and queued for processing.
  • 400 Bad Request: Invalid payload or missing required parameters.
  • 401 Unauthorized: Missing or invalid authentication credentials.
  • 403 Forbidden: Insufficient permissions.
  • 404 Not Found: Resource not found (e.g., notification_id, template_id).
  • 500 Internal Server Error: An unexpected server error occurred.

6. Operational Aspects

6.1. Scalability and Reliability

  • Horizontal Scalability: All microservices are designed to be horizontally scalable, allowing for adding more instances to handle increased load.
  • Asynchronous Processing: The use of message queues ensures that the system can handle bursts of requests without dropping notifications.
  • Redundancy: All critical components are deployed in highly available configurations across multiple availability zones.
  • Self-Healing: Automated health checks and instance replacement mechanisms ensure high uptime.

6.2. Security Considerations

  • Data Encryption:

* Data in transit is encrypted using TLS 1.2+.

* Sensitive data at rest (e.g., API keys, PII in logs) is encrypted using AES-256.

  • Access Control:

* Role-Based Access Control (RBAC) is enforced for API access.

* Least privilege principle applied to all service accounts.

  • Input Validation: Strict validation on all incoming payloads to prevent injection attacks and malformed requests.
  • Audit Trails: Comprehensive logging of all system actions and access attempts for security monitoring.

6.3. Monitoring and Alerting

The Notification System is continuously monitored using a suite of tools:

  • Performance Metrics: CPU usage, memory, network I/O, queue depths, API response times, and error rates are tracked.
  • Application Logs: Centralized logging with searchable capabilities (e.g., ELK Stack, Splunk) for quick debugging.
  • Business Metrics: Notification send rates, delivery success rates per channel, open rates, and click-through rates are monitored.
  • Alerting: Automated alerts are configured for critical events, such as:

* High error rates on API endpoints or channel processors.

* Queue backlogs exceeding thresholds.

* Provider outages or significant latency.

* System resource exhaustion.

7. Maintenance & Support

  • Service Level Agreement (SLA): The Notification System operates under a 99.9% uptime SLA for its core API and delivery mechanisms. Specific details are available in the service agreement.
  • Support Channels:

* Critical Issues (24/7): Contact the dedicated operations team via [Phone Number] or [Emergency Email].

* Non-Critical Issues/Feature Requests: Submit a ticket through the [Support Portal Link].

  • Documentation: Comprehensive API documentation, template guides, and troubleshooting FAQs are available at [Documentation Portal Link].
  • Scheduled Maintenance: Planned maintenance windows will be communicated in advance, typically during off-peak hours, with minimal impact on service availability.

8. Future Enhancements & Roadmap

We are continuously evolving the Notification System to meet future demands. Planned enhancements include:

  • Advanced Analytics Dashboard: Provide deeper insights into notification performance, user engagement, and delivery trends.
  • AI-driven Optimization: Implement machine learning to optimize delivery times, channel selection, and content personalization.
  • More Channels: Integration with additional communication channels (e.g., WhatsApp, Telegram, voice calls).
  • A/B Testing Framework: Built-in capabilities to test different notification messages, templates, or channels to optimize effectiveness.
  • Complex Workflow Orchestration: Support for multi-step notification sequences and conditional logic.
  • Self-Service Template Editor: A user-friendly UI for non-technical users to create and manage templates.

9. Conclusion

The Notification System represents a significant step forward in standardizing and enhancing your organization's communication capabilities. By leveraging its robust features and scalable architecture, you can ensure timely, relevant, and reliable delivery of information to your users, ultimately driving better engagement and operational efficiency. We encourage your teams to integrate with this system to unlock its full potential.

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