Unit Test Generator
Run ID: 69cb3a8061b1021a29a871152026-03-31Development
PantheraHive BOS
BOS Dashboard

Step 2: Code Generation for Unit Tests (gemini → generate_code)

This document details the output of the generate_code step, executed by the Gemini model, within the "Unit Test Generator" workflow. This step is responsible for creating clean, well-commented, and production-ready unit test code based on the provided input.


1. Overview of Code Generation

This phase leverages advanced AI capabilities to analyze the structure, logic, and potential edge cases of your source code. The primary goal is to produce a comprehensive suite of unit tests that ensure the reliability, correctness, and robustness of your functions or methods. We focus on generating tests that are:

For this demonstration, we assume the input to this step was a Python function, and the output will be pytest compatible unit tests.


2. Assumed Input Function for Test Generation

To illustrate the capabilities of this step, let's consider a practical example. The following Python function, calculate_discounted_price, is provided as the hypothetical input for which unit tests will be generated:

text • 3,529 chars
---

### 4. Explanation of Generated Code

The generated unit test code follows best practices for `pytest` and provides comprehensive coverage for the `calculate_discounted_price` function:

*   **Imports:**
    *   `pytest`: The testing framework.
    *   `calculate_discounted_price`: The function under test, imported directly from its module (`my_financial_calculations`).
*   **Parameterized Tests (`@pytest.mark.parametrize`):**
    *   **`test_calculate_discounted_price_positive_cases`**: This test function is designed to handle multiple valid input scenarios efficiently. It uses `@pytest.mark.parametrize` to define a list of tuples, where each tuple represents a test case (`price`, `discount`, `expected_price`).
        *   **Coverage:** Includes standard discounts, edge cases (0% and 100% discount), zero price, and fractional values for both price and discount percentage, covering typical and boundary conditions.
        *   **`ids`:** Provides human-readable identifiers for each parameterized test case, making test reports clearer.
        *   **`pytest.approx`**: Crucially, for floating-point comparisons, `pytest.approx` is used instead of direct equality (`==`). This accounts for the inherent precision limitations of floating-point arithmetic, preventing flaky tests due to minor discrepancies.
    *   **`test_calculate_discounted_price_value_error`**: This parameterized test targets `ValueError` exceptions. It verifies that the function correctly raises `ValueError` with the expected error message when provided with invalid numerical inputs (e.g., negative price, discount outside 0-100 range).
        *   **`pytest.raises`**: This context manager is used to assert that a specific exception is raised. It also captures the exception information, allowing for assertion against the error message.
    *   **`test_calculate_discounted_price_type_error`**: This parameterized test specifically checks for `TypeError` exceptions. It ensures that the function correctly validates input types and raises `TypeError` for non-numeric inputs (e.g., strings, `None`, lists, dictionaries).
*   **Specific Edge Cases:**
    *   **`test_calculate_discounted_price_zero_point_one_discount`**: A dedicated test for a very small non-zero discount, ensuring the function correctly handles minute percentage calculations and rounding.
    *   **`test_calculate_discounted_price_high_precision_input`**: Checks how the function behaves with inputs that have many decimal places, specifically verifying the `round(..., 2)` behavior.
*   **Comments:** Extensive comments are included throughout the code to explain the purpose of test functions, specific test cases, and the rationale behind certain assertions (e.g., using `pytest.approx`).
*   **Readability and Maintainability:** The use of `pytest.mark.parametrize` significantly reduces code duplication, making the test suite more concise and easier to maintain. Clear function names and `ids` enhance readability of test results.

---

### 5. Actionable Next Steps

To utilize this generated unit test code:

