Repository navigation
fix: v4 monorepo builds - #3253
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
WalkthroughCLI build/dev now forward the resolved Changes
Sequence DiagramsequenceDiagram
participant CLI as CLI (build/dev)
participant Sub as Subcommand\n(generate / cache-graphql / generate-i18n)
participant Dir as Directory Util\n(withBasePath / getRoot)
participant Gen as Generate Types/Schema
participant FS as File System
CLI->>CLI: resolve basePath (arg or cwd)
alt Monorepo (cwd ≠ basePath)
CLI->>CLI: compute package prefix
CLI->>FS: move .next/standalone/${prefix}.faststore -> target
CLI->>FS: remove moved ${prefix}.faststore
end
CLI->>Sub: spawn node <cli> <script> <basePath>
Sub->>Dir: withBasePath(basePath)
Dir-->>Sub: return tmp/user paths rooted at getRoot(basePath)
Sub->>Gen: request schema/types generation (root)
Gen->>FS: if root/.faststore exists
alt .faststore present
Gen->>FS: read/write under root/.faststore/@generated
else
Gen->>FS: read/write under root/@generated
end
FS-->>Gen: files created/updated
Gen-->>Sub: types ready
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~22 minutes Suggested labels
Suggested reviewers
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📝 Generate docstrings
🧪 Generate unit tests (beta)
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 |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
f30cf18 to
4b3e6c6
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
packages/cli/src/commands/build.ts (1)
203-215: Narrow the imported JSON instead of asserting it.
as { ... }only silences the compiler; it does not protectcheckDeps()from malformed shapes likedependencies: null. A small runtime normalizer for each dependency bag would keep this path safe without the cast.As per coding guidelines, "Ensure type safety and avoid type assertions when possible".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/build.ts` around lines 203 - 215, The code asserts the imported JSON shape with "as { ... }" which can hide runtime issues (e.g., dependencies: null); instead remove the type assertion on pkg (keep const pkg = mod.default ?? mod) and normalize each dependency bag before use: ensure devDependencies, dependencies, and peerDependencies are plain objects (fallback to {} when missing or not an object) so checkDeps() always receives an object; reference the variables mod, pkg, devDependencies, dependencies, peerDependencies and the function checkDeps() when applying this normalization.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli/src/commands/build.ts`:
- Around line 72-75: The spawnSync calls currently build shell-interpolated
commands like `node ${binCli} generate ${basePath}`, which risks shell injection
and breaks on spaces; update each of the three usages of spawnSync to call
spawnSync(process.execPath, [binCli, '<subcommand>', basePath], { stdio:
'inherit' }) (e.g., for the generate invocation use [binCli, 'generate',
basePath], and similarly replace the other two subcommands) so arguments are
passed as an array (no shell: true) and basePath is not interpolated into a
shell string; ensure you remove or set shell:false and preserve stdio and other
options.
In `@packages/cli/src/commands/dev.ts`:
- Around line 201-210: The two spawnSync invocations that run `node ${cliPath}
cache-graphql ${basePath}` and `node ${cliPath} generate-i18n ${basePath}` are
unsafe and don't check exit codes; replace them with argv-style child calls
using spawnSync(cliPath, ['cache-graphql', basePath], { shell: false, stdio:
'inherit' }) and spawnSync(cliPath, ['generate-i18n', basePath], { shell: false,
stdio: 'inherit' }) (i.e., stop interpolating basePath into a shell string) and
after each call inspect the returned result.status/failure to abort
(process.exit with the non-zero status or throw) if the command failed so `dev`
doesn't continue with stale artifacts; update the locations where `cliPath`,
`basePath`, and the `cache-graphql`/`generate-i18n` spawnSync calls appear.
---
Nitpick comments:
In `@packages/cli/src/commands/build.ts`:
- Around line 203-215: The code asserts the imported JSON shape with "as { ...
}" which can hide runtime issues (e.g., dependencies: null); instead remove the
type assertion on pkg (keep const pkg = mod.default ?? mod) and normalize each
dependency bag before use: ensure devDependencies, dependencies, and
peerDependencies are plain objects (fallback to {} when missing or not an
object) so checkDeps() always receives an object; reference the variables mod,
pkg, devDependencies, dependencies, peerDependencies and the function
checkDeps() when applying this normalization.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 814e268b-26a9-4a6d-8542-07f12cf56ade
📒 Files selected for processing (5)
packages/cli/src/commands/build.tspackages/cli/src/commands/dev.tspackages/cli/src/utils/directory.test.tspackages/cli/src/utils/directory.tspackages/cli/src/utils/generate-types.ts
| let scriptResult = spawnSync(`node ${binCli} generate ${basePath}`, { | ||
| shell: true, | ||
| stdio: 'inherit', | ||
| }) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let me check the file structure and read the relevant sections
head -100 packages/cli/src/commands/build.ts | tail -50Repository: vtex/faststore
Length of output: 1541
🏁 Script executed:
# Also get the full context around those lines
sed -n '60,100p' packages/cli/src/commands/build.tsRepository: vtex/faststore
Length of output: 1170
🏁 Script executed:
# Check how basePath is derived - trace its origin
sed -n '1,70p' packages/cli/src/commands/build.tsRepository: vtex/faststore
Length of output: 2305
Use process.execPath with array arguments instead of shell-interpolating basePath.
The three subprocess calls (lines 72–75, 81–84, 94–97) embed user-provided basePath in shell strings. This creates a shell injection vulnerability: paths with spaces break the command, and paths with shell metacharacters (e.g., $(...) or ;) enable arbitrary command execution.
Replace spawnSync(command_string, { shell: true, ... }) with spawnSync(process.execPath, [binCli, subcommand, basePath], { ... }) to safely pass arguments without shell interpretation.
Suggested change
- let scriptResult = spawnSync(`node ${binCli} generate ${basePath}`, {
- shell: true,
- stdio: 'inherit',
- })
+ let scriptResult = spawnSync(
+ process.execPath,
+ [binCli, 'generate', basePath],
+ { stdio: 'inherit' }
+ )
- scriptResult = spawnSync(`node ${binCli} cache-graphql ${basePath}`, {
- shell: true,
- stdio: 'inherit',
- })
+ scriptResult = spawnSync(
+ process.execPath,
+ [binCli, 'cache-graphql', basePath],
+ { stdio: 'inherit' }
+ )
// generate-i18n will validate localization config and check if it's enabled
- scriptResult = spawnSync(`node ${binCli} generate-i18n ${basePath}`, {
- shell: true,
- stdio: 'inherit',
- })
+ scriptResult = spawnSync(
+ process.execPath,
+ [binCli, 'generate-i18n', basePath],
+ { stdio: 'inherit' }
+ )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli/src/commands/build.ts` around lines 72 - 75, The spawnSync calls
currently build shell-interpolated commands like `node ${binCli} generate
${basePath}`, which risks shell injection and breaks on spaces; update each of
the three usages of spawnSync to call spawnSync(process.execPath, [binCli,
'<subcommand>', basePath], { stdio: 'inherit' }) (e.g., for the generate
invocation use [binCli, 'generate', basePath], and similarly replace the other
two subcommands) so arguments are passed as an array (no shell: true) and
basePath is not interpolated into a shell string; ensure you remove or set
shell:false and preserve stdio and other options.
| spawnSync(`node ${cliPath} cache-graphql ${basePath}`, { | ||
| shell: true, | ||
| stdio: 'inherit', | ||
| }) | ||
|
|
||
| // generate-i18n will validate localization config and check if it's enabled | ||
| spawnSync(`node ${cliPath} generate-i18n`, { | ||
| spawnSync(`node ${cliPath} generate-i18n ${basePath}`, { | ||
| shell: true, | ||
| stdio: 'inherit', | ||
| }) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n packages/cli/src/commands/dev.ts | sed -n '195,220p'Repository: vtex/faststore
Length of output: 1024
🏁 Script executed:
cat -n packages/cli/src/commands/dev.ts | head -n 210 | tail -n +1 | head -n 100Repository: vtex/faststore
Length of output: 3471
🏁 Script executed:
cat -n packages/cli/src/commands/dev.ts | sed -n '130,210p'Repository: vtex/faststore
Length of output: 2750
🏁 Script executed:
fd -t f "directory\|runCommandSync" packages/cli/src/utils/ | head -20Repository: vtex/faststore
Length of output: 40
🏁 Script executed:
ls -la packages/cli/src/utils/Repository: vtex/faststore
Length of output: 1186
🏁 Script executed:
cat -n packages/cli/src/utils/runCommandSync.tsRepository: vtex/faststore
Length of output: 2393
🏁 Script executed:
cat -n packages/cli/src/utils/directory.tsRepository: vtex/faststore
Length of output: 3004
Use argv-based child processes and check their exit codes.
These spawnSync calls interpolate basePath into shell commands with shell: true. Since basePath comes directly from user input (via getBasePath(args.path)), paths with spaces or special characters will be misparsed. Additionally, neither call checks exit codes, so dev can continue with stale GraphQL/i18n artifacts if these setup steps fail.
Suggested change
- spawnSync(`node ${cliPath} cache-graphql ${basePath}`, {
- shell: true,
- stdio: 'inherit',
- })
+ const cacheGraphqlResult = spawnSync(
+ process.execPath,
+ [cliPath, 'cache-graphql', basePath],
+ { stdio: 'inherit' }
+ )
+ if (cacheGraphqlResult.error || cacheGraphqlResult.status !== 0) {
+ throw new Error('Unable to run cache-graphql')
+ }
// generate-i18n will validate localization config and check if it's enabled
- spawnSync(`node ${cliPath} generate-i18n ${basePath}`, {
- shell: true,
- stdio: 'inherit',
- })
+ const generateI18nResult = spawnSync(
+ process.execPath,
+ [cliPath, 'generate-i18n', basePath],
+ { stdio: 'inherit' }
+ )
+ if (generateI18nResult.error || generateI18nResult.status !== 0) {
+ throw new Error('Unable to run generate-i18n')
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| spawnSync(`node ${cliPath} cache-graphql ${basePath}`, { | |
| shell: true, | |
| stdio: 'inherit', | |
| }) | |
| // generate-i18n will validate localization config and check if it's enabled | |
| spawnSync(`node ${cliPath} generate-i18n`, { | |
| spawnSync(`node ${cliPath} generate-i18n ${basePath}`, { | |
| shell: true, | |
| stdio: 'inherit', | |
| }) | |
| const cacheGraphqlResult = spawnSync( | |
| process.execPath, | |
| [cliPath, 'cache-graphql', basePath], | |
| { stdio: 'inherit' } | |
| ) | |
| if (cacheGraphqlResult.error || cacheGraphqlResult.status !== 0) { | |
| throw new Error('Unable to run cache-graphql') | |
| } | |
| // generate-i18n will validate localization config and check if it's enabled | |
| const generateI18nResult = spawnSync( | |
| process.execPath, | |
| [cliPath, 'generate-i18n', basePath], | |
| { stdio: 'inherit' } | |
| ) | |
| if (generateI18nResult.error || generateI18nResult.status !== 0) { | |
| throw new Error('Unable to run generate-i18n') | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/cli/src/commands/dev.ts` around lines 201 - 210, The two spawnSync
invocations that run `node ${cliPath} cache-graphql ${basePath}` and `node
${cliPath} generate-i18n ${basePath}` are unsafe and don't check exit codes;
replace them with argv-style child calls using spawnSync(cliPath,
['cache-graphql', basePath], { shell: false, stdio: 'inherit' }) and
spawnSync(cliPath, ['generate-i18n', basePath], { shell: false, stdio: 'inherit'
}) (i.e., stop interpolating basePath into a shell string) and after each call
inspect the returned result.status/failure to abort (process.exit with the
non-zero status or throw) if the command failed so `dev` doesn't continue with
stale artifacts; update the locations where `cliPath`, `basePath`, and the
`cache-graphql`/`generate-i18n` spawnSync calls appear.
4b3e6c6 to
eb2cca6
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/cli/src/commands/build.ts (1)
72-75:⚠️ Potential issue | 🟠 MajorShell injection risk persists—use array arguments.
These subprocess calls embed
basePathdirectly into shell strings. Paths containing spaces or shell metacharacters (;,$(), etc.) can break execution or enable command injection. This was flagged in a previous review.,
Recommended fix: pass arguments as array
- let scriptResult = spawnSync(`node ${binCli} generate ${basePath}`, { - shell: true, - stdio: 'inherit', - }) + let scriptResult = spawnSync( + process.execPath, + [binCli, 'generate', basePath], + { stdio: 'inherit' } + ) - scriptResult = spawnSync(`node ${binCli} cache-graphql ${basePath}`, { - shell: true, - stdio: 'inherit', - }) + scriptResult = spawnSync( + process.execPath, + [binCli, 'cache-graphql', basePath], + { stdio: 'inherit' } + ) - scriptResult = spawnSync(`node ${binCli} generate-i18n ${basePath}`, { - shell: true, - stdio: 'inherit', - }) + scriptResult = spawnSync( + process.execPath, + [binCli, 'generate-i18n', basePath], + { stdio: 'inherit' } + )Also applies to: 81-84, 94-97
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/build.ts` around lines 72 - 75, The spawnSync calls that build command strings (e.g., the call assigning scriptResult using spawnSync(`node ${binCli} generate ${basePath}`, { shell: true, ... })) are vulnerable to shell injection via basePath; change these to pass the executable and arguments as an array (e.g., ['node', binCli, 'generate', basePath]) and remove shell: true so the child process receives raw argv, preserving spaces and preventing metacharacter expansion; apply the same fix to the other spawnSync usages in this module that call node with binCli and basePath (the similar blocks around the build/preview invocations).
🧹 Nitpick comments (1)
packages/cli/src/commands/build.ts (1)
150-164: Monorepo standalone normalization looks correct.The logic properly handles the prefix-based path rewriting for monorepo builds where
outputFileTracingRootcreates nested.faststoredirectories. ThePromise.allwithmoveSyncis synchronous despite the async wrapper—consider whether this is intentional.The
moveSynccalls are synchronous, so wrapping them inPromise.alldoesn't provide concurrency benefits. This works fine but could be simplified:Optional: simplify to synchronous iteration
- await Promise.all( - standaloneBuildFiles.map((file) => - moveSync( - `${tmpDir}/.next/standalone/${prefix}.faststore/${file}`, - `${tmpDir}/.next/standalone/${file}`, - { overwrite: true } - ) - ) - ) + for (const file of standaloneBuildFiles) { + moveSync( + `${tmpDir}/.next/standalone/${prefix}.faststore/${file}`, + `${tmpDir}/.next/standalone/${file}`, + { overwrite: true } + ) + }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/cli/src/commands/build.ts` around lines 150 - 164, The Promise.all wrapping the synchronous moveSync calls is misleading since moveSync is blocking; update the monorepo standalone normalization in the block that checks existsSync(`${tmpDir}/.next/standalone/${prefix}.faststore`) to use a plain synchronous loop instead of Promise.all (e.g., forEach or for..of over readdirSync result) to call moveSync for each file, then call removeSync as before; this keeps behavior identical but removes the pointless async wrapper around moveSync and clarifies intent (references: existsSync, readdirSync, moveSync, Promise.all, removeSync, tmpDir, prefix).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/cli/src/commands/build.ts`:
- Around line 144-147: path.relative(process.cwd(), basePath) can return
backslashes on Windows causing wrong paths; when computing prefix in build.ts
(symbols: isRunningFromMonorepo, prefix, basePath, process.cwd(), path.relative)
normalize the relative path to forward slashes before appending '/' (e.g.
replace backslashes with '/' or use path.posix.join on the split segments) so
prefix is always using '/' separators for downstream template/path usage.
---
Duplicate comments:
In `@packages/cli/src/commands/build.ts`:
- Around line 72-75: The spawnSync calls that build command strings (e.g., the
call assigning scriptResult using spawnSync(`node ${binCli} generate
${basePath}`, { shell: true, ... })) are vulnerable to shell injection via
basePath; change these to pass the executable and arguments as an array (e.g.,
['node', binCli, 'generate', basePath]) and remove shell: true so the child
process receives raw argv, preserving spaces and preventing metacharacter
expansion; apply the same fix to the other spawnSync usages in this module that
call node with binCli and basePath (the similar blocks around the build/preview
invocations).
---
Nitpick comments:
In `@packages/cli/src/commands/build.ts`:
- Around line 150-164: The Promise.all wrapping the synchronous moveSync calls
is misleading since moveSync is blocking; update the monorepo standalone
normalization in the block that checks
existsSync(`${tmpDir}/.next/standalone/${prefix}.faststore`) to use a plain
synchronous loop instead of Promise.all (e.g., forEach or for..of over
readdirSync result) to call moveSync for each file, then call removeSync as
before; this keeps behavior identical but removes the pointless async wrapper
around moveSync and clarifies intent (references: existsSync, readdirSync,
moveSync, Promise.all, removeSync, tmpDir, prefix).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 98da6f8b-b56f-4109-b7f8-8ff41d998714
📒 Files selected for processing (7)
packages/cli/src/commands/build.tspackages/cli/src/commands/dev.tspackages/cli/src/utils/directory.test.tspackages/cli/src/utils/directory.tspackages/cli/src/utils/generate-types.tspackages/core/src/sdk/product/useProductGalleryQuery.tspackages/sdk/src/index.ts
✅ Files skipped from review due to trivial changes (2)
- packages/core/src/sdk/product/useProductGalleryQuery.ts
- packages/cli/src/commands/dev.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/cli/src/utils/generate-types.ts
- packages/cli/src/utils/directory.ts
What's the purpose of this pull request?
Fix FastStore v4 builds and codegen in monorepos when the CLI runs from the repo root and Discovery lives in a nested package (
packages/...):.faststoreand subprocesses now respect the projectbasePath, and standalone output withoutputFileTracingRootat the repo root no longer breaks layouts that expectserver.jsunder.next/standalone/.SFS-3116
How it works?
directory:tmpDir=<basePath>/.faststore(no longercwd/.faststore).build: passesbasePathtogenerate,cache-graphql, andgenerate-i18n;normalizeStandaloneBuildDirusespath.relative(cwd, basePath)as a prefix whencwd !== basePath; -dev:cache-graphqlandgenerate-i18nreceivebasePath.generate-types: resolves paths into.faststorewhen it exists.basePath+ monorepo scenarios.How to test it?
Starters Deploy Preview
References
Summary by CodeRabbit
Bug Fixes
Tests
Chores