Full Stack App Blueprint
Run ID: 69ccfa573e7fb09ff16a6d9e2026-04-01Development
PantheraHive BOS
BOS Dashboard

This document provides a comprehensive, detailed, and professional blueprint for a full-stack application, complete with code examples, architectural patterns, and deployment considerations. This blueprint aims to be actionable, guiding developers through the process of setting up and structuring a modern web application.


Full Stack App Blueprint: Code Generation

This deliverable provides the foundational code and architectural patterns for a robust, scalable full-stack application. We've chosen a popular and efficient technology stack to demonstrate best practices across frontend, backend, database, authentication, deployment, and testing.

Technology Stack:


Project Overview and Structure

A well-organized project structure is crucial for maintainability and scalability. Below is a recommended high-level directory structure for both the frontend and backend applications.

text • 1,734 chars
.
├── backend/
│   ├── src/
│   │   ├── config/              # Environment variables, database connection
│   │   ├── controllers/         # Request handling logic
│   │   ├── middleware/          # Authentication, error handling, etc.
│   │   ├── models/              # Database schema definitions, interfaces
│   │   ├── routes/              # API endpoint definitions
│   │   ├── services/            # Business logic, database interactions
│   │   ├── utils/               # Helper functions
│   │   ├── app.ts               # Express app setup
│   │   └── server.ts            # Server entry point
│   ├── tests/                   # Unit and integration tests
│   ├── .env.example
│   ├── package.json
│   ├── tsconfig.json
│   └── Dockerfile
│
├── frontend/
│   ├── public/                  # Static assets
│   ├── src/
│   │   ├── assets/              # Images, icons
│   │   ├── components/          # Reusable UI components
│   │   ├── contexts/            # React Context API for global state
│   │   ├── hooks/               # Custom React hooks
│   │   ├── pages/               # Page-level components (routes)
│   │   ├── services/            # API interaction logic (e.g., Axios instance)
│   │   ├── utils/               # Helper functions
│   │   ├── App.tsx              # Main application component, routing
│   │   ├── main.tsx             # Entry point
│   │   └── vite-env.d.ts
│   ├── tests/                   # Frontend tests
│   ├── .env.example
│   ├── package.json
│   ├── tsconfig.json
│   └── Dockerfile
│
├── docker-compose.yml           # Defines multi-container Docker application
├── .gitignore
├── README.md
└── package.json                 # (Optional) Root workspace package.json for monorepo setup
Sandboxed live preview

This document outlines a comprehensive architectural blueprint for a full-stack application, covering all essential components from the user interface to the database, including authentication, deployment, and testing strategies. This plan is designed to be robust, scalable, and maintainable, serving as a foundational guide for development.

Note: The request contained a conflicting instruction regarding a "detailed study plan." This instruction has been disregarded in favor of generating a comprehensive "Full Stack App Blueprint" as per the primary workflow step description.


1. Executive Summary

This blueprint proposes a modern, cloud-native full-stack application architecture. It leverages a combination of industry-standard technologies to ensure high performance, scalability, security, and developer efficiency. The frontend will be a single-page application (SPA), communicating with a RESTful API backend, backed by a robust relational database. Cloud services will facilitate deployment, monitoring, and scaling.

2. Core Technology Stack (Proposed)

This section outlines the primary technologies chosen for each layer of the application.

  • Frontend Framework: React.js with TypeScript

Rationale:* High community support, component-based architecture, strong ecosystem, and static typing for improved maintainability.

  • Backend Framework: Node.js with Express.js and TypeScript

Rationale:* Non-blocking I/O for high concurrency, JavaScript/TypeScript consistency across the stack, vast package ecosystem (npm), and proven performance for API services.

  • Database: PostgreSQL

Rationale:* Robust, open-source relational database, ACID compliance, excellent support for complex queries, and widely adopted for critical applications.

  • Authentication: JSON Web Tokens (JWT)

