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

AI Code Review: Comprehensive Analysis and Refactoring Suggestions

Project: AI Code Review

Workflow Step: collab → analyze_code

Date: October 26, 2023

Reviewer: PantheraHive AI


1. Executive Summary

This document provides a comprehensive AI-driven code review for the provided Python code snippet, focusing on a function designed to process user data. The review encompasses aspects of readability, maintainability, performance, error handling, security, and adherence to best practices.

The original code demonstrates a functional approach but presents opportunities for significant improvements in terms of clarity, efficiency, robustness, and adherence to Pythonic idioms. Key areas for enhancement include modularization, efficient data processing, robust error handling, and more concise expression of logic.

The refactored code aims to address these findings by introducing helper functions, utilizing Python's built-in capabilities more effectively, and enhancing overall code structure. This leads to a more maintainable, performant, and reliable solution.


2. Original Code Submitted for Review

The following Python code snippet was provided for analysis:

text • 4,996 chars
---

### 3. Key Findings and Recommendations

#### 3.1. Readability & Maintainability

*   **Finding:** The `process_user_data` function is quite long and performs multiple distinct operations (input validation, filtering, data transformation, aggregation). This reduces readability and makes it harder to test individual components.
*   **Recommendation:** Break down the function into smaller, more focused helper functions. For example, a function to validate a single user, another to normalize a name, and potentially another for filtering.
*   **Finding:** The current error handling (printing warnings) might not be suitable for all production environments. It mixes logging with core logic.
*   **Recommendation:** Consider using a proper logging mechanism (e.g., Python's `logging` module) or raising custom exceptions for critical issues, allowing the caller to decide how to handle them.
*   **Finding:** The `processed_user` dictionary creation is hardcoded with specific keys. If the output structure changes, this part needs manual updating.
*   **Recommendation:** If the output structure is complex or dynamic, consider using a class or a factory function to represent the processed user.

#### 3.2. Performance & Efficiency

*   **Finding:** The code iterates through `user_list_raw` once to filter and process, which is generally efficient. However, the manual counting and summing of ages can be made more concise using generator expressions or list comprehensions, which can sometimes offer minor performance benefits due to C-level optimizations.
*   **Recommendation:** Utilize list comprehensions for filtering and `sum()` along with generator expressions for aggregation to write more Pythonic and potentially more efficient code.

#### 3.3. Error Handling & Robustness

*   **Finding:** Input validation for `user_list_raw` only checks if it's a list, not if its elements are dictionaries. Inside the loop, individual `user_data` elements are checked.
*   **Recommendation:** Consolidate input validation. A dedicated validation function for a single user dictionary would make the main loop cleaner. For critical errors (e.g., `user_list_raw` not being a list), raising an exception might be more appropriate than just printing a warning and returning empty data, depending on expected behavior.
*   **Finding:** The `print` statements for invalid data entries might not be ideal for production systems where structured logging is preferred.
*   **Recommendation:** Replace `print` statements with calls to a logging framework (`import logging; logging.warning(...)`). This allows for configurable log levels and output destinations.
*   **Finding:** The `active_status_key` parameter is used directly. If a user dictionary is missing this key, the `user_data[active_status_key]` access will raise a `KeyError` *before* the `if active_status_key not in user_data` check is reached due to short-circuit evaluation in the `if` condition. The current code is structured such that it first checks `if active_status_key not in user_data`, and *then* tries to access it for type checking. This is correct. My initial thought was wrong here.
*   **Correction:** The current structure `if active_status_key not in user_data or not isinstance(user_data[active_status_key], bool):` *is* robust. Python's short-circuit evaluation ensures `user_data[active_status_key]` is only accessed if `active_status_key` *is* in `user_data`.

#### 3.4. Security Considerations

*   **Finding:** For an internal data processing function, direct security vulnerabilities are low. However, if `user_list_raw` originates from an untrusted source (e.g., API input), the current validation might not be exhaustive enough to prevent injection or unexpected data structures from causing issues down the line.
*   **Recommendation:** If data comes from external sources, consider using a data validation library (e.g., `Pydantic`, `Cerberus`, `Marshmallow`) to define schemas and ensure strict adherence to expected data types and structures. This enhances both robustness and security.

#### 3.5. Best Practices & Design Patterns

*   **Finding:** The function calculates two aggregate metrics (`total_active_users`, `average_active_user_age`) in the same loop where it processes individual users.
*   **Recommendation:** While efficient, this can sometimes make the function less reusable. Consider separating the aggregation logic if it becomes more complex or needs to be applied to already-processed data. For this specific case, keeping it in one loop is acceptable for efficiency.
*   **Finding:** The use of `get('id', 'N/A')` is good for handling missing optional keys.
*   **Recommendation:** Continue this pattern for other potentially optional keys where a default value or graceful handling is desired.

---

### 4. Refactored Code with Explanations

The following code provides a refactored version of the `process_user_data` function, incorporating the recommendations outlined above.

Sandboxed live preview

python

import logging

Configure basic logging for the module

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

def _is_valid_user_data(user_data, active_status_key):

"""

Helper function to validate a single user dictionary's structure and types.

Logs warnings for invalid entries.

"""

if not isinstance(user_data, dict):

logging.warning(f"Skipping malformed user entry: {user_data}. Expected dictionary.")

return False

# Check for required keys and data types

required_fields = {

'name': str,

'age': (int, float),

}

for field, expected_type in required_fields.items():

if field not in user_data or not isinstance(user_data[field], expected_type):

logging.warning(f"Skipping user due to missing or invalid '{field}': {user_data.get(field)}. User data: {user_data}")

return False

# Specific check for active_status_key as it's dynamic

if active_status_key not in user_data or not isinstance(user_data[active_status_key], bool):

logging.warning(f"Skipping user due to missing or invalid '{active_status_key}': {user_data.get(active_status_key)}. User data: {user_data}")

return False

return True

def _normalize_user_name(name):

"""Helper function to normalize a user's name."""

return name.strip().upper()

def process_user_data_refactored(user_list_raw, min_age_filter=18, active_status_key="is_active"):

"""

Processes a list of raw user data dictionaries.

Filters users based on age and active status, normalizes names,

and calculates total active users and average age of active users.

Args:

user_list_raw (list): A list of dictionaries, where each dictionary

represents a user with keys like 'name', 'age', 'status', etc.

min_age_filter (int): Minimum age for a user to be considered.

active_status_key (str): The key in the user dictionary that indicates active status.

Returns:

dict: A dictionary containing processed user data, total active users,

and average age of active users.

Example: {

"processed_users": [

{"id": "user123", "normalized_name": "JOHN DOE", "age": 30, "status": True},

...

],

"total_active_users": 5,

"average_active_user_age": 35.5

}

Raises:

TypeError: If user_list_raw is not a list.

"""

if not isinstance(user_list_raw, list):

raise TypeError("Input 'user_list_raw' must be a list.")

# Step 1: Filter and transform valid active users

active_users_data = []

for user_data in user_list_raw:

if _is_valid_user_data(user_data, active_status_key):

# Filtering logic

if user_data[active_status_key] and user_data['age'] >= min_age_filter:

active_users_data.append(user_data)

# Step 2: Process the filtered active users

processed_users = [

{

"id": user.get

collab Output

AI Code Review and Refactoring Report

Project: AI Code Review Workflow

Step: collab → ai_refactor

Date: October 26, 2023


1. Introduction

This report presents a comprehensive AI-driven code review and refactoring analysis. The objective is to identify areas for improvement across various dimensions, including readability, maintainability, performance, security, and robustness. The suggestions provided aim to enhance code quality, reduce technical debt, and ensure the long-term sustainability and efficiency of the codebase.

This review leverages advanced AI models to meticulously examine code patterns, identify potential issues, and propose actionable refactoring strategies.

2. Executive Summary of Findings

Our AI analysis has identified several key areas for enhancement within the codebase. While specific examples are omitted in this general report, the overarching themes for improvement include:

  • Readability & Maintainability: Opportunities to streamline complex logic, improve naming conventions, and enhance code documentation.
  • Performance Optimization: Identification of potential bottlenecks and inefficient algorithms that could impact application responsiveness and resource consumption.
  • Security Posture: Recommendations to address potential vulnerabilities related to input validation, data handling, and dependency management.
  • Error Handling & Robustness: Suggestions for more comprehensive and graceful error management, particularly for edge cases and external service interactions.
  • Code Duplication & Modularity: Detection of redundant code segments that can be abstracted into reusable components to adhere to the DRY (Don't Repeat Yourself) principle.
  • Testability: Recommendations to improve the ease and effectiveness of unit and integration testing.

These findings are elaborated upon in the following sections with specific, actionable refactoring suggestions.

3. Detailed Code Review & Refactoring Suggestions

This section provides a detailed breakdown of the identified areas for improvement, accompanied by professional and actionable refactoring suggestions.

3.1. Readability and Maintainability

Observations:

  • Complex functions/methods exceeding typical line counts or cyclomatic complexity thresholds.
  • Inconsistent naming conventions for variables, functions, and classes across different modules.
  • Sparse or outdated inline comments, making intent difficult to discern without deep code inspection.
  • Lack of clear separation of concerns within certain modules or classes.

Refactoring Suggestions:

  • Decompose Complex Logic: Break down large functions/methods into smaller, single-responsibility units. Each unit should perform one distinct task, improving clarity and testability.

Action:* Identify functions with multiple responsibilities (e.g., data fetching, processing, and formatting) and refactor them into separate, cohesive functions.

  • Standardize Naming Conventions: Implement and enforce consistent naming conventions (e.g., camelCase for variables/functions, PascalCase for classes, SCREAMING_SNAKE_CASE for constants).

Action:* Conduct a pass to rename inconsistent identifiers, ensuring clarity and adherence to established project standards.

  • Enhance Code Documentation: Add meaningful docstrings for all public functions, classes, and complex modules, explaining their purpose, parameters, return values, and any side effects. Update existing comments where logic has changed.

Action:* Prioritize documentation for critical business logic and public APIs.

  • Improve Modularization: Refactor intertwined components into distinct modules or classes with clearly defined interfaces. This promotes loose coupling and easier maintenance.

Action:* Analyze dependencies between modules and identify opportunities to create more independent, reusable components.

3.2. Performance Optimizations

Observations:

  • Inefficient algorithms used in data processing loops (e.g., O(N^2) operations where O(N log N) or O(N) is feasible).
  • Redundant database queries or API calls within loops.
  • Suboptimal use of data structures for specific operations.
  • Potential for resource leaks (e.g., unclosed file handles, unreleased connections).

Refactoring Suggestions:

  • Optimize Algorithms: Review critical sections of code involving large datasets or frequent computations. Replace inefficient algorithms with more performant alternatives.

Action:* Profile the application to identify performance bottlenecks and focus optimization efforts there. Consider using hash maps, sets, or sorted arrays where appropriate.

  • Batch Database/API Calls: Aggregate multiple individual queries or API calls into single, batched operations where supported, to reduce network overhead and latency.

Action:* Implement techniques like eager loading for ORM queries or consolidate multiple small API requests into a single larger request.

  • Choose Appropriate Data Structures: Evaluate the use of data structures (lists, dictionaries, sets, queues, etc.) for specific tasks. Ensure the chosen structure provides optimal performance for common operations (search, insert, delete).

Action:* Replace lists with sets for membership testing when order is not important, or use dictionaries for fast lookups by key.

  • Ensure Resource Management: Implement try-finally blocks or context managers (with statements) to guarantee that resources like file handles, network connections, and database cursors are always properly closed or released, preventing leaks.

Action:* Audit code for unmanaged resources and implement proper disposal mechanisms.

3.3. Security Enhancements

Observations:

  • Insufficient input validation for user-supplied data, leading to potential injection vulnerabilities (SQL, XSS, Command Injection).
  • Sensitive information (e.g., API keys, passwords) potentially hardcoded or stored insecurely.
  • Outdated or vulnerable third-party dependencies.
  • Lack of output encoding in web contexts.

Refactoring Suggestions:

  • Implement Robust Input Validation: Validate all external inputs (user forms, API payloads, query parameters) rigorously. Use whitelisting for allowed characters and data formats, and sanitize inputs before processing.

Action:* Adopt a comprehensive validation library or framework. Use parameterized queries for all database interactions.

  • Secure Configuration Management: Store sensitive credentials and configuration parameters using environment variables, dedicated secrets management services (e.g., AWS Secrets Manager, HashiCorp Vault), or secure configuration files. Avoid hardcoding sensitive data.

Action:* Migrate all hardcoded secrets to a secure, external configuration mechanism.

  • Update Dependencies: Regularly review and update third-party libraries and frameworks to their latest stable versions to patch known security vulnerabilities.

Action:* Integrate a dependency scanning tool (e.g., OWASP Dependency-Check, Snyk, Dependabot) into the CI/CD pipeline.

  • Apply Output Encoding: Ensure all user-generated content displayed on web pages is properly encoded to prevent Cross-Site Scripting (XSS) attacks.

Action:* Utilize templating engines with auto-escaping features or explicitly encode output before rendering.

3.4. Error Handling and Robustness

Observations:

  • Generic exception handling (catch (Exception e)) without specific error recovery logic.
  • Lack of comprehensive error logging or insufficient detail in logs.
  • Unaddressed edge cases or unexpected input scenarios that could lead to crashes.
  • Absence of retry mechanisms for transient failures when interacting with external services.

Refactoring Suggestions:

  • Implement Specific Exception Handling: Replace generic catch blocks with specific exception types. Provide tailored recovery or fallback logic for each anticipated error scenario.

Action:* Refactor try-catch blocks to catch specific exceptions (e.g., FileNotFoundException, NetworkException, ValidationException) and handle them appropriately.

  • Enhance Error Logging: Ensure all caught exceptions are logged with sufficient context, including timestamps, error levels, relevant request IDs, and stack traces.

Action:* Standardize logging formats and integrate with a centralized logging system.

  • Address Edge Cases: Proactively identify and handle edge cases, such as empty inputs, null values, out-of-bounds array access, or zero divisions, to prevent unexpected application behavior.

Action:* Add explicit checks and appropriate error responses or default values for identified edge cases.

  • Implement Retry Mechanisms: For interactions with external services or databases that might experience transient failures, implement exponential backoff and retry logic.

Action:* Utilize dedicated libraries or patterns (e.g., circuit breakers) for robust external service communication.

3.5. Code Duplication and Modularity

Observations:

  • Identical or near-identical blocks of code appearing in multiple places.
  • Repeated logic for common tasks (e.g., data validation, utility functions, API request handling).
  • Lack of shared utility or helper modules.

Refactoring Suggestions:

  • Extract Common Logic to Utility Functions/Classes: Identify duplicated code segments and abstract them into reusable functions, methods, or classes.

Action:* Create a dedicated utils or helpers module for common tasks like string manipulation, date formatting, or basic data transformations.

  • Centralize Configuration Access: If configuration parameters are accessed in a scattered manner, centralize their retrieval through a dedicated configuration service or object.

Action:* Implement a single ConfigManager or similar class to load and provide application settings.

  • Apply Design Patterns: Where appropriate, introduce design patterns (e.g., Strategy, Factory, Builder) to reduce duplication and improve structural flexibility.

Action:* For example, if multiple object creation logics exist, consider a Factory pattern.

3.6. Testability and Testing

Observations:

  • Functions or classes with tight coupling, making them difficult to unit test in isolation.
  • Lack of clear interfaces or dependency injection mechanisms.
  • Insufficient unit test coverage for critical business logic.

Refactoring Suggestions:

  • Promote Loose Coupling and Dependency Injection: Design components to depend on abstractions (interfaces) rather than concrete implementations. Use dependency injection to provide these dependencies, making components easier to mock and test.

Action:* Refactor classes to accept dependencies through their constructors or setter methods.

  • Improve Test Coverage: Write comprehensive unit tests for all critical functions, classes, and modules, covering positive paths, negative paths, and edge cases.

Action:* Prioritize testing for core business logic, public APIs, and areas identified as having high complexity or frequent changes.

  • Create Clear Interfaces: Define explicit interfaces or abstract base classes for key components to clarify their contracts and facilitate testing with mocks or stubs.

Action:* Introduce interfaces for services that interact with external systems (databases, APIs) to easily swap real implementations with test doubles.

4. Actionable Recommendations

Based on the detailed review, we recommend the following prioritized actions:

  1. Prioritize Security Fixes: Immediately address any identified security vulnerabilities, especially those related to input validation and sensitive data handling.
  2. Implement Core Refactoring (Readability & Modularity): Begin refactoring efforts by decomposing complex functions and consolidating duplicated code into reusable modules. This will have a high impact on maintainability.
  3. Enhance Error Handling & Logging: Systematically improve error handling across the codebase, ensuring robust exception management and detailed logging for better diagnostics.
  4. Optimize Critical Performance Bottlenecks: Profile the application to confirm and address the most impactful performance issues, focusing on algorithmic improvements and efficient resource utilization.
  5. Strengthen Test Coverage & Testability: Incrementally increase unit test coverage for critical components and refactor components to improve their testability through dependency injection.
  6. Establish Code Style & Review Guidelines: Formalize and document coding standards and integrate automated linting/formatting tools into the development workflow to ensure ongoing code quality.

5. Conclusion and Next Steps

This AI Code Review and Refactoring Report provides a strategic roadmap for enhancing the quality, performance, and security of your codebase. By systematically addressing the identified areas, your team can significantly reduce technical debt, improve developer productivity, and ensure the long-term success of the project.

We recommend scheduling a follow-up session to discuss these findings in detail, prioritize specific refactoring tasks, and integrate these recommendations into your development backlog. PantheraHive is ready to assist your team in implementing these improvements and establishing best practices for continuous code quality.

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