Full Stack App Blueprint
Run ID: 69cbcc1d61b1021a29a8c6a82026-03-31Development
PantheraHive BOS
BOS Dashboard

This document provides a comprehensive and detailed blueprint for a full-stack application, complete with frontend components, backend API, database design, authentication, deployment configuration, and test suites. The goal is to provide a ready-to-build foundation, using modern technologies and best practices.

Chosen Technology Stack:


1. Project Overview and Structure

This blueprint outlines a modular, scalable, and maintainable full-stack application. Each part (frontend, backend) is a separate project within a monorepo structure, allowing for independent development and deployment while maintaining a cohesive codebase.

text • 1,769 chars
├── my-fullstack-app/
│   ├── frontend/                 # React frontend application
│   │   ├── public/
│   │   ├── src/
│   │   │   ├── assets/
│   │   │   ├── components/       # Reusable UI components
│   │   │   ├── features/         # Feature-specific modules (e.g., Auth, Users, Products)
│   │   │   ├── hooks/            # Custom React hooks
│   │   │   ├── lib/              # Utility functions, API clients
│   │   │   ├── pages/            # Page-level components (routes)
│   │   │   ├── styles/           # Global styles, Tailwind config
│   │   │   ├── App.tsx
│   │   │   ├── main.tsx
│   │   │   └── vite-env.d.ts
│   │   ├── .env.example
│   │   ├── package.json
│   │   ├── tsconfig.json
│   │   └── tailwind.config.js
│   ├── backend/                  # Node.js/Express API
│   │   ├── src/
│   │   │   ├── config/           # Environment variables, database connection
│   │   │   ├── controllers/      # Request handlers, business logic orchestration
│   │   │   ├── middlewares/      # Express middleware (e.g., auth, error handling)
│   │   │   ├── routes/           # API routes definitions
│   │   │   ├── services/         # Core business logic, data manipulation
│   │   │   ├── utils/            # Helper functions
│   │   │   ├── app.ts            # Express application setup
│   │   │   └── server.ts         # Server entry point
│   │   ├── prisma/               # Prisma schema and migrations
│   │   │   ├── migrations/
│   │   │   └── schema.prisma
│   │   ├── .env.example
│   │   ├── package.json
│   │   ├── tsconfig.json
│   │   └── jest.config.js
│   ├── docker-compose.yml        # For local development with Docker
│   ├── README.md
│   └── package.json              # Monorepo root package.json (optional, for shared scripts)
Sandboxed live preview

Full Stack Application Blueprint: PantheraHive Project Tracker

Executive Summary:

This document outlines a comprehensive blueprint for a full-stack web application, "PantheraHive Project Tracker." This blueprint covers all critical architectural components, from frontend user interfaces and backend APIs to database design, authentication strategies, deployment configurations, and robust testing methodologies. The aim is to provide a detailed, actionable plan ready for development, utilizing modern, scalable, and maintainable technologies.


1. Application Overview: PantheraHive Project Tracker

To provide a concrete example for this blueprint, we define "PantheraHive Project Tracker" – a collaborative project management tool.

  • Goal: To enable teams to efficiently manage projects, track tasks, and collaborate effectively.
  • Core Features:

* User Management: Registration, login, profile management, password reset.

* Project Management: Create, view, update, delete projects; assign project managers and team members.

* Task Management: Create, view, update, delete tasks within projects; assign tasks to users, set due dates, priorities, and statuses (To Do, In Progress, Done, Blocked).

* Comments & Activity Feed: Allow users to comment on tasks and view project activity.

* Dashboard: Overview of assigned tasks, project progress, and deadlines.

* Basic Reporting: Task completion rates, project status summaries.

  • Key User Roles:

* Admin: Full control over users, projects, and system settings.

* Project Manager: Create/manage projects, assign tasks, manage team members within their projects.

* Team Member: View assigned projects/tasks, update task status, add comments.


2. Frontend Architecture

The frontend will be built using a modern React framework for a highly interactive and responsive user experience.

  • Framework/Library: Next.js (React)

* Rationale: Provides server-side rendering (SSR), static site generation (SSG), file-system based routing, API routes (for small serverless functions if needed), and optimized performance.

  • Language: TypeScript

* Rationale: Enhances code quality, maintainability, and developer experience through static type checking.

  • State Management: Zustand / React Context API

* Rationale: Zustand for global, complex states (e.g., user session, notifications) due to its simplicity and performance. React Context API for localized, component-tree specific state.

  • Routing: Next.js Built-in File-system Routing

* Rationale: Intuitive and powerful, supports dynamic routes and nested layouts.

  • Styling: Tailwind CSS

* Rationale: Utility-first CSS framework for rapid UI development, highly customizable, and ensures consistent design. Potentially combined with Styled Components for complex, reusable components.

  • Component Structure: Atomic Design Principles

* Rationale: Organizes UI into Atoms (buttons, inputs), Molecules (forms, navigation bars), Organisms (header, footer), Templates (page layouts), and Pages (actual views) for modularity and reusability.

  • Data Fetching: React Query (TanStack Query)

* Rationale: Provides powerful hooks for managing server state, caching, background refetching, and error handling, simplifying data fetching logic.

  • Build Process: Next.js Built-in Build System

* Rationale: Handles transpilation, bundling, optimization, and code splitting automatically.

  • Deployment Target: Vercel (recommended for Next.js) or AWS S3/CloudFront (for static assets if Next.js is exported as static).

3. Backend Architecture

The backend will be a robust and scalable API service, designed to handle business logic and data persistence.

  • Language/Framework: Node.js with NestJS

* Rationale: NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications, leveraging TypeScript and inspired by Angular's modular structure. Provides dependency injection, modules, and decorators.

  • API Style: RESTful API

* Rationale: Standard, widely understood, and easy to consume for typical CRUD operations.

  • Authentication: JSON Web Tokens (JWT)

* Rationale: Stateless authentication, scalable, and widely adopted. Tokens are issued upon successful login and used for subsequent requests.

  • Authorization: Role-Based Access Control (RBAC)

* Rationale: Users are assigned roles (Admin, Project Manager, Team Member), and routes/actions are protected based on these roles using NestJS guards and interceptors.

  • Data Access Layer: TypeORM / Prisma

* Rationale: Object-Relational Mapper (ORM) for interacting with the database. TypeORM offers strong TypeScript support and a rich feature set. Prisma offers a modern developer experience with powerful type safety.

  • Business Logic Layer: Services (NestJS)

* Rationale: Encapsulates core application logic, decoupled from controllers and data access, promoting reusability and testability.

  • Error Handling: Centralized Middleware/Interceptors (NestJS)

* Rationale: A global exception filter or middleware to catch and standardize API error responses (e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found, 500 Internal Server Error).

  • Caching Strategy: Redis

* Rationale: Used for high-speed data retrieval, e.g., frequently accessed project lists, user sessions (if not using JWT entirely stateless), or rate limiting.

  • Logging: Winston / Pino

* Rationale: Structured logging for better observability and easier debugging in production environments.


4. Database Design

A robust relational database will store all application data, ensuring data integrity and consistency.

  • Type: Relational Database (PostgreSQL)

* Rationale: Open-source, highly reliable, feature-rich, ACID compliant, and excellent for structured data with complex relationships.

  • Schema Overview:

* Users Table:

* id (PK, UUID)

* username (UNIQUE, VARCHAR)

* email (UNIQUE, VARCHAR)

* password_hash (VARCHAR)

* first_name (VARCHAR)

* last_name (VARCHAR)

* created_at (TIMESTAMP)

* updated_at (TIMESTAMP)

* Roles Table:

* id (PK, UUID)

* name (UNIQUE, VARCHAR - e.g., 'admin', 'project_manager', 'team_member')

* UserRoles Table (Junction for Many-to-Many):

* user_id (FK to Users.id)

* role_id (FK to Roles.id)

* (Composite PK on user_id, role_id)

* Projects Table:

* id (PK, UUID)

* name (VARCHAR)

* description (TEXT)

* status (ENUM: 'active', 'completed', 'archived')

* start_date (DATE)

* end_date (DATE)

* created_by (FK to Users.id)

* created_at (TIMESTAMP)

* updated_at (TIMESTAMP)

* ProjectMembers Table (Junction for Many-to-Many):

* project_id (FK to Projects.id)

* user_id (FK to Users.id)

