Skip to content

Implement code generation export pipeline (JSZip templates + export hook)#108

Merged
Krosebrook merged 2 commits intomainfrom
codex/develop-and-integrate-next-feature
Jan 22, 2026
Merged

Implement code generation export pipeline (JSZip templates + export hook)#108
Krosebrook merged 2 commits intomainfrom
codex/develop-and-integrate-next-feature

Conversation

@Krosebrook
Copy link
Owner

@Krosebrook Krosebrook commented Jan 21, 2026

Motivation

  • Enable the AI Code Generator to produce downloadable, safe ZIP exports so generated projects can be consumed immediately.
  • Refactor in-place generation helpers into a shared template service to improve reuse and maintainability.
  • Add a robust export pipeline that sanitizes filenames/paths and surfaces errors to the UI instead of producing broken artifacts.
  • Provide documentation and tests so the feature is discoverable and has a minimal automated coverage baseline.

Description

  • Added a shared template service src/services/codeGenerationTemplates.ts containing file/name helpers and template generators for components, APIs, tests, docs and configs.
  • Implemented a ZIP export hook src/hooks/useProjectExport.ts and helper createProjectZip that uses JSZip and sanitizes project names and file paths before export.
  • Wired the export flow into the UI by updating src/components/tools/generation/CodeGeneratorTool.tsx to use useProjectExport, to normalize/sanitize project names, and to show export progress and errors in the Export tab.
  • Added types src/types/code-generation.ts, an export test src/hooks/__tests__/useProjectExport.test.ts, and docs src/docs/CODE_GENERATION_ENGINE.md describing the engine and the next 9 logical steps.

Testing

  • Added a unit test file src/hooks/__tests__/useProjectExport.test.ts covering createProjectZip success and the empty-project error case.
  • The test(s) were not executed in the environment because dependency installation failed with a 403 from the npm registry while running npm install, preventing test execution.
  • No CI, lint, or typecheck runs were performed as part of this change in this environment due to the same install issue.
  • Manual verification: the CodeGeneratorTool UI now calls downloadProjectZip and shows a loading state (Preparing ZIP...) while exporting.

Codex Task


Summary by cubic

Adds a JSZip-based export pipeline and hook to download generated projects as safe ZIPs. Refactors templates and updates the Export tab to show progress and errors.

  • New Features

    • useProjectExport hook creates ZIPs with JSZip/file-saver, sanitizes project names and paths, and returns success/error.
    • CodeGeneratorTool now uses the hook, normalizes names, and shows a loading state (“Preparing ZIP...”) and error toasts.
    • Added docs (src/docs/CODE_GENERATION_ENGINE.md) and a unit test for createProjectZip (success and empty-project error).
  • Refactors

    • Moved generation helpers into src/services/codeGenerationTemplates.ts (file/config generators, name helpers).
    • Added shared types (src/types/code-generation.ts).

Written for commit 2dd5803. Summary will update on new commits.

Summary by CodeRabbit

  • New Features

    • Added project export as ZIP files with loading indicators during preparation
    • Enhanced project name sanitization for safe file naming
  • Bug Fixes

    • Improved error handling and user feedback during export operations
  • Documentation

    • Added comprehensive Code Generation Engine documentation covering current capabilities and roadmap
  • Tests

    • Added test coverage for project export functionality

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings January 21, 2026 20:53
@gemini-code-assist
Copy link

Summary of Changes

Hello @Krosebrook, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a complete pipeline for exporting AI-generated code projects as downloadable ZIP files. It centralizes all code generation logic into a dedicated service for better organization and reusability, while also implementing robust sanitization and error handling to ensure the integrity and safety of exported project artifacts. The user interface has been seamlessly integrated with this new export functionality, providing clear feedback and handling potential issues gracefully.

Highlights

  • ZIP Export Functionality: The AI Code Generator now supports downloading generated projects as safe ZIP archives, enabling immediate consumption by users.
  • Centralized Template Service: In-place code generation helpers have been refactored into a shared codeGenerationTemplates.ts service, significantly improving code reuse and maintainability.
  • Robust Export Pipeline: A new useProjectExport hook has been implemented to handle ZIP creation, including sanitization of filenames and paths, and providing user-facing error feedback for a more reliable export process.
  • Enhanced UI Feedback: The Code Generator UI now displays export progress and errors, such as a 'Preparing ZIP...' loading state, to improve the user experience during project download.
  • Comprehensive Documentation & Testing: New documentation (CODE_GENERATION_ENGINE.md) and unit tests (useProjectExport.test.ts) have been added to ensure the feature is discoverable and has a minimal automated coverage baseline.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Jan 21, 2026