Rationale:* Stateless, scalable, and secure for API-driven applications.

  • Cloud Provider: Amazon Web Services (AWS)

Rationale:* Comprehensive suite of services for compute, database, storage, networking, and security, offering unparalleled scalability and reliability.

  • Containerization: Docker

Rationale:* Ensures consistent environments from development to production, simplifies deployment, and enhances portability.

3. Frontend Architecture

The frontend will be a Single Page Application (SPA) built with React.js and TypeScript.

  • Framework: React.js (v18+) with TypeScript
  • State Management: React Context API for global state, combined with useState/useReducer for local component state. For more complex global state, consider Redux Toolkit.
  • Routing: React Router DOM (v6+) for declarative navigation.
  • UI Library/Component System:

* Styling: Tailwind CSS for utility-first CSS, enabling rapid UI development and highly customizable designs.

* Component Library (Optional): Chakra UI or Material-UI for pre-built, accessible, and themable components, if faster UI development is prioritized over full customizability.

  • Data Fetching: React Query (TanStack Query) for efficient data fetching, caching, synchronization, and error handling.
  • Build Tool: Vite for fast development server and optimized production builds.
  • Folder Structure: Feature-based, e.g., /src/features/auth, /src/features/dashboard, /src/components/common.
  • Key Components:

* Layout Components: Header, Footer, Navigation (Sidebar/Navbar).

* Authentication Components: Login, Register, Forgot Password.

* Dashboard Components: User Profile, Data Display Widgets, Forms.

* Reusable UI Components: Buttons, Inputs, Modals, Spinners, Tables.

4. Backend Architecture

The backend will be a RESTful API built with Node.js, Express.js, and TypeScript.

  • Framework: Node.js (v18+) with Express.js
  • Language: TypeScript for type safety and better code organization.
  • API Style: RESTful API, adhering to HTTP methods and status codes for resource manipulation.
  • Folder Structure: Layered architecture (MVC-inspired):

* /src/routes: Defines API endpoints and links to controllers.

* /src/controllers: Handles incoming requests, validates input, and orchestrates business logic.

* /src/services: Contains core business logic, interacts with the database via models/repositories.

* /src/models: Defines data structures and interacts directly with the database (via ORM).

* /src/middleware: Global or route-specific middleware (e.g., authentication, error handling, logging).

* /src/utils: Helper functions, constants, configurations.

  • ORM/ODM: TypeORM (or Sequelize) for PostgreSQL, providing an object-relational mapping layer.
  • Validation: Joi (or class-validator) for robust input validation on API endpoints.
  • Logging: Winston or Pino for structured logging, capturing request details, errors, and system events.
  • Environment Variables: dotenv for managing configuration based on environment.
  • Error Handling: Centralized error handling middleware to catch and format API errors consistently.

5. Database Architecture

PostgreSQL will serve as the primary relational database.

  • Database System: PostgreSQL (v14+)
  • Schema Design (Conceptual Example):

* users Table:

* id (UUID, PK)

* email (VARCHAR(255), UNIQUE, NOT NULL)

* password_hash (VARCHAR(255), NOT NULL)

* first_name (VARCHAR(100))

* last_name (VARCHAR(100))

* role (ENUM('admin', 'user'), DEFAULT 'user', NOT NULL)

* is_active (BOOLEAN, DEFAULT TRUE)

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW())

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW())

* products Table (Example for an E-commerce/Catalog App):

* id (UUID, PK)

* name (VARCHAR(255), NOT NULL)

* description (TEXT)

* price (NUMERIC(10, 2), NOT NULL)

* category_id (UUID, FK to categories.id)

* stock_quantity (INTEGER, NOT NULL)

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW())

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW())

* categories Table:

* id (UUID, PK)

* name (VARCHAR(100), UNIQUE, NOT NULL)

* description (TEXT)

* created_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW())

* updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW())

  • Relationships:

* One-to-many: A category can have many products.

  • Indexing Strategy:

