Notification System
Run ID: 69cc780d3e7fb09ff16a22962026-04-01Development
PantheraHive BOS
BOS Dashboard

Notification System: Core Code Generation (Step 2 of 3)

This deliverable provides the foundational, production-ready code for your Notification System. This step focuses on the core logic for defining, triggering, and dispatching various types of notifications (Email, SMS, In-App, Push Notifications), along with a robust architecture for handling user preferences and asynchronous processing.


1. Project Overview

This section delivers the core Python code for a flexible and scalable Notification System. The system is designed to allow easy integration of various notification channels, manage notification templates, respect user preferences, and process notifications asynchronously for improved performance and reliability.

Key Features Implemented:


2. System Architecture & Technology Stack

The proposed architecture is designed for modularity, scalability, and ease of maintenance.

High-Level Architecture:

text • 1,464 chars
notification_system/
├── app/
│   ├── __init__.py
│   ├── main.py                     # FastAPI application entry point
│   ├── api/
│   │   └── endpoints.py            # API routes for triggering notifications
│   ├── core/
│   │   ├── config.py               # Application configuration
│   │   ├── models.py               # Pydantic models for data validation
│   │   ├── db_models.py            # Conceptual database models (SQLAlchemy example)
│   │   └── exceptions.py           # Custom exceptions
│   ├── services/
│   │   ├── notification_service.py # Core logic for managing and dispatching notifications
│   │   ├── email_sender.py         # Logic for sending emails
│   │   ├── sms_sender.py           # Logic for sending SMS (placeholder)
│   │   ├── push_sender.py          # Logic for sending Push Notifications (placeholder)
│   │   └── inapp_sender.py         # Logic for sending In-App Notifications (placeholder)
│   ├── worker/
│   │   └── notification_worker.py  # Background worker to process the notification queue
│   └── templates/
│       └── email/
│           ├── welcome.html
│           └── password_reset.html
├── .env                            # Environment variables
├── requirements.txt                # Project dependencies
├── run_api.sh                      # Script to run the FastAPI app
├── run_worker.sh                   # Script to run the notification worker
└── README.md                       # Project documentation
Sandboxed live preview

Comprehensive Study Plan: Understanding and Designing Notification Systems

This document outlines a detailed study plan designed to provide a comprehensive understanding of Notification Systems, from fundamental concepts to advanced architectural considerations. This plan is tailored for professionals seeking to gain the expertise necessary to design, implement, or manage robust, scalable, and reliable notification platforms.


Introduction: The Importance of Notification Systems

Notification systems are critical components of modern applications, facilitating timely and relevant communication between systems and users. They encompass a wide array of channels (email, SMS, push notifications, in-app messages, webhooks) and require sophisticated architectural designs to ensure reliability, scalability, security, and user experience. This study plan will equip you with the knowledge to navigate the complexities of building such systems.


1. Learning Objectives

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

  • Define and Differentiate: Understand the various types of notifications (transactional, promotional, system alerts) and their associated communication channels (email, SMS, push, in-app, webhooks).
  • Identify Core Components: Recognize and describe the essential architectural components of a notification system, including publishers, subscribers, message queues, templating engines, rate limiters, and delivery services.
  • Design for Scalability & Reliability: Apply principles of distributed systems to design notification systems that can handle high volumes, ensure message delivery, and maintain availability under varying loads.
  • Implement Security & Privacy: Understand and integrate security best practices, including data encryption, access control, and compliance with privacy regulations (e.g., GDPR, CCPA).
  • Optimize Performance & Cost: Evaluate and select appropriate technologies and strategies for efficient message processing, delivery, and cost management.
  • Monitor & Troubleshoot: Develop strategies for monitoring notification delivery, identifying failures, and implementing robust retry mechanisms and alerting.
  • Evaluate Third-Party Services: Critically assess and integrate external notification service providers (e.g., Twilio, SendGrid, Firebase Cloud Messaging).
  • Articulate Trade-offs: Discuss the pros and cons of different architectural choices and technology selections in the context of specific business requirements.
  • Propose a High-Level Architecture: Sketch and explain a high-level architectural design for a notification system tailored to a given set of requirements.

2. Weekly Schedule

This study plan is structured over 5 weeks, with an estimated commitment of 8-12 hours per week.

Week 1: Fundamentals and Core Concepts

  • Focus: Introduction to notification systems, types of notifications, communication channels, and basic system components.
  • Topics:

* What are notification systems? Use cases and business value.

