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

AI Code Review: Comprehensive Analysis and Refactoring

This document presents a comprehensive AI-driven code review of the provided Python code snippet. Our analysis focuses on code quality, potential issues, performance, adherence to best practices, and offers detailed refactoring suggestions to enhance maintainability, robustness, and readability.


1. Review Summary

The initial code snippet demonstrates an attempt to create a versatile data processing function that reads data from JSON or CSV files, performs a simple transformation, and writes the results to a new file in a specified format. While functional for basic use cases, the current implementation suffers from several common issues, including a violation of the Single Responsibility Principle (SRP), inconsistent error handling, lack of input validation, and brittle file path manipulation.

The primary goal of this review is to refactor the code into a modular, robust, and extensible solution, making it production-ready.


2. Initial Code Under Review

text • 3,972 chars
---

### 3. Detailed Review and Observations

#### 3.1. Code Quality & Maintainability

*   **Single Responsibility Principle (SRP) Violation**: The `process_data_file` function handles reading, processing, and writing data. This makes it hard to test, modify, and reuse individual components.
*   **Readability**: The function is long and contains deeply nested logic, which reduces readability and increases cognitive load.
*   **Duplication**: Logic for creating `output_filepath` is duplicated. Data processing logic for `value` and `amount` is similar.
*   **Magic Strings**: File extensions (`.json`, `.csv`) and output formats (`json`, `csv`) are hardcoded.
*   **Type Hinting & Docstrings**: Lacks type hints for function arguments and return values, making the API less clear. No docstrings are present, hindering understanding of the function's purpose, arguments, and behavior.

#### 3.2. Error Handling & Robustness

*   **Inconsistent Error Reporting**: Errors are reported via `print()` statements and the function returns `None`. This makes programmatic error handling difficult for callers. It's generally better to raise specific exceptions or use a logging mechanism.
*   **Broad Exception Catch**: `except Exception as e:` catches all exceptions, potentially masking unexpected issues and making debugging harder.
*   **File Path Generation**: `filepath.replace('.', '_processed.')` is brittle. For example, `my.data.json` would become `my_processed.data.json`, which might not be the desired behavior. It also doesn't handle cases where the file has no extension.
*   **Input Validation**: No explicit validation for `filepath` (e.g., if it's a string, if it exists before trying to open) or `output_format` (e.g., if it's one of the supported values).
*   **Edge Cases**:
    *   If `processed_data` is empty for CSV output, it prints "No data to write" but still returns `None`. This behavior is inconsistent with other error paths.
    *   What if `processed_data[0]` doesn't exist when trying to get `fieldnames` for CSV? (Handled by `if processed_data:`, but could be more explicit).

#### 3.3. Performance & Efficiency

*   **Memory Usage**: For very large files, `json.load(f)` and `data.append(row)` for CSV will load the entire dataset into memory. While acceptable for small files, this can lead to memory exhaustion for large inputs. A streaming approach might be necessary for scalability. (This review assumes moderate file sizes for the proposed refactoring).

#### 3.4. Security Considerations

*   **No Obvious Vulnerabilities**: For this specific code, no direct security vulnerabilities (like SQL injection or XSS) are apparent as it's purely local file processing. However, if `filepath` or `output_format` were user-controlled inputs in a larger application context, proper sanitization and validation would be crucial to prevent path traversal or arbitrary file writing.

---

### 4. Refactoring Suggestions & Actionable Improvements

To address the identified issues, we propose the following refactoring strategy:

1.  **Decompose into Smaller Functions**: Separate concerns into dedicated functions for reading, processing, and writing data.
2.  **Robust Error Handling**: Replace `print()` statements with custom exceptions or a logging framework.
3.  **Path Manipulation with `pathlib`**: Use Python's `pathlib` module for safer and more intuitive file path operations.
4.  **Flexible Data Processing**: Abstract the data processing logic into a separate, configurable function.
5.  **Input Validation**: Implement explicit checks for input parameters.
6.  **Add Type Hints and Docstrings**: Improve code clarity and maintainability.
7.  **Logging**: Integrate a standard logging mechanism instead of `print()` for better operational visibility.

---

### 5. Production-Ready Code (Refactored Version)

The following code implements the suggested refactoring, resulting in a cleaner, more robust, and maintainable solution.

Sandboxed live preview

python

import json

import csv

import logging

from pathlib import Path

from typing import List, Dict, Any, Callable, Optional, Union

--- Configure Logging ---

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

logger = logging.getLogger(__name__)

--- Custom Exceptions ---

class DataProcessingError(Exception):

"""Base exception for data processing errors."""

pass

class UnsupportedFileFormatError(DataProcessingError):

"""Raised when an unsupported input file format is encountered."""

pass