* Create indexes on frequently queried columns (e.g., users.email, products.category_id, products.name).

* Utilize UUIDs for primary keys to distribute writes and prevent hot spots in distributed systems.

  • Migration Tool: TypeORM Migrations (or Knex.js) for managing schema changes in a version-controlled manner.

6. Authentication & Authorization

  • Authentication Method: JSON Web Tokens (JWT)

* Flow:

1. User sends credentials (email, password) to /api/auth/login.

2. Backend validates credentials, generates a JWT containing user ID and role, and signs it with a secret key.

3. Backend sends the JWT back to the client.

4. Client stores the JWT (e.g., in an HttpOnly cookie for security against XSS, or in localStorage with careful XSS mitigation).

5. For subsequent requests to protected routes, the client includes the JWT in the Authorization header (Bearer Token).

6. Backend middleware intercepts requests, verifies the JWT's signature and expiration, and extracts user information.

* Password Hashing: bcrypt for secure storage of user passwords.

* Rate Limiting: Implement express-rate-limit to prevent brute-force attacks on login endpoints.

  • Authorization: Role-Based Access Control (RBAC)

* Backend middleware checks the role embedded in the JWT against required roles for specific routes/actions.

Example: An admin role might have access to /api/admin/ routes, while user roles can only access /api/profile or /api/products.

7. Deployment Strategy

Leveraging AWS for a scalable and robust cloud infrastructure.

  • Frontend Deployment (Static Assets):

* Build: React application is built into static HTML, CSS, and JavaScript files.

* Hosting: AWS S3 for storage of static assets.

* CDN: AWS CloudFront to distribute content globally, improving performance and reducing latency.

* CI/CD: GitHub Actions (or AWS CodePipeline/CodeBuild) to automatically build, test, and deploy frontend assets to S3/CloudFront upon code pushes to the main branch.

  • Backend Deployment (Containerized):

* Containerization: Dockerize the Node.js application.

* Container Registry: AWS Elastic Container Registry (ECR) to store Docker images.

* Orchestration: AWS Elastic Container Service (ECS) with Fargate launch type for serverless container management.

* Load Balancing: AWS Application Load Balancer (ALB) to distribute incoming traffic

tsx

// frontend/src/components/ProtectedRoute.tsx

import React from 'react

gemini Output

Full Stack Application Blueprint: Comprehensive Deliverable

Date: October 26, 2023

Prepared For: [Customer Name/Team]

Prepared By: PantheraHive AI


1. Executive Summary

This document presents a comprehensive blueprint for a modern full-stack application, outlining the architecture, key components, database design, authentication mechanisms, deployment strategies, and testing frameworks. Designed for scalability, maintainability, and security, this blueprint provides a ready-to-build foundation for your application development. It details both frontend and backend aspects, ensuring a cohesive and robust system from user interface to data persistence.

2. Application Overview

This blueprint is designed for a [Generic Full Stack Application] that requires user interaction, data management, and secure operations. Examples include a SaaS platform, an e-commerce site, a project management tool, or a social networking application.

Key Features (Illustrative):

  • User Authentication & Authorization: Secure login, registration, and role-based access control.
  • CRUD Operations: Create, Read, Update, Delete functionality for core application data.
  • Responsive User Interface: Accessible across various devices (desktop, tablet, mobile).
  • Scalable API: Robust and well-documented API for frontend and potential third-party integrations.
  • Data Persistence: Reliable storage and retrieval of application data.

Proposed Technology Stack:

  • Frontend: React (with TypeScript), Vite, Tailwind CSS, Zustand
  • Backend: Node.js (Express.js with TypeScript)
  • Database: PostgreSQL
  • Authentication: JSON Web Tokens (JWT)
  • Deployment: Docker, AWS (ECS/EC2, S3, RDS), GitHub Actions (CI/CD)
  • Testing: Jest, React Testing Library, Supertest, Cypress

3. Frontend Blueprint

