@kubb/ast 5.25.0 → 5.25.1
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/dist/{file-3gsgXreK.js → combineFileMembers-DJHNAZBN.js} +204 -161
- package/dist/combineFileMembers-DJHNAZBN.js.map +1 -0
- package/dist/{file-D73XubVb.cjs → combineFileMembers-DmmuOmY8.cjs} +216 -160
- package/dist/combineFileMembers-DmmuOmY8.cjs.map +1 -0
- package/dist/factory.cjs +6 -6
- package/dist/factory.d.cts +2 -2
- package/dist/factory.d.ts +2 -2
- package/dist/factory.js +2 -2
- package/dist/{file-CMHRNuMX.d.cts → file-DJqd2j3y.d.cts} +3 -1
- package/dist/{file-D67ITWja.d.ts → file-Dg70hXm3.d.ts} +3 -1
- package/dist/{file-1YtTOZeL.js → file-HwCmj--S.js} +5 -3
- package/dist/file-HwCmj--S.js.map +1 -0
- package/dist/{file-azmmZwDb.cjs → file-z3xToonr.cjs} +11 -9
- package/dist/file-z3xToonr.cjs.map +1 -0
- package/dist/file.cjs +7 -5
- package/dist/file.d.cts +2 -2
- package/dist/file.d.ts +2 -2
- package/dist/file.js +3 -3
- package/dist/{index-DNZgWmNq.d.cts → index-BjmAaymt.d.cts} +1 -1
- package/dist/{index-CIUD99Ft.d.ts → index-Br4bwEnS.d.ts} +2 -2
- package/dist/{index-CGmrJThc.d.ts → index-Bz33tfQo.d.ts} +1 -1
- package/dist/{index-Bcxj7FqZ.d.cts → index-C5SXJAtZ.d.cts} +2 -2
- package/dist/{index-bkTCYnZj.d.cts → index-CCUB1hoV.d.cts} +1 -1
- package/dist/{index-C-nsgwuD.d.ts → index-D3yqgtiN.d.ts} +2 -2
- package/dist/{index-84453BaS.d.cts → index-DBKL6vyC.d.cts} +16 -3
- package/dist/{index-BvdIGsVr.d.cts → index-DNDNDzyJ.d.cts} +2 -2
- package/dist/{index-C7U9EiIP.d.ts → index-DXdwkq7X.d.ts} +2 -2
- package/dist/{index-B3o1AkNE.d.ts → index-MzcNxet1.d.ts} +1 -1
- package/dist/{index-DR9ahJ-x.d.cts → index-OfWkiJ5O.d.cts} +2 -2
- package/dist/{index-BFwAhPp8.d.ts → index-VPq6RwTm.d.ts} +16 -3
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/macro-3uGSg-ic.js.map +1 -1
- package/dist/macro-Ywn4-0s5.cjs.map +1 -1
- package/dist/macro.d.cts +1 -1
- package/dist/macro.d.ts +1 -1
- package/dist/mediaType-BbIfudh0.cjs.map +1 -1
- package/dist/mediaType-DXQCNYdM.js.map +1 -1
- package/dist/mediaType.d.cts +2 -2
- package/dist/mediaType.d.ts +2 -2
- package/dist/node.d.cts +2 -2
- package/dist/node.d.ts +2 -2
- package/dist/{nodes-BdZfapPI.cjs → nodes-TtDfZ9qf.cjs} +12 -12
- package/dist/{nodes-BdZfapPI.cjs.map → nodes-TtDfZ9qf.cjs.map} +1 -1
- package/dist/{nodes-D9nwroV5.js → nodes-u9i-tqFp.js} +2 -2
- package/dist/{nodes-D9nwroV5.js.map → nodes-u9i-tqFp.js.map} +1 -1
- package/dist/promise-B3YkZ4C8.js.map +1 -1
- package/dist/promise-DScaykew.cjs.map +1 -1
- package/dist/schema-0YJZqRXb.cjs.map +1 -1
- package/dist/schema-BvUrXIoX.js.map +1 -1
- package/dist/schema-CC008xgK.js.map +1 -1
- package/dist/schema-DfLGJ-oh.cjs.map +1 -1
- package/dist/schema.d.cts +2 -2
- package/dist/schema.d.ts +2 -2
- package/dist/{visitor-VYLe7Q4m.d.cts → visitor-BN5QJX7-.d.cts} +1 -1
- package/dist/{visitor-CqI8T9Qa.d.ts → visitor-BNGMMmpe.d.ts} +1 -1
- package/dist/visitor-DA5yfOJz.js.map +1 -1
- package/dist/visitor-DhuKS-7x.cjs.map +1 -1
- package/package.json +1 -1
- package/dist/file-1YtTOZeL.js.map +0 -1
- package/dist/file-3gsgXreK.js.map +0 -1
- package/dist/file-D73XubVb.cjs.map +0 -1
- package/dist/file-azmmZwDb.cjs.map +0 -1
package/dist/schema.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as schemaTypes } from "./base-A-xF4pUL.js";
|
|
2
2
|
import { n as narrowSchema } from "./guards-l2AsKeHR.js";
|
|
3
|
-
import { a as resolveSchemaProperties, c as SchemaKind, d as applyOptionality, i as inferDiscriminatorPropertyName, l as is, n as isString, o as IsOptions, r as getSchemaLiteralValues, s as SchemaFollow, u as getEmbeddedJson } from "./index-
|
|
4
|
-
import { o as findSchema } from "./visitor-
|
|
3
|
+
import { a as resolveSchemaProperties, c as SchemaKind, d as applyOptionality, i as inferDiscriminatorPropertyName, l as is, n as isString, o as IsOptions, r as getSchemaLiteralValues, s as SchemaFollow, u as getEmbeddedJson } from "./index-MzcNxet1.js";
|
|
4
|
+
import { o as findSchema } from "./visitor-BNGMMmpe.js";
|
|
5
5
|
export { type IsOptions, type SchemaFollow, type SchemaKind, applyOptionality, findSchema as find, resolveSchemaProperties as findProperties, getEmbeddedJson, getSchemaLiteralValues as getLiterals, inferDiscriminatorPropertyName as inferDiscriminator, is, isString, narrowSchema as narrow, schemaTypes as types };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Node } from "./index-
|
|
1
|
+
import { t as Node } from "./index-BjmAaymt.cjs";
|
|
2
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.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Node } from "./index-
|
|
1
|
+
import { t as Node } from "./index-Bz33tfQo.js";
|
|
2
2
|
import { $ as PropertyNode, D as InputNode, G as SchemaNode, h as ParameterNode, i as OperationNode, l as ResponseNode } from "./operation-Dd0-l2VB.js";
|
|
3
3
|
/**
|
|
4
4
|
* Traversal depth for AST visitor utilities.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"visitor-DA5yfOJz.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 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,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,YAAY,CAAC,YAAY;CACzB,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;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":["../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 */\nconst 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 */\nexport type VisitorOf<TResult> = {\n [K in keyof Visitor]?: (node: Parameters<NonNullable<Visitor[K]>>[0], context: Parameters<NonNullable<Visitor[K]>>[1]) => TResult | null | undefined\n}\n\nexport type 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 */\nexport type 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 */\nexport type 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,YAAY,CAAC,YAAY;CACzB,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,MAAM,kBAAkB;CAAC;CAAgB;CAAY;AAAS;;AAG9D,MAAa,cA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AAI,QAAQ,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;GACpC;EACF;EACA,IAAI,OAAO,KAAK,GAAG;GACjB,MAAM,OAAO,cAAc,KAAK;GAChC,IAAI,SAAS,OAAO,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;GAC5C;EACF;EACA,IAAI,aAAa,KAAK,GAAG;GACvB,IAAI;GACJ,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,GAAG;IAChD,MAAM,OAAO,OAAO,IAAI,IAAI,cAAc,IAAI,IAAI;IAClD,IAAI,SAAS,MAAM,CAAC,WAAW,EAAE,GAAG,MAAM,EAAA,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,SAAS,UAAU,UAAU,CAAC,SAAS;CAChD,gBAAgB,OAAO,UAAU;EAC/B,YAAe,OAAO,SAAS,SAAS,MAAM,MAAM;EACpD,OAAO;CACT,CAAC;AACH"}
|
|
@@ -1 +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,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,YAAY,CAAC,YAAY;CACzB,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,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EACF;EACA,IAAI,OAAO,KAAK,GAAG;GACjB,MAAM,OAAO,cAAc,KAAK;GAChC,IAAI,SAAS,OAAO,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;GAC5C;EACF;EACA,IAAI,aAAa,KAAK,GAAG;GACvB,IAAI;GACJ,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,GAAG;IAChD,MAAM,OAAO,OAAO,IAAI,IAAI,cAAc,IAAI,IAAI;IAClD,IAAI,SAAS,MAAM,CAAC,WAAW,EAAE,GAAG,MAAM,EAAA,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
|
+
{"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 */\nconst 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 */\nexport type VisitorOf<TResult> = {\n [K in keyof Visitor]?: (node: Parameters<NonNullable<Visitor[K]>>[0], context: Parameters<NonNullable<Visitor[K]>>[1]) => TResult | null | undefined\n}\n\nexport type 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 */\nexport type 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 */\nexport type 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,YAAY,CAAC,YAAY;CACzB,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,MAAM,kBAAkB;CAAC;CAAgB;CAAY;AAAS;;AAG9D,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;;;;AAk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GAChC,IAAI,SAAS,OAAO,CAAC,YAAY,CAAC,EAAA,CAAG,OAAO;GAC5C;EACF;EACA,IAAI,aAAa,KAAK,GAAG;GACvB,IAAI;GACJ,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,KAAK,GAAG;IAChD,MAAM,OAAO,OAAO,IAAI,IAAI,cAAc,IAAI,IAAI;IAClD,IAAI,SAAS,MAAM,CAAC,WAAW,EAAE,GAAG,MAAM,EAAA,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"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"file-1YtTOZeL.js","names":[],"sources":["../src/utils/inline.ts","../src/file/index.ts"],"sourcesContent":["import { nodeKinds } from '../constants.ts'\nimport type { CodeNode } from '../nodes/code.ts'\nimport { createFile, createImport } from '../nodes/file.ts'\nimport type { FileNode, ImportNode, SourceNode } from '../nodes/file.ts'\nimport { getNames } from './moduleNames.ts'\nimport { CODE_NODE_TEXT_FIELDS, getNodeText } from './nodeText.ts'\n\ntype InlineFilesResult = {\n /**\n * Files that imported an inline name, rewritten to hold its definition.\n */\n files: Array<FileNode>\n /**\n * Paths of the virtual files, which are not written.\n */\n virtualPaths: Array<string>\n /**\n * One message per name that could not be inlined.\n */\n problems: Array<{ path: string; message: string }>\n}\n\ntype Definition = { expression: string; imports: Array<ImportNode> }\n\n/**\n * The language-specific half of {@link inlineFiles}, supplied by the parser that prints the file.\n */\nexport type InlineLanguage = {\n /**\n * Swaps in what `replace` returns for every identifier in `text` that references a name, skipping strings and comments.\n */\n replaceIdentifiers(text: string, replace: (name: string) => string | undefined): string\n /**\n * Makes `expression` safe to put where a name was, such as `(A | B)` in TypeScript.\n */\n wrap(expression: string): string\n}\n\ntype InlineFilesOptions = {\n /**\n * The inline support for a file's language, or `undefined` when it has none.\n */\n language: (file: FileNode) => InlineLanguage | undefined\n}\n\n/**\n * Replaces every name a file imports from a virtual file (one marked `inline`, so it is never written) with the body of that name's\n * declaration, until no inline names are left. The definitions' own imports move to the importing file.\n */\nexport function inlineFiles(files: ReadonlyArray<FileNode>, { language }: InlineFilesOptions): InlineFilesResult {\n const virtualFiles = new Map(files.filter(isInlineFile).map((file) => [file.path, file]))\n const result: InlineFilesResult = { files: [], virtualPaths: [...virtualFiles.keys()], problems: [] }\n if (virtualFiles.size === 0) return result\n\n // `null` marks a definition that is being resolved, so a name that reaches itself is a cycle.\n const definitions = new Map<string, Definition | null>()\n\n function define(path: string, name: string, from: string, lang: InlineLanguage): Definition | undefined {\n const key = `${path}\\0${name}`\n if (definitions.has(key)) {\n const definition = definitions.get(key)\n if (definition === null) result.problems.push({ path: from, message: `\"${name}\" from \"${path}\" is defined in terms of itself.` })\n return definition ?? undefined\n }\n\n const file = virtualFiles.get(path)!\n const expression = bodyOf(file.sources.find((source) => source.name === name))\n if (expression === undefined) {\n result.problems.push({ path: from, message: `\"${name}\" is imported from \"${path}\", which never writes it and has no inline definition for it.` })\n return undefined\n }\n\n definitions.set(key, null)\n const imports: Array<ImportNode> = []\n const { text, used } = replaceNames(expression, file, lang, imports)\n imports.push(...file.imports.flatMap((imp) => (virtualFiles.has(imp.path) ? [] : pickNames(imp, used))))\n\n const definition = { expression: text, imports }\n definitions.set(key, definition)\n return definition\n }\n\n // Pushes the imports the replaced definitions need onto `imports`; `used` holds the names left as they are.\n function replaceNames(input: string, file: FileNode, lang: InlineLanguage, imports: Array<ImportNode>) {\n const used = new Set<string>()\n const text = lang.replaceIdentifiers(input, (local) => {\n const target = findTarget(file, local)\n const definition = target && define(target.path, target.name, file.path, lang)\n if (!definition) {\n used.add(local)\n return undefined\n }\n\n imports.push(...definition.imports)\n return lang.wrap(definition.expression)\n })\n\n return { text, used }\n }\n\n function findTarget(file: FileNode, local: string): { path: string; name: string } | undefined {\n if (virtualFiles.has(file.path) && file.sources.some((source) => source.name === local)) return { path: file.path, name: local }\n\n for (const imp of file.imports) {\n const item = virtualFiles.has(imp.path) && getNames(imp).find((item) => (item.alias ?? item.name) === local)\n if (item) return { path: imp.path, name: item.name }\n }\n\n return undefined\n }\n\n for (const file of files) {\n if (virtualFiles.has(file.path) || !file.imports.some((imp) => virtualFiles.has(imp.path))) continue\n\n const lang = language(file)\n if (!lang) {\n result.problems.push({ path: file.path, message: `No parser for \"${file.extname}\" files supports inline sources.` })\n continue\n }\n\n const carried: Array<ImportNode> = []\n const sources = file.sources.map((source) => ({ ...source, nodes: rewriteNodes(source.nodes, (text) => replaceNames(text, file, lang, carried).text) }))\n\n // A carried import keeps its target; `root` moves to the importing file so the relative path is computed from there.\n const imports = [...file.imports.filter((imp) => !virtualFiles.has(imp.path)), ...carried.map((imp) => (imp.root ? { ...imp, root: file.path } : imp))]\n\n result.files.push(createFile({ ...file, sources, imports }))\n }\n\n return result\n}\n\n// A file of only deprecated per-source `inline` counts as inline too.\nfunction isInlineFile(file: FileNode): boolean {\n return !!file.inline || (file.sources.length > 0 && file.sources.every((source) => source.inline))\n}\n\n// The right-hand side of a `Const` or `Type`. A function body is not an expression, and printed text such as `Code` has none.\nfunction bodyOf(source: SourceNode | undefined): string | undefined {\n if (source?.inline) return source.inline.expression\n const node = source?.nodes?.length === 1 ? source.nodes[0] : undefined\n if (node?.kind !== nodeKinds.const && node?.kind !== nodeKinds.type) return undefined\n return getNodeText(node.nodes) || undefined\n}\n\nfunction pickNames(imp: ImportNode, used: ReadonlySet<string>): Array<ImportNode> {\n const names = getNames(imp).filter((item) => used.has(item.alias ?? item.name))\n return names.length > 0 ? [createImport({ path: imp.path, ...(imp.root != null ? { root: imp.root } : {}), names })] : []\n}\n\n// Rewrites the string fields `getNodeText` reads; JSDoc stays as written.\nfunction rewriteNodes(nodes: Array<CodeNode> | undefined, rewrite: (text: string) => string): Array<CodeNode> | undefined {\n return nodes?.map((node): CodeNode => {\n // Backward-compat: compiled plugins may still pass bare strings at runtime\n if (typeof node === 'string') return rewrite(node) as unknown as CodeNode\n if (node.kind === nodeKinds.break) return node\n\n const next = { ...node } as unknown as Record<string, unknown>\n for (const field of CODE_NODE_TEXT_FIELDS[node.kind] ?? []) {\n const value = next[field]\n if (Array.isArray(value)) next[field] = value.map(rewrite)\n if (typeof value === 'string' && value) next[field] = rewrite(value)\n }\n if ('nodes' in node && node.nodes) next.nodes = rewriteNodes(node.nodes, rewrite)\n return next as unknown as CodeNode\n })\n}\n","export { inlineFiles as inline } from '../utils/inline.ts'\nexport { getNames, getSpace } from '../utils/moduleNames.ts'\n"],"mappings":";;;;;;;;;AAiDA,SAAgB,YAAY,OAAgC,EAAE,YAAmD;CAC/G,MAAM,eAAe,IAAI,IAAI,MAAM,OAAO,YAAY,CAAC,CAAC,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;CACxF,MAAM,SAA4B;EAAE,OAAO,CAAC;EAAG,cAAc,CAAC,GAAG,aAAa,KAAK,CAAC;EAAG,UAAU,CAAC;CAAE;CACpG,IAAI,aAAa,SAAS,GAAG,OAAO;CAGpC,MAAM,8BAAc,IAAI,IA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sgXreK.js","names":[],"sources":["../src/utils/moduleNames.ts","../src/utils/combineFileMembers.ts","../src/nodes/base.ts","../src/nodes/file.ts"],"sourcesContent":["import type { ExportNode, ImportNode, ModuleName, SourceNode, Space } from '../nodes/file.ts'\n\n/**\n * Returns the names an import or export brings across. A node built with the deprecated fields gets them from\n * those, each with an explicit `space`, so it prints exactly as before.\n */\nexport function getNames(node: ImportNode | ExportNode): Array<ModuleName> {\n if (node.names) return node.names\n return node.kind === 'Import' ? fromDeprecatedImport(node) : fromDeprecatedExport(node)\n}\n\nexport function getSpace(source: SourceNode): Space {\n if (source.space) return source.space\n if (source.isTypeOnly != null) return source.isTypeOnly ? 'type' : 'value'\n return source.nodes?.[0]?.kind === 'Type' ? 'type' : 'value'\n}\n\ntype DeprecatedImport = Pick<ImportNode, 'name' | 'isTypeOnly' | 'isNameSpace'>\ntype DeprecatedExport = Pick<ExportNode, 'name' | 'isTypeOnly' | 'asAlias'>\n\n/**\n * @deprecated Converts a node built with `name`, `isTypeOnly` and `isNameSpace` to `names`. Removed in Kubb v6.\n */\nexport function fromDeprecatedImport({ name, isTypeOnly, isNameSpace }: DeprecatedImport): Array<ModuleName> {\n const space: Space = isTypeOnly ? 'type' : 'value'\n if (!Array.isArray(name)) return [{ name: isNameSpace ? '*' : 'default', alias: name, space }]\n return name.map((item) => (typeof item === 'string' ? { name: item, space } : { name: item.propertyName, ...(item.name ? { alias: item.name } : {}), space }))\n}\n\n/**\n * @deprecated Converts a node built with `name`, `isTypeOnly` and `asAlias` to `names`. Removed in Kubb v6.\n */\nexport function fromDeprecatedExport({ name, isTypeOnly, asAlias }: DeprecatedExport): Array<ModuleName> {\n const space: Space = isTypeOnly ? 'type' : 'value'\n if (name == null) return [{ name: '*', space }]\n if (!Array.isArray(name)) return [asAlias ? { name: '*', alias: name, space } : { name, space }]\n return name.map((item) => ({ name: item, space }))\n}\n\n/**\n * @deprecated The old import fields for `names`, for code that still reads them. Removed in Kubb v6.\n */\nexport function toDeprecatedImport(names: ReadonlyArray<ModuleName>): DeprecatedImport {\n const isTypeOnly = names.length > 0 && names.every((item) => item.space === 'type')\n const [first] = names\n if (names.length === 1 && first?.alias && (first.name === '*' || first.name === 'default')) {\n return { name: first.alias, isTypeOnly, isNameSpace: first.name === '*' }\n }\n return { name: names.map((item) => (item.alias ? { propertyName: item.name, name: item.alias } : item.name)), isTypeOnly, isNameSpace: false }\n}\n\n/**\n * @deprecated The old export fields for `names`; an alias stands in for its name. Removed in Kubb v6.\n */\nexport function toDeprecatedExport(names: ReadonlyArray<ModuleName>): DeprecatedExport {\n const isTypeOnly = names.length > 0 && names.every((item) => item.space === 'type')\n const [first] = names\n if (names.length === 1 && first?.name === '*') {\n return first.alias ? { name: first.alias, isTypeOnly, asAlias: true } : { isTypeOnly, asAlias: false }\n }\n return { name: names.map((item) => item.alias ?? item.name), isTypeOnly, asAlias: false }\n}\n","/**\n * File-member merging. `combineImports` and `combineExports` deduplicate and sort the import and\n * export entries of one file, while `combineSources` deduplicates source entries in original order.\n * `combineImports` also drops imports nothing references. This works on a file's members, not on\n * schema content.\n */\nimport path from 'node:path'\nimport { memo } from '@internals/utils'\nimport type { ExportNode, ImportNode, ModuleName, SourceNode, Space } from '../nodes/file.ts'\nimport { getNames, getSpace, toDeprecatedExport, toDeprecatedImport } from './moduleNames.ts'\n\nconst IDENTIFIER_RUN = /[\\w$]+/g\n\n/**\n * How many imports a file needs before indexing the source beats scanning it once per name.\n */\nconst INDEX_ABOVE_IMPORTS = 128\n\ntype Form = 'named' | 'default' | '*'\n\ntype Statement = { path: string; root?: string | null; form: Form; space: Space; names: Array<ModuleName> }\n\nconst importForm = (item: ModuleName): Form => (item.alias && (item.name === '*' || item.name === 'default') ? item.name : 'named')\nconst exportForm = (item: ModuleName): Form => (item.name === '*' ? '*' : 'named')\nconst label = (item: ModuleName): string => (item.alias ? `${item.name} as ${item.alias}` : item.name)\n\nfunction statementKey({ path, form, space, names }: Statement): string {\n return form === 'named' ? `${path}\\0named\\0${space}` : `${path}\\0${form}\\0${names[0]?.alias ?? ''}\\0${space}`\n}\n\nfunction toStatements(nodes: ReadonlyArray<ImportNode | ExportNode>, formOf: (item: ModuleName) => Form): Array<Statement> {\n return nodes.flatMap((node) => {\n const statements = new Map<string, Statement>()\n for (const item of getNames(node)) {\n const statement: Statement = {\n path: node.path,\n root: node.kind === 'Import' ? node.root : undefined,\n form: formOf(item),\n space: item.space ?? 'value',\n names: [],\n }\n const key = statementKey({ ...statement, names: [item] })\n const existing = statements.get(key) ?? statement\n statements.set(key, existing)\n existing.names.push(item)\n }\n return [...statements.values()]\n })\n}\n\n/**\n * Relative specifiers by `root`, then `path`. `createFile` sorts a file's imports again on every\n * merge, and the path math dominated that sort on large specs. Two levels keep the existing strings\n * as keys, so lookups reuse their hashes instead of hashing a new joined key each time.\n */\nconst specifierCache = memo.create<string, Map<string, string>>({ max: 10_000 })\n\n/**\n * Returns the specifier a member is written with: POSIX and relative to the importing file when it\n * has a `root`, like `getRelativePath` in parser-ts. Sorting on it keeps the order the same on every OS.\n */\nfunction specifier(node: { path: string; root?: string | null }): string {\n const { root, path: target } = node\n if (!root) return target\n const byPath = memo(specifierCache, root, () => new Map<string, string>())\n return memo(byPath, target, () => {\n const relative = path.relative(path.dirname(root), target).replaceAll('\\\\', '/')\n return relative.startsWith('../') ? relative : `./${relative}`\n })\n}\n\nfunction sortKey(statement: Statement): string {\n const form = statement.form === 'named' ? '1' : '0'\n const space = statement.space === 'type' ? '0' : '1'\n return `${form}:${space}:${specifier(statement)}:${statement.names.map(label).toSorted().join('\\0')}`\n}\n\nfunction mergeStatements(statements: Array<Statement>, keep: (item: ModuleName, statement: Statement) => boolean = () => true): Array<Statement> {\n const merged = new Map<string, { statement: Statement; seen: Set<string> }>()\n const sorted = statements.map((statement) => ({ statement, key: sortKey(statement) })).sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))\n\n for (const { statement } of sorted) {\n const key = statementKey(statement)\n const entry = merged.get(key) ?? { statement: { ...statement, names: [] }, seen: new Set<string>() }\n merged.set(key, entry)\n for (const item of statement.names) {\n const id = item.alias ?? item.name\n if (entry.seen.has(id) || !keep(item, statement)) continue\n entry.seen.add(id)\n entry.statement.names.push(item)\n }\n }\n\n const result = [...merged.values()].map(({ statement }) => statement)\n // A name kept as a value also serves its type uses, so a type statement from the same path must not bind it again.\n const bound = ({ path, item }: { path: string; item: ModuleName }) => `${path}\\0${item.alias ?? item.name}`\n const values = new Set(result.filter(({ space }) => space === 'value').flatMap(({ path, names }) => names.map((item) => bound({ path, item }))))\n return result\n .map((statement) =>\n statement.space === 'type' ? { ...statement, names: statement.names.filter((item) => !values.has(bound({ path: statement.path, item }))) } : statement,\n )\n .filter((statement) => statement.names.length > 0)\n}\n\n/**\n * Deduplicates `SourceNode` objects by `name + export + space`, keeping the first of each\n * key. An unnamed source only drops when the same node appears twice, so markdown can repeat a\n * paragraph or a table. Returns the deduplicated array in original order.\n */\nexport function combineSources(sources: Array<SourceNode>): Array<SourceNode> {\n const seen = new Set<SourceNode | string>()\n return sources.filter((source) => {\n const key = source.name != null ? `${source.name}:${source.export ?? source.isExportable ?? false}:${getSpace(source)}` : source\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/**\n * Deduplicates and merges `ExportNode` objects: one export per path, form and space. Returns a sorted array.\n */\nexport function combineExports(exports: Array<ExportNode>): Array<ExportNode> {\n return mergeStatements(toStatements(exports, exportForm)).map(({ path, names }) => ({ kind: 'Export', path, ...toDeprecatedExport(names), names }))\n}\n\n/**\n * Deduplicates and merges `ImportNode` objects, filtering out unused imports.\n *\n * Retains imports that are referenced in `source` or re-exported. One import per path, form and space. Returns\n * a sorted, deduplicated, filtered array.\n */\nexport function combineImports(imports: Array<ImportNode>, exports: Array<ExportNode>, source?: string): Array<ImportNode> {\n // Build a lookup of all exported names to retain imports that are re-exported\n const exportedNames = new Set(exports.flatMap((node) => getNames(node).map((item) => item.alias ?? item.name)))\n // `createFile` re-runs on every merge into a file, so scanning the source once per import name\n // costs a heavily merged file that scan again for every fragment it already holds. Indexing pays\n // for itself there, and costs more than it saves on the small files the default output produces.\n const identifiers = source && imports.length > INDEX_ABOVE_IMPORTS ? new Set(source.match(IDENTIFIER_RUN)) : null\n\n // A name in the index is used. One that is not still might be, inside a longer identifier, so the\n // substring test stays behind it.\n const isUsed = (importName: string): boolean => !source || identifiers?.has(importName) || source.includes(importName) || exportedNames.has(importName)\n\n const statements = toStatements(\n imports.filter((node) => node.path !== node.root),\n importForm,\n )\n\n // Paths that keep at least one used named import. A default import from such a path is retained\n // even when its binding can't be found in `source` e.g. a generated `client` default import\n // alongside `import type { Client } from <same path>`, where merged grouped output omits the body.\n const pathsWithUsedNamedImport = new Set(\n statements.filter(({ form, names }) => form === 'named' && names.some((item) => isUsed(item.alias ?? item.name))).map(({ path }) => path),\n )\n const keep = (item: ModuleName, { form, path }: Statement) => isUsed(item.alias ?? item.name) || (form !== 'named' && pathsWithUsedNamedImport.has(path))\n\n return mergeStatements(statements, keep).map(({ path, root, names }) => ({\n kind: 'Import',\n path,\n ...(root != null ? { root } : {}),\n ...toDeprecatedImport(names),\n names,\n }))\n}\n","import type { ValueOf } from '@internals/utils'\nimport type { nodeKinds } from '../constants.ts'\n\n/**\n * `kind` values used by AST nodes.\n *\n * @example\n * ```ts\n * const kind: NodeKind = 'Schema'\n * ```\n */\nexport type NodeKind = ValueOf<typeof nodeKinds>\n\n/**\n * Base shape shared by all AST nodes.\n *\n * @example\n * ```ts\n * const base: BaseNode = { kind: 'Input' }\n * ```\n */\nexport type BaseNode = {\n /**\n * Node discriminator.\n */\n kind: NodeKind\n /**\n * Where the node comes from in the input, in the form the adapter's `locate` reads. Document\n * adapters such as OpenAPI and AsyncAPI use an RFC 6901 JSON pointer, for example\n * `#/components/schemas/Pet`. Plugins can copy it to the code nodes they emit.\n */\n pointer?: string\n}\n\n/** `Omit` applied to each member of a union, so the union survives. */\nexport type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never\n\n/** Builds a `createX` factory for a node whose only computed field is `kind`. */\nexport function nodeFactory<T extends BaseNode>(kind: T['kind']): (input: Omit<T, 'kind'>) => T {\n return (input) => {\n const node = { ...input, kind }\n return node as T\n }\n}\n","import { hash } from 'node:crypto'\nimport path from 'node:path'\nimport { nodeKinds } from '../constants.ts'\nimport { combineExports, combineImports, combineSources } from '../utils/combineFileMembers.ts'\nimport { getNames, toDeprecatedExport, toDeprecatedImport } from '../utils/moduleNames.ts'\nimport { getNodeText } from '../utils/nodeText.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\nimport type { CodeNode } from './code.ts'\n\n/**\n * Supported file extensions.\n */\ntype Extname = '.ts' | '.js' | '.tsx' | '.json' | `.${string}`\n\ntype ImportName = string | Array<string | { propertyName: string; name?: string }>\n\n/**\n * Whether a declaration exists only at compile time (`'type'`) or also at runtime (`'value'`).\n */\nexport type Space = 'type' | 'value'\n\n/**\n * One name an import or export brings across, as in the ECMAScript `ImportEntry` record.\n */\nexport type ModuleName = {\n /**\n * Name in the other module: `'default'` for its default export, `'*'` for the whole module.\n */\n name: string\n /**\n * Local name for an import, or the exported name for an export.\n */\n alias?: string | null\n /**\n * Type or value.\n * @default 'value'\n */\n space?: Space | null\n}\n\n/**\n * Represents a language-agnostic import/dependency declaration.\n *\n * @example Named import (TypeScript: `import { useState } from 'react'`)\n * ```ts\n * createImport({ names: [{ name: 'useState' }], path: 'react' })\n * ```\n *\n * @example Default import (TypeScript: `import React from 'react'`)\n * ```ts\n * createImport({ names: [{ name: 'default', alias: 'React' }], path: 'react' })\n * ```\n *\n * @example Type-only import (TypeScript: `import type { FC } from 'react'`)\n * ```ts\n * createImport({ names: [{ name: 'FC', space: 'type' }], path: 'react' })\n * ```\n *\n * @example Namespace import (TypeScript: `import * as React from 'react'`)\n * ```ts\n * createImport({ names: [{ name: '*', alias: 'React' }], path: 'react' })\n * ```\n */\nexport type ImportNode = BaseNode & {\n kind: 'Import'\n /**\n * The names the import brings in. `ast.file.getNames` also reads the deprecated fields.\n */\n names?: Array<ModuleName> | null\n /**\n * Import name(s) to be used.\n *\n * @deprecated Use `names`. Removed in Kubb v6.\n */\n name: ImportName\n /**\n * Path for the import.\n *\n * @example\n * `'@kubb/core'`\n */\n path: string\n /**\n * Add a type-only import prefix.\n *\n * @deprecated Set `space: 'type'` on each name. Removed in Kubb v6.\n */\n isTypeOnly?: boolean | null\n /**\n * Import the entire module as a namespace.\n *\n * @deprecated Use `{ name: '*', alias }` in `names`. Removed in Kubb v6.\n */\n isNameSpace?: boolean | null\n /**\n * When set, the import path is resolved relative to this root.\n */\n root?: string | null\n}\n\n/**\n * Represents a language-agnostic export/public API declaration.\n *\n * @example Named export (TypeScript: `export { Pets } from './Pets'`)\n * ```ts\n * createExport({ names: [{ name: 'Pets' }], path: './Pets' })\n * ```\n *\n * @example Type-only export (TypeScript: `export type { Pet } from './Pet'`)\n * ```ts\n * createExport({ names: [{ name: 'Pet', space: 'type' }], path: './Pet' })\n * ```\n *\n * @example Wildcard export (TypeScript: `export * from './utils'`)\n * ```ts\n * createExport({ names: [{ name: '*' }], path: './utils' })\n * ```\n *\n * @example Namespace alias (TypeScript: `export * as utils from './utils'`)\n * ```ts\n * createExport({ names: [{ name: '*', alias: 'utils' }], path: './utils' })\n * ```\n */\nexport type ExportNode = BaseNode & {\n kind: 'Export'\n /**\n * The names the export passes on. `ast.file.getNames` also reads the deprecated fields.\n */\n names?: Array<ModuleName> | null\n /**\n * Export name(s) to be used. When omitted, generates a wildcard export.\n *\n * @deprecated Use `names`. Removed in Kubb v6.\n */\n name?: string | Array<string> | null\n /**\n * Path for the export.\n *\n * @example\n * `'@kubb/core'`\n */\n path: string\n /**\n * Add a type-only export prefix.\n *\n * @deprecated Set `space: 'type'` on each name. Removed in Kubb v6.\n */\n isTypeOnly?: boolean | null\n /**\n * Export as an aliased namespace.\n *\n * @deprecated Use `{ name: '*', alias }` in `names`. Removed in Kubb v6.\n */\n asAlias?: boolean | null\n}\n\n/**\n * Represents a fragment of source code within a file.\n *\n * @example Named exportable source\n * ```ts\n * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], export: true })\n * ```\n *\n * @example Inline unnamed code block\n * ```ts\n * createSource({ nodes: [createText('const x = 1')] })\n * ```\n */\nexport type SourceNode = BaseNode & {\n kind: 'Source'\n /**\n * Optional name identifying this source (used for deduplication and barrel generation).\n */\n name?: string | null\n /**\n * Type or value. When unset, a source whose first node is a `Type` is a type.\n */\n space?: Space | null\n /**\n * Mark this source as a type-only export.\n *\n * @deprecated Use `space: 'type'`. Removed in Kubb v6.\n */\n isTypeOnly?: boolean | null\n /**\n * Mark this source as an exported declaration, which barrels list. The source text carries its own `export` keyword.\n */\n export?: boolean | null\n /**\n * Mark this exported source as the module's default export. Barrels skip it, since they can't re-export it by name.\n */\n default?: boolean | null\n /**\n * @deprecated Use `export`. Removed in Kubb v6.\n */\n isExportable?: boolean | null\n /**\n * @deprecated Use `export`. Removed in Kubb v6.\n */\n isIndexable?: boolean | null\n /**\n * Marks the source as a definition that importing files absorb instead of import. `expression` is\n * the declaration's right-hand side, such as `{ body: Pet }`.\n *\n * @deprecated Set `inline` on the file. Removed in Kubb v6.\n */\n inline?: { expression: string } | null\n /**\n * Child nodes that make up this source fragment, in DOM order.\n * Use a {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * Represents a fully resolved file in the AST.\n *\n * Created via `createFile()`, which computes the `id`, `name`, and `extname` from the input\n * and deduplicates `imports`, `exports`, and `sources`.\n *\n * @example\n * ```ts\n * const file = createFile({\n * baseName: 'petStore.ts',\n * path: 'src/models/petStore.ts',\n * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], export: true })],\n * imports: [createImport({ name: ['z'], path: 'zod' })],\n * exports: [createExport({ name: ['Pet'], path: './petStore' })],\n * })\n * // file.id = SHA256 hash of the path\n * // file.name = 'petStore'\n * // file.extname = '.ts'\n * ```\n */\nexport type FileNode<TMeta extends object = object> = BaseNode & {\n kind: 'File'\n /**\n * Unique identifier derived from a SHA256 hash of the file path. `createFile`\n * computes it, so callers do not need to provide it.\n */\n id: string\n /**\n * File name without extension, derived from `baseName`.\n *\n * @see https://nodejs.org/api/path.html#pathformatpathobject\n */\n name: string\n /**\n * File base name, including extension, shaped like `${name}${extname}`.\n *\n * @see https://nodejs.org/api/path.html#pathbasenamepath-suffix\n */\n baseName: `${string}.${string}`\n /**\n * Full qualified path to the file.\n */\n path: string\n /**\n * File extension extracted from `baseName`.\n */\n extname: Extname\n /**\n * Deduplicated list of source code fragments.\n */\n sources: Array<SourceNode>\n /**\n * Deduplicated list of import declarations.\n */\n imports: Array<ImportNode>\n /**\n * Deduplicated list of export declarations.\n */\n exports: Array<ExportNode>\n /**\n * Optional metadata attached to this file, read by plugins during barrel generation.\n */\n meta?: TMeta\n /**\n * Optional banner prepended to the generated file content.\n * Accepts `null` so `resolver.default.banner()` results can be passed directly.\n */\n banner?: string | null\n /**\n * Optional footer appended to the generated file content.\n * Accepts `null` so `resolver.default.footer()` results can be passed directly.\n */\n footer?: string | null\n /**\n * Absolute on-disk path to copy into the output, through the parser's `copy` hook when it has one.\n *\n * Use to emit a real source file shipped inside a package (a template) into the generated\n * folder. When set, `copy` provides the file content and any `sources` nodes are ignored for\n * output; `sources` may still carry `name`/`export` so barrel generation\n * treats the file the same as a rendered one.\n */\n copy?: string | null\n /**\n * Marks a file that is never written. Each file that imports from it gets the body of each imported declaration, such as `{ body: Pet }`, in place of its name.\n */\n inline?: boolean | null\n}\n\nexport type ImportInput = Omit<ImportNode, 'kind' | 'name'> & { name?: ImportName }\n\nexport type ExportInput = Omit<ExportNode, 'kind'>\n\n// A spread node carries the deprecated fields derived from its `names`, so only a value that differs is an override.\ntype Override<TValue> = { value: TValue | null | undefined; derived: TValue | null | undefined }\n\nfunction overrideSpace(names: Array<ModuleName>, { value, derived }: Override<boolean>): Array<ModuleName> {\n if (value == null || value === derived) return names\n const space = value ? 'type' : 'value'\n return names.map((item) => ({ ...item, space }))\n}\n\nconst isOverride = ({ value, derived }: Override<unknown>): boolean => value !== undefined && JSON.stringify(value) !== JSON.stringify(derived)\n\n/**\n * Creates an `ImportNode`. A node built from `names` also gets the deprecated fields. A deprecated `name` or\n * `isTypeOnly` that differs from the one `names` gives overrides it, so `{ ...imp, isTypeOnly: true }` still works.\n *\n * @example Named import\n * ```ts\n * createImport({ names: [{ name: 'useState' }], path: 'react' })\n * // import { useState } from 'react'\n * ```\n */\nexport function createImport(input: ImportInput): ImportNode {\n if (!input.names) return { ...input, name: input.name ?? [], kind: nodeKinds.import }\n const derived = toDeprecatedImport(input.names)\n if (isOverride({ value: input.name, derived: derived.name })) return { ...input, names: null, name: input.name ?? [], kind: nodeKinds.import }\n const names = overrideSpace(input.names, { value: input.isTypeOnly, derived: derived.isTypeOnly })\n return { ...input, ...toDeprecatedImport(names), names, kind: nodeKinds.import }\n}\n\n/**\n * Creates an `ExportNode`. A node built from `names` also gets the deprecated fields. A deprecated `name` or\n * `isTypeOnly` that differs from the one `names` gives overrides it.\n *\n * @example Named export\n * ```ts\n * createExport({ names: [{ name: 'Pet' }], path: './Pet' })\n * // export { Pet } from './Pet'\n * ```\n */\nexport function createExport(input: ExportInput): ExportNode {\n if (!input.names) return { ...input, kind: nodeKinds.export }\n const derived = toDeprecatedExport(input.names)\n if (isOverride({ value: input.name, derived: derived.name })) return { ...input, names: null, kind: nodeKinds.export }\n const names = overrideSpace(input.names, { value: input.isTypeOnly, derived: derived.isTypeOnly })\n return { ...input, ...toDeprecatedExport(names), names, kind: nodeKinds.export }\n}\n\n/**\n * Creates a `SourceNode` representing a fragment of source code within a file.\n *\n * @example\n * ```ts\n * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], export: true })\n * ```\n */\nexport const createSource = nodeFactory<SourceNode>(nodeKinds.source)\n\n/**\n * Input descriptor for {@link createFile}, before `id`, `name`, and `extname` are computed\n * and `imports`/`exports`/`sources` are deduplicated.\n */\nexport type UserFileNode<TMeta extends object = object> = Omit<FileNode<TMeta>, 'kind' | 'id' | 'name' | 'extname' | 'imports' | 'exports' | 'sources'> &\n Pick<Partial<FileNode<TMeta>>, 'imports' | 'exports' | 'sources'>\n\n/**\n * Creates a fully resolved `FileNode` from a file input descriptor.\n *\n * Computes:\n * - `id` SHA256 hash of the file path\n * - `name` `baseName` without extension\n * - `extname` extension extracted from `baseName`\n *\n * Deduplicates:\n * - `sources` via `combineSources`\n * - `exports` via `combineExports`\n * - `imports` via `combineImports` (also filters unused imports)\n *\n * @throws {Error} when `baseName` has no extension.\n *\n * @example\n * ```ts\n * const file = createFile({\n * baseName: 'petStore.ts',\n * path: 'src/models/petStore.ts',\n * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],\n * imports: [createImport({ name: ['z'], path: 'zod' })],\n * exports: [createExport({ name: ['Pet'], path: './petStore' })],\n * })\n * // file.id = SHA256 hash of 'src/models/petStore.ts'\n * // file.name = 'petStore'\n * // file.extname = '.ts'\n * ```\n *\n * @example Copy a real file into the output\n * ```ts\n * const file = createFile({\n * baseName: 'client.ts',\n * path: 'src/gen/client.ts',\n * copy: '/abs/path/to/templates/client.ts',\n * })\n * ```\n */\nexport function createFile<TMeta extends object = object>(input: UserFileNode<TMeta>): FileNode<TMeta> {\n const extname = path.extname(input.baseName) as `.${string}`\n if (!extname) {\n throw new Error(`No extname found for ${input.baseName}`)\n }\n\n const resolvedExports = input.exports?.length ? combineExports(input.exports) : []\n const resolvedSources = input.sources?.length ? combineSources(input.sources) : []\n\n // Skip building the source text and local-name set when there are no imports to resolve against them.\n const resolvedImports: Array<ImportNode> = (() => {\n if (!input.imports?.length) return []\n\n const sourceParts: Array<string> = []\n const localNames = new Set<string>()\n // Only the sources the file keeps count: an import used just by a dropped duplicate is unused.\n for (const item of resolvedSources) {\n const extracted = item.nodes && getNodeText(item.nodes)\n if (extracted) sourceParts.push(extracted)\n if (item.name) localNames.add(item.name)\n }\n const source = sourceParts.join('\\n') || undefined\n const combinedImports = combineImports(input.imports, resolvedExports, source)\n // Consolidating output (`mode: 'file'`) can put a symbol's definition and an import of it in the\n // same file: by path when the import still targets this file, by name when consolidation moved it.\n return combinedImports.flatMap((imp) => {\n if (imp.path === input.path) return []\n const names = getNames(imp)\n const kept = names.filter((item) => !localNames.has(item.alias ?? item.name))\n if (!kept.length) return []\n return [kept.length === names.length ? imp : createImport({ path: imp.path, ...(imp.root != null ? { root: imp.root } : {}), names: kept })]\n })\n })()\n\n return {\n ...input,\n kind: nodeKinds.file,\n id: hash('sha256', input.path, 'hex'),\n name: path.basename(input.baseName, extname),\n extname,\n imports: resolvedImports,\n exports: resolvedExports,\n sources: resolvedSources,\n meta: (input.meta ?? {}) as TMeta,\n }\n}\n"],"mappings":";;;;;;;;;;;AAMA,SAAgB,SAAS,MAAkD;CACzE,IAAI,KAAK,OAAO,OAAO,KAAK;CAC5B,OAAO,KAAK,SAAS,WAAW,qBAAqB,IAAI,IAAI,qBAAqB,IAAI;AACxF;AAEA,SAAgB,SAAS,QAA2B;CAClD,IAAI,OAAO,OAAO,OAAO,OAAO;CAChC,IAAI,OAAO,cAAc,MAAM,OAAO,OAAO,aAAa,SAAS;CACnE,OAAO,OAAO,QAAQ,EAAE,EAAE,SAAS,SAAS,SAAS;AACvD;;;;AAQA,SAAgB,qBAAqB,EAAE,MAAM,YAAY,eAAoD;CAC3G,MAAM,QAAe,aAAa,SAAS;CAC3C,IAAI,CAAC,MAAM,QAAQ,IAAI,GAAG,OAAO,CAAC;EAAE,MAAM,cAAc,MAAM;EAAW,OAAO;EAAM;CAAM,CAAC;CAC7F,OAAO,KAAK,KAAK,SAAU,OAAO,SAAS,WAAW;EAAE,MAAM;EAAM;CAAM,IAAI;EAAE,MAAM,KAAK;EAAc,GAAI,KAAK,OAAO,EAAE,OAAO,KAAK,KAAK,IAAI,CAAC;EAAI;CAAM,CAAE;AAC/J;;;;AAKA,SAAgB,qBAAqB,EAAE,MAAM,YAAY,WAAgD;CACvG,MAAM,Q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IAAI;EACzC;EACA,MAAM,SAAS,YAAY,KAAK,IAAI,KAAK,KAAA;EAIzC,OAHwB,eAAe,MAAM,SAAS,iBAAiB,MAGlD,CAAC,CAAC,SAAS,QAAQ;GACtC,IAAI,IAAI,SAAS,MAAM,MAAM,OAAO,CAAC;GACrC,MAAM,QAAQ,SAAS,GAAG;GAC1B,MAAM,OAAO,MAAM,QAAQ,SAAS,CAAC,WAAW,IAAI,KAAK,SAAS,KAAK,IAAI,CAAC;GAC5E,IAAI,CAAC,KAAK,QAAQ,OAAO,CAAC;GAC1B,OAAO,CAAC,KAAK,WAAW,MAAM,SAAS,MAAM,aAAa;IAAE,MAAM,IAAI;IAAM,GAAI,IAAI,QAAQ,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;IAAI,OAAO;GAAK,CAAC,CAAC;EAC7I,CAAC;CACH,EAAA,CAAG;CAEH,OAAO;EACL,GAAG;EACH,MAAM,UAAU;EAChB,IAAI,KAAK,UAAU,MAAM,MAAM,KAAK;EACpC,MAAM,KAAK,SAAS,MAAM,UAAU,OAAO;EAC3C;EACA,SAAS;EACT,SAAS;EACT,SAAS;EACT,MAAO,MAAM,QAAQ,CAAC;CACxB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"file-D73XubVb.cjs","names":["memo","path","nodeKinds","path","getNodeText","hash"],"sources":["../src/utils/moduleNames.ts","../src/utils/combineFileMembers.ts","../src/nodes/base.ts","../src/nodes/file.ts"],"sourcesContent":["import type { ExportNode, ImportNode, ModuleName, SourceNode, Space } from '../nodes/file.ts'\n\n/**\n * Returns the names an import or export brings across. A node built with the deprecated fields gets them from\n * those, each with an explicit `space`, so it prints exactly as before.\n */\nexport function getNames(node: ImportNode | ExportNode): Array<ModuleName> {\n if (node.names) return node.names\n return node.kind === 'Import' ? fromDeprecatedImport(node) : fromDeprecatedExport(node)\n}\n\nexport function getSpace(source: SourceNode): Space {\n if (source.space) return source.space\n if (source.isTypeOnly != null) return source.isTypeOnly ? 'type' : 'value'\n return source.nodes?.[0]?.kind === 'Type' ? 'type' : 'value'\n}\n\ntype DeprecatedImport = Pick<ImportNode, 'name' | 'isTypeOnly' | 'isNameSpace'>\ntype DeprecatedExport = Pick<ExportNode, 'name' | 'isTypeOnly' | 'asAlias'>\n\n/**\n * @deprecated Converts a node built with `name`, `isTypeOnly` and `isNameSpace` to `names`. Removed in Kubb v6.\n */\nexport function fromDeprecatedImport({ name, isTypeOnly, isNameSpace }: DeprecatedImport): Array<ModuleName> {\n const space: Space = isTypeOnly ? 'type' : 'value'\n if (!Array.isArray(name)) return [{ name: isNameSpace ? '*' : 'default', alias: name, space }]\n return name.map((item) => (typeof item === 'string' ? { name: item, space } : { name: item.propertyName, ...(item.name ? { alias: item.name } : {}), space }))\n}\n\n/**\n * @deprecated Converts a node built with `name`, `isTypeOnly` and `asAlias` to `names`. Removed in Kubb v6.\n */\nexport function fromDeprecatedExport({ name, isTypeOnly, asAlias }: DeprecatedExport): Array<ModuleName> {\n const space: Space = isTypeOnly ? 'type' : 'value'\n if (name == null) return [{ name: '*', space }]\n if (!Array.isArray(name)) return [asAlias ? { name: '*', alias: name, space } : { name, space }]\n return name.map((item) => ({ name: item, space }))\n}\n\n/**\n * @deprecated The old import fields for `names`, for code that still reads them. Removed in Kubb v6.\n */\nexport function toDeprecatedImport(names: ReadonlyArray<ModuleName>): DeprecatedImport {\n const isTypeOnly = names.length > 0 && names.every((item) => item.space === 'type')\n const [first] = names\n if (names.length === 1 && first?.alias && (first.name === '*' || first.name === 'default')) {\n return { name: first.alias, isTypeOnly, isNameSpace: first.name === '*' }\n }\n return { name: names.map((item) => (item.alias ? { propertyName: item.name, name: item.alias } : item.name)), isTypeOnly, isNameSpace: false }\n}\n\n/**\n * @deprecated The old export fields for `names`; an alias stands in for its name. Removed in Kubb v6.\n */\nexport function toDeprecatedExport(names: ReadonlyArray<ModuleName>): DeprecatedExport {\n const isTypeOnly = names.length > 0 && names.every((item) => item.space === 'type')\n const [first] = names\n if (names.length === 1 && first?.name === '*') {\n return first.alias ? { name: first.alias, isTypeOnly, asAlias: true } : { isTypeOnly, asAlias: false }\n }\n return { name: names.map((item) => item.alias ?? item.name), isTypeOnly, asAlias: false }\n}\n","/**\n * File-member merging. `combineImports` and `combineExports` deduplicate and sort the import and\n * export entries of one file, while `combineSources` deduplicates source entries in original order.\n * `combineImports` also drops imports nothing references. This works on a file's members, not on\n * schema content.\n */\nimport path from 'node:path'\nimport { memo } from '@internals/utils'\nimport type { ExportNode, ImportNode, ModuleName, SourceNode, Space } from '../nodes/file.ts'\nimport { getNames, getSpace, toDeprecatedExport, toDeprecatedImport } from './moduleNames.ts'\n\nconst IDENTIFIER_RUN = /[\\w$]+/g\n\n/**\n * How many imports a file needs before indexing the source beats scanning it once per name.\n */\nconst INDEX_ABOVE_IMPORTS = 128\n\ntype Form = 'named' | 'default' | '*'\n\ntype Statement = { path: string; root?: string | null; form: Form; space: Space; names: Array<ModuleName> }\n\nconst importForm = (item: ModuleName): Form => (item.alias && (item.name === '*' || item.name === 'default') ? item.name : 'named')\nconst exportForm = (item: ModuleName): Form => (item.name === '*' ? '*' : 'named')\nconst label = (item: ModuleName): string => (item.alias ? `${item.name} as ${item.alias}` : item.name)\n\nfunction statementKey({ path, form, space, names }: Statement): string {\n return form === 'named' ? `${path}\\0named\\0${space}` : `${path}\\0${form}\\0${names[0]?.alias ?? ''}\\0${space}`\n}\n\nfunction toStatements(nodes: ReadonlyArray<ImportNode | ExportNode>, formOf: (item: ModuleName) => Form): Array<Statement> {\n return nodes.flatMap((node) => {\n const statements = new Map<string, Statement>()\n for (const item of getNames(node)) {\n const statement: Statement = {\n path: node.path,\n root: node.kind === 'Import' ? node.root : undefined,\n form: formOf(item),\n space: item.space ?? 'value',\n names: [],\n }\n const key = statementKey({ ...statement, names: [item] })\n const existing = statements.get(key) ?? statement\n statements.set(key, existing)\n existing.names.push(item)\n }\n return [...statements.values()]\n })\n}\n\n/**\n * Relative specifiers by `root`, then `path`. `createFile` sorts a file's imports again on every\n * merge, and the path math dominated that sort on large specs. Two levels keep the existing strings\n * as keys, so lookups reuse their hashes instead of hashing a new joined key each time.\n */\nconst specifierCache = memo.create<string, Map<string, string>>({ max: 10_000 })\n\n/**\n * Returns the specifier a member is written with: POSIX and relative to the importing file when it\n * has a `root`, like `getRelativePath` in parser-ts. Sorting on it keeps the order the same on every OS.\n */\nfunction specifier(node: { path: string; root?: string | null }): string {\n const { root, path: target } = node\n if (!root) return target\n const byPath = memo(specifierCache, root, () => new Map<string, string>())\n return memo(byPath, target, () => {\n const relative = path.relative(path.dirname(root), target).replaceAll('\\\\', '/')\n return relative.startsWith('../') ? relative : `./${relative}`\n })\n}\n\nfunction sortKey(statement: Statement): string {\n const form = statement.form === 'named' ? '1' : '0'\n const space = statement.space === 'type' ? '0' : '1'\n return `${form}:${space}:${specifier(statement)}:${statement.names.map(label).toSorted().join('\\0')}`\n}\n\nfunction mergeStatements(statements: Array<Statement>, keep: (item: ModuleName, statement: Statement) => boolean = () => true): Array<Statement> {\n const merged = new Map<string, { statement: Statement; seen: Set<string> }>()\n const sorted = statements.map((statement) => ({ statement, key: sortKey(statement) })).sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))\n\n for (const { statement } of sorted) {\n const key = statementKey(statement)\n const entry = merged.get(key) ?? { statement: { ...statement, names: [] }, seen: new Set<string>() }\n merged.set(key, entry)\n for (const item of statement.names) {\n const id = item.alias ?? item.name\n if (entry.seen.has(id) || !keep(item, statement)) continue\n entry.seen.add(id)\n entry.statement.names.push(item)\n }\n }\n\n const result = [...merged.values()].map(({ statement }) => statement)\n // A name kept as a value also serves its type uses, so a type statement from the same path must not bind it again.\n const bound = ({ path, item }: { path: string; item: ModuleName }) => `${path}\\0${item.alias ?? item.name}`\n const values = new Set(result.filter(({ space }) => space === 'value').flatMap(({ path, names }) => names.map((item) => bound({ path, item }))))\n return result\n .map((statement) =>\n statement.space === 'type' ? { ...statement, names: statement.names.filter((item) => !values.has(bound({ path: statement.path, item }))) } : statement,\n )\n .filter((statement) => statement.names.length > 0)\n}\n\n/**\n * Deduplicates `SourceNode` objects by `name + export + space`, keeping the first of each\n * key. An unnamed source only drops when the same node appears twice, so markdown can repeat a\n * paragraph or a table. Returns the deduplicated array in original order.\n */\nexport function combineSources(sources: Array<SourceNode>): Array<SourceNode> {\n const seen = new Set<SourceNode | string>()\n return sources.filter((source) => {\n const key = source.name != null ? `${source.name}:${source.export ?? source.isExportable ?? false}:${getSpace(source)}` : source\n if (seen.has(key)) return false\n seen.add(key)\n return true\n })\n}\n\n/**\n * Deduplicates and merges `ExportNode` objects: one export per path, form and space. Returns a sorted array.\n */\nexport function combineExports(exports: Array<ExportNode>): Array<ExportNode> {\n return mergeStatements(toStatements(exports, exportForm)).map(({ path, names }) => ({ kind: 'Export', path, ...toDeprecatedExport(names), names }))\n}\n\n/**\n * Deduplicates and merges `ImportNode` objects, filtering out unused imports.\n *\n * Retains imports that are referenced in `source` or re-exported. One import per path, form and space. Returns\n * a sorted, deduplicated, filtered array.\n */\nexport function combineImports(imports: Array<ImportNode>, exports: Array<ExportNode>, source?: string): Array<ImportNode> {\n // Build a lookup of all exported names to retain imports that are re-exported\n const exportedNames = new Set(exports.flatMap((node) => getNames(node).map((item) => item.alias ?? item.name)))\n // `createFile` re-runs on every merge into a file, so scanning the source once per import name\n // costs a heavily merged file that scan again for every fragment it already holds. Indexing pays\n // for itself there, and costs more than it saves on the small files the default output produces.\n const identifiers = source && imports.length > INDEX_ABOVE_IMPORTS ? new Set(source.match(IDENTIFIER_RUN)) : null\n\n // A name in the index is used. One that is not still might be, inside a longer identifier, so the\n // substring test stays behind it.\n const isUsed = (importName: string): boolean => !source || identifiers?.has(importName) || source.includes(importName) || exportedNames.has(importName)\n\n const statements = toStatements(\n imports.filter((node) => node.path !== node.root),\n importForm,\n )\n\n // Paths that keep at least one used named import. A default import from such a path is retained\n // even when its binding can't be found in `source` e.g. a generated `client` default import\n // alongside `import type { Client } from <same path>`, where merged grouped output omits the body.\n const pathsWithUsedNamedImport = new Set(\n statements.filter(({ form, names }) => form === 'named' && names.some((item) => isUsed(item.alias ?? item.name))).map(({ path }) => path),\n )\n const keep = (item: ModuleName, { form, path }: Statement) => isUsed(item.alias ?? item.name) || (form !== 'named' && pathsWithUsedNamedImport.has(path))\n\n return mergeStatements(statements, keep).map(({ path, root, names }) => ({\n kind: 'Import',\n path,\n ...(root != null ? { root } : {}),\n ...toDeprecatedImport(names),\n names,\n }))\n}\n","import type { ValueOf } from '@internals/utils'\nimport type { nodeKinds } from '../constants.ts'\n\n/**\n * `kind` values used by AST nodes.\n *\n * @example\n * ```ts\n * const kind: NodeKind = 'Schema'\n * ```\n */\nexport type NodeKind = ValueOf<typeof nodeKinds>\n\n/**\n * Base shape shared by all AST nodes.\n *\n * @example\n * ```ts\n * const base: BaseNode = { kind: 'Input' }\n * ```\n */\nexport type BaseNode = {\n /**\n * Node discriminator.\n */\n kind: NodeKind\n /**\n * Where the node comes from in the input, in the form the adapter's `locate` reads. Document\n * adapters such as OpenAPI and AsyncAPI use an RFC 6901 JSON pointer, for example\n * `#/components/schemas/Pet`. Plugins can copy it to the code nodes they emit.\n */\n pointer?: string\n}\n\n/** `Omit` applied to each member of a union, so the union survives. */\nexport type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never\n\n/** Builds a `createX` factory for a node whose only computed field is `kind`. */\nexport function nodeFactory<T extends BaseNode>(kind: T['kind']): (input: Omit<T, 'kind'>) => T {\n return (input) => {\n const node = { ...input, kind }\n return node as T\n }\n}\n","import { hash } from 'node:crypto'\nimport path from 'node:path'\nimport { nodeKinds } from '../constants.ts'\nimport { combineExports, combineImports, combineSources } from '../utils/combineFileMembers.ts'\nimport { getNames, toDeprecatedExport, toDeprecatedImport } from '../utils/moduleNames.ts'\nimport { getNodeText } from '../utils/nodeText.ts'\nimport { type BaseNode, nodeFactory } from './base.ts'\nimport type { CodeNode } from './code.ts'\n\n/**\n * Supported file extensions.\n */\ntype Extname = '.ts' | '.js' | '.tsx' | '.json' | `.${string}`\n\ntype ImportName = string | Array<string | { propertyName: string; name?: string }>\n\n/**\n * Whether a declaration exists only at compile time (`'type'`) or also at runtime (`'value'`).\n */\nexport type Space = 'type' | 'value'\n\n/**\n * One name an import or export brings across, as in the ECMAScript `ImportEntry` record.\n */\nexport type ModuleName = {\n /**\n * Name in the other module: `'default'` for its default export, `'*'` for the whole module.\n */\n name: string\n /**\n * Local name for an import, or the exported name for an export.\n */\n alias?: string | null\n /**\n * Type or value.\n * @default 'value'\n */\n space?: Space | null\n}\n\n/**\n * Represents a language-agnostic import/dependency declaration.\n *\n * @example Named import (TypeScript: `import { useState } from 'react'`)\n * ```ts\n * createImport({ names: [{ name: 'useState' }], path: 'react' })\n * ```\n *\n * @example Default import (TypeScript: `import React from 'react'`)\n * ```ts\n * createImport({ names: [{ name: 'default', alias: 'React' }], path: 'react' })\n * ```\n *\n * @example Type-only import (TypeScript: `import type { FC } from 'react'`)\n * ```ts\n * createImport({ names: [{ name: 'FC', space: 'type' }], path: 'react' })\n * ```\n *\n * @example Namespace import (TypeScript: `import * as React from 'react'`)\n * ```ts\n * createImport({ names: [{ name: '*', alias: 'React' }], path: 'react' })\n * ```\n */\nexport type ImportNode = BaseNode & {\n kind: 'Import'\n /**\n * The names the import brings in. `ast.file.getNames` also reads the deprecated fields.\n */\n names?: Array<ModuleName> | null\n /**\n * Import name(s) to be used.\n *\n * @deprecated Use `names`. Removed in Kubb v6.\n */\n name: ImportName\n /**\n * Path for the import.\n *\n * @example\n * `'@kubb/core'`\n */\n path: string\n /**\n * Add a type-only import prefix.\n *\n * @deprecated Set `space: 'type'` on each name. Removed in Kubb v6.\n */\n isTypeOnly?: boolean | null\n /**\n * Import the entire module as a namespace.\n *\n * @deprecated Use `{ name: '*', alias }` in `names`. Removed in Kubb v6.\n */\n isNameSpace?: boolean | null\n /**\n * When set, the import path is resolved relative to this root.\n */\n root?: string | null\n}\n\n/**\n * Represents a language-agnostic export/public API declaration.\n *\n * @example Named export (TypeScript: `export { Pets } from './Pets'`)\n * ```ts\n * createExport({ names: [{ name: 'Pets' }], path: './Pets' })\n * ```\n *\n * @example Type-only export (TypeScript: `export type { Pet } from './Pet'`)\n * ```ts\n * createExport({ names: [{ name: 'Pet', space: 'type' }], path: './Pet' })\n * ```\n *\n * @example Wildcard export (TypeScript: `export * from './utils'`)\n * ```ts\n * createExport({ names: [{ name: '*' }], path: './utils' })\n * ```\n *\n * @example Namespace alias (TypeScript: `export * as utils from './utils'`)\n * ```ts\n * createExport({ names: [{ name: '*', alias: 'utils' }], path: './utils' })\n * ```\n */\nexport type ExportNode = BaseNode & {\n kind: 'Export'\n /**\n * The names the export passes on. `ast.file.getNames` also reads the deprecated fields.\n */\n names?: Array<ModuleName> | null\n /**\n * Export name(s) to be used. When omitted, generates a wildcard export.\n *\n * @deprecated Use `names`. Removed in Kubb v6.\n */\n name?: string | Array<string> | null\n /**\n * Path for the export.\n *\n * @example\n * `'@kubb/core'`\n */\n path: string\n /**\n * Add a type-only export prefix.\n *\n * @deprecated Set `space: 'type'` on each name. Removed in Kubb v6.\n */\n isTypeOnly?: boolean | null\n /**\n * Export as an aliased namespace.\n *\n * @deprecated Use `{ name: '*', alias }` in `names`. Removed in Kubb v6.\n */\n asAlias?: boolean | null\n}\n\n/**\n * Represents a fragment of source code within a file.\n *\n * @example Named exportable source\n * ```ts\n * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], export: true })\n * ```\n *\n * @example Inline unnamed code block\n * ```ts\n * createSource({ nodes: [createText('const x = 1')] })\n * ```\n */\nexport type SourceNode = BaseNode & {\n kind: 'Source'\n /**\n * Optional name identifying this source (used for deduplication and barrel generation).\n */\n name?: string | null\n /**\n * Type or value. When unset, a source whose first node is a `Type` is a type.\n */\n space?: Space | null\n /**\n * Mark this source as a type-only export.\n *\n * @deprecated Use `space: 'type'`. Removed in Kubb v6.\n */\n isTypeOnly?: boolean | null\n /**\n * Mark this source as an exported declaration, which barrels list. The source text carries its own `export` keyword.\n */\n export?: boolean | null\n /**\n * Mark this exported source as the module's default export. Barrels skip it, since they can't re-export it by name.\n */\n default?: boolean | null\n /**\n * @deprecated Use `export`. Removed in Kubb v6.\n */\n isExportable?: boolean | null\n /**\n * @deprecated Use `export`. Removed in Kubb v6.\n */\n isIndexable?: boolean | null\n /**\n * Marks the source as a definition that importing files absorb instead of import. `expression` is\n * the declaration's right-hand side, such as `{ body: Pet }`.\n *\n * @deprecated Set `inline` on the file. Removed in Kubb v6.\n */\n inline?: { expression: string } | null\n /**\n * Child nodes that make up this source fragment, in DOM order.\n * Use a {@link TextNode} for raw string content.\n */\n nodes?: Array<CodeNode>\n}\n\n/**\n * Represents a fully resolved file in the AST.\n *\n * Created via `createFile()`, which computes the `id`, `name`, and `extname` from the input\n * and deduplicates `imports`, `exports`, and `sources`.\n *\n * @example\n * ```ts\n * const file = createFile({\n * baseName: 'petStore.ts',\n * path: 'src/models/petStore.ts',\n * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], export: true })],\n * imports: [createImport({ name: ['z'], path: 'zod' })],\n * exports: [createExport({ name: ['Pet'], path: './petStore' })],\n * })\n * // file.id = SHA256 hash of the path\n * // file.name = 'petStore'\n * // file.extname = '.ts'\n * ```\n */\nexport type FileNode<TMeta extends object = object> = BaseNode & {\n kind: 'File'\n /**\n * Unique identifier derived from a SHA256 hash of the file path. `createFile`\n * computes it, so callers do not need to provide it.\n */\n id: string\n /**\n * File name without extension, derived from `baseName`.\n *\n * @see https://nodejs.org/api/path.html#pathformatpathobject\n */\n name: string\n /**\n * File base name, including extension, shaped like `${name}${extname}`.\n *\n * @see https://nodejs.org/api/path.html#pathbasenamepath-suffix\n */\n baseName: `${string}.${string}`\n /**\n * Full qualified path to the file.\n */\n path: string\n /**\n * File extension extracted from `baseName`.\n */\n extname: Extname\n /**\n * Deduplicated list of source code fragments.\n */\n sources: Array<SourceNode>\n /**\n * Deduplicated list of import declarations.\n */\n imports: Array<ImportNode>\n /**\n * Deduplicated list of export declarations.\n */\n exports: Array<ExportNode>\n /**\n * Optional metadata attached to this file, read by plugins during barrel generation.\n */\n meta?: TMeta\n /**\n * Optional banner prepended to the generated file content.\n * Accepts `null` so `resolver.default.banner()` results can be passed directly.\n */\n banner?: string | null\n /**\n * Optional footer appended to the generated file content.\n * Accepts `null` so `resolver.default.footer()` results can be passed directly.\n */\n footer?: string | null\n /**\n * Absolute on-disk path to copy into the output, through the parser's `copy` hook when it has one.\n *\n * Use to emit a real source file shipped inside a package (a template) into the generated\n * folder. When set, `copy` provides the file content and any `sources` nodes are ignored for\n * output; `sources` may still carry `name`/`export` so barrel generation\n * treats the file the same as a rendered one.\n */\n copy?: string | null\n /**\n * Marks a file that is never written. Each file that imports from it gets the body of each imported declaration, such as `{ body: Pet }`, in place of its name.\n */\n inline?: boolean | null\n}\n\nexport type ImportInput = Omit<ImportNode, 'kind' | 'name'> & { name?: ImportName }\n\nexport type ExportInput = Omit<ExportNode, 'kind'>\n\n// A spread node carries the deprecated fields derived from its `names`, so only a value that differs is an override.\ntype Override<TValue> = { value: TValue | null | undefined; derived: TValue | null | undefined }\n\nfunction overrideSpace(names: Array<ModuleName>, { value, derived }: Override<boolean>): Array<ModuleName> {\n if (value == null || value === derived) return names\n const space = value ? 'type' : 'value'\n return names.map((item) => ({ ...item, space }))\n}\n\nconst isOverride = ({ value, derived }: Override<unknown>): boolean => value !== undefined && JSON.stringify(value) !== JSON.stringify(derived)\n\n/**\n * Creates an `ImportNode`. A node built from `names` also gets the deprecated fields. A deprecated `name` or\n * `isTypeOnly` that differs from the one `names` gives overrides it, so `{ ...imp, isTypeOnly: true }` still works.\n *\n * @example Named import\n * ```ts\n * createImport({ names: [{ name: 'useState' }], path: 'react' })\n * // import { useState } from 'react'\n * ```\n */\nexport function createImport(input: ImportInput): ImportNode {\n if (!input.names) return { ...input, name: input.name ?? [], kind: nodeKinds.import }\n const derived = toDeprecatedImport(input.names)\n if (isOverride({ value: input.name, derived: derived.name })) return { ...input, names: null, name: input.name ?? [], kind: nodeKinds.import }\n const names = overrideSpace(input.names, { value: input.isTypeOnly, derived: derived.isTypeOnly })\n return { ...input, ...toDeprecatedImport(names), names, kind: nodeKinds.import }\n}\n\n/**\n * Creates an `ExportNode`. A node built from `names` also gets the deprecated fields. A deprecated `name` or\n * `isTypeOnly` that differs from the one `names` gives overrides it.\n *\n * @example Named export\n * ```ts\n * createExport({ names: [{ name: 'Pet' }], path: './Pet' })\n * // export { Pet } from './Pet'\n * ```\n */\nexport function createExport(input: ExportInput): ExportNode {\n if (!input.names) return { ...input, kind: nodeKinds.export }\n const derived = toDeprecatedExport(input.names)\n if (isOverride({ value: input.name, derived: derived.name })) return { ...input, names: null, kind: nodeKinds.export }\n const names = overrideSpace(input.names, { value: input.isTypeOnly, derived: derived.isTypeOnly })\n return { ...input, ...toDeprecatedExport(names), names, kind: nodeKinds.export }\n}\n\n/**\n * Creates a `SourceNode` representing a fragment of source code within a file.\n *\n * @example\n * ```ts\n * createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')], export: true })\n * ```\n */\nexport const createSource = nodeFactory<SourceNode>(nodeKinds.source)\n\n/**\n * Input descriptor for {@link createFile}, before `id`, `name`, and `extname` are computed\n * and `imports`/`exports`/`sources` are deduplicated.\n */\nexport type UserFileNode<TMeta extends object = object> = Omit<FileNode<TMeta>, 'kind' | 'id' | 'name' | 'extname' | 'imports' | 'exports' | 'sources'> &\n Pick<Partial<FileNode<TMeta>>, 'imports' | 'exports' | 'sources'>\n\n/**\n * Creates a fully resolved `FileNode` from a file input descriptor.\n *\n * Computes:\n * - `id` SHA256 hash of the file path\n * - `name` `baseName` without extension\n * - `extname` extension extracted from `baseName`\n *\n * Deduplicates:\n * - `sources` via `combineSources`\n * - `exports` via `combineExports`\n * - `imports` via `combineImports` (also filters unused imports)\n *\n * @throws {Error} when `baseName` has no extension.\n *\n * @example\n * ```ts\n * const file = createFile({\n * baseName: 'petStore.ts',\n * path: 'src/models/petStore.ts',\n * sources: [createSource({ name: 'Pet', nodes: [createText('export type Pet = { id: number }')] })],\n * imports: [createImport({ name: ['z'], path: 'zod' })],\n * exports: [createExport({ name: ['Pet'], path: './petStore' })],\n * })\n * // file.id = SHA256 hash of 'src/models/petStore.ts'\n * // file.name = 'petStore'\n * // file.extname = '.ts'\n * ```\n *\n * @example Copy a real file into the output\n * ```ts\n * const file = createFile({\n * baseName: 'client.ts',\n * path: 'src/gen/client.ts',\n * copy: '/abs/path/to/templates/client.ts',\n * })\n * ```\n */\nexport function createFile<TMeta extends object = object>(input: UserFileNode<TMeta>): FileNode<TMeta> {\n const extname = path.extname(input.baseName) as `.${string}`\n if (!extname) {\n throw new Error(`No extname found for ${input.baseName}`)\n }\n\n const resolvedExports = input.exports?.length ? combineExports(input.exports) : []\n const resolvedSources = input.sources?.length ? combineSources(input.sources) : []\n\n // Skip building the source text and local-name set when there are no imports to resolve against them.\n const resolvedImports: Array<ImportNode> = (() => {\n if (!input.imports?.length) return []\n\n const sourceParts: Array<string> = []\n const localNames = new Set<string>()\n // Only the sources the file keeps count: an import used just by a dropped duplicate is unused.\n for (const item of resolvedSources) {\n const extracted = item.nodes && getNodeText(item.nodes)\n if (extracted) sourceParts.push(extracted)\n if (item.name) localNames.add(item.name)\n }\n const source = sourceParts.join('\\n') || undefined\n const combinedImports = combineImports(input.imports, resolvedExports, source)\n // Consolidating output (`mode: 'file'`) can put a symbol's definition and an import of it in the\n // same file: by path when the import still targets this file, by name when consolidation moved it.\n return combinedImports.flatMap((imp) => {\n if (imp.path === input.path) return []\n const names = getNames(imp)\n const kept = names.filter((item) => !localNames.has(item.alias ?? item.name))\n if (!kept.length) return []\n return [kept.length === names.length ? imp : createImport({ path: imp.path, ...(imp.root != null ? { root: imp.root } : {}), names: kept })]\n })\n })()\n\n return {\n ...input,\n kind: nodeKinds.file,\n id: hash('sha256', input.path, 'hex'),\n name: path.basename(input.baseName, extname),\n extname,\n imports: resolvedImports,\n exports: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AK,SAAS,KAAK,IAAI,CAAC;GAC5E,IAAI,CAAC,KAAK,QAAQ,OAAO,CAAC;GAC1B,OAAO,CAAC,KAAK,WAAW,MAAM,SAAS,MAAM,aAAa;IAAE,MAAM,IAAI;IAAM,GAAI,IAAI,QAAQ,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;IAAI,OAAO;GAAK,CAAC,CAAC;EAC7I,CAAC;CACH,EAAA,CAAG;CAEH,OAAO;EACL,GAAG;EACH,MAAMF,kBAAAA,UAAU;EAChB,KAAA,GAAIG,YAAAA,KAAAA,CAAK,UAAU,MAAM,MAAM,KAAK;EACpC,MAAMF,UAAAA,QAAK,SAAS,MAAM,UAAU,OAAO;EAC3C;EACA,SAAS;EACT,SAAS;EACT,SAAS;EACT,MAAO,MAAM,QAAQ,CAAC;CACxB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"file-azmmZwDb.cjs","names":["getNames","createFile","nodeKinds","getNodeText","createImport","CODE_NODE_TEXT_FIELDS"],"sources":["../src/utils/inline.ts","../src/file/index.ts"],"sourcesContent":["import { nodeKinds } from '../constants.ts'\nimport type { CodeNode } from '../nodes/code.ts'\nimport { createFile, createImport } from '../nodes/file.ts'\nimport type { FileNode, ImportNode, SourceNode } from '../nodes/file.ts'\nimport { getNames } from './moduleNames.ts'\nimport { CODE_NODE_TEXT_FIELDS, getNodeText } from './nodeText.ts'\n\ntype InlineFilesResult = {\n /**\n * Files that imported an inline name, rewritten to hold its definition.\n */\n files: Array<FileNode>\n /**\n * Paths of the virtual files, which are not written.\n */\n virtualPaths: Array<string>\n /**\n * One message per name that could not be inlined.\n */\n problems: Array<{ path: string; message: string }>\n}\n\ntype Definition = { expression: string; imports: Array<ImportNode> }\n\n/**\n * The language-specific half of {@link inlineFiles}, supplied by the parser that prints the file.\n */\nexport type InlineLanguage = {\n /**\n * Swaps in what `replace` returns for every identifier in `text` that references a name, skipping strings and comments.\n */\n replaceIdentifiers(text: string, replace: (name: string) => string | undefined): string\n /**\n * Makes `expression` safe to put where a name was, such as `(A | B)` in TypeScript.\n */\n wrap(expression: string): string\n}\n\ntype InlineFilesOptions = {\n /**\n * The inline support for a file's language, or `undefined` when it has none.\n */\n language: (file: FileNode) => InlineLanguage | undefined\n}\n\n/**\n * Replaces every name a file imports from a virtual file (one marked `inline`, so it is never written) with the body of that name's\n * declaration, until no inline names are left. The definitions' own imports move to the importing file.\n */\nexport function inlineFiles(files: ReadonlyArray<FileNode>, { language }: InlineFilesOptions): InlineFilesResult {\n const virtualFiles = new Map(files.filter(isInlineFile).map((file) => [file.path, file]))\n const result: InlineFilesResult = { files: [], virtualPaths: [...virtualFiles.keys()], problems: [] }\n if (virtualFiles.size === 0) return result\n\n // `null` marks a definition that is being resolved, so a name that reaches itself is a cycle.\n const definitions = new Map<string, Definition | null>()\n\n function define(path: string, name: string, from: string, lang: InlineLanguage): Definition | undefined {\n const key = `${path}\\0${name}`\n if (definitions.has(key)) {\n const definition = definitions.get(key)\n if (definition === null) result.problems.push({ path: from, message: `\"${name}\" from \"${path}\" is defined in terms of itself.` })\n return definition ?? undefined\n }\n\n const file = virtualFiles.get(path)!\n const expression = bodyOf(file.sources.find((source) => source.name === name))\n if (expression === undefined) {\n result.problems.push({ path: from, message: `\"${name}\" is imported from \"${path}\", which never writes it and has no inline definition for it.` })\n return undefined\n }\n\n definitions.set(key, null)\n const imports: Array<ImportNode> = []\n const { text, used } = replaceNames(expression, file, lang, imports)\n imports.push(...file.imports.flatMap((imp) => (virtualFiles.has(imp.path) ? [] : pickNames(imp, used))))\n\n const definition = { expression: text, imports }\n definitions.set(key, definition)\n return definition\n }\n\n // Pushes the imports the replaced definitions need onto `imports`; `used` holds the names left as they are.\n function replaceNames(input: string, file: FileNode, lang: InlineLanguage, imports: Array<ImportNode>) {\n const used = new Set<string>()\n const text = lang.replaceIdentifiers(input, (local) => {\n const target = findTarget(file, local)\n const definition = target && define(target.path, target.name, file.path, lang)\n if (!definition) {\n used.add(local)\n return undefined\n }\n\n imports.push(...definition.imports)\n return lang.wrap(definition.expression)\n })\n\n return { text, used }\n }\n\n function findTarget(file: FileNode, local: string): { path: string; name: string } | undefined {\n if (virtualFiles.has(file.path) && file.sources.some((source) => source.name === local)) return { path: file.path, name: local }\n\n for (const imp of file.imports) {\n const item = virtualFiles.has(imp.path) && getNames(imp).find((item) => (item.alias ?? item.name) === local)\n if (item) return { path: imp.path, name: item.name }\n }\n\n return undefined\n }\n\n for (const file of files) {\n if (virtualFiles.has(file.path) || !file.imports.some((imp) => virtualFiles.has(imp.path))) continue\n\n const lang = language(file)\n if (!lang) {\n result.problems.push({ path: file.path, message: `No parser for \"${file.extname}\" files supports inline sources.` })\n continue\n }\n\n const carried: Array<ImportNode> = []\n const sources = file.sources.map((source) => ({ ...source, nodes: rewriteNodes(source.nodes, (text) => replaceNames(text, file, lang, carried).text) }))\n\n // A carried import keeps its target; `root` moves to the importing file so the relative path is computed from there.\n const imports = [...file.imports.filter((imp) => !virtualFiles.has(imp.path)), ...carried.map((imp) => (imp.root ? { ...imp, root: file.path } : imp))]\n\n result.files.push(createFile({ ...file, sources, imports }))\n }\n\n return result\n}\n\n// A file of only deprecated per-source `inline` counts as inline too.\nfunction isInlineFile(file: FileNode): boolean {\n return !!file.inline || (file.sources.length > 0 && file.sources.every((source) => source.inline))\n}\n\n// The right-hand side of a `Const` or `Type`. A function body is not an expression, and printed text such as `Code` has none.\nfunction bodyOf(source: SourceNode | undefined): string | undefined {\n if (source?.inline) return source.inline.expression\n const node = source?.nodes?.length === 1 ? source.nodes[0] : undefined\n if (node?.kind !== nodeKinds.const && node?.kind !== nodeKinds.type) return undefined\n return getNodeText(node.nodes) || undefined\n}\n\nfunction pickNames(imp: ImportNode, used: ReadonlySet<string>): Array<ImportNode> {\n const names = getNames(imp).filter((item) => used.has(item.alias ?? item.name))\n return names.length > 0 ? [createImport({ path: imp.path, ...(imp.root != null ? { root: imp.root } : {}), names })] : []\n}\n\n// Rewrites the string fields `getNodeText` reads; JSDoc stays as written.\nfunction rewriteNodes(nodes: Array<CodeNode> | undefined, rewrite: (text: string) => string): Array<CodeNode> | undefined {\n return nodes?.map((node): CodeNode => {\n // Backward-compat: compiled plugins may still pass bare strings at runtime\n if (typeof node === 'string') return rewrite(node) as unknown as CodeNode\n if (node.kind === nodeKinds.break) return node\n\n const next = { ...node } as unknown as Record<string, unknown>\n for (const field of CODE_NODE_TEXT_FIELDS[node.kind] ?? []) {\n const value = next[field]\n if (Array.isArray(value)) next[field] = value.map(rewrite)\n if (typeof value === 'string' && value) next[field] = rewrite(value)\n }\n if ('nodes' in node && node.nodes) next.nodes = rewriteNodes(node.nodes, rewrite)\n return next as unknown as CodeNode\n })\n}\n","export { inlineFiles as inline } from '../utils/inline.ts'\nexport { getNames, getSpace } from '../utils/moduleNames.ts'\n"],"mappings":";;;;;;;;;AAiDA,SAAgB,YAAY,OAAgC,EAAE,YAAmD;CAC/G,MAAM,eAAe,IAAI,IAAI,MAAM,OAAO,YAAY,CAAC,CAAC,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;CACxF,MAAM,SAA4B;EAAE,OAAO,CAAC;EAAG,cAAc,CAAC,GAAG,aAAa,KAAK,CAAC;EAAG,UAAU,CAAC;CAAE;CACpG,IAAI,aAAa,SAAS,GAAG,OAAO;CAGpC,MAAM,8BAAc,IAAI,IAA+B;CAEvD,SAAS,OAAO,MAAc,MAAc,MAAc,MAA8C;EACtG,MAAM,MAAM,GAAG,KAAK,IAAI;EACxB,IAAI,YAAY,IAAI,GAAG,GAAG;GACxB,MAAM,aAAa,YAAY,IAAI,GAAG;GACtC,IAAI,eAAe,MAAM,OAAO,SAAS,KAAK;IAAE,MAAM;IAAM,SAAS,IAAI,KAAK,UAAU,KAAK;GAAkC,CAAC;GAChI,OAAO,cAAc,KAAA;EACvB;EAEA,MAAM,OAAO,aAAa,IAAI,IAAI;EAClC,MAAM,aAAa,OAAO,KAAK,QAAQ,MAAM,WAAW,OAAO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