class UnsupportedOutputFormatError(DataProcessingError):

"""Raised when an unsupported output file format is requested."""

pass

class InvalidDataStructureError(DataProcessingError):

"""Raised when data items do not conform to expected structure."""

pass

--- Helper Functions for File Operations ---

def _read_json_data(filepath: Path) -> List[Dict[str, Any]]:

"""Reads data from a JSON file."""

try:

with open(filepath, 'r', encoding='utf-8') as f:

data = json.load(f)

if not isinstance(data, list):

logger.warning(f"JSON file {filepath} content is not a list. Converting to list.")

data = [data] # Wrap non-list JSON in a list for consistent processing

return data

except FileNotFoundError:

logger.error(f"File not found: {filepath}")

raise

except json.JSONDecodeError as e:

logger.error(f"Invalid JSON format in {filepath}: {e}")

raise

except Exception as e:

logger.exception(f"An unexpected error occurred while reading JSON from {filepath}")

raise

def _read_csv_data(filepath: Path) -> List[Dict[str, Any]]:

"""Reads data from a CSV file."""

try:

with open(filepath, 'r', newline='', encoding='utf-8') as f:

reader = csv.DictReader(f)

return list(reader)

except FileNotFoundError:

logger.error(f"File not found: {filepath}")

raise

except Exception as e:

logger.exception(f"An unexpected error occurred while reading CSV from {filepath}")

raise

def _write_json_data(filepath: Path, data: List[Dict[str, Any]]) -> None:

"""Writes data to a JSON file."""

try:

with open(filepath, 'w', encoding='utf-8') as f:

json.dump(data, f, indent=4)

logger.info(f"Data successfully written to JSON file: {filepath}")

except Exception as e:

logger.exception(f"Error writing data to JSON file {filepath}")

raise

def _write_csv_data(filepath: Path, data: List[Dict[str, Any]]) -> None:

"""Writes data to a CSV file."""

if not data:

logger.warning(f"No data to write to CSV file: {filepath}")

return

try:

# Determine fieldnames from the first item, assuming consistent structure

fieldnames = list(data[0].keys())

with open(filepath, 'w', newline='', encoding='utf-8') as f:

writer = csv.DictWriter(f, fieldnames=fieldnames)

writer.writeheader()

writer.writerows(data)

logger.info(f"Data successfully written to CSV file: {filepath}")

except IndexError:

logger.error(f"Cannot determine CSV fieldnames from empty data list for {filepath}")

raise InvalidDataStructureError("Data list is empty, cannot infer CSV headers.")

except Exception as e:

logger.exception(f"Error writing data to CSV file {filepath}")

raise

--- Core Data Processing Logic ---

def default_processor(item: Dict[str, Any]) -> Optional[Dict[str, Any]]:

"""

Default processing function: Multiplies 'value' or 'amount' by 2.

Returns the modified item or None if not suitable for processing.

"""

collab Output

Project: AI Code Review - Refactoring & Suggestions

Workflow Step: collab → ai_refactor (Step 2 of 2)

Date: October 26, 2023


Overall Assessment & Refactoring Focus

This comprehensive AI-driven code review has identified several opportunities to enhance the provided codebase. While the code appears to be functional, focusing on refactoring will significantly improve its maintainability, readability, performance, and long-term scalability.

The primary focus of these refactoring suggestions is to:

  1. Improve Code Readability and Maintainability: Make the code easier to understand, debug, and extend for current and future developers.
  2. Optimize Performance: Identify and suggest changes to reduce execution time and resource consumption.
  3. Enhance Robustness and Error Handling: Improve the code's ability to gracefully handle unexpected inputs or states.
  4. Reduce Technical Debt: Address common anti-patterns and introduce best practices.
  5. Promote Modularity and Reusability: Break down complex logic into smaller, testable, and reusable components.

Key Areas Identified for Refactoring

Based on a thorough analysis, the following key areas have been identified for refactoring:

  • Code Readability & Maintainability: Addressing long functions, unclear variable names, and lack of comments/documentation.
  • Performance Optimization: Identifying inefficient algorithms, redundant computations, and suboptimal data structure usage.
  • Error Handling & Robustness: Suggesting improvements for error propagation, specific exception handling, and input validation.
  • Code Duplication & Abstraction: Recommending the consolidation of repetitive code blocks into reusable functions or classes.
  • Security Enhancements: Pointing out potential vulnerabilities and suggesting secure coding practices.
  • Testability & Modularity: Advocating for changes that make components easier to isolate and test.

Detailed Refactoring Suggestions & Examples

Below are detailed suggestions for refactoring, accompanied by conceptual "Before" and "After" examples to illustrate the proposed changes.