* (Composite PK on project_id, user_id)

* Tasks Table:

* id (PK, UUID)

* project_id (FK to Projects.id)

* assigned_to (FK to Users.id, NULLABLE)

* title (VARCHAR)

* description (TEXT)

* status (ENUM: 'to_do', 'in_progress', 'done', 'blocked')

* priority (ENUM: 'low', 'medium', 'high')

* due_date (DATE, NULLABLE)

* created_by (FK to Users.id)

* created_at (TIMESTAMP)

* updated_at (TIMESTAMP)

* Comments Table:

* id (PK, UUID)

* task_id (FK to Tasks.id)

*

typescript

// backend/src/server.ts

import dotenv from 'dotenv';

dotenv.config(); // Load environment variables from .env file

import app from './app'; // The Express application instance

import { connectDB } from './config/database'; // Database connection

gemini Output

Full Stack Application Blueprint: Comprehensive Deliverable

This document provides a comprehensive, detailed blueprint for your full-stack application, covering all essential components from frontend design to deployment strategy and testing. This blueprint is designed to be highly actionable, enabling your development team to proceed directly to implementation with a clear roadmap.


1. Application Overview

This blueprint outlines a robust, scalable, and maintainable full-stack application designed to deliver a modern user experience. The application will feature a clear separation of concerns between the frontend user interface and the backend API, ensuring flexibility and ease of development.

Key Objectives:

  • Modularity: Component-based architecture for both frontend and backend.
  • Scalability: Designed to handle increasing user loads and data volumes.
  • Security: Robust authentication and authorization mechanisms.
  • Maintainability: Clear code structure, documentation, and automated testing.
  • Performance: Optimized for speed and responsiveness.

2. Core Features & Functionality (Illustrative Example)

While the specific features will depend on your application's domain, this blueprint assumes a typical web application requiring:

  • User Management: Registration, Login, Profile Management, Password Reset.
  • Data Management (CRUD): Create, Read, Update, Delete operations for core entities (e.g., Items, Posts, Tasks).
  • Dashboard/Overview: Personalized view for authenticated users.
  • Search & Filtering: Ability to query and refine data.
  • Notifications: Basic in-app notification system.

3. Technology Stack Recommendation

To ensure a modern, performant, and maintainable application, we recommend the following technology stack:

  • Frontend:

* Framework: React (with Next.js for server-side rendering, routing, and API routes)

* Language: TypeScript

* Styling: Tailwind CSS (utility-first CSS framework)

* State Management: React Query (data fetching, caching, synchronization) & Zustand (simple, fast global state)

  • Backend:

* Framework: Node.js with NestJS (a progressive Node.js framework for building efficient, scalable server-side applications)

* Language: TypeScript

* API Style: RESTful API

  • Database:

* Type: PostgreSQL (relational database, chosen for its robustness, ACID compliance, and rich feature set)

* ORM: Prisma ORM (Type-safe database access, migrations, and schema management)

  • Authentication:

* Strategy: JSON Web Tokens (JWT)

  • Deployment & Infrastructure:

* Containerization: Docker

* Cloud Provider: AWS (Amazon Web Services)

* CI/CD: GitHub Actions

  • Testing:

* Frameworks: Jest, React Testing Library, Cypress

4. Frontend Blueprint

4.1. Architecture

  • Component-Based: The UI will be broken down into reusable, independent components.
  • Pages & Layouts: Next.js pages directory for routing and _app.tsx / _document.tsx for global layouts and configurations.
  • Server-Side Rendering (SSR) / Static Site Generation (SSG): Leverage Next.js for optimal SEO, initial page load performance, and data pre-fetching.
  • Atomic Design Principles (Optional but Recommended): Structure components into Atoms, Molecules, Organisms, Templates, and Pages for better organization and scalability.

4.2. Key Components (Illustrative)

  • Layout Components:

* Layout.tsx: Global layout wrapper (Header, Footer, Navigation).

* Sidebar.tsx: Navigation menu.

* Header.tsx: Application title, user profile, notifications.

* Footer.tsx: Copyright, links.

  • UI Primitives (Atoms):

* Button.tsx

* Input.tsx

* Typography.tsx (Headings, Paragraphs)

* Icon.tsx