The frontend will be a Single Page Application (SPA) built for performance, responsiveness, and an excellent user experience.

3.1. Architecture & Framework:

  • Framework: React with TypeScript for type safety and enhanced developer experience.
  • Build Tool: Vite for fast development server and optimized builds.
  • Architecture: Component-based, following a modular structure (e.g., Atomic Design principles).

3.2. Core Components (Illustrative):

  • Layout Components: Header, Footer, Sidebar, MainContentArea.
  • Navigation Components: Navbar, Breadcrumbs, Pagination.
  • Authentication Components: LoginPage, RegisterPage, ForgotPasswordPage, UserProfile.
  • Data Display Components: DataTable, Card, ListGroup.
  • Form Components: InputField, Button, Dropdown, FormGroup.
  • Feature-Specific Components: Dashboard, ItemDetails, SettingsPage.
  • Utility Components: Modal, Spinner, ToastNotification.

3.3. State Management:

  • Global State: Zustand for lightweight, fast, and scalable state management. Suitable for managing user session, application-wide settings, and shared data.
  • Local Component State: React's useState and useReducer hooks for component-specific state.
  • Data Fetching & Caching: React Query (or similar) for efficient data fetching, caching, and synchronization with the backend.

3.4. Routing:

  • Library: React Router DOM for declarative navigation.
  • Routes:

* /: Home Page

* /login: User Login

* /register: User Registration

* /dashboard: User Dashboard (protected)

* /settings: User Settings (protected)

* /items: List of Items (protected)

* /items/:id: Specific Item Details (protected)

/: 404 Not Found Page

3.5. Styling:

  • Framework: Tailwind CSS for utility-first CSS, enabling rapid UI development and highly customizable designs.
  • Component Styling: Direct application of Tailwind classes. For complex or reusable styles, @apply directive or component libraries built on Tailwind can be used.

3.6. Internationalization (i18n):

  • Library: react-i18next for managing multiple languages, allowing for a global user base.

4. Backend API Blueprint

The backend will be a RESTful API, adhering to best practices for security, performance, and maintainability.

4.1. Architecture & Framework:

  • Framework: Node.js with Express.js for its flexibility and extensive middleware ecosystem.
  • Language: TypeScript for type safety and improved code quality.
  • Architecture: Layered architecture (Controller -> Service -> Repository/DAO) for clear separation of concerns.

4.2. Core Services/Modules (Illustrative):

  • Authentication Service: User registration, login, password reset, token generation/validation.
  • User Service: CRUD operations for user profiles, role management.
  • Item Service: CRUD operations for core application data (e.g., products, tasks, posts).
  • Validation Service: Centralized input validation logic.
  • Error Handling Service: Standardized error responses.

4.3. API Endpoints (Illustrative):

| Method | Path | Description | Authentication | Request Body (Example) | Response Body (Example) |

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

| POST | /api/auth/register | Register a new user | Public | { "username": "user", "email": "e@mail.com", "password": "pass" } | { "message": "User registered successfully" } |

| POST | /api/auth/login | Authenticate user & get JWT | Public | { "email": "e@mail.com", "password": "pass" } | { "token": "jwt_token_string", "user": { "id": "uuid", "email": "e@mail.com" } } |

| GET | /api/users/me | Get current authenticated user profile | Protected | None | { "id": "uuid", "username": "user", "email": "e@mail.com" } |

| GET | /api/items | Get all items (with optional filters/pagination) | Protected | None | [ { "id": "uuid", "name": "Item 1", "userId": "uuid" } ] |

| POST | /api/items | Create a new item | Protected | { "name": "New Item", "description": "Details" } | { "id": "uuid", "name": "New Item" } |

| GET | /api/items/:id | Get a specific item by ID | Protected | None | { "id": "uuid", "name": "Item 1", "description": "Details" } |

| PUT | /api/items/:id | Update a specific item by ID | Protected | { "name": "Updated Item" } | { "id": "uuid", "name": "Updated Item" } |