Caution

Review failed

The pull request is closed.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

This change extracts and reorganizes code generation logic from the CodeGeneratorTool component into reusable external modules, introducing a new type system for generated files and projects, a project export hook with ZIP functionality, comprehensive template generation service utilities, enhanced documentation, and new unit tests.

Changes

Cohort / File(s) Summary
Type Definitions
src/types/code-generation.ts
Introduces GeneratedFile and CodeProject interfaces that define the data model for code generation artifacts, including file metadata (path, content, language, size) and project metadata (name, dependencies, scripts, framework, features).
Export Pipeline
src/hooks/useProjectExport.ts
Implements useProjectExport hook and utilities for safe ZIP export: exports project files with sanitized names and paths, manages asynchronous download state, integrates with JSZip and file-saver for client-side file generation. Includes sanitization functions and a createProjectZip function that validates and bundles projects.
Template Generation Service
src/services/codeGenerationTemplates.ts
Provides comprehensive template generation utilities: path helpers (getMainFileName, getTestFileName), config generators (ESLint, TypeScript, package.json), component/API/hook scaffolds, testing and documentation templates, and mock project builders. Supports framework-aware and feature-conditional code generation across multiple artifact types.
Component Refactoring
src/components/tools/generation/CodeGeneratorTool.tsx
Refactors component to externalize types and logic: replaces local type declarations with imported CodeProject type, integrates useProjectExport hook for ZIP download, externalizes template helpers from new service module, adds project name sanitization via normalizeProjectName hook, updates download UI to reflect async export state (loading spinner, disabled state).
Tests & Documentation
src/hooks/__tests__/useProjectExport.test.ts
src/docs/CODE_GENERATION_ENGINE.md
Adds unit tests for createProjectZip validating ZIP file inclusion and error handling for empty projects; introduces comprehensive documentation outlining the code generation engine architecture, capabilities, edge cases, usage flow, and planned next steps.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Component as CodeGeneratorTool
    participant Hook as useProjectExport
    participant Zip as JSZip
    participant FileSaver as file-saver
    
    User->>Component: Click Download ZIP
    Component->>Component: normalizeProjectName()
    Component->>Hook: downloadProjectZip(project)
    activate Hook
    Hook->>Hook: createProjectZip(project)
    activate Hook
    Hook->>Hook: validateProject()
    Hook->>Hook: sanitizeProjectName()
    Loop Each File in Project
        Hook->>Hook: sanitizeFilePath()
        Hook->>Zip: addFile(sanitized_path, content)
    end
    Hook->>Zip: generateAsync()
    Zip-->>Hook: ZIP Blob
    deactivate Hook
    Hook->>FileSaver: saveAs(blob, filename)
    Hook-->>Component: {success: true}
    deactivate Hook
    Component->>Component: Show success toast
    Component->>User: Download complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

Review effort 3/5

Poem

🐰 A refactor most fine, with types so divine,
Templates extracted, and exports align,
Hooks spin their magic, while services sing,
ZIP files download on a rabbit's swift wing! 📦✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: implementing a code generation export pipeline using JSZip and a custom export hook, which is reflected across multiple files and is the primary objective.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a robust code generation export pipeline, a significant feature enhancement. The refactoring of generation logic into a dedicated service (codeGenerationTemplates.ts) and a custom hook (useProjectExport) greatly improves modularity and maintainability. The implementation of a real ZIP export using JSZip, complete with filename and path sanitization, is a solid improvement for security and correctness. The new documentation and unit tests provide a good foundation for this feature. I've identified a few minor issues related to code robustness, type safety, and test coverage that could further strengthen this implementation.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 75ad5bd4d7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request implements a comprehensive code generation export pipeline for the FlashFusion AI Code Generator. It refactors inline template generation logic into a shared service, adds JSZip-based project export functionality with path sanitization, and provides UI integration with proper loading states and error handling.

Changes:

  • Extracted template generation logic from CodeGeneratorTool into a reusable service (codeGenerationTemplates.ts) with functions for generating components, APIs, hooks, configs, and documentation
  • Implemented a ZIP export pipeline using JSZip with sanitization for project names and file paths to prevent invalid exports
  • Added type definitions for code generation artifacts and updated the UI to display export progress and handle errors gracefully

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 16 comments.

