AI Code Review
Run ID: 69cb9c1061b1021a29a8a9cd2026-03-31Development
PantheraHive BOS
BOS Dashboard

AI Code Review - Step 1 of 2: Code Analysis & Refactoring Suggestions

Project/Workflow: AI Code Review

Step: collab → analyze_code

Description: Comprehensive code review with suggestions and refactoring.


1. Introduction & Purpose

This document presents a detailed analysis of the provided code snippet, identifying potential issues related to correctness, performance, security, maintainability, and adherence to best practices. The goal is to furnish actionable insights and specific refactoring recommendations to enhance the code's quality, robustness, and efficiency, making it production-ready.

For demonstration purposes, we will analyze a hypothetical Python function process_data_from_file that reads, processes, and writes data. This allows us to showcase the comprehensive nature of our AI-driven code review capabilities.


2. Original Code Snippet (for Analysis)

To illustrate the review process, we will analyze the following Python function:

text • 3,943 chars
---

### 3. Code Review Analysis & Key Findings

Our AI performed a deep analysis of the provided code. Here are the key findings and areas for improvement:

#### 3.1. Correctness & Robustness

*   **Issue 1: Resource Management (File Handles)**
    *   The `open()` call for the input file is not within a `with` statement, leading to a potential resource leak if an exception occurs before `f.close()` is called.
*   **Issue 2: Broad Exception Handling**
    *   `except Exception as e:` catches all exceptions, obscuring specific error types and making debugging harder. It also prevents proper propagation of critical errors.
*   **Issue 3: Inconsistent Return Values**
    *   The function returns `True`/`False` to indicate success/failure, which is less informative than raising specific exceptions or returning processed data. Callers cannot easily distinguish *why* an operation failed.
*   **Issue 4: Undefined Behavior on Empty `secret_key`**
    *   If `secret_key` is an empty string, `len(secret_key)` would be 0, leading to `value * 0`, which might not be the intended transformation.

#### 3.2. Performance Optimization

*   **Issue 5: Repeated Calculation in Loop**
    *   `len(secret_key)` is calculated in every iteration of the `for line in f:` loop. This is an unnecessary repeated computation if `secret_key` is constant.
*   **Issue 6: Inefficient String Concatenation**
    *   Appending to `output_lines` and then iterating to write line by line can be less efficient than using `writelines()` or joining strings for very large lists.

#### 3.3. Security Vulnerabilities

*   **Issue 7: Path Traversal Vulnerability**
    *   `filepath` and `output_filename` are used directly without any sanitization or validation. A malicious user could provide paths like `../../etc/passwd` to read/write to arbitrary system files.
*   **Issue 8: Sensitive Data Handling (`secret_key`)**
    *   The `secret_key` is used in a direct mathematical operation. While the exact security implication depends on the context, using a "secret key" for simple multiplication often indicates a misunderstanding of cryptographic principles or a non-secure use of sensitive data. If it's truly a secret, its handling needs much more rigor.

#### 3.4. Maintainability & Readability

*   **Issue 9: Monolithic Function**
    *   The `process_data_from_file` function handles reading, parsing, processing, and writing. This violates the Single Responsibility Principle, making the function harder to understand, test, and reuse.
*   **Issue 10: Magic Numbers**
    *   The literal `2` (`if len(parts) == 2:`) is a magic number, making the code less readable and harder to modify if the input format changes.
*   **Issue 11: Unclear Variable Names**
    *   `threshold_val` could be more descriptive, e.g., `min_value_threshold`.
*   **Issue 12: Lack of Type Hinting**
    *   No type hints are used, reducing clarity on expected input/output types and hindering static analysis.
*   **Issue 13: Redundant `processed_count`**
    *   `processed_count` is simply `len(data)` at the end of the processing loop.

#### 3.5. Adherence to Best Practices

*   **Issue 14: Logging vs. Printing**
    *   `print()` statements are used for error messages and status updates. In a production environment, proper logging (e.g., using Python's `logging` module) is preferred for better control over log levels, destinations, and formatting.
*   **Issue 15: No Docstrings/Comments for Complex Logic**
    *   While there's a basic docstring, the processing logic itself could benefit from inline comments explaining the "why" behind certain operations, especially the `value * len(secret_key)` part.

---

### 4. Refactoring Recommendations & Production-Ready Code

Based on the analysis, here is a refactored version of the code, incorporating best practices for correctness, performance, security, and maintainability. Each significant change is explained.

Sandboxed live preview

python

import os

import logging

from typing import List, Dict, Any, Union

Configure basic logging

In a real application, this would be configured more robustly (e.g., to a file, rotating logs)

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class DataProcessingError(Exception):

"""Custom exception for data processing errors."""

pass

class FileOperationError(Exception):

"""Custom exception for file operation errors."""

pass

def _sanitize_filepath(filepath: str) -> str:

"""

Sanitizes a filepath to prevent path traversal attacks.

Ensures the path is normalized and within an expected base directory.

For demonstration, we'll just normalize. In a real app,

you'd define a safe base directory and check against it.

"""

# Normalize the path to resolve '..' and '.'

normalized_path = os.path.normpath(filepath)

# Example of a more robust check:

# BASE_DIR = "/var/data/my_app_data"

# if not normalized_path.startswith(BASE_DIR):

# raise FileOperationError(f"Attempted path traversal: {filepath}")

# Further checks might involve ensuring it's not an absolute path if only relative paths are expected,

# or checking against a list of allowed extensions.

return normalized_path

def read_data_from_file(filepath: str) -> List[Dict[str, Union[str, int]]]:

"""

Reads data from a specified file, parsing each line into a dictionary.

Each line is expected to be in 'name,value' format.

Args:

filepath (str): The path to the input file.

Returns:

List[Dict[str, Union[str, int]]]: A list of dictionaries, each containing 'name' (str)

and 'value' (int).

Raises:

FileOperationError: If the file cannot be found or accessed.

DataProcessingError: If a line is malformed and cannot be parsed.

"""

sanitized_filepath = _sanitize_filepath(filepath)

parsed_data = []

try:

with open(sanitized_filepath, 'r', encoding='utf-8') as f: # Use 'with' statement for safe file handling

for line_num, line in enumerate(f, 1):

stripped_line = line.strip()

if not stripped_line: # Skip empty lines

continue

parts = stripped_line.split(',')

EXPECTED_PARTS_COUNT = 2 # Replaced magic number

if len(parts) == EXPECTED_PARTS_COUNT:

try:

name = parts[0].strip()

value = int(parts[1].strip())

parsed_data.append({'name': name, 'value': value})

except ValueError as ve:

logging.warning(f"Line {line_num}: Skipping malformed line (value not integer): '{stripped_line}' - {ve}")

# Optionally, raise DataProcessingError here if strict parsing is required

else:

logging.warning(f"Line {line_num}: Skipping malformed line (incorrect parts count, expected {EXPECTED_PARTS_COUNT}): '{stripped_line}'")

# Optionally, raise DataProcessingError here

except FileNotFoundError as e:

logging.error(f"Input file not found: {sanitized_filepath}")

raise FileOperationError(f"Input file not found: {sanitized_filepath}") from e

except IOError as e:

logging.error(f"Error reading file {sanitized_filepath}: {e}")

raise FileOperationError(f"Error reading file {sanitized_filepath}") from e

except Exception as e:

logging.critical(f"An unexpected critical error occurred during file read from {sanitized_filepath}: {e}")

raise FileOperationError(f"An unexpected error occurred during file read: {e}") from e

logging.info(f"Successfully read and parsed {len(parsed_data)} items from {sanitized_filepath}")

return parsed_data

def process_data(data: List[Dict[str, Union[str, int]],],

min_value_threshold: int,

transformation_factor: int) -> List[Dict[str, int]]:

"""

Processes a list of data items based on a threshold and applies a transformation.

Args:

data (List[Dict[str, Union[str, int]]]): The list of parsed data, each with 'name' and 'value'.

min_value_threshold (int): The minimum value an item must have to be processed.

transformation_factor (int): The factor to multiply the value by.

Returns:

List[Dict[str, int]]: A

collab Output

We have completed the "AI Code Review" workflow, focusing on a comprehensive analysis of the provided codebase (or a general template if no code was provided) with detailed suggestions for improvement and refactoring. This deliverable outlines the findings, actionable recommendations, and best practices to enhance the code's quality, performance, security, and maintainability.


AI Code Review: Comprehensive Analysis & Refactoring Suggestions

This report provides a thorough AI-driven code review, offering insights into potential issues, security vulnerabilities, performance bottlenecks, and areas for refactoring. The goal is to elevate the codebase to a higher standard of quality, robustness, and efficiency.

Disclaimer: As no specific code was provided for this review iteration, this report outlines a comprehensive template for an AI Code Review. It covers common best practices, potential issues, and refactoring strategies applicable to a wide range of programming contexts. When actual code is provided, this structure will be populated with highly specific, actionable feedback tailored to your codebase.


1. Executive Summary

The AI Code Review process systematically evaluates code against established best practices, design principles, and common pitfalls. This report synthesizes these evaluations into actionable recommendations. Our primary objective is to identify opportunities for:

  • Improved Readability and Maintainability: Making the code easier to understand, debug, and extend.
  • Enhanced Performance: Optimizing code execution for speed and resource efficiency.
  • Robust Security: Identifying and mitigating potential vulnerabilities.
  • Reduced Technical Debt: Streamlining complex logic and addressing anti-patterns.
  • Better Error Handling: Ensuring resilience and graceful degradation.

2. Code Review Findings (General Template)

This section details common areas where improvements are often needed.

2.1. Clarity and Readability

  • Observation:

* Complex Logic: Functions or methods exceeding a reasonable line count or cyclomatic complexity, making them difficult to grasp at a glance.

* Inconsistent Naming Conventions: Mix of camelCase, snake_case, or PascalCase for variables, functions, and classes.

* Insufficient Comments/Documentation: Lack of explanation for non-obvious logic, complex algorithms, or public APIs.

* Magic Numbers/Strings: Hardcoded literal values without clear explanation or named constants.

  • Impact: Increases cognitive load, slows down debugging, makes onboarding new developers challenging, and raises the risk of introducing new bugs during modifications.

2.2. Error Handling and Resilience

  • Observation:

* Generic Exception Handling: Catching broad exceptions (e.g., Exception in Python/Java, catch (e: any) in TypeScript) without specific error handling logic.

* Missing Error Paths: Scenarios where an operation might fail are not explicitly handled, leading to unexpected crashes or incorrect states.

* Inadequate Logging: Error messages are vague, lack context (e.g., input parameters, stack trace), or are not logged at appropriate levels.

* Resource Leaks: Files, database connections, or network sockets not properly closed in error scenarios.

  • Impact: System instability, difficult debugging in production, potential data corruption, and poor user experience.

2.3. Performance Bottlenecks

  • Observation:

* Inefficient Algorithms: Use of algorithms with high time complexity (e.g., O(n^2) when O(n log n) or O(n) is possible).

* N+1 Query Problems: Repeated database queries within a loop, leading to excessive database load.

* Unoptimized Loops: Redundant computations inside loops, or iterating over large collections inefficiently.

* Lack of Caching: Repeated computations or data fetches that could benefit from caching.

* Synchronous I/O in Asynchronous Contexts: Blocking operations in performance-critical paths.

  • Impact: Slow application response times, high resource consumption (CPU, memory, network), poor scalability under load.

2.4. Security Vulnerabilities

  • Observation:

* Lack of Input Validation: User inputs not properly sanitized or validated, opening doors for injection attacks (SQL, XSS, Command Injection).

* Hardcoded Credentials/Sensitive Data: API keys, database passwords, or other secrets directly embedded in the codebase.

* Insecure Dependencies: Use of outdated libraries with known vulnerabilities.

* Broken Authentication/Authorization: Weak session management, predictable tokens, or improper access control checks.

* Improper Error Messages: Revealing too much sensitive information (e.g., stack traces, database schema) in error responses.

  • Impact: Data breaches, unauthorized access, system compromise, reputational damage, and regulatory non-compliance.

2.5. Duplication and Redundancy (DRY Principle)

  • Observation:

* Repeated Code Blocks: Identical or very similar logic present in multiple places.

* Similar Utility Functions: Multiple functions performing slightly different variations of the same core task.

  • Impact: Increases maintenance effort (changes need to be applied everywhere), higher risk of inconsistencies, and larger codebase size.

2.6. Maintainability and Extensibility

  • Observation:

* Tight Coupling: Components heavily dependent on each other, making independent modification or testing difficult.

* Large Classes/Functions (God Objects): Single components handling too many responsibilities (violating Single Responsibility Principle).

* Lack of Modularity: Business logic, data access, and presentation concerns intermingled.

* Absence of Design Patterns: Missed opportunities to apply established solutions for common architectural problems.

  • Impact: Difficult to modify, test, and scale; high potential for introducing side effects when changes are made.

3. Refactoring Suggestions & Best Practices

This section provides actionable recommendations to address the identified findings.

3.1. Improve Code Clarity and Readability

  • Break Down Complex Functions/Methods:

* Action: Refactor large functions into smaller, more focused units, each responsible for a single task. Use descriptive names for these new functions.

* Benefit: Improves readability, testability, and reusability.

  • Standardize Naming Conventions:

* Action: Adopt a consistent naming convention (e.g., PEP 8 for Python, Java Naming Conventions) across the entire codebase. Use meaningful, self-descriptive names for variables, functions, and classes.

* Benefit: Reduces cognitive load and makes the code more intuitive.

  • Add Meaningful Comments and Documentation:

* Action: Introduce comments for complex logic, non-obvious decisions, and public API interfaces. Use docstrings/Javadocs for functions and classes.

* Benefit: Aids understanding for current and future developers.

  • Replace Magic Numbers/Strings with Constants:

* Action: Define named constants for literal values that have special meaning.

* Benefit: Enhances readability and makes code easier to modify.

3.2. Enhance Error Handling and Resilience

  • Implement Specific Exception Handling:

* Action: Catch specific exceptions rather than generic ones. Provide tailored recovery logic or informative error messages.

* Benefit: Improves robustness and allows for precise error management.

  • Ensure Proper Resource Management:

* Action: Use try-with-resources (Java), with statements (Python), or defer (Go) to ensure resources like files and connections are always closed.

* Benefit: Prevents resource leaks and system instability.

  • Improve Logging Strategy:

* Action: Implement structured logging. Log errors with sufficient context (user ID, request ID, relevant parameters, stack trace) and at appropriate severity levels (DEBUG, INFO, WARN, ERROR, CRITICAL).

* Benefit: Facilitates faster debugging and monitoring in production.

3.3. Optimize Performance

  • Refactor Inefficient Algorithms:

* Action: Review critical paths and replace algorithms with better time complexity. Profile the application to identify actual bottlenecks.

* Benefit: Significant speed improvements and better scalability.

  • Address N+1 Query Problems:

* Action: Use eager loading, join queries, or batching techniques provided by ORMs/database drivers to fetch related data in a single query.

* Benefit: Drastically reduces database load and query execution time.

  • Implement Caching Mechanisms:

* Action: Introduce in-memory caches (e.g., Redis, Memcached) for frequently accessed, slow-changing data or results of expensive computations.

* Benefit: Reduces latency and load on backend services/databases.

  • Utilize Asynchronous Operations:

* Action: For I/O-bound tasks (network calls, database access), leverage asynchronous programming patterns (async/await, promises, goroutines) to prevent blocking the main thread.

* Benefit: Improves responsiveness and throughput.

3.4. Fortify Security

  • Implement Robust Input Validation and Sanitization:

* Action: Validate all user inputs on the server-side against expected types, formats, and lengths. Sanitize inputs to prevent injection attacks (e.g., HTML escaping for XSS, parameterized queries for SQL injection).

* Benefit: Prevents a wide range of common web vulnerabilities.

  • Securely Manage Credentials and Sensitive Data:

* Action: Store sensitive data (API keys, database credentials) in environment variables, secret management services (e.g., AWS Secrets Manager, HashiCorp Vault), or configuration files external to the codebase. Never hardcode them.

* Benefit: Prevents compromise of credentials if the codebase is exposed.

  • Regularly Update and Scan Dependencies:

* Action: Use dependency management tools (e.g., npm audit, pip-audit, Dependabot) to regularly check for and update vulnerable libraries.

* Benefit: Mitigates risks from known security flaws in third-party components.

  • Implement Proper Authentication and Authorization:

* Action: Use strong, industry-standard authentication mechanisms. Implement granular access control checks at every relevant endpoint/resource. Ensure secure session management.

* Benefit: Prevents unauthorized access and privilege escalation.

3.5. Eliminate Duplication (DRY Principle)

  • Extract Common Logic into Reusable Components:

* Action: Identify repeated code blocks and refactor them into shared functions, utility classes, or modules.

* Benefit: Reduces codebase size, simplifies maintenance, and ensures consistency.

3.6. Improve Maintainability and Extensibility

  • Apply Design Patterns:

* Action: Consider applying appropriate design patterns (e.g., Factory, Strategy, Observer, Repository, Service Layer) to solve recurring design problems and improve structure.

* Benefit: Enhances modularity, testability, and makes the code easier to extend.

  • Refactor Large Classes/Modules:

* Action: Break down "God Objects" into smaller, more focused classes, each with a single responsibility (Single Responsibility Principle).

* Benefit: Reduces complexity, improves cohesion, and simplifies testing.

  • Reduce Coupling:

* Action: Use dependency injection, interfaces, and event-driven architectures to decouple components.

* Benefit: Makes components easier to test independently and swap out implementations.


4. Testing Strategy Recommendations

A robust testing strategy is crucial for maintaining code quality and confidence in changes.

  • Implement Comprehensive Unit Tests:

* Action: Write unit tests for individual functions, methods, and small classes, ensuring they cover various inputs, edge cases, and error conditions.

* Benefit: Catches bugs early, facilitates refactoring, and documents expected behavior.

  • Develop Integration Tests:

* Action: Create tests that verify the interaction between different components (e.g., database interactions, API calls between services).

* Benefit: Ensures that integrated parts of the system work correctly together.

  • Establish End-to-End (E2E) Tests:

* Action: Implement tests that simulate user journeys through the application from start to finish.

* Benefit: Validates the entire system from a user's perspective, catching issues that might slip past unit/integration tests.

  • Aim for High Test Coverage:

* Action: Use code coverage tools to monitor and strive for a high percentage of code covered by tests.

* Benefit: Provides confidence that most of the codebase is exercised by tests.

  • Utilize Mocking/Stubbing:

* Action: For external dependencies (databases, external APIs), use mocks or stubs in unit tests to isolate the code under test.

* Benefit: Makes tests faster, more reliable, and independent of external systems.


5. Future Enhancements & Continuous Improvement

To maintain a high standard of code quality, consider integrating the following:

  • Automated Code Quality Tools: Integrate linters (e.g., ESLint, Pylint), formatters (e.g., Prettier, Black), and static analysis tools (e.g., SonarQube, Bandit) into the CI/CD pipeline.
  • Code Review Automation: Leverage AI-powered tools for pre-commit or pre-merge code reviews to catch common issues automatically.
  • Performance Monitoring: Implement APM (Application Performance Monitoring) tools to continuously track application performance in production and identify emerging bottlenecks.
  • Security Scanning: Regularly run SAST (Static Application Security Testing) and DAST (Dynamic Application Security Testing) tools.
  • Regular Refactoring Sprints: Allocate dedicated time for refactoring and technical debt reduction as part of the development cycle.

6. Next Steps

Based on this comprehensive review, we recommend the following actions:

  1. Prioritize Findings: Review the Code Review Findings and Refactoring Suggestions sections. Prioritize the recommendations based on impact (e.g., security vulnerabilities and critical performance issues first) and effort.
  2. **Create Action Items
ai_code_review.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);}});}