1. Code Readability & Maintainability

  • Issue: Overly Long Functions/Methods

* Rationale: Functions with too many lines of code or multiple responsibilities become difficult to understand, test, and maintain. They often violate the Single Responsibility Principle (SRP).

* Proposed Refactoring: Extract smaller, more focused functions from the larger one. Each new function should ideally do one thing and do it well.

* Conceptual Example:


        # BEFORE: Long and complex function
        def process_user_data(user_info, preferences, system_settings):
            # 1. Validate user_info
            if not validate_user_input(user_info):
                raise ValueError("Invalid user info")
            
            # 2. Format data
            formatted_data = format_input(user_info)
            
            # 3. Apply preferences
            final_data = apply_user_preferences(formatted_data, preferences)
            
            # 4. Store in database
            store_to_db(final_data)
            
            # 5. Generate report
            report = generate_summary_report(final_data, system_settings)
            
            # 6. Send notification
            send_email_notification(report, user_info['email'])
            
            return {"status": "success", "report": report}

        # AFTER: Extracted smaller, focused functions
        def _validate_user_input(user_info):
            # ... validation logic ...
            pass

        def _format_input_data(user_info):
            # ... formatting logic ...
            pass
            
        def _apply_preferences(data, preferences):
            # ... preference application logic ...
            pass

        def _store_data(data):
            # ... database storage logic ...
            pass

        def _generate_report(data, settings):
            # ... report generation logic ...
            pass

        def _send_notification(report, email):
            # ... email sending logic ...
            pass

        def process_user_data(user_info, preferences, system_settings):
            _validate_user_input(user_info)
            formatted_data = _format_input_data(user_info)
            final_data = _apply_preferences(formatted_data, preferences)
            _store_data(final_data)
            report = _generate_report(final_data, system_settings)
            _send_notification(report, user_info['email'])
            return {"status": "success", "report": report}
  • Issue: Unclear Variable/Function Names

* Rationale: Ambiguous names make it hard to understand the purpose of variables or functions without deep code analysis.

* Proposed Refactoring: Use descriptive, self-documenting names that clearly convey intent.

* Conceptual Example:


        # BEFORE
        def proc(d, p):
            temp = d['id'] + '_' + p
            # ... more logic ...
            return temp

        # AFTER
        def generate_user_identifier(user_details, prefix):
            user_id = user_details['user_id']
            formatted_identifier = f"{user_id}_{prefix}"
            # ... more logic ...
            return formatted_identifier

2. Performance Optimization

  • Issue: Inefficient Loop or Data Structure Usage

* Rationale: Using nested loops for operations that could be done with a single pass, or choosing a list for frequent lookups instead of a dictionary/hash map, can lead to significant performance bottlenecks (e.g., O(n^2) instead of O(n) or O(1)).

* Proposed Refactoring: Review algorithms for complexity. Utilize appropriate data structures (e.g., sets for membership testing, dictionaries for fast lookups, generators for large data streams).

* Conceptual Example (Pythonic Optimization):


        # BEFORE: Inefficient list lookup in a loop
        products = [{"id": 1, "name": "A"}, {"id": 2, "name": "B"}, {"id": 3, "name": "C"}]
        order_ids = [2, 1]
        
        ordered_products = []
        for order_id in order_ids:
            for product in products:
                if product["id"] == order_id:
                    ordered_products.append(product)
                    break # Found it, break inner loop

        # AFTER: Using a dictionary for O(1) average time lookup
        products_map = {product["id"]: product for product in products} # Pre-process to O(N)
        
        ordered_products_optimized = [products_map[order_id] for order_id in order_ids if order_id in products_map]
  • Issue: Redundant Computations

* Rationale: Performing the same expensive calculation multiple times within a loop or function when the result doesn't change can waste CPU cycles.

* Proposed Refactoring: Cache results of expensive computations, or move them outside loops if their inputs are constant within the loop's scope.

* Conceptual Example:


        # BEFORE
        def process_items(items):
            result = []
            for item in items:
                # Assuming get_complex_config() is an expensive call
                config = get_complex_config() 
                processed_item = apply_config(item, config)
                result.append(processed_item)
            return result

        # AFTER
        def process_items_optimized(items):
            config = get_complex_config() # Called only once
            result = []
            for item in items:
                processed_item = apply_config(item, config)
                result.append(processed_item)
            return result

3. Error Handling & Robustness

  • Issue: Broad/Bare Exception Handling (except:)

* Rationale: Catching all exceptions (except:) can mask underlying issues, making debugging difficult and potentially hiding critical errors. It can also catch SystemExit or KeyboardInterrupt, preventing graceful termination.

* Proposed Refactoring: Catch specific exceptions relevant to the expected failure modes. Log exceptions with full traceback for debugging.

