API Rate Limiter
Run ID: 69ccf6db3e7fb09ff16a6b0a2026-04-01Development
PantheraHive BOS
BOS Dashboard

This output delivers a comprehensive, production-ready code implementation for an API Rate Limiter, utilizing a robust Sliding Window Counter strategy with Redis for distributed state management and integrated into a Flask web application.


API Rate Limiter: Code Generation & Implementation

Overview

This deliverable provides a detailed and actionable solution for implementing an API Rate Limiter. The goal is to prevent abuse, ensure fair resource usage, and protect your backend services from being overwhelmed by excessive requests.

We have chosen a Sliding Window Counter algorithm, which offers a good balance between accuracy and efficiency, especially suitable for distributed environments. The implementation leverages Python for the application logic, Flask as a common web framework, and Redis as a high-performance, in-memory data store to manage rate limiting state across multiple application instances.

Rate Limiting Strategy: Sliding Window Counter

The Sliding Window Counter algorithm is an improvement over the simpler Fixed Window Counter. It works as follows:

  1. Time Window: A fixed duration (e.g., 60 seconds) is defined for the rate limit.
  2. Request Timestamps: For each client (identified by IP address, user ID, API key, etc.), the timestamp of every request within the current window is stored.
  3. Sliding Calculation: When a new request arrives:

* All timestamps older than the start of the current window (current time - window duration) are removed.

* The count of remaining timestamps (requests) is checked.

* If the count is below the allowed limit, the request is permitted, and its timestamp is added.

* If the count exceeds the limit, the request is denied.

Advantages:

Technology Stack

Implementation Details

Our implementation provides a flexible rate_limit decorator that can be applied to any Flask route. It identifies clients based on their IP address (though this can be customized to user IDs, API keys, etc.).

Key features:

Prerequisites

Before running the code, ensure you have the following installed:

  1. Python 3.x:
text • 320 chars
2.  **Redis Server:**
    *   Install Redis (e.g., `sudo apt-get install redis-server` on Ubuntu, or using Docker `docker run --name my-redis -p 6379:6379 -d redis`).
    *   Ensure the Redis server is running on `localhost:6379` (default).
3.  **Python Packages:** Install the necessary Python libraries using pip:
    
Sandboxed live preview

API Rate Limiter: Comprehensive Study Plan

This document outlines a detailed, actionable study plan for mastering API Rate Limiter concepts, design, and implementation. This plan is designed to provide a deep understanding of rate limiting, from fundamental algorithms to advanced distributed system design challenges.


1. Introduction and Overall Goal

API Rate Limiting is a critical component in modern distributed systems, essential for ensuring system stability, preventing abuse, managing costs, and enforcing fair usage policies. Without effective rate limiting, APIs can become vulnerable to denial-of-service attacks, resource exhaustion, and uncontrolled traffic spikes.

Overall Goal: By the end of this study plan, you will be able to:

  • Understand the fundamental principles and necessity of API rate limiting.
  • Identify, explain, and critically evaluate various rate limiting algorithms.
  • Design a scalable, robust, and performant distributed API rate limiting system.
  • Implement basic rate limiting mechanisms and integrate them into existing architectures.
  • Analyze and troubleshoot common challenges in rate limiter deployment and operation.

2. Weekly Schedule

This study plan is structured over four weeks, with each week building upon the previous one. Allocate approximately 5-10 hours per week for focused study, including reading, watching videos, and practical exercises.

Week 1: Fundamentals and Basic Concepts

Focus: Understand what rate limiting is, why it's crucial, and explore the foundational algorithms.

  • Day 1-2: Introduction to Rate Limiting

* What is API Rate Limiting?

* Why is it necessary? (Security, Cost Management, Resource Protection, Fair Usage)

* Key metrics: requests per second (RPS), requests per minute (RPM), burst limits.

  • Day 3-4: Common Rate Limiting Algorithms - Part 1

* Fixed Window Counter: Mechanism, Pros, Cons, Edge Cases (bursts at window edges).

* Sliding Log: Mechanism, Pros, Cons, Data Storage requirements.

  • Day 5-7: Common Rate Limiting Algorithms - Part 2

* Sliding Window Counter: Mechanism, Pros, Cons, Comparison with Fixed Window.

* Token Bucket: Mechanism, Pros, Cons, Burst handling capabilities.

* Leaky Bucket: Mechanism, Pros, Cons, Comparison with Token Bucket.

  • Practical Exercise: Sketch out how each algorithm would handle a specific traffic pattern (e.g., a sudden burst followed by sustained traffic).

Week 2: Algorithm Deep Dive and Implementation Considerations

Focus: Gain a deeper understanding of algorithm mechanics, their trade-offs, and initial thoughts on implementation.

  • Day 1-2: Algorithm Comparison and Trade-offs

* Detailed comparison of all learned algorithms: Fixed Window, Sliding Log, Sliding Window Counter, Token Bucket, Leaky Bucket.