* Types of notifications: transactional, marketing, system alerts, real-time updates.

* Communication channels: email, SMS, push notifications (mobile/web), in-app, webhooks, voice.

* Basic architecture overview: producer-consumer model, message brokers.

* Key considerations: latency, delivery guarantees, personalization, user preferences.

  • Activities: Read introductory articles, watch overview videos, begin exploring different channel providers.

Week 2: Architectural Components and Message Handling

  • Focus: Deep dive into the core building blocks and message flow within a notification system.
  • Topics:

* Publishers/Producers: Application services generating notifications.

* Message Queues/Brokers: Kafka, RabbitMQ, AWS SQS/SNS, Google Pub/Sub, Azure Service Bus. Their role, guarantees, and trade-offs.

* Consumers/Workers: Services responsible for processing messages from queues.

* Templating Engines: Handle dynamic content and personalization (e.g., Handlebars, Jinja).

* User Preference Management: Storing and applying user notification settings.

* Notification Dispatchers/Gateways: Services responsible for sending notifications via specific channels.

  • Activities: Study message queue concepts, explore templating libraries, understand data models for user preferences.

Week 3: Scalability, Reliability, and Performance

  • Focus: Designing for high throughput, fault tolerance, and efficient operation.
  • Topics:

* Scalability Patterns: Horizontal scaling of producers, consumers, and dispatchers.

* Reliability & Durability: Message persistence, acknowledgments, retry mechanisms, dead-letter queues (DLQs), idempotency.

* Rate Limiting: Protecting downstream services and complying with provider limits.

* Throttling & Backpressure: Managing load and preventing system overload.

* Concurrency: Handling multiple notifications simultaneously.

* Performance Optimization: Asynchronous processing, batching, connection pooling.

* Disaster Recovery: Strategies for system resilience.

  • Activities: Analyze case studies of large-scale notification systems, compare retry strategies, discuss trade-offs between immediate delivery and batching.

Week 4: Security, Monitoring, and Advanced Features

  • Focus: Securing the system, ensuring visibility, and exploring advanced capabilities.
  • Topics:

* Security: Data encryption (in-transit, at-rest), authentication/authorization, API key management, sensitive data handling.

* Privacy & Compliance: GDPR, CCPA, PII handling.

* Monitoring & Alerting: Metrics (delivery rates, latency, errors), logging, dashboards, anomaly detection.

* Analytics: Tracking user engagement, open rates, click-through rates.

* A/B Testing: Optimizing notification content and timing.

* Internationalization (i18n) & Localization (l10n): Supporting multiple languages and regions.

* Webhooks: Implementing outbound webhooks for system-to-system notifications.

  • Activities: Design a monitoring dashboard, identify potential security vulnerabilities, research privacy regulations.

Week 5: Real-world Applications, Case Studies, and Design Patterns

  • Focus: Consolidating knowledge through practical application and understanding industry best practices.
  • Topics:

* Case Studies: Analyze the architectures of major notification systems (e.g., Netflix, Uber, LinkedIn, AWS SNS/SQS).

* Third-Party Integrations: Evaluating and working with external email, SMS, and push notification providers.

* Event-Driven Architecture: How notification systems fit into broader event-driven patterns.

* Microservices vs. Monolith: Designing notification services within different architectural styles.

* Emerging Trends: AI/ML for personalization, conversational notifications.

* Design Patterns: Command pattern, Observer pattern, Publisher-Subscriber pattern in the context of notifications.

  • Activities: Participate in a system design exercise for a hypothetical notification system, compare and contrast different real-world architectures.

3. Recommended Resources

  • Books:

* "Designing Data-Intensive Applications" by Martin Kleppmann (Chapters on distributed systems, messaging, reliability).

* "System Design Interview – An Insider's Guide" by Alex Xu (Look for chapters on notification or messaging systems).

  • Online Courses:

* Coursera/Udemy/Pluralsight: Search for "System Design," "Distributed Systems," "Kafka," "RabbitMQ," "Cloud Messaging Services."

* Educative.io: "Grokking the System Design Interview" (often includes notification system examples).

  • Engineering Blogs:

* Netflix TechBlog

* Uber Engineering Blog

* LinkedIn Engineering Blog

* AWS, Google Cloud, Azure Blogs (for specific service deep-dives like SNS, SQS, Pub/Sub, Event Hubs).

* Twilio, SendGrid, Firebase Blogs (for channel-specific best practices).

  • Documentation:

* Apache Kafka Documentation

* RabbitMQ Documentation

