Skip to content

feat(mock): support separate mock output paths - #3559

Merged
melloware merged 7 commits into
orval-labs:masterfrom
aqeelat:feat/mock-output-paths
Jun 9, 2026
Merged

melloware merged 7 commits into
orval-labs:masterfrom
aqeelat:feat/mock-output-paths

Conversation

@aqeelat

@aqeelat aqeelat commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Adds support for writing mock outputs to separate directories via a shared mock.path or per-generator path values. This lets MSW handlers and faker fixtures live outside the production client entrypoint while preserving imports back to generated schemas.

Also fixes function-form mock generators so they are consistently treated as MSW across write modes, matching the upstream normalization in client.ts.

Closes #3537
Fixes #3554

Validation:

  • node_modules/.bin/vitest run --config vitest.config.ts packages/core/src/writers/split-mode.test.ts packages/core/src/writers/tags-mode.test.ts packages/core/src/writers/split-tags-mode.test.ts packages/core/src/writers/mock-utils.test.ts
  • node_modules/.bin/vp run -F './packages/*' typecheck
  • node_modules/.bin/vp lint --type-aware --type-check packages/core packages/orval

Snapshot note:
Running bun run test:snapshots:update generated 199 files. I did not include those generated snapshot/fixture updates in this PR yet; I will add them after the source changes are reviewed.

Summary by CodeRabbit

  • New Features

    • Shared mock output path with optional per-generator path overrides; conditional de-inlining to emit mocks as separate files and optional per-directory index barrels.
  • Bug Fixes

    • Function-form mock generators are treated as MSW in split and tags-split modes; deterministic ordering of index exports ensured.
  • Documentation

    • Docs updated with mock.path, per-generator path examples, and indexMockFiles guidance.
  • Tests

    • Added unit and regression tests for mock-path resolution, schema import paths, de-inlining, and index generation.

@coderabbitai

coderabbitai Bot commented Jun 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds optional path to mock types, normalizes shared mock path, implements utilities to compute per-generator mock dirs and schema-relative imports, and refactors writers (single/split/tags variants) to conditionally de-inline mocks, emit per-mock files and per-dir index barrels; tests, docs, and snapshots updated.

Changes

Mock output paths and de-inlining

Layer / File(s) Summary
All changes (single checkpoint)
packages/core/src/types.ts, packages/orval/src/utils/options.ts, packages/core/src/writers/mock-utils.ts, packages/core/src/writers/mock-utils.test.ts, packages/core/src/writers/single-mode.ts, packages/core/src/writers/single-mode.test.ts, packages/core/src/writers/split-mode.ts, packages/core/src/writers/split-mode.test.ts, packages/core/src/writers/split-tags-mode.ts, packages/core/src/writers/split-tags-mode.test.ts, packages/core/src/writers/tags-mode.ts, packages/core/src/writers/tags-mode.test.ts, tests/configs/mock.config.ts, tests/api-generation.spec.ts, docs/content/docs/reference/configuration/output.mdx, docs/content/docs/zh/reference/configuration/output.mdx, many tests/__snapshots__/*
Adds path?: string to mock types and normalized config, normalizes shared mock.path in options, implements getMockDir/hasAnyMockPath/resolveMockSchemasPath with tests, refactors writers to support conditional de-inlining, per-mock directories, per-dir index barrels, updates tests/configs/docs and many generated snapshots to reflect new output layout.

Sequence Diagram(s)

sequenceDiagram
  participant Normalizer
  participant Writer
  participant MockUtils
  participant FS
  Normalizer->>Writer: normalized mock config (includes shared `path`)
  Writer->>MockUtils: getMockDir(entry, mockConfig)
  Writer->>MockUtils: resolveMockSchemasPath(mockFilePath, schemasTarget)
  Writer->>FS: write main file
  alt de-inlined
    Writer->>FS: write per-mock files
    Writer->>FS: write per-dir index barrels
  end
  FS-->>Writer: written paths
  Writer-->>Normalizer: returned generated paths
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

  • #3574 — Per-mock-file emission changes touch finalize/dedupe/indexing areas mentioned in that issue; may be relevant to index/barrel generation adjustments.

Possibly related PRs

Suggested reviewers

  • melloware
  • wadakatu

"🐰 I found the paths and cleaned the trails,
Mapped mock files, fixed de-inline details.
Function generators now join the play,
Barrels gather neatly, no stray.
Hooray — mocks hop home, hip-hip-hurray!"

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
packages/core/src/writers/tags-mode.ts (1)

126-127: 💤 Low value

Consider hoisting collapseInlineMockOutputs to avoid redundant computation.

collapseInlineMockOutputs(rawMockOutputs) is called three times within the !shouldDeinlineMocks branch with identical input. Hoisting the result to a single variable at the start of the per-tag processing would improve efficiency and reduce maintenance risk.

♻️ Suggested refactor

Collapse once at the top of the try block:

       try {
         const {
           imports,
           implementation,
           mockOutputs: rawMockOutputs,
           // ...
         } = target;

+        // Collapse once for all inline-mock branches
+        const inlineMockOutputs = !shouldDeinlineMocks
+          ? collapseInlineMockOutputs(rawMockOutputs)
+          : [];

         // ... later uses become:
-        const mockOutputs = collapseInlineMockOutputs(rawMockOutputs);
+        // use inlineMockOutputs directly

Also applies to: 172-173, 260-261

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/writers/tags-mode.ts` around lines 126 - 127, The branch
inside tags-mode.ts calling collapseInlineMockOutputs(rawMockOutputs) multiple
times should compute that value once and reuse it: inside the per-tag processing
try block (the !shouldDeinlineMocks branch), hoist
collapseInlineMockOutputs(rawMockOutputs) into a local const (e.g.
collapsedMockOutputs) before the repeated uses and then replace the three
duplicate calls with references to that const; update any usages that expect the
original shape accordingly (functions/mappings that read
mockOutputs/rawMockOutputs should now use collapsedMockOutputs) to avoid
redundant computation and ensure consistent results.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/writers/single-mode.ts`:
- Around line 278-337: The loop over rawMockOutputs in single-mode.ts causes
de-inlined mocks of the same type to overwrite each other; before iterating (the
block that uses rawMockOutputs and computes mockFilePath, mockExtension, etc.),
collapse/merge the outputs by calling the same collapseInlineMockOutputs used
for the inline path (or an equivalent merge function) and iterate over that
collapsed array instead of rawMockOutputs; update references inside the loop
(e.g., mockOutput, mockOutput.implementation, mockOutput.imports) to use the
merged entries so multiple outputs of the same type (MSW, etc.) are merged
rather than overwritten.

In `@packages/core/src/writers/split-mode.test.ts`:
- Around line 241-291: The test's custom importsMock may not be applied because
createSplitModeProps(target).builder could be frozen/sealed so the nested spread
doesn't override importsMock; modify the props construction to ensure
builder.importsMock is actually set (e.g., start from a shallow clone or
construct builder explicitly rather than relying on nested spread of
createSplitModeProps(...).builder) and keep the importsMockCalls capture logic,
and add a defensive assertion (e.g.,
expect(importsMockCalls.length).toBeGreaterThan(0)) before accessing
importsMockCalls[0]; reference the importsMock function, importsMockCalls array,
createSplitModeProps, and writeSplitMode to locate where to apply these changes.

In `@packages/core/src/writers/split-tags-mode.ts`:
- Around line 300-312: The index generation currently iterates tagEntries for
every mockIndexEntry, causing exports for tags that may not have a mock file in
that mockDir; modify the mock generation to record which tags actually produced
files per (ext, mockDir) during the mock emission loop (collect tuples of {ext,
mockDir, tag}), then when output.mock.indexMockFiles is true, group those tuples
by ext+mockDir (instead of using tagEntries) and build indexContent from only
the tags present for that group (using the same localMockPath logic with
upath.joinSafe and the OutputMockType.MSW branch) before calling
writeGeneratedFile for each indexPath; ensure helpers referenced
(mockIndexEntries, OutputMockType.MSW, pascal, writeGeneratedFile) are reused
as-is.

In `@packages/core/src/writers/tags-mode.ts`:
- Around line 359-377: The index generator currently iterates all tagEntries for
each mockIndexEntries entry causing exports for non-existent mock files; update
the logic to only include tags that actually have a mock for the given (ext,
mockDir). For example, when building mockIndexEntries or just before mapping
tagEntries in the block around shouldDeinlineMocks/output.mock.indexMockFiles,
filter tagEntries using either a precomputed map of which tags provide which ext
types or by checking the mock file existence for the resolved localMockPath,
then generate exports only for those filtered tags (use the same symbols:
mockIndexEntries, tagEntries, OutputMockType, writeGeneratedFile,
generatedFilePathsArray). Also update the tracking structure for each (ext,
mockDir) entry to record contributing tags so generated index files contain only
valid exports.

---

Nitpick comments:
In `@packages/core/src/writers/tags-mode.ts`:
- Around line 126-127: The branch inside tags-mode.ts calling
collapseInlineMockOutputs(rawMockOutputs) multiple times should compute that
value once and reuse it: inside the per-tag processing try block (the
!shouldDeinlineMocks branch), hoist collapseInlineMockOutputs(rawMockOutputs)
into a local const (e.g. collapsedMockOutputs) before the repeated uses and then
replace the three duplicate calls with references to that const; update any
usages that expect the original shape accordingly (functions/mappings that read
mockOutputs/rawMockOutputs should now use collapsedMockOutputs) to avoid
redundant computation and ensure consistent results.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7a489390-bbc7-4eca-ab7f-dc2635c415a0

📥 Commits

Reviewing files that changed from the base of the PR and between 33ef474 and f5226b9.

📒 Files selected for processing (12)
  • packages/core/src/types.ts
  • packages/core/src/writers/mock-utils.test.ts
  • packages/core/src/writers/mock-utils.ts
  • packages/core/src/writers/single-mode.ts
  • packages/core/src/writers/split-mode.test.ts
  • packages/core/src/writers/split-mode.ts
  • packages/core/src/writers/split-tags-mode.test.ts
  • packages/core/src/writers/split-tags-mode.ts
  • packages/core/src/writers/tags-mode.test.ts
  • packages/core/src/writers/tags-mode.ts
  • packages/orval/src/utils/options.ts
  • tests/api-generation.spec.ts

Comment thread packages/core/src/writers/tags-mode.ts Resolved

@melloware melloware left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Build is failing

@aqeelat

aqeelat commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@melloware It is because I didn't include the snapshot updates. they're > 150 files and will cause rabbit to not review the code.
I'll add them when the logic is done.

@aqeelat
aqeelat force-pushed the feat/mock-output-paths branch from f5226b9 to de607fc Compare June 7, 2026 10:00
@melloware melloware added the mock Related to mock generation label Jun 7, 2026
@melloware

Copy link
Copy Markdown
Collaborator

@wadakatu please review this when available

@aqeelat
aqeelat force-pushed the feat/mock-output-paths branch 2 times, most recently from d7042ef to f46b20d Compare June 7, 2026 12:16
@suzunn

suzunn commented Jun 7, 2026

Copy link
Copy Markdown

I noticed the implementation intentionally keeps the generated snapshot refresh out of this PR for reviewability, but that is also where a lot of the new path/import behavior will be exercised. Before merging, I would add at least one committed fixture that combines mock.path, per-generator path, indexMockFiles, and output.schemas using the .schemas suffix case covered by resolveMockSchemasPath.

That would lock down the highest-risk contract here: generated MSW/faker files living outside the client tree still import schemas from the right relative path, and the per-directory barrels stay deterministic after tags are sorted. The unit tests cover the helpers well, but a generated-output fixture would catch a future writer-level regression where one mode bypasses the shared helper or computes the mock directory before normalization.

@aqeelat

aqeelat commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

@suzunn already added in a previous commit.

@wadakatu wadakatu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@melloware @aqeelat — took a thorough pass through the source changes (the 7 non-snapshot files) and exercised the new code paths locally. The core design is solid: the de-inline logic preserves existing no-path behavior (only the index-mock-file sort diff changed among existing snapshots), import resolution is correct across all the path layouts I tried (mocks/ → ../model, mocks/<tag>/ → ../../model, and the inline-schema ../endpoints / ../endpoints.schemas cases), and the #3554 function-generator unification works as intended.

Two things I'd want addressed before merge, left as inline comments below: one confirmed determinism bug, and a test-coverage gap around the new path code.

if (shouldDeinlineMocks && output.mock.indexMockFiles) {
for (const { ext, mockDir, tags } of mockIndexEntries) {
const indexPath = path.join(mockDir, `index.${ext}${extension}`);
const indexContent = tags

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

tags mode + mock.path + indexMockFiles produces a non-deterministic barrel.

The ordering fix from f46b20db2 was only applied to split-tags-mode.ts, not here. mockIndexEntries[].tags is populated inside the concurrent Promise.all(tagEntries.map(async …)) loop via indexEntry.tags.push(kebabTag), so insertion order depends on which async write resolves first — and this barrel emit maps over tags without sorting.

Generating the same spec 8× (petstore, tags pets/health) flips the order between runs:

run 1: export { getPetsMock }   … ; export { getHealthMock } …
run 2: export { getHealthMock } … ; export { getPetsMock }   …
run 5: export { getPetsMock }   … ; export { getHealthMock } …
(other runs: health → pets)

This causes regeneration diff noise for users and would make any future fixture for this combo a flaky snapshot. split-tags-mode is unaffected (it sorts) and single mode is unaffected (single mock file per type).

Fix — sort at emit time, mirroring split-tags-mode.ts:

const sortedTags = [...tags].sort();
const indexContent = sortedTags.map((kebabTag) => { … }).join('');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the fast turnaround — and the three new fixtures (singleMockPath, tagsMockPath, tagsSplitPerGeneratorPath) close the coverage gap nicely. 🙏

However, the determinism fix in e9e2d838a doesn't actually resolve it, and it regressed split-tags-mode. Sorting Object.entries(target) at the source doesn't constrain the barrel order, because indexEntry.tags is accumulated after await writeGeneratedFile(...) inside the concurrent Promise.all(tagEntries.map(async …)) — so the push order follows I/O completion, not the sorted input order. Removing the emit-time [...tags].sort() therefore re-opens the race.

Verified locally by regenerating the new fixtures 10× each:

tagsMockPath        (tags + path + index):       still flips health↔pets across runs
tagsSplitMockPath   (split-tags, per-gen paths): now ALSO flips  ← regressed by removing the emit-time sort

So tagsMockPath, tagsSplitMockPath, and the existing index-mock-file snapshots are now flaky — CI passing here is just luck of the draw on the I/O completion order.

The robust fix is to keep the sort at emit time (where the order actually matters), in both writers:

// tags-mode.ts and split-tags-mode.ts — barrel emit loop
const indexContent = [...tags]
  .sort()
  .map((tag) => { … })
  .join('');

With that restored, all three fixtures are stable across 10/10 regenerations. The .toSorted() on tagEntries is harmless but isn't sufficient on its own.

target: '../specifications/faker-array-items-tags-split.yaml',
},
},
splitMockPath: {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Committed fixtures don't cover the most complex new path code.

These configs only exercise a shared mock.path in split / tags-split. The following new behaviors have no committed fixture — I verified them manually and they generate correctly, but there's no regression net:

Combination Covered?
single mode + path (de-inline path) ❌
tags mode + path (+ indexMockFiles) ❌ — this is exactly where the determinism bug lives
per-generator distinct path (e.g. msw → ./msw, faker → ./faker) ❌

The de-inline branch in single-mode.ts / tags-mode.ts is the largest piece of new logic, so a fixture there is the highest-value addition (and a tags+path+indexMockFiles fixture would have caught the ordering bug). This is the part of @suzunn's earlier request that's still open — single/tags and per-generator paths aren't in the current fixtures.

@aqeelat
aqeelat force-pushed the feat/mock-output-paths branch from f46b20d to e9e2d83 Compare June 8, 2026 10:29
@melloware
melloware requested a review from wadakatu June 8, 2026 12:02
@melloware

Copy link
Copy Markdown
Collaborator

@aqeelat let @wadakatu know when this is ready for re-review.

@aqeelat

aqeelat commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review --dir packages
@coderabbitai review --dir docs

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

@aqeelat Sure! I'll kick off a review focused on the packages and docs directories now.


🧠 Learnings used
Learnt from: wadakatu
Repo: orval-labs/orval PR: 3284
File: tests/__snapshots__/react-query/global-use-query-with-use-mutation-false/endpoints.ts:495-497
Timestamp: 2026-04-28T08:29:49.179Z
Learning: In `packages/query/src/query-generator.ts` (orval repo), when non-GET verbs (POST/DELETE/etc.) are emitted as query hooks via `override.query.useQuery: true`, the generated `get*QueryKey` helpers use path-only keys (e.g., `['/pets/${petId}']`). This causes a pre-existing cache collision between different HTTP verbs targeting the same path (e.g., `getShowPetByIdQueryKey` and `getDeletePetByIdQueryKey` both produce `['/pets/${petId}']`). Fixing this requires adding verb/operationId namespacing to non-GET query keys across every TanStack-Query and SWR generator and reflowing all snapshots — it is tracked as a follow-up and intentionally not fixed in PR `#3284`.
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@aqeelat

aqeelat commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

@melloware @wadakatu the PR is ready

@melloware
melloware self-requested a review June 8, 2026 17:24
@wadakatu

wadakatu commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

@aqeelat Left a follow-up on the determinism thread — the new fixtures look great, but the toSorted() approach in e9e2d83 doesn't actually fix the ordering (and removing the emit-time sort regressed split-tags-mode). I verified it still flips across regenerations. Details + the one-line fix here: #3559 (comment) — could you take a look when you get a chance? 🙏

@aqeelat
aqeelat force-pushed the feat/mock-output-paths branch from 5b0355e to 66950c0 Compare June 9, 2026 09:32
@aqeelat

aqeelat commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review but ignore tests/__snapshots__/*

@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

@aqeelat Sure! I'll kick off a full review now, excluding tests/__snapshots__/*.

Path exclusion: tests/__snapshots__/*

✅ Action performed

Full review finished.

@aqeelat

aqeelat commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@melloware is it a good idea to configure coderabbit to ignore tests/__snapshots__/* by default?

@aqeelat

aqeelat commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@wadakatu I now understand the issue. I fixed it and added a test case for it. The test has a 10ms delay but I couldn't get around that.

@melloware

Copy link
Copy Markdown
Collaborator

@aqeelat sorry I just merged another PR and you have merge conflicts! Apologies!

@melloware

Copy link
Copy Markdown
Collaborator

@aqeelat i just asked @anymaniax if we can ignore tests/snapshots i will let you know what he says!

aqeelat added 3 commits June 9, 2026 15:14
Adds per-generator and shared output paths to the mock configuration,
so MSW handlers and faker fixtures can be written to a separate
package entrypoint instead of next to the generated client services.

Output config now supports:

  mock: {
    path: '<shared mock output dir>',
    generators: [
      { type: 'msw', path: '<msw dir>' },
      { type: 'faker', path: '<faker dir>' },
      (client, options) => ...,         // ClientMockBuilder
    ],
  }

A per-entry `path` overrides the shared `mock.path`. Function-form
generators (ClientMockBuilder) cannot carry a `path` and fall back
to the shared `mock.path`.

Function-form generators are now mapped to MSW consistently across
all four write modes (single, split, tags, tags-split). Previously,
`split` mode silently skipped them and `tags-split` mode threw
`Function mock generators ... are not supported in tags-split mode`.

`mock-utils.ts` centralizes the shared `getMockDir`,
`hasAnyMockPath`, and `resolveMockSchemasPath` helpers used by
all four writers. The relative-import computation now treats a
trailing `.schemas` on the schemas target as a logical marker
(not a real extension) so `output.schemas` paths keep their
`<filename>.schemas` suffix in generated mock imports.

Closes orval-labs#3537
Fixes orval-labs#3554
aqeelat added 4 commits June 9, 2026 15:14
Use .toSorted() on Object.entries(target) in tags-mode and
split-tags-mode so that Promise.all accumulation order is
deterministic, removing the need for emit-time sorting.

Also adds test fixtures for previously uncovered mock path combos:
- single mode + mock.path + indexMockFiles
- tags mode + mock.path + indexMockFiles
- tags-split mode with per-generator distinct paths
Add unit tests that mock writeGeneratedFile with a 10ms delay on the
health tag to force reverse I/O completion order. Asserts the barrel
exports appear in locale-sorted order (admin, health, pets) regardless
of Promise.all settle order.

Also adds emit-time .toSorted() on the tags array in both tags-mode
and split-tags-mode barrel generation as a belt-and-suspenders fix
alongside the existing source-level sort.
@aqeelat
aqeelat force-pushed the feat/mock-output-paths branch from 66950c0 to 471dd63 Compare June 9, 2026 12:17
@aqeelat

aqeelat commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@melloware rebased

@melloware
melloware merged commit 8563fcd into orval-labs:master Jun 9, 2026
6 checks passed
@aqeelat
aqeelat deleted the feat/mock-output-paths branch June 9, 2026 12:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mock Related to mock generation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Function generators are handled inconsistently across write modes feat: support separate output paths for mocks and fakers

4 participants