* Factors for comparison: accuracy, memory usage, CPU usage, burst tolerance, fairness.

* Scenario-based algorithm selection: When to use which algorithm?

  • Day 3-4: Data Structures and Storage for Rate Limiting

* In-memory counters vs. persistent storage.

* Using Redis for distributed counters and timestamps.

* Hashing techniques for client identification (IP, User ID, API Key).

  • Day 5-7: Basic Implementation Exercise (In-Memory)

* Choose one algorithm (e.g., Token Bucket or Fixed Window).

Implement a basic, in-memory* rate limiter in your preferred language (Python, Go, Java, Node.js).

* Test with simple scenarios to observe behavior.

  • Practical Exercise: Implement a basic rate limiter class/function.

Week 3: System Design & Advanced Topics

Focus: Transition from individual algorithms to designing a complete, scalable, and distributed rate limiting system.

  • Day 1-2: Distributed Rate Limiting Challenges

* Consistency models: eventual vs. strong consistency.

* Race conditions in distributed counters.

* Handling clock skew across distributed systems.

* Replication and High Availability.

  • Day 3-4: Designing a Distributed Rate Limiter

* Architecture components: Edge proxy (NGINX, Envoy), Centralized Rate Limiting Service, Data Store (Redis Cluster, Cassandra).

* Placement of the rate limiter: Gateway vs. Service Mesh vs. Application Layer.

* Sharding and partitioning strategies for rate limiting data.

  • Day 5-7: Advanced Concepts and Edge Cases

* Hierarchical Rate Limiting (user, endpoint, global).

* Handling bursts and grace periods.

* Client-side vs. Server-side Rate Limiting.

* Dynamic rate limits and configuration management.

* Throttling vs. Rate Limiting.

  • Practical Exercise: Sketch a high-level architecture diagram for a distributed rate limiter for a hypothetical e-commerce API.

Week 4: Practical Application and Case Studies

Focus: Apply learned knowledge to real-world scenarios, review existing solutions, and prepare for design discussions.

  • Day 1-2: Review of Existing Solutions

* NGINX rate limiting module.

* Envoy Proxy rate limiting filter.

* Cloud Provider solutions (AWS WAF, Google Cloud Endpoints, Azure API Management).

* Open-source rate limiting libraries/services.

  • Day 3-4: System Design Interview Scenarios

* Practice designing a rate limiter for specific scenarios (e.g., Twitter API, payment gateway, video streaming service).

* Focus on justifying algorithm choice, data store, scalability, and fault tolerance.

  • Day 5-7: Deep Dive into a Chosen Implementation or Library

* Pick one open-source rate limiter (e.g., a Go library, a Python Flask extension) or a cloud service.

* Read its documentation, understand its configuration, and try to integrate it into a simple application.

* Analyze its internal workings if source code is available.

  • Practical Exercise: Design a rate limiting system for an API that has both user-level and global limits, with different limits for authenticated vs. unauthenticated users.

3. Learning Objectives

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

  • Conceptual Understanding:

* Explain the "why" and "what" of API rate limiting.

* Differentiate between various rate limiting algorithms (Fixed Window, Sliding Log, Sliding Window Counter, Token Bucket, Leaky Bucket) and articulate their pros and cons.

* Understand the challenges of implementing rate limiters in distributed environments.

  • Design & Architecture:

* Design a scalable and fault-tolerant distributed API rate limiting system.

* Choose appropriate data stores and technologies for rate limiter implementation (e.g., Redis).

* Identify optimal placement for rate limiters within a system architecture (e.g., API Gateway, Service Mesh).

* Consider and address issues like consistency, concurrency, and high availability in rate limiter design.

  • Implementation & Evaluation:

* Implement basic in-memory rate limiting algorithms.

* Evaluate existing rate limiting solutions (e.g., NGINX, Envoy, cloud services) and their suitability for different use cases.

* Analyze trade-offs in terms of performance, cost, and complexity when selecting an implementation strategy.

  • Problem Solving:

* Troubleshoot common issues related to rate limiting (e.g., false positives, unexpected blocking).

* Formulate and justify design decisions for rate limiting in various real-world scenarios.


4. Recommended Resources

This list provides a curated selection of resources to support your learning journey.

  • Books:

* "System Design Interview – An Insider's Guide" by Alex Xu: Chapters specifically on "Design a Rate Limiter."

* "Designing Data-Intensive Applications" by Martin Kleppmann: Relevant sections on distributed systems, consistency, and fault tolerance.

  • Online Articles & Blogs:

* "How to design a distributed rate limiter?" (System Design Interview Blog): A foundational article.

* Stripe Engineering Blog: Search for articles on rate limiting and API design.

* Uber Engineering Blog: Search for their approach to rate limiting at scale.

* Medium Articles: Many excellent deep dives by engineers on specific algorithms and implementations (e.g., "Rate Limiting with Redis").

* Cloud Provider Documentation: AWS WAF, Google Cloud Endpoints, Azure API Management documentation on their rate limiting features.

  • Videos & Courses:

* Gaurav Sen (YouTube): "System Design: Rate Limiter" video.

* ByteByteGo (YouTube): "System Design: Rate Limiter" video and related content.

* Hussein Nasser (YouTube): Videos on Redis, distributed systems, and API Gateways often touch upon rate limiting.

* Educative.io / Grokking the System Design Interview: Look for the "Design a Rate Limiter" module.

  • Code Examples & Tools:

* GitHub Repositories: Search for "rate limiter golang," "rate limiter python," etc., to find open-source implementations.

* Redis: Essential for practical distributed rate limiting. Explore its commands and data structures (INCR, ZADD, ZRANGEBYSCORE).

* NGINX: Experiment with its limit_req_zone and limit_req directives.

* Envoy Proxy: Investigate its rate limit filter and external rate limit service integration.


5. Milestones

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

  • End of Week 1:

* Deliverable: A concise summary (1-2 pages) explaining the purpose of rate limiting and outlining the five core algorithms (Fixed Window, Sliding Log, Sliding Window Counter, Token Bucket, Leaky Bucket) with their main pros and cons.

  • End of Week 2:

Deliverable: Working code for an in-memory* rate limiter using at least one chosen algorithm (e.g., Token Bucket or Sliding Window Counter) in your preferred programming language. Include simple unit tests demonstrating its functionality.

  • End of Week 3:

Deliverable: A high-level architectural diagram and a brief design document (2-3 pages) for a distributed* API rate limiting system. This should include chosen algorithms, data store, and considerations for consistency, scalability, and fault tolerance.

  • End of Week 4:

* Deliverable: A detailed system design presentation (e.g., 10-15 slides or a comprehensive document) for a specific, complex API rate limiting scenario (e.g., "Design a rate limiter for a social media platform's posting API"). This should cover all aspects from algorithm choice to deployment and monitoring.


6. Assessment Strategies

Regular assessment is crucial for reinforcing learning and identifying areas for improvement.

  • Self-Assessment Quizzes:

* After each major topic (e.g., per algorithm, per distributed challenge), create 3-5 multiple-choice questions or short answer prompts to test your understanding.

* Review your answers against your notes and resources.

  • Coding Challenges:

* Implement different rate limiting algorithms.

* Extend your basic in-memory rate limiter to handle more complex rules (e.g., different limits for different user tiers).

* Integrate a Redis instance to make your rate limiter distributed.

  • System Design Exercises:

* Regularly practice drawing system design diagrams and articulating your design choices for various rate limiting scenarios.

Focus on explaining why* you chose a particular algorithm or data store.

  • Peer Review & Discussion:

* Discuss your designs and implementations with peers or mentors. Explain your thought process and be open to constructive feedback.

* Present your weekly milestones to a study group.

  • Mock Interviews:

* Practice explaining rate limiting concepts and designing systems in a mock interview setting. This is invaluable for solidifying your knowledge and communication skills.

  • Case Study Analysis:

* Take a real-world incident report or a major outage related to rate limiting (or lack thereof) and analyze what went wrong and how a robust rate limiter could have prevented it.


python

from flask import Flask, jsonify

import redis

import os

from rate_limiter import RateLimiter

Initialize Flask app

app = Flask(__name__)

--- Redis Configuration ---

Get Redis connection details from environment variables or use defaults

REDIS_HOST = os.getenv('REDIS_HOST', 'localhost')

REDIS_PORT = int(os.getenv('REDIS_PORT', 6379))

REDIS_DB = int(os.getenv('REDIS_DB', 0))

Initialize Redis client

Use decode_responses=True to get strings instead of bytes

try:

redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, decode_responses=True)

redis_client.ping() # Test connection

print(f"Connected to Redis at {REDIS_HOST}:{REDIS_PORT}")

except redis.exceptions.ConnectionError as e:

print(f"Could not connect to Redis: {e}")

print("Please ensure Redis server is running.")

exit(1) # Exit if Redis connection fails, as rate limiter won't work

Initialize RateLimiter with the Redis client

Default limit: 5 requests per 60 seconds

rate_limiter = RateLimiter(redis_client=redis_client, default_limit=5, default_period=60)

--- API Endpoints ---

@app.route('/')

def home():

"""

A simple home endpoint without rate limiting.

"""

return jsonify({"message": "Welcome to the API! Try /limited or /strict-limited."})

@app.route('/limited')

@rate_limiter.rate_limit(limit=3, period=10) # 3 requests every 10 seconds

def limited_endpoint():

"""

An endpoint with a custom rate limit: 3 requests per 10 seconds.

"""

return jsonify({"message": "This is a

gemini Output

API Rate Limiter: Comprehensive Overview and Implementation Guide

This document provides a comprehensive overview of API Rate Limiting, covering its importance, core mechanisms, design considerations, implementation strategies, and best practices. It is designed to serve as a detailed guide for understanding and effectively deploying rate limiting within your API ecosystem.


1. Introduction to API Rate Limiting

An API Rate Limiter is a critical component in modern web service architectures that controls the number of requests a user or client can make to an API within a given timeframe. Its primary purpose is to regulate traffic, prevent abuse, ensure fair resource allocation, and maintain the stability and reliability of your API infrastructure.

2. Key Benefits of Implementing API Rate Limiting

Implementing a robust API rate limiting strategy offers several significant advantages:

  • Security & Abuse Prevention:

* DDoS and Brute-Force Attack Mitigation: Prevents malicious actors from overwhelming your servers with excessive requests or attempting to guess credentials through repeated login attempts.

* Scraping Prevention: Limits automated data extraction, protecting your intellectual property and data integrity.

  • System Stability & Reliability:

* Resource Protection: Prevents a single client or a surge in requests from consuming all available server resources (CPU, memory, database connections), ensuring the API remains responsive for all legitimate users.

* Predictable Performance: Helps maintain consistent API performance by smoothing out traffic spikes.

  • Cost Control:

* Reduces infrastructure costs by preventing excessive resource usage, especially relevant in cloud environments where you pay for compute, bandwidth, and database operations.

  • Fair Usage & Quality of Service (QoS):

* Ensures that no single client monopolizes API resources, providing a fair and consistent experience for all consumers.

  • Monetization & Tiering:

* Enables the creation of different service tiers (e.g., free, premium, enterprise) with varying request limits, supporting business models based on API usage.

3. Core Concepts and Rate Limiting Algorithms

Several algorithms are commonly used to implement rate limiting, each with its own characteristics:

  • a. Fixed Window Counter

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

* Pros: Simple to implement, low memory overhead.

* Cons: Prone to "bursting" at window edges. For example, a client could make N requests at the very end of one window and another N requests at the very beginning of the next, effectively making 2N requests in a short period.

  • b. Sliding Window Log

* How it works: Stores a timestamp for every request made by a client. When a new request arrives, it counts the number of timestamps within the current sliding window (e.g., the last 60 seconds). If the count exceeds the limit, the request is blocked.

* Pros: Highly accurate, prevents the "bursting" issue of fixed windows.

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

  • c. Sliding Window Counter (Approximation)

* How it works: A hybrid approach that combines the simplicity of fixed windows with the accuracy of sliding windows. It calculates the current rate by weighting the current fixed window's count with a fraction of the previous fixed window's count.

* Pros: Good balance between accuracy and memory efficiency. Mitigates the bursting issue better than fixed window.

* Cons: Still an approximation, not perfectly accurate as sliding window log.

  • d. Token Bucket

* How it works: Imagine a bucket with a fixed capacity that tokens are added to at a constant rate. Each API request consumes one token. If the bucket is empty, the request is blocked.

* Pros: Allows for bursts of requests (up to the bucket capacity), providing flexibility. Controls the average rate of requests.

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

  • e. Leaky Bucket

* How it works: Requests are added to a "bucket" (a queue) that "leaks" (processes requests) at a constant rate. If the bucket is full, new requests are dropped.

* Pros: Smooths out traffic, effectively preventing bursts. Ideal for scenarios where a constant output rate is desired.

* Cons: Can introduce latency if the bucket fills up. Dropping requests when full can be less graceful than token bucket.

4. Design Considerations for API Rate Limiting

Effective rate limiting requires careful consideration of several design aspects:

  • a. Scope of Limiting:

* Global: Limits all requests to the entire API.

* Per-User/Per-Client: Based on user ID, API key, or authentication token. (Most common and recommended).

* Per-IP Address: Simple but problematic with shared IPs (NAT, VPNs, proxies).

* Per-Endpoint/Per-Route: Different limits for different API endpoints (e.g., GET /read might have higher limits than POST /write).

* Per-Method: Limits based on HTTP method (e.g., GET vs. POST).

  • b. Granularity of Limits:

* Timeframe: Seconds, minutes, hours, daily.

* Request Definition: What constitutes a "request" for counting purposes? (e.g., any HTTP request, only authenticated requests, specific resource access).

  • c. Exclusions and Whitelisting:

* Identify and exempt internal services, trusted partners, or specific IP ranges from rate limits.

  • d. Handling Over-Limit Requests:

* HTTP Status Code: Always return 429 Too Many Requests.

* Response Headers: Provide informative headers to clients:

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

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

* X-RateLimit-Reset: The timestamp (in UTC epoch seconds) when the current rate limit window resets.

* Retry-After: The number of seconds the client should wait before making another request.

* Logging: Log rate limit violations for monitoring and analysis.

  • e. Persistence and State Management:

* In-Memory: Fastest but not scalable for distributed systems (each instance has its own state).

* Distributed Cache (e.g., Redis): Recommended for scalable, distributed systems. Provides fast access to counters and logs across multiple API instances.

* Database: Slower, generally not recommended for real-time rate limiting due to latency.

  • f. Distributed Systems Challenges:

* Ensuring consistent rate counting across multiple API instances requires a centralized, shared state (e.g., Redis). Atomic operations are crucial to prevent race conditions.

5. Implementation Strategies

API rate limiting can be implemented at various layers of your application stack:

  • a. Application-Level Middleware:

* Description: Integrated directly into your API's codebase (e.g., using frameworks like Express.js, Spring Boot, Django, Flask).

* Pros: Fine-grained control, can access application-specific context (user ID, subscription tier).

* Cons: Adds overhead to application logic, requires implementation in each service, harder to manage across a microservices architecture.

  • b. API Gateway/Proxy Level:

* Description: Implemented at the edge of your network using an API Gateway (e.g., Nginx, Envoy, Kong, AWS API Gateway, Azure API Management, Google Cloud Endpoints).

* Pros: Centralized control, offloads rate limiting logic from individual services, consistent policy enforcement across all APIs, scalable.

* Cons: May lack deep application context without custom integration, can be a single point of failure if not highly available.

  • c. Dedicated Rate Limiting Service:

* Description: A standalone microservice specifically designed to handle rate limiting requests, often backed by a distributed cache like Redis.

* Pros: Highly scalable and performant, completely decoupled from application logic, reusable across multiple APIs.

* Cons: Adds complexity to the architecture, requires separate deployment and management.

  • d. Cloud Provider Services:

* Description: Leveraging managed rate limiting features provided by cloud platforms (e.g., AWS WAF, Cloudflare, Azure Front Door).

* Pros: Fully managed, high availability, integrated with other security features, simplifies operations.

* Cons: Vendor lock-in, potentially less customizable than self-managed solutions.

6. Best Practices for API Rate Limiting

To maximize the effectiveness of your rate limiting strategy:

  • a. Clear Documentation:

Provide comprehensive documentation for API consumers, detailing the rate limits, the meaning of 429 responses, and how to use Retry-After and X-RateLimit- headers for graceful handling.

  • b. Client-Side Guidance:

* Educate clients on implementing exponential backoff and jitter for retries to avoid overwhelming your API further during periods of high traffic or when a 429 is received.

  • c. Granular Control:

* Implement different limits for different types of requests or user tiers to optimize resource allocation.

  • d. Prioritization:

* Consider allowing critical internal services or specific high-priority clients to have higher limits or bypass rate limiting entirely.

  • e. Dynamic Adjustment:

* Design your system to allow for dynamic adjustment of rate limits without requiring a full service redeployment. This is crucial for responding to incidents or changing traffic patterns.

  • f. Graceful Degradation:

* Ensure that your rate limiting mechanism itself is highly available and doesn't become a single point of failure. If the rate limiter fails, decide on a fallback strategy (e.g., temporarily allow all requests, or block all to prevent overload).

  • g. Test Thoroughly:

* Rigorously test your rate limiter under various load conditions to ensure it behaves as expected and doesn't introduce unintended bottlenecks.

7. Monitoring and Alerting

Robust monitoring and alerting are essential for maintaining an effective rate limiting system:

  • a. Key Metrics to Monitor:

* Number of 429 Too Many Requests responses.

* Rate limit violations per client/IP.

* Requests per second (RPS) for various endpoints and client groups.

* Latency introduced by the rate limiter.

* Health and performance of the rate limiting service/component.

  • b. Alerting:

* Set up alerts for:

* Sustained high rates of 429s for specific clients (may indicate abuse or a client-side issue).

* Unusually high overall 429 rates (may indicate a broader attack or unexpected traffic surge).

* Failure or degradation of the rate limiting service itself.

  • c. Dashboards:

* Create dashboards to visualize rate limit usage, violations, and client behavior patterns over time. This helps in identifying trends and potential issues proactively.

8. Common Challenges

  • False Positives/Negatives: Blocking legitimate users (false positive) or failing to block malicious ones (false negative).
  • State Management in Distributed Systems: Ensuring consistent and atomic updates to counters across many instances.
  • Performance Overhead: The rate limiter itself must be highly performant; otherwise, it becomes the bottleneck.
  • NAT/Proxy Environments: Multiple users behind a single IP address can hit limits quickly. Solutions include per-user/API key limits.
  • Complexity: Choosing the right algorithm and scaling it effectively can be complex.

9. Conclusion

API Rate Limiting is an indispensable tool for securing your APIs, ensuring their stability, and optimizing resource utilization. By carefully designing and implementing a strategy that aligns with your specific needs, you can protect your infrastructure, provide a consistent user experience, and enable flexible monetization models.

We recommend a phased approach, starting with basic rate limits and gradually refining them based on observed traffic patterns and business requirements. Regular review and adjustment of your rate limiting policies are crucial for long-term success.


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
"); var hasSrcMain=Object.keys(extracted).some(function(k){return k.indexOf("src/main")>=0;}); if(!hasSrcMain) zip.file(folder+"src/main."+ext,"import React from 'react' import ReactDOM from 'react-dom/client' import App from './App' import './index.css' ReactDOM.createRoot(document.getElementById('root')!).render( ) "); var hasSrcApp=Object.keys(extracted).some(function(k){return k==="src/App."+ext||k==="App."+ext;}); if(!hasSrcApp) zip.file(folder+"src/App."+ext,"import React from 'react' import './App.css' function App(){ return(

"+slugTitle(pn)+"

Built with PantheraHive BOS

) } export default App "); zip.file(folder+"src/index.css","*{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#f0f2f5;color:#1a1a2e} .app{min-height:100vh;display:flex;flex-direction:column} .app-header{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:40px} h1{font-size:2.5rem;font-weight:700} "); zip.file(folder+"src/App.css",""); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/pages/.gitkeep",""); zip.file(folder+"src/hooks/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` ## Open in IDE Open the project folder in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- Vue (Vite + Composition API + TypeScript) --- */ function buildVue(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{ "name": "'+pn+'", "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "vue-tsc -b && vite build", "preview": "vite preview" }, "dependencies": { "vue": "^3.5.13", "vue-router": "^4.4.5", "pinia": "^2.3.0", "axios": "^1.7.9" }, "devDependencies": { "@vitejs/plugin-vue": "^5.2.1", "typescript": "~5.7.3", "vite": "^6.0.5", "vue-tsc": "^2.2.0" } } '); zip.file(folder+"vite.config.ts","import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { resolve } from 'path' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': resolve(__dirname,'src') } } }) "); zip.file(folder+"tsconfig.json",'{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]} '); zip.file(folder+"tsconfig.app.json",'{ "compilerOptions":{ "target":"ES2020","useDefineForClassFields":true,"module":"ESNext","lib":["ES2020","DOM","DOM.Iterable"], "skipLibCheck":true,"moduleResolution":"bundler","allowImportingTsExtensions":true, "isolatedModules":true,"moduleDetection":"force","noEmit":true,"jsxImportSource":"vue", "strict":true,"paths":{"@/*":["./src/*"]} }, "include":["src/**/*.ts","src/**/*.d.ts","src/**/*.tsx","src/**/*.vue"] } '); zip.file(folder+"env.d.ts","/// "); zip.file(folder+"index.html"," "+slugTitle(pn)+"
"); var hasMain=Object.keys(extracted).some(function(k){return k==="src/main.ts"||k==="main.ts";}); if(!hasMain) zip.file(folder+"src/main.ts","import { createApp } from 'vue' import { createPinia } from 'pinia' import App from './App.vue' import './assets/main.css' const app = createApp(App) app.use(createPinia()) app.mount('#app') "); var hasApp=Object.keys(extracted).some(function(k){return k.indexOf("App.vue")>=0;}); if(!hasApp) zip.file(folder+"src/App.vue"," "); zip.file(folder+"src/assets/main.css","*{margin:0;padding:0;box-sizing:border-box}body{font-family:system-ui,sans-serif;background:#fff;color:#213547} "); zip.file(folder+"src/components/.gitkeep",""); zip.file(folder+"src/views/.gitkeep",""); zip.file(folder+"src/stores/.gitkeep",""); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install npm run dev ``` ## Build ```bash npm run build ``` Open in VS Code or WebStorm. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local "); } /* --- Angular (v19 standalone) --- */ function buildAngular(zip,folder,app,code,panelTxt){ var pn=pkgName(app); var C=cc(pn); var sel=pn.replace(/_/g,"-"); var extracted=extractCode(panelTxt); zip.file(folder+"package.json",'{ "name": "'+pn+'", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test" }, "dependencies": { "@angular/animations": "^19.0.0", "@angular/common": "^19.0.0", "@angular/compiler": "^19.0.0", "@angular/core": "^19.0.0", "@angular/forms": "^19.0.0", "@angular/platform-browser": "^19.0.0", "@angular/platform-browser-dynamic": "^19.0.0", "@angular/router": "^19.0.0", "rxjs": "~7.8.0", "tslib": "^2.3.0", "zone.js": "~0.15.0" }, "devDependencies": { "@angular-devkit/build-angular": "^19.0.0", "@angular/cli": "^19.0.0", "@angular/compiler-cli": "^19.0.0", "typescript": "~5.6.0" } } '); zip.file(folder+"angular.json",'{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "'+pn+'": { "projectType": "application", "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "outputPath": "dist/'+pn+'", "index": "src/index.html", "browser": "src/main.ts", "tsConfig": "tsconfig.app.json", "styles": ["src/styles.css"], "scripts": [] } }, "serve": {"builder":"@angular-devkit/build-angular:dev-server","configurations":{"production":{"buildTarget":"'+pn+':build:production"},"development":{"buildTarget":"'+pn+':build:development"}},"defaultConfiguration":"development"} } } } } '); zip.file(folder+"tsconfig.json",'{ "compileOnSave": false, "compilerOptions": {"baseUrl":"./","outDir":"./dist/out-tsc","forceConsistentCasingInFileNames":true,"strict":true,"noImplicitOverride":true,"noPropertyAccessFromIndexSignature":true,"noImplicitReturns":true,"noFallthroughCasesInSwitch":true,"paths":{"@/*":["src/*"]},"skipLibCheck":true,"esModuleInterop":true,"sourceMap":true,"declaration":false,"experimentalDecorators":true,"moduleResolution":"bundler","importHelpers":true,"target":"ES2022","module":"ES2022","useDefineForClassFields":false,"lib":["ES2022","dom"]}, "references":[{"path":"./tsconfig.app.json"}] } '); zip.file(folder+"tsconfig.app.json",'{ "extends":"./tsconfig.json", "compilerOptions":{"outDir":"./dist/out-tsc","types":[]}, "files":["src/main.ts"], "include":["src/**/*.d.ts"] } '); zip.file(folder+"src/index.html"," "+slugTitle(pn)+" "); zip.file(folder+"src/main.ts","import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent, appConfig) .catch(err => console.error(err)); "); zip.file(folder+"src/styles.css","* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: system-ui, -apple-system, sans-serif; background: #f9fafb; color: #111827; } "); var hasComp=Object.keys(extracted).some(function(k){return k.indexOf("app.component")>=0;}); if(!hasComp){ zip.file(folder+"src/app/app.component.ts","import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = '"+pn+"'; } "); zip.file(folder+"src/app/app.component.html","

"+slugTitle(pn)+"

Built with PantheraHive BOS

"); zip.file(folder+"src/app/app.component.css",".app-header{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:60vh;gap:16px}h1{font-size:2.5rem;font-weight:700;color:#6366f1} "); } zip.file(folder+"src/app/app.config.ts","import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes) ] }; "); zip.file(folder+"src/app/app.routes.ts","import { Routes } from '@angular/router'; export const routes: Routes = []; "); Object.keys(extracted).forEach(function(p){ var fp=p.startsWith("src/")?p:"src/"+p; zip.file(folder+fp,extracted[p]); }); zip.file(folder+"README.md","# "+slugTitle(pn)+" Generated by PantheraHive BOS. ## Setup ```bash npm install ng serve # or: npm start ``` ## Build ```bash ng build ``` Open in VS Code with Angular Language Service extension. "); zip.file(folder+".gitignore","node_modules/ dist/ .env .DS_Store *.local .angular/ "); } /* --- Python --- */ function buildPython(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/m,"").trim(); var reqMap={"numpy":"numpy","pandas":"pandas","sklearn":"scikit-learn","tensorflow":"tensorflow","torch":"torch","flask":"flask","fastapi":"fastapi","uvicorn":"uvicorn","requests":"requests","sqlalchemy":"sqlalchemy","pydantic":"pydantic","dotenv":"python-dotenv","PIL":"Pillow","cv2":"opencv-python","matplotlib":"matplotlib","seaborn":"seaborn","scipy":"scipy"}; var reqs=[]; Object.keys(reqMap).forEach(function(k){if(src.indexOf("import "+k)>=0||src.indexOf("from "+k)>=0)reqs.push(reqMap[k]);}); var reqsTxt=reqs.length?reqs.join(" "):"# add dependencies here "; zip.file(folder+"main.py",src||"# "+title+" # Generated by PantheraHive BOS print(title+" loaded") "); zip.file(folder+"requirements.txt",reqsTxt); zip.file(folder+".env.example","# Environment variables "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` ## Run ```bash python main.py ``` "); zip.file(folder+".gitignore",".venv/ __pycache__/ *.pyc .env .DS_Store "); } /* --- Node.js --- */ function buildNode(zip,folder,app,code){ var title=slugTitle(app); var pn=pkgName(app); var src=code.replace(/^```[w]* ?/m,"").replace(/ ?```$/m,"").trim(); var depMap={"mongoose":"^8.0.0","dotenv":"^16.4.5","axios":"^1.7.9","cors":"^2.8.5","bcryptjs":"^2.4.3","jsonwebtoken":"^9.0.2","socket.io":"^4.7.4","uuid":"^9.0.1","zod":"^3.22.4","express":"^4.18.2"}; var deps={}; Object.keys(depMap).forEach(function(k){if(src.indexOf(k)>=0)deps[k]=depMap[k];}); if(!deps["express"])deps["express"]="^4.18.2"; var pkgJson=JSON.stringify({"name":pn,"version":"1.0.0","main":"src/index.js","scripts":{"start":"node src/index.js","dev":"nodemon src/index.js"},"dependencies":deps,"devDependencies":{"nodemon":"^3.0.3"}},null,2)+" "; zip.file(folder+"package.json",pkgJson); var fallback="const express=require("express"); const app=express(); app.use(express.json()); app.get("/",(req,res)=>{ res.json({message:""+title+" API"}); }); const PORT=process.env.PORT||3000; app.listen(PORT,()=>console.log("Server on port "+PORT)); "; zip.file(folder+"src/index.js",src||fallback); zip.file(folder+".env.example","PORT=3000 "); zip.file(folder+".gitignore","node_modules/ .env .DS_Store "); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Setup ```bash npm install ``` ## Run ```bash npm run dev ``` "); } /* --- Vanilla HTML --- */ function buildVanillaHtml(zip,folder,app,code){ var title=slugTitle(app); var isFullDoc=code.trim().toLowerCase().indexOf("=0||code.trim().toLowerCase().indexOf("=0; var indexHtml=isFullDoc?code:" "+title+" "+code+" "; zip.file(folder+"index.html",indexHtml); zip.file(folder+"style.css","/* "+title+" — styles */ *{margin:0;padding:0;box-sizing:border-box} body{font-family:system-ui,-apple-system,sans-serif;background:#fff;color:#1a1a2e} "); zip.file(folder+"script.js","/* "+title+" — scripts */ "); zip.file(folder+"assets/.gitkeep",""); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. ## Open Double-click `index.html` in your browser. Or serve locally: ```bash npx serve . # or python3 -m http.server 3000 ``` "); zip.file(folder+".gitignore",".DS_Store node_modules/ .env "); } /* ===== MAIN ===== */ var sc=document.createElement("script"); sc.src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"; sc.onerror=function(){ if(lbl)lbl.textContent="Download ZIP"; alert("JSZip load failed — check connection."); }; sc.onload=function(){ var zip=new JSZip(); var base=(_phFname||"output").replace(/.[^.]+$/,""); var app=base.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"my_app"; var folder=app+"/"; var vc=document.getElementById("panel-content"); var panelTxt=vc?(vc.innerText||vc.textContent||""):""; var lang=detectLang(_phCode,panelTxt); if(_phIsHtml){ buildVanillaHtml(zip,folder,app,_phCode); } else if(lang==="flutter"){ buildFlutter(zip,folder,app,_phCode,panelTxt); } else if(lang==="react-native"){ buildReactNative(zip,folder,app,_phCode,panelTxt); } else if(lang==="swift"){ buildSwift(zip,folder,app,_phCode,panelTxt); } else if(lang==="kotlin"){ buildKotlin(zip,folder,app,_phCode,panelTxt); } else if(lang==="react"){ buildReact(zip,folder,app,_phCode,panelTxt); } else if(lang==="vue"){ buildVue(zip,folder,app,_phCode,panelTxt); } else if(lang==="angular"){ buildAngular(zip,folder,app,_phCode,panelTxt); } else if(lang==="python"){ buildPython(zip,folder,app,_phCode); } else if(lang==="node"){ buildNode(zip,folder,app,_phCode); } else { /* Document/content workflow */ var title=app.replace(/_/g," "); var md=_phAll||_phCode||panelTxt||"No content"; zip.file(folder+app+".md",md); var h=""+title+""; h+="

"+title+"

"; var hc=md.replace(/&/g,"&").replace(//g,">"); hc=hc.replace(/^### (.+)$/gm,"

$1

"); hc=hc.replace(/^## (.+)$/gm,"

$1

"); hc=hc.replace(/^# (.+)$/gm,"

$1

"); hc=hc.replace(/**(.+?)**/g,"$1"); hc=hc.replace(/ {2,}/g,"

"); h+="

"+hc+"

Generated by PantheraHive BOS
"; zip.file(folder+app+".html",h); zip.file(folder+"README.md","# "+title+" Generated by PantheraHive BOS. Files: - "+app+".md (Markdown) - "+app+".html (styled HTML) "); } zip.generateAsync({type:"blob"}).then(function(blob){ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download=app+".zip"; a.click(); URL.revokeObjectURL(a.href); if(lbl)lbl.textContent="Download ZIP"; }); }; document.head.appendChild(sc); }function phShare(){navigator.clipboard.writeText(window.location.href).then(function(){var el=document.getElementById("ph-share-lbl");if(el){el.textContent="Link copied!";setTimeout(function(){el.textContent="Copy share link";},2500);}});}function phEmbed(){var runId=window.location.pathname.split("/").pop().replace(".html","");var embedUrl="https://pantherahive.com/embed/"+runId;var code='';navigator.clipboard.writeText(code).then(function(){var el=document.getElementById("ph-embed-lbl");if(el){el.textContent="Embed code copied!";setTimeout(function(){el.textContent="Get Embed Code";},2500);}});}