* Spinner.tsx

  • Feature-Specific Components (Molecules/Organisms):

* LoginForm.tsx

* RegistrationForm.tsx

* UserProfileCard.tsx

* DataTable.tsx (for displaying lists of items)

* Modal.tsx

* NotificationToast.tsx

4.3. State Management

  • Server State (Data Fetching): React Query will manage all asynchronous data fetching, caching, invalidation, and synchronization with the backend. This eliminates the need for complex global state for server-derived data.
  • Client State (UI State): Zustand will be used for simple, local, or global UI state management (e.g., modal open/close, theme toggles, form input values not managed by a form library).
  • Form State: React Hook Form for efficient and flexible form management.

4.4. Styling Strategy

  • Tailwind CSS: Utility-first approach for rapid UI development and consistent design.
  • CSS-in-JS (Optional): For highly dynamic or scoped styles, Emotion or Styled Components can be integrated, though Tailwind usually suffices.
  • Theming: Centralized tailwind.config.js for design tokens (colors, fonts, spacing).

4.5. Routing

  • Next.js File-system Routing: Pages are automatically routed based on their file names in the pages directory.
  • Dynamic Routes: Use [param].tsx for dynamic segments (e.g., /users/[id]).
  • Protected Routes: Implement higher-order components (HOCs) or route guards to protect routes based on authentication status and user roles.

5. Backend API Blueprint

5.1. Architecture

  • RESTful API: Standard HTTP methods (GET, POST, PUT, DELETE) for resource manipulation.
  • Monolithic (Initial): Start with a well-structured monolithic application using NestJS, which provides excellent modularity for future microservices extraction if needed.
  • Modules: Organize backend logic into feature-specific modules (e.g., AuthModule, UsersModule, ItemsModule).
  • Layered Architecture:

* Controllers: Handle incoming HTTP requests, validate input, and delegate to services.

* Services: Contain business logic, interact with the database via repositories/ORM.

* Repositories/ORM: Abstract database interactions (Prisma).

* DTOs (Data Transfer Objects): Define request/response shapes and validate input.

5.2. Key Endpoints (Illustrative)

Authentication (/api/auth)

  • POST /register: User registration.
  • POST /login: User authentication, returns JWT.
  • POST /refresh-token: Refresh expired JWT (optional, for longer sessions).
  • POST /logout: Invalidate token (optional, for server-side token blacklisting).
  • POST /forgot-password: Initiate password reset.
  • POST /reset-password: Complete password reset.

User Management (/api/users)

  • GET /me: Get current authenticated user's profile. (Protected)
  • PUT /me: Update current authenticated user's profile. (Protected)
  • GET /:id: Get user by ID (Admin/Protected).
  • GET /: Get all users (Admin/Protected).
  • DELETE /:id: Delete user (Admin/Protected).

Item Management (/api/items)

  • GET /: Get all items (with pagination, filtering, sorting).
  • POST /: Create a new item. (Protected)
  • GET /:id: Get item by ID.
  • PUT /:id: Update item by ID. (Protected)
  • DELETE /:id: Delete item by ID. (Protected)

5.3. Data Models (Simplified, will correspond to Prisma Schema)

  • User: id, email, passwordHash, firstName, lastName, role, createdAt, updatedAt
  • Item: id, name, description, ownerId (FK to User), status, createdAt, updatedAt

5.4. Error Handling

  • Standardized Error Responses: Consistent JSON format for errors (e.g., { "statusCode": 400, "message": "Validation failed", "error": "Bad Request" }).
  • HTTP Status Codes: Use appropriate HTTP status codes (e.g., 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error).
  • Global Exception Filters: NestJS provides powerful exception filters to catch and handle errors centrally.

5.5. API Documentation Strategy

  • OpenAPI (Swagger): Integrate Swagger UI with NestJS to automatically generate and serve interactive API documentation based on controllers and DTOs. This will be invaluable for frontend developers and external consumers.

6. Database Design

6.1. Database Type

  • PostgreSQL: Chosen for its reliability, transactional integrity (ACID), strong support for complex queries, and extensibility.

6.2. Schema Design (Illustrative)

User Table

| Column Name | Data Type | Constraints | Description |

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