1.  **Save the Code:** Save the generated test code (from Section 3) into a file named `test_my_financial_calculations.py` (or similar, following `pytest`'s discovery rules, e.g., files starting with `test_` or ending with `_test.py`) in your project's `tests/` directory. Ensure `my_financial_calculations.py` is accessible (e.g., in the project root or on the Python path).
2.  **Install pytest:** If you haven't already, install `pytest`:
    
Sandboxed live preview

As part of the PantheraHive workflow "Unit Test Generator", this deliverable outlines a detailed and professional study plan. This plan is designed to provide a comprehensive understanding of unit testing principles, advanced testing techniques, and the architectural considerations required to build or understand a "Unit Test Generator" tool, including potential AI/ML integration.


Detailed Study Plan: Unit Test Generator

This study plan is structured over four weeks, focusing on progressive learning from foundational concepts to advanced architectural design and implementation considerations for a Unit Test Generator.

1. Learning Objectives

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

  • Understand Core Principles: Articulate the fundamental principles, benefits, and best practices of unit testing (e.g., FIRST principles, AAA pattern).
  • Master Test Frameworks: Demonstrate proficiency in using at least one major unit testing framework (e.g., Pytest, JUnit, Jest) and its features (assertions, test doubles, parameterization).
  • Analyze Code Structure: Analyze source code using Abstract Syntax Trees (ASTs) or similar techniques to identify testable units (functions, methods, classes) and their dependencies.
  • Design Test Generation Logic: Develop logical strategies and algorithms for automatically generating basic unit test boilerplate, including setup, teardown, and initial assertions.
  • Implement Advanced Test Generation: Implement techniques for generating tests for various scenarios, including edge cases, error handling, and mocking complex dependencies.
  • Architect a Generator Tool: Design a high-level architecture for a robust Unit Test Generator tool, considering input parsing, analysis, generation, and output formatting across different programming languages.
  • Explore AI/ML Integration: Identify and evaluate opportunities for integrating Artificial Intelligence and Machine Learning techniques to enhance test generation, such as suggesting test cases, generating test data, or identifying missing tests.

2. Weekly Schedule

This schedule allocates approximately 10-15 hours per week, combining theoretical learning with practical application.


Week 1: Foundations of Unit Testing & Code Analysis

  • Focus: Core unit testing concepts, test doubles, and introduction to code parsing for analysis.
  • Topics:

* Introduction to Unit Testing: Definition, importance, benefits, types of tests.

* Unit Testing Principles: FIRST (Fast, Independent, Repeatable, Self-validating, Timely), AAA (Arrange, Act, Assert).

* Test Doubles: Mocks, stubs, fakes, spies – when and how to use them.

* Introduction to Abstract Syntax Trees (ASTs): What they are, how they represent code.

* Basic Code Parsing: Hands-on exploration of an AST library in a chosen language (e.g., Python's ast module, Java's JDT, C#'s Roslyn).

* Identifying basic code structures (functions, classes, variables) from an AST.

  • Practical Exercise: Write a comprehensive suite of unit tests for a small, existing utility class using a chosen framework. Experiment with basic AST parsing to extract function names from a simple code file.

Week 2: Test Frameworks & Basic Generation Logic

  • Focus: Deep dive into a specific unit testing framework and initial strategies for generating test boilerplate.
  • Topics:

* Deep Dive into a Chosen Framework: (e.g., Pytest for Python, JUnit 5 for Java, Jest for JavaScript).

* Test structure, assertions, fixtures/setup methods, parameterization, test discovery.

* Identifying Testable Units: Strategies for programmatically determining functions/methods and classes that require unit tests.

* Dependency Injection and Inversion of Control (IoC) for testability.

* Generating Basic Test Boilerplate: Developing logic to create empty test methods/functions for identified units.

* Generating Simple Assertions: Based on return types or expected behavior (e.g., assertNotNull, assertTrue).

  • Practical Exercise: Select a small open-source library. Write a module that parses its code (using AST) and generates a skeletal test file with empty test methods for each public function/method, using your chosen framework's syntax.

Week 3: Advanced Test Generation & Best Practices

  • Focus: Generating tests for complex scenarios, managing dependencies, and ensuring test quality.
  • Topics:

* Mocking Dependencies Programmatically: Strategies for identifying dependencies and generating mock objects or stubs.

* Generating Tests for Edge Cases: Null checks, empty collections, boundary values, error conditions.

* Data-Driven Testing: Generating tests with various input data sets.

* Integration with Static Analysis: How a generator can leverage static analysis tools to suggest more effective tests.

* Refactoring and Improving Generated Tests: Techniques to make generated tests more readable and maintainable.

* Design Patterns for Testable Code: Understanding how code design impacts testability and generation.

  • Practical Exercise: Enhance your module from Week 2 to:

* Generate mock objects for identified dependencies using the framework's mocking capabilities (e.g., unittest.mock, Mockito, Jest mocks).

* Generate at least one basic edge case test (e.g., passing null or an empty string where applicable).


Week 4: Architecture for a Unit Test Generator & AI Concepts

  • Focus: Designing the overall architecture of a comprehensive generator tool and exploring AI/ML integration.
  • Topics:

* Unit Test Generator Architecture:

* Input Layer: Handling various source code formats, project structures.

* Parsing/Analysis Layer: Robust AST parsing, semantic analysis, dependency graph generation.

* Generation Engine: Templating, rule-based generation, customization options.

* Output Layer: Formatting, integration with existing test suites, reporting.

* Language Agnostic Design: Strategies for supporting multiple programming languages.

* AI/ML Integration for Test Generation:

* Test Case Prioritization: Using ML to identify critical code paths for testing.

* Automated Test Data Generation: Leveraging AI to create realistic and diverse test data.

* Missing Test Identification: AI-driven analysis to suggest tests for uncovered code or scenarios.

* Natural Language Processing (NLP): Generating descriptive test names and comments.

* Reinforcement Learning: Optimizing test suite effectiveness over time.

* Review of existing tools and research in automated test generation.

  • Practical Exercise: Develop a high-level architectural diagram and detailed design document for a "Unit Test Generator" that could support multiple languages. Include a section outlining at least two specific points where AI/ML could significantly enhance its capabilities.

3. Recommended Resources

  • Books:

* "Effective Unit Testing" by Lasse Koskela

* "Test-Driven Development by Example" by Kent Beck

* "Working Effectively with Legacy Code" by Michael C. Feathers (for understanding testability challenges)

* "Refactoring: Improving the Design of Existing Code" by Martin Fowler (for writing cleaner, more testable code)

  • Online Courses (e.g., Pluralsight, Udemy, Coursera):

* Courses on specific unit testing frameworks (e.g., "Pytest: The Complete Guide", "JUnit 5 Masterclass").

* Courses on Abstract Syntax Trees and compiler design basics.

* Courses on Test-Driven Development (TDD).

* Introductory courses on Machine Learning and AI for software engineering.

  • Documentation:

* Official documentation for your chosen unit testing framework (e.g., docs.pytest.org, junit.org, jestjs.io).

* Official documentation for AST libraries in your chosen language (e.g., Python ast module, Roslyn for C#, ANTLR for general parsing).

* Mocking libraries documentation (e.g., unittest.mock, Mockito).

  • Articles & Blogs:

* Martin Fowler's website (martinfowler.com) on test doubles, refactoring, and general testing strategies.

* Various engineering blogs from companies like Google, Microsoft, Facebook on testing practices and tools.

* Academic papers and research on automated test generation (e.g., using search terms like "search-based software testing," "test case generation AI").

  • Tools:

* IDEs: Visual Studio Code, IntelliJ IDEA, PyCharm (with integrated testing tools).

* Testing Frameworks: Pytest, JUnit, Jest, NUnit, xUnit.

* Mocking Libraries: unittest.mock, Mockito, Sinon.js.

* Code Analysis: SonarQube, Pylint, ESLint, Checkstyle, Roslyn Analyzers.

4. Milestones

  • End of Week 1: Solid understanding of unit testing fundamentals, test doubles, and the ability to parse basic code structures using an AST library.
  • End of Week 2: Proficiency in using a chosen unit testing framework and the ability to generate skeletal test methods for identified code units.
  • End of Week 3: Capability to generate more sophisticated tests, including basic mocks and tests for edge cases, demonstrating an understanding of programmatic test enhancement.
  • End of Week 4: A well-defined architectural plan for a comprehensive Unit Test Generator, including a clear vision for AI/ML integration, and a consolidated understanding of the entire workflow.

5. Assessment Strategies

  • Weekly Practical Exercises: Completion and self-review of the assigned practical tasks, demonstrating hands-on application of learned concepts.
  • Code Reviews: Peer or mentor review of generated code (tests and generator modules) to provide feedback on correctness, style, and adherence to best practices.
  • Self-Assessment Quizzes: Regular self-quizzes on theoretical concepts (e.g., types of test doubles, AST node types, TDD principles).
  • Project Work: The culmination of the practical exercises into a small, functional prototype or detailed design document for a Unit Test Generator.
  • Architectural Presentation/Discussion: A brief presentation or discussion at the end of Week 4, explaining the proposed architecture of the Unit Test Generator and the rationale behind AI/ML integration points. This will assess conceptual understanding and critical thinking.

  1. Review Results: Examine the test output. All tests should pass. If any fail, it indicates a potential issue in the
gemini Output

Unit Test Generator - Deliverable Report: Review & Documentation

This document outlines the comprehensive review and detailed documentation provided for the unit tests generated for your project. Our "Unit Test Generator" workflow leverages advanced AI capabilities (Gemini) to produce high-quality unit tests, which are then meticulously reviewed and documented to ensure clarity, accuracy, and ease of integration into your development lifecycle.


1. Executive Summary

We are pleased to deliver the comprehensive unit tests and their accompanying documentation. This deliverable focuses on providing a robust set of tests designed to enhance the quality, stability, and maintainability of your codebase. The generated tests have undergone a rigorous review process to ensure adherence to best practices, optimal coverage, and readability. The detailed documentation provided will empower your development team to understand, integrate, and leverage these tests effectively.

Key Deliverables in this package:

  • Generated Unit Test Files: Ready-to-integrate unit test code.
  • Comprehensive Test Documentation: Detailed insights into each test suite and individual test case.
  • Review Findings & Best Practice Adherence: Assurance of quality and maintainability.
  • Integration Guidelines: Practical advice for seamless adoption.

2. Review Process Overview

The generated unit tests undergo a multi-faceted review process to ensure their quality, effectiveness, and alignment with modern software development standards.

2.1. AI-Assisted Validation & Sanity Checks

  • Syntax & Structure Validation: Automated checks to ensure all generated code adheres to the target language's syntax and the chosen testing framework's structure (e.g., JUnit, Pytest, Jest).
  • Basic Coverage Assessment: Initial analysis to identify the methods and classes targeted by the generated tests, ensuring foundational coverage.
  • Dependency Resolution Check: Verification that mock objects and dependency injections are correctly identified and implemented where necessary.

2.2. Expert-Guided Quality Assurance

Our team of software engineers performs an in-depth review, focusing on the following critical aspects:

  • Adherence to Testing Best Practices:

* Arrange-Act-Assert (AAA) Pattern: Confirmation that tests clearly separate setup, execution, and assertion phases.

* Test Isolation: Ensuring each test case runs independently without side effects on others.

* Meaningful Naming Conventions: Verifying test methods are descriptively named, clearly indicating their purpose and expected outcome.

* Clear & Concise Assertions: Checking that assertions are specific, unambiguous, and test only one logical outcome per test.

  • Functional Correctness & Completeness:

* Targeted Functionality: Verifying that tests accurately target the intended functionality of the System Under Test (SUT).

* Edge Case Identification: Reviewing for coverage of common edge cases, error conditions, and boundary values.

* Positive & Negative Scenarios: Ensuring a balance of tests for expected successful operations and error-handling scenarios.

  • Readability & Maintainability:

* Code Clarity: Assessing the ease with which a human developer can understand the purpose and logic of each test.

* Simplicity: Promoting straightforward test implementations that avoid unnecessary complexity.

* Future Adaptability: Considering how easily these tests can be updated or expanded as the SUT evolves.

  • Contextual Relevance: Confirming that the generated tests align with the architectural patterns, design principles, and business logic inherent to your specific project's context (based on provided source code and initial requirements).

3. Detailed Test Documentation

The documentation is structured to provide a clear, hierarchical understanding of the generated unit tests, making them immediately actionable for your team.

3.1. Overall Test Suite Summary

  • Project Component/Module: [Placeholder: e.g., OrderProcessingService, UserAuthenticationAPI, DataValidationLibrary]
  • Primary Language: [Placeholder: e.g., Java, Python, JavaScript, C#]
  • Testing Framework: [Placeholder: e.g., JUnit 5, Pytest, Jest, NUnit]
  • Total Test Files Generated: [Number]
  • Total Individual Test Cases: [Number]
  • Scope of Coverage: [Brief description of what areas/features are primarily covered by these tests.]
  • Assumptions Made: [e.g., "Assumes external dependencies like databases are mocked.", "Assumes valid input for DTOs unless explicitly tested otherwise."]

3.2. Per-File Documentation Structure (Example)

For each generated test file, the following details are provided:

  • Test File Name: [e.g., UserServiceTests.java]
  • Purpose: A concise description of the primary class or component being tested by this file.

Example: "This file contains unit tests for the UserService class, verifying its core CRUD operations and business logic."*

  • Key Methods/Functions Under Test: A list of the specific methods or functions within the SUT that are targeted by the tests in this file.

Example: createUser(UserDTO), getUserById(long id), updateUser(UserDTO), deleteUser(long id).*

  • Dependencies & Mocking Strategy: Details on any external dependencies (e.g., repositories, other services) that were mocked or stubbed for these tests, and the strategy used (e.g., Mockito, unittest.mock).

Example: "Mocks UserRepository using Mockito to isolate UserService logic from database interactions."*

  • Test Cases Breakdown: A detailed breakdown of each individual test method within the file.

* Test Method Name: [e.g., testCreateUser_successWithValidData()]

* Description: A clear explanation of what this specific test case aims to verify.

Example: "Verifies that the createUser method successfully creates and returns a User object when provided with valid input data."*

* Input/Scenario: The specific inputs or conditions set up for this test.

Example: "Input: UserDTO with email='test@example.com', password='password123'."*

* Expected Output/Behavior: The anticipated result, return value, or exception expected from the SUT.

Example: "Expected: A User object is returned with a generated ID. userRepository.save() is called exactly once."*

* Assertions Used: The key assertions made to validate the expected behavior.

Example: assertEquals(expectedUser.getEmail(), actualUser.getEmail()), verify(userRepository, times(1)).save(any(User.class)).*

* Edge Case/Error Covered (if applicable): If the test specifically targets an edge case or error scenario.

Example: "Covers: InvalidEmailException when email format is incorrect."*

3.3. Code Quality & Best Practices Observations

This section highlights specific observations regarding the quality and adherence to best practices in the generated tests:

  • Consistent AAA Pattern: All tests consistently follow the Arrange-Act-Assert structure.
  • Descriptive Test Naming: Test method names clearly convey their purpose.
  • Effective Use of Mocks: Dependencies are appropriately mocked to ensure unit isolation.
  • Clear Assertions: Assertions are precise and directly validate the expected outcome.
  • Areas for Potential Expansion (Recommendations):

Example: "Consider adding more parameter validation tests for updateUser method to cover all possible field updates."*

Example: "Further integration tests might be beneficial for scenarios involving multiple service interactions."*


4. How to Utilize This Deliverable

To maximize the value of these generated unit tests and documentation, we recommend the following steps:

  1. Review the Documentation: Start by reviewing the "Overall Test Suite Summary" and then delve into the "Per-File Documentation" to gain a thorough understanding of each test.
  2. Integrate Test Files: Place the generated test files into the appropriate test directory within your project structure, following your existing conventions.
  3. Dependency Management: Ensure all necessary testing framework dependencies (e.g., JUnit, Mockito, Pytest, Jest) are correctly configured in your project's build file (e.g., pom.xml, build.gradle, requirements.txt, package.json).
  4. Execute Tests: Run the tests using your IDE or build tool (e.g., mvn test, gradle test, pytest, npm test). Verify that all tests pass as expected.
  5. Refine & Expand (Optional but Recommended): While comprehensive, these tests serve as an excellent foundation. Your team can extend them to cover highly specific business logic, complex integrations, or newly identified edge cases.
  6. Continuous Integration: Incorporate these tests into your CI/CD pipeline to ensure that new code changes do not introduce regressions.

5. Next Steps & Support

  • Feedback & Questions: We encourage you to review this deliverable and provide any feedback or questions you may have. Our team is ready to clarify any aspect of the generated tests or documentation.
  • Further Test Generation: Should you require unit tests for additional components or deeper coverage for existing ones, we are prepared for further iterations.
  • Consultation & Integration Support: For complex integration scenarios or advanced usage, our experts are available for further consultation and hands-on support.

6. Conclusion

This "Unit Test Generator" deliverable represents a significant step towards enhancing the quality and reliability of your software. By providing meticulously reviewed and thoroughly documented unit tests, we aim to accelerate your development cycles, reduce debugging efforts, and foster a culture of robust code quality. We are committed to supporting your success and look forward to your feedback.

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