* Conceptual Example:


        # BEFORE
        try:
            data = read_config_file("config.json")
            process(data)
        except: # Catches everything, including SystemExit, KeyboardInterrupt
            print("An error occurred.")

        # AFTER
        import logging
        logging.basicConfig(level=logging.ERROR)

        try:
            data = read_config_file("config.json")
            process(data)
        except FileNotFoundError:
            logging.error("Configuration file not found. Please check path.")
            # Handle specifically, e.g., use default config
        except json.JSONDecodeError:
            logging.error("Invalid JSON format in config file.")
            # Handle specifically, e.g., notify administrator
        except Exception as e: # Catch other unexpected errors
            logging.exception(f"An unexpected error occurred during processing: {e}")
            # Re-raise or handle gracefully, e.g., return error state
  • Issue: Lack of Input Validation

* Rationale: Unvalidated inputs can lead to runtime errors, security vulnerabilities (e.g., injection attacks), or unexpected behavior.

* Proposed Refactoring: Implement explicit input validation at the boundaries of your system (API endpoints, function parameters).

* Conceptual Example:


        # BEFORE
        def get_user_by_id(user_id):
            return db.query("SELECT * FROM users WHERE id = " + str(user_id)) # SQL Injection risk if user_id is not int

        # AFTER
        def get_user_by_id(user_id):
            if not isinstance(user_id, int) or user_id <= 0:
                raise ValueError("Invalid user_id: Must be a positive integer.")
            # Using parameterized query to prevent SQL injection
            return db.query("SELECT * FROM users WHERE id = ?", (user_id,))

4. Code Duplication & Abstraction

  • Issue: Repeated Code Blocks (DRY Violation)

* Rationale: Duplicated code increases maintenance effort (a bug fix or feature change needs to be applied in multiple places) and increases the likelihood of inconsistencies.

* Proposed Refactoring: Extract duplicated logic into a new function, method, or class. Use higher-order functions or design patterns where appropriate.

* Conceptual Example:


        # BEFORE
        def process_type_A(data):
            # ... common validation ...
            if not data: return None
            # ... specific logic A ...
            result_a = data * 2
            # ... common logging ...
            print(f"Processed A: {result_a}")
            return result_a

        def process_type_B(data):
            # ... common validation ...
            if not data: return None
            # ... specific logic B ...
            result_b = data + 10
            # ... common logging ...
            print(f"Processed B: {result_b}")
            return result_b

        # AFTER
        def _common_validation(data):
            if not data:
                print("Invalid input data.")
                return False
            return True

        def _common_logging(process_type, result):
            print(f"Processed {process_type}: {result}")

        def process_type_A(data):
            if not _common_validation(data): return None
            result_a = data * 2
            _common_logging("A", result_a)
            return result_a

        def process_type_B(data):
            if not _common_validation(data): return None
            result_b = data + 10
            _common_logging("B", result_b)
            return result_b

Benefits of Implementing Proposed Changes

Implementing these refactoring suggestions will yield significant benefits:

  • Increased Maintainability: Easier to understand, modify, and extend the codebase.
  • Reduced Debugging Time: Clearer code and specific error handling make identifying and fixing bugs faster.
  • Improved Performance: Optimized algorithms and resource usage lead to faster execution and lower operational costs.
  • Enhanced Reliability: Robust error handling and input validation prevent unexpected crashes and ensure stable operation.
  • Lower Technical Debt: Addresses underlying structural issues, making future development more efficient.
  • Better Collaboration: Standardized practices and clear code facilitate teamwork.
  • Improved Security Posture: Identification and mitigation of common security vulnerabilities.

Recommended Next Steps

  1. Review and Prioritize: Carefully review all suggestions. Prioritize refactoring tasks based on their impact (e.g., critical bugs, performance bottlenecks, high-risk security issues) and effort required.
  2. Iterative Implementation: Implement changes incrementally. Avoid large, sweeping refactors that can introduce new risks.
  3. Thorough Testing: Ensure that after each refactoring step, existing tests pass, and new tests are added to cover the refactored logic. If automated tests are lacking, this is an excellent opportunity to introduce them.
  4. Version Control: Commit changes frequently and use meaningful commit messages. Consider feature branches for larger refactoring efforts.
  5. Code Review (Human): While this is an AI review, a human peer review of the implemented refactoring is always recommended to catch any nuances or overlooked details.
  6. Documentation Update: Update any relevant documentation (inline comments, READMEs, design documents) to reflect the changes.

Disclaimer

This AI-generated code review and refactoring suggestion is based on static analysis and best practices. While comprehensive, it may not capture all business logic nuances or implicit requirements. Human review, judgment, and thorough testing are always recommended before deploying any refactored code to production.

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