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

This document outlines the implementation details for a robust and scalable Notification System, addressing core functionalities such as multi-channel delivery, asynchronous processing, and user preference management. This output serves as a direct deliverable, providing clean, well-commented, and production-ready code along with comprehensive explanations.


Notification System: Implementation Details

This section provides the detailed technical implementation for the Notification System, focusing on a Python-based backend service.

1. Project Overview

The Notification System is designed to provide a flexible and extensible platform for sending various types of notifications (e.g., email, SMS, in-app) to users. It supports:

2. Architectural Design

The system follows a modular, service-oriented architecture, making it suitable for integration into larger microservice ecosystems or as a standalone component.

High-Level Flow:

  1. An external service or a client makes an API call to /api/v1/send_notification.
  2. The Flask API receives the request and enqueues an asynchronous task to Celery.
  3. A Celery worker picks up the task.
  4. The worker consults the notification_service to fetch user details, preferences, and the relevant template.
  5. The template is rendered with provided context data.
  6. The notification_service dispatches the notification through the appropriate channel handler(s) based on user preferences and request.
  7. The status of the notification (sent, failed) is logged in the database.

3. Technology Stack

4. Core Components & Code

4.1. Project Structure

text • 962 chars
notification_system/
├── .env.example                # Example environment variables
├── app.py                      # Flask application, API endpoints
├── config.py                   # Configuration settings
├── models.py                   # SQLAlchemy database models
├── tasks.py                    # Celery asynchronous tasks
├── requirements.txt            # Python dependencies
├── services/
│   └── notification_service.py # Core notification logic
├── channels/
│   ├── __init__.py             # Makes 'channels' a Python package
│   ├── email_channel.py        # Email sending logic
│   ├── sms_channel.py          # SMS sending logic (placeholder for external API)
│   └── in_app_channel.py       # In-App/Push notification logic (placeholder)
├── templates/
│   ├── email_welcome.html      # Example email template
│   └── email_reset_password.html # Another example email template
└── README.md                   # Project setup and run instructions
Sandboxed live preview

Notification System Architecture Study Plan

This document outlines a comprehensive study plan designed to equip your team with the foundational knowledge and advanced concepts required to architect a robust, scalable, and reliable notification system. This plan is structured to provide a deep dive into the various components, technologies, and best practices involved in designing such a critical system.


1. Introduction and Overview

A notification system is a vital component for engaging users and providing timely information across various channels. Architecting such a system requires a thorough understanding of distributed systems, message queuing, third-party integrations, scalability patterns, and operational considerations. This study plan will guide you through these essential areas, culminating in the ability to design a resilient and efficient notification architecture.


2. Learning Objectives

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

  • Understand Notification Fundamentals: Differentiate between various notification types (e.g., email, SMS, push, in-app, webhooks) and their respective use cases.
  • Master Asynchronous Processing: Grasp the importance and implementation of message queues and event streaming platforms in a notification system.
  • Evaluate Delivery Mechanisms: Understand the technical requirements and integration strategies for different notification delivery channels, including third-party APIs.
  • Design Scalable Architectures: Apply architectural patterns (e.g., microservices, fan-out) to design a notification service that is highly available, fault-tolerant, and scalable.
  • Address Cross-Cutting Concerns: Identify and implement strategies for security, observability (logging, monitoring, alerting), rate limiting, and user preference management.
  • Select Appropriate Technologies: Evaluate and choose suitable technologies (databases, message brokers, third-party services) based on system requirements.
  • Develop an Architectural Blueprint: Create a detailed high-level architecture diagram and design document for a complex notification system.

3. Weekly Schedule

This study plan is designed for a 6-week duration, assuming approximately 10-15 hours of dedicated study per week.

Week 1: Notification System Fundamentals & Core Concepts

  • Focus: Introduction to notification types, core components, and the necessity of asynchronous processing.
  • Key Topics:

* Types of notifications: Email, SMS, Mobile Push (FCM, APN), Web Push, In-App, Webhooks.

* Use cases and business requirements for each type.

* Introduction to distributed systems concepts: latency, throughput, reliability, eventual consistency.

* Overview of architectural patterns: Monolith vs. Microservices for notification systems.

* Basic API design principles for a notification service.

  • Activities: Research common notification scenarios, analyze basic system diagrams, begin exploring different notification service providers.

Week 2: Message Queues & Event Streaming

  • Focus: Deep dive into asynchronous communication patterns using message queues and event brokers.
  • Key Topics:

* Why message queues? Decoupling, buffering, load leveling, fault tolerance.