| id | UUID | PRIMARY KEY, NOT NULL, DEFAULT gen_random_uuid() | Unique identifier for the user. |

| email | VARCHAR(255) | NOT NULL, UNIQUE | User's email address, used for login. |

| passwordHash | VARCHAR(255) | NOT NULL | Hashed password. |

| firstName | VARCHAR(100) | | User's first name. |

| lastName | VARCHAR(100) | | User's last name. |

| role | ENUM('USER', 'ADMIN') | NOT NULL, DEFAULT 'USER' | User's role for authorization. |

| createdAt | TIMESTAMP WITH TIME ZONE | NOT NULL, DEFAULT NOW() | Timestamp of user creation. |

| updatedAt | TIMESTAMP WITH TIME ZONE | NOT NULL, DEFAULT NOW() | Timestamp of last update. |

Item Table

| Column Name | Data Type | Constraints | Description |

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

| id | UUID | PRIMARY KEY, NOT NULL, DEFAULT gen_random_uuid() | Unique identifier for the item. |

| name | VARCHAR(255) | NOT NULL | Name of the item. |

| description | TEXT | | Detailed description of the item. |

| status | ENUM('ACTIVE', 'ARCHIVED') | NOT NULL, DEFAULT 'ACTIVE' | Current status of the item. |

| ownerId | UUID | NOT NULL, FOREIGN KEY REFERENCES User(id) ON DELETE CASCADE | ID of the user who owns this item. |

| createdAt | TIMESTAMP WITH TIME ZONE | NOT NULL, DEFAULT NOW() | Timestamp of item creation. |

| updatedAt | TIMESTAMP WITH TIME ZONE | NOT NULL, DEFAULT NOW() | Timestamp of last update. |

6.3. Indexing Strategy

  • Primary Keys: Automatically indexed.
  • Foreign Keys: Automatically indexed by Prisma/PostgreSQL.
  • Frequently Queried Columns: email in User table, ownerId in Item table, name in Item table (for search).
  • Timestamp Columns: createdAt for ordering data.

6.4. Migration Strategy

  • Prisma Migrate: Use Prisma's migration tool to manage database schema changes.

* Generate migrations based on schema changes.

* Apply migrations to development, staging, and production environments.

* Version control migration files.

7. Authentication & Authorization

7.1. Authentication Strategy

  • JSON Web Tokens (JWT):

* Upon successful login, the backend issues a JWT containing user information (e.g., userId, role).

* The JWT is stored securely on the client-side (e.g., HTTP-only cookie for CSRF protection, or localStorage/sessionStorage if appropriate security measures are in place).

* For subsequent requests, the JWT is sent in the Authorization header (Bearer <token>).

* The backend validates the JWT on each protected route.

  • Hashing: Use a strong hashing algorithm (e.g., bcrypt) for storing passwords.
  • Password Reset: Implement a secure password reset flow using time-limited, single-use tokens sent via email.

7.2. Authorization Mechanisms

  • Role-Based Access Control (RBAC):

* Assign roles to users (e.g., USER, ADMIN).

* Implement route guards/interceptors on the backend to check the user's role from the JWT payload before allowing access to specific endpoints.

* Frontend can also use user roles to conditionally render UI elements.

8. Deployment Configuration

8.1. Infrastructure (AWS)

  • Compute:

* Frontend (Next.js): Deploy as a serverless function (AWS Lambda) via Vercel or directly to AWS Amplify/ECS for SSR/SSG.

* Backend (NestJS): AWS Elastic Container Service (ECS) with Fargate for serverless container management, or EC2 instances for more control.

  • Database: AWS RDS (Relational Database Service) for managed PostgreSQL.
  • Networking: AWS VPC (Virtual Private Cloud), Load Balancer (ALB), Route 53 for DNS.
  • Storage: AWS S3 for static assets (images, files) and backups.
  • Cache (Optional): AWS ElastiCache (Redis) for session management or frequently accessed data.

8.2. Containerization

  • Docker: Create Dockerfiles for both frontend and backend applications.

* Frontend: Multi-stage build for production-optimized Next.js application.

* Backend: Multi-stage build for NestJS application, including dependencies.

  • Docker Compose: For local development, define docker-compose.yml to run the frontend
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
\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);}});}