Full-Stack Website
Run ID: 69c93baefee1f7eb4a80fa532026-03-29Web Development
PantheraHive BOS
BOS Dashboard

This document outlines the initial generation of your full-stack website, focusing on establishing the core architecture, essential components, and foundational code. This deliverable represents Step 1 of 3: websitebuilder → generate_site for your "Full-Stack Website" workflow.


1. Project Overview & Scope

We have generated a foundational structure for a "Professional Portfolio & Services Showcase" website. This application is designed to allow you to present your work, services, and contact information, with a clear separation between client-side presentation and server-side data management.

Core Components:

Chosen Technology Stack:

To ensure a modern, scalable, and maintainable application, the following technologies have been selected and used for this initial generation:

2. Frontend Generation (Client-Side)

The frontend is built using React and styled with Tailwind CSS, providing a responsive and modular user interface.

2.1. Project Structure

jsx • 1,522 chars
import React, { useEffect, useState } from 'react';
import ServiceCard from '../components/ServiceCard';
import axios from 'axios'; // Assuming axios is installed for API calls

function ServicesPage() {
  const [services, setServices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchServices = async () => {
      try {
        const response = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/services`);
        setServices(response.data);
      } catch (err) {
        setError('Failed to fetch services. Please try again later.');
        console.error('Error fetching services:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchServices();
  }, []);

  if (loading) return <div className="text-center py-10">Loading services...</div>;
  if (error) return <div className="text-center py-10 text-red-600">{error}</div>;

  return (
    <section className="container mx-auto px-4 py-12">
      <h1 className="text-4xl font-bold text-center mb-10 text-gray-800">Our Services</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {services.length > 0 ? (
          services.map(service => (
            <ServiceCard key={service.id} service={service} />
          ))
        ) : (
          <p className="col-span-full text-center text-gray-600">No services available yet.</p>
        )}
      </div>
    </section>
  );
}

export default ServicesPage;
Sandboxed live preview

javascript

const { Pool } = require('pg');

const dotenv = require('dotenv');

dotenv.config();

const pool = new Pool({

user: process.env.DB_USER,

host: process.env.DB_HOST,

database: process.env.DB_NAME,

password: process.env.DB_PASSWORD,

port: process.env.DB_PORT,

});

const connectDB = async () => {

try {

await

collab Output

Step 2: Code Generation for Full-Stack Website (Task Manager)

This document provides the comprehensive, detailed, and production-ready code for your full-stack website. We've chosen to build a simple Task Manager application, demonstrating core functionalities like creating, reading, updating, and deleting tasks. This application will serve as a robust foundation for more complex features in the future.

Project Overview

Application Name: Task Manager

Description: A web application to manage a list of tasks, allowing users to add, view, mark as complete, and delete tasks.

Key Features:

  • Create new tasks with a description.
  • View all existing tasks.
  • Mark tasks as completed.
  • Delete tasks.
  • Persistent storage for tasks.

Technology Stack:

  • Frontend: React.js (JavaScript library for building user interfaces)
  • Backend: Node.js with Express.js (JavaScript runtime and web framework)
  • Database: MongoDB (NoSQL database)
  • Database ODM: Mongoose (Object Data Modeling for MongoDB in Node.js)
  • Styling: Plain CSS (for simplicity, can be extended with Tailwind CSS, Styled Components, etc.)

Project Structure

The project will be organized into two main directories: server for the backend and client for the frontend.


full-stack-website/
├── server/
│   ├── .env                       # Environment variables
│   ├── .gitignore                 # Git ignore rules for server
│   ├── package.json               # Backend dependencies and scripts
│   ├── README.md                  # Backend README
│   ├── server.js                  # Main server entry point
│   ├── config/
│   │   └── db.js                  # Database connection setup
│   ├── models/
│   │   └── Task.js                # Mongoose Task model
│   └── routes/
│       └── taskRoutes.js          # API routes for tasks
└── client/
    ├── .env.development           # Environment variables for client development
    ├── .gitignore                 # Git ignore rules for client
    ├── package.json               # Frontend dependencies and scripts
    ├── README.md                  # Frontend README
    ├── public/                    # Public assets (e.g., index.html)
    │   └── index.html
    ├── src/
    │   ├── App.css                # Global styles
    │   ├── App.js                 # Main application component
    │   ├── index.css              # Basic CSS for body/root
    │   ├── index.js               # React app entry point
    │   ├── api/
    │   │   └── tasks.js           # API service for tasks
    │   └── components/
    │       ├── TaskForm.js        # Component for adding new tasks
    │       ├── TaskItem.js        # Component for displaying a single task
    │       └── TaskList.js        # Component for displaying a list of tasks

Backend Code (server/)

This section provides the complete code for the Node.js/Express backend, responsible for handling API requests and interacting with the MongoDB database.

1. server/package.json


{
  "name": "task-manager-backend",
  "version": "1.0.0",
  "description": "Backend for the Task Manager application",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "keywords": [
    "node",
    "express",
    "mongodb",
    "task-manager"
  ],
  "author": "PantheraHive",
  "license": "MIT",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.19.2",
    "mongoose": "^8.4.1"
  },
  "devDependencies": {
    "nodemon": "^3.1.3"
  }
}
  • Explanation: Defines project metadata, scripts (start for production, dev for development with nodemon for auto-restarts), and dependencies.

* cors: Enables Cross-Origin Resource Sharing, allowing the frontend to make requests to the backend.

* dotenv: Loads environment variables from a .env file.

* express: The web framework for building the API.

* mongoose: ODM for MongoDB.

* nodemon (dev dependency): Automatically restarts the Node.js server when file changes are detected.

2. server/.env


PORT=5000
MONGO_URI=mongodb://localhost:27017/taskmanager
  • Explanation: Stores sensitive configuration information (like database connection strings and port numbers) outside of the codebase.

* PORT: The port on which the Express server will run.

* MONGO_URI: The connection string for your MongoDB database. Adjust localhost:27017 if your MongoDB instance is running elsewhere. taskmanager is the database name.

3. server/.gitignore


node_modules/
.env
  • Explanation: Specifies files and directories that Git should ignore, preventing unnecessary files (like installed dependencies and sensitive environment variables) from being committed to the repository.

4. server/README.md


# Task Manager Backend

This is the backend for the Task Manager application, built with Node.js, Express, and MongoDB.

## Features

- RESTful API for managing tasks (CRUD operations).
- Connects to a MongoDB database using Mongoose.

## Setup

1.  **Clone the repository:**

git clone <repository-url>

cd full-stack-website/server


2.  **Install dependencies:**

npm install


3.  **Create a `.env` file:**
    Create a file named `.env` in the `server/` directory and add the following:

PORT=5000

MONGO_URI=mongodb://localhost:27017/taskmanager


    *Ensure MongoDB is running on your system or update `MONGO_URI` accordingly.*

4.  **Run the server:**
    *   **Development mode (with nodemon):**

npm run dev


    *   **Production mode:**

npm start



The server will run on the port specified in your `.env` file (default: `http://localhost:5000`).

## API Endpoints

| Method | Endpoint      | Description                  | Request Body (JSON)                                |
| :----- | :------------ | :--------------------------- | :------------------------------------------------- |
| `GET`  | `/api/tasks`  | Get all tasks                | None                                               |
| `POST` | `/api/tasks`  | Create a new task            | `{ "description": "New task description" }`        |
| `PUT`  | `/api/tasks/:id` | Update a task (e.g., toggle complete) | `{ "completed": true }` or `{ "description": "Updated desc" }` |
| `DELETE`| `/api/tasks/:id` | Delete a task                | None                                               |

---
  • Explanation: Provides essential information about the backend, including setup instructions, how to run it, and documentation for the API endpoints.

5. server/config/db.js


const mongoose = require('mongoose');

const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI);
    console.log(`MongoDB Connected: ${conn.connection.host}`);
  } catch (error) {
    console.error(`Error: ${error.message}`);
    process.exit(1); // Exit process with failure
  }
};

module.exports = connectDB;
  • Explanation:

* Imports mongoose for database interaction.

* connectDB function attempts to connect to MongoDB using the MONGO_URI from environment variables.

* Logs success or error messages to the console.

* process.exit(1) ensures the application exits if the database connection fails, which is critical for preventing the server from running without a database.

6. server/models/Task.js


const mongoose = require('mongoose');

const TaskSchema = new mongoose.Schema({
  description: {
    type: String,
    required: [true, 'Please add a task description'],
    trim: true,
    maxlength: [100, 'Description cannot be more than 100 characters']
  },
  completed: {
    type: Boolean,
    default: false
  },
  createdAt: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model('Task', TaskSchema);
  • Explanation:

* Defines the Mongoose schema for a Task.

* description: String, required, trimmed, and has a max length.

* completed: Boolean, defaults to false.

* createdAt: Date, defaults to the current timestamp.

* module.exports: Exports the Task model, making it available for use in other parts of the application (e.g., routes).

7. server/routes/taskRoutes.js


const express = require('express');
const router = express.Router();
const Task = require('../models/Task'); // Import the Task model

// @desc    Get all tasks
// @route   GET /api/tasks
// @access  Public
router.get('/', async (req, res) => {
  try {
    const tasks = await Task.find();
    res.status(200).json(tasks);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// @desc    Create a new task
// @route   POST /api/tasks
// @access  Public
router.post('/', async (req, res) => {
  const { description } = req.body;

  if (!description) {
    return res.status(400).json({ message: 'Task description is required' });
  }

  const task = new Task({
    description
  });

  try {
    const newTask = await task.save();
    res.status(201).json(newTask);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// @desc    Get single task
// @route   GET /api/tasks/:id
// @access  Public
router.get('/:id', async (req, res) => {
  try {
    const task = await Task.findById(req.params.id);
    if (!task) {
      return res.status(404).json({ message: 'Task not found' });
    }
    res.status(200).json(task);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// @desc    Update a task (e.g., toggle completed, update description)
// @route   PUT /api/tasks/:id
// @access  Public
router.put('/:id', async (req, res) => {
  try {
    const task = await Task.findById(req.params.id);
    if (!task) {
      return res.status(404).json({ message: 'Task not found' });
    }

    // Update fields if provided in the request body
    if (req.body.description != null) {
      task.description = req.body.description;
    }
    if (req.body.completed != null) {
      task.completed = req.body.completed;
    }

    const updatedTask = await task.save(); // Save the updated task
    res.status(200).json(updatedTask);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// @desc    Delete a task
// @route   DELETE /api/tasks/:id
// @access  Public
router.delete('/:id', async (req, res) => {
  try {
    const task = await Task.findByIdAndDelete(req.params.id); // Use findByIdAndDelete for direct deletion
    if (!task) {
      return res.status(404).json({ message: 'Task not found' });
    }
    res.status(200).json({ message: 'Task removed' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
  • Explanation:

* Sets up Express Router to define API endpoints.

* GET /api/tasks: Fetches all tasks from the database.

* POST /api/tasks: Creates a new task. Requires description in the request body. Includes basic validation.

* GET /api/tasks/:id: Fetches a single task by its ID.

* PUT /api/tasks/:id: Updates an existing task by ID. Can update description or completed status.

*`DELETE /

websitebuilder Output

Step 3 of 3: Full-Stack Website Deployment

This document outlines the comprehensive process for deploying your full-stack website, transforming your developed application into a live, accessible product. This step covers the transition from local development to a production environment, ensuring your frontend, backend, and database are securely hosted, performant, and available to your users.


1. Introduction to Deployment

Congratulations on building your full-stack website! This final step, "Deploy," is crucial for making your application publicly available. Deployment involves packaging your code, provisioning servers or services, configuring network settings, and ensuring all components (frontend, backend, database) communicate effectively in a production environment. Our goal is to achieve a robust, scalable, and secure deployment.


2. Pre-Deployment Checklist

Before initiating the deployment process, ensure the following critical items are addressed:

  • Code Readiness:

* All Features Complete: Verify that all planned features for the initial launch are implemented and thoroughly tested.

* Code Review: Conduct a final code review to catch any potential issues, enforce coding standards, and improve maintainability.

* Tests Passed: All unit, integration, and end-to-end tests must pass successfully.

* Dependencies Updated: Ensure all project dependencies are up-to-date and compatible.

* Dead Code Removed: Eliminate any unused code, libraries, or assets to reduce bundle size and complexity.

  • Environment Variables:

* Production Configuration: Create a separate .env.production (or similar) file or configuration method for production-specific environment variables (e.g., API keys, database connection strings, JWT secrets).

Secure Storage: Ensure sensitive environment variables are not* committed to version control and are securely managed by your chosen deployment platform.

  • Database Preparation:

* Schema & Migrations: Confirm your database schema is finalized and all necessary migrations are ready to be applied to the production database.

* Seed Data (Optional): If your application requires initial data, prepare scripts or methods to populate the production database.

* Backup Strategy: Plan for regular database backups.

  • Build Artifacts:

* Frontend Build: Ensure your frontend project can be successfully built into optimized static assets (e.g., using npm run build or yarn build).

* Backend Build (if applicable): If your backend uses a compiled language (e.g., Java, Go) or transpiled language (e.g., TypeScript), ensure the production build process is verified.

  • Domain Name:

* Acquired & Configured: Purchase and configure your desired domain name (e.g., yourwebsite.com).

* DNS Access: Ensure you have access to your domain registrar's DNS settings to point to your deployed services.

  • SSL Certificates:

* HTTPS Enabled: Plan to enable HTTPS for all traffic to ensure secure communication. Most modern hosting platforms provide free SSL certificates (e.g., Let's Encrypt) or integrate with certificate providers.


3. Deployment Strategy and Platform Selection

Choosing the right deployment platforms is critical for performance, scalability, and cost-effectiveness. We recommend a common and robust setup:

  • Frontend Hosting (Static Assets):

* Recommendation: Vercel or Netlify for their ease of use, built-in CI/CD, global CDNs, and free SSL. Alternatively, AWS S3 + CloudFront for highly scalable and customizable solutions.

* Why: These platforms are optimized for serving static files quickly and efficiently worldwide.

  • Backend Hosting (API Server):

* Recommendation: Render, Heroku, or AWS Elastic Beanstalk (PaaS - Platform as a Service) for managed services that simplify server management, scaling, and deployments. For more control or custom environments, a VPS (Virtual Private Server) like DigitalOcean or AWS EC2 with Docker can be used.

* Why: PaaS solutions abstract away much of the underlying infrastructure, allowing you to focus on your application code. They offer features like automatic scaling, load balancing, and logging.

  • Database Hosting:

* Recommendation: Managed Database Services like AWS RDS (PostgreSQL/MySQL), Google Cloud SQL, or Render Managed Databases.

* Why: Managed services handle database backups, patching, scaling, and high availability, significantly reducing operational overhead.


4. Recommended Deployment Flow (Actionable Steps)

This section provides a step-by-step guide for deploying your full-stack application using a common combination of platforms (e.g., React Frontend, Node.js Backend, PostgreSQL Database).

4.1. Database Setup (e.g., AWS RDS PostgreSQL)

  1. Provision Database Instance:

* Go to your chosen cloud provider's console (e.g., AWS, GCP, Azure, Render).

* Navigate to the managed database service (e.g., AWS RDS).

* Create a new PostgreSQL (or your chosen database type) instance.

* Key Configurations:

* Instance Size: Start with a smaller instance and scale up as needed.

* Database Name: e.g., yourwebappdb

* Master Username & Password: Store these securely.

Public Accessibility: Set to No for production (access via private network or VPC). If your backend is not* in the same VPC, you might need to configure security groups carefully or use a VPN/peering.

Security Group/Firewall: Configure inbound rules to allow traffic only* from your backend server's IP address range or security group.

  1. Apply Migrations:

* Connect to the newly provisioned database using a client (e.g., DBeaver, pgAdmin) or your backend's migration tools (e.g., Knex.js, TypeORM, Prisma).

* Execute your database migration scripts to create the necessary tables and schema.

* (Optional) Run seed scripts to populate initial data.

4.2. Backend Deployment (e.g., Node.js on Render)

  1. Prepare Backend for Production:

* Environment Variables: Ensure your backend code reads environment variables for sensitive data (database URL, API keys, port, etc.).


        // Example: Node.js
        const PORT = process.env.PORT || 5000;
        const DATABASE_URL = process.env.DATABASE_URL;
        // ...

CORS Configuration: Configure CORS (Cross-Origin Resource Sharing) headers to allow requests only* from your frontend's production domain.


        // Example: Express.js CORS configuration
        const cors = require('cors');
        app.use(cors({
            origin: 'https://yourfrontenddomain.com', // Replace with your actual frontend domain
            methods: ['GET', 'POST', 'PUT', 'DELETE'],
            credentials: true
        }));

* Build Script (if applicable): If you're using TypeScript or another transpiled language, ensure your package.json has a build script that compiles your code for production.

* Start Script: Ensure your package.json has a start script that runs your production-ready backend code (e.g., node dist/server.js or node server.js).

  1. Deploy to Render:

* Connect Repository: Log in to Render, connect your Git repository (GitHub, GitLab, Bitbucket).

* Create New Web Service: Select "New Web Service."

* Configure Service:

* Name: Give your service a descriptive name.

* Root Directory: If your backend is in a monorepo, specify the subdirectory.

* Build Command: e.g., npm install && npm run build (if applicable)

* Start Command: e.g., npm start

* Environment: Set the Node.js version.

Environment Variables: Add all production environment variables (e.g., DATABASE_URL, JWT_SECRET, PORT). Crucially, the DATABASE_URL will connect to your newly provisioned managed database.*

* Instance Type: Choose an appropriate plan (e.g., "Starter" for initial deployment).

* Deploy: Render will automatically build and deploy your service. It will provide a public URL (e.g., your-backend-service.onrender.com).

4.3. Frontend Deployment (e.g., React on Vercel)

  1. Prepare Frontend for Production:

API Endpoint Configuration: Update your frontend code to point to your deployed backend API URL*. This is typically done using environment variables.


        // Example: React with .env file
        // In .env.production:
        // REACT_APP_API_URL=https://your-backend-service.onrender.com
        // In your component:
        const API_URL = process.env.REACT_APP_API_URL;
        fetch(`${API_URL}/api/data`).then(...);

* Build Script: Ensure your package.json has a build script that generates optimized static assets (e.g., react-scripts build).

  1. Deploy to Vercel:

* Connect Repository: Log in to Vercel, connect your Git repository.

* Import Project: Select "New Project" and import your frontend repository.

* Configure Project:

* Root Directory: If your frontend is in a monorepo, specify the subdirectory.

* Framework Preset: Vercel usually auto-detects (e.g., Create React App, Next.js, Vue).

* Build & Output Settings: Vercel typically configures these automatically for common frameworks.

* Environment Variables: Add REACT_APP_API_URL (or equivalent) with the full URL of your deployed backend service.

* Deploy: Vercel will build your frontend and deploy it to their CDN, providing a preview URL.

4.4. Domain and DNS Configuration

  1. Backend Domain (Optional but Recommended):

* If you want a custom domain for your backend API (e.g., api.yourwebsite.com), go to your backend hosting platform (e.g., Render) and add a custom domain.

* You'll be provided with DNS records (e.g., CNAME) to add at your domain registrar.

  1. Frontend Domain:

* In your frontend hosting platform (e.g., Vercel), navigate to your project settings and add your custom domain (e.g., yourwebsite.com).

* Vercel will provide you with DNS records (e.g., A records, CNAME records) to configure at your domain registrar.

* Update DNS Records: Go to your domain registrar (e.g., GoDaddy, Namecheap, Cloudflare) and update the DNS records as provided by your hosting platforms.

* Propagation: DNS changes can take a few minutes to up to 48 hours to propagate globally.

4.5. SSL/HTTPS Configuration

  • Both Vercel and Render (and most modern hosting platforms) automatically provision and renew SSL certificates (via Let's Encrypt) for custom domains. Ensure this is enabled in your project settings.
  • Verify that your website is accessible via https:// and that the padlock icon appears in the browser.

5. Post-Deployment Verification & Maintenance

Once deployed, it's crucial to verify everything is working correctly and establish ongoing maintenance practices.

  • Initial Verification:

* Access Website: Open https://yourwebsite.com in various browsers.

* Test Core Functionality: Thoroughly test all user flows, forms, data submission, and API interactions.

* Check Console/Network: Open browser developer tools to check for any frontend errors or failed network requests.

* Backend Logs: Monitor your backend logs for any errors or warnings.

  • Monitoring & Logging:

* Enable Logging: Ensure comprehensive logging is enabled for both frontend (e.g., Sentry for error tracking) and backend (platform-provided logs, or dedicated services like Loggly, Datadog).

* Performance Monitoring: Set up tools to monitor application performance (e.g., Lighthouse for frontend, New Relic/Datadog for backend).

* Uptime Monitoring: Use services like UptimeRobot to notify you if your site goes down.

  • Security Best Practices:

* Regular Updates: Keep all dependencies and server software updated to patch vulnerabilities.

* Input Validation: Ensure all user input is validated on both frontend and backend.

* Rate Limiting: Implement rate limiting on your API to prevent abuse.

* Secret Management: Never hardcode sensitive information; use environment variables or dedicated secret management services.

* Firewall Rules: Regularly review and tighten firewall rules for your database and backend servers.

  • Backups:

* Database Backups: Confirm your managed database service is performing regular, automated backups. Understand the recovery process.

* Code Backups: Your Git repository serves as a primary code backup.

  • Continuous Integration/Continuous Deployment (CI/CD):

* Automate Deployments: Configure your hosting platforms (Vercel, Render) to automatically deploy new changes whenever you push to your main branch (e.g., main or master). This streamlines updates and reduces manual errors.

* Automated Tests: Integrate automated tests into your CI/CD pipeline to ensure that new code doesn't break existing functionality before deployment.


6. Next Steps

Your full-stack website is now live!

  • Final Review: Conduct a final comprehensive review of all functionalities in the live environment.
  • Share with Users: Announce your website and begin gathering user feedback.
  • Ongoing Maintenance: Establish a routine for monitoring, updating, and backing up your application.
  • Future Enhancements: Start planning for
full_stack_website.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);}});}