Show a summary per file
File Description
src/types/code-generation.ts Defines TypeScript interfaces for GeneratedFile and CodeProject structures
src/services/codeGenerationTemplates.ts Shared template service containing generators for React components, APIs, hooks, tests, configs, and project scaffolding
src/hooks/useProjectExport.ts Export hook with JSZip integration, path/name sanitization, and error handling for project downloads
src/hooks/tests/useProjectExport.test.ts Unit tests for createProjectZip function covering successful export and empty project validation
src/docs/CODE_GENERATION_ENGINE.md Documentation describing the code generation architecture, modules, edge cases, and future roadmap
src/components/tools/generation/CodeGeneratorTool.tsx UI component refactored to use shared template service and export hook, with improved project name normalization and export progress display
README.md Added link to code generation engine documentation
Comments suppressed due to low confidence (1)

src/components/tools/generation/CodeGeneratorTool.tsx:312

  • The size field is calculated using 'new Blob([testCode]).size' for the test file at line 290, but hardcoded to 256 for the ESLint config at line 311. This inconsistency makes the data confusing - either all sizes should be calculated from content or all should be placeholders. Consider standardizing this approach across all file generation.
          size: new Blob([testCode]).size
        });
      }

      // Generate documentation if requested
      if (includeDocs) {
        const documentation = await AIService.generateDocumentation(mainCode, codeType as any);
        files.push({
          path: 'README.md',
          content: documentation,
          language: 'markdown',
          size: new Blob([documentation]).size
        });
      }

      // Generate configuration files based on features
      if (selectedFeatures.includes('ESLint Configuration')) {
        files.push({
          path: '.eslintrc.json',
          content: generateEslintConfig(),
          language: 'json',
          size: 256
        });

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 7 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="src/hooks/useProjectExport.ts">

<violation number="1" location="src/hooks/useProjectExport.ts:38">
P2: createProjectZip can return a successful but empty ZIP when all sanitized file paths are invalid because skipped files aren’t detected.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🤖 Fix all issues with AI agents
In `@src/hooks/__tests__/useProjectExport.test.ts`:
- Line 51: The test's expected error string is incorrect: update the assertion
in the test that calls createProjectZip(project) to expect the exact message
thrown by the implementation ("Project has no files to export.") instead of
"Project has no files" so the rejection matches createProjectZip's thrown error;
locate the assertion referencing createProjectZip in the test and replace the
expected string accordingly.

In `@src/services/codeGenerationTemplates.ts`:
- Around line 104-107: The code branch that handles framework === 'nextjs'
incorrectly deletes dependencies['react-dom']; instead remove that delete and
ensure react-dom is present and aligned with React by setting
dependencies['react-dom'] to the same version as dependencies.react (or a
sensible default like '^18.2.0' if dependencies.react is absent) while still
adding dependencies.next = '^13.4.0'; update the block around the framework
variable and dependencies object accordingly.
- Around line 477-482: The generated test import path in generateTestFile is
incorrect — tests are emitted to src/__tests__/ (see getTestFileName) while
components live in src/components/, so update the import from './${name}' to
'../components/${name}' in the template returned by generateTestFile so the test
file resolves the component correctly; modify the template string in
generateTestFile to use the correct relative path (referencing componentName and
name variables) and ensure any other occurrences of './${name}' in that template
are similarly updated.
- Around line 160-216: generateReactComponent currently always references
styles.button and styles[variant] in the returned JSX, but the styles import is
only added when features.includes('CSS Modules'), causing a runtime
ReferenceError when CSS Modules is not selected; update the JSX generation in
generateReactComponent (and the componentName template) to conditionally build
the className: when features.includes('CSS Modules') is true include
`${styles.button} ${styles[variant]} ${className}`, otherwise omit any `styles`
references and only use `className` (or a fallback string built from
variant/className), and ensure the disabled/aria/handler logic remains
unchanged; locate the className expression in the template return and change it
to branch on features.includes('CSS Modules') so no code references styles
unless the import is present.
- Around line 653-668: The GeneratedFile entries are using hardcoded size
values; replace those static numbers by computing the actual byte length from
each content string (e.g., use Buffer.byteLength(content, 'utf8') or equivalent)
when you push files into the files array so the size reflects the output of
generateReactComponent(name,...), generateComponentStyles(), etc.; update every
place that constructs a GeneratedFile (path/content/language/size) to compute
size from the content instead of using literals.
- Around line 291-332: The generated controller uses the `@authenticate` decorator
(see ${name.charAt(0).toUpperCase() + name.slice(1)}Controller and the
'@authenticate' insertion) which will fail unless experimentalDecorators is
enabled in tsconfig; either update the ts config generation (generateTsConfig)
to set "experimentalDecorators": true or change the template to a non-decorator
call (e.g., wrap route handlers with authenticate(...) instead of using
'@authenticate'). Also fix the error handler that checks z.ZodError (the catch
block referencing z.ZodError) so it only references Zod when Validation is
enabled: guard the check behind the same feature flag used to import z or
replace the instanceof check with a safe runtime test that first verifies z is
defined before accessing z.ZodError.
- Around line 67-89: The generateTsConfig function includes a reference to
'./tsconfig.node.json' in the references array, but the buildMockProjectFiles
function does not generate this referenced file, which will cause TypeScript
warnings. To fix this, either remove the reference array from the tsconfig
object in generateTsConfig, or create a new generateTsConfigNode function that
generates the referenced tsconfig.node.json file and add it to the
buildMockProjectFiles function to ensure all referenced files are created when
the mock project is built.
🧹 Nitpick comments (5)
src/hooks/__tests__/useProjectExport.test.ts (1)

6-52: Consider expanding test coverage.

The tests cover the basic happy path and empty files case, but consider adding tests for:

  • null project input (throws 'No project available for export.')
  • Files with paths requiring sanitization (e.g., ../traversal/file.ts, \\windows\\path.ts)
  • Project with empty/whitespace name to verify default naming
src/hooks/useProjectExport.ts (1)

8-12: Duplicate sanitization logic with normalizeProjectName in CodeGeneratorTool.tsx.

This function duplicates the logic in normalizeProjectName (lines 189-194 in CodeGeneratorTool.tsx). Consider exporting sanitizeProjectName from this module and reusing it in the component to maintain a single source of truth.

♻️ Suggested approach

Export sanitizeProjectName and import it in CodeGeneratorTool.tsx:

-const sanitizeProjectName = (name: string): string => {
+export const sanitizeProjectName = (name: string): string => {

Then in CodeGeneratorTool.tsx, replace normalizeProjectName with the imported function.

src/components/tools/generation/CodeGeneratorTool.tsx (1)

189-194: Consolidate with sanitizeProjectName from useProjectExport.

This normalizeProjectName function largely duplicates sanitizeProjectName in useProjectExport.ts. The only difference is the fallback name generation. Consider exporting and reusing the sanitization logic to avoid drift between implementations.

src/services/codeGenerationTemplates.ts (2)

446-463: Consider documenting the callback memoization requirement.

The fetchData callback depends on onSuccess and onError, and useEffect runs whenever fetchData changes. If callers pass non-memoized callbacks, this will cause infinite fetch loops. Consider adding a JSDoc note or refactoring to use refs for callbacks.

Option: Use refs to avoid callback dependency issues
+  const onSuccessRef = useRef(onSuccess);
+  const onErrorRef = useRef(onError);
+  
+  useEffect(() => {
+    onSuccessRef.current = onSuccess;
+    onErrorRef.current = onError;
+  }, [onSuccess, onError]);
+
   const fetchData = useCallback(async () => {
     // ...
-      onSuccess?.(result);
+      onSuccessRef.current?.(result);
     // ...
-      onError?.(error);
+      onErrorRef.current?.(error);
     // ...
-  }, [onSuccess, onError]);
+  }, []);

607-632: Consider using modern npm flag.

Line 618 uses --only=production which was deprecated in npm 7+. While it still works, consider using the modern equivalent for better forward compatibility.

Suggested fix
-RUN npm ci --only=production
+RUN npm ci --omit=dev

@Krosebrook Krosebrook merged commit 23c687c into main Jan 22, 2026
2 of 7 checks passed
@Krosebrook Krosebrook deleted the codex/develop-and-integrate-next-feature branch January 22, 2026 04:52
@github-actions
Copy link

✅ Automated Validation Complete

This PR has been automatically validated:

  • ✓ Dependencies installed successfully
  • ✓ Linting checked
  • ✓ Type checking completed
  • ✓ Tests executed
  • ✓ Build succeeded

Next Steps:

  • Review the changes manually if needed
  • This PR can be auto-merged if all checks pass

This is an automated message from the PR validation workflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant