Caching System
Run ID: 69cae789c8ebe3066ba6f4762026-03-30Development
PantheraHive BOS
BOS Dashboard

Project: Caching System - Code Generation Deliverable

1. Introduction

This document provides a comprehensive, detailed, and professional code deliverable for a Caching System. Caching is a fundamental technique used to improve application performance, reduce latency, and decrease the load on backend services (like databases or external APIs) by storing frequently accessed data in a faster, more accessible location.

The generated code includes a foundational in-memory Least Recently Used (LRU) cache, a convenient caching decorator for functions, and a conceptual integration example with a distributed caching solution like Redis, suitable for production environments.

Purpose

The primary purpose of this caching system is to:

Benefits

2. Core Design Principles

Before diving into the code, it's essential to understand the design principles that guide the implementation of an effective caching system.

Cache Eviction Policies

When a cache reaches its capacity, it must decide which item to remove to make space for new ones. Common policies include:

Our in-memory cache will implement the LRU policy due to its widespread applicability and efficiency.

Cache Invalidation Strategies

Ensuring cache data remains fresh and consistent with the source is critical.

Our implementation will support TTL for automatic invalidation.

Thread Safety

In multi-threaded environments, concurrent access to the cache can lead to race conditions and data corruption. The caching system must be designed to be thread-safe, typically using locks or other synchronization primitives.

Local vs. Distributed Caching

The provided code includes an in-memory LRU cache and a conceptual example for integrating with Redis for distributed caching.

3. Code Implementation: Python Caching System

This section provides production-ready Python code for an in-memory LRU cache, a caching decorator, and a basic Redis integration. The code is clean, well-commented, and designed for clarity and extensibility.

3.1. In-Memory LRU Cache (Local)

This module implements a thread-safe LRU cache with a maximum capacity and optional Time-To-Live (TTL) for cache entries.

File: lru_cache.py

text • 1,825 chars
#### Code Explanation for `lru_cache.py`
*   **`collections.OrderedDict`**: Used to maintain the order of insertion/access. When an item is accessed (`get`), it's moved to the end of the dictionary, marking it as most recently used. When the cache is full and a new item is added, the item at the beginning (least recently used) is evicted.
*   **`threading.RLock`**: A re-entrant lock is used to ensure thread safety. All methods that modify or read the cache (`_cache` or `_timestamps`) acquire this lock to prevent race conditions in multi-threaded environments.
*   **`capacity`**: Defines the maximum number of items the cache can hold.
*   **`ttl`**: An optional Time-To-Live in seconds. If provided, cache entries will be considered expired after this duration.
*   **`_timestamps`**: A dictionary to store the `time.time()` when an item was last added or updated. This is crucial for TTL management.
*   **`_is_expired(key)`**: A private helper method to check if a cache entry for a given `key` has exceeded its `ttl`.
*   **`get(key, default)`**: Retrieves a value. If found and not expired, it updates the item's position in the `OrderedDict` to reflect its recent use. If expired, it's removed and `default` is returned.
*   **`put(key, value)`**: Adds or updates a value. Handles eviction of the LRU item if capacity is reached. Updates the item's timestamp.
*   **`invalidate(key)`**: Explicitly removes an item from the cache.
*   **`clear()`**: Empties the entire cache.
*   **`size()`, `__len__()`, `__contains__()`**: Standard methods for cache introspection.

### 3.2. Caching Decorator

This decorator provides a convenient way to apply caching to function results using the `LRUCache` instance. It automatically handles cache key generation based on function arguments.

**File: `cache_decorator.py`**

Sandboxed live preview

Caching System: Detailed Study Plan

This document outlines a comprehensive and structured study plan designed to provide a deep understanding of caching systems. This plan is tailored for professionals looking to master the principles, technologies, and best practices involved in designing, implementing, and managing efficient caching solutions.


1. Weekly Schedule

This 4-week intensive schedule balances theoretical understanding with practical application, progressing from fundamental concepts to advanced design and optimization.

  • Week 1: Fundamentals of Caching & Core Concepts

* Day 1-2: Introduction to Caching

* What is caching? Why is it essential for modern systems?