| DELETE | /api/items/:id | Delete a specific item by ID | Protected | None | { "message": "Item deleted successfully" } |

4.4. Data Validation:

  • Library: Joi or Zod for schema-based input validation on all API requests.
  • Implementation: Middleware functions to validate request bodies, query parameters, and path parameters before reaching controllers.

4.5. Error Handling:

  • Standardized Responses: Consistent JSON error responses including statusCode, message, and optionally errors (for validation failures).
  • Centralized Middleware: A dedicated error handling middleware to catch and process all errors, preventing sensitive information leakage.

4.6. Security:

  • CORS: Configured to allow requests only from trusted frontend origins.
  • Rate Limiting: express-rate-limit to prevent brute-force attacks and abuse.
  • Input Sanitization: Protect against XSS and SQL injection by sanitizing user inputs.
  • Helmet.js: A collection of middleware to set various HTTP headers for security (e.g., X-XSS-Protection, Strict-Transport-Security).

5. Database Design

A relational database will be used for structured data storage, ensuring data integrity and powerful querying capabilities.

5.1. Database System:

  • Choice: PostgreSQL, known for its robustness, extensibility, and strong support for complex queries and data types.

5.2. Schema Design (Logical - Illustrative):

Table: users

  • id (UUID, Primary Key, NOT NULL)
  • username (VARCHAR(255), UNIQUE, NOT NULL)
  • email (VARCHAR(255), UNIQUE, NOT NULL)
  • password_hash (VARCHAR(255), NOT NULL)
  • role (VARCHAR(50), DEFAULT 'user', NOT NULL) - e.g., 'user', 'admin'
  • created_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW(), NOT NULL)
  • updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW(), NOT NULL)

Table: items

  • id (UUID, Primary Key, NOT NULL)
  • user_id (UUID, Foreign Key REFERENCES users.id, NOT NULL)
  • name (VARCHAR(255), NOT NULL)
  • description (TEXT)
  • status (VARCHAR(50), DEFAULT 'active', NOT NULL) - e.g., 'active', 'archived'
  • created_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW(), NOT NULL)
  • updated_at (TIMESTAMP WITH TIME ZONE, DEFAULT NOW(), NOT NULL)

Relationships:

  • users to items: One-to-Many (One user can have many items).

5.3. Indexing Strategy:

  • Indexes will be created on frequently queried columns, such as users.email, users.username, items.user_id, and items.created_at to optimize read performance.
  • Foreign key columns are automatically indexed in PostgreSQL.

5.4. Migration Strategy:

  • Tool: TypeORM Migrations or Knex.js Migrations for managing database schema changes in a version-controlled manner.
  • Process: Each schema change (e.g., adding a column, creating a table) will be a new migration file, ensuring consistent database evolution across environments.

6. Authentication & Authorization

A secure and scalable authentication system using JWT will be implemented.

6.1. Authentication Mechanism:

  • JSON Web Tokens (JWT): Stateless authentication, ideal for distributed systems and mobile clients.
  • Flow:

1. User registers/logs in with credentials.

2. Backend authenticates credentials, generates a signed JWT containing user ID and role.

3. JWT is sent back to the client.

4. Client stores JWT (e.g., in localStorage or HttpOnly cookie).

5. For subsequent requests, client sends JWT in the Authorization header (Bearer <token>).

6. Backend validates JWT signature and expiry.

6.2. Password Management:

  • Hashing: bcrypt will be used to securely hash and salt user passwords, preventing plaintext storage.
  • Strength: Enforce strong password policies (min length, complexity).

6.3. Authorization:

  • Role-Based Access Control (RBAC): Users will be assigned roles (e.g., user, admin).
  • Middleware: Authorization middleware on the backend will check the user's role from the JWT against required permissions for specific routes/actions.
  • Permissions: Granular permissions can be defined (e.g., can_create_item, can_delete_user).

**6.4

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