@kubb/ast 5.0.0-beta.75 → 5.0.0-beta.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +17 -10
- package/README.md +53 -27
- package/dist/defineMacro-C58x6uaa.cjs +114 -0
- package/dist/defineMacro-C58x6uaa.cjs.map +1 -0
- package/dist/defineMacro-DzsACbFo.d.ts +466 -0
- package/dist/defineMacro-Zagno12u.js +98 -0
- package/dist/defineMacro-Zagno12u.js.map +1 -0
- package/dist/index-Cu2zmNxv.d.ts +2188 -0
- package/dist/index.cjs +183 -2179
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +88 -3364
- package/dist/index.js +139 -2101
- package/dist/index.js.map +1 -1
- package/dist/macros.cjs +130 -0
- package/dist/macros.cjs.map +1 -0
- package/dist/macros.d.ts +61 -0
- package/dist/macros.js +128 -0
- package/dist/macros.js.map +1 -0
- package/dist/refs-DhraOHHv.cjs +135 -0
- package/dist/refs-DhraOHHv.cjs.map +1 -0
- package/dist/refs-DliAPaUa.js +101 -0
- package/dist/refs-DliAPaUa.js.map +1 -0
- package/dist/rolldown-runtime-CNktS9qV.js +17 -0
- package/dist/types-Ctz5NB1o.d.ts +244 -0
- package/dist/types.cjs +0 -0
- package/dist/types.d.ts +4 -0
- package/dist/types.js +1 -0
- package/dist/utils.cjs +613 -0
- package/dist/utils.cjs.map +1 -0
- package/dist/utils.d.ts +353 -0
- package/dist/utils.js +589 -0
- package/dist/utils.js.map +1 -0
- package/dist/visitor-CDa9Cn6x.cjs +1547 -0
- package/dist/visitor-CDa9Cn6x.cjs.map +1 -0
- package/dist/visitor-Ns-njjbG.js +1183 -0
- package/dist/visitor-Ns-njjbG.js.map +1 -0
- package/package.json +18 -7
- package/dist/chunk--u3MIqq1.js +0 -8
- package/src/constants.ts +0 -228
- package/src/factory.ts +0 -742
- package/src/guards.ts +0 -110
- package/src/index.ts +0 -45
- package/src/infer.ts +0 -130
- package/src/mocks.ts +0 -176
- package/src/nodes/base.ts +0 -56
- package/src/nodes/code.ts +0 -304
- package/src/nodes/file.ts +0 -230
- package/src/nodes/function.ts +0 -223
- package/src/nodes/http.ts +0 -119
- package/src/nodes/index.ts +0 -86
- package/src/nodes/operation.ts +0 -111
- package/src/nodes/output.ts +0 -26
- package/src/nodes/parameter.ts +0 -41
- package/src/nodes/property.ts +0 -34
- package/src/nodes/response.ts +0 -43
- package/src/nodes/root.ts +0 -64
- package/src/nodes/schema.ts +0 -656
- package/src/printer.ts +0 -250
- package/src/refs.ts +0 -67
- package/src/resolvers.ts +0 -45
- package/src/transformers.ts +0 -159
- package/src/types.ts +0 -70
- package/src/utils.ts +0 -833
- package/src/visitor.ts +0 -592
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.cjs","names":["narrowSchema","createSchema","resolveRefName","collectLazy"],"sources":["../../../internals/utils/src/promise.ts","../../../internals/utils/src/reserved.ts","../../../internals/utils/src/string.ts","../src/utils/codegen.ts","../src/utils/schemaMerge.ts","../src/utils/strings.ts","../src/utils/schemaGraph.ts","../src/utils/schemaTraversal.ts"],"sourcesContent":["/** A value that may already be resolved or still pending.\n *\n * @example\n * ```ts\n * function load(id: string): PossiblePromise<string> {\n * return cache.get(id) ?? fetchRemote(id)\n * }\n * ```\n */\nexport type PossiblePromise<T> = Promise<T> | T\n\n/** Returns `true` when `result` is a thenable `Promise`.\n *\n * @example\n * ```ts\n * isPromise(Promise.resolve(1)) // true\n * isPromise(42) // false\n * ```\n */\nexport function isPromise<T>(result: PossiblePromise<T>): result is Promise<T> {\n return result !== null && result !== undefined && typeof (result as Record<string, unknown>)['then'] === 'function'\n}\n\ntype Store<TKey, TValue> = {\n has(key: TKey): boolean\n get(key: TKey): TValue | undefined\n set(key: TKey, value: TValue): unknown\n}\n\n/**\n * Wraps `factory` with a keyed cache backed by the provided store.\n *\n * Pass a `WeakMap` for object keys (results are GC-eligible when the key is\n * collected) or a `Map` for primitive keys. For multi-argument functions,\n * nest two `memoize` calls — the outer keyed by the first argument, the\n * inner (created once per outer miss) keyed by the second.\n *\n * Because the cache is owned by the caller, it can be shared, inspected, or\n * cleared independently of the memoized function.\n *\n * @example Single WeakMap key\n * ```ts\n * const cache = new WeakMap<SchemaNode, Set<string>>()\n * const getRefs = memoize(cache, (node) => collectRefs(node))\n * ```\n *\n * @example Single Map key (primitive)\n * ```ts\n * const cache = new Map<string, Resolver>()\n * const getResolver = memoize(cache, (name) => buildResolver(name))\n * ```\n *\n * @example Two-level (object + primitive)\n * ```ts\n * const outer = new WeakMap<Params[], Map<string, Params[]>>()\n * const fn = memoize(outer, (params) => memoize(new Map(), (key) => transform(params, key)))\n * fn(params)('camelcase')\n * ```\n */\nexport function memoize<TKey, TValue>(store: Store<TKey, TValue>, factory: (key: TKey) => TValue): (key: TKey) => TValue {\n return (key: TKey): TValue => {\n if (store.has(key)) return store.get(key)!\n const value = factory(key)\n store.set(key, value)\n return value\n }\n}\n\n/**\n * Container that switches between an eager `Array<T>` and a lazy `AsyncIterable<T>`.\n *\n * `Array<T>` by default. With `Stream` set to `true` it becomes `AsyncIterable<T>`, so large\n * collections can be produced lazily without holding every item in memory. Pairs with\n * {@link arrayToAsyncIterable}, which lifts a plain array into the streaming form.\n *\n * @example\n * ```ts\n * type Eager = Streamable<number> // Array<number>\n * type Lazy = Streamable<number, true> // AsyncIterable<number>\n * ```\n */\nexport type Streamable<T, Stream extends boolean = false> = Stream extends true ? AsyncIterable<T> : Array<T>\n\n/**\n * Wraps a plain array in a reusable `AsyncIterable`.\n * Each `[Symbol.asyncIterator]()` call returns a fresh generator so the\n * iterable can be consumed multiple times (e.g. once per plugin pre-scan).\n *\n * @example\n * ```ts\n * const stream = arrayToAsyncIterable([1, 2, 3])\n * for await (const n of stream) console.log(n) // 1, 2, 3\n * ```\n */\nexport function arrayToAsyncIterable<T>(arr: ReadonlyArray<T>): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n return (async function* () {\n yield* arr\n })()\n },\n }\n}\n","/**\n * JavaScript and Java reserved words.\n * @link https://github.com/jonschlinkert/reserved/blob/master/index.js\n */\nconst reservedWords = new Set([\n 'abstract',\n 'arguments',\n 'boolean',\n 'break',\n 'byte',\n 'case',\n 'catch',\n 'char',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'double',\n 'else',\n 'enum',\n 'eval',\n 'export',\n 'extends',\n 'false',\n 'final',\n 'finally',\n 'float',\n 'for',\n 'function',\n 'goto',\n 'if',\n 'implements',\n 'import',\n 'in',\n 'instanceof',\n 'int',\n 'interface',\n 'let',\n 'long',\n 'native',\n 'new',\n 'null',\n 'package',\n 'private',\n 'protected',\n 'public',\n 'return',\n 'short',\n 'static',\n 'super',\n 'switch',\n 'synchronized',\n 'this',\n 'throw',\n 'throws',\n 'transient',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'volatile',\n 'while',\n 'with',\n 'yield',\n 'Array',\n 'Date',\n 'hasOwnProperty',\n 'Infinity',\n 'isFinite',\n 'isNaN',\n 'isPrototypeOf',\n 'length',\n 'Math',\n 'name',\n 'NaN',\n 'Number',\n 'Object',\n 'prototype',\n 'String',\n 'toString',\n 'undefined',\n 'valueOf',\n] as const)\n\n/**\n * Prefixes `word` with `_` when it is a reserved JavaScript/Java identifier or starts with a digit.\n *\n * @example\n * ```ts\n * transformReservedWord('class') // '_class'\n * transformReservedWord('42foo') // '_42foo'\n * transformReservedWord('status') // 'status'\n * ```\n */\nexport function transformReservedWord(word: string): string {\n const firstChar = word.charCodeAt(0)\n if (word && (reservedWords.has(word as 'valueOf') || (firstChar >= 48 && firstChar <= 57))) {\n return `_${word}`\n }\n return word\n}\n\n/**\n * Returns `true` when `name` is a syntactically valid JavaScript variable name.\n *\n * @example\n * ```ts\n * isValidVarName('status') // true\n * isValidVarName('class') // false (reserved word)\n * isValidVarName('42foo') // false (starts with digit)\n * ```\n */\nexport function isValidVarName(name: string): boolean {\n if (!name || reservedWords.has(name as 'valueOf')) {\n return false\n }\n return isIdentifier(name)\n}\n\n/**\n * Returns `true` when `name` is syntactically a valid identifier, ignoring reserved words.\n *\n * Reserved words and globals (`class`, `name`, `Date`, …) are valid as bare object-literal keys\n * even though they are not valid variable names, so use this (not {@link isValidVarName}) when\n * deciding whether an object key needs quoting.\n *\n * @example\n * ```ts\n * isIdentifier('name') // true\n * isIdentifier('x-total')// false\n * ```\n */\nexport function isIdentifier(name: string): boolean {\n return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)\n}\n","/**\n * Wraps a value in single quotes for emitting a single-quoted JavaScript string literal, escaping\n * any backslash or single quote in the content.\n *\n * @example\n * ```ts\n * singleQuote('foo') // \"'foo'\"\n * singleQuote(\"o'clock\") // \"'o\\\\'clock'\"\n * ```\n */\nexport function singleQuote(value: string | number | boolean | undefined | null): string {\n if (value === undefined || value === null) return \"''\"\n const escaped = String(value).replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\")\n\n return `'${escaped}'`\n}\n","import { isIdentifier, singleQuote } from '@internals/utils'\nimport { INDENT } from '../constants.ts'\n\n/**\n * Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no\n * comments.\n *\n * @example\n * ```ts\n * buildJSDoc(['@type string', '@example hello'])\n * // '/**\\n * @type string\\n * @example hello\\n *\\/\\n '\n * ```\n */\nexport function buildJSDoc(\n comments: Array<string>,\n options: {\n /**\n * String used to indent each comment line.\n * @default ' * '\n */\n indent?: string\n /**\n * String appended after the closing tag.\n * @default '\\n '\n */\n suffix?: string\n /**\n * Returned as-is when `comments` is empty.\n * @default ' '\n */\n fallback?: string\n } = {},\n): string {\n const { indent = ' * ', suffix = '\\n ', fallback = ' ' } = options\n\n if (comments.length === 0) return fallback\n\n return `/**\\n${comments.map((c) => `${indent}${c}`).join('\\n')}\\n */${suffix}`\n}\n\n/**\n * Indents every non-empty line of `text` by one indent level, leaving blank lines empty.\n */\nfunction indentLines(text: string): string {\n if (!text) return ''\n return text\n .split('\\n')\n .map((line) => (line.trim() ? `${INDENT}${line}` : ''))\n .join('\\n')\n}\n\n/**\n * Renders an object key, quoting it with single quotes only when it is not a valid identifier.\n * Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.\n *\n * @example\n * ```ts\n * objectKey('name') // 'name'\n * objectKey('x-total') // \"'x-total'\"\n * ```\n */\nexport function objectKey(name: string): string {\n return isIdentifier(name) ? name : singleQuote(name)\n}\n\n/**\n * Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one\n * level and closing the brace at column zero. Entries that are themselves multi-line objects indent\n * cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.\n *\n * @example\n * ```ts\n * buildObject(['id: z.number()', 'name: z.string()'])\n * // '{\\n id: z.number(),\\n name: z.string(),\\n}'\n * ```\n */\nexport function buildObject(entries: Array<string>): string {\n if (entries.length === 0) return '{}'\n const body = entries.map((entry) => `${indentLines(entry)},`).join('\\n')\n\n return `{\\n${body}\\n}`\n}\n\n/**\n * Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on\n * one line when no item spans multiple lines, and otherwise puts each item on its own line, indented\n * one level with a trailing comma and the closing bracket at column zero. Used for member lists such\n * as `z.union([…])` and `z.array([…])`.\n *\n * @example\n * ```ts\n * buildList(['z.string()', 'z.number()'])\n * // '[z.string(), z.number()]'\n * ```\n */\nexport function buildList(items: Array<string>, brackets: [open: string, close: string] = ['[', ']']): string {\n const [open, close] = brackets\n if (items.length === 0) return `${open}${close}`\n if (!items.some((item) => item.includes('\\n'))) return `${open}${items.join(', ')}${close}`\n const body = items.map((item) => `${indentLines(item)},`).join('\\n')\n\n return `${open}\\n${body}\\n${close}`\n}\n","import { narrowSchema } from '../guards.ts'\nimport { createSchema, type SchemaNode } from '../nodes/schema.ts'\n\n/**\n * Merges a run of adjacent anonymous object members into one. Named or non-object members break the\n * run and pass through unchanged. The merge follows member order, so callers control which members\n * combine by where they place them in the sequence.\n *\n * @example\n * ```ts\n * const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]\n * ```\n */\nexport function* mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined> {\n let acc: SchemaNode | undefined\n\n for (const member of members) {\n const objectMember = narrowSchema(member, 'object')\n if (objectMember && !objectMember.name && acc !== undefined) {\n const accObject = narrowSchema(acc, 'object')\n if (accObject && !accObject.name) {\n acc = createSchema({\n ...accObject,\n properties: [...(accObject.properties ?? []), ...(objectMember.properties ?? [])],\n })\n continue\n }\n }\n if (acc !== undefined) yield acc\n acc = member\n }\n\n if (acc !== undefined) yield acc\n}\n","/**\n * Strips a single matching pair of `\"...\"`, `'...'`, or `` `...` `` from both ends of `text`.\n * Returns the string unchanged when no balanced quote pair is found.\n *\n * @example\n * ```ts\n * trimQuotes('\"hello\"') // 'hello'\n * trimQuotes('hello') // 'hello'\n * ```\n */\nexport function trimQuotes(text: string): string {\n if (text.length >= 2) {\n const first = text[0]\n const last = text[text.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\") || (first === '`' && last === '`')) {\n return text.slice(1, -1)\n }\n }\n return text\n}\n\n/**\n * Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.\n *\n * Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated\n * code matches the repo style without a formatter.\n *\n * @example\n * ```ts\n * stringify('hello') // \"'hello'\"\n * stringify('\"hello\"') // \"'hello'\"\n * ```\n */\nexport function stringify(value: string | number | boolean | undefined): string {\n if (value === undefined || value === null) return \"''\"\n const json = JSON.stringify(trimQuotes(value.toString()))\n const inner = json.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/'/g, \"\\\\'\")\n return `'${inner}'`\n}\n\n/**\n * Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,\n * and the Unicode line terminators U+2028 and U+2029.\n *\n * @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4\n *\n * @example\n * ```ts\n * jsStringEscape('say \"hi\"\\nbye') // 'say \\\\\"hi\\\\\"\\\\nbye'\n * ```\n */\nexport function jsStringEscape(input: unknown): string {\n return `${input}`.replace(/[\"'\\\\\\n\\r\\u2028\\u2029]/g, (character) => {\n switch (character) {\n case '\"':\n case \"'\":\n case '\\\\':\n return `\\\\${character}`\n case '\\n':\n return '\\\\n'\n case '\\r':\n return '\\\\r'\n case '\\u2028':\n return '\\\\u2028'\n case '\\u2029':\n return '\\\\u2029'\n default:\n return ''\n }\n })\n}\n\n/**\n * Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.\n * Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.\n * Pass `null` as the second argument to emit a `/pattern/flags` literal instead.\n *\n * @example\n * ```ts\n * toRegExpString('^(?im)foo') // 'new RegExp(\"^foo\", \"im\")'\n * toRegExpString('^(?im)foo', null) // '/^foo/im'\n * ```\n */\nexport function toRegExpString(text: string, func: string | null = 'RegExp'): string {\n const raw = trimQuotes(text)\n\n const match = raw.match(/^\\^(\\(\\?([igmsuy]+)\\))/i)\n const replacementTarget = match?.[1] ?? ''\n const matchedFlags = match?.[2]\n const cleaned = raw\n .replace(/^\\\\?\\//, '')\n .replace(/\\\\?\\/$/, '')\n .replace(replacementTarget, '')\n\n const { source, flags } = new RegExp(cleaned, matchedFlags)\n\n if (func === null) return `/${source}/${flags}`\n\n return `new ${func}(${JSON.stringify(source)}${flags ? `, ${JSON.stringify(flags)}` : ''})`\n}\n\n/**\n * Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested\n * objects recurse with fixed indentation, so the result drops straight into an object literal\n * without re-parsing.\n *\n * @example\n * ```ts\n * stringifyObject({ foo: 'bar', nested: { a: 1 } })\n * // 'foo: bar,\\nnested: {\\n a: 1\\n }'\n * ```\n */\nexport function stringifyObject(value: Record<string, unknown>): string {\n const items = Object.entries(value)\n .map(([key, val]) => {\n if (val !== null && typeof val === 'object') {\n return `${key}: {\\n ${stringifyObject(val as Record<string, unknown>)}\\n }`\n }\n return `${key}: ${val}`\n })\n .filter(Boolean)\n return items.join(',\\n')\n}\n\n/**\n * Renders a dotted path or string array as an optional-chaining accessor expression rooted at\n * `accessor`. Returns `null` for an empty path.\n *\n * @example\n * ```ts\n * getNestedAccessor('pagination.next.id', 'lastPage')\n * // \"lastPage?.['pagination']?.['next']?.['id']\"\n * ```\n */\nexport function getNestedAccessor(param: string | Array<string>, accessor: string): string | null {\n const parts = Array.isArray(param) ? param : param.split('.')\n if (parts.length === 0 || (parts.length === 1 && parts[0] === '')) return null\n return `${accessor}?.['${`${parts.join(\"']?.['\")}']`}`\n}\n","import { memoize } from '@internals/utils'\nimport type { OperationNode, SchemaNode } from '../nodes/index.ts'\nimport { collect, collectLazy } from '../visitor.ts'\nimport { resolveRefName } from './refs.ts'\n\n/**\n * Memoized inner pass that walks a single node and returns the names of every schema it references.\n */\nconst collectSchemaRefs = memoize(new WeakMap<SchemaNode, ReadonlySet<string>>(), (node: SchemaNode): ReadonlySet<string> => {\n const refs = new Set<string>()\n collect<void>(node, {\n schema(child) {\n if (child.type === 'ref') {\n const name = resolveRefName(child)\n if (name) refs.add(name)\n }\n },\n })\n return refs\n})\n\n/**\n * Collects the names of every ref found anywhere inside a node's own subtree.\n *\n * Each ref contributes its name only, so the schema it points to is never traversed here. Pass `out`\n * to accumulate names from several nodes into one set.\n *\n * @example Collect refs from a single schema\n * ```ts\n * const names = collectReferencedSchemaNames(petSchema)\n * // Set { 'Category', 'Tag' }\n * ```\n *\n * @example Accumulate refs from multiple schemas into one set\n * ```ts\n * const out = new Set<string>()\n * for (const schema of schemas) {\n * collectReferencedSchemaNames(schema, out)\n * }\n * ```\n */\nexport function collectReferencedSchemaNames(node: SchemaNode | undefined, out: Set<string> = new Set()): Set<string> {\n if (!node) return out\n for (const name of collectSchemaRefs(node)) out.add(name)\n return out\n}\n\n/**\n * Memoized two-level cache keyed first on the operations array, then on the schemas array.\n */\nconst collectUsedSchemaNamesMemo = memoize(new WeakMap<ReadonlyArray<OperationNode>, (schemas: ReadonlyArray<SchemaNode>) => Set<string>>(), (ops) =>\n memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas) => computeUsedSchemaNames(ops, schemas)),\n)\n\nfunction computeUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {\n const schemaMap = new Map<string, SchemaNode>()\n for (const schema of schemas) {\n if (schema.name) schemaMap.set(schema.name, schema)\n }\n\n const result = new Set<string>()\n\n function visitSchema(schema: SchemaNode): void {\n const directRefs = collectReferencedSchemaNames(schema)\n for (const name of directRefs) {\n if (!result.has(name)) {\n result.add(name)\n const namedSchema = schemaMap.get(name)\n if (namedSchema) visitSchema(namedSchema)\n }\n }\n }\n\n for (const op of operations) {\n for (const schema of collectLazy<SchemaNode>(op, { depth: 'shallow', schema: (node) => node })) {\n visitSchema(schema)\n }\n }\n\n return result\n}\n\n/**\n * Collects the names of all top-level schemas transitively used by a set of operations.\n *\n * An operation uses a schema when its parameters, request body, or responses reference it, directly\n * or through other named schemas. Once a name is added to the result it is not revisited, so\n * reference cycles terminate.\n *\n * Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.\n *\n * @example Only generate schemas referenced by included operations\n * ```ts\n * const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)\n * const allowed = collectUsedSchemaNames(includedOps, schemas)\n *\n * for (const schema of schemas) {\n * if (schema.name && !allowed.has(schema.name)) continue\n * // generate schema\n * }\n * ```\n */\nexport function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string> {\n return collectUsedSchemaNamesMemo(operations)(schemas)\n}\n\nconst EMPTY_CIRCULAR_SET = new Set<string>()\n\nconst findCircularSchemasMemo = memoize(new WeakMap<ReadonlyArray<SchemaNode>, Set<string>>(), (schemas: ReadonlyArray<SchemaNode>): Set<string> => {\n const graph = new Map<string, Set<string>>()\n\n for (const schema of schemas) {\n if (!schema.name) continue\n graph.set(schema.name, collectReferencedSchemaNames(schema))\n }\n\n const circular = new Set<string>()\n for (const start of graph.keys()) {\n const visited = new Set<string>()\n const stack: Array<string> = [...(graph.get(start) ?? [])]\n while (stack.length > 0) {\n const node = stack.pop()!\n if (node === start) {\n circular.add(start)\n break\n }\n if (visited.has(node)) continue\n visited.add(node)\n\n const next = graph.get(node)\n if (next) for (const r of next) stack.push(r)\n }\n }\n\n return circular\n})\n\n/**\n * Finds every schema that takes part in a circular dependency chain, including direct self-loops.\n *\n * Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so\n * the generated code does not recurse forever. Refs are followed by name only, so the walk stays\n * linear in the size of the schema graph.\n *\n * @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.\n */\nexport function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string> {\n if (schemas.length === 0) return EMPTY_CIRCULAR_SET\n return findCircularSchemasMemo(schemas)\n}\n\n/**\n * Returns `true` when a schema, or anything nested inside it, references a circular schema.\n *\n * Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled\n * on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.\n *\n * @note Stops at the first matching circular ref.\n */\nexport function containsCircularRef(\n node: SchemaNode | undefined,\n { circularSchemas, excludeName }: { circularSchemas: ReadonlySet<string>; excludeName?: string },\n): boolean {\n if (!node || circularSchemas.size === 0) return false\n\n for (const _ of collectLazy<true>(node, {\n schema(child) {\n if (child.type !== 'ref') return null\n const name = resolveRefName(child)\n return name && name !== excludeName && circularSchemas.has(name) ? true : null\n },\n })) {\n return true\n }\n\n return false\n}\n","import type { ArraySchemaNode, IntersectionSchemaNode, ObjectSchemaNode, PropertyNode, SchemaNode, UnionSchemaNode } from '../nodes/index.ts'\nimport { objectKey } from './codegen.ts'\n\n/**\n * Converts a child schema to printer output. Plugins instantiate it with their own output type:\n * `string` for the zod and faker printers, `ts.TypeNode` for the TypeScript printer. A printer's\n * `this.transform` fits directly, so its `null` for an empty result carries through to `output`.\n */\nexport type SchemaTransform<TOutput> = (schema: SchemaNode) => TOutput\n\n/**\n * A union or intersection member, or an array or tuple item, paired with its transformed output.\n */\nexport type MappedSchema<TOutput> = {\n /**\n * The original child schema, kept so the printer can read its metadata for leaf formatting.\n */\n schema: SchemaNode\n /**\n * The child schema after being run through the transform.\n */\n output: TOutput\n}\n\n/**\n * An object property paired with its transformed output.\n */\nexport type MappedProperty<TOutput> = {\n /**\n * The property name as written on the schema, before any identifier quoting.\n */\n name: string\n /**\n * The original property node, kept so the printer can read `required`, `schema`, and metadata.\n */\n property: PropertyNode\n /**\n * The property schema after being run through the transform.\n */\n output: TOutput\n}\n\n/**\n * Maps each property of an object schema to its transformed output. Pairs every result with the\n * original property so the printer keeps full control over modifiers, getters, and key syntax.\n *\n * @example\n * ```ts\n * const entries = mapSchemaProperties(node, (schema) => this.transform(schema))\n * // entries: [{ name: 'id', property, output: 'z.number()' }, ...]\n * ```\n */\nexport function mapSchemaProperties<TOutput>(node: ObjectSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedProperty<TOutput>> {\n return node.properties.map((property) => ({ name: property.name, property, output: transform(property.schema) }))\n}\n\n/**\n * Maps each member of a union or intersection schema to its transformed output, pairing every\n * result with the original member.\n */\nexport function mapSchemaMembers<TOutput>(node: UnionSchemaNode | IntersectionSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>> {\n return (node.members ?? []).map((schema) => ({ schema, output: transform(schema) }))\n}\n\n/**\n * Maps each item of an array or tuple schema to its transformed output, pairing every result with\n * the original item.\n */\nexport function mapSchemaItems<TOutput>(node: ArraySchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>> {\n return (node.items ?? []).map((schema) => ({ schema, output: transform(schema) }))\n}\n\n/**\n * Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key\n * is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation\n * of a recursive schema until first access.\n *\n * @example\n * ```ts\n * lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })\n * // \"get parent() { return z.lazy(() => Pet) }\"\n * ```\n */\nexport function lazyGetter({ name, body }: { name: string; body: string }): string {\n return `get ${objectKey(name)}() { return ${body} }`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,QAAsB,OAA4B,SAAuD;CACvH,QAAQ,QAAsB;EAC5B,IAAI,MAAM,IAAI,GAAG,GAAG,OAAO,MAAM,IAAI,GAAG;EACxC,MAAM,QAAQ,QAAQ,GAAG;EACzB,MAAM,IAAI,KAAK,KAAK;EACpB,OAAO;CACT;AACF;;;;;;;AC9DA,MAAM,gBAAgB,IAAI,IAAI;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAU;;;;;;;;;;;AA8BV,SAAgB,eAAe,MAAuB;CACpD,IAAI,CAAC,QAAQ,cAAc,IAAI,IAAiB,GAC9C,OAAO;CAET,OAAO,aAAa,IAAI;AAC1B;;;;;;;;;;;;;;AAeA,SAAgB,aAAa,MAAuB;CAClD,OAAO,6BAA6B,KAAK,IAAI;AAC/C;;;;;;;;;;;;;AChIA,SAAgB,YAAY,OAA6D;CACvF,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAGlD,OAAO,IAFS,OAAO,KAAK,CAAC,CAAC,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,KAElD,EAAE;AACrB;;;;;;;;;;;;;ACFA,SAAgB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KAAK,YAAY;EAAE;EAAQ,QAAQ,UAAU,MAAM;CAAE,EAAE;AACrF;;;;;AAMA,SAAgB,eAAwB,MAAuB,WAAmE;CAChI,QAAQ,KAAK,SAAS,CAAC,EAAA,CAAG,KAAK,YAAY;EAAE;EAAQ,QAAQ,UAAU,MAAM;CAAE,EAAE;AACnF;;;;;;;;;;;;AAaA,SAAgB,WAAW,EAAE,MAAM,QAAgD;CACjF,OAAO,OAAO,UAAU,IAAI,EAAE,cAAc,KAAK;AACnD"}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
import { n as __name } from "./rolldown-runtime-CNktS9qV.js";
|
|
2
|
+
import { U as ArraySchemaNode, Y as ObjectSchemaNode, _t as CodeNode, at as UnionSchemaNode, et as SchemaNode, f as OperationNode, lt as PropertyNode, q as IntersectionSchemaNode } from "./index-Cu2zmNxv.js";
|
|
3
|
+
|
|
4
|
+
//#region ../../internals/utils/src/reserved.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Returns `true` when `name` is a syntactically valid JavaScript variable name.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* isValidVarName('status') // true
|
|
11
|
+
* isValidVarName('class') // false (reserved word)
|
|
12
|
+
* isValidVarName('42foo') // false (starts with digit)
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
declare function isValidVarName(name: string): boolean;
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/utils/codegen.d.ts
|
|
18
|
+
/**
|
|
19
|
+
* Builds a JSDoc comment block from an array of lines. Returns `fallback` when there are no
|
|
20
|
+
* comments.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* buildJSDoc(['@type string', '@example hello'])
|
|
25
|
+
* // '/**\n * @type string\n * @example hello\n *\/\n '
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
declare function buildJSDoc(comments: Array<string>, options?: {
|
|
29
|
+
/**
|
|
30
|
+
* String used to indent each comment line.
|
|
31
|
+
* @default ' * '
|
|
32
|
+
*/
|
|
33
|
+
indent?: string;
|
|
34
|
+
/**
|
|
35
|
+
* String appended after the closing tag.
|
|
36
|
+
* @default '\n '
|
|
37
|
+
*/
|
|
38
|
+
suffix?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Returned as-is when `comments` is empty.
|
|
41
|
+
* @default ' '
|
|
42
|
+
*/
|
|
43
|
+
fallback?: string;
|
|
44
|
+
}): string;
|
|
45
|
+
/**
|
|
46
|
+
* Renders an object key, quoting it with single quotes only when it is not a valid identifier.
|
|
47
|
+
* Reserved words and globals (`name`, `class`, …) are valid bare keys and stay unquoted.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* objectKey('name') // 'name'
|
|
52
|
+
* objectKey('x-total') // "'x-total'"
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
declare function objectKey(name: string): string;
|
|
56
|
+
/**
|
|
57
|
+
* Assembles a multi-line object literal from already-rendered `entries`, indenting each entry one
|
|
58
|
+
* level and closing the brace at column zero. Entries that are themselves multi-line objects indent
|
|
59
|
+
* cumulatively. Each entry ends with a trailing comma to match the formatter's multi-line style.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* buildObject(['id: z.number()', 'name: z.string()'])
|
|
64
|
+
* // '{\n id: z.number(),\n name: z.string(),\n}'
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
declare function buildObject(entries: Array<string>): string;
|
|
68
|
+
/**
|
|
69
|
+
* Assembles a bracketed list (array by default) from already-rendered `items`. Keeps everything on
|
|
70
|
+
* one line when no item spans multiple lines, and otherwise puts each item on its own line, indented
|
|
71
|
+
* one level with a trailing comma and the closing bracket at column zero. Used for member lists such
|
|
72
|
+
* as `z.union([…])` and `z.array([…])`.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```ts
|
|
76
|
+
* buildList(['z.string()', 'z.number()'])
|
|
77
|
+
* // '[z.string(), z.number()]'
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
declare function buildList(items: Array<string>, brackets?: [open: string, close: string]): string;
|
|
81
|
+
//#endregion
|
|
82
|
+
//#region src/utils/extractStringsFromNodes.d.ts
|
|
83
|
+
/**
|
|
84
|
+
* Extracts all string content from a `CodeNode` tree recursively.
|
|
85
|
+
*
|
|
86
|
+
* Collects text node values, identifier references in string fields (`params`, `generics`, `returnType`, `type`),
|
|
87
|
+
* and nested node content. Used to build the full source string for import filtering.
|
|
88
|
+
*/
|
|
89
|
+
declare function extractStringsFromNodes(nodes: Array<CodeNode> | undefined): string;
|
|
90
|
+
//#endregion
|
|
91
|
+
//#region src/utils/refs.d.ts
|
|
92
|
+
/**
|
|
93
|
+
* Returns the last path segment of a reference string.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* `extractRefName('#/components/schemas/Pet') // 'Pet'`
|
|
97
|
+
*/
|
|
98
|
+
declare function extractRefName(ref: string): string;
|
|
99
|
+
/**
|
|
100
|
+
* Builds a PascalCase child schema name by joining a parent name and property name.
|
|
101
|
+
* Returns `null` when there is no parent to nest under.
|
|
102
|
+
*
|
|
103
|
+
* @example Nested under a parent
|
|
104
|
+
* `childName('Order', 'shipping_address') // 'OrderShippingAddress'`
|
|
105
|
+
*
|
|
106
|
+
* @example No parent
|
|
107
|
+
* `childName(undefined, 'params') // null`
|
|
108
|
+
*/
|
|
109
|
+
declare function childName(parentName: string | null | undefined, propName: string): string | null;
|
|
110
|
+
/**
|
|
111
|
+
* Builds a PascalCase enum name from the parent name, property name, and a suffix, skipping any
|
|
112
|
+
* empty parts.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* `enumPropName('Order', 'status', 'enum') // 'OrderStatusEnum'`
|
|
116
|
+
*/
|
|
117
|
+
declare function enumPropName(parentName: string | null | undefined, propName: string, enumSuffix: string): string;
|
|
118
|
+
/**
|
|
119
|
+
* Merges a ref node with its resolved schema, giving usage-site fields precedence.
|
|
120
|
+
*
|
|
121
|
+
* Every field set on the ref node except `kind`, `type`, `name`, `ref`, and `schema` overrides the
|
|
122
|
+
* same field in the resolved `node.schema` (for example `description`, `nullable`, `readOnly`,
|
|
123
|
+
* `deprecated`). Fields left `undefined` on the ref do not shadow the resolved schema. Non-ref
|
|
124
|
+
* nodes and refs without a resolved `schema` are returned unchanged.
|
|
125
|
+
*
|
|
126
|
+
* @example
|
|
127
|
+
* ```ts
|
|
128
|
+
* const ref = createSchema({ type: 'ref', ref: '#/components/schemas/Pet', description: 'A cute pet' })
|
|
129
|
+
* const merged = syncSchemaRef(ref) // merges with resolved Pet schema
|
|
130
|
+
* ```
|
|
131
|
+
*/
|
|
132
|
+
declare function syncSchemaRef(node: SchemaNode): SchemaNode;
|
|
133
|
+
/**
|
|
134
|
+
* Type guard that returns `true` when a schema emits as a plain `string` type.
|
|
135
|
+
*
|
|
136
|
+
* Covers `string`, `uuid`, `email`, `url`, and `datetime` types. For `date` and `time`
|
|
137
|
+
* types, returns `true` only when `representation` is `'string'` rather than `'date'`.
|
|
138
|
+
*/
|
|
139
|
+
declare function isStringType(node: SchemaNode): boolean;
|
|
140
|
+
//#endregion
|
|
141
|
+
//#region src/utils/schemaMerge.d.ts
|
|
142
|
+
/**
|
|
143
|
+
* Merges a run of adjacent anonymous object members into one. Named or non-object members break the
|
|
144
|
+
* run and pass through unchanged. The merge follows member order, so callers control which members
|
|
145
|
+
* combine by where they place them in the sequence.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* const merged = [...mergeAdjacentObjectsLazy([objectA, objectB])]
|
|
150
|
+
* ```
|
|
151
|
+
*/
|
|
152
|
+
declare function mergeAdjacentObjectsLazy(members: Iterable<SchemaNode>): Generator<SchemaNode, void, undefined>;
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region src/utils/strings.d.ts
|
|
155
|
+
/**
|
|
156
|
+
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
157
|
+
* Returns the string unchanged when no balanced quote pair is found.
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```ts
|
|
161
|
+
* trimQuotes('"hello"') // 'hello'
|
|
162
|
+
* trimQuotes('hello') // 'hello'
|
|
163
|
+
* ```
|
|
164
|
+
*/
|
|
165
|
+
declare function trimQuotes(text: string): string;
|
|
166
|
+
/**
|
|
167
|
+
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
|
|
168
|
+
*
|
|
169
|
+
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
|
|
170
|
+
* code matches the repo style without a formatter.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```ts
|
|
174
|
+
* stringify('hello') // "'hello'"
|
|
175
|
+
* stringify('"hello"') // "'hello'"
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
declare function stringify(value: string | number | boolean | undefined): string;
|
|
179
|
+
/**
|
|
180
|
+
* Escapes characters that are not allowed inside JS string literals, covering quotes, backslashes,
|
|
181
|
+
* and the Unicode line terminators U+2028 and U+2029.
|
|
182
|
+
*
|
|
183
|
+
* @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* ```ts
|
|
187
|
+
* jsStringEscape('say "hi"\nbye') // 'say \\"hi\\"\\nbye'
|
|
188
|
+
* ```
|
|
189
|
+
*/
|
|
190
|
+
declare function jsStringEscape(input: unknown): string;
|
|
191
|
+
/**
|
|
192
|
+
* Converts a pattern string into a `new RegExp(...)` constructor call or a regex literal string.
|
|
193
|
+
* Inline flags expressed as a `^(?im)` prefix are extracted and applied to the resulting expression.
|
|
194
|
+
* Pass `null` as the second argument to emit a `/pattern/flags` literal instead.
|
|
195
|
+
*
|
|
196
|
+
* @example
|
|
197
|
+
* ```ts
|
|
198
|
+
* toRegExpString('^(?im)foo') // 'new RegExp("^foo", "im")'
|
|
199
|
+
* toRegExpString('^(?im)foo', null) // '/^foo/im'
|
|
200
|
+
* ```
|
|
201
|
+
*/
|
|
202
|
+
declare function toRegExpString(text: string, func?: string | null): string;
|
|
203
|
+
/**
|
|
204
|
+
* Renders a plain object as multi-line `key: value` source for embedding in generated code. Nested
|
|
205
|
+
* objects recurse with fixed indentation, so the result drops straight into an object literal
|
|
206
|
+
* without re-parsing.
|
|
207
|
+
*
|
|
208
|
+
* @example
|
|
209
|
+
* ```ts
|
|
210
|
+
* stringifyObject({ foo: 'bar', nested: { a: 1 } })
|
|
211
|
+
* // 'foo: bar,\nnested: {\n a: 1\n }'
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
declare function stringifyObject(value: Record<string, unknown>): string;
|
|
215
|
+
/**
|
|
216
|
+
* Renders a dotted path or string array as an optional-chaining accessor expression rooted at
|
|
217
|
+
* `accessor`. Returns `null` for an empty path.
|
|
218
|
+
*
|
|
219
|
+
* @example
|
|
220
|
+
* ```ts
|
|
221
|
+
* getNestedAccessor('pagination.next.id', 'lastPage')
|
|
222
|
+
* // "lastPage?.['pagination']?.['next']?.['id']"
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
declare function getNestedAccessor(param: string | Array<string>, accessor: string): string | null;
|
|
226
|
+
//#endregion
|
|
227
|
+
//#region src/utils/schemaGraph.d.ts
|
|
228
|
+
/**
|
|
229
|
+
* Collects the names of all top-level schemas transitively used by a set of operations.
|
|
230
|
+
*
|
|
231
|
+
* An operation uses a schema when its parameters, request body, or responses reference it, directly
|
|
232
|
+
* or through other named schemas. Once a name is added to the result it is not revisited, so
|
|
233
|
+
* reference cycles terminate.
|
|
234
|
+
*
|
|
235
|
+
* Pair it with `include` filters so schemas reachable only from excluded operations stay ungenerated.
|
|
236
|
+
*
|
|
237
|
+
* @example Only generate schemas referenced by included operations
|
|
238
|
+
* ```ts
|
|
239
|
+
* const includedOps = operations.filter((op) => resolver.resolveOptions(op, { options, include }) !== null)
|
|
240
|
+
* const allowed = collectUsedSchemaNames(includedOps, schemas)
|
|
241
|
+
*
|
|
242
|
+
* for (const schema of schemas) {
|
|
243
|
+
* if (schema.name && !allowed.has(schema.name)) continue
|
|
244
|
+
* // generate schema
|
|
245
|
+
* }
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
declare function collectUsedSchemaNames(operations: ReadonlyArray<OperationNode>, schemas: ReadonlyArray<SchemaNode>): Set<string>;
|
|
249
|
+
/**
|
|
250
|
+
* Finds every schema that takes part in a circular dependency chain, including direct self-loops.
|
|
251
|
+
*
|
|
252
|
+
* Wrap the returned schema positions in a deferred construct (a lazy getter or `z.lazy(() => …)`) so
|
|
253
|
+
* the generated code does not recurse forever. Refs are followed by name only, so the walk stays
|
|
254
|
+
* linear in the size of the schema graph.
|
|
255
|
+
*
|
|
256
|
+
* @note Call this once on the full graph, then check individual schemas with `containsCircularRef()`.
|
|
257
|
+
*/
|
|
258
|
+
declare function findCircularSchemas(schemas: ReadonlyArray<SchemaNode>): Set<string>;
|
|
259
|
+
/**
|
|
260
|
+
* Returns `true` when a schema, or anything nested inside it, references a circular schema.
|
|
261
|
+
*
|
|
262
|
+
* Pass `excludeName` to skip refs to a specific schema, which helps when self-references are handled
|
|
263
|
+
* on their own. Pair it with `findCircularSchemas()` to decide where lazy wrappers go.
|
|
264
|
+
*
|
|
265
|
+
* @note Stops at the first matching circular ref.
|
|
266
|
+
*/
|
|
267
|
+
declare function containsCircularRef(node: SchemaNode | undefined, {
|
|
268
|
+
circularSchemas,
|
|
269
|
+
excludeName
|
|
270
|
+
}: {
|
|
271
|
+
circularSchemas: ReadonlySet<string>;
|
|
272
|
+
excludeName?: string;
|
|
273
|
+
}): boolean;
|
|
274
|
+
//#endregion
|
|
275
|
+
//#region src/utils/schemaTraversal.d.ts
|
|
276
|
+
/**
|
|
277
|
+
* Converts a child schema to printer output. Plugins instantiate it with their own output type:
|
|
278
|
+
* `string` for the zod and faker printers, `ts.TypeNode` for the TypeScript printer. A printer's
|
|
279
|
+
* `this.transform` fits directly, so its `null` for an empty result carries through to `output`.
|
|
280
|
+
*/
|
|
281
|
+
type SchemaTransform<TOutput> = (schema: SchemaNode) => TOutput;
|
|
282
|
+
/**
|
|
283
|
+
* A union or intersection member, or an array or tuple item, paired with its transformed output.
|
|
284
|
+
*/
|
|
285
|
+
type MappedSchema<TOutput> = {
|
|
286
|
+
/**
|
|
287
|
+
* The original child schema, kept so the printer can read its metadata for leaf formatting.
|
|
288
|
+
*/
|
|
289
|
+
schema: SchemaNode;
|
|
290
|
+
/**
|
|
291
|
+
* The child schema after being run through the transform.
|
|
292
|
+
*/
|
|
293
|
+
output: TOutput;
|
|
294
|
+
};
|
|
295
|
+
/**
|
|
296
|
+
* An object property paired with its transformed output.
|
|
297
|
+
*/
|
|
298
|
+
type MappedProperty<TOutput> = {
|
|
299
|
+
/**
|
|
300
|
+
* The property name as written on the schema, before any identifier quoting.
|
|
301
|
+
*/
|
|
302
|
+
name: string;
|
|
303
|
+
/**
|
|
304
|
+
* The original property node, kept so the printer can read `required`, `schema`, and metadata.
|
|
305
|
+
*/
|
|
306
|
+
property: PropertyNode;
|
|
307
|
+
/**
|
|
308
|
+
* The property schema after being run through the transform.
|
|
309
|
+
*/
|
|
310
|
+
output: TOutput;
|
|
311
|
+
};
|
|
312
|
+
/**
|
|
313
|
+
* Maps each property of an object schema to its transformed output. Pairs every result with the
|
|
314
|
+
* original property so the printer keeps full control over modifiers, getters, and key syntax.
|
|
315
|
+
*
|
|
316
|
+
* @example
|
|
317
|
+
* ```ts
|
|
318
|
+
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
|
|
319
|
+
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
|
|
320
|
+
* ```
|
|
321
|
+
*/
|
|
322
|
+
declare function mapSchemaProperties<TOutput>(node: ObjectSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedProperty<TOutput>>;
|
|
323
|
+
/**
|
|
324
|
+
* Maps each member of a union or intersection schema to its transformed output, pairing every
|
|
325
|
+
* result with the original member.
|
|
326
|
+
*/
|
|
327
|
+
declare function mapSchemaMembers<TOutput>(node: UnionSchemaNode | IntersectionSchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>>;
|
|
328
|
+
/**
|
|
329
|
+
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
|
|
330
|
+
* the original item.
|
|
331
|
+
*/
|
|
332
|
+
declare function mapSchemaItems<TOutput>(node: ArraySchemaNode, transform: SchemaTransform<TOutput>): Array<MappedSchema<TOutput>>;
|
|
333
|
+
/**
|
|
334
|
+
* Emits a lazy getter for a circular-ref property position, `get name() { return body }`. The key
|
|
335
|
+
* is quoted only when it is not a valid identifier. Used by the string printers to defer evaluation
|
|
336
|
+
* of a recursive schema until first access.
|
|
337
|
+
*
|
|
338
|
+
* @example
|
|
339
|
+
* ```ts
|
|
340
|
+
* lazyGetter({ name: 'parent', body: 'z.lazy(() => Pet)' })
|
|
341
|
+
* // "get parent() { return z.lazy(() => Pet) }"
|
|
342
|
+
* ```
|
|
343
|
+
*/
|
|
344
|
+
declare function lazyGetter({
|
|
345
|
+
name,
|
|
346
|
+
body
|
|
347
|
+
}: {
|
|
348
|
+
name: string;
|
|
349
|
+
body: string;
|
|
350
|
+
}): string;
|
|
351
|
+
//#endregion
|
|
352
|
+
export { buildJSDoc, buildList, buildObject, childName, collectUsedSchemaNames, containsCircularRef, enumPropName, extractRefName, extractStringsFromNodes, findCircularSchemas, getNestedAccessor, isStringType, isValidVarName, jsStringEscape, lazyGetter, mapSchemaItems, mapSchemaMembers, mapSchemaProperties, mergeAdjacentObjectsLazy, objectKey, stringify, stringifyObject, syncSchemaRef, toRegExpString, trimQuotes };
|
|
353
|
+
//# sourceMappingURL=utils.d.ts.map
|