API Rate Limiter
Run ID: 69cb1fbd61b1021a29a8617b2026-03-31Development
PantheraHive BOS
BOS Dashboard

This deliverable provides a comprehensive output for generating production-ready code for an API Rate Limiter, focusing on key strategies, implementation details, and professional considerations.


API Rate Limiter: Code Generation & Implementation Guide

This document details the design, implementation, and integration of robust API Rate Limiting mechanisms. It includes clean, well-commented, production-ready Python code demonstrating two common strategies, along with a guide for integration and critical considerations for deployment in a production environment.


1. Introduction to API Rate Limiting

API rate limiting is a crucial component for managing resource consumption, preventing abuse, and ensuring the stability and availability of your services. By restricting the number of requests a user or client can make within a defined timeframe, you can:

2. Core Rate Limiting Strategies

Several algorithms exist for implementing rate limiting, each with its own advantages and trade-offs. We will focus on two popular and effective strategies for our code implementation, and briefly mention others.

2.1. Fixed Window Counter

Concept:

The fixed window counter strategy divides time into fixed-size windows (e.g., 60 seconds). For each window, it maintains a counter for each client. When a request arrives, the counter for the current window is incremented. If the counter exceeds the allowed limit for that window, the request is rejected.

Pros:

Cons:

2.2. Sliding Window Log (or Timestamp-based)

Concept:

Instead of a single counter, this strategy keeps a log (a sorted list) of timestamps for each client's successful requests. When a new request arrives, the system first prunes all timestamps from the log that fall outside the current window (e.g., older than 60 seconds ago). Then, it checks if the number of remaining timestamps in the log (including the current request's timestamp) exceeds the allowed limit. If it does, the request is rejected; otherwise, the current request's timestamp is added to the log.

Pros:

Cons:

2.3. Other Notable Strategies (Brief Mention)


3. API Rate Limiter Implementation (Python)

We will provide a modular Python implementation that can be easily integrated into various applications (e.g., Flask, FastAPI, Django). The code includes both FixedWindowRateLimiter and SlidingWindowLogRateLimiter for demonstration.

3.1. Prerequisites

3.2. Core Rate Limiter Code (rate_limiter.py)

text • 209 chars
#### 3.3. Example Usage (Standalone & Flask Integration)

This section demonstrates how to use the implemented rate limiters both as standalone components and integrated into a simple Flask web application.

Sandboxed live preview

API Rate Limiter: Comprehensive Study Plan

This document outlines a detailed and actionable study plan for mastering API Rate Limiting, covering fundamental concepts, advanced algorithms, system design, and practical implementation. This plan is structured to provide a thorough understanding, enabling you to design, implement, and maintain robust rate-limiting solutions.


1. Introduction & Overview

API Rate Limiting is a critical component in modern distributed systems, essential for ensuring stability, preventing abuse, and managing resource consumption. It controls the number of requests a user or client can make to an API within a given timeframe. This study plan will guide you through the theoretical underpinnings and practical applications of various rate-limiting strategies.


2. Learning Objectives

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

  • Understand Necessity: Articulate the core reasons for implementing API rate limiting, including security, resource management, and cost control.
  • Master Algorithms: Differentiate, explain, and compare the strengths and weaknesses of key rate-limiting algorithms (e.g., Leaky Bucket, Token Bucket, Fixed Window, Sliding Window Log, Sliding Window Counter).
  • Design Distributed Systems: Design scalable and resilient distributed rate-limiting systems, addressing challenges like consistency, synchronization, and fault tolerance.
  • Select Technologies: Identify and evaluate appropriate technologies and tools for implementing rate limiters (e.g., Redis, Nginx, Envoy, specific programming language libraries).
  • Implement Solutions: Develop functional prototypes of rate limiters using a chosen programming language and data store.
  • Apply Best Practices: Implement robust error handling (e.g., HTTP 429, Retry-After header), comprehensive monitoring, and effective alerting strategies.
  • Address Advanced Concepts: Analyze advanced topics such as dynamic rate limiting, adaptive algorithms, bot detection, and integration with business logic (e.g., tiered access).
  • Evaluate Trade-offs: Critically assess the trade-offs involved in different rate-limiting designs, considering factors like accuracy, resource utilization, and complexity.

3. Weekly Schedule

This 4-week intensive study plan is designed for a dedicated learner, assuming approximately 10-15 hours of study per week, including reading, watching, and hands-on practice.

Week 1: Fundamentals & Basic Algorithms

  • Focus: Core concepts of rate limiting, its importance, and an in-depth dive into foundational algorithms.
  • Topics:

* What is API Rate Limiting? Why is it crucial? (Security, DDoS, resource protection, cost management).

* Types of limits: Request count, bandwidth, concurrency.

* Leaky Bucket Algorithm: Principles, implementation details (queue), pros & cons (smooth output rate, burst handling).

* Token Bucket Algorithm: Principles, implementation details (token generation, bucket size), pros & cons (burst allowance, resource efficiency).

* Comparison of Leaky Bucket vs. Token Bucket.

* Basic in-memory implementation examples.

  • Hands-on: Implement a simple in-memory Leaky Bucket or Token Bucket rate limiter in your preferred programming language.

Week 2: Advanced Algorithms & Distributed Systems

  • Focus: Exploring more complex algorithms and addressing the challenges of rate limiting in distributed environments.
  • Topics:

* Fixed Window Counter Algorithm: Principles, implementation, pros & cons (window edge problem).

* Sliding Window Log Algorithm: Principles, implementation (timestamps), pros & cons (memory usage for large windows).

* Sliding Window Counter Algorithm: Principles, implementation (combining fixed window with weighted average), pros & cons (accuracy vs. memory).

* Distributed Rate Limiting Challenges: Consistency, synchronization across multiple instances, race conditions.

* Data stores for distributed rate limiting: Redis (hashes, sorted sets, lists), Memcached.

* Introduction to atomic operations and scripting in Redis (e.g., Lua scripts).

  • Hands-on: Implement a basic distributed rate limiter using Redis for either the Fixed Window or Sliding Window Counter algorithm.

Week 3: Design & Implementation Patterns

  • Focus: Understanding where and how to integrate rate limiters into a system architecture, and practical considerations for production environments.
  • Topics:

* Placement Strategies: API Gateway (e.g., Nginx, Envoy, AWS API Gateway, Kong), Load Balancer, Application Layer (middleware), Service Mesh.

* Common Tools & Libraries:

* Nginx limit_req module.

* Envoy Proxy rate limiting filter.

* Language-specific libraries (e.g., ratelimiter in Python, guava-rate-limiter in Java, go-rate in Go).

* Error Handling: HTTP 429 Too Many Requests, Retry-After header, custom error messages.

* Monitoring & Alerting: Key metrics to track (requests blocked, requests processed, latency), setting up alerts (e.g., Prometheus, Grafana).

* Logging strategies for rate limiting events.

  • Hands-on: Configure Nginx or Envoy for basic rate limiting. Integrate a chosen rate-limiting library into a simple web application (e.g., Flask/Express/Spring Boot API).

Week 4: Advanced Topics, Security & Case Studies

  • Focus: Delving into sophisticated rate-limiting techniques, security considerations, and real-world examples.
  • Topics:

* Security Aspects: DoS/DDoS protection, bot detection and mitigation, identifying malicious patterns.

* Dynamic Rate Limiting: Adapting limits based on system load, user behavior, or resource availability.

* Adaptive Algorithms: Machine learning approaches for anomaly detection and rate adjustment.

* Business Logic Integration: User tiers (free vs. premium), subscription models, API key management.

* Fairness and Prioritization: How to ensure fair access and prioritize critical requests.

* Case Studies: Analyze how major companies (e.g., Twitter, Stripe, GitHub) implement and manage their API rate limits.

* Idempotency and rate limiting considerations.

  • Hands-on: Design a more complex rate-limiting system for a hypothetical scenario (e.g., an e-commerce API with different user tiers). Implement a feature like dynamic adjustment or tiered limits.

4. Recommended Resources

Articles & Blogs:

  • System Design Interview – API Rate Limiter: Search for "System Design Interview Rate Limiter" on platforms like Educative.io, GeeksforGeeks, or Medium for comprehensive guides.
  • Cloudflare Blog: Search for "Cloudflare rate limiting" for insights into large-scale distributed rate limiting.
  • Stripe API Documentation: Review their excellent documentation on how they handle rate limits and best practices for integrators.
  • Redis Documentation: Explore INCR, EXPIRE, ZADD, ZCOUNT, ZREMRANGEBYSCORE commands, and Lua scripting for atomic operations.
  • Nginx/Envoy Documentation: Understand their respective rate-limiting modules and filters.

Books:

  • "System Design Interview – An Insider's Guide" by Alex Xu (Volume 1 & 2): Chapter(s) on Rate Limiter design.
  • "Designing Data-Intensive Applications" by Martin Kleppmann: Provides foundational knowledge on distributed systems, consistency, and fault tolerance, which are crucial for distributed rate limiting.

Videos & Courses:

  • YouTube: Search for "API Rate Limiter System Design" for various explanations and whiteboard sessions. Channels like "System Design Interview," "Gaurav Sen," or "Tech Dummies" often have good content.
  • Online Courses: Platforms like Coursera, Udemy, or Udacity may offer specific modules on system design that include rate limiting.

Tools & Technologies:

  • Programming Languages: Python, Java, Go, Node.js (choose one for implementation).
  • Data Store: Redis (essential for distributed rate limiting).
  • Proxy/Gateway: Nginx, Envoy Proxy, Kong Gateway.
  • Containerization: Docker (for easily setting up Redis and your application).

5. Milestones

Achieving these milestones will signify your progress and mastery of the subject matter.

  • End of Week 1:

* Can clearly explain Leaky Bucket and Token Bucket algorithms, including their trade-offs.

Successfully implemented a basic in-memory* rate limiter.

* Identified common use cases for each basic algorithm.

  • End of Week 2:

* Can clearly explain Fixed Window, Sliding Window Log, and Sliding Window Counter algorithms.

* Understands the key challenges of distributed rate limiting (consistency, race conditions).

Successfully implemented a basic distributed* rate limiter using Redis for one algorithm.

  • End of Week 3:

* Can articulate where to place a rate limiter within a system architecture and justify the choice.

* Demonstrated proficiency in configuring a proxy (Nginx/Envoy) for basic rate limiting.

* Defined essential monitoring metrics and error handling strategies for a production system.

  • End of Week 4:

* Understands advanced concepts like dynamic rate limiting, adaptive algorithms, and security implications.

* Completed a small project integrating a chosen rate-limiting strategy into a simple API with appropriate error handling and logging.

* Can confidently discuss the architectural choices, trade-offs, and scaling considerations for a robust API rate limiter.


6. Assessment Strategies

To effectively gauge your understanding and practical skills, the following assessment strategies are recommended:

  • Weekly Self-Quizzes/Flashcards: Create short questions or flashcards covering definitions, algorithm steps, pros/cons, and distributed challenges.
  • Coding Challenges:

* Implement each core rate-limiting algorithm from scratch, focusing on correctness and efficiency.

* Develop a minimal API endpoint and add rate-limiting middleware to it.

* Write Redis Lua scripts for atomic rate-limiting operations.

  • System Design Exercises:

* Given a specific scenario (e.g., "Design a rate limiter for a popular social media API"), sketch out the architecture, choose algorithms, and justify your decisions.

* Critique existing rate-limiter designs, identifying potential weaknesses or areas for improvement.

  • Code Review Simulation: Review a provided implementation of a rate limiter, identifying bugs, performance bottlenecks, or architectural flaws.
  • Final Project: Build a small, functional API (e.g., a simple URL shortener or a weather API) and implement a comprehensive rate-limiting solution, including:

* Choice of algorithm(s).

* Distributed state management (e.g., Redis).

* Proper HTTP status codes and Retry-After headers.

* Basic logging and monitoring hooks.

* Consideration for different user tiers or API keys.

  • Discussion & Presentation: Prepare to explain and defend your design choices, compare different algorithms, and discuss the trade-offs involved in various rate-limiting scenarios.

By diligently following this study plan, you will acquire a profound and practical understanding of API Rate Limiting, a highly sought-after skill in modern software engineering.

python

--- Example Usage (example_app.py) ---

from flask import Flask, request, jsonify, g

import time

import threading

from rate_limiter import FixedWindowRateLimiter, SlidingWindowLogRateLimiter, BaseRateLimiter

app = Flask(__name__)

Initialize rate limiters globally

For a real application, these might be configured via environment variables

or a configuration file.

fixed_limiter = FixedWindowRateLimiter(limit=5, window_size=60) # 5 requests per 60 seconds

sliding_limiter = SlidingWindowLogRateLimiter(limit=3, window_size=30) # 3 requests per 30 seconds

--- Middleware/Decorator for Rate Limiting ---

def rate_limit_middleware(limiter: BaseRateLimiter):

"""

A decorator/middleware factory for applying rate limiting to Flask routes.

"""

def decorator(f):

def wrapper(args, *kwargs):

# In a real app, you'd extract a unique client identifier:

# - request.remote_addr (IP address)

gemini Output

API Rate Limiter: Comprehensive Overview and Implementation Guide

This document provides a detailed, professional overview of API Rate Limiters, outlining their critical importance, underlying mechanisms, implementation strategies, and best practices. This deliverable is designed to equip your team with a thorough understanding necessary for effective design, deployment, and management of API rate limiting solutions.


1. Introduction to API Rate Limiters

An API Rate Limiter is a mechanism that controls the number of requests a user or client can make to an API within a given timeframe. Its primary purpose is to prevent misuse, ensure fair resource allocation, and maintain the stability and availability of your services. Without effective rate limiting, APIs are vulnerable to various forms of abuse, ranging from denial-of-service (DoS) attacks to excessive data scraping, which can degrade performance, increase operational costs, and compromise security.

2. Core Concepts and Principles

At its heart, an API Rate Limiter operates by:

  • Identifying the Caller: Determining who is making the request. This can be based on:

* IP Address: Common for public-facing APIs but can be problematic with shared IPs (NAT, proxies).

* API Key/Token: Unique identifiers assigned to specific applications or users.

* User ID/Session Token: After authentication, linking requests to a specific user account.

  • Defining Limits: Establishing policies for the maximum number of requests allowed within a specific time window (e.g., 100 requests per minute, 5000 requests per hour). Limits can be global, per-endpoint, or per-method.
  • Tracking Requests: Counting and recording requests made by identified callers within their respective time windows. This typically involves a persistent data store like Redis or a database.
  • Enforcing Limits: When a caller exceeds their defined limit, the rate limiter takes action, typically:

* Denying the Request: Returning an HTTP 429 Too Many Requests status code.

* Adding Retry-After Header: Providing guidance to the client on when they can safely retry their request.

* Logging the Event: Recording the violation for monitoring and analysis.

3. Benefits of Implementing API Rate Limiting

Implementing a robust API rate limiting strategy yields significant advantages:

  • Enhanced Security:

* DDoS Protection: Mitigates Distributed Denial-of-Service attacks by preventing a flood of requests from overwhelming your servers.

* Brute-Force Attack Prevention: Thwarts attempts to guess credentials (passwords, API keys) by limiting login attempts.

* Data Scraping Prevention: Deters bots from rapidly extracting large volumes of data.

  • Improved Stability and Reliability:

* Resource Protection: Prevents individual users or applications from monopolizing server resources (CPU, memory, database connections), ensuring consistent performance for all legitimate users.

* Service Availability: Maintains uptime and responsiveness by protecting backend services from overload.

  • Cost Management:

* Reduced Infrastructure Costs: Prevents unnecessary scaling of infrastructure due to excessive or abusive traffic.

* Optimized Resource Utilization: Ensures that your existing resources are used efficiently.

  • Fair Usage and User Experience:

* Equitable Access: Guarantees that all users have fair access to API resources, preventing a few heavy users from degrading the experience for others.

* Predictable Performance: Users can expect consistent API response times under normal load.

  • Monetization and Tiering:

* Service Differentiation: Enables the creation of different API access tiers (e.g., free, premium, enterprise) with varying rate limits, supporting monetization strategies.

4. Common Rate Limiting Algorithms

Different algorithms offer varying trade-offs in terms of accuracy, resource usage, and ability to handle bursts.

  • 4.1. Fixed Window Counter

* How it works: Divides time into fixed-size windows (e.g., 60 seconds). Each request increments a counter for the current window. If the counter exceeds the limit within that window, subsequent requests are blocked.

* Pros: Simple to implement and understand.

* Cons: Can allow "bursts at the edge." For example, if the limit is 100 req/min, a user could make 100 requests at the very end of one window and another 100 requests at the very beginning of the next, effectively making 200 requests in a very short period.

  • 4.2. Sliding Window Log

* How it works: For each client, stores a timestamp for every request made. To check if a request is allowed, it counts all timestamps within the current sliding window (e.g., the last 60 seconds from the current time).

* Pros: Highly accurate and smooth, as it considers the exact time of each request.

* Cons: High memory consumption, especially for high request volumes, as it needs to store a log of timestamps for each client.

  • 4.3. Sliding Window Counter (or Sliding Log Counter)

* How it works: A hybrid approach that combines elements of fixed window and sliding log. It calculates the weighted average of the request counts from the previous fixed window and the current fixed window. For example, to check the last 60 seconds, it might consider 80% of the previous window's count (if 80% of it overlaps) and 20% of the current window's count.

* Pros: Offers a good balance between accuracy and memory efficiency compared to the sliding log. Mitigates the "burst at the edge" problem better than the fixed window.

* Cons: Less precise than the sliding window log but significantly more efficient.

  • 4.4. Token Bucket

* How it works: Imagine a bucket that holds "tokens." Tokens are added to the bucket at a fixed rate (e.g., 100 tokens per minute), up to a maximum capacity. Each API request consumes one token. If a request arrives and the bucket is empty, the request is denied.

* Pros: Allows for bursts of requests (up to the bucket's capacity) and smooths out traffic over time. Excellent for handling uneven request patterns.

* Cons: Can be slightly more complex to implement than fixed window.

  • 4.5. Leaky Bucket

* How it works: Imagine a bucket with a hole at the bottom. Requests arrive and are added to the bucket. Requests "leak" out of the bucket at a constant rate, which is the maximum processing rate. If the bucket overflows (i.e., too many requests arrive too quickly), new requests are dropped.

* Pros: Smooths out the request rate, ensuring a constant output rate. Good for protecting backend services that have a fixed processing capacity.

* Cons: Does not allow for bursts. Requests might experience delays if the bucket is filling up.

5. Implementation Strategies

The choice of where to implement rate limiting depends on your architecture and specific needs.

  • 5.1. Client-Side Limiting (Discouraged for Security)

* Description: Implemented within the client application (e.g., mobile app, web browser).

* Pros: Can reduce unnecessary requests to the server.

Cons: Easily bypassed by malicious users. Should never be the sole rate limiting mechanism for security-sensitive operations.*

  • 5.2. Server-Side Limiting (Recommended)

* 5.2.1. API Gateway / Reverse Proxy Level:

* Description: Implemented at the edge of your network, using an API Gateway (e.g., AWS API Gateway, Azure API Management, Kong, Apigee) or a reverse proxy (e.g., Nginx, Envoy).

* Pros: Centralized control, high performance, offloads rate limiting logic from backend services, protects all downstream services. Ideal for microservices architectures.

* Cons: Requires careful configuration and scaling of the gateway itself.

* 5.2.2. Application Layer:

* Description: Implemented directly within your application code.

* Pros: Highly flexible, allows for granular, context-aware limiting (e.g., limiting based on specific user roles or data in the request body).

* Cons: Adds complexity to application logic, consumes application resources, requires consistent implementation across all instances of your application.

* 5.2.3. Distributed Rate Limiting (for Scalability):

* Description: For applications running on multiple instances (e.g., microservices, autoscaled web servers), rate limit counters must be synchronized across all instances. This typically involves using a shared, high-performance data store like Redis or Memcached.

* Pros: Ensures consistent rate limiting across a distributed system, scalable.

* Cons: Introduces dependency on an external data store, requires careful management of data consistency and latency.

6. Key Considerations and Best Practices

  • Granularity: Decide what to limit: per IP, per user, per API key, per endpoint, per method, or a combination. More granular limits offer better control but add complexity.
  • Informative Headers: Use standard HTTP headers to communicate rate limit status to clients:

* X-RateLimit-Limit: The maximum number of requests allowed in the current window.

* X-RateLimit-Remaining: The number of requests remaining in the current window.

* X-RateLimit-Reset: The time (in UTC epoch seconds or human-readable format) when the current rate limit window resets.

* Retry-After: For 429 Too Many Requests responses, indicates how long the client should wait before making another request.

  • Error Handling: Return a clear HTTP 429 Too Many Requests status code with a descriptive error message. Encourage clients to implement exponential backoff with jitter for retries.
  • Bursting Allowance: For Token Bucket algorithms, configure a bucket capacity larger than the refill rate to allow legitimate bursts of activity.
  • Exemptions: Consider exempting internal services, trusted partners, or administrative tools from rate limits.
  • Logging and Monitoring:

* Log Rate Limit Breaches: Record instances where clients hit limits, including caller ID, endpoint, and timestamp.

* Monitor Metrics: Track requests per second, rate limit hits, error rates, and latency.

* Alerting: Set up alerts for sustained high rates of 429 errors or unusual traffic patterns.

  • Scalability: Ensure your rate limiting solution itself is scalable and does not become a bottleneck under heavy load.
  • Configuration Management: Make rate limits easily configurable, allowing for adjustments without code deployments.
  • Testing: Thoroughly test your rate limiting configuration under various load conditions to ensure it behaves as expected.
  • Graceful Degradation: Design your system to fail gracefully. If the rate limiter itself becomes unavailable, consider a fallback strategy (e.g., temporarily allow more requests, or prioritize critical endpoints).

7. Monitoring and Alerting

Effective monitoring is crucial for maintaining a healthy API and optimizing rate limits.

  • Key Metrics to Track:

* Total API requests (per minute/hour).

* Number of 429 Too Many Requests responses.

* X-RateLimit-Remaining values (to see how close clients are getting to limits).

* Latency of the rate limiting service itself.

* CPU/memory utilization of rate limiting infrastructure.

  • Tools:
api_rate_limiter.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);}});}