Skip to content

Comments

[zod-mock]: add recursion depth control feature#262

Open
akkonrad wants to merge 1 commit intoanatine:mainfrom
akkonrad:main
Open

[zod-mock]: add recursion depth control feature#262
akkonrad wants to merge 1 commit intoanatine:mainfrom
akkonrad:main

Conversation

@akkonrad
Copy link

Pull Request: Prevent infinite recursion in zod-mock with levelLimit option

  • Scope: packages/zod-mock
  • Type: Feature/Fix

Summary

Adds a recursion guard to generateMock to prevent infinite loops for self-referential schemas. Introduces a new option levelLimit (default: 1) to control how many times the same schema instance can expand along a single generation path.

Motivation

Self-referential schemas (e.g., via z.lazy) could cause infinite recursion during mock generation. This change provides a safe default and a configurable limit to support controlled depth.

Changes

  • Add levelLimit?: number to GenerateMockOptions (default = 1).
  • Add internal __levelsMap__?: WeakMap<ZodTypeAny, number> to track per-call expansion counts.
  • Return undefined when the limit is exceeded at a specific node to stop further expansion.
  • Tests:
    • Default behavior prevents recursion (stops at one level).
    • Custom depth when levelLimit is increased.
  • Docs:
    • Add “Controlling recursion depth for self-referential schemas” section to README.md with examples.

Usage

const Node: z.ZodType<any> = z.lazy(() =>
  z.object({ value: z.string(), next: Node.optional() })
);

// default: stops at one expansion (next is undefined)
const mock1 = generateMock(Node);

// allow one nested node (two levels total)
const mock2 = generateMock(Node, { levelLimit: 2 });

Backwards Compatibility

  • No breaking changes. Default behavior is safe for self-referential schemas and does not affect non-recursive schemas.

Tests

  • Added unit tests to validate default and custom recursion depth behaviors.

Documentation

  • Updated packages/zod-mock/README.md with a new section describing levelLimit, rationale, and examples.

If there’s a preferred default depth or alternative handling strategy (e.g., truncating with a sentinel value), I can adjust accordingly.

@nx-cloud
Copy link

nx-cloud bot commented Sep 11, 2025

View your CI Pipeline Execution ↗ for commit 67e7cfb

Command Status Duration Result
nx affected:test --base=origin/main --codeCoverage ✅ Succeeded 21s View ↗
nx affected:lint --base=origin/main ✅ Succeeded 4s View ↗

☁️ Nx Cloud last updated this comment at 2025-09-11 13:12:17 UTC

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant