@kubb/ast 5.23.4 → 5.24.0
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/README.md +1 -1
- package/dist/{base-LhsPvVY1.d.ts → base-A-xF4pUL.d.ts} +1 -0
- package/dist/{base-UFBZi-FO.d.cts → base-CyJhBRMi.d.cts} +1 -0
- package/dist/{constants-DztHlVmY.cjs → constants-BCRkFAiy.cjs} +2 -1
- package/dist/constants-BCRkFAiy.cjs.map +1 -0
- package/dist/{constants-BTTus9ee.js → constants-UorsTFsa.js} +2 -1
- package/dist/constants-UorsTFsa.js.map +1 -0
- package/dist/factory.cjs +4 -3
- package/dist/factory.d.cts +4 -4
- package/dist/factory.d.ts +4 -4
- package/dist/factory.js +4 -4
- package/dist/{file-D_ih0x7q.js → file-1YtTOZeL.js} +4 -4
- package/dist/{file-D_ih0x7q.js.map → file-1YtTOZeL.js.map} +1 -1
- package/dist/{file-Bq2GPaxh.js → file-3gsgXreK.js} +3 -3
- package/dist/{file-Bq2GPaxh.js.map → file-3gsgXreK.js.map} +1 -1
- package/dist/{file-B269mZh4.d.cts → file-CMHRNuMX.d.cts} +1 -1
- package/dist/{file-oLlejzZV.d.ts → file-D67ITWja.d.ts} +1 -1
- package/dist/{file-C4pqV8yl.cjs → file-D73XubVb.cjs} +3 -3
- package/dist/{file-C4pqV8yl.cjs.map → file-D73XubVb.cjs.map} +1 -1
- package/dist/{file-DiPZBLSP.cjs → file-azmmZwDb.cjs} +4 -4
- package/dist/{file-DiPZBLSP.cjs.map → file-azmmZwDb.cjs.map} +1 -1
- package/dist/file.cjs +2 -2
- package/dist/file.d.cts +1 -1
- package/dist/file.d.ts +1 -1
- package/dist/file.js +2 -2
- package/dist/{graph-CFJ4wzFR.cjs → graph-DDh1FFrm.cjs} +3 -3
- package/dist/{graph-CFJ4wzFR.cjs.map → graph-DDh1FFrm.cjs.map} +1 -1
- package/dist/{graph-BUEOBomo.js → graph-DImDxlJE.js} +3 -3
- package/dist/{graph-BUEOBomo.js.map → graph-DImDxlJE.js.map} +1 -1
- package/dist/graph.cjs +1 -1
- package/dist/graph.d.cts +1 -1
- package/dist/graph.d.ts +1 -1
- package/dist/graph.js +1 -1
- package/dist/{guards-u-dAAtl8.d.cts → guards-B6LgmDhJ.d.cts} +1 -1
- package/dist/{guards-RCnH6re9.d.ts → guards-l2AsKeHR.d.ts} +1 -1
- package/dist/http.d.cts +2 -2
- package/dist/http.d.ts +2 -2
- package/dist/{index-C1za72gL.d.cts → index-2hzFweaD.d.cts} +1 -1
- package/dist/{index-DbQ-J072.d.cts → index-84453BaS.d.cts} +1 -1
- package/dist/{index-UwSVys3m.d.ts → index-B3o1AkNE.d.ts} +4 -4
- package/dist/{index-BgFaJtnv.d.ts → index-BFwAhPp8.d.ts} +1 -1
- package/dist/{index-c9FD2S5f.d.cts → index-Bcxj7FqZ.d.cts} +3 -3
- package/dist/index-BiXrjYNm.d.cts +5 -0
- package/dist/{index-D_WLsIMP.d.cts → index-BvdIGsVr.d.cts} +2 -2
- package/dist/{index-DzHcy3vy.d.ts → index-C7U9EiIP.d.ts} +2 -2
- package/dist/index-CC5Rmgcm.d.ts +5 -0
- package/dist/{index-6-ZZCX9W.d.ts → index-CGmrJThc.d.ts} +4 -4
- package/dist/{index-DF7CbpYW.d.ts → index-CIUD99Ft.d.ts} +3 -3
- package/dist/{index-DpnCCtXt.d.cts → index-D2tWPgnK.d.cts} +1 -1
- package/dist/{index-B2nnOQjf.d.cts → index-DNZgWmNq.d.cts} +4 -4
- package/dist/{index-DbAnYRRM.d.ts → index-DerFkxlp.d.ts} +1 -1
- package/dist/{index-sdprVPKQ.d.cts → index-DfTgdgaH.d.cts} +1 -1
- package/dist/{index-DfRcRYF2.d.ts → index-YTyLBHFN.d.ts} +1 -1
- package/dist/{index-Bw2oMIM1.d.cts → index-bkTCYnZj.d.cts} +4 -4
- package/dist/{index-2TMYDLjK.d.ts → index-f90iIhHX.d.ts} +1 -1
- package/dist/index.cjs +11 -11
- package/dist/index.d.cts +17 -16
- package/dist/index.d.ts +17 -16
- package/dist/index.js +11 -11
- package/dist/{json-DyDtIZTj.js → json-DeqPhPUQ.js} +2 -2
- package/dist/{json-DyDtIZTj.js.map → json-DeqPhPUQ.js.map} +1 -1
- package/dist/{json-CCWMgzJZ.cjs → json-KV2VhBue.cjs} +2 -2
- package/dist/{json-CCWMgzJZ.cjs.map → json-KV2VhBue.cjs.map} +1 -1
- package/dist/json.cjs +1 -1
- package/dist/json.d.cts +1 -1
- package/dist/json.d.ts +1 -1
- package/dist/json.js +1 -1
- package/dist/{macro-9WouvtZe.js → macro-3uGSg-ic.js} +2 -2
- package/dist/{macro-9WouvtZe.js.map → macro-3uGSg-ic.js.map} +1 -1
- package/dist/{macro-BEwfGNu1.cjs → macro-Ywn4-0s5.cjs} +2 -2
- package/dist/{macro-BEwfGNu1.cjs.map → macro-Ywn4-0s5.cjs.map} +1 -1
- package/dist/macro.cjs +1 -1
- package/dist/macro.d.cts +1 -1
- package/dist/macro.d.ts +1 -1
- package/dist/macro.js +1 -1
- package/dist/{node-vTrAIz3e.cjs → node-BeccjrHH.cjs} +4 -4
- package/dist/{node-vTrAIz3e.cjs.map → node-BeccjrHH.cjs.map} +1 -1
- package/dist/{node-DtuO3zr8.js → node-Dm56432_.js} +4 -4
- package/dist/{node-DtuO3zr8.js.map → node-Dm56432_.js.map} +1 -1
- package/dist/node.cjs +4 -4
- package/dist/node.d.cts +3 -3
- package/dist/node.d.ts +3 -3
- package/dist/node.js +4 -4
- package/dist/{nodeText-BSYvDZOH.js → nodeText-DFak5VpX.js} +2 -2
- package/dist/{nodeText-BSYvDZOH.js.map → nodeText-DFak5VpX.js.map} +1 -1
- package/dist/{nodeText-CZ7wgxu9.cjs → nodeText-DH4dLGUb.cjs} +2 -2
- package/dist/{nodeText-CZ7wgxu9.cjs.map → nodeText-DH4dLGUb.cjs.map} +1 -1
- package/dist/{nodes-DEQjVliP.cjs → nodes-BdZfapPI.cjs} +26 -4
- package/dist/nodes-BdZfapPI.cjs.map +1 -0
- package/dist/{nodes-ClL1C158.js → nodes-D9nwroV5.js} +21 -5
- package/dist/nodes-D9nwroV5.js.map +1 -0
- package/dist/{operation-Cu4XSaJQ.d.ts → operation-Dd0-l2VB.d.ts} +27 -2
- package/dist/{operation-AFw8tzIN.d.cts → operation-De4lbIZS.d.cts} +27 -2
- package/dist/{ref-Bh5Xo8T7.cjs → ref-Ck-0j8NV.cjs} +2 -2
- package/dist/{ref-Bh5Xo8T7.cjs.map → ref-Ck-0j8NV.cjs.map} +1 -1
- package/dist/{ref-DPqeS8K1.js → ref-Dlxn7eu7.js} +2 -2
- package/dist/{ref-DPqeS8K1.js.map → ref-Dlxn7eu7.js.map} +1 -1
- package/dist/ref.cjs +1 -1
- package/dist/ref.d.cts +1 -1
- package/dist/ref.d.ts +1 -1
- package/dist/ref.js +1 -1
- package/dist/{schema-gSjYgaCl.cjs → schema-0YJZqRXb.cjs} +2 -2
- package/dist/{schema-gSjYgaCl.cjs.map → schema-0YJZqRXb.cjs.map} +1 -1
- package/dist/{schema-4UcdIPQ2.js → schema-BvUrXIoX.js} +4 -4
- package/dist/{schema-4UcdIPQ2.js.map → schema-BvUrXIoX.js.map} +1 -1
- package/dist/{schema-tH14gE6i.js → schema-CC008xgK.js} +2 -2
- package/dist/{schema-tH14gE6i.js.map → schema-CC008xgK.js.map} +1 -1
- package/dist/{schema-DuCY4lCG.cjs → schema-DfLGJ-oh.cjs} +4 -4
- package/dist/{schema-DuCY4lCG.cjs.map → schema-DfLGJ-oh.cjs.map} +1 -1
- package/dist/schema.cjs +3 -3
- package/dist/schema.d.cts +4 -4
- package/dist/schema.d.ts +4 -4
- package/dist/schema.js +3 -3
- package/dist/{visitor-CpmsR8o5.d.ts → visitor-CqI8T9Qa.d.ts} +2 -2
- package/dist/{visitor-XA0W3OVv.js → visitor-DA5yfOJz.js} +3 -2
- package/dist/visitor-DA5yfOJz.js.map +1 -0
- package/dist/{visitor-Bh1CBAOz.cjs → visitor-DhuKS-7x.cjs} +3 -2
- package/dist/visitor-DhuKS-7x.cjs.map +1 -0
- package/dist/{visitor-DnBK2MNl.d.cts → visitor-VYLe7Q4m.d.cts} +2 -2
- package/package.json +1 -1
- package/dist/constants-BTTus9ee.js.map +0 -1
- package/dist/constants-DztHlVmY.cjs.map +0 -1
- package/dist/index-Bj7a0aSM.d.cts +0 -5
- package/dist/index-CW-ztJjd.d.ts +0 -5
- package/dist/nodes-ClL1C158.js.map +0 -1
- package/dist/nodes-DEQjVliP.cjs.map +0 -1
- package/dist/visitor-Bh1CBAOz.cjs.map +0 -1
- package/dist/visitor-XA0W3OVv.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"visitor-DhuKS-7x.cjs","names":["isJson","nodeKinds"],"sources":["../src/schema/embeddedJson.ts","../src/visitor.ts"],"sourcesContent":["import { isJson } from '../mediaType/index.ts'\nimport type { SchemaNode, StringSchemaNode } from '../nodes/schema.ts'\n\n/** The schema of the JSON document a string holds (`contentMediaType` with `contentSchema`), else `undefined`. */\nexport function getEmbeddedJson({ content }: Pick<StringSchemaNode, 'content'>): SchemaNode | undefined {\n // shortcut: an encoded document (`contentEncoding`) is not decoded, so only its encoding is checked; decode it once a spec needs both.\n if (!content?.schema || content.encoding || !content.mediaType) return undefined\n return isJson(content.mediaType) ? content.schema : undefined\n}\n","import { nodeKinds } from './constants.ts'\nimport type { Node } from './nodes/index.ts'\nimport type { InputNode } from './nodes/input.ts'\nimport type { NodeKind } from './nodes/base.ts'\nimport type { OperationNode } from './nodes/operation.ts'\nimport type { ParameterNode } from './nodes/parameter.ts'\nimport type { PropertyNode } from './nodes/property.ts'\nimport type { ResponseNode } from './nodes/response.ts'\nimport type { SchemaNode } from './nodes/schema.ts'\nimport { getEmbeddedJson } from './schema/embeddedJson.ts'\n\n/**\n * Traversal depth for AST visitor utilities.\n *\n * - `'shallow'` recurses through every node except nested `Schema` subtrees, which it treats as\n * leaves: a schema node itself is visited, but its children are not.\n * - `'deep'` recursively visits all descendant nodes, including schema subtrees.\n */\nexport type VisitorDepth = 'shallow' | 'deep'\n\n/**\n * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).\n */\nconst VISITOR_KEYS: Partial<Record<NodeKind, ReadonlyArray<string>>> = {\n Input: ['schemas', 'operations'],\n Operations: ['operations'],\n Operation: ['parameters', 'requestBody', 'responses'],\n RequestBody: ['content'],\n Content: ['schema', 'stream'],\n Response: ['content', 'headers'],\n Schema: ['properties', 'items', 'members', 'additionalProperties', 'patternProperties', 'propertyNames', 'rest'],\n Property: ['schema'],\n Parameter: ['schema'],\n}\n\n/**\n * Schema fields that hold checks rather than shape: the `conditionals` entries, `contains` and a string's `content`.\n * `transform` and `collect` skip them, and `visitChildNodes` walks them with `checks: true`.\n */\nexport const schemaCheckKeys = ['conditionals', 'contains', 'content'] as const\n\n/** Visitor callback names in traversal order, the keys of {@link Visitor}. */\nexport const visitorKeys = ['input', 'operation', 'schema', 'property', 'parameter', 'response'] as const\n\nexport type VisitorKey = (typeof visitorKeys)[number]\n\n/**\n * Maps a node kind to the matching visitor callback name.\n */\nconst VISITOR_KEY_BY_KIND: Partial<Record<NodeKind, VisitorKey>> = {\n Input: 'input',\n Operation: 'operation',\n Schema: 'schema',\n Property: 'property',\n Parameter: 'parameter',\n Response: 'response',\n}\n\n/**\n * Traversal context passed as the second argument to every visitor callback.\n *\n * @example\n * ```ts\n * const visitor: Visitor = {\n * schema(node, { parent }) {\n * // parent is the node that holds this schema, or undefined at the root\n * },\n * }\n * ```\n */\nexport type VisitorContext = {\n /**\n * Parent node of the currently visited node. For the root node, this is `undefined`.\n */\n parent?: Node\n}\n\n/**\n * Synchronous visitor consumed by `transform`. Each optional callback runs\n * for the matching node type. Return a new node to replace it, or `undefined`\n * to leave it untouched.\n *\n * Plugins typically expose `transformer` so users can supply a `Visitor` that\n * rewrites the AST before printing.\n *\n * @example Prefix every operationId\n * ```ts\n * const visitor: Visitor = {\n * operation(node) {\n * return { ...node, operationId: `api_${node.operationId}` }\n * },\n * }\n * ```\n *\n * @example Strip schema descriptions\n * ```ts\n * const visitor: Visitor = {\n * schema(node) {\n * return { ...node, description: undefined }\n * },\n * }\n * ```\n */\nexport type Visitor = {\n input?(node: InputNode, context: VisitorContext): undefined | null | InputNode\n operation?(node: OperationNode, context: VisitorContext): undefined | null | OperationNode\n schema?(node: SchemaNode, context: VisitorContext): undefined | null | SchemaNode\n property?(node: PropertyNode, context: VisitorContext): undefined | null | PropertyNode\n parameter?(node: ParameterNode, context: VisitorContext): undefined | null | ParameterNode\n response?(node: ResponseNode, context: VisitorContext): undefined | null | ResponseNode\n}\n\n/**\n * The callbacks of {@link Visitor} with every return type replaced by `TResult`. `collect` uses it\n * so a visitor can yield values instead of replacement nodes.\n *\n * @example\n * ```ts\n * const visitor: VisitorOf<string> = {\n * operation(node) {\n * return node.operationId\n * },\n * }\n * ```\n */\ntype VisitorOf<TResult> = {\n [K in keyof Visitor]?: (node: Parameters<NonNullable<Visitor[K]>>[0], context: Parameters<NonNullable<Visitor[K]>>[1]) => TResult | null | undefined\n}\n\ntype TraversalOptions = {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\n/**\n * Options for `transform`.\n *\n * @example\n * ```ts\n * const options: TransformOptions = { depth: 'deep', schema: (node) => node }\n * ```\n *\n * @example\n * ```ts\n * // Only transform the current node, not nested children\n * const options: TransformOptions = { depth: 'shallow', schema: (node) => node }\n * ```\n */\ntype TransformOptions = Visitor & TraversalOptions\n\n/**\n * Options for `collect`.\n *\n * @example\n * ```ts\n * const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }\n * ```\n */\ntype CollectOptions<T> = VisitorOf<T> & TraversalOptions\n\n/**\n * Returns `true` when `value` is an AST node (an object carrying a `kind`).\n */\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as { kind?: unknown }).kind === 'string'\n}\n\n/**\n * Returns `true` for a plain object that maps names to nodes, such as `patternProperties`.\n */\nfunction isNodeRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// A check no printer emits: a `contains` that any array meets (`min: 0`, no `max`), or `content` that is not JSON.\nfunction isNeverPrinted({ node, key }: { node: Node; key: string }): boolean {\n if (node.kind !== nodeKinds.schema) return false\n if (key === 'contains' && (node.type === 'array' || node.type === 'tuple')) return node.contains?.min === 0 && node.contains.max === undefined\n if (key === 'content' && node.type === 'string') return !getEmbeddedJson(node)\n return false\n}\n\n/**\n * Child keys of a schema walked with `checks: true`: the shape keys, then {@link schemaCheckKeys}.\n */\nconst SCHEMA_CHECK_VISITOR_KEYS: ReadonlyArray<string> = [...VISITOR_KEYS.Schema!, ...schemaCheckKeys]\n\n/**\n * Children a node already passed to `visit`. A node under two keys, such as a stream item under `schema` and\n * `stream`, is visited once. The `Set` is only created once a node has a second child.\n */\ntype SeenChildren = { first: Node | undefined; rest: Set<Node> | undefined }\n\nfunction visitOnce(child: Node, seen: SeenChildren, visit: (child: Node) => boolean): boolean {\n if (seen.first === undefined) {\n seen.first = child\n return visit(child)\n }\n if (seen.first === child || seen.rest?.has(child)) return false\n ;(seen.rest ??= new Set()).add(child)\n return visit(child)\n}\n\nfunction visitRecord(value: Record<string, unknown>, seen: SeenChildren, visit: (child: Node) => boolean): boolean {\n for (const name in value) {\n if (!Object.hasOwn(value, name)) continue\n const item = value[name]\n if (isNode(item) && visitOnce(item, seen, visit)) return true\n }\n return false\n}\n\n/**\n * Calls `visit` for each direct child node and stops at the first call that returns `true`.\n * With `checks: true`, a schema's {@link schemaCheckKeys} fields are walked too, except checks that cannot fail.\n */\nexport function visitChildNodes(node: Node, visit: (child: Node) => boolean, { checks = false }: { checks?: boolean } = {}): boolean {\n const withChecks = checks && node.kind === nodeKinds.schema\n const keys = withChecks ? SCHEMA_CHECK_VISITOR_KEYS : VISITOR_KEYS[node.kind]\n if (!keys) return false\n\n const record = node as unknown as Record<string, unknown>\n let seen: SeenChildren | undefined\n for (const key of keys) {\n const value = record[key]\n if (value === undefined || value === null) continue\n if (withChecks && isNeverPrinted({ node, key })) continue\n seen ??= { first: undefined, rest: undefined }\n if (Array.isArray(value)) {\n // Items can be plain objects that hold nodes, such as the `{ if, then, else }` entries of `conditionals`.\n for (const item of value) if (isNode(item) ? visitOnce(item, seen, visit) : isNodeRecord(item) && visitRecord(item, seen, visit)) return true\n continue\n }\n if (isNode(value)) {\n if (visitOnce(value, seen, visit)) return true\n continue\n }\n if (isNodeRecord(value) && visitRecord(value, seen, visit)) return true\n }\n return false\n}\n\ntype FindResult = { found: SchemaNode | undefined; low: number }\n\nconst notFound: FindResult = { found: undefined, low: Number.POSITIVE_INFINITY }\n\n/**\n * Finds the first schema that matches `predicate` in depth-first order. Pass `follow: ['ref']` to include resolved ref targets.\n *\n * @example\n * ```ts\n * const firstString = findSchema(operationNode, {\n * predicate: (schema) => schema.type === 'string',\n * })\n * ```\n */\nexport function findSchema(\n node: Node,\n {\n predicate,\n follow,\n followRefs = false,\n cache,\n }: {\n predicate: (schema: SchemaNode) => boolean\n /**\n * Links to follow on top of the walk over every child. `['ref']` also walks a resolved ref's target.\n * @default []\n */\n follow?: ReadonlyArray<'ref'>\n /**\n * @deprecated Use `follow: ['ref']`. Removed in Kubb v6.\n */\n followRefs?: boolean\n /**\n * Remembers the match below each schema (`null` for none), so later calls skip the parts of the graph they share.\n * Keep one cache per `predicate` and ref-following mode (`follow`, or the deprecated `followRefs`), for example one per build.\n * In a cyclic graph, a cached call can return a different match than the first one in depth-first order.\n */\n cache?: WeakMap<SchemaNode, SchemaNode | null>\n },\n): SchemaNode | undefined {\n const followsRefs = followRefs || (follow?.includes('ref') ?? false)\n // When following refs, as in Tarjan's algorithm: the visit order of a schema still being walked, or for a finished\n // schema without a match the lowest visit order of an unfinished schema its subtree reached. Only a schema whose\n // subtree reached nothing visited before it has a final no-match; until then it waits in `pending`.\n const state = followsRefs ? new Map<SchemaNode, number>() : undefined\n const pending: Array<SchemaNode> = []\n let order = 0\n\n const walkChildren = (current: Node, initial: FindResult): FindResult => {\n let result = initial\n visitChildNodes(current, (child) => {\n const next = walk(child)\n result = next.found || next.low < result.low ? next : result\n return next.found !== undefined\n })\n return result\n }\n\n const walkSchema = (current: SchemaNode): FindResult => {\n const target = state && current.type === 'ref' && current.schema ? walk(current.schema) : notFound\n if (target.found) return target\n return walkChildren(current, target)\n }\n\n const walk = (current: Node): FindResult => {\n if (current.kind !== nodeKinds.schema) return walkChildren(current, notFound)\n\n const cached = cache?.get(current)\n if (cached === null) return notFound\n if (cached) return { found: cached, low: Number.POSITIVE_INFINITY }\n if (predicate(current)) {\n cache?.set(current, current)\n return { found: current, low: Number.POSITIVE_INFINITY }\n }\n const known = state?.get(current)\n if (known !== undefined) return { found: undefined, low: known }\n\n const index = order++\n const start = pending.length\n state?.set(current, index)\n const result = walkSchema(current)\n if (result.found) {\n cache?.set(current, result.found)\n return result\n }\n if (!state) {\n cache?.set(current, null)\n return notFound\n }\n if (result.low < index) {\n state.set(current, result.low)\n pending.push(current)\n return result\n }\n for (const done of [...pending.splice(start), current]) {\n state.set(done, Number.POSITIVE_INFINITY)\n cache?.set(done, null)\n }\n return notFound\n }\n\n return walk(node).found\n}\n\n/**\n * Runs the visitor callback that matches `node.kind` with the traversal\n * context. The result is a replacement node, a collected value, or `undefined`\n * when no callback is registered for the kind.\n *\n * Shared by `transform` and `collect` so node-kind dispatch lives in one place.\n * `TResult` is the caller's expected return: the same node type for `transform`,\n * the collected value type for `collect`.\n */\nfunction applyVisitor<TResult>(node: Node, visitor: Visitor | VisitorOf<unknown>, parent: Node | undefined): TResult | null | undefined {\n const key = VISITOR_KEY_BY_KIND[node.kind]\n if (!key) return undefined\n\n const fn = visitor[key] as ((node: Node, context: VisitorContext) => TResult | null | undefined) | undefined\n\n return fn?.(node, { parent })\n}\n\n/**\n * Synchronous depth-first transform. Each visitor callback can return a\n * replacement node. Returning `undefined` keeps the original.\n *\n * The original tree is never mutated, a new tree is returned. Pass\n * `depth: 'shallow'` to skip the children of every schema node; other nodes are still walked.\n *\n * @example Prefix every operationId\n * ```ts\n * const next = transform(root, {\n * operation(node) {\n * return { ...node, operationId: `prefixed_${node.operationId}` }\n * },\n * })\n * ```\n *\n * @example Rewrite the root node without walking its schemas\n * ```ts\n * const next = transform(root, {\n * depth: 'shallow',\n * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),\n * })\n * ```\n */\nexport function transform<T extends Node>(node: T, options: TransformOptions): T {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? 'deep') === 'deep'\n\n // Split the visitor object out once here, then thread it plus `recurse`/`parent` as plain\n // arguments through the recursion. The previous code re-ran the `...visitor` rest-destructure on\n // every recursive `transform` call and rebuilt a `{ ...options, parent }` object per node, so the\n // options shape (which callbacks are present) varied call to call and the hot recursion churned.\n return transformNode(node, visitor, recurse, parent) as T\n}\n\n/**\n * Visits a single node, then immutably rebuilds its children. Returns the original\n * reference when neither the visitor nor the child rebuild changed anything, so callers\n * can detect \"nothing changed\" by identity and ancestors avoid reallocating.\n */\nfunction transformNode(node: Node, visitor: Visitor, recurse: boolean, parent: Node | undefined): Node {\n const visited = applyVisitor<Node>(node, visitor, parent) ?? node\n return transformChildren(visited, visitor, recurse)\n}\n\n/**\n * Immutably rebuilds a node's children, transforming each child node and leaving non-node values\n * (e.g. `additionalProperties: true`) intact.\n */\nfunction transformChildren(node: Node, visitor: Visitor, recurse: boolean): Node {\n const keys = node.kind === nodeKinds.schema && !recurse ? undefined : VISITOR_KEYS[node.kind]\n if (!keys) return node\n\n const record = node as unknown as Record<string, unknown>\n let updates: Record<string, unknown> | undefined\n // A node under two keys is transformed once, so both keys keep pointing at one node. Leaves never create the map.\n let done: Map<Node, Node> | undefined\n const transformOnce = (child: Node) => {\n done ??= new Map()\n const next = done.get(child) ?? transformNode(child, visitor, recurse, node)\n done.set(child, next)\n return next\n }\n\n for (const key of keys) {\n const value = record[key]\n if (value === undefined || value === null) continue\n if (Array.isArray(value)) {\n // Rebuild the array lazily: allocate a new array only once a child actually changes, copying\n // the unchanged prefix at that point. An unchanged array keeps its original reference and\n // allocates nothing. This also drops the per-array `.map` closure that ran on every node.\n let mapped: Array<unknown> | undefined\n for (const [i, item] of value.entries()) {\n const next = isNode(item) ? transformOnce(item) : item\n if (mapped) {\n mapped.push(next)\n continue\n }\n if (next !== item) mapped = [...value.slice(0, i), next]\n }\n if (mapped) (updates ??= {})[key] = mapped\n continue\n }\n if (isNode(value)) {\n const next = transformOnce(value)\n if (next !== value) (updates ??= {})[key] = next\n continue\n }\n if (isNodeRecord(value)) {\n let mapped: Record<string, unknown> | undefined\n for (const [name, item] of Object.entries(value)) {\n const next = isNode(item) ? transformOnce(item) : item\n if (next !== item) (mapped ??= { ...value })[name] = next\n }\n if (mapped) (updates ??= {})[key] = mapped\n }\n }\n\n if (!updates) return node\n const merged = { ...node, ...updates }\n return merged as Node\n}\n\n/**\n * Depth-first collection pass. Gathers every non-null value the visitor\n * callbacks return into an array.\n *\n * @example Collect every operationId\n * ```ts\n * const ids = collect<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })\n * ```\n */\nexport function collect<T>(node: Node, options: CollectOptions<T>): Array<T> {\n const { depth, parent, ...visitor } = options\n const result: Array<T> = []\n // Plain recursion: draining nested generators costs a `yield*` hop per level for every value.\n collectInto<T>(node, visitor, (depth ?? 'deep') === 'deep', parent, result)\n return result\n}\n\nfunction collectInto<T>(node: Node, visitor: VisitorOf<T>, recurse: boolean, parent: Node | undefined, result: Array<T>): void {\n const v = applyVisitor<T>(node, visitor, parent)\n if (v != null) result.push(v)\n\n if (node.kind === nodeKinds.schema && !recurse) return\n visitChildNodes(node, (child) => {\n collectInto<T>(child, visitor, recurse, node, result)\n return false\n })\n}\n"],"mappings":";;;;;AAIA,SAAgB,gBAAgB,EAAE,WAAsE;CAEtG,IAAI,CAAC,SAAS,UA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CAE1B,YAAe,MAAM,UAAU,SAAS,YAAY,QAAQ,QAAQ,MAAM;CAC1E,OAAO;AACT;AAEA,SAAS,YAAe,MAAY,SAAuB,SAAkB,QAA0B,QAAwB;CAC7H,MAAM,IAAI,aAAgB,MAAM,SAAS,MAAM;CAC/C,IAAI,KAAK,MAAM,OAAO,KAAK,CAAC;CAE5B,IAAI,KAAK,SAASA,kBAAAA,UAAU,UAAU,CAAC,SAAS;CAChD,gBAAgB,OAAO,UAAU;EAC/B,YAAe,OAAO,SAAS,SAAS,MAAM,MAAM;EACpD,OAAO;CACT,CAAC;AACH"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Node } from "./index-
|
|
2
|
-
import {
|
|
1
|
+
import { t as Node } from "./index-DNZgWmNq.cjs";
|
|
2
|
+
import { $ as PropertyNode, D as InputNode, G as SchemaNode, h as ParameterNode, i as OperationNode, l as ResponseNode } from "./operation-De4lbIZS.cjs";
|
|
3
3
|
/**
|
|
4
4
|
* Traversal depth for AST visitor utilities.
|
|
5
5
|
*
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-BTTus9ee.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["import type { SchemaType } from './nodes/schema.ts'\n\n/**\n * Node kind discriminators used by every AST node (for example `node.kind === nodeKinds.text`).\n */\nexport const nodeKinds = {\n input: 'Input',\n operation: 'Operation',\n schema: 'Schema',\n property: 'Property',\n parameter: 'Parameter',\n response: 'Response',\n requestBody: 'RequestBody',\n content: 'Content',\n type: 'Type',\n file: 'File',\n import: 'Import',\n export: 'Export',\n source: 'Source',\n const: 'Const',\n function: 'Function',\n arrowFunction: 'ArrowFunction',\n text: 'Text',\n break: 'Break',\n jsx: 'Jsx',\n} as const\n\n/**\n * Schema type discriminators used by all AST schema nodes.\n *\n * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).\n */\nexport const schemaTypes = {\n /**\n * Text value.\n */\n string: 'string',\n /**\n * Floating-point number (`float`, `double`).\n */\n number: 'number',\n /**\n * Whole number (`int32`). Use `bigint` for `int64`.\n */\n integer: 'integer',\n /**\n * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.\n */\n bigint: 'bigint',\n /**\n * Boolean value.\n */\n boolean: 'boolean',\n /**\n * Explicit null value.\n */\n null: 'null',\n /**\n * Any value (no type restriction).\n */\n any: 'any',\n /**\n * Unknown value (must be narrowed before usage).\n */\n unknown: 'unknown',\n /**\n * No return value (`void`).\n */\n void: 'void',\n /**\n * Object with named properties.\n */\n object: 'object',\n /**\n * Sequential list of items.\n */\n array: 'array',\n /**\n * Fixed-length list with position-specific items.\n */\n tuple: 'tuple',\n /**\n * \"One of\" multiple schema members.\n */\n union: 'union',\n /**\n * \"All of\" multiple schema members.\n */\n intersection: 'intersection',\n /** \"Not\" a single schema member. */\n not: 'not',\n /**\n * Enum schema.\n */\n enum: 'enum',\n /**\n * Reference to another schema.\n */\n ref: 'ref',\n /**\n * Calendar date (for example `2026-03-24`).\n */\n date: 'date',\n /**\n * Date-time value (for example `2026-03-24T09:00:00Z`).\n */\n datetime: 'datetime',\n /**\n * Time-only value (for example `09:00:00`).\n */\n time: 'time',\n /**\n * UUID value.\n */\n uuid: 'uuid',\n /**\n * Email address value.\n */\n email: 'email',\n /**\n * URL value.\n */\n url: 'url',\n /**\n * IPv4 address value.\n */\n ipv4: 'ipv4',\n /**\n * IPv6 address value.\n */\n ipv6: 'ipv6',\n /**\n * Binary/blob value.\n */\n blob: 'blob',\n /**\n * Impossible value (`never`).\n */\n never: 'never',\n} as const satisfies Record<SchemaType, SchemaType>\n"],"mappings":";;;;AAKA,MAAa,YAAY;CACvB,OAAO;CACP,WAAW;CACX,QAAQ;CACR,UAAU;CACV,WAAW;CACX,UAAU;CACV,aAAa;CACb,SAAS;CACT,MAAM;CACN,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,UAAU;CACV,eAAe;CACf,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;AAOA,MAAa,cAAc;;;;CAIzB,QAAQ;;;;CAIR,QAAQ;;;;CAIR,SAAS;;;;CAIT,QAAQ;;;;CAIR,SAAS;;;;CAIT,MAAM;;;;CAIN,KAAK;;;;CAIL,SAAS;;;;CAIT,MAAM;;;;CAIN,QAAQ;;;;CAIR,OAAO;;;;CAIP,OAAO;;;;CAIP,OAAO;;;;CAIP,cAAc;;CAEd,KAAK;;;;CAIL,MAAM;;;;CAIN,KAAK;;;;CAIL,MAAM;;;;CAIN,UAAU;;;;CAIV,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;;;;CAIP,KAAK;;;;CAIL,MAAM;;;;CAIN,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants-DztHlVmY.cjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["import type { SchemaType } from './nodes/schema.ts'\n\n/**\n * Node kind discriminators used by every AST node (for example `node.kind === nodeKinds.text`).\n */\nexport const nodeKinds = {\n input: 'Input',\n operation: 'Operation',\n schema: 'Schema',\n property: 'Property',\n parameter: 'Parameter',\n response: 'Response',\n requestBody: 'RequestBody',\n content: 'Content',\n type: 'Type',\n file: 'File',\n import: 'Import',\n export: 'Export',\n source: 'Source',\n const: 'Const',\n function: 'Function',\n arrowFunction: 'ArrowFunction',\n text: 'Text',\n break: 'Break',\n jsx: 'Jsx',\n} as const\n\n/**\n * Schema type discriminators used by all AST schema nodes.\n *\n * Each value is a stable discriminator across the AST (for example `schema.type === schemaTypes.object`).\n */\nexport const schemaTypes = {\n /**\n * Text value.\n */\n string: 'string',\n /**\n * Floating-point number (`float`, `double`).\n */\n number: 'number',\n /**\n * Whole number (`int32`). Use `bigint` for `int64`.\n */\n integer: 'integer',\n /**\n * 64-bit integer (`int64`). Only used when `integerType` is set to `'bigint'`.\n */\n bigint: 'bigint',\n /**\n * Boolean value.\n */\n boolean: 'boolean',\n /**\n * Explicit null value.\n */\n null: 'null',\n /**\n * Any value (no type restriction).\n */\n any: 'any',\n /**\n * Unknown value (must be narrowed before usage).\n */\n unknown: 'unknown',\n /**\n * No return value (`void`).\n */\n void: 'void',\n /**\n * Object with named properties.\n */\n object: 'object',\n /**\n * Sequential list of items.\n */\n array: 'array',\n /**\n * Fixed-length list with position-specific items.\n */\n tuple: 'tuple',\n /**\n * \"One of\" multiple schema members.\n */\n union: 'union',\n /**\n * \"All of\" multiple schema members.\n */\n intersection: 'intersection',\n /** \"Not\" a single schema member. */\n not: 'not',\n /**\n * Enum schema.\n */\n enum: 'enum',\n /**\n * Reference to another schema.\n */\n ref: 'ref',\n /**\n * Calendar date (for example `2026-03-24`).\n */\n date: 'date',\n /**\n * Date-time value (for example `2026-03-24T09:00:00Z`).\n */\n datetime: 'datetime',\n /**\n * Time-only value (for example `09:00:00`).\n */\n time: 'time',\n /**\n * UUID value.\n */\n uuid: 'uuid',\n /**\n * Email address value.\n */\n email: 'email',\n /**\n * URL value.\n */\n url: 'url',\n /**\n * IPv4 address value.\n */\n ipv4: 'ipv4',\n /**\n * IPv6 address value.\n */\n ipv6: 'ipv6',\n /**\n * Binary/blob value.\n */\n blob: 'blob',\n /**\n * Impossible value (`never`).\n */\n never: 'never',\n} as const satisfies Record<SchemaType, SchemaType>\n"],"mappings":";;;;AAKA,MAAa,YAAY;CACvB,OAAO;CACP,WAAW;CACX,QAAQ;CACR,UAAU;CACV,WAAW;CACX,UAAU;CACV,aAAa;CACb,SAAS;CACT,MAAM;CACN,MAAM;CACN,QAAQ;CACR,QAAQ;CACR,QAAQ;CACR,OAAO;CACP,UAAU;CACV,eAAe;CACf,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;AAOA,MAAa,cAAc;;;;CAIzB,QAAQ;;;;CAIR,QAAQ;;;;CAIR,SAAS;;;;CAIT,QAAQ;;;;CAIR,SAAS;;;;CAIT,MAAM;;;;CAIN,KAAK;;;;CAIL,SAAS;;;;CAIT,MAAM;;;;CAIN,QAAQ;;;;CAIR,OAAO;;;;CAIP,OAAO;;;;CAIP,OAAO;;;;CAIP,cAAc;;CAEd,KAAK;;;;CAIL,MAAM;;;;CAIN,KAAK;;;;CAIL,MAAM;;;;CAIN,UAAU;;;;CAIV,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;;;;CAIP,KAAK;;;;CAIL,MAAM;;;;CAIN,MAAM;;;;CAIN,MAAM;;;;CAIN,OAAO;AACT"}
|
package/dist/index-CW-ztJjd.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nodes-ClL1C158.js","names":[],"sources":["../src/nodes/code.ts","../src/nodes/content.ts","../src/nodes/input.ts","../src/nodes/requestBody.ts","../src/nodes/operation.ts","../src/nodes/parameter.ts","../src/nodes/property.ts","../src/nodes/response.ts","../src/nodes/index.ts"],"sourcesContent":["import { nodeKinds } from '../constants.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\n\n/**\n * JSDoc documentation metadata attached to code declarations.\n */\nexport type JSDocNode = {\n /**\n * JSDoc comment lines. `undefined` entries are filtered out during rendering.\n *\n * @example\n * ```ts\n * ['@description A pet resource', '@deprecated']\n * ```\n */\n comments?: Array<string | undefined>\n}\n\n/**\n * AST node representing a TypeScript `const` declaration.\n *\n * Mirrors the props of the `Const` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createConst({ name: 'pet', export: true, asConst: true })\n * // export const pet = ... as const\n * ```\n */\nexport type ConstNode = BaseNode & {\n kind: 'Const'\n /**\n * Name of the constant declaration.\n */\n name: string\n /**\n * Whether the declaration should be exported.\n */\n export?: boolean | null\n /**\n * Explicit type annotation.\n *\n * @example Type reference\n * `'Pet'`\n */\n type?: string | null\n /**\n * JSDoc documentation metadata.\n */\n JSDoc?: JSDocNode | null\n /**\n * Whether to append `as const` to the declaration.\n */\n asConst?: boolean | null\n /**\n * Child nodes representing the value of the constant (children of the `Const` component).\n * Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * AST node representing a TypeScript `type` alias declaration.\n *\n * Mirrors the props of the `Type` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createType({ name: 'Pet', export: true })\n * // export type Pet = ...\n * ```\n */\nexport type TypeNode = BaseNode & {\n kind: 'Type'\n /**\n * Name of the type alias.\n */\n name: string\n /**\n * Whether the declaration should be exported.\n */\n export?: boolean | null\n /**\n * How the declaration is written.\n * - `'type'` declares `type Name = …`\n * - `'interface'` declares `interface Name { … }`, so the body must be an object type\n *\n * @default 'type'\n */\n syntax?: 'type' | 'interface' | null\n /**\n * JSDoc documentation metadata.\n */\n JSDoc?: JSDocNode | null\n /**\n * Child nodes representing the type body (children of the `Type` component).\n * Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * AST node representing a TypeScript `function` declaration.\n *\n * Mirrors the props of the `Function` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createFunction({ name: 'getPet', export: true, async: true, returnType: 'Pet' })\n * // export async function getPet(): Promise<Pet> { ... }\n * ```\n */\nexport type FunctionNode = BaseNode & {\n kind: 'Function'\n /**\n * Name of the function.\n */\n name: string\n /**\n * Whether the function is a default export.\n */\n default?: boolean | null\n /**\n * Function parameter list as a pre-rendered string, written verbatim between the parentheses.\n *\n * @example\n * `'id: string, config: Config = {}'`\n */\n params?: string | null\n /**\n * Whether the function should be exported.\n */\n export?: boolean | null\n /**\n * Whether the function is async. When `true`, the return type is wrapped in `Promise<>`.\n */\n async?: boolean | null\n /**\n * TypeScript generic type parameters.\n *\n * @example Constrained generics\n * `['T', 'U extends string']`\n */\n generics?: string | Array<string> | null\n /**\n * Return type annotation.\n *\n * @example Type reference\n * `'Pet'`\n */\n returnType?: string | null\n /**\n * JSDoc documentation metadata.\n */\n JSDoc?: JSDocNode | null\n /**\n * Child nodes representing the function body (children of the `Function` component).\n * Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * AST node representing a TypeScript arrow function (`const name = () => { ... }`).\n *\n * Mirrors the props of the `Function.Arrow` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createArrowFunction({ name: 'getPet', export: true, singleLine: true })\n * // export const getPet = () => ...\n * ```\n */\nexport type ArrowFunctionNode = Omit<FunctionNode, 'kind'> & {\n kind: 'ArrowFunction'\n /**\n * Render the arrow function body as a single-line expression.\n */\n singleLine?: boolean | null\n}\n\n/**\n * AST node representing a raw text/string fragment in the source output.\n *\n * Used instead of bare `string` values so that all entries in `nodes` arrays\n * are typed `CodeNode` objects rather than a mixed `CodeNode | string` union.\n *\n * @example\n * ```ts\n * createText('return fetch(id)')\n * // { kind: 'Text', value: 'return fetch(id)' }\n * ```\n */\nexport type TextNode = BaseNode & {\n kind: 'Text'\n /**\n * The raw string content.\n */\n value: string\n}\n\n/**\n * AST node representing a blank line in the source output.\n *\n * Corresponds to `<br/>` in JSX components. `printNodes` turns a `Break` between two\n * statements into one blank line. Consecutive breaks, and breaks at the start or end of\n * the list, are folded away, so a `Break` never produces more than one blank line.\n *\n * @example\n * ```ts\n * createBreak()\n * // { kind: 'Break' }\n * ```\n */\nexport type BreakNode = BaseNode & {\n kind: 'Break'\n}\n\n/**\n * AST node representing a raw JSX fragment in the source output.\n *\n * Mirrors the `Jsx` component from `@kubb/renderer-jsx`. Embeds raw JSX/TSX markup\n * (including fragments `<>…</>`) directly in generated code.\n *\n * @example\n * ```ts\n * createJsx('<>\\n <a href={href}>Open</a>\\n</>')\n * // { kind: 'Jsx', value: '<>\\n <a href={href}>Open</a>\\n</>' }\n * ```\n */\nexport type JsxNode = BaseNode & {\n kind: 'Jsx'\n /**\n * The raw JSX string content.\n */\n value: string\n}\n\n/**\n * Union of all code-generation AST nodes.\n *\n * These nodes mirror the JSX components from `@kubb/renderer-jsx` and are used as\n * structured children in {@link SourceNode.nodes}.\n */\nexport type CodeNode = ConstNode | TypeNode | FunctionNode | ArrowFunctionNode | TextNode | BreakNode | JsxNode\n\n/**\n * Creates a `ConstNode` representing a TypeScript `const` declaration.\n *\n * @example Exported constant with type and `as const`\n * ```ts\n * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })\n * // export const pets: Pet[] = ... as const\n * ```\n */\nexport const createConst = nodeFactory<ConstNode>(nodeKinds.const)\n\n/**\n * Creates a `TypeNode` representing a TypeScript `type` alias declaration.\n *\n * @example\n * ```ts\n * createType({ name: 'Pet', export: true })\n * // export type Pet = ...\n * ```\n */\nexport const createType = nodeFactory<TypeNode>(nodeKinds.type)\n\n/**\n * Creates a `FunctionNode` representing a TypeScript `function` declaration.\n *\n * @example\n * ```ts\n * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })\n * // export async function fetchPet(): Promise<Pet> { ... }\n * ```\n */\nexport const createFunction = nodeFactory<FunctionNode>(nodeKinds.function)\n\n/**\n * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.\n *\n * @example\n * ```ts\n * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })\n * // export const double = (n: number) => ...\n * ```\n */\nexport const createArrowFunction = nodeFactory<ArrowFunctionNode>(nodeKinds.arrowFunction)\n\n/**\n * Creates a {@link TextNode} representing a raw string fragment in the source output.\n *\n * @example\n * ```ts\n * createText('return fetch(id)')\n * // { kind: 'Text', value: 'return fetch(id)' }\n * ```\n */\nexport function createText(value: string): TextNode {\n return { kind: nodeKinds.text, value }\n}\n\n/**\n * Creates a {@link BreakNode} representing a line break in the source output.\n *\n * @example\n * ```ts\n * createBreak()\n * // { kind: 'Break' }\n * ```\n */\nexport function createBreak(): BreakNode {\n return { kind: nodeKinds.break }\n}\n\n/**\n * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.\n *\n * @example\n * ```ts\n * createJsx('<>\\n <a href={href}>Open</a>\\n</>')\n * // { kind: 'Jsx', value: '<>\\n <a href={href}>Open</a>\\n</>' }\n * ```\n */\nexport function createJsx(value: string): JsxNode {\n return { kind: nodeKinds.jsx, value }\n}\n","import { nodeKinds } from '../constants.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\nimport type { ParameterStyle } from './parameter.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * How one body property is serialized, from the `encoding` entry of its media type.\n */\nexport type EncodingNode = {\n /**\n * Content type of the part, for example `'application/json'` for a multipart property.\n */\n contentType?: string\n /**\n * Serialization style of the property.\n */\n style?: ParameterStyle\n /**\n * Whether array and object values expand into separate values.\n */\n explode?: boolean\n /**\n * Whether reserved characters are sent as-is instead of percent-encoded.\n */\n allowReserved?: boolean\n encoding?: Record<string, EncodingNode>\n prefixEncoding?: Array<EncodingNode>\n itemEncoding?: EncodingNode\n}\n\nexport type ExampleNode = {\n name?: string\n summary?: string\n description?: string\n value?: unknown\n serializedValue?: string\n}\n\n/**\n * AST node representing one content-type entry of a request body or response.\n *\n * There is one entry per content type declared in the spec (e.g. `application/json`,\n * `multipart/form-data`), and each entry holds its own body schema.\n *\n * @example\n * ```ts\n * const content: ContentNode = {\n * kind: 'Content',\n * contentType: 'application/json',\n * schema: createSchema({ type: 'string' }),\n * }\n * ```\n */\nexport type ContentNode = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Content'\n /**\n * The content type for this entry (e.g. `'application/json'`), or `''` for a response without a body.\n */\n contentType: string\n /**\n * Body schema for this content type. For a stream it is the same node as `stream.schema`.\n */\n schema?: SchemaNode\n /**\n * Set when the content is a stream of items (an event stream, JSON Lines, a channel of messages) instead of one body.\n */\n stream?: {\n /**\n * Schema of one item, such as one event of `text/event-stream` or one line of JSON Lines.\n */\n schema?: SchemaNode\n /**\n * What `schema` describes for an event stream.\n * - `'event'` the parsed event with its `event`, `data`, `id` and `retry` fields\n * - `'data'` only the `data` payload, which the client wraps in its own event type\n */\n shape?: 'event' | 'data'\n }\n /**\n * Property keys to exclude from the generated type via `Omit<Type, Keys>`.\n * Set when a referenced schema has `readOnly`/`writeOnly` fields that should be omitted.\n */\n keysToOmit?: Array<string> | null\n /**\n * Serialization settings per body property that sets at least one field in the spec's `encoding`.\n */\n encoding?: Record<string, EncodingNode>\n examples?: Array<ExampleNode>\n /**\n * Serialization of the first parts by position, for a body sent as an array of parts such as `multipart/mixed`.\n */\n prefixEncoding?: Array<EncodingNode>\n /**\n * Serialization of every part after `prefixEncoding`, for a body sent as an array of parts such as `multipart/mixed`.\n */\n itemEncoding?: EncodingNode\n /** Vendor extensions (`x-*` keys) from the source media type, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Creates a `ContentNode` for a single request-body or response content type.\n */\nexport const createContent = nodeFactory<ContentNode>(nodeKinds.content)\n","import { nodeKinds } from '../constants.ts'\nimport type { BaseNode } from './base.ts'\nimport type { OperationNode } from './operation.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * A variable declared by a server URL template.\n */\nexport type InputServerVariable = {\n default?: string\n enum?: Array<string>\n description?: string\n}\n\n/**\n * A server from the source document, with `{variable}` placeholders filled from their defaults.\n */\nexport type InputServer = {\n url: string\n name?: string\n description?: string\n /**\n * Variables of the source URL template, copied as-is. `url` already has their defaults filled in, so\n * this tells a templated server apart from a literal one. Absent when the server declares none.\n */\n variables?: Record<string, InputServerVariable>\n}\n\nexport type ExternalDocs = { url: string; description?: string }\n\nexport type InputTag = {\n name: string\n summary?: string\n description?: string\n /**\n * Name of the tag this tag nests under. `group: { type: 'tag' }` places its files in the parent's folder.\n */\n parent?: string\n kind?: string\n externalDocs?: ExternalDocs\n}\n\nexport type OAuthFlow = {\n authorizationUrl?: string\n deviceAuthorizationUrl?: string\n tokenUrl?: string\n refreshUrl?: string\n scopes?: Record<string, string>\n}\n\n/**\n * How a client sends a credential, in the same shape as the `Auth` object the generated clients pass to `auth`.\n */\nexport type AuthCredential =\n | { type: 'http'; scheme: 'bearer' | 'basic' | (string & {}); bearerFormat?: string }\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n | { type: 'oauth2'; flows: Record<string, OAuthFlow>; metadataUrl?: string }\n | { type: 'openIdConnect'; url?: string }\n | { type: 'mutualTLS' }\n\n/**\n * One way to authenticate, keyed by `name`, which operations refer to in `auth`.\n */\nexport type AuthScheme = {\n name: string\n description?: string\n deprecated?: boolean\n credential: AuthCredential\n}\n\n/**\n * One way to meet an operation's auth. Every scheme in it applies together. `scopes` are the OAuth2 or OpenID\n * Connect scopes the call needs. An empty list means the call may be sent without credentials.\n */\nexport type AuthRequirement = Array<{ scheme: string; scopes?: Array<string> }>\n\n/**\n * Metadata for an API document, populated by the adapter and available to every generator.\n * Every field is a plain JSON value.\n *\n * @example\n * ```ts\n * const meta: InputMeta = { title: 'Pet Store', version: '1.0.0', baseURL: 'https://api.example.com/v2' }\n * ```\n */\nexport type InputMeta = {\n /**\n * API title from `info.title` in the source document.\n */\n title?: string\n /**\n * API description from `info.description` in the source document.\n */\n description?: string\n /**\n * API version string from `info.version` in the source document.\n */\n version?: string\n summary?: string\n termsOfService?: string\n contact?: { name?: string; url?: string; email?: string }\n license?: { name: string; identifier?: string; url?: string }\n externalDocs?: ExternalDocs\n /**\n * Resolved base URL from the first matching server entry in the source document.\n */\n baseURL?: string | null\n servers?: Array<InputServer>\n tags?: Array<InputTag>\n auth?: Array<AuthScheme>\n /**\n * Vendor extensions (`x-*` keys) from the document root, copied as-is. Absent when the root has none.\n */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Input AST node that contains all schemas and operations for one API document.\n * Produced by the adapter and consumed by all Kubb plugins.\n *\n * @example\n * ```ts\n * const input: InputNode = {\n * kind: 'Input',\n * schemas: [],\n * operations: [],\n * meta: {},\n * }\n * ```\n */\nexport type InputNode = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Input'\n /**\n * All schema nodes in the document.\n */\n schemas: Array<SchemaNode>\n /**\n * All operation nodes in the document.\n */\n operations: Array<OperationNode>\n /**\n * Document metadata populated by the adapter.\n */\n meta: InputMeta\n}\n\n/**\n * Creates an `InputNode`, defaulting `schemas`/`operations` to empty arrays and `meta` to an empty\n * object. Every call allocates fresh defaults so no two inputs share them.\n *\n * @example\n * ```ts\n * const input = createInput()\n * // { kind: 'Input', schemas: [], operations: [] }\n * ```\n */\nexport function createInput(overrides: Partial<Omit<InputNode, 'kind'>> = {}): InputNode {\n return { schemas: [], operations: [], meta: {}, ...overrides, kind: nodeKinds.input }\n}\n","import { nodeKinds } from '../constants.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\nimport type { ContentNode } from './content.ts'\n\n/**\n * AST node representing an operation request body.\n *\n * Body schemas live exclusively inside the `content` array (one entry per content type),\n * mirroring {@link ResponseNode}.\n *\n * @example\n * ```ts\n * const requestBody: RequestBodyNode = {\n * kind: 'RequestBody',\n * required: true,\n * content: [{ kind: 'Content', contentType: 'application/json', schema: createSchema({ type: 'string' }) }],\n * }\n * ```\n */\nexport type RequestBodyNode = BaseNode & {\n kind: 'RequestBody'\n /**\n * Request body description carried over from the spec.\n */\n description?: string\n /**\n * Whether the request body is required (`requestBody.required: true` in the spec).\n * When `false` or absent, the generated `data` parameter should be optional.\n */\n required?: boolean\n /**\n * Content type entries for this request body.\n *\n * When the adapter `contentType` option is set, this array contains exactly one entry for\n * that content type. Otherwise it contains one entry per content type declared in the spec,\n * so plugins can generate code for every variant (for example, separate hooks for\n * `application/json` and `multipart/form-data`).\n */\n content?: Array<ContentNode>\n /** Vendor extensions (`x-*` keys) from the source request body, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Creates a `RequestBodyNode`.\n */\nexport const createRequestBody = nodeFactory<RequestBodyNode>(nodeKinds.requestBody)\n","import { nodeKinds } from '../constants.ts'\nimport type { BaseNode } from './base.ts'\nimport type { AuthRequirement, ExternalDocs, InputServer } from './input.ts'\nimport type { ParameterNode } from './parameter.ts'\nimport { createRequestBody, type RequestBodyNode } from './requestBody.ts'\nimport type { ResponseNode } from './response.ts'\n\n/**\n * HTTP method an operation responds to. `QUERY` is the safe, idempotent method with a request body\n * from RFC 10008, declared with the `query` field of an OpenAPI 3.2 path item. Any other name is a\n * method the source declares outside this fixed set, in the capitalization it is sent with.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'QUERY' | (string & {})\n\n/**\n * Fields shared by every operation, regardless of transport.\n */\ntype OperationNodeBase = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Operation'\n /**\n * Stable identifier for the operation.\n */\n operationId: string\n /**\n * Group labels for the operation.\n */\n tags: Array<string>\n /**\n * Short one-line operation summary.\n */\n summary?: string\n /**\n * Full operation description.\n */\n description?: string\n /**\n * Marks the operation as deprecated.\n */\n deprecated?: boolean\n externalDocs?: ExternalDocs\n /**\n * Query, path, header, and cookie parameters for the operation.\n */\n parameters: Array<ParameterNode>\n /**\n * Request body for the operation.\n */\n requestBody?: RequestBodyNode\n /**\n * Operation responses.\n */\n responses: Array<ResponseNode>\n /**\n * Vendor extensions (`x-*` keys) from the source operation, copied as-is. Absent when the source has none.\n */\n extensions?: Record<string, unknown>\n /** The operation's own `servers`, else its path item's, such as an upload host. Absent when neither declares any. */\n servers?: Array<InputServer>\n /**\n * Ways to authenticate, from the operation or else the document. Any one entry is enough. `[]` means no auth.\n */\n auth?: Array<AuthRequirement>\n}\n\n/**\n * Operation served over HTTP. `method` and `path` are guaranteed.\n *\n * @example\n * ```ts\n * const operation: HttpOperationNode = {\n * kind: 'Operation',\n * operationId: 'listPets',\n * protocol: 'http',\n * method: 'GET',\n * path: '/pets',\n * tags: [],\n * parameters: [],\n * responses: [],\n * }\n * ```\n */\nexport type HttpOperationNode = OperationNodeBase & {\n /**\n * Transport the operation belongs to.\n */\n protocol?: 'http'\n /**\n * HTTP method like `'GET'`.\n */\n method: HttpMethod\n /**\n * Path string, for example `/pets/{petId}`, with `{param}` notation preserved.\n */\n path: string\n}\n\n/**\n * Operation for a non-HTTP transport. HTTP-only fields are forbidden.\n */\nexport type GenericOperationNode = OperationNodeBase & {\n protocol?: never\n method?: never\n path?: never\n}\n\n/**\n * AST node representing one API operation.\n *\n * Discriminated on `protocol`: an {@link HttpOperationNode} (`protocol: 'http'`) guarantees\n * `method` and `path`, while a {@link GenericOperationNode} omits them. Narrow with\n * `ast.http.isOperation(node)` or `node.protocol === 'http'` before reading `method`/`path`.\n */\nexport type OperationNode = HttpOperationNode | GenericOperationNode\n\ntype OperationInput = {\n operationId: string\n method?: HttpOperationNode['method']\n path?: HttpOperationNode['path']\n requestBody?: Omit<RequestBodyNode, 'kind'>\n [key: string]: unknown\n}\n\n/**\n * Creates an `OperationNode` with default empty arrays for `tags`, `parameters`, and `responses`.\n * HTTP operations (those carrying both `method` and `path`) are tagged with `protocol: 'http'`,\n * and the request body is normalized into a `RequestBodyNode`.\n *\n * @example\n * ```ts\n * const operation = createOperation({ operationId: 'getPetById', method: 'GET', path: '/pet/{petId}' })\n * // tags, parameters, and responses are []\n * ```\n */\nexport function createOperation(\n props: Pick<HttpOperationNode, 'operationId' | 'method' | 'path'> &\n Partial<Omit<HttpOperationNode, 'kind' | 'operationId' | 'method' | 'path' | 'requestBody'>> & {\n requestBody?: Omit<RequestBodyNode, 'kind'>\n },\n): HttpOperationNode\nexport function createOperation(\n props: Pick<GenericOperationNode, 'operationId'> &\n Partial<Omit<GenericOperationNode, 'kind' | 'operationId' | 'requestBody'>> & {\n requestBody?: Omit<RequestBodyNode, 'kind'>\n },\n): GenericOperationNode\nexport function createOperation(props: OperationInput): OperationNode {\n const { requestBody, ...rest } = props\n const isHttp = rest.method !== undefined && rest.path !== undefined\n\n const node = {\n tags: [],\n parameters: [],\n responses: [],\n ...rest,\n kind: nodeKinds.operation,\n ...(isHttp ? { protocol: 'http' as const } : {}),\n requestBody: requestBody ? createRequestBody(requestBody) : undefined,\n }\n\n return node as OperationNode\n}\n","import { nodeKinds } from '../constants.ts'\nimport { applyOptionality } from '../optionality.ts'\nimport type { BaseNode } from './base.ts'\nimport type { EncodingNode, ExampleNode } from './content.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * Where a parameter is sent. `querystring` carries the whole query string as one value, serialized per `contentType`.\n */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'querystring'\n\n/**\n * Parameter serialization style, controlling how a parameter value is rendered into the request.\n */\nexport type ParameterStyle = 'matrix' | 'label' | 'form' | 'simple' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject' | 'cookie'\n\n/**\n * AST node representing one operation parameter.\n *\n * @example\n * ```ts\n * const param: ParameterNode = {\n * kind: 'Parameter',\n * name: 'petId',\n * in: 'path',\n * schema: createSchema({ type: 'string' }),\n * required: true,\n * }\n * ```\n */\nexport type ParameterNode = BaseNode & {\n kind: 'Parameter'\n /**\n * Parameter name.\n */\n name: string\n /**\n * Parameter location (`path`, `query`, `header`, `cookie`, or `querystring`).\n */\n in: ParameterLocation\n /**\n * Parameter schema.\n */\n schema: SchemaNode\n /**\n * Whether the parameter is required.\n */\n required: boolean\n /**\n * Serialization style. Absent when the source omits it, leaving consumers to apply the\n * per-location default.\n */\n style?: ParameterStyle\n /**\n * Whether array and object values expand into separate values. Absent when the source omits it,\n * leaving consumers to apply the default for the style.\n */\n explode?: boolean\n /**\n * Whether reserved characters (RFC 3986 `:/?#[]@!$&'()*+,;=`) are sent as-is instead of\n * percent-encoded. Absent when the source omits it.\n */\n allowReserved?: boolean\n /**\n * Media type of a parameter described with `content` instead of `schema`, for example\n * `application/json` when the value is sent as a JSON-encoded string. Absent for `schema` parameters.\n */\n contentType?: string\n /**\n * Serialization settings per property of a `content` parameter, from the `encoding` of its media type. An OpenAPI 3.2\n * `querystring` parameter sent as `application/x-www-form-urlencoded` uses it to set `style` and `explode` per field.\n */\n encoding?: Record<string, EncodingNode>\n examples?: Array<ExampleNode>\n deprecated?: boolean\n allowEmptyValue?: boolean\n /** Vendor extensions (`x-*` keys) from the source parameter, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\ntype UserParameterNode = Pick<ParameterNode, 'name' | 'in' | 'schema'> & Partial<Omit<ParameterNode, 'kind' | 'name' | 'in' | 'schema'>>\n\n/**\n * Creates a `ParameterNode`. `required` defaults to `false`, and the schema's\n * `optional`/`nullish` flags are derived from it.\n *\n * @example\n * ```ts\n * const param = createParameter({\n * name: 'petId',\n * in: 'path',\n * required: true,\n * schema: createSchema({ type: 'string' }),\n * })\n * ```\n */\nexport function createParameter(input: UserParameterNode): ParameterNode {\n const required = input.required ?? false\n\n return { ...input, required, schema: applyOptionality(input.schema, required), kind: nodeKinds.parameter }\n}\n","import { nodeKinds } from '../constants.ts'\nimport { applyOptionality } from '../optionality.ts'\nimport type { BaseNode } from './base.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * AST node representing one named object property.\n *\n * @example\n * ```ts\n * const property: PropertyNode = {\n * kind: 'Property',\n * name: 'id',\n * schema: createSchema({ type: 'integer' }),\n * required: true,\n * }\n * ```\n */\nexport type PropertyNode = BaseNode & {\n kind: 'Property'\n /**\n * Property key.\n */\n name: string\n /**\n * Property schema.\n */\n schema: SchemaNode\n /**\n * Whether the property is required.\n */\n required: boolean\n}\n\n/**\n * Loosely-typed property accepted by `createProperty`, with `required` optional.\n */\ntype UserPropertyNode = Pick<PropertyNode, 'name' | 'schema'> & Partial<Omit<PropertyNode, 'kind' | 'name' | 'schema'>>\n\n/**\n * Creates a `PropertyNode`. `required` defaults to `false`, and the schema's\n * `optional`/`nullish` flags are derived from it.\n *\n * @example\n * ```ts\n * const property = createProperty({\n * name: 'status',\n * required: true,\n * schema: createSchema({ type: 'string', nullable: true }),\n * })\n * // required=true, no optional/nullish\n * ```\n */\nexport function createProperty(input: UserPropertyNode): PropertyNode {\n const required = input.required ?? false\n\n return { ...input, required, schema: applyOptionality(input.schema, required), kind: nodeKinds.property }\n}\n","import { nodeKinds } from '../constants.ts'\nimport type { BaseNode } from './base.ts'\nimport { type ContentNode, createContent } from './content.ts'\nimport type { InputServer } from './input.ts'\nimport type { ParameterNode } from './parameter.ts'\nimport type { SchemaNode } from './schema.ts'\n\ntype Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n\n/**\n * Response status code literal used by operations.\n *\n * Includes three-digit HTTP status code strings, ranges such as `\"2xx\"`, and `\"default\"` for catch-all responses.\n *\n * @example\n * ```ts\n * const status: StatusCode = '200'\n * const fallback: StatusCode = 'default'\n * ```\n */\nexport type StatusCode = `${1 | 2 | 3 | 4 | 5}${Digit}${Digit}` | `${1 | 2 | 3 | 4 | 5}xx` | 'default'\n\n/**\n * AST node representing one operation response variant.\n *\n * Mirrors {@link OperationNode.requestBody}: the response body schemas live exclusively inside\n * the `content` array (one entry per content type), so the same schema is never duplicated at the\n * node root and inside `content`.\n *\n * @example\n * ```ts\n * const response: ResponseNode = {\n * kind: 'Response',\n * statusCode: '200',\n * content: [{ kind: 'Content', contentType: 'application/json', schema: createSchema({ type: 'string' }) }],\n * }\n * ```\n */\nexport type ResponseNode = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Response'\n /**\n * HTTP status code or `'default'` for a fallback response.\n */\n statusCode: StatusCode\n summary?: string\n /**\n * Optional response description.\n */\n description?: string\n /**\n * All available content type entries for this response.\n *\n * For a response that declares content, the array holds exactly one entry for the adapter\n * `contentType` option when it is set. Otherwise it holds one entry per content type declared in\n * the spec, so that plugins can generate a union of response types (e.g. `application/json` and\n * `application/xml`). A body-less response always keeps a single entry whose `contentType` is `''`\n * and whose `schema` is the empty/`void` placeholder, even when the option is set.\n *\n * @example\n * ```ts\n * // spec response declares both application/json and application/xml\n * response.content[0].contentType // 'application/json'\n * response.content[1].contentType // 'application/xml'\n * ```\n */\n content?: Array<ContentNode>\n /**\n * Response headers, as `in: 'header'` parameters. `Content-Type` is left out.\n */\n headers?: Array<ParameterNode>\n links?: Record<string, ResponseLink>\n /** Vendor extensions (`x-*` keys) from the source response, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\n/**\n * A link to another operation. `parameters` and `requestBody` hold runtime expressions such as `$response.body#/id`.\n */\nexport type ResponseLink = {\n operationId?: string\n operationRef?: string\n parameters?: Record<string, unknown>\n requestBody?: unknown\n description?: string\n server?: InputServer\n}\n\ntype ResponseInput = Pick<ResponseNode, 'statusCode'> &\n Partial<Omit<ResponseNode, 'kind' | 'statusCode' | 'content'>> & {\n content?: Array<ContentNode>\n schema?: SchemaNode\n mediaType?: string | null\n keysToOmit?: Array<string> | null\n }\n\n/**\n * Creates a `ResponseNode`. A single legacy `schema` (with optional `mediaType`/`keysToOmit`)\n * is normalized into one `content` entry.\n *\n * @example\n * ```ts\n * const response = createResponse({\n * statusCode: '200',\n * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],\n * })\n * ```\n */\nexport function createResponse(props: ResponseInput): ResponseNode {\n const { schema, mediaType, keysToOmit, content, ...rest } = props\n const entries = content ?? (schema ? [createContent({ contentType: mediaType ?? 'application/json', schema, keysToOmit: keysToOmit ?? null })] : undefined)\n\n return { ...rest, content: entries, kind: nodeKinds.response }\n}\n","import type { ArrowFunctionNode, BreakNode, ConstNode, FunctionNode, JsxNode, TextNode, TypeNode } from './code.ts'\nimport type { ContentNode } from './content.ts'\nimport type { ExportNode, FileNode, ImportNode, SourceNode } from './file.ts'\nimport type { InputNode } from './input.ts'\nimport type { OperationNode } from './operation.ts'\nimport type { ParameterNode } from './parameter.ts'\nimport type { PropertyNode } from './property.ts'\nimport type { RequestBodyNode } from './requestBody.ts'\nimport type { ResponseNode } from './response.ts'\nimport type { SchemaNode } from './schema.ts'\n\nexport { createArrowFunction, createBreak, createConst, createFunction, createJsx, createText, createType } from './code.ts'\nexport { createContent } from './content.ts'\nexport { createExport, createFile, createImport, createSource } from './file.ts'\nexport type { ExportInput, ImportInput, ModuleName, Space, UserFileNode } from './file.ts'\nexport { createInput } from './input.ts'\nexport { createOperation } from './operation.ts'\nexport { createParameter } from './parameter.ts'\nexport { createProperty } from './property.ts'\nexport { createRequestBody } from './requestBody.ts'\nexport { createResponse } from './response.ts'\nexport { createSchema } from './schema.ts'\n\n/**\n * Union of all AST node types.\n *\n * This lets TypeScript narrow types in `switch (node.kind)` blocks.\n *\n * @example\n * ```ts\n * function getKind(node: Node): string {\n * switch (node.kind) {\n * case nodeKinds.input:\n * return 'input'\n * default:\n * return 'other'\n * }\n * }\n * ```\n */\nexport type Node =\n | InputNode\n | OperationNode\n | SchemaNode\n | PropertyNode\n | ParameterNode\n | ResponseNode\n | RequestBodyNode\n | ContentNode\n | FileNode\n | ImportNode\n | ExportNode\n | SourceNode\n | ConstNode\n | TypeNode\n | FunctionNode\n | ArrowFunctionNode\n | TextNode\n | BreakNode\n | JsxNode\n"],"mappings":";;;;;;;;;;;;;;;AAmQA,MAAa,cAAc,YAAuB,UAAU,KAAK;;;;;;;;;;AAWjE,MAAa,aAAa,YAAsB,UAAU,IAAI;;;;;;;;;;AAW9D,MAAa,iBAAiB,YAA0B,UAAU,QAAQ;;;;;;;;;;AAW1E,MAAa,sBAAsB,YAA+B,UAAU,aAAa;;;;;;;;;;AAWzF,SAAgB,WAAW,OAAyB;CAClD,OAAO;EAAE,MAAM,UAAU;EAAM;CAAM;AACvC;;;;;;;;;;AAWA,SAAgB,cAAyB;CACvC,OAAO,EAAE,MAAM,UAAU,MAAM;AACjC;;;;;;;;;;AAWA,SAAgB,UAAU,OAAwB;CAChD,OAAO;EAAE,MAAM,UAAU;EAAK;CAAM;AACtC;;;;;ACjOA,MAAa,gBAAgB,YAAyB,UAAU,OAAO;;;;;;;;;;;;ACqDvE,SAAgB,YAAY,YAA8C,CAAC,GAAc;CACvF,OAAO;EAAE,SAAS,CAAC;EAAG,YAAY,CAAC;EAAG,MAAM,CAAC;EAAG,GAAG;EAAW,MAAM,UAAU;CAAM;AACtF;;;;;ACnHA,MAAa,oBAAoB,YAA6B,UAAU,WAAW;;ACsGnF,SAAgB,gBAAgB,OAAsC;CACpE,MAAM,EAAE,aAAa,GAAG,SAAS;CACjC,MAAM,SAAS,KAAK,WAAW,KAAA,KAAa,KAAK,SAAS,KAAA;CAY1D,OAAO;EATL,MAAM,CAAC;EACP,YAAY,CAAC;EACb,WAAW,CAAC;EACZ,GAAG;EACH,MAAM,UAAU;EAChB,GAAI,SAAS,EAAE,UAAU,OAAgB,IAAI,CAAC;EAC9C,aAAa,cAAc,kBAAkB,WAAW,IAAI,KAAA;CAGpD;AACZ;;;;;;;;;;;;;;;;ACnEA,SAAgB,gBAAgB,OAAyC;CACvE,MAAM,WAAW,MAAM,YAAY;CAEnC,OAAO;EAAE,GAAG;EAAO;EAAU,QAAQ,iBAAiB,MAAM,QAAQ,QAAQ;EAAG,MAAM,UAAU;CAAU;AAC3G;;;;;;;;;;;;;;;;AC/CA,SAAgB,eAAe,OAAuC;CACpE,MAAM,WAAW,MAAM,YAAY;CAEnC,OAAO;EAAE,GAAG;EAAO;EAAU,QAAQ,iBAAiB,MAAM,QAAQ,QAAQ;EAAG,MAAM,UAAU;CAAS;AAC1G;;;;;;;;;;;;;;ACqDA,SAAgB,eAAe,OAAoC;CACjE,MAAM,EAAE,QAAQ,WAAW,YAAY,SAAS,GAAG,SAAS;CAC5D,MAAM,UAAU,YAAY,SAAS,CAAC,cAAc;EAAE,aAAa,aAAa;EAAoB;EAAQ,YAAY,cAAc;CAAK,CAAC,CAAC,IAAI,KAAA;CAEjJ,OAAO;EAAE,GAAG;EAAM,SAAS;EAAS,MAAM,UAAU;CAAS;AAC/D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nodes-DEQjVliP.cjs","names":["nodeFactory","nodeKinds","nodeFactory","nodeKinds","nodeKinds","nodeFactory","nodeKinds","nodeKinds","applyOptionality","nodeKinds","applyOptionality","nodeKinds","nodeKinds"],"sources":["../src/nodes/code.ts","../src/nodes/content.ts","../src/nodes/input.ts","../src/nodes/requestBody.ts","../src/nodes/operation.ts","../src/nodes/parameter.ts","../src/nodes/property.ts","../src/nodes/response.ts","../src/nodes/index.ts"],"sourcesContent":["import { nodeKinds } from '../constants.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\n\n/**\n * JSDoc documentation metadata attached to code declarations.\n */\nexport type JSDocNode = {\n /**\n * JSDoc comment lines. `undefined` entries are filtered out during rendering.\n *\n * @example\n * ```ts\n * ['@description A pet resource', '@deprecated']\n * ```\n */\n comments?: Array<string | undefined>\n}\n\n/**\n * AST node representing a TypeScript `const` declaration.\n *\n * Mirrors the props of the `Const` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createConst({ name: 'pet', export: true, asConst: true })\n * // export const pet = ... as const\n * ```\n */\nexport type ConstNode = BaseNode & {\n kind: 'Const'\n /**\n * Name of the constant declaration.\n */\n name: string\n /**\n * Whether the declaration should be exported.\n */\n export?: boolean | null\n /**\n * Explicit type annotation.\n *\n * @example Type reference\n * `'Pet'`\n */\n type?: string | null\n /**\n * JSDoc documentation metadata.\n */\n JSDoc?: JSDocNode | null\n /**\n * Whether to append `as const` to the declaration.\n */\n asConst?: boolean | null\n /**\n * Child nodes representing the value of the constant (children of the `Const` component).\n * Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * AST node representing a TypeScript `type` alias declaration.\n *\n * Mirrors the props of the `Type` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createType({ name: 'Pet', export: true })\n * // export type Pet = ...\n * ```\n */\nexport type TypeNode = BaseNode & {\n kind: 'Type'\n /**\n * Name of the type alias.\n */\n name: string\n /**\n * Whether the declaration should be exported.\n */\n export?: boolean | null\n /**\n * How the declaration is written.\n * - `'type'` declares `type Name = …`\n * - `'interface'` declares `interface Name { … }`, so the body must be an object type\n *\n * @default 'type'\n */\n syntax?: 'type' | 'interface' | null\n /**\n * JSDoc documentation metadata.\n */\n JSDoc?: JSDocNode | null\n /**\n * Child nodes representing the type body (children of the `Type` component).\n * Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * AST node representing a TypeScript `function` declaration.\n *\n * Mirrors the props of the `Function` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createFunction({ name: 'getPet', export: true, async: true, returnType: 'Pet' })\n * // export async function getPet(): Promise<Pet> { ... }\n * ```\n */\nexport type FunctionNode = BaseNode & {\n kind: 'Function'\n /**\n * Name of the function.\n */\n name: string\n /**\n * Whether the function is a default export.\n */\n default?: boolean | null\n /**\n * Function parameter list as a pre-rendered string, written verbatim between the parentheses.\n *\n * @example\n * `'id: string, config: Config = {}'`\n */\n params?: string | null\n /**\n * Whether the function should be exported.\n */\n export?: boolean | null\n /**\n * Whether the function is async. When `true`, the return type is wrapped in `Promise<>`.\n */\n async?: boolean | null\n /**\n * TypeScript generic type parameters.\n *\n * @example Constrained generics\n * `['T', 'U extends string']`\n */\n generics?: string | Array<string> | null\n /**\n * Return type annotation.\n *\n * @example Type reference\n * `'Pet'`\n */\n returnType?: string | null\n /**\n * JSDoc documentation metadata.\n */\n JSDoc?: JSDocNode | null\n /**\n * Child nodes representing the function body (children of the `Function` component).\n * Each entry is a {@link CodeNode}. Use {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * AST node representing a TypeScript arrow function (`const name = () => { ... }`).\n *\n * Mirrors the props of the `Function.Arrow` component from `@kubb/renderer-jsx`.\n * The `children` prop of the component is represented as `nodes`.\n *\n * @example\n * ```ts\n * createArrowFunction({ name: 'getPet', export: true, singleLine: true })\n * // export const getPet = () => ...\n * ```\n */\nexport type ArrowFunctionNode = Omit<FunctionNode, 'kind'> & {\n kind: 'ArrowFunction'\n /**\n * Render the arrow function body as a single-line expression.\n */\n singleLine?: boolean | null\n}\n\n/**\n * AST node representing a raw text/string fragment in the source output.\n *\n * Used instead of bare `string` values so that all entries in `nodes` arrays\n * are typed `CodeNode` objects rather than a mixed `CodeNode | string` union.\n *\n * @example\n * ```ts\n * createText('return fetch(id)')\n * // { kind: 'Text', value: 'return fetch(id)' }\n * ```\n */\nexport type TextNode = BaseNode & {\n kind: 'Text'\n /**\n * The raw string content.\n */\n value: string\n}\n\n/**\n * AST node representing a blank line in the source output.\n *\n * Corresponds to `<br/>` in JSX components. `printNodes` turns a `Break` between two\n * statements into one blank line. Consecutive breaks, and breaks at the start or end of\n * the list, are folded away, so a `Break` never produces more than one blank line.\n *\n * @example\n * ```ts\n * createBreak()\n * // { kind: 'Break' }\n * ```\n */\nexport type BreakNode = BaseNode & {\n kind: 'Break'\n}\n\n/**\n * AST node representing a raw JSX fragment in the source output.\n *\n * Mirrors the `Jsx` component from `@kubb/renderer-jsx`. Embeds raw JSX/TSX markup\n * (including fragments `<>…</>`) directly in generated code.\n *\n * @example\n * ```ts\n * createJsx('<>\\n <a href={href}>Open</a>\\n</>')\n * // { kind: 'Jsx', value: '<>\\n <a href={href}>Open</a>\\n</>' }\n * ```\n */\nexport type JsxNode = BaseNode & {\n kind: 'Jsx'\n /**\n * The raw JSX string content.\n */\n value: string\n}\n\n/**\n * Union of all code-generation AST nodes.\n *\n * These nodes mirror the JSX components from `@kubb/renderer-jsx` and are used as\n * structured children in {@link SourceNode.nodes}.\n */\nexport type CodeNode = ConstNode | TypeNode | FunctionNode | ArrowFunctionNode | TextNode | BreakNode | JsxNode\n\n/**\n * Creates a `ConstNode` representing a TypeScript `const` declaration.\n *\n * @example Exported constant with type and `as const`\n * ```ts\n * createConst({ name: 'pets', export: true, type: 'Pet[]', asConst: true })\n * // export const pets: Pet[] = ... as const\n * ```\n */\nexport const createConst = nodeFactory<ConstNode>(nodeKinds.const)\n\n/**\n * Creates a `TypeNode` representing a TypeScript `type` alias declaration.\n *\n * @example\n * ```ts\n * createType({ name: 'Pet', export: true })\n * // export type Pet = ...\n * ```\n */\nexport const createType = nodeFactory<TypeNode>(nodeKinds.type)\n\n/**\n * Creates a `FunctionNode` representing a TypeScript `function` declaration.\n *\n * @example\n * ```ts\n * createFunction({ name: 'fetchPet', export: true, async: true, returnType: 'Pet' })\n * // export async function fetchPet(): Promise<Pet> { ... }\n * ```\n */\nexport const createFunction = nodeFactory<FunctionNode>(nodeKinds.function)\n\n/**\n * Creates an `ArrowFunctionNode` representing a TypeScript arrow function.\n *\n * @example\n * ```ts\n * createArrowFunction({ name: 'double', export: true, params: 'n: number', singleLine: true })\n * // export const double = (n: number) => ...\n * ```\n */\nexport const createArrowFunction = nodeFactory<ArrowFunctionNode>(nodeKinds.arrowFunction)\n\n/**\n * Creates a {@link TextNode} representing a raw string fragment in the source output.\n *\n * @example\n * ```ts\n * createText('return fetch(id)')\n * // { kind: 'Text', value: 'return fetch(id)' }\n * ```\n */\nexport function createText(value: string): TextNode {\n return { kind: nodeKinds.text, value }\n}\n\n/**\n * Creates a {@link BreakNode} representing a line break in the source output.\n *\n * @example\n * ```ts\n * createBreak()\n * // { kind: 'Break' }\n * ```\n */\nexport function createBreak(): BreakNode {\n return { kind: nodeKinds.break }\n}\n\n/**\n * Creates a {@link JsxNode} representing a raw JSX fragment in the source output.\n *\n * @example\n * ```ts\n * createJsx('<>\\n <a href={href}>Open</a>\\n</>')\n * // { kind: 'Jsx', value: '<>\\n <a href={href}>Open</a>\\n</>' }\n * ```\n */\nexport function createJsx(value: string): JsxNode {\n return { kind: nodeKinds.jsx, value }\n}\n","import { nodeKinds } from '../constants.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\nimport type { ParameterStyle } from './parameter.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * How one body property is serialized, from the `encoding` entry of its media type.\n */\nexport type EncodingNode = {\n /**\n * Content type of the part, for example `'application/json'` for a multipart property.\n */\n contentType?: string\n /**\n * Serialization style of the property.\n */\n style?: ParameterStyle\n /**\n * Whether array and object values expand into separate values.\n */\n explode?: boolean\n /**\n * Whether reserved characters are sent as-is instead of percent-encoded.\n */\n allowReserved?: boolean\n encoding?: Record<string, EncodingNode>\n prefixEncoding?: Array<EncodingNode>\n itemEncoding?: EncodingNode\n}\n\nexport type ExampleNode = {\n name?: string\n summary?: string\n description?: string\n value?: unknown\n serializedValue?: string\n}\n\n/**\n * AST node representing one content-type entry of a request body or response.\n *\n * There is one entry per content type declared in the spec (e.g. `application/json`,\n * `multipart/form-data`), and each entry holds its own body schema.\n *\n * @example\n * ```ts\n * const content: ContentNode = {\n * kind: 'Content',\n * contentType: 'application/json',\n * schema: createSchema({ type: 'string' }),\n * }\n * ```\n */\nexport type ContentNode = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Content'\n /**\n * The content type for this entry (e.g. `'application/json'`), or `''` for a response without a body.\n */\n contentType: string\n /**\n * Body schema for this content type. For a stream it is the same node as `stream.schema`.\n */\n schema?: SchemaNode\n /**\n * Set when the content is a stream of items (an event stream, JSON Lines, a channel of messages) instead of one body.\n */\n stream?: {\n /**\n * Schema of one item, such as one event of `text/event-stream` or one line of JSON Lines.\n */\n schema?: SchemaNode\n /**\n * What `schema` describes for an event stream.\n * - `'event'` the parsed event with its `event`, `data`, `id` and `retry` fields\n * - `'data'` only the `data` payload, which the client wraps in its own event type\n */\n shape?: 'event' | 'data'\n }\n /**\n * Property keys to exclude from the generated type via `Omit<Type, Keys>`.\n * Set when a referenced schema has `readOnly`/`writeOnly` fields that should be omitted.\n */\n keysToOmit?: Array<string> | null\n /**\n * Serialization settings per body property that sets at least one field in the spec's `encoding`.\n */\n encoding?: Record<string, EncodingNode>\n examples?: Array<ExampleNode>\n /**\n * Serialization of the first parts by position, for a body sent as an array of parts such as `multipart/mixed`.\n */\n prefixEncoding?: Array<EncodingNode>\n /**\n * Serialization of every part after `prefixEncoding`, for a body sent as an array of parts such as `multipart/mixed`.\n */\n itemEncoding?: EncodingNode\n /** Vendor extensions (`x-*` keys) from the source media type, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Creates a `ContentNode` for a single request-body or response content type.\n */\nexport const createContent = nodeFactory<ContentNode>(nodeKinds.content)\n","import { nodeKinds } from '../constants.ts'\nimport type { BaseNode } from './base.ts'\nimport type { OperationNode } from './operation.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * A variable declared by a server URL template.\n */\nexport type InputServerVariable = {\n default?: string\n enum?: Array<string>\n description?: string\n}\n\n/**\n * A server from the source document, with `{variable}` placeholders filled from their defaults.\n */\nexport type InputServer = {\n url: string\n name?: string\n description?: string\n /**\n * Variables of the source URL template, copied as-is. `url` already has their defaults filled in, so\n * this tells a templated server apart from a literal one. Absent when the server declares none.\n */\n variables?: Record<string, InputServerVariable>\n}\n\nexport type ExternalDocs = { url: string; description?: string }\n\nexport type InputTag = {\n name: string\n summary?: string\n description?: string\n /**\n * Name of the tag this tag nests under. `group: { type: 'tag' }` places its files in the parent's folder.\n */\n parent?: string\n kind?: string\n externalDocs?: ExternalDocs\n}\n\nexport type OAuthFlow = {\n authorizationUrl?: string\n deviceAuthorizationUrl?: string\n tokenUrl?: string\n refreshUrl?: string\n scopes?: Record<string, string>\n}\n\n/**\n * How a client sends a credential, in the same shape as the `Auth` object the generated clients pass to `auth`.\n */\nexport type AuthCredential =\n | { type: 'http'; scheme: 'bearer' | 'basic' | (string & {}); bearerFormat?: string }\n | { type: 'apiKey'; in: 'header' | 'query' | 'cookie'; name: string }\n | { type: 'oauth2'; flows: Record<string, OAuthFlow>; metadataUrl?: string }\n | { type: 'openIdConnect'; url?: string }\n | { type: 'mutualTLS' }\n\n/**\n * One way to authenticate, keyed by `name`, which operations refer to in `auth`.\n */\nexport type AuthScheme = {\n name: string\n description?: string\n deprecated?: boolean\n credential: AuthCredential\n}\n\n/**\n * One way to meet an operation's auth. Every scheme in it applies together. `scopes` are the OAuth2 or OpenID\n * Connect scopes the call needs. An empty list means the call may be sent without credentials.\n */\nexport type AuthRequirement = Array<{ scheme: string; scopes?: Array<string> }>\n\n/**\n * Metadata for an API document, populated by the adapter and available to every generator.\n * Every field is a plain JSON value.\n *\n * @example\n * ```ts\n * const meta: InputMeta = { title: 'Pet Store', version: '1.0.0', baseURL: 'https://api.example.com/v2' }\n * ```\n */\nexport type InputMeta = {\n /**\n * API title from `info.title` in the source document.\n */\n title?: string\n /**\n * API description from `info.description` in the source document.\n */\n description?: string\n /**\n * API version string from `info.version` in the source document.\n */\n version?: string\n summary?: string\n termsOfService?: string\n contact?: { name?: string; url?: string; email?: string }\n license?: { name: string; identifier?: string; url?: string }\n externalDocs?: ExternalDocs\n /**\n * Resolved base URL from the first matching server entry in the source document.\n */\n baseURL?: string | null\n servers?: Array<InputServer>\n tags?: Array<InputTag>\n auth?: Array<AuthScheme>\n /**\n * Vendor extensions (`x-*` keys) from the document root, copied as-is. Absent when the root has none.\n */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Input AST node that contains all schemas and operations for one API document.\n * Produced by the adapter and consumed by all Kubb plugins.\n *\n * @example\n * ```ts\n * const input: InputNode = {\n * kind: 'Input',\n * schemas: [],\n * operations: [],\n * meta: {},\n * }\n * ```\n */\nexport type InputNode = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Input'\n /**\n * All schema nodes in the document.\n */\n schemas: Array<SchemaNode>\n /**\n * All operation nodes in the document.\n */\n operations: Array<OperationNode>\n /**\n * Document metadata populated by the adapter.\n */\n meta: InputMeta\n}\n\n/**\n * Creates an `InputNode`, defaulting `schemas`/`operations` to empty arrays and `meta` to an empty\n * object. Every call allocates fresh defaults so no two inputs share them.\n *\n * @example\n * ```ts\n * const input = createInput()\n * // { kind: 'Input', schemas: [], operations: [] }\n * ```\n */\nexport function createInput(overrides: Partial<Omit<InputNode, 'kind'>> = {}): InputNode {\n return { schemas: [], operations: [], meta: {}, ...overrides, kind: nodeKinds.input }\n}\n","import { nodeKinds } from '../constants.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\nimport type { ContentNode } from './content.ts'\n\n/**\n * AST node representing an operation request body.\n *\n * Body schemas live exclusively inside the `content` array (one entry per content type),\n * mirroring {@link ResponseNode}.\n *\n * @example\n * ```ts\n * const requestBody: RequestBodyNode = {\n * kind: 'RequestBody',\n * required: true,\n * content: [{ kind: 'Content', contentType: 'application/json', schema: createSchema({ type: 'string' }) }],\n * }\n * ```\n */\nexport type RequestBodyNode = BaseNode & {\n kind: 'RequestBody'\n /**\n * Request body description carried over from the spec.\n */\n description?: string\n /**\n * Whether the request body is required (`requestBody.required: true` in the spec).\n * When `false` or absent, the generated `data` parameter should be optional.\n */\n required?: boolean\n /**\n * Content type entries for this request body.\n *\n * When the adapter `contentType` option is set, this array contains exactly one entry for\n * that content type. Otherwise it contains one entry per content type declared in the spec,\n * so plugins can generate code for every variant (for example, separate hooks for\n * `application/json` and `multipart/form-data`).\n */\n content?: Array<ContentNode>\n /** Vendor extensions (`x-*` keys) from the source request body, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\n/**\n * Creates a `RequestBodyNode`.\n */\nexport const createRequestBody = nodeFactory<RequestBodyNode>(nodeKinds.requestBody)\n","import { nodeKinds } from '../constants.ts'\nimport type { BaseNode } from './base.ts'\nimport type { AuthRequirement, ExternalDocs, InputServer } from './input.ts'\nimport type { ParameterNode } from './parameter.ts'\nimport { createRequestBody, type RequestBodyNode } from './requestBody.ts'\nimport type { ResponseNode } from './response.ts'\n\n/**\n * HTTP method an operation responds to. `QUERY` is the safe, idempotent method with a request body\n * from RFC 10008, declared with the `query` field of an OpenAPI 3.2 path item. Any other name is a\n * method the source declares outside this fixed set, in the capitalization it is sent with.\n */\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'TRACE' | 'QUERY' | (string & {})\n\n/**\n * Fields shared by every operation, regardless of transport.\n */\ntype OperationNodeBase = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Operation'\n /**\n * Stable identifier for the operation.\n */\n operationId: string\n /**\n * Group labels for the operation.\n */\n tags: Array<string>\n /**\n * Short one-line operation summary.\n */\n summary?: string\n /**\n * Full operation description.\n */\n description?: string\n /**\n * Marks the operation as deprecated.\n */\n deprecated?: boolean\n externalDocs?: ExternalDocs\n /**\n * Query, path, header, and cookie parameters for the operation.\n */\n parameters: Array<ParameterNode>\n /**\n * Request body for the operation.\n */\n requestBody?: RequestBodyNode\n /**\n * Operation responses.\n */\n responses: Array<ResponseNode>\n /**\n * Vendor extensions (`x-*` keys) from the source operation, copied as-is. Absent when the source has none.\n */\n extensions?: Record<string, unknown>\n /** The operation's own `servers`, else its path item's, such as an upload host. Absent when neither declares any. */\n servers?: Array<InputServer>\n /**\n * Ways to authenticate, from the operation or else the document. Any one entry is enough. `[]` means no auth.\n */\n auth?: Array<AuthRequirement>\n}\n\n/**\n * Operation served over HTTP. `method` and `path` are guaranteed.\n *\n * @example\n * ```ts\n * const operation: HttpOperationNode = {\n * kind: 'Operation',\n * operationId: 'listPets',\n * protocol: 'http',\n * method: 'GET',\n * path: '/pets',\n * tags: [],\n * parameters: [],\n * responses: [],\n * }\n * ```\n */\nexport type HttpOperationNode = OperationNodeBase & {\n /**\n * Transport the operation belongs to.\n */\n protocol?: 'http'\n /**\n * HTTP method like `'GET'`.\n */\n method: HttpMethod\n /**\n * Path string, for example `/pets/{petId}`, with `{param}` notation preserved.\n */\n path: string\n}\n\n/**\n * Operation for a non-HTTP transport. HTTP-only fields are forbidden.\n */\nexport type GenericOperationNode = OperationNodeBase & {\n protocol?: never\n method?: never\n path?: never\n}\n\n/**\n * AST node representing one API operation.\n *\n * Discriminated on `protocol`: an {@link HttpOperationNode} (`protocol: 'http'`) guarantees\n * `method` and `path`, while a {@link GenericOperationNode} omits them. Narrow with\n * `ast.http.isOperation(node)` or `node.protocol === 'http'` before reading `method`/`path`.\n */\nexport type OperationNode = HttpOperationNode | GenericOperationNode\n\ntype OperationInput = {\n operationId: string\n method?: HttpOperationNode['method']\n path?: HttpOperationNode['path']\n requestBody?: Omit<RequestBodyNode, 'kind'>\n [key: string]: unknown\n}\n\n/**\n * Creates an `OperationNode` with default empty arrays for `tags`, `parameters`, and `responses`.\n * HTTP operations (those carrying both `method` and `path`) are tagged with `protocol: 'http'`,\n * and the request body is normalized into a `RequestBodyNode`.\n *\n * @example\n * ```ts\n * const operation = createOperation({ operationId: 'getPetById', method: 'GET', path: '/pet/{petId}' })\n * // tags, parameters, and responses are []\n * ```\n */\nexport function createOperation(\n props: Pick<HttpOperationNode, 'operationId' | 'method' | 'path'> &\n Partial<Omit<HttpOperationNode, 'kind' | 'operationId' | 'method' | 'path' | 'requestBody'>> & {\n requestBody?: Omit<RequestBodyNode, 'kind'>\n },\n): HttpOperationNode\nexport function createOperation(\n props: Pick<GenericOperationNode, 'operationId'> &\n Partial<Omit<GenericOperationNode, 'kind' | 'operationId' | 'requestBody'>> & {\n requestBody?: Omit<RequestBodyNode, 'kind'>\n },\n): GenericOperationNode\nexport function createOperation(props: OperationInput): OperationNode {\n const { requestBody, ...rest } = props\n const isHttp = rest.method !== undefined && rest.path !== undefined\n\n const node = {\n tags: [],\n parameters: [],\n responses: [],\n ...rest,\n kind: nodeKinds.operation,\n ...(isHttp ? { protocol: 'http' as const } : {}),\n requestBody: requestBody ? createRequestBody(requestBody) : undefined,\n }\n\n return node as OperationNode\n}\n","import { nodeKinds } from '../constants.ts'\nimport { applyOptionality } from '../optionality.ts'\nimport type { BaseNode } from './base.ts'\nimport type { EncodingNode, ExampleNode } from './content.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * Where a parameter is sent. `querystring` carries the whole query string as one value, serialized per `contentType`.\n */\nexport type ParameterLocation = 'path' | 'query' | 'header' | 'cookie' | 'querystring'\n\n/**\n * Parameter serialization style, controlling how a parameter value is rendered into the request.\n */\nexport type ParameterStyle = 'matrix' | 'label' | 'form' | 'simple' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject' | 'cookie'\n\n/**\n * AST node representing one operation parameter.\n *\n * @example\n * ```ts\n * const param: ParameterNode = {\n * kind: 'Parameter',\n * name: 'petId',\n * in: 'path',\n * schema: createSchema({ type: 'string' }),\n * required: true,\n * }\n * ```\n */\nexport type ParameterNode = BaseNode & {\n kind: 'Parameter'\n /**\n * Parameter name.\n */\n name: string\n /**\n * Parameter location (`path`, `query`, `header`, `cookie`, or `querystring`).\n */\n in: ParameterLocation\n /**\n * Parameter schema.\n */\n schema: SchemaNode\n /**\n * Whether the parameter is required.\n */\n required: boolean\n /**\n * Serialization style. Absent when the source omits it, leaving consumers to apply the\n * per-location default.\n */\n style?: ParameterStyle\n /**\n * Whether array and object values expand into separate values. Absent when the source omits it,\n * leaving consumers to apply the default for the style.\n */\n explode?: boolean\n /**\n * Whether reserved characters (RFC 3986 `:/?#[]@!$&'()*+,;=`) are sent as-is instead of\n * percent-encoded. Absent when the source omits it.\n */\n allowReserved?: boolean\n /**\n * Media type of a parameter described with `content` instead of `schema`, for example\n * `application/json` when the value is sent as a JSON-encoded string. Absent for `schema` parameters.\n */\n contentType?: string\n /**\n * Serialization settings per property of a `content` parameter, from the `encoding` of its media type. An OpenAPI 3.2\n * `querystring` parameter sent as `application/x-www-form-urlencoded` uses it to set `style` and `explode` per field.\n */\n encoding?: Record<string, EncodingNode>\n examples?: Array<ExampleNode>\n deprecated?: boolean\n allowEmptyValue?: boolean\n /** Vendor extensions (`x-*` keys) from the source parameter, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\ntype UserParameterNode = Pick<ParameterNode, 'name' | 'in' | 'schema'> & Partial<Omit<ParameterNode, 'kind' | 'name' | 'in' | 'schema'>>\n\n/**\n * Creates a `ParameterNode`. `required` defaults to `false`, and the schema's\n * `optional`/`nullish` flags are derived from it.\n *\n * @example\n * ```ts\n * const param = createParameter({\n * name: 'petId',\n * in: 'path',\n * required: true,\n * schema: createSchema({ type: 'string' }),\n * })\n * ```\n */\nexport function createParameter(input: UserParameterNode): ParameterNode {\n const required = input.required ?? false\n\n return { ...input, required, schema: applyOptionality(input.schema, required), kind: nodeKinds.parameter }\n}\n","import { nodeKinds } from '../constants.ts'\nimport { applyOptionality } from '../optionality.ts'\nimport type { BaseNode } from './base.ts'\nimport type { SchemaNode } from './schema.ts'\n\n/**\n * AST node representing one named object property.\n *\n * @example\n * ```ts\n * const property: PropertyNode = {\n * kind: 'Property',\n * name: 'id',\n * schema: createSchema({ type: 'integer' }),\n * required: true,\n * }\n * ```\n */\nexport type PropertyNode = BaseNode & {\n kind: 'Property'\n /**\n * Property key.\n */\n name: string\n /**\n * Property schema.\n */\n schema: SchemaNode\n /**\n * Whether the property is required.\n */\n required: boolean\n}\n\n/**\n * Loosely-typed property accepted by `createProperty`, with `required` optional.\n */\ntype UserPropertyNode = Pick<PropertyNode, 'name' | 'schema'> & Partial<Omit<PropertyNode, 'kind' | 'name' | 'schema'>>\n\n/**\n * Creates a `PropertyNode`. `required` defaults to `false`, and the schema's\n * `optional`/`nullish` flags are derived from it.\n *\n * @example\n * ```ts\n * const property = createProperty({\n * name: 'status',\n * required: true,\n * schema: createSchema({ type: 'string', nullable: true }),\n * })\n * // required=true, no optional/nullish\n * ```\n */\nexport function createProperty(input: UserPropertyNode): PropertyNode {\n const required = input.required ?? false\n\n return { ...input, required, schema: applyOptionality(input.schema, required), kind: nodeKinds.property }\n}\n","import { nodeKinds } from '../constants.ts'\nimport type { BaseNode } from './base.ts'\nimport { type ContentNode, createContent } from './content.ts'\nimport type { InputServer } from './input.ts'\nimport type { ParameterNode } from './parameter.ts'\nimport type { SchemaNode } from './schema.ts'\n\ntype Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n\n/**\n * Response status code literal used by operations.\n *\n * Includes three-digit HTTP status code strings, ranges such as `\"2xx\"`, and `\"default\"` for catch-all responses.\n *\n * @example\n * ```ts\n * const status: StatusCode = '200'\n * const fallback: StatusCode = 'default'\n * ```\n */\nexport type StatusCode = `${1 | 2 | 3 | 4 | 5}${Digit}${Digit}` | `${1 | 2 | 3 | 4 | 5}xx` | 'default'\n\n/**\n * AST node representing one operation response variant.\n *\n * Mirrors {@link OperationNode.requestBody}: the response body schemas live exclusively inside\n * the `content` array (one entry per content type), so the same schema is never duplicated at the\n * node root and inside `content`.\n *\n * @example\n * ```ts\n * const response: ResponseNode = {\n * kind: 'Response',\n * statusCode: '200',\n * content: [{ kind: 'Content', contentType: 'application/json', schema: createSchema({ type: 'string' }) }],\n * }\n * ```\n */\nexport type ResponseNode = BaseNode & {\n /**\n * Node kind.\n */\n kind: 'Response'\n /**\n * HTTP status code or `'default'` for a fallback response.\n */\n statusCode: StatusCode\n summary?: string\n /**\n * Optional response description.\n */\n description?: string\n /**\n * All available content type entries for this response.\n *\n * For a response that declares content, the array holds exactly one entry for the adapter\n * `contentType` option when it is set. Otherwise it holds one entry per content type declared in\n * the spec, so that plugins can generate a union of response types (e.g. `application/json` and\n * `application/xml`). A body-less response always keeps a single entry whose `contentType` is `''`\n * and whose `schema` is the empty/`void` placeholder, even when the option is set.\n *\n * @example\n * ```ts\n * // spec response declares both application/json and application/xml\n * response.content[0].contentType // 'application/json'\n * response.content[1].contentType // 'application/xml'\n * ```\n */\n content?: Array<ContentNode>\n /**\n * Response headers, as `in: 'header'` parameters. `Content-Type` is left out.\n */\n headers?: Array<ParameterNode>\n links?: Record<string, ResponseLink>\n /** Vendor extensions (`x-*` keys) from the source response, copied as-is. */\n extensions?: Record<string, unknown>\n}\n\n/**\n * A link to another operation. `parameters` and `requestBody` hold runtime expressions such as `$response.body#/id`.\n */\nexport type ResponseLink = {\n operationId?: string\n operationRef?: string\n parameters?: Record<string, unknown>\n requestBody?: unknown\n description?: string\n server?: InputServer\n}\n\ntype ResponseInput = Pick<ResponseNode, 'statusCode'> &\n Partial<Omit<ResponseNode, 'kind' | 'statusCode' | 'content'>> & {\n content?: Array<ContentNode>\n schema?: SchemaNode\n mediaType?: string | null\n keysToOmit?: Array<string> | null\n }\n\n/**\n * Creates a `ResponseNode`. A single legacy `schema` (with optional `mediaType`/`keysToOmit`)\n * is normalized into one `content` entry.\n *\n * @example\n * ```ts\n * const response = createResponse({\n * statusCode: '200',\n * content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'object', properties: [] }) })],\n * })\n * ```\n */\nexport function createResponse(props: ResponseInput): ResponseNode {\n const { schema, mediaType, keysToOmit, content, ...rest } = props\n const entries = content ?? (schema ? [createContent({ contentType: mediaType ?? 'application/json', schema, keysToOmit: keysToOmit ?? null })] : undefined)\n\n return { ...rest, content: entries, kind: nodeKinds.response }\n}\n","import type { ArrowFunctionNode, BreakNode, ConstNode, FunctionNode, JsxNode, TextNode, TypeNode } from './code.ts'\nimport type { ContentNode } from './content.ts'\nimport type { ExportNode, FileNode, ImportNode, SourceNode } from './file.ts'\nimport type { InputNode } from './input.ts'\nimport type { OperationNode } from './operation.ts'\nimport type { ParameterNode } from './parameter.ts'\nimport type { PropertyNode } from './property.ts'\nimport type { RequestBodyNode } from './requestBody.ts'\nimport type { ResponseNode } from './response.ts'\nimport type { SchemaNode } from './schema.ts'\n\nexport { createArrowFunction, createBreak, createConst, createFunction, createJsx, createText, createType } from './code.ts'\nexport { createContent } from './content.ts'\nexport { createExport, createFile, createImport, createSource } from './file.ts'\nexport type { ExportInput, ImportInput, ModuleName, Space, UserFileNode } from './file.ts'\nexport { createInput } from './input.ts'\nexport { createOperation } from './operation.ts'\nexport { createParameter } from './parameter.ts'\nexport { createProperty } from './property.ts'\nexport { createRequestBody } from './requestBody.ts'\nexport { createResponse } from './response.ts'\nexport { createSchema } from './schema.ts'\n\n/**\n * Union of all AST node types.\n *\n * This lets TypeScript narrow types in `switch (node.kind)` blocks.\n *\n * @example\n * ```ts\n * function getKind(node: Node): string {\n * switch (node.kind) {\n * case nodeKinds.input:\n * return 'input'\n * default:\n * return 'other'\n * }\n * }\n * ```\n */\nexport type Node =\n | InputNode\n | OperationNode\n | SchemaNode\n | PropertyNode\n | ParameterNode\n | ResponseNode\n | RequestBodyNode\n | ContentNode\n | FileNode\n | ImportNode\n | ExportNode\n | SourceNode\n | ConstN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kBAAkB,WAAW,IAAI,KAAA;CAGpD;AACZ;;;;;;;;;;;;;;;;ACnEA,SAAgB,gBAAgB,OAAyC;CACvE,MAAM,WAAW,MAAM,YAAY;CAEnC,OAAO;EAAE,GAAG;EAAO;EAAU,QAAQC,oBAAAA,iBAAiB,MAAM,QAAQ,QAAQ;EAAG,MAAMC,kBAAAA,UAAU;CAAU;AAC3G;;;;;;;;;;;;;;;;AC/CA,SAAgB,eAAe,OAAuC;CACpE,MAAM,WAAW,MAAM,YAAY;CAEnC,OAAO;EAAE,GAAG;EAAO;EAAU,QAAQC,oBAAAA,iBAAiB,MAAM,QAAQ,QAAQ;EAAG,MAAMC,kBAAAA,UAAU;CAAS;AAC1G;;;;;;;;;;;;;;ACqDA,SAAgB,eAAe,OAAoC;CACjE,MAAM,EAAE,QAAQ,WAAW,YAAY,SAAS,GAAG,SAAS;CAC5D,MAAM,UAAU,YAAY,SAAS,CAAC,cAAc;EAAE,aAAa,aAAa;EAAoB;EAAQ,YAAY,cAAc;CAAK,CAAC,CAAC,IAAI,KAAA;CAEjJ,OAAO;EAAE,GAAG;EAAM,SAAS;EAAS,MAAMC,kBAAAA,UAAU;CAAS;AAC/D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"visitor-Bh1CBAOz.cjs","names":["isJson","nodeKinds"],"sources":["../src/schema/embeddedJson.ts","../src/visitor.ts"],"sourcesContent":["import { isJson } from '../mediaType/index.ts'\nimport type { SchemaNode, StringSchemaNode } from '../nodes/schema.ts'\n\n/** The schema of the JSON document a string holds (`contentMediaType` with `contentSchema`), else `undefined`. */\nexport function getEmbeddedJson({ content }: Pick<StringSchemaNode, 'content'>): SchemaNode | undefined {\n // shortcut: an encoded document (`contentEncoding`) is not decoded, so only its encoding is checked; decode it once a spec needs both.\n if (!content?.schema || content.encoding || !content.mediaType) return undefined\n return isJson(content.mediaType) ? content.schema : undefined\n}\n","import { nodeKinds } from './constants.ts'\nimport type { Node } from './nodes/index.ts'\nimport type { InputNode } from './nodes/input.ts'\nimport type { NodeKind } from './nodes/base.ts'\nimport type { OperationNode } from './nodes/operation.ts'\nimport type { ParameterNode } from './nodes/parameter.ts'\nimport type { PropertyNode } from './nodes/property.ts'\nimport type { ResponseNode } from './nodes/response.ts'\nimport type { SchemaNode } from './nodes/schema.ts'\nimport { getEmbeddedJson } from './schema/embeddedJson.ts'\n\n/**\n * Traversal depth for AST visitor utilities.\n *\n * - `'shallow'` recurses through every node except nested `Schema` subtrees, which it treats as\n * leaves: a schema node itself is visited, but its children are not.\n * - `'deep'` recursively visits all descendant nodes, including schema subtrees.\n */\nexport type VisitorDepth = 'shallow' | 'deep'\n\n/**\n * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).\n */\nconst VISITOR_KEYS: Partial<Record<NodeKind, ReadonlyArray<string>>> = {\n Input: ['schemas', 'operations'],\n Operation: ['parameters', 'requestBody', 'responses'],\n RequestBody: ['content'],\n Content: ['schema', 'stream'],\n Response: ['content', 'headers'],\n Schema: ['properties', 'items', 'members', 'additionalProperties', 'patternProperties', 'propertyNames', 'rest'],\n Property: ['schema'],\n Parameter: ['schema'],\n}\n\n/**\n * Schema fields that hold checks rather than shape: the `conditionals` entries, `contains` and a string's `content`.\n * `transform` and `collect` skip them, and `visitChildNodes` walks them with `checks: true`.\n */\nexport const schemaCheckKeys = ['conditionals', 'contains', 'content'] as const\n\n/** Visitor callback names in traversal order, the keys of {@link Visitor}. */\nexport const visitorKeys = ['input', 'operation', 'schema', 'property', 'parameter', 'response'] as const\n\nexport type VisitorKey = (typeof visitorKeys)[number]\n\n/**\n * Maps a node kind to the matching visitor callback name.\n */\nconst VISITOR_KEY_BY_KIND: Partial<Record<NodeKind, VisitorKey>> = {\n Input: 'input',\n Operation: 'operation',\n Schema: 'schema',\n Property: 'property',\n Parameter: 'parameter',\n Response: 'response',\n}\n\n/**\n * Traversal context passed as the second argument to every visitor callback.\n *\n * @example\n * ```ts\n * const visitor: Visitor = {\n * schema(node, { parent }) {\n * // parent is the node that holds this schema, or undefined at the root\n * },\n * }\n * ```\n */\nexport type VisitorContext = {\n /**\n * Parent node of the currently visited node. For the root node, this is `undefined`.\n */\n parent?: Node\n}\n\n/**\n * Synchronous visitor consumed by `transform`. Each optional callback runs\n * for the matching node type. Return a new node to replace it, or `undefined`\n * to leave it untouched.\n *\n * Plugins typically expose `transformer` so users can supply a `Visitor` that\n * rewrites the AST before printing.\n *\n * @example Prefix every operationId\n * ```ts\n * const visitor: Visitor = {\n * operation(node) {\n * return { ...node, operationId: `api_${node.operationId}` }\n * },\n * }\n * ```\n *\n * @example Strip schema descriptions\n * ```ts\n * const visitor: Visitor = {\n * schema(node) {\n * return { ...node, description: undefined }\n * },\n * }\n * ```\n */\nexport type Visitor = {\n input?(node: InputNode, context: VisitorContext): undefined | null | InputNode\n operation?(node: OperationNode, context: VisitorContext): undefined | null | OperationNode\n schema?(node: SchemaNode, context: VisitorContext): undefined | null | SchemaNode\n property?(node: PropertyNode, context: VisitorContext): undefined | null | PropertyNode\n parameter?(node: ParameterNode, context: VisitorContext): undefined | null | ParameterNode\n response?(node: ResponseNode, context: VisitorContext): undefined | null | ResponseNode\n}\n\n/**\n * The callbacks of {@link Visitor} with every return type replaced by `TResult`. `collect` uses it\n * so a visitor can yield values instead of replacement nodes.\n *\n * @example\n * ```ts\n * const visitor: VisitorOf<string> = {\n * operation(node) {\n * return node.operationId\n * },\n * }\n * ```\n */\ntype VisitorOf<TResult> = {\n [K in keyof Visitor]?: (node: Parameters<NonNullable<Visitor[K]>>[0], context: Parameters<NonNullable<Visitor[K]>>[1]) => TResult | null | undefined\n}\n\ntype TraversalOptions = {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\n/**\n * Options for `transform`.\n *\n * @example\n * ```ts\n * const options: TransformOptions = { depth: 'deep', schema: (node) => node }\n * ```\n *\n * @example\n * ```ts\n * // Only transform the current node, not nested children\n * const options: TransformOptions = { depth: 'shallow', schema: (node) => node }\n * ```\n */\ntype TransformOptions = Visitor & TraversalOptions\n\n/**\n * Options for `collect`.\n *\n * @example\n * ```ts\n * const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }\n * ```\n */\ntype CollectOptions<T> = VisitorOf<T> & TraversalOptions\n\n/**\n * Returns `true` when `value` is an AST node (an object carrying a `kind`).\n */\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as { kind?: unknown }).kind === 'string'\n}\n\n/**\n * Returns `true` for a plain object that maps names to nodes, such as `patternProperties`.\n */\nfunction isNodeRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// A check no printer emits: a `contains` that any array meets (`min: 0`, no `max`), or `content` that is not JSON.\nfunction isNeverPrinted({ node, key }: { node: Node; key: string }): boolean {\n if (node.kind !== nodeKinds.schema) return false\n if (key === 'contains' && (node.type === 'array' || node.type === 'tuple')) return node.contains?.min === 0 && node.contains.max === undefined\n if (key === 'content' && node.type === 'string') return !getEmbeddedJson(node)\n return false\n}\n\n/**\n * Child keys of a schema walked with `checks: true`: the shape keys, then {@link schemaCheckKeys}.\n */\nconst SCHEMA_CHECK_VISITOR_KEYS: ReadonlyArray<string> = [...VISITOR_KEYS.Schema!, ...schemaCheckKeys]\n\n/**\n * Children a node already passed to `visit`. A node under two keys, such as a stream item under `schema` and\n * `stream`, is visited once. The `Set` is only created once a node has a second child.\n */\ntype SeenChildren = { first: Node | undefined; rest: Set<Node> | undefined }\n\nfunction visitOnce(child: Node, seen: SeenChildren, visit: (child: Node) => boolean): boolean {\n if (seen.first === undefined) {\n seen.first = child\n return visit(child)\n }\n if (seen.first === child || seen.rest?.has(child)) return false\n ;(seen.rest ??= new Set()).add(child)\n return visit(child)\n}\n\nfunction visitRecord(value: Record<string, unknown>, seen: SeenChildren, visit: (child: Node) => boolean): boolean {\n for (const name in value) {\n if (!Object.hasOwn(value, name)) continue\n const item = value[name]\n if (isNode(item) && visitOnce(item, seen, visit)) return true\n }\n return false\n}\n\n/**\n * Calls `visit` for each direct child node and stops at the first call that returns `true`.\n * With `checks: true`, a schema's {@link schemaCheckKeys} fields are walked too, except checks that cannot fail.\n */\nexport function visitChildNodes(node: Node, visit: (child: Node) => boolean, { checks = false }: { checks?: boolean } = {}): boolean {\n const withChecks = checks && node.kind === nodeKinds.schema\n const keys = withChecks ? SCHEMA_CHECK_VISITOR_KEYS : VISITOR_KEYS[node.kind]\n if (!keys) return false\n\n const record = node as unknown as Record<string, unknown>\n let seen: SeenChildren | undefined\n for (const key of keys) {\n const value = record[key]\n if (value === undefined || value === null) continue\n if (withChecks && isNeverPrinted({ node, key })) continue\n seen ??= { first: undefined, rest: undefined }\n if (Array.isArray(value)) {\n // Items can be plain objects that hold nodes, such as the `{ if, then, else }` entries of `conditionals`.\n for (const item of value) if (isNode(item) ? visitOnce(item, seen, visit) : isNodeRecord(item) && visitRecord(item, seen, visit)) return true\n continue\n }\n if (isNode(value)) {\n if (visitOnce(value, seen, visit)) return true\n continue\n }\n if (isNodeRecord(value) && visitRecord(value, seen, visit)) return true\n }\n return false\n}\n\ntype FindResult = { found: SchemaNode | undefined; low: number }\n\nconst notFound: FindResult = { found: undefined, low: Number.POSITIVE_INFINITY }\n\n/**\n * Finds the first schema that matches `predicate` in depth-first order. Pass `follow: ['ref']` to include resolved ref targets.\n *\n * @example\n * ```ts\n * const firstString = findSchema(operationNode, {\n * predicate: (schema) => schema.type === 'string',\n * })\n * ```\n */\nexport function findSchema(\n node: Node,\n {\n predicate,\n follow,\n followRefs = false,\n cache,\n }: {\n predicate: (schema: SchemaNode) => boolean\n /**\n * Links to follow on top of the walk over every child. `['ref']` also walks a resolved ref's target.\n * @default []\n */\n follow?: ReadonlyArray<'ref'>\n /**\n * @deprecated Use `follow: ['ref']`. Removed in Kubb v6.\n */\n followRefs?: boolean\n /**\n * Remembers the match below each schema (`null` for none), so later calls skip the parts of the graph they share.\n * Keep one cache per `predicate` and ref-following mode (`follow`, or the deprecated `followRefs`), for example one per build.\n * In a cyclic graph, a cached call can return a different match than the first one in depth-first order.\n */\n cache?: WeakMap<SchemaNode, SchemaNode | null>\n },\n): SchemaNode | undefined {\n const followsRefs = followRefs || (follow?.includes('ref') ?? false)\n // When following refs, as in Tarjan's algorithm: the visit order of a schema still being walked, or for a finished\n // schema without a match the lowest visit order of an unfinished schema its subtree reached. Only a schema whose\n // subtree reached nothing visited before it has a final no-match; until then it waits in `pending`.\n const state = followsRefs ? new Map<SchemaNode, number>() : undefined\n const pending: Array<SchemaNode> = []\n let order = 0\n\n const walkChildren = (current: Node, initial: FindResult): FindResult => {\n let result = initial\n visitChildNodes(current, (child) => {\n const next = walk(child)\n result = next.found || next.low < result.low ? next : result\n return next.found !== undefined\n })\n return result\n }\n\n const walkSchema = (current: SchemaNode): FindResult => {\n const target = state && current.type === 'ref' && current.schema ? walk(current.schema) : notFound\n if (target.found) return target\n return walkChildren(current, target)\n }\n\n const walk = (current: Node): FindResult => {\n if (current.kind !== nodeKinds.schema) return walkChildren(current, notFound)\n\n const cached = cache?.get(current)\n if (cached === null) return notFound\n if (cached) return { found: cached, low: Number.POSITIVE_INFINITY }\n if (predicate(current)) {\n cache?.set(current, current)\n return { found: current, low: Number.POSITIVE_INFINITY }\n }\n const known = state?.get(current)\n if (known !== undefined) return { found: undefined, low: known }\n\n const index = order++\n const start = pending.length\n state?.set(current, index)\n const result = walkSchema(current)\n if (result.found) {\n cache?.set(current, result.found)\n return result\n }\n if (!state) {\n cache?.set(current, null)\n return notFound\n }\n if (result.low < index) {\n state.set(current, result.low)\n pending.push(current)\n return result\n }\n for (const done of [...pending.splice(start), current]) {\n state.set(done, Number.POSITIVE_INFINITY)\n cache?.set(done, null)\n }\n return notFound\n }\n\n return walk(node).found\n}\n\n/**\n * Runs the visitor callback that matches `node.kind` with the traversal\n * context. The result is a replacement node, a collected value, or `undefined`\n * when no callback is registered for the kind.\n *\n * Shared by `transform` and `collect` so node-kind dispatch lives in one place.\n * `TResult` is the caller's expected return: the same node type for `transform`,\n * the collected value type for `collect`.\n */\nfunction applyVisitor<TResult>(node: Node, visitor: Visitor | VisitorOf<unknown>, parent: Node | undefined): TResult | null | undefined {\n const key = VISITOR_KEY_BY_KIND[node.kind]\n if (!key) return undefined\n\n const fn = visitor[key] as ((node: Node, context: VisitorContext) => TResult | null | undefined) | undefined\n\n return fn?.(node, { parent })\n}\n\n/**\n * Synchronous depth-first transform. Each visitor callback can return a\n * replacement node. Returning `undefined` keeps the original.\n *\n * The original tree is never mutated, a new tree is returned. Pass\n * `depth: 'shallow'` to skip the children of every schema node; other nodes are still walked.\n *\n * @example Prefix every operationId\n * ```ts\n * const next = transform(root, {\n * operation(node) {\n * return { ...node, operationId: `prefixed_${node.operationId}` }\n * },\n * })\n * ```\n *\n * @example Rewrite the root node without walking its schemas\n * ```ts\n * const next = transform(root, {\n * depth: 'shallow',\n * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),\n * })\n * ```\n */\nexport function transform<T extends Node>(node: T, options: TransformOptions): T {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? 'deep') === 'deep'\n\n // Split the visitor object out once here, then thread it plus `recurse`/`parent` as plain\n // arguments through the recursion. The previous code re-ran the `...visitor` rest-destructure on\n // every recursive `transform` call and rebuilt a `{ ...options, parent }` object per node, so the\n // options shape (which callbacks are present) varied call to call and the hot recursion churned.\n return transformNode(node, visitor, recurse, parent) as T\n}\n\n/**\n * Visits a single node, then immutably rebuilds its children. Returns the original\n * reference when neither the visitor nor the child rebuild changed anything, so callers\n * can detect \"nothing changed\" by identity and ancestors avoid reallocating.\n */\nfunction transformNode(node: Node, visitor: Visitor, recurse: boolean, parent: Node | undefined): Node {\n const visited = applyVisitor<Node>(node, visitor, parent) ?? node\n return transformChildren(visited, visitor, recurse)\n}\n\n/**\n * Immutably rebuilds a node's children, transforming each child node and leaving non-node values\n * (e.g. `additionalProperties: true`) intact.\n */\nfunction transformChildren(node: Node, visitor: Visitor, recurse: boolean): Node {\n const keys = node.kind === nodeKinds.schema && !recurse ? undefined : VISITOR_KEYS[node.kind]\n if (!keys) return node\n\n const record = node as unknown as Record<string, unknown>\n let updates: Record<string, unknown> | undefined\n // A node under two keys is transformed once, so both keys keep pointing at one node. Leaves never create the map.\n let done: Map<Node, Node> | undefined\n const transformOnce = (child: Node) => {\n done ??= new Map()\n const next = done.get(child) ?? transformNode(child, visitor, recurse, node)\n done.set(child, next)\n return next\n }\n\n for (const key of keys) {\n const value = record[key]\n if (value === undefined || value === null) continue\n if (Array.isArray(value)) {\n // Rebuild the array lazily: allocate a new array only once a child actually changes, copying\n // the unchanged prefix at that point. An unchanged array keeps its original reference and\n // allocates nothing. This also drops the per-array `.map` closure that ran on every node.\n let mapped: Array<unknown> | undefined\n for (const [i, item] of value.entries()) {\n const next = isNode(item) ? transformOnce(item) : item\n if (mapped) {\n mapped.push(next)\n continue\n }\n if (next !== item) mapped = [...value.slice(0, i), next]\n }\n if (mapped) (updates ??= {})[key] = mapped\n continue\n }\n if (isNode(value)) {\n const next = transformOnce(value)\n if (next !== value) (updates ??= {})[key] = next\n continue\n }\n if (isNodeRecord(value)) {\n let mapped: Record<string, unknown> | undefined\n for (const [name, item] of Object.entries(value)) {\n const next = isNode(item) ? transformOnce(item) : item\n if (next !== item) (mapped ??= { ...value })[name] = next\n }\n if (mapped) (updates ??= {})[key] = mapped\n }\n }\n\n if (!updates) return node\n const merged = { ...node, ...updates }\n return merged as Node\n}\n\n/**\n * Depth-first collection pass. Gathers every non-null value the visitor\n * callbacks return into an array.\n *\n * @example Collect every operationId\n * ```ts\n * const ids = collect<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })\n * ```\n */\nexport function collect<T>(node: Node, options: CollectOptions<T>): Array<T> {\n const { depth, parent, ...visitor } = options\n const result: Array<T> = []\n // Plain recursion: draining nested generators costs a `yield*` hop per level for every value.\n collectInto<T>(node, visitor, (depth ?? 'deep') === 'deep', parent, result)\n return result\n}\n\nfunction collectInto<T>(node: Node, visitor: VisitorOf<T>, recurse: boolean, parent: Node | undefined, result: Array<T>): void {\n const v = applyVisitor<T>(node, visitor, parent)\n if (v != null) result.push(v)\n\n if (node.kind === nodeKinds.schema && !recurse) return\n visitChildNodes(node, (child) => {\n collectInto<T>(child, visitor, recurse, node, result)\n return false\n })\n}\n"],"mappings":";;;;;AAIA,SAAgB,gBAAgB,EAAE,WAAsE;CAEtG,IAAI,CAAC,SAAS,UAAU,QAAQ,YAAY,CAAC,QAAQ,WAAW,OAAO,KAAA;CACvE,OAAOA,kBAAAA,OAAO,QAAQ,SAAS,IAAI,QAAQ,SAAS,KAAA;AACtD;;;;;ACeA,MAAM,eAAiE;CACrE,OAAO,CAAC,WAAW,YAAY;CAC/B,WAAW;EAAC;EAAc;EAAe;CAAW;CACpD,aAAa,CAAC,SAAS;CACvB,SAAS,CAAC,UAAU,QAAQ;CAC5B,UAAU,CAAC,WAAW,SAAS;CAC/B,QAAQ;EAAC;EAAc;EAAS;EAAW;EAAwB;EAAqB;EAAiB;CAAM;CAC/G,UAAU,CAAC,QAAQ;CACnB,WAAW,CAAC,QAAQ;AACtB;;;;;AAMA,MAAa,kBAAkB;CAAC;CAAgB;CAAY;AAAS;;AAGrE,MAAa,cAAc;CAAC;CAAS;CAAa;CAAU;CAAY;CAAa;AAAU;;;;AAO/F,MAAM,sBAA6D;CACjE,OAAO;CACP,WAAW;CACX,QAAQ;CACR,UAAU;CACV,WAAW;CACX,UAAU;AACZ;;;;AAkHA,SAAS,OAAO,OAA+B;CAC7C,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAA6B,SAAS;AACtG;;;;AAKA,SAAS,aAAa,OAAkD;CACtE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAGA,SAAS,eAAe,EAAE,MAAM,OAA6C;CAC3E,IAAI,KAAK,SAASC,kBAAAA,UAAU,QAAQ,O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AAA,CAAG,QAAQ;GACvD;GACA,IAAI,QAAQ,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;EACtC;CACF;CAEA,IAAI,CAAC,SAAS,OAAO;CAErB,OAAO;EADU,GAAG;EAAM,GAAG;CACjB;AACd;;;;;;;;;;;;;;AAeA,SAAgB,QAAW,MAAY,SAAsC;CAC3E,MAAM,EAAE,OAAO,QAAQ,GAAG,YAAY;CACtC,MAAM,SAAmB,CAAC;CAE1B,YAAe,MAAM,UAAU,SAAS,YAAY,QAAQ,QAAQ,MAAM;CAC1E,OAAO;AACT;AAEA,SAAS,YAAe,MAAY,SAAuB,SAAkB,QAA0B,QAAwB;CAC7H,MAAM,IAAI,aAAgB,MAAM,SAAS,MAAM;CAC/C,IAAI,KAAK,MAAM,OAAO,KAAK,CAAC;CAE5B,IAAI,KAAK,SAASA,kBAAAA,UAAU,UAAU,CAAC,SAAS;CAChD,gBAAgB,OAAO,UAAU;EAC/B,YAAe,OAAO,SAAS,SAAS,MAAM,MAAM;EACpD,OAAO;CACT,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"visitor-XA0W3OVv.js","names":[],"sources":["../src/schema/embeddedJson.ts","../src/visitor.ts"],"sourcesContent":["import { isJson } from '../mediaType/index.ts'\nimport type { SchemaNode, StringSchemaNode } from '../nodes/schema.ts'\n\n/** The schema of the JSON document a string holds (`contentMediaType` with `contentSchema`), else `undefined`. */\nexport function getEmbeddedJson({ content }: Pick<StringSchemaNode, 'content'>): SchemaNode | undefined {\n // shortcut: an encoded document (`contentEncoding`) is not decoded, so only its encoding is checked; decode it once a spec needs both.\n if (!content?.schema || content.encoding || !content.mediaType) return undefined\n return isJson(content.mediaType) ? content.schema : undefined\n}\n","import { nodeKinds } from './constants.ts'\nimport type { Node } from './nodes/index.ts'\nimport type { InputNode } from './nodes/input.ts'\nimport type { NodeKind } from './nodes/base.ts'\nimport type { OperationNode } from './nodes/operation.ts'\nimport type { ParameterNode } from './nodes/parameter.ts'\nimport type { PropertyNode } from './nodes/property.ts'\nimport type { ResponseNode } from './nodes/response.ts'\nimport type { SchemaNode } from './nodes/schema.ts'\nimport { getEmbeddedJson } from './schema/embeddedJson.ts'\n\n/**\n * Traversal depth for AST visitor utilities.\n *\n * - `'shallow'` recurses through every node except nested `Schema` subtrees, which it treats as\n * leaves: a schema node itself is visited, but its children are not.\n * - `'deep'` recursively visits all descendant nodes, including schema subtrees.\n */\nexport type VisitorDepth = 'shallow' | 'deep'\n\n/**\n * Child node fields per node kind, in traversal order (Babel's `VISITOR_KEYS`).\n */\nconst VISITOR_KEYS: Partial<Record<NodeKind, ReadonlyArray<string>>> = {\n Input: ['schemas', 'operations'],\n Operation: ['parameters', 'requestBody', 'responses'],\n RequestBody: ['content'],\n Content: ['schema', 'stream'],\n Response: ['content', 'headers'],\n Schema: ['properties', 'items', 'members', 'additionalProperties', 'patternProperties', 'propertyNames', 'rest'],\n Property: ['schema'],\n Parameter: ['schema'],\n}\n\n/**\n * Schema fields that hold checks rather than shape: the `conditionals` entries, `contains` and a string's `content`.\n * `transform` and `collect` skip them, and `visitChildNodes` walks them with `checks: true`.\n */\nexport const schemaCheckKeys = ['conditionals', 'contains', 'content'] as const\n\n/** Visitor callback names in traversal order, the keys of {@link Visitor}. */\nexport const visitorKeys = ['input', 'operation', 'schema', 'property', 'parameter', 'response'] as const\n\nexport type VisitorKey = (typeof visitorKeys)[number]\n\n/**\n * Maps a node kind to the matching visitor callback name.\n */\nconst VISITOR_KEY_BY_KIND: Partial<Record<NodeKind, VisitorKey>> = {\n Input: 'input',\n Operation: 'operation',\n Schema: 'schema',\n Property: 'property',\n Parameter: 'parameter',\n Response: 'response',\n}\n\n/**\n * Traversal context passed as the second argument to every visitor callback.\n *\n * @example\n * ```ts\n * const visitor: Visitor = {\n * schema(node, { parent }) {\n * // parent is the node that holds this schema, or undefined at the root\n * },\n * }\n * ```\n */\nexport type VisitorContext = {\n /**\n * Parent node of the currently visited node. For the root node, this is `undefined`.\n */\n parent?: Node\n}\n\n/**\n * Synchronous visitor consumed by `transform`. Each optional callback runs\n * for the matching node type. Return a new node to replace it, or `undefined`\n * to leave it untouched.\n *\n * Plugins typically expose `transformer` so users can supply a `Visitor` that\n * rewrites the AST before printing.\n *\n * @example Prefix every operationId\n * ```ts\n * const visitor: Visitor = {\n * operation(node) {\n * return { ...node, operationId: `api_${node.operationId}` }\n * },\n * }\n * ```\n *\n * @example Strip schema descriptions\n * ```ts\n * const visitor: Visitor = {\n * schema(node) {\n * return { ...node, description: undefined }\n * },\n * }\n * ```\n */\nexport type Visitor = {\n input?(node: InputNode, context: VisitorContext): undefined | null | InputNode\n operation?(node: OperationNode, context: VisitorContext): undefined | null | OperationNode\n schema?(node: SchemaNode, context: VisitorContext): undefined | null | SchemaNode\n property?(node: PropertyNode, context: VisitorContext): undefined | null | PropertyNode\n parameter?(node: ParameterNode, context: VisitorContext): undefined | null | ParameterNode\n response?(node: ResponseNode, context: VisitorContext): undefined | null | ResponseNode\n}\n\n/**\n * The callbacks of {@link Visitor} with every return type replaced by `TResult`. `collect` uses it\n * so a visitor can yield values instead of replacement nodes.\n *\n * @example\n * ```ts\n * const visitor: VisitorOf<string> = {\n * operation(node) {\n * return node.operationId\n * },\n * }\n * ```\n */\ntype VisitorOf<TResult> = {\n [K in keyof Visitor]?: (node: Parameters<NonNullable<Visitor[K]>>[0], context: Parameters<NonNullable<Visitor[K]>>[1]) => TResult | null | undefined\n}\n\ntype TraversalOptions = {\n /**\n * Traversal depth.\n * @default 'deep'\n */\n depth?: VisitorDepth\n /**\n * Internal parent override used during recursion.\n */\n parent?: Node\n}\n\n/**\n * Options for `transform`.\n *\n * @example\n * ```ts\n * const options: TransformOptions = { depth: 'deep', schema: (node) => node }\n * ```\n *\n * @example\n * ```ts\n * // Only transform the current node, not nested children\n * const options: TransformOptions = { depth: 'shallow', schema: (node) => node }\n * ```\n */\ntype TransformOptions = Visitor & TraversalOptions\n\n/**\n * Options for `collect`.\n *\n * @example\n * ```ts\n * const options: CollectOptions<string> = { depth: 'shallow', schema: () => undefined }\n * ```\n */\ntype CollectOptions<T> = VisitorOf<T> & TraversalOptions\n\n/**\n * Returns `true` when `value` is an AST node (an object carrying a `kind`).\n */\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && typeof (value as { kind?: unknown }).kind === 'string'\n}\n\n/**\n * Returns `true` for a plain object that maps names to nodes, such as `patternProperties`.\n */\nfunction isNodeRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// A check no printer emits: a `contains` that any array meets (`min: 0`, no `max`), or `content` that is not JSON.\nfunction isNeverPrinted({ node, key }: { node: Node; key: string }): boolean {\n if (node.kind !== nodeKinds.schema) return false\n if (key === 'contains' && (node.type === 'array' || node.type === 'tuple')) return node.contains?.min === 0 && node.contains.max === undefined\n if (key === 'content' && node.type === 'string') return !getEmbeddedJson(node)\n return false\n}\n\n/**\n * Child keys of a schema walked with `checks: true`: the shape keys, then {@link schemaCheckKeys}.\n */\nconst SCHEMA_CHECK_VISITOR_KEYS: ReadonlyArray<string> = [...VISITOR_KEYS.Schema!, ...schemaCheckKeys]\n\n/**\n * Children a node already passed to `visit`. A node under two keys, such as a stream item under `schema` and\n * `stream`, is visited once. The `Set` is only created once a node has a second child.\n */\ntype SeenChildren = { first: Node | undefined; rest: Set<Node> | undefined }\n\nfunction visitOnce(child: Node, seen: SeenChildren, visit: (child: Node) => boolean): boolean {\n if (seen.first === undefined) {\n seen.first = child\n return visit(child)\n }\n if (seen.first === child || seen.rest?.has(child)) return false\n ;(seen.rest ??= new Set()).add(child)\n return visit(child)\n}\n\nfunction visitRecord(value: Record<string, unknown>, seen: SeenChildren, visit: (child: Node) => boolean): boolean {\n for (const name in value) {\n if (!Object.hasOwn(value, name)) continue\n const item = value[name]\n if (isNode(item) && visitOnce(item, seen, visit)) return true\n }\n return false\n}\n\n/**\n * Calls `visit` for each direct child node and stops at the first call that returns `true`.\n * With `checks: true`, a schema's {@link schemaCheckKeys} fields are walked too, except checks that cannot fail.\n */\nexport function visitChildNodes(node: Node, visit: (child: Node) => boolean, { checks = false }: { checks?: boolean } = {}): boolean {\n const withChecks = checks && node.kind === nodeKinds.schema\n const keys = withChecks ? SCHEMA_CHECK_VISITOR_KEYS : VISITOR_KEYS[node.kind]\n if (!keys) return false\n\n const record = node as unknown as Record<string, unknown>\n let seen: SeenChildren | undefined\n for (const key of keys) {\n const value = record[key]\n if (value === undefined || value === null) continue\n if (withChecks && isNeverPrinted({ node, key })) continue\n seen ??= { first: undefined, rest: undefined }\n if (Array.isArray(value)) {\n // Items can be plain objects that hold nodes, such as the `{ if, then, else }` entries of `conditionals`.\n for (const item of value) if (isNode(item) ? visitOnce(item, seen, visit) : isNodeRecord(item) && visitRecord(item, seen, visit)) return true\n continue\n }\n if (isNode(value)) {\n if (visitOnce(value, seen, visit)) return true\n continue\n }\n if (isNodeRecord(value) && visitRecord(value, seen, visit)) return true\n }\n return false\n}\n\ntype FindResult = { found: SchemaNode | undefined; low: number }\n\nconst notFound: FindResult = { found: undefined, low: Number.POSITIVE_INFINITY }\n\n/**\n * Finds the first schema that matches `predicate` in depth-first order. Pass `follow: ['ref']` to include resolved ref targets.\n *\n * @example\n * ```ts\n * const firstString = findSchema(operationNode, {\n * predicate: (schema) => schema.type === 'string',\n * })\n * ```\n */\nexport function findSchema(\n node: Node,\n {\n predicate,\n follow,\n followRefs = false,\n cache,\n }: {\n predicate: (schema: SchemaNode) => boolean\n /**\n * Links to follow on top of the walk over every child. `['ref']` also walks a resolved ref's target.\n * @default []\n */\n follow?: ReadonlyArray<'ref'>\n /**\n * @deprecated Use `follow: ['ref']`. Removed in Kubb v6.\n */\n followRefs?: boolean\n /**\n * Remembers the match below each schema (`null` for none), so later calls skip the parts of the graph they share.\n * Keep one cache per `predicate` and ref-following mode (`follow`, or the deprecated `followRefs`), for example one per build.\n * In a cyclic graph, a cached call can return a different match than the first one in depth-first order.\n */\n cache?: WeakMap<SchemaNode, SchemaNode | null>\n },\n): SchemaNode | undefined {\n const followsRefs = followRefs || (follow?.includes('ref') ?? false)\n // When following refs, as in Tarjan's algorithm: the visit order of a schema still being walked, or for a finished\n // schema without a match the lowest visit order of an unfinished schema its subtree reached. Only a schema whose\n // subtree reached nothing visited before it has a final no-match; until then it waits in `pending`.\n const state = followsRefs ? new Map<SchemaNode, number>() : undefined\n const pending: Array<SchemaNode> = []\n let order = 0\n\n const walkChildren = (current: Node, initial: FindResult): FindResult => {\n let result = initial\n visitChildNodes(current, (child) => {\n const next = walk(child)\n result = next.found || next.low < result.low ? next : result\n return next.found !== undefined\n })\n return result\n }\n\n const walkSchema = (current: SchemaNode): FindResult => {\n const target = state && current.type === 'ref' && current.schema ? walk(current.schema) : notFound\n if (target.found) return target\n return walkChildren(current, target)\n }\n\n const walk = (current: Node): FindResult => {\n if (current.kind !== nodeKinds.schema) return walkChildren(current, notFound)\n\n const cached = cache?.get(current)\n if (cached === null) return notFound\n if (cached) return { found: cached, low: Number.POSITIVE_INFINITY }\n if (predicate(current)) {\n cache?.set(current, current)\n return { found: current, low: Number.POSITIVE_INFINITY }\n }\n const known = state?.get(current)\n if (known !== undefined) return { found: undefined, low: known }\n\n const index = order++\n const start = pending.length\n state?.set(current, index)\n const result = walkSchema(current)\n if (result.found) {\n cache?.set(current, result.found)\n return result\n }\n if (!state) {\n cache?.set(current, null)\n return notFound\n }\n if (result.low < index) {\n state.set(current, result.low)\n pending.push(current)\n return result\n }\n for (const done of [...pending.splice(start), current]) {\n state.set(done, Number.POSITIVE_INFINITY)\n cache?.set(done, null)\n }\n return notFound\n }\n\n return walk(node).found\n}\n\n/**\n * Runs the visitor callback that matches `node.kind` with the traversal\n * context. The result is a replacement node, a collected value, or `undefined`\n * when no callback is registered for the kind.\n *\n * Shared by `transform` and `collect` so node-kind dispatch lives in one place.\n * `TResult` is the caller's expected return: the same node type for `transform`,\n * the collected value type for `collect`.\n */\nfunction applyVisitor<TResult>(node: Node, visitor: Visitor | VisitorOf<unknown>, parent: Node | undefined): TResult | null | undefined {\n const key = VISITOR_KEY_BY_KIND[node.kind]\n if (!key) return undefined\n\n const fn = visitor[key] as ((node: Node, context: VisitorContext) => TResult | null | undefined) | undefined\n\n return fn?.(node, { parent })\n}\n\n/**\n * Synchronous depth-first transform. Each visitor callback can return a\n * replacement node. Returning `undefined` keeps the original.\n *\n * The original tree is never mutated, a new tree is returned. Pass\n * `depth: 'shallow'` to skip the children of every schema node; other nodes are still walked.\n *\n * @example Prefix every operationId\n * ```ts\n * const next = transform(root, {\n * operation(node) {\n * return { ...node, operationId: `prefixed_${node.operationId}` }\n * },\n * })\n * ```\n *\n * @example Rewrite the root node without walking its schemas\n * ```ts\n * const next = transform(root, {\n * depth: 'shallow',\n * input: (node) => ({ ...node, meta: { ...node.meta, title: 'Rewritten' } }),\n * })\n * ```\n */\nexport function transform<T extends Node>(node: T, options: TransformOptions): T {\n const { depth, parent, ...visitor } = options\n const recurse = (depth ?? 'deep') === 'deep'\n\n // Split the visitor object out once here, then thread it plus `recurse`/`parent` as plain\n // arguments through the recursion. The previous code re-ran the `...visitor` rest-destructure on\n // every recursive `transform` call and rebuilt a `{ ...options, parent }` object per node, so the\n // options shape (which callbacks are present) varied call to call and the hot recursion churned.\n return transformNode(node, visitor, recurse, parent) as T\n}\n\n/**\n * Visits a single node, then immutably rebuilds its children. Returns the original\n * reference when neither the visitor nor the child rebuild changed anything, so callers\n * can detect \"nothing changed\" by identity and ancestors avoid reallocating.\n */\nfunction transformNode(node: Node, visitor: Visitor, recurse: boolean, parent: Node | undefined): Node {\n const visited = applyVisitor<Node>(node, visitor, parent) ?? node\n return transformChildren(visited, visitor, recurse)\n}\n\n/**\n * Immutably rebuilds a node's children, transforming each child node and leaving non-node values\n * (e.g. `additionalProperties: true`) intact.\n */\nfunction transformChildren(node: Node, visitor: Visitor, recurse: boolean): Node {\n const keys = node.kind === nodeKinds.schema && !recurse ? undefined : VISITOR_KEYS[node.kind]\n if (!keys) return node\n\n const record = node as unknown as Record<string, unknown>\n let updates: Record<string, unknown> | undefined\n // A node under two keys is transformed once, so both keys keep pointing at one node. Leaves never create the map.\n let done: Map<Node, Node> | undefined\n const transformOnce = (child: Node) => {\n done ??= new Map()\n const next = done.get(child) ?? transformNode(child, visitor, recurse, node)\n done.set(child, next)\n return next\n }\n\n for (const key of keys) {\n const value = record[key]\n if (value === undefined || value === null) continue\n if (Array.isArray(value)) {\n // Rebuild the array lazily: allocate a new array only once a child actually changes, copying\n // the unchanged prefix at that point. An unchanged array keeps its original reference and\n // allocates nothing. This also drops the per-array `.map` closure that ran on every node.\n let mapped: Array<unknown> | undefined\n for (const [i, item] of value.entries()) {\n const next = isNode(item) ? transformOnce(item) : item\n if (mapped) {\n mapped.push(next)\n continue\n }\n if (next !== item) mapped = [...value.slice(0, i), next]\n }\n if (mapped) (updates ??= {})[key] = mapped\n continue\n }\n if (isNode(value)) {\n const next = transformOnce(value)\n if (next !== value) (updates ??= {})[key] = next\n continue\n }\n if (isNodeRecord(value)) {\n let mapped: Record<string, unknown> | undefined\n for (const [name, item] of Object.entries(value)) {\n const next = isNode(item) ? transformOnce(item) : item\n if (next !== item) (mapped ??= { ...value })[name] = next\n }\n if (mapped) (updates ??= {})[key] = mapped\n }\n }\n\n if (!updates) return node\n const merged = { ...node, ...updates }\n return merged as Node\n}\n\n/**\n * Depth-first collection pass. Gathers every non-null value the visitor\n * callbacks return into an array.\n *\n * @example Collect every operationId\n * ```ts\n * const ids = collect<string>(root, {\n * operation(node) {\n * return node.operationId\n * },\n * })\n * ```\n */\nexport function collect<T>(node: Node, options: CollectOptions<T>): Array<T> {\n const { depth, parent, ...visitor } = options\n const result: Array<T> = []\n // Plain recursion: draining nested generators costs a `yield*` hop per level for every value.\n collectInto<T>(node, visitor, (depth ?? 'deep') === 'deep', parent, result)\n return result\n}\n\nfunction collectInto<T>(node: Node, visitor: VisitorOf<T>, recurse: boolean, parent: Node | undefined, result: Array<T>): void {\n const v = applyVisitor<T>(node, visitor, parent)\n if (v != null) result.push(v)\n\n if (node.kind === nodeKinds.schema && !recurse) return\n visitChildNodes(node, (child) => {\n collectInto<T>(child, visitor, recurse, node, result)\n return false\n })\n}\n"],"mappings":";;;;;AAIA,SAAgB,gBAAgB,EAAE,WAAsE;CAEtG,IAAI,CAAC,SAAS,UAAU,QAAQ,YAAY,CAAC,QAAQ,WAAW,OAAO,KAAA;CACvE,OAAO,OAAO,QAAQ,SAAS,IAAI,QAAQ,SAAS,KAAA;AACtD;;;;;ACeA,MAAM,eAAiE;CACrE,OAAO,CAAC,WAAW,YAAY;CAC/B,WAAW;EAAC;EAAc;EAAe;CAAW;CACpD,aAAa,CAAC,SAAS;CACvB,SAAS,CAAC,UAAU,QAAQ;CAC5B,UAAU,CAAC,WAAW,SAAS;CAC/B,QAAQ;EAAC;EAAc;EAAS;EAAW;EAAwB;EAAqB;EAAiB;CAAM;CAC/G,UAAU,CAAC,QAAQ;CACnB,WAAW,CAAC,QAAQ;AACtB;;;;;AAMA,MAAa,kBAAkB;CAAC;CAAgB;CAAY;AAAS;;AAGrE,MAAa,cAAc;CAAC;CAAS;CAAa;CAAU;CAAY;CAAa;AAAU;;;;AAO/F,MAAM,sBAA6D;CACjE,OAAO;CACP,WAAW;CACX,QAAQ;CACR,UAAU;CACV,WAAW;CACX,UAAU;AACZ;;;;AAkHA,SAAS,OAAO,OAA+B;CAC7C,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAQ,MAA6B,SAAS;AACtG;;;;AAKA,SAAS,aAAa,OAAkD;CACtE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAGA,SAAS,eAAe,EAAE,MAAM,OAA6C;CAC3E,IAAI,KAAK,SAAS,UAAU,QAAQ,OAAO;CAC3C,IAAI,QAAQ,eAAe,KAAK,SAAS,WAAW,KAAK,SAAS,UAAU,OAAO,KAAK,UAAU,QAAQ,KAAK,KAAK,SAAS,QAAQ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