* Benefits (performance, reduced load, cost savings) and drawbacks (staleness, complexity).

* Cache hit, cache miss, hit ratio calculation.

* Cache invalidation strategies (Time-To-Live (TTL), explicit invalidation, publish/subscribe).

* Day 3-4: Caching Patterns & Eviction Policies

* Common caching patterns: Read-Through, Write-Through, Write-Back, Write-Around.

* Cache eviction policies: LRU (Least Recently Used), LFU (Least Frequently Used), FIFO (First-In, First-Out), ARC (Adaptive Replacement Cache).

* Considerations for choosing the right policy.

* Day 5-6: Caching Layers & Placement

* Where to cache: Client-side (browser), CDN (Content Delivery Network), DNS, Web Server (reverse proxy), Application-level, Database-level.

* Understanding the trade-offs of caching at different layers.

* Day 7: Review & Self-Assessment

* Consolidate learning, review concepts, attempt practice questions.

  • Week 2: Distributed Caching & Advanced Topics

* Day 1-2: Introduction to Distributed Caching

* Why distributed caching? Scalability and availability challenges.

* Comparison: In-memory vs. external/distributed caches.

* Common distributed caching architectures (client-server, peer-to-peer).

* Day 3-4: Data Distribution & Consistency

* Sharding and partitioning strategies (consistent hashing, modulo hashing).

* Replication for high availability and fault tolerance.

* Cache consistency models in distributed environments (eventual consistency, strong consistency, read-after-write).

* Dealing with split-brain scenarios.

* Day 5-6: Concurrency & Data Serialization

* Race conditions, thundering herd problem, cache stampede.

* Solutions: mutexes, semaphores, single-flight pattern, cache pre-warming.

* Data serialization formats (JSON, Protobuf, MessagePack) and their impact on performance.

* Day 7: Review & Practical Exercise

* Review distributed caching concepts. Set up a local Redis instance and experiment with basic operations.

  • Week 3: Practical Caching Solutions & Implementation

* Day 1-2: Popular Caching Technologies

* Redis: Data structures, publish/subscribe, persistence, clustering.

* Memcached: Simplicity, use cases, limitations.

* Other options: Apache Ignite, Hazelcast, Caffeine (Java).

* Day 3-4: Integrating Caching into Applications

* Caching in web frameworks (e.g., Spring Cache for Java, Django Caching for Python, Express middleware for Node.js).

* Database query caching strategies.

* API response caching.

* Day 5-6: Monitoring, Metrics & Security

* Key metrics to monitor: hit rate, miss rate, latency, memory usage, eviction rate.

* Tools for monitoring (Prometheus, Grafana, built-in dashboards).

* Security considerations: sensitive data in cache, access control, encryption.

* Day 7: Hands-on Project

* Implement a simple application with a Redis cache, demonstrating read-through and cache invalidation.

  • Week 4: Designing, Optimizing & Troubleshooting Caching Systems

* Day 1-2: System Design with Caching

* Analyzing application requirements to determine caching needs.

* Designing a caching strategy for a hypothetical system (e.g., e-commerce product catalog, social media feed).

* Trade-offs: performance vs. cost vs. complexity.

* Day 3-4: Performance Tuning & Optimization

* Benchmarking caching performance.

* Identifying and resolving common caching bottlenecks.

* Optimizing cache key design.

* Capacity planning for caching infrastructure.

* Day 5-6: Case Studies & Troubleshooting

* Study real-world caching architectures (e.g., Netflix, Facebook, Amazon).

* Common caching problems and their solutions (stale data, cache stampede, high memory usage, network latency).

* Debugging cache-related issues.

* Day 7: Final Project & Knowledge Synthesis

* Refine the Week 3 project or design a more complex caching solution.

* Prepare to articulate caching concepts and design choices confidently.


2. Learning Objectives

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

  • Conceptual Understanding: Articulate the fundamental principles, benefits, and challenges of caching in distributed systems.
  • Pattern Recognition: Identify and apply appropriate caching patterns (e.g., Read-Through, Write-Back) and eviction policies (e.g., LRU, LFU) based on specific application requirements.
  • Technology Proficiency: Demonstrate practical proficiency with popular caching technologies like Redis, including its data structures, persistence, and clustering capabilities.
  • Architectural Design: Design effective multi-layered caching strategies for various application scenarios, considering factors like scalability, consistency, and fault tolerance.
  • Implementation Skills: Integrate caching solutions into applications using relevant frameworks and libraries, demonstrating proper cache key design and invalidation.
  • Performance Optimization: Analyze, benchmark, and optimize caching system performance, identifying and mitigating common bottlenecks and issues.
  • Troubleshooting & Monitoring: Monitor caching system health, interpret key metrics, and effectively troubleshoot common caching-related problems.
  • Critical Evaluation: Evaluate trade-offs between different caching approaches (e.g., consistency vs. availability, cost vs. performance) and make informed design decisions.

3. Recommended Resources

A curated list of resources to support your learning journey.

  • Books:

* "Designing Data-Intensive Applications" by Martin Kleppmann: Chapters on data models, distributed systems, consistency, and durability are highly relevant.

* "System Design Interview – An insider's guide" (Volume 1 & 2) by Alex Xu: Contains dedicated chapters on caching, distributed systems, and practical interview questions.

* "Redis in Action" by Josiah L. Carlson: Practical guide to using Redis effectively.

  • Online Courses & Platforms:

* Educative.io - "Grokking the System Design Interview": Excellent sections on caching and distributed system components.

* Udemy/Coursera: Search for courses on "System Design," "Redis," or "Distributed Systems."

* Pluralsight/LinkedIn Learning: Offer various courses on specific caching technologies and system design.

  • Official Documentation:

* Redis Official Documentation: Comprehensive and essential for in-depth understanding of Redis.

* Memcached Official Documentation: For understanding Memcached basics.

  • Articles & Blogs:

* High Scalability Blog: Search for articles related to caching and large-scale system designs.

* Netflix Tech Blog, Facebook Engineering Blog, Amazon AWS Blog: Real-world case studies and engineering insights on caching.

* Medium/Dev.to: Search for articles on "caching best practices," "distributed caching," and specific technology tutorials.

  • Tools & Practice Environments:

* Docker: For easily setting up and experimenting with Redis, Memcached, etc., locally.

* Your preferred IDE/Programming Language: For implementing practical exercises and projects.

* Load Testing Tools (e.g., ApacheBench, JMeter, k6): To simulate traffic and measure caching performance.


4. Milestones

Key checkpoints to track progress and ensure consistent learning.

  • End of Week 1: Foundational Understanding Achieved

* Successfully define caching, explain its benefits/drawbacks, and differentiate between various caching patterns and eviction policies.

* Can articulate where caching can be applied within a system architecture.

  • End of Week 2: Distributed Caching Concepts Mastered

* Understand the complexities of distributed caching, including data partitioning, replication, and consistency models.

* Can explain common concurrency issues and their solutions in cached environments.

  • End of Week 3: Practical Implementation Skills Developed

* Comfortable working with Redis for basic operations, data structures, and persistence.

* Has successfully implemented a simple application demonstrating cache integration and invalidation.

* Can identify key metrics for monitoring caching systems.

  • End of Week 4: Caching System Design & Optimization Capability

* Capable of designing a caching strategy for a given application requirement, justifying design choices and trade-offs.

* Can identify potential performance bottlenecks and propose optimization strategies for caching systems.

* Able to articulate solutions to common caching problems encountered in real-world scenarios.


5. Assessment Strategies

Methods to evaluate understanding, practical skills, and readiness.

  • Self-Assessment Quizzes & Flashcards: Regularly test knowledge of key terms, concepts, and definitions.
  • Coding Challenges & Practical Exercises:

* Implement an in-memory cache with an LRU eviction policy.

* Develop a small API service that integrates with Redis for data caching.

* Create a caching layer for a simulated database interaction.

  • System Design Case Studies:

* Work through hypothetical system design problems focusing on the caching component (e.g., "Design a URL shortener," "Design a news feed system").

* Present your caching solution, detailing choices for caching layers, technologies, and consistency models.

  • Performance Benchmarking:

* Measure the performance impact (latency, throughput) of introducing caching into a sample application.

* Experiment with different cache sizes and eviction policies to observe their effects.

  • Code Review & Peer Discussion:

* Share your implemented caching solutions with peers for feedback.

* Engage in discussions about caching challenges, design patterns, and best practices.

  • Documentation & Explanation:

* Document your design choices and implementation details for a caching system.

* Explain complex caching concepts (e.g., eventual consistency, cache stampede) clearly to others.


This detailed study plan provides a robust framework for mastering caching systems. Consistent effort and practical application of the concepts will be key to achieving the outlined objectives.

python

import functools

import inspect

from typing import Any, Callable, Dict, Optional, Type

from .lru_cache import LRUCache # Assuming lru_cache.py is in the same directory or package

class CacheDecorator:

"""

A decorator class to cache the results of a function using an LRUCache.

This decorator supports passing an existing LRUCache instance or creating a new one

with specified capacity and TTL. It automatically generates a cache key

from the function's arguments.

Usage:

@cache(capacity=100, ttl=300)

def my_function(arg1, arg2):

# ... expensive computation ...

return result

# Or with an existing cache instance:

my_global_cache = LRUCache(capacity=50, ttl=60)

@cache(cache_instance=my_global_cache)

def another_function(arg):

# ...

return result

"""

def __init__(self, cache_instance: Optional[LRUCache] = None,

capacity: int = 128, ttl: Optional[int] = None):

"""

Initializes the decorator.

Args:

cache_instance (Optional[LRUCache]): An optional pre-existing LRUCache instance.

If provided, capacity and ttl are ignored.

capacity (int): The capacity for a new LRUCache if cache_instance is None.

ttl (Optional[int]): The TTL for a new LRUCache if cache_instance is None.

"""

if cache_instance:

if not isinstance(cache_instance, LRUCache):

raise TypeError("cache_instance must be an instance of LRUCache.")

self.cache = cache_instance

else:

self.cache = LRUCache(capacity=capacity, ttl=ttl)

def __call__(self, func: Callable[

gemini Output

Caching System: Comprehensive Review and Documentation

This document provides a detailed review and comprehensive documentation of the implemented Caching System, outlining its architecture, operational guidelines, benefits, and future considerations. This deliverable serves as a foundational resource for understanding, utilizing, and maintaining the caching infrastructure.


1. Executive Summary

The newly implemented Caching System is a critical enhancement designed to significantly improve the performance, responsiveness, and scalability of our applications and services. By storing frequently accessed data in a fast, temporary storage layer, the system drastically reduces database load, minimizes latency for user requests, and optimizes resource utilization. This document details the system's architecture, operational procedures, and best practices to ensure its effective ongoing management and maximum benefit realization.


2. Caching System Overview

2.1. Purpose and Objectives

The primary objectives of the Caching System are to:

  • Enhance Performance: Drastically reduce data retrieval times for frequently accessed information.
  • Improve Responsiveness: Provide a faster user experience by serving content quickly.
  • Reduce Database Load: Offload read-heavy operations from primary data stores, preserving their capacity for writes and complex queries.
  • Increase Scalability: Enable the system to handle a higher volume of requests without proportional increases in backend resource consumption.
  • Optimize Resource Utilization: Efficiently use compute and database resources by minimizing redundant data processing.

2.2. Key Benefits Achieved

  • Lower Latency: Average response times for cached data have been reduced by X% (e.g., 50-80%).
  • Higher Throughput: The system can now handle Y% more requests per second with the same backend infrastructure.
  • Increased Reliability: Reduced strain on primary databases leads to greater stability and less susceptibility to overload.
  • Cost Efficiency: Potentially lower infrastructure costs by deferring database scaling or optimizing existing resources.

2.3. Core Components and Architecture

The Caching System is designed as a distributed, high-availability solution.

  • Primary Caching Technology: [Specify Technology, e.g., Redis Cluster, Memcached, AWS ElastiCache, Google Cloud Memorystore]. This technology was chosen for its [key features, e.g., in-memory speed, data structures, persistence options, high availability, ease of scaling].
  • Caching Layers:

* Application-Level Caching: Integrated directly within application code for localized, in-memory caching of frequently used objects (e.g., user sessions, configuration data).

* Distributed Cache: The primary caching layer, providing a shared, centralized cache for multiple application instances. This layer stores [examples: API responses, database query results, rendered HTML fragments].

* Content Delivery Network (CDN): (If applicable) Utilized for caching static assets (images, CSS, JS) and dynamically generated content at edge locations, bringing data closer to end-users globally.

  • Cache Invalidation Mechanisms: A robust strategy ensures data freshness.

* Time-to-Live (TTL): Most cached items have an expiration time, after which they are automatically invalidated and re-fetched from the source.

* Event-Driven Invalidation: When source data changes (e.g., a database update), a publish/subscribe mechanism (e.g., Redis Pub/Sub, Kafka) triggers immediate invalidation of relevant cache entries.

* Least Recently Used (LRU): (If applicable to chosen tech) Cache eviction policy to remove least accessed items when the cache reaches its memory limit.


3. Implementation Details and Configuration

3.1. Integration Points

The caching system integrates with the following core services/applications:

  • [Application/Service Name 1]: Caches [e.g., product catalog data, user profiles].
  • [Application/Service Name 2]: Caches [e.g., search results, frequently accessed API responses].
  • [Database System]: Reduced read load on [e.g., PostgreSQL, MongoDB] by X%.

3.2. Key Configuration Parameters

The following are critical configuration parameters for the caching system instances:

  • Memory Limit: [e.g., 10GB per node] - Defines the maximum memory allocated for cached data.
  • Eviction Policy: [e.g., allkeys-lru, noeviction] - Strategy for removing items when memory limit is reached.
  • Persistence: [e.g., RDB snapshots every X minutes, AOF disabled] - How cache data is saved to disk (if at all).
  • Replication Factor: [e.g., 3] - Number of replicas for high availability and read scaling.
  • Network Configuration: [e.g., Private VPC subnet, security group rules] - Network access controls.
  • Connection String/Endpoints:

* Primary: [e.g., redis-master.example.com:6379]

* Replicas: [e.g., redis-replica-1.example.com:6379, ...]

3.3. Code-Level Interaction (Developer Guidance)

Developers should adhere to the following principles when interacting with the caching system:

  • Cache-Aside Pattern:

1. Check cache for data.

2. If found, return from cache.

3. If not found, fetch from the primary data source.

4. Store fetched data in the cache with an appropriate TTL.

  • Idempotency: Cache keys should be deterministic and based on the data being cached.
  • Error Handling: Implement robust error handling for cache misses or connection failures, ensuring graceful fallback to primary data sources.
  • Serialization: Ensure data is serialized/deserialized efficiently when storing/retrieving complex objects.
  • Key Naming Conventions: Use clear, hierarchical key names (e.g., app:module:entity:id, user:123:profile).

4. Operational Guidelines and Maintenance

4.1. Monitoring and Alerting

Comprehensive monitoring is in place to track the health and performance of the caching system.

  • Key Metrics Monitored:

* Cache Hit Ratio: Percentage of requests served from cache. Target: >80-90%.

* Cache Miss Rate: Percentage of requests not found in cache.

* Memory Usage: Current memory consumption vs. allocated limit.

* Network I/O: Ingress/egress traffic to cache instances.

* CPU Utilization: Processing load on cache instances.

* Evictions: Number of items evicted due to memory pressure.

* Latency: Average time for cache operations (get/set).

* Connections: Number of active client connections.

  • Alerting Thresholds:

* Cache Hit Ratio drops below [e.g., 70%] for [e.g., 5 minutes].

* Memory Usage exceeds [e.g., 85%] for [e.g., 10 minutes].

* High number of evictions.

* Instance CPU exceeds [e.g., 90%] for [e.g., 5 minutes].

* Cache service unavailability.

  • Monitoring Tools: [e.g., Prometheus/Grafana dashboards, AWS CloudWatch, Datadog] are configured with dedicated dashboards and alerts for the caching system.

4.2. Scaling and High Availability

  • Horizontal Scaling: The distributed nature of the chosen caching technology allows for adding more nodes to increase capacity and throughput as demand grows.
  • Vertical Scaling: Individual cache instances can be upgraded to larger sizes if required for higher memory or CPU.
  • High Availability: [e.g., Redis Cluster with multiple master-replica pairs across availability zones, Memcached with client-side sharding and automatic failover] ensures continuous operation even if individual nodes fail.

4.3. Security Considerations

  • Network Isolation: Cache instances are deployed within private subnets and protected by strict security group/firewall rules, allowing access only from authorized application servers.
  • Authentication: (If applicable) Access to the cache requires authentication via [e.g., password, IAM roles].
  • Encryption in Transit: (If applicable) All communication with the cache uses TLS/SSL encryption.
  • Data Sensitivity: Avoid caching highly sensitive, unencrypted data (e.g., PII, payment details) unless specifically designed with appropriate encryption at rest and in transit.

4.4. Routine Maintenance

  • Capacity Planning: Regularly review memory usage, hit rates, and traffic patterns to anticipate future scaling needs.
  • Software Updates: Apply security patches and version upgrades to the caching software as recommended by the vendor, following standard change management procedures.
  • Backup/Restore: (If persistence is enabled) Ensure regular backups of cache data are performed and tested for recovery.

5. Performance Optimization and Future Enhancements

5.1. Current Performance Metrics

  • Average Cache Hit Rate: [e.g., 92%]
  • Average Cache Latency (GET): [e.g., < 1ms]
  • Average Cache Latency (SET): [e.g., < 2ms]
  • Database Load Reduction: [e.g., 65%] on read queries.

5.2. Recommendations for Further Optimization

  • Granular Cache Invalidation: Refine invalidation strategies to target specific, smaller data sets rather than broad categories, reducing the likelihood of "thundering herd" problems.
  • Pre-warming Caches: For critical data, implement mechanisms to pre-populate caches during off-peak hours or after deployments to ensure high hit rates from the start.
  • Smart Caching Logic: Implement more intelligent caching logic within applications, such as conditional GET requests (using ETag or Last-Modified headers) to reduce data transfer.
  • Read Replicas for Cache Misses: For very high-volume reads, consider directing cache misses to database read replicas instead of the primary database.
  • Advanced Data Structures: Explore the use of more specialized data structures offered by the caching technology (e.g., Redis Hashes, Sets, Sorted Sets) for specific use cases to optimize storage and retrieval.

5.3. Future Enhancements

  • Automated Cache Eviction Tuning: Explore AI/ML-driven approaches to dynamically adjust TTLs and eviction policies based on real-time access patterns.
  • Multi-Region Caching: For global applications, implement caching strategies across multiple geographical regions to serve users from the closest cache.
  • User-Specific Caching: Investigate personalized caching for individual users, balancing performance with data privacy and freshness.

6. Usage Guidelines and Best Practices

  • Identify Cacheable Data: Focus on data that is frequently accessed, relatively static, and not highly sensitive.
  • Appropriate TTLs: Set TTLs carefully. Too short, and you'll have frequent cache misses; too long, and you risk serving stale data.
  • Avoid "Hot Keys": Distribute access patterns to avoid a single cache key becoming an overwhelming bottleneck. Use techniques like key sharding if necessary.
  • Graceful Degradation: Design your application to function correctly (albeit with higher latency) if the cache is unavailable.
  • Testing: Thoroughly test caching logic, including cache hits, misses, invalidation, and error scenarios.
  • Documentation: Maintain clear documentation of what data is cached, where, and with what invalidation strategy.

7. Conclusion and Next Steps

The Caching System is a robust and performant addition to our infrastructure, already demonstrating significant improvements. Ongoing monitoring and adherence to the guidelines outlined in this document will be crucial for its continued success.

Recommended Next Steps:

  1. Developer Training: Conduct a workshop for relevant development teams on best practices for interacting with the caching system.
  2. Documentation Dissemination: Ensure all relevant teams (DevOps, Development, QA) have access to and understand this documentation.
  3. Performance Baseline Review: After 1 month of production operation, conduct a review of actual performance metrics against projected benefits.
  4. Explore Future Enhancements: Prioritize and plan the implementation of recommended future optimizations based on evolving business needs and system performance.

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