* Common message broker technologies: Apache Kafka, RabbitMQ, AWS SQS/SNS, Azure Service Bus, Google Cloud Pub/Sub.

* Concepts: Producers, Consumers, Topics/Queues, Partitions, Message Acknowledgment, Dead-Letter Queues (DLQs).

* Idempotency and retry mechanisms.

* Message payload design and serialization.

  • Activities: Compare and contrast different message brokers, diagram message flow for a notification, understand error handling strategies.

Week 3: Delivery Mechanisms & Third-Party Integrations

  • Focus: Understanding the specifics of integrating with various delivery channels and external services.
  • Key Topics:

* Email: SMTP, API-based services (SendGrid, Mailgun, AWS SES), templating engines (Handlebars, Jinja2).

* SMS: SMS gateways (Twilio, Nexmo), short codes vs. long codes, delivery reports.

* Mobile Push Notifications: FCM (Firebase Cloud Messaging) for Android, APN (Apple Push Notification service) for iOS, unified SDKs.

* In-App/Web Push: WebSockets, Server-Sent Events (SSE), service workers.

* Webhooks: Designing and consuming webhooks for event-driven notifications.

* Rate limiting and quotas for external APIs.

  • Activities: Research API documentation for specific providers, design a template management system, consider fallback mechanisms.

Week 4: System Design & Architectural Patterns

  • Focus: Integrating all components into a cohesive, scalable, and resilient architecture.
  • Key Topics:

* High-level architectural components: API Gateway, Notification Service, Template Service, User Preference Service, Delivery Services, Database.

* Database choices: SQL (user preferences, audit logs) vs. NoSQL (event storage, notification metadata).

* Scalability patterns: Horizontal scaling, load balancing, sharding.

* High Availability and Disaster Recovery strategies.

* Fan-out architecture for multiple recipients/channels.

* Handling concurrency and race conditions.

  • Activities: Sketch initial architectural diagrams, identify potential bottlenecks, discuss trade-offs between different design choices.

Week 5: Advanced Topics & Operational Concerns

  • Focus: Addressing crucial non-functional requirements and ensuring system robustness.
  • Key Topics:

* Security: Authentication and authorization for notification APIs, data encryption (in-transit, at-rest), secure credential management.

* Observability: Logging (structured logging, log aggregation), Monitoring (metrics, dashboards, alerts), Tracing (distributed tracing).

* Rate Limiting & Throttling: Implementing internal and external rate limits to prevent abuse and manage costs.

* User Preference Management: Designing a system for user opt-in/opt-out, channel preferences, and notification frequency.

* A/B Testing for notification effectiveness.

* Internationalization (i18n) and Localization (l10n) for notifications.

  • Activities: Define key metrics for a notification system, design an alerting strategy, plan for user preference storage and retrieval.

Week 6: Case Studies & Architecture Planning Workshop

  • Focus: Consolidating knowledge through real-world examples and initiating the architecture design for a specific use case.
  • Key Topics:

* Review of existing large-scale notification system architectures (e.g., Uber, Netflix, Slack).

* Identification of common challenges and solutions in production environments.

* Interactive workshop: Applying learned concepts to a hypothetical notification system requirement.

* Developing a preliminary architectural blueprint for your specific needs.

  • Activities: Analyze case studies, participate in a collaborative design session, prepare a presentation of the proposed high-level architecture.

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, databases, and message queues.
  • "System Design Interview – An insider's guide" by Alex Xu: Provides practical examples and frameworks for system design.
  • "Kafka: The Definitive Guide" by Gwen Shapira, Neha Narkhede, Todd Palino: For deep dives into Apache Kafka.

Online Courses & Platforms:

  • Educative.io: "Grokking the System Design Interview," "Grokking Modern System Design for Software Engineers & Managers."
  • Coursera/Udemy/Pluralsight: Courses on specific technologies like Kafka, RabbitMQ, AWS SQS/SNS, Azure Service Bus, etc.
  • YouTube Channels: "ByteByteGo," "System Design Interview," "Google Cloud Tech," "AWS re:Invent."

Documentation & Blogs:

  • Official Documentation: AWS SQS/SNS, Azure Service Bus, Google Cloud Pub/Sub, Apache Kafka, RabbitMQ, Twilio, SendGrid, Firebase Cloud Messaging, Apple Push Notification service.
  • Engineering Blogs: Uber Engineering, Netflix TechBlog, Slack Engineering, Medium articles on system design and specific technologies.
  • Cloud Provider Whitepapers: AWS Well-Architected Framework, Azure Architecture Center, Google Cloud Architecture Framework.

