Implement code generation export pipeline (JSZip templates + export hook)#108
Conversation
Summary of ChangesHello @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
Using Gemini Code AssistThe 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
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 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
|
|
Caution Review failedThe pull request is closed. Note Other AI code review bot(s) detectedCodeRabbit 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. 📝 WalkthroughWalkthroughThis 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. Comment |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:
nullproject 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 withnormalizeProjectNamein CodeGeneratorTool.tsx.This function duplicates the logic in
normalizeProjectName(lines 189-194 in CodeGeneratorTool.tsx). Consider exportingsanitizeProjectNamefrom this module and reusing it in the component to maintain a single source of truth.♻️ Suggested approach
Export
sanitizeProjectNameand import it in CodeGeneratorTool.tsx:-const sanitizeProjectName = (name: string): string => { +export const sanitizeProjectName = (name: string): string => {Then in CodeGeneratorTool.tsx, replace
normalizeProjectNamewith the imported function.src/components/tools/generation/CodeGeneratorTool.tsx (1)
189-194: Consolidate withsanitizeProjectNamefrom useProjectExport.This
normalizeProjectNamefunction largely duplicatessanitizeProjectNameinuseProjectExport.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
fetchDatacallback depends ononSuccessandonError, anduseEffectruns wheneverfetchDatachanges. 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=productionwhich 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
✅ Automated Validation CompleteThis PR has been automatically validated:
Next Steps:
This is an automated message from the PR validation workflow. |
Motivation
Description
src/services/codeGenerationTemplates.tscontaining file/name helpers and template generators for components, APIs, tests, docs and configs.src/hooks/useProjectExport.tsand helpercreateProjectZipthat usesJSZipand sanitizes project names and file paths before export.src/components/tools/generation/CodeGeneratorTool.tsxto useuseProjectExport, to normalize/sanitize project names, and to show export progress and errors in the Export tab.src/types/code-generation.ts, an export testsrc/hooks/__tests__/useProjectExport.test.ts, and docssrc/docs/CODE_GENERATION_ENGINE.mddescribing the engine and the next 9 logical steps.Testing
src/hooks/__tests__/useProjectExport.test.tscoveringcreateProjectZipsuccess and the empty-project error case.403from the npm registry while runningnpm install, preventing test execution.CodeGeneratorToolUI now callsdownloadProjectZipand 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
Refactors
Written for commit 2dd5803. Summary will update on new commits.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests
✏️ Tip: You can customize this high-level summary in your review settings.