* AWS SNS/SQS/Pinpoint Documentation

* Google Cloud Pub/Sub/Firebase Cloud Messaging Documentation

* Azure Event Hubs/Service Bus Documentation

  • Videos:

* YouTube channels like "System Design Interview," "Gaurav Sen" for system design walkthroughs.

* Conference talks (e.g., AWS re:Invent, Google Cloud Next, Kafka Summit) on messaging and notification systems.


4. Milestones

  • End of Week 1: Ability to articulate the different types of notifications and their primary use cases, along with the basic components of a notification flow.
  • End of Week 2: Solid understanding of message queues and their role in decoupling and asynchronous processing within a notification system.
  • End of Week 3: Capability to discuss key considerations for scaling, ensuring reliability, and managing performance of a notification system.
  • End of Week 4: Awareness of security and privacy implications, and the ability to propose monitoring strategies for notification delivery.
  • End of Week 5: Proficiency in analyzing real-world notification system architectures and proposing a high-level design for new requirements.

5. Assessment Strategies

  • Self-Quizzes & Flashcards: Regularly test your understanding of key terms, concepts, and architectural patterns.
  • Design Exercises: Practice sketching high-level notification system architectures for various scenarios (e.g., an e-commerce order notification system, a social media feed update system).
  • Peer Discussions: Engage with colleagues or mentors to discuss design choices, trade-offs, and solutions to hypothetical problems.
  • Case Study Analysis: Choose an existing large-scale application (e.g., Twitter, Amazon) and try to infer or research how their notification system might be designed, identifying strengths and weaknesses.
  • Documentation Review: Critically read the documentation for various message brokers or cloud notification services, focusing on their guarantees, limitations, and use cases.
  • Presentation/Whiteboard Session: Prepare and deliver a brief presentation or whiteboard session on a specific aspect of notification system design (e.g., "Designing a Push Notification System for Mobile").

This detailed study plan provides a structured path to mastering the intricacies of notification systems. By diligently following this plan, you will build a strong foundation, enabling you to confidently approach the architectural planning phase for any notification system project.

python

app/core/db_models.py

This file provides conceptual SQLAlchemy models.

In a real application, you would configure an actual database

and use these models with an ORM like SQLAlchemy.

from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, JSON

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy import create_engine

from sqlalchemy.orm import sessionmaker

import datetime

Base = declarative_base()

class DBNotificationTemplate(Base):

__tablename__ = "notification_templates"

id = Column(Integer, primary_key=True, index=True)

type = Column(String, index=True, nullable=False)

channel = Column(String, index=True, nullable=False)

subject_template = Column(Text, nullable

gemini Output

This document outlines the comprehensive "Notification System" solution, designed to enhance user engagement, streamline communication, and provide a robust, scalable platform for all your notification needs. This deliverable summarizes the proposed system's architecture, key features, benefits, and a clear roadmap for implementation.


Notification System: Comprehensive Solution Deliverable

1. Executive Summary

This document presents a detailed proposal for a robust, scalable, and highly configurable Notification System. The primary goal is to centralize and optimize all outbound communications to users, ensuring timely, relevant, and personalized delivery across multiple channels. By implementing this system, your organization will achieve significant improvements in user engagement, operational efficiency, and overall user experience, while providing a foundation for future growth and advanced communication strategies.

2. System Overview and Objectives

The Notification System is an independent, microservice-based platform designed to manage the lifecycle of user notifications. It abstracts the complexity of various communication channels, allowing internal teams to trigger notifications easily and consistently.

Core Objectives:

  • Centralized Control: Provide a single point of truth for all notification logic and delivery.
  • Multi-Channel Delivery: Support seamless communication across email, SMS, push notifications, in-app messages, and potentially more.
  • Personalization & Context: Deliver highly relevant messages based on user data and real-time context.
  • Scalability & Reliability: Ensure high availability and performance even under heavy load.
  • Operational Efficiency: Reduce development effort for new notification types and simplify management.
  • Analytics & Insights: Provide data on notification performance to drive continuous improvement.
  • User Preference Management: Empower users to control their notification experience.

3. High-Level Technical Architecture

The proposed Notification System follows a modular, event-driven architecture to ensure scalability, resilience, and maintainability.

3.1. Core Components

  • API Gateway: Serves as the entry point for all internal services to request notifications. Handles authentication, authorization, and rate limiting.
  • Notification Request Service: Receives notification requests, validates them, enriches data, and publishes messages to the Message Queue.
  • Message Queue (e.g., Kafka, RabbitMQ): Acts as a buffer and communication backbone, decoupling the request service from the delivery services. Ensures reliable message delivery and supports asynchronous processing.
  • Notification Processing Service: Consumes messages from the queue, applies templating, personalization logic, and determines the appropriate delivery channel(s) based on rules and user preferences.
  • Channel-Specific Delivery Services:

* Email Service: Integrates with email providers (e.g., SendGrid, Mailgun).

* SMS Service: Integrates with SMS gateways (e.g., Twilio, Nexmo).

* Push Notification Service: Integrates with mobile push providers (e.g., Firebase Cloud Messaging, Apple Push Notification Service).

* In-App Notification Service: Delivers messages directly to user interfaces within the application.

  • Template Management Service: Stores and manages notification templates (e.g., Handlebars, Jinja2), allowing for dynamic content and easy updates without code changes.
  • User Preference Service: Stores and retrieves user-defined notification preferences (e.g., preferred channels, opt-ins/outs for specific notification types).
  • Database (e.g., PostgreSQL, MongoDB): Stores notification logs, templates, user preferences, and configuration data.
  • Monitoring & Analytics Service: Collects metrics, logs, and delivery statuses for reporting and system health checks.

3.2. Data Flow (Simplified)

  1. Trigger: An internal service (e.g., Order Service, User Management Service) makes an API call to the Notification System's API Gateway to request a notification.
  2. Request Processing: The Notification Request Service validates the request, enriches it with necessary data (e.g., user details from a User Service), and publishes a notification event to the Message Queue.
  3. Asynchronous Processing: The Notification Processing Service consumes the event from the queue.
  4. Personalization & Routing: It fetches the relevant template from the Template Management Service, applies personalization data, and consults the User Preference Service to determine the user's preferred channels and opt-in status.
  5. Channel Delivery: The Notification Processing Service then routes the prepared message to the appropriate Channel-Specific Delivery Service(s) (e.g., Email Service, SMS Service).
  6. External Delivery: The Channel-Specific Delivery Service integrates with the external provider to send the notification.
  7. Logging & Analytics: All steps, including request, processing, and delivery status, are logged to the Database and fed into the Monitoring & Analytics Service for reporting.

4. Key Capabilities and Features

  • Multi-Channel Delivery:

* Email (HTML/Plain Text)

* SMS

* Push Notifications (iOS, Android)

* In-App Notifications / Message Center

* Web Push Notifications (Optional)

  • Dynamic Templating:

* Support for rich, customizable templates with placeholders for dynamic content.

* Version control for templates.

* WYSIWYG editor for non-technical users (future enhancement).

  • Personalization Engine:

* Inject user-specific data (name, order details, event data) into templates.

* Conditional logic within templates for highly tailored messages.

  • User Preference Management:

* API and UI components for users to manage their notification subscriptions (opt-in/out per channel, per notification type).

* Global unsubscribe options.

  • Scheduling & Throttling:

* Schedule notifications for future delivery.

* Throttle notification rates to prevent spamming users.

* "Do Not Disturb" windows based on user preferences or global settings.

  • Prioritization:

* Assign priority levels (e.g., critical, important, marketing) to notifications.

* Prioritize delivery for high-priority messages.

  • Retry Mechanisms & Fallbacks:

* Automatic retries for transient delivery failures.

* Configurable fallback channels (e.g., if push fails, send SMS).

  • Delivery Status Tracking:

* Real-time tracking of notification delivery status (sent, delivered, opened, clicked, failed).

* Webhooks for external systems to receive delivery updates.

  • Analytics & Reporting:

* Dashboards for monitoring notification performance (delivery rates, open rates, click-through rates).

* Insights into user engagement and preferred channels.

  • Auditing & Logging:

* Comprehensive logs for every notification request and delivery attempt for debugging and compliance.

  • Internationalization (i18n):

* Support for multiple languages and localized content based on user preferences.

  • Security:

* Data encryption in transit and at rest.

* Access control for notification APIs.

* Compliance with data privacy regulations (e.g., GDPR, CCPA).

5. Benefits to Your Organization

  • Enhanced User Experience & Engagement: Deliver timely, relevant, and personalized communications that users value, leading to higher engagement and satisfaction.
  • Increased Operational Efficiency:

* Decouple notification logic from core business services, reducing complexity.

* Empower marketing and product teams to manage notification content and rules without developer intervention.

* Faster time-to-market for new notification types.

  • Reduced Development Overhead: Developers can simply trigger a notification via API, rather than integrating with multiple external communication providers.
  • Scalability & Future-Proofing: The modular architecture supports easy integration of new channels and scales horizontally to meet growing demands.
  • Data-Driven Decision Making: Gain valuable insights into communication effectiveness, allowing for continuous optimization of strategies.
  • Improved Reliability & Resilience: Robust retry mechanisms and queue-based processing ensure notifications are delivered even during peak loads or temporary failures.
  • Compliance & Control: Centralized management facilitates adherence to communication policies and privacy regulations.

6. Implementation Roadmap (Next Steps)

This roadmap outlines the typical phases for deploying a comprehensive Notification System.

Phase 1: Discovery & Detailed Requirements (Estimated: 2-4 Weeks)

  • Workshops: Conduct sessions with key stakeholders (Product, Engineering, Marketing, Support) to gather detailed requirements.
  • Use Case Definition: Identify all critical notification types, their triggers, content, channels, and priority levels.
  • Integration Points: Map out all internal services that will interact with the Notification System.
  • Data Mapping: Define data required for personalization and how it will be sourced.
  • Technical Deep Dive: Review existing infrastructure, security policies, and preferred technologies.
  • Deliverable: Detailed Requirements Document, API Specification Draft.

Phase 2: System Design & Prototyping (Estimated: 4-6 Weeks)

  • Architectural Design: Finalize the detailed technical architecture, component choices, and infrastructure requirements.
  • Database Schema: Design data models for notifications, templates, user preferences, and logs.
  • API Design: Refine and finalize the external-facing API for triggering notifications.
  • Proof of Concept (PoC): Develop a basic PoC for a critical notification type across 1-2 channels to validate core components and integrations.
  • Deliverable: Detailed Design Document, API Documentation, PoC Demonstration.

Phase 3: Development & Integration (Estimated: 12-20 Weeks)

  • Core Services Development: Build the Notification Request, Processing, Template, and User Preference Services.
  • Channel Integrations: Develop and integrate with chosen Email, SMS, Push Notification providers.
  • Database Implementation: Set up and configure the primary database.
  • Internal Service Integration: Work with internal teams to integrate their services with the new Notification System API.
  • Monitoring & Logging: Implement comprehensive monitoring, alerting, and logging solutions.
  • Deliverable: Deployed Development Environment with Core Functionality.

Phase 4: Testing & Deployment (Estimated: 4-8 Weeks)

  • Unit & Integration Testing: Thorough testing of all individual components and their interactions.
  • Performance & Load Testing: Ensure the system can handle anticipated load and scale.
  • Security Testing: Conduct vulnerability assessments and penetration testing.
  • User Acceptance Testing (UAT): Business users validate the system against defined use cases.
  • Staging & Production Deployment: Deploy the system to staging and then to the production environment.
  • Deliverable: Production-Ready Notification System.

Phase 5: Monitoring & Optimization (Ongoing)

  • Continuous Monitoring: Actively monitor system health, performance, and notification delivery rates.
  • Feedback Loop: Collect user and stakeholder feedback for continuous improvement.
  • Feature Enhancements: Plan and implement new features (e.g., A/B testing, advanced analytics, new channels).
  • Deliverable: Regular Performance Reports, Iterative System Enhancements.

7. Security and Compliance Considerations

Security and data privacy are paramount. The Notification System will be designed with the following in mind:

  • Data Encryption: All sensitive data (e.g., user contact information) will be encrypted in transit (TLS/SSL) and at rest.
  • Access Control: Strict role-based access control (RBAC) will be implemented for all system APIs and management interfaces.
  • Audit Trails: Comprehensive audit logs will track all notification requests, modifications, and delivery attempts.
  • Compliance: The system will adhere to relevant data privacy regulations (e.g., GDPR, CCPA) by providing mechanisms for consent management and data subject rights.
  • Vulnerability Management: Regular security audits and penetration testing will be conducted.

8. Conclusion and Call to Action

The proposed Notification System represents a strategic investment in your organization's communication infrastructure. It will empower you to deliver exceptional user experiences, drive engagement, and operate with greater efficiency.

We are confident that this solution will meet and exceed your expectations. We recommend scheduling a follow-up session to discuss this proposal in detail, answer any questions you may have, and begin the exciting journey of implementing this transformative system.

Next Action: Please contact your PantheraHive representative to schedule a detailed review meeting and initiate Phase 1: Discovery & Detailed Requirements.

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