Tools & Community:

  • Excalidraw/draw.io/Lucidchart: For creating architectural diagrams.
  • GitHub: Explore open-source notification system examples or libraries.
  • Stack Overflow/Reddit (r/system_design, r/softwarearchitecture): For discussions and specific problem-solving.

5. Milestones

Achieving these milestones will mark significant progress in mastering the architecture of a notification system.

  • End of Week 1: Documented understanding of different notification types, their use cases, and initial thoughts on system components.
  • End of Week 2: Ability to articulate the benefits of message queues and distinguish between major message broker technologies, with a high-level message flow diagram.
  • End of Week 3: Comprehensive understanding of integration patterns for email, SMS, and push notification services, including API considerations.
  • End of Week 4: A preliminary high-level architectural diagram for a generic notification system, identifying core services and data flows.
  • End of Week 5: A detailed list of operational concerns (security, monitoring, etc.) and proposed strategies for addressing them within a notification system.
  • End of Week 6: A presented architectural proposal (including diagrams and key design decisions) for a specific notification system use case, ready for feedback and refinement.

6. Assessment Strategies

To ensure effective learning and retention, various assessment strategies will be employed throughout and at the culmination of this study plan.

  • Weekly Self-Assessment Quizzes: Short quizzes focusing on the week's learning objectives to reinforce concepts and identify areas needing further review.
  • Conceptual Design Exercises: Given a specific business requirement (e.g., "Design a notification system for an e-commerce platform"), participants will be tasked with outlining key components and data flows.
  • Architectural Diagram Reviews: Peer review and expert feedback sessions on drafted architectural diagrams to ensure clarity, completeness, and adherence to best practices.
  • Technology Comparison Matrix: Create a matrix comparing different message brokers, database types, or third-party providers based on specific criteria (cost, scalability, features, integration complexity).
  • Case Study Analysis: Present findings and proposed improvements for an existing notification system architecture.
  • Final Architecture Presentation & Document: A comprehensive presentation of the proposed notification system architecture, supported by a detailed design document outlining choices, trade-offs, and future considerations. This will be the primary deliverable for this study plan.
  • Q&A Sessions: Regular interactive sessions to clarify doubts, discuss complex topics, and challenge architectural decisions.

python

notification_system/models.py

from datetime import datetime

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):

"""

Simplified User model. In a real system, this would likely be fetched from a User service.

Here, it's included to demonstrate relationships and user-specific data.

"""

__tablename__ = 'users'

id = db.Column(db.Integer, primary_key=True)

username = db.Column(db.String(80), unique=True, nullable=False)

email = db.Column(db.String(120), unique=True, nullable=

gemini Output

Notification System: Comprehensive Review and Documentation

This document provides a detailed overview and documentation of the proposed Notification System, outlining its core functionalities, high-level architecture, benefits, and recommended next steps. This deliverable serves as a foundational blueprint for your organization, enabling effective communication and enhanced user engagement.


1. Executive Summary

The Notification System is designed to provide a robust, scalable, and flexible platform for delivering timely and relevant communications to your users across multiple channels. By centralizing notification logic, templating, and dispatch, this system aims to significantly improve user engagement, streamline operational workflows, and provide valuable insights into communication effectiveness. It empowers your applications to send personalized messages efficiently, ensuring critical information reaches the right user at the right time through their preferred medium.


2. System Overview

The Notification System is a critical component for any modern application, enabling proactive and reactive communication with users. Its primary purpose is to abstract the complexities of multi-channel message delivery, allowing product teams and developers to focus on what to communicate rather than how to communicate it.

2.1. Purpose

To create a unified, reliable, and intelligent platform for sending various types of notifications (e.g., transactional, marketing, alerts) to users across diverse communication channels.

2.2. Key Objectives

  • Reliability: Ensure high deliverability rates and robust error handling.
  • Scalability: Support a growing number of users and notification volumes without performance degradation.
  • Flexibility: Easily integrate new notification channels and adapt to evolving business requirements.
  • Personalization: Enable dynamic content generation and user-specific preferences.
  • Observability: Provide comprehensive logging, monitoring, and analytics for all notifications.
  • Efficiency: Reduce development effort and operational overhead for sending messages.

3. Core Features & Functionality

The Notification System will encompass a rich set of features designed to meet modern communication demands:

  • Multi-Channel Delivery:

* Email: Integration with leading email service providers (e.g., SendGrid, Mailgun, AWS SES).

* SMS/MMS: Integration with SMS gateways (e.g., Twilio, Nexmo).

* Push Notifications: Support for mobile push (e.g., Firebase Cloud Messaging, Apple Push Notification Service) and potentially web push.

* In-App Notifications: Display notifications directly within the application UI (e.g., notification center, banners).

* Webhooks: Ability to send notifications to external systems or custom endpoints.

  • Dynamic Templating Engine:

* Utilize a powerful templating language (e.g., Handlebars, Jinja2) for creating reusable notification templates.

* Support for variables and conditional logic within templates to personalize content.

* Version control for templates to manage changes effectively.

* Preview functionality for templates before sending.

  • Notification Prioritization:

* Define different priority levels (e.g., critical, high, medium, low) to ensure urgent messages are processed and delivered first.

* Queue management based on priority.

  • User Preference Management:

* Allow users to define their preferred notification channels for different types of messages (e.g., email for marketing, SMS for critical alerts).

* Opt-in/opt-out mechanisms for various notification categories.

  • Rate Limiting & Throttling:

* Implement controls to prevent notification spamming and adhere to channel provider limits.

* Global and per-user/per-channel rate limits.

  • Delivery Status Tracking & Logging:

* Record the full lifecycle of each notification: requested, queued, sent, delivered, failed, opened, clicked.

* Detailed logs for auditing, debugging, and compliance.

  • Retry Mechanisms & Fallbacks:

* Automatic retries for transient delivery failures with exponential backoff.

* Configurable fallback channels (e.g., if SMS fails, try email).

  • Analytics & Reporting:

* Dashboard to visualize key metrics: send rates, delivery success rates, open rates, click-through rates.

* Ability to filter and analyze notification performance by type, channel, and user segment.

  • API-Driven Integration:

* Provide a clean, well-documented API for internal applications to submit notification requests.

* Asynchronous processing for non-blocking integration.


4. Technical Architecture (High-Level)

The Notification System will be designed with a microservices-oriented approach, emphasizing modularity, scalability, and resilience.


+----------------+       +----------------+       +-------------------+       +--------------------+
|                |       |                |       |                   |       |                    |
|  Source Apps   |------>|  API Gateway   |------>|  Message Queue    |<------|  Templating Service|
| (e.g., CRM,    |       | (Ingestion     |       | (e.g., Kafka, SQS)|       |                    |
|  Backend, Web) |       |  Layer)        |       |                   |       |                    |
+----------------+       +----------------+       +-------------------+       +--------------------+
                                 |                                 |
                                 | (Notification Request)          | (Queued Messages)
                                 V                                 V
+-----------------------------------------------------------------------------------------------------+
|                                            Notification Processing Engine                           |
|                                                                                                     |
|  - Message Parsing & Validation                                                                     |
|  - User Preference Lookup (DB)                                                                      |
|  - Template Rendering (Templating Service)                                                          |
|  - Priority Assignment                                                                              |
|  - Rate Limiting Checks                                                                             |
|  - Dispatch to Channel-Specific Workers                                                             |
+-----------------------------------------------------------------------------------------------------+
        |                                       |                                       |
        V                                       V                                       V
+----------------+       +----------------+       +----------------+       +----------------+
|                |       |                |       |                |       |                |
| Email Dispatch |------>| SMS Dispatch   |------>| Push Dispatch  |------>| Webhook/In-App |
| (e.g., SendGrid)|      | (e.g., Twilio) |       | (e.g., FCM, APNS)|      | Dispatch       |
+----------------+       +----------------+       +----------------+       +----------------+
        |                        |                        |                        |
        V                        V                        V                        V
+-----------------------------------------------------------------------------------------------------+
|                                            Database & Storage                                       |
|                                                                                                     |
|  - User Preferences (Opt-ins, Channels)                                                             |
|  - Notification Templates                                                                           |
|  - Notification Logs (Status, Metadata)                                                             |
|  - Analytics Data                                                                                   |
+-----------------------------------------------------------------------------------------------------+
        ^                                                                                            |
        |---------------------------------------------------------------------------------------------|
                                                    (Monitoring & Logging)

4.1. Key Components:

  • API Gateway / Ingestion Layer: The single entry point for all notification requests from source applications. Handles authentication, authorization, and initial validation.
  • Message Queue: An asynchronous buffer (e.g., Kafka, AWS SQS, RabbitMQ) to decouple request submission from processing, ensuring scalability and resilience.
  • Notification Processing Engine: The core logic component that consumes messages from the queue, performs preference lookups, renders templates, applies rate limits, and routes messages to the appropriate dispatchers.
  • Templating Service: A dedicated microservice responsible for managing and rendering notification templates with dynamic data.
  • Notification Dispatchers: Channel-specific services (Email, SMS, Push, Webhook, In-App) that integrate with external providers or internal systems to send the final message. They handle provider-specific APIs, error codes, and retries.
  • Database & Storage:

* Relational Database (e.g., PostgreSQL, MySQL): For storing user preferences, notification templates, and metadata.

* NoSQL Database (e.g., DynamoDB, MongoDB): Potentially for high-volume, unstructured notification logs and analytics data.

  • Monitoring & Logging: Centralized logging (e.g., ELK Stack, Splunk, CloudWatch Logs) and monitoring (e.g., Prometheus, Grafana, Datadog) for system health, performance, and notification delivery status.

5. Benefits to Your Organization

Implementing this Notification System will yield significant advantages:

  • Enhanced User Engagement: Deliver timely, personalized, and relevant messages, fostering a stronger connection with your users and improving their overall experience.
  • Increased Operational Efficiency: Centralize notification logic, reducing redundant code and maintenance across different applications. Developers can integrate with a single API instead of multiple channel providers.
  • Scalability & Reliability: The asynchronous, microservices-based architecture ensures the system can handle fluctuating loads and maintain high availability, even during peak times.
  • Flexibility & Agility: Easily add new communication channels, update templates, or modify notification logic without requiring changes across all integrated applications.
  • Data-Driven Insights: Comprehensive analytics and logging provide actionable insights into notification performance, allowing for continuous optimization of communication strategies.
  • Improved Compliance & Control: Centralized preference management and audit trails help in adhering to privacy regulations (e.g., GDPR, CCPA) and internal policies.

6. Next Steps & Implementation Roadmap

To move forward with the development and deployment of the Notification System, we propose the following actionable roadmap:

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

* Stakeholder Workshops: Conduct sessions with product, marketing, engineering, and support teams to identify all notification types, business rules, priority levels, and user journey touchpoints.

* Channel Provider Selection: Finalize choices for email, SMS, push, and other providers based on existing contracts, cost, features, and regional coverage.

* User Preference Definition: Detail how user preferences will be managed, stored, and integrated.

* API Specification: Draft a comprehensive API specification for the Notification Ingestion Layer.

* Security & Compliance Review: Define security requirements, data handling policies, and compliance considerations.

  1. Phase 2: Detailed Design & Architecture (3-5 Weeks)

* Technical Design Document: Create detailed architectural designs for each microservice, data models, message queue configurations, and infrastructure setup.

* Technology Stack Finalization: Confirm specific technologies, frameworks, and cloud services to be used.

* Proof of Concept (POC): Potentially develop a small POC for a critical component (e.g., templating engine or a specific dispatcher) to validate technical choices.

  1. Phase 3: Development Sprints (12-20 Weeks, iterative)

* Iterative Development: Implement the system in agile sprints, focusing on core functionalities first (e.g., API, Message Queue, Email Dispatch).

* Continuous Integration/Continuous Deployment (CI/CD): Set up automated pipelines for building, testing, and deploying the services.

* Regular Demos: Provide periodic demonstrations of progress to stakeholders.

  1. Phase 4: Testing & Quality Assurance (4-6 Weeks)

* Unit & Integration Testing: Conduct thorough testing at the component and integration levels.

* Performance & Load Testing: Simulate high loads to ensure scalability and identify bottlenecks.

* User Acceptance Testing (UAT): Engage key business users to validate that the system meets their requirements.

* Security Testing: Perform vulnerability assessments and penetration testing.

  1. Phase 5: Deployment & Monitoring (2-3 Weeks)

* Staged Rollout: Deploy the system to a staging environment, followed by a controlled rollout to production.

* Monitoring & Alerting: Configure comprehensive monitoring dashboards and alerts for system health, performance, and notification delivery metrics.

* Documentation: Create detailed operational runbooks, API documentation, and user guides.

  1. Phase 6: Training & Handover (Ongoing)

* Team Training: Provide training to engineering, operations, and support teams on how to use and manage the system.

* Ongoing Support: Establish a clear support model for maintenance and future enhancements.


7. Conclusion

The proposed Notification System represents a strategic investment in your organization's ability to communicate effectively and efficiently with its users. By centralizing and optimizing your notification infrastructure, you will unlock new opportunities for user engagement, streamline operations, and gain valuable insights into your communication strategies. We are confident that this robust solution will serve as a cornerstone for your future growth and success.

We look forward to discussing this comprehensive plan further and partnering with you to bring this essential system to fruition.

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