@schema-engine/registry 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +94 -7
  2. package/dist/bind-registry.d.ts +6 -3
  3. package/dist/bind-registry.js +1 -1
  4. package/dist/bind-registry.js.map +4 -4
  5. package/dist/chunk-24SNVXNP.js +2 -0
  6. package/dist/chunk-24SNVXNP.js.map +7 -0
  7. package/dist/chunk-55J6XMHW.js +0 -0
  8. package/dist/chunk-55J6XMHW.js.map +7 -0
  9. package/dist/chunk-BY4BKVNV.js +1 -0
  10. package/dist/chunk-BY4BKVNV.js.map +7 -0
  11. package/dist/chunk-DDOMNXV7.js +1 -0
  12. package/dist/chunk-DDOMNXV7.js.map +7 -0
  13. package/dist/chunk-DE7GQKZP.js +3 -0
  14. package/dist/chunk-DE7GQKZP.js.map +7 -0
  15. package/dist/chunk-FRJ453UJ.js +1 -0
  16. package/dist/chunk-FRJ453UJ.js.map +7 -0
  17. package/dist/chunk-GX6PAJLU.js +1 -0
  18. package/dist/chunk-GX6PAJLU.js.map +7 -0
  19. package/dist/chunk-HBQNBR6L.js +1 -0
  20. package/dist/chunk-HBQNBR6L.js.map +7 -0
  21. package/dist/chunk-L3ZXHX7S.js +1 -0
  22. package/dist/chunk-L3ZXHX7S.js.map +7 -0
  23. package/dist/chunk-M3SYVKZK.js +1 -0
  24. package/dist/chunk-M3SYVKZK.js.map +7 -0
  25. package/dist/chunk-MWH2GNPD.js +1 -0
  26. package/dist/chunk-MWH2GNPD.js.map +7 -0
  27. package/dist/chunk-O5CRFISG.js +1 -0
  28. package/dist/chunk-O5CRFISG.js.map +7 -0
  29. package/dist/chunk-P3DDHPDA.js +1 -0
  30. package/dist/chunk-P3DDHPDA.js.map +7 -0
  31. package/dist/chunk-UH3CEF45.js +1 -0
  32. package/dist/chunk-UH3CEF45.js.map +7 -0
  33. package/dist/create-registry.d.ts +70 -10
  34. package/dist/create-registry.js +1 -1
  35. package/dist/create-registry.js.map +4 -4
  36. package/dist/export-tree-schema.d.ts +112 -0
  37. package/dist/export-tree-schema.js +1 -0
  38. package/dist/export-tree-schema.js.map +7 -0
  39. package/dist/format-issue-path.js +1 -1
  40. package/dist/format-issue-path.js.map +4 -4
  41. package/dist/index.d.ts +4 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +4 -4
  44. package/dist/json-schema/embedder.d.ts +119 -0
  45. package/dist/json-schema/embedder.js +1 -0
  46. package/dist/json-schema/embedder.js.map +7 -0
  47. package/dist/json-schema/index.d.ts +5 -0
  48. package/dist/json-schema/index.js +1 -0
  49. package/dist/json-schema/index.js.map +7 -0
  50. package/dist/json-schema/slot.d.ts +46 -0
  51. package/dist/json-schema/slot.js +1 -0
  52. package/dist/json-schema/slot.js.map +7 -0
  53. package/dist/json-schema/standard.d.ts +44 -0
  54. package/dist/json-schema/standard.js +1 -0
  55. package/dist/json-schema/standard.js.map +7 -0
  56. package/dist/parse-node.d.ts +69 -10
  57. package/dist/parse-node.js +1 -1
  58. package/dist/parse-node.js.map +4 -4
  59. package/dist/parse-tree.d.ts +111 -35
  60. package/dist/parse-tree.js +1 -1
  61. package/dist/parse-tree.js.map +4 -4
  62. package/dist/registry-error.d.ts +82 -0
  63. package/dist/registry-error.js +1 -0
  64. package/dist/registry-error.js.map +7 -0
  65. package/dist/standard-schema.d.ts +9 -0
  66. package/dist/standard-schema.js +1 -1
  67. package/dist/standard-schema.js.map +4 -4
  68. package/dist/tree-types.d.ts +152 -0
  69. package/dist/tree-types.js +0 -0
  70. package/dist/tree-types.js.map +7 -0
  71. package/dist/types.d.ts +37 -7
  72. package/dist/types.js +1 -0
  73. package/dist/yaml/index.js +1 -4
  74. package/dist/yaml/index.js.map +4 -4
  75. package/dist/yaml/parse.js +1 -2
  76. package/dist/yaml/parse.js.map +4 -4
  77. package/dist/yaml/stringify.js +1 -3
  78. package/dist/yaml/stringify.js.map +4 -4
  79. package/package.json +13 -9
  80. package/skill/SKILL.md +9 -9
  81. package/skill/reference/registry.md +57 -18
  82. package/dist/base-registry.d.ts +0 -73
  83. package/dist/base-registry.js +0 -1
  84. package/dist/base-registry.js.map +0 -7
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/base-registry.ts", "../src/create-registry.ts", "../src/bind-registry.ts", "../src/standard-schema.ts", "../src/parse-node.ts", "../src/parse-tree.ts", "../src/format-issue-path.ts"],
4
- "sourcesContent": ["import { Logger } from '@ecopages/logger';\nimport type { BaseRegistration } from './types.js';\n\nconst logger = new Logger('[@schema-engine/registry]');\n\n/**\n * Base Registry - Abstract class for all registries\n *\n * Provides common registration, retrieval, and management functionality.\n * Each registry extends this to add type-specific behavior.\n *\n * All registrations must extend BaseRegistration which provides the unified `$type` field.\n *\n * @template TKey - The key type (typically string)\n * @template TValue - The value type (registration object extending BaseRegistration)\n */\nexport abstract class BaseRegistry<TKey extends string, TValue extends BaseRegistration> {\n\tprotected items = new Map<TKey, TValue>();\n\n\t/**\n\t * Get the registry name for logging purposes.\n\t */\n\tabstract get registryName(): string;\n\n\t/**\n\t * Extract the key from an item.\n\t * Uses the unified `$type` field from BaseRegistration.\n\t * @param item - The item to extract the key from\n\t */\n\tprotected getItemKey(item: TValue): TKey {\n\t\treturn item.$type as TKey;\n\t}\n\n\t/**\n\t * Extract the name from an item for logging.\n\t * Uses the `name` field from metadata.\n\t * @param item - The item to extract the name from\n\t */\n\tprotected getItemName(item: TValue): string {\n\t\treturn item.metadata.name;\n\t}\n\n\t/**\n\t * Register an item.\n\t *\n\t * @param item - The item to register\n\t */\n\tregister(item: TValue): void {\n\t\tconst key = this.getItemKey(item);\n\t\tconst name = this.getItemName(item);\n\n\t\tif (this.items.has(key)) {\n\t\t\tconst existing = this.items.get(key);\n\t\t\tconst existingName = existing ? this.getItemName(existing) : 'unknown';\n\t\t\tlogger.warn(`Overriding ${this.registryName}: ${key}`, {\n\t\t\t\tpreviousName: existingName,\n\t\t\t\tnewName: name,\n\t\t\t});\n\t\t}\n\n\t\tthis.items.set(key, item);\n\t\tlogger.debug(`Registered ${this.registryName}: ${key}`, {\n\t\t\tname,\n\t\t});\n\t}\n\n\t/**\n\t * Check if an item is registered.\n\t *\n\t * @param key - The key to check\n\t * @returns True if the item is registered\n\t */\n\thas(key: TKey): boolean {\n\t\treturn this.items.has(key);\n\t}\n\n\t/**\n\t * Get a registered item.\n\t *\n\t * @param key - The key to retrieve\n\t * @returns The item or undefined if not found\n\t */\n\tget(key: TKey): TValue | undefined {\n\t\treturn this.items.get(key);\n\t}\n\n\t/**\n\t * Get all registered items.\n\t *\n\t * @returns Array of all registered items\n\t */\n\tgetAll(): TValue[] {\n\t\treturn Array.from(this.items.values());\n\t}\n\n\t/**\n\t * Get all registered keys.\n\t *\n\t * @returns Array of all registered keys\n\t */\n\tgetAllKeys(): TKey[] {\n\t\treturn Array.from(this.items.keys());\n\t}\n\n\t/**\n\t * Get the number of registered items.\n\t *\n\t * @returns The number of items in the registry\n\t */\n\tget size(): number {\n\t\treturn this.items.size;\n\t}\n\n\t/**\n\t * Clear all registered items. Primarily for testing.\n\t */\n\tclear(): void {\n\t\tthis.items.clear();\n\t\tlogger.debug(`${this.registryName} cleared`);\n\t}\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * A registry built once from a list of registrations. It has no `register` or\n * `clear`; to change its contents, build another registry from a new list.\n */\nexport interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseRegistration> {\n\t/** Label used in build errors, for example `Element`. */\n\treadonly kind: string;\n\t/** Number of distinct `$type` keys. */\n\treadonly size: number;\n\tget(key: string): TRegistration | undefined;\n\thas(key: string): boolean;\n\t/** Registrations in first-registration order. The array is frozen. */\n\tall(): readonly TRegistration[];\n\t/** `$type` keys in first-registration order. The array is frozen. */\n\tkeys(): readonly string[];\n}\n\n/**\n * Require a registration schema to implement Standard Schema.\n *\n * @param schema - Value to check\n * @param context - Subject of the error message, for example `Element 'text' schema`\n * @throws {Error} When `schema` has no `~standard.validate` function\n */\nexport function assertStandardSchema(schema: unknown, context = 'Registration schema'): StandardSchemaV1 {\n\tconst standard =\n\t\tschema !== null && (typeof schema === 'object' || typeof schema === 'function')\n\t\t\t? (schema as Partial<StandardSchemaV1>)['~standard']\n\t\t\t: undefined;\n\tif (typeof standard?.validate !== 'function') {\n\t\tthrow new Error(`${context} must implement Standard Schema (~standard.validate).`);\n\t}\n\treturn schema as StandardSchemaV1;\n}\n\n/**\n * Check the `childPaths` of a registration.\n *\n * @remarks\n * Two paths that read the same once joined with dots would share one key of `ParsedNode.children`, so they count as\n * one path declared twice. A path that runs through another one would reach inside a child node, whose own\n * registration says where its children are, so the walk would visit the same node from two parents.\n */\nfunction assertChildPaths(childPaths: unknown, context: string): void {\n\tif (childPaths === undefined) return;\n\tif (!Array.isArray(childPaths)) throw new Error(`${context} childPaths must be a list of key paths.`);\n\tconst paths: string[][] = [];\n\tfor (const keys of childPaths as unknown[]) {\n\t\tif (!Array.isArray(keys) || keys.length === 0 || keys.some((key) => typeof key !== 'string' || key === '')) {\n\t\t\tthrow new Error(`${context} childPaths must hold non-empty lists of non-empty keys.`);\n\t\t}\n\t\tpaths.push(keys as string[]);\n\t}\n\tconst joined = paths.map((keys) => keys.join('.'));\n\tfor (const [index, keys] of paths.entries()) {\n\t\tconst name = keys.join('.');\n\t\tif (joined.indexOf(name) !== index) throw new Error(`${context} declares the child path '${name}' twice.`);\n\t\tconst outer = paths.find(\n\t\t\t(other) => other.length < keys.length && other.every((key, position) => key === keys[position]),\n\t\t);\n\t\tif (outer) {\n\t\t\tthrow new Error(`${context} child path '${name}' runs through the child path '${outer.join('.')}'.`);\n\t\t}\n\t}\n}\n\n/** Options of {@link createRegistry}. */\nexport interface CreateRegistryOptions {\n\t/**\n\t * What a second registration of one `$type` does: replace the first (`'override'`, the default) or fail the build\n\t * (`'error'`).\n\t *\n\t * @remarks\n\t * `'override'` is how `[...defaults, custom]` replaces a built-in. Use `'error'` for a catalog where a repeated\n\t * key is always a mistake, such as component keys.\n\t */\n\treadonly duplicates?: 'override' | 'error';\n}\n\n/**\n * Build a frozen, read-only registry from a list of registrations.\n *\n * @param kind - Label for errors, for example `Element`\n * @param registrations - Registrations to store, keyed by `$type`\n * @param options - How to treat a repeated `$type`, see {@link CreateRegistryOptions}\n * @throws {Error} `Widget 'card' is registered twice.` when `duplicates` is `'error'` and a `$type` repeats, before any\n * schema is checked\n * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema\n * @throws {Error} Naming the `$type` when a winning registration's `childPaths` is not a list of non-empty key lists, repeats a path, or has a path that runs through another\n *\n * @remarks\n * By default a later registration with the same `$type` replaces the earlier one without a\n * warning, so `[...defaults, custom]` is the way to override. A replaced key\n * keeps its first position. Only the winning registration of each key is\n * checked. The registry stores a frozen shallow copy of each winner, taken at\n * build, and leaves the objects you passed untouched. Later assignments to or\n * spies on those objects do not reach the registry, so patch before building or\n * build a new registry. The copy shares nested values such as `schema` with the\n * original.\n *\n * Use {@link BaseRegistry} instead when registrations arrive at runtime.\n */\nexport function createRegistry<const TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly TRegistration[],\n\toptions: CreateRegistryOptions = {},\n): ReadOnlyRegistry<TRegistration> {\n\tconst winners = new Map<string, TRegistration>();\n\tfor (const registration of registrations) {\n\t\tif (options.duplicates === 'error' && winners.has(registration.$type)) {\n\t\t\tthrow new Error(`${kind} '${registration.$type}' is registered twice.`);\n\t\t}\n\t\twinners.set(registration.$type, registration);\n\t}\n\tconst entries = new Map<string, Readonly<TRegistration>>();\n\tfor (const [key, registration] of winners) {\n\t\tassertStandardSchema(registration.schema, `${kind} '${key}' schema`);\n\t\tassertChildPaths(registration.childPaths, `${kind} '${key}'`);\n\t\tentries.set(key, Object.freeze({ ...registration }));\n\t}\n\tconst all = Object.freeze([...entries.values()]);\n\tconst keys = Object.freeze([...entries.keys()]);\n\n\treturn Object.freeze({\n\t\tkind,\n\t\tsize: entries.size,\n\t\tget: (key: string) => entries.get(key),\n\t\thas: (key: string) => entries.has(key),\n\t\tall: () => all,\n\t\tkeys: () => keys,\n\t});\n}\n", "import { createRegistry, type ReadOnlyRegistry } from './create-registry.js';\nimport type { BaseRegistration } from './types.js';\n\n/** What a binding may not set: the keys its contract already defines. */\ntype ContractKeys<TContract> = { readonly [K in keyof TContract]?: never };\n\n/** The binding each `$type` of a contracts registry takes, which may not set a key of its own contract. */\ntype BindingsOf<TContract extends BaseRegistration> = {\n\treadonly [K in TContract['$type']]: Readonly<Record<string, unknown>> &\n\t\tContractKeys<Extract<TContract, { $type: K }>>;\n};\n\n/** The keys of `TBindings` that no contract answers; each is typed `never`, so naming one is a compile error. */\ntype ExtraBindings<TBindings, TContract extends BaseRegistration> = {\n\treadonly [K in Exclude<keyof TBindings, TContract['$type']>]: never;\n};\n\n/**\n * One binding per `$type` of a contracts registry, every binding of the same shape.\n *\n * @remarks\n * Use it with `satisfies` to fix what one renderer binds:\n * `{ card: { render: Card } } satisfies RegistryBindings<typeof contracts, ReactBinding>`.\n * A contracts registry whose `$type` is a plain `string` has no known keys to require, so only {@link bindRegistry}'s\n * build-time checks apply to it.\n */\nexport type RegistryBindings<TRegistry extends ReadOnlyRegistry, TBinding extends object = object> =\n\tTRegistry extends ReadOnlyRegistry<infer TContract> ? { readonly [K in TContract['$type']]: TBinding } : never;\n\n/** A contract merged with the binding its `$type` names, member by member. */\nexport type BoundRegistration<TContract extends BaseRegistration, TBindings> = TContract extends unknown\n\t? TContract & TBindings[TContract['$type'] & keyof TBindings]\n\t: never;\n\n/** The `$type`s of a contracts registry that are known literals; `never` when the contracts are typed only as `string`. */\ntype KnownTypes<TContract extends BaseRegistration> = string extends TContract['$type'] ? never : TContract['$type'];\n\n/**\n * What {@link bindRegistry} returns: a read-only registry whose `get` also answers a known `$type` without `undefined`.\n *\n * @remarks\n * `get` returns the registration of that exact `$type` when the contracts name their `$type`s as literals, because\n * `bindRegistry` guarantees every contract is bound. The `string` overload stays for a `$type` read from a document.\n */\nexport interface BoundRegistry<TContract extends BaseRegistration, TBindings> extends ReadOnlyRegistry<\n\tBoundRegistration<TContract, TBindings>\n> {\n\tget<K extends KnownTypes<TContract>>(key: K): Extract<BoundRegistration<TContract, TBindings>, { $type: K }>;\n\tget(key: string): BoundRegistration<TContract, TBindings> | undefined;\n}\n\n/**\n * Build a renderer's registry from a registry of contracts and one binding per `$type`.\n *\n * @param contracts - Registrations without the renderer's part: the `$type`, schema and metadata, plus what the domain fixes\n * @param bindings - What this renderer adds to each contract, keyed by `$type`, such as `render` or a tag name\n * @throws {Error} `Widget 'card' has no binding.` when a contract has no binding\n * @throws {Error} `Widget binding 'crad' names no registration.` when a binding's key is no contract's `$type`\n * @throws {Error} `Widget 'card' binding sets 'schema', which the contract defines.` when a binding sets a contract key\n *\n * @remarks\n * The result is a frozen registry built with {@link createRegistry}, so it keeps the contracts' order and checks every\n * schema again. Each registration is a shallow merge, so `schema`, `metadata` and every other value of a contract is\n * shared by identity between all the renderers that bind it. A binding is renderer-only data (a `render` function, a\n * tag name) and never carries schema or metadata.\n *\n * With contracts typed by literal `$type`, a missing binding, an extra one and a binding that sets a contract key are\n * also compile errors. With contracts typed only as `string` the three checks run when the registry is built.\n */\nexport function bindRegistry<TContract extends BaseRegistration, const TBindings extends BindingsOf<TContract>>(\n\tcontracts: ReadOnlyRegistry<TContract>,\n\tbindings: TBindings & ExtraBindings<TBindings, TContract>,\n): BoundRegistry<TContract, TBindings>;\nexport function bindRegistry(\n\tcontracts: ReadOnlyRegistry,\n\tbindings: Readonly<Record<string, object>>,\n): ReadOnlyRegistry<BaseRegistration> {\n\tconst { kind } = contracts;\n\tfor (const key of Object.keys(bindings)) {\n\t\tif (!contracts.has(key)) throw new Error(`${kind} binding '${key}' names no registration.`);\n\t}\n\tconst bound = contracts.all().map((contract) => {\n\t\tconst binding: unknown = Object.hasOwn(bindings, contract.$type) ? bindings[contract.$type] : undefined;\n\t\tif (typeof binding !== 'object' || binding === null) {\n\t\t\tthrow new Error(`${kind} '${contract.$type}' has no binding.`);\n\t\t}\n\t\tfor (const key of Object.keys(binding)) {\n\t\t\tif (Object.hasOwn(contract, key)) {\n\t\t\t\tthrow new Error(`${kind} '${contract.$type}' binding sets '${key}', which the contract defines.`);\n\t\t\t}\n\t\t}\n\t\treturn { ...contract, ...binding };\n\t});\n\treturn createRegistry(kind, bound);\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type StandardSchemaIssue = StandardSchemaV1.Issue;\n\nexport type StandardSchemaSafeParseResult<T> =\n\t{ success: true; data: T } | { success: false; error: { issues: StandardSchemaIssue[] } };\n\n/**\n * Validate `value` with a Standard Schema without throwing.\n *\n * @param schema - Standard Schema to run\n * @param value - Input to validate\n * @throws {Error} When the schema validates asynchronously or returns a malformed result\n *\n * @remarks\n * Only synchronous validation is supported, because the callers (registry lookups, form validation,\n * action parsing) need an immediate result.\n */\nexport function safeParseStandardSchema<TInput, TOutput>(\n\tschema: StandardSchemaV1<TInput, TOutput>,\n\tvalue: TInput,\n): StandardSchemaSafeParseResult<TOutput> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\n\tconst syncResult = result as StandardSchemaV1.Result<TOutput>;\n\n\tif (syncResult.issues !== undefined) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tissues: [...syncResult.issues],\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { success: true, data: syncResult.value };\n}\n\n/**\n * A Standard Schema that validates with a function, for a check that is not a schema library's.\n *\n * @param validate - Returns `{ value }` for an input that passes, or `{ issues }` for one that does not\n *\n * @remarks\n * The schema reports `schema-engine` as its vendor and is synchronous, as {@link safeParseStandardSchema} requires.\n * `TInput` only types what the schema accepts, so an authoring type can be inferred from it; `validate` still receives `unknown`.\n */\nexport function standardSchema<TOutput, TInput = unknown>(\n\tvalidate: (value: unknown) => StandardSchemaV1.Result<TOutput>,\n): StandardSchemaV1<TInput, TOutput> {\n\treturn { '~standard': { version: 1, vendor: 'schema-engine', validate } };\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseStandardSchema, type StandardSchemaIssue } from './standard-schema.js';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * What {@link safeParseNode} needs of a registry: the registration of a `$type`, of which it reads the schema.\n * Both registry kinds fit.\n */\nexport interface NodeLookup<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> {\n\tget(key: string): TRegistration | undefined;\n\t/**\n\t * A sentence that follows the message of a `$type` `get` does not answer, such as where to register it.\n\t *\n\t * @remarks\n\t * The message is `No registration for $type 'x'.`, a space and the hint.\n\t */\n\thint?: string;\n}\n\n/**\n * What {@link safeParseNode} returns: the registration with the node's validated configuration, or every issue found.\n *\n * @remarks\n * The success branch has one member per registration of a typed registry, so checking `$type` (the node's, repeated at\n * the top of the result because TypeScript narrows a union only by a property of the union itself) narrows\n * `registration` and `data` together. A registration that does not declare its `$type`, such as a lookup typed by\n * `{ schema }` alone, leaves it a `string`. A registry typed as plain `BaseRegistration` has no concrete schema to\n * read, so its `data` is `unknown`.\n */\nexport type SafeParseNodeResult<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> =\n\t| (TRegistration extends unknown\n\t\t\t? {\n\t\t\t\t\tsuccess: true;\n\t\t\t\t\t$type: TRegistration extends { $type: infer TType extends string } ? TType : string;\n\t\t\t\t\tregistration: TRegistration;\n\t\t\t\t\tdata: StandardSchemaV1.InferOutput<TRegistration['schema']>;\n\t\t\t\t}\n\t\t\t: never)\n\t| { success: false; issues: StandardSchemaIssue[] };\n\n/**\n * The message for a `$type` no registration answers, as {@link safeParseNode} reports it.\n *\n * @param type - The `$type` that found nothing\n * @param hint - A sentence that follows the message, as {@link NodeLookup.hint} gives it\n *\n * @remarks\n * Exported so a caller that has to throw for the same case, instead of returning an issue, says the same thing.\n */\nexport function unregisteredTypeMessage(type: string, hint?: string): string {\n\tconst message = `No registration for $type '${type}'.`;\n\treturn hint ? `${message} ${hint}` : message;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Check one node against the registration its `$type` names, without throwing.\n *\n * @param registry - Where the node's `$type` finds its registration\n * @param node - The node as it arrived, for example one entry of a parsed JSON document\n * @param path - Where the node sits in its document. Every issue's `path` starts with it.\n *\n * @remarks\n * An issue points at the value that is wrong, as a schema reports it, so an editor can mark that value and a YAML\n * mapper finds its line: a node that is not an object is an issue at `path`; an object without a string `$type`, and\n * a `$type` no registration answers, are issues at `[...path, '$type']`, where a schema reports a missing required key.\n * The lookup's `hint` adds to the message of the last.\n * Otherwise the issues are those of the registration's schema, with `path` in front of the path the schema reported.\n *\n * `data` is what the schema returned, so its defaults and transforms apply. Its type is the schema output of the\n * registration that `registration.$type` names, for a registry typed by registrations with literal `$type`s, and\n * `unknown` for one typed as `BaseRegistration`. TypeScript cannot follow the runtime lookup from the node's string\n * `$type` to a registration, so the function returns `data` through one cast to that type: it is the value the matched\n * registration's own schema returned. The node is checked on its own: {@link safeParseTree} walks a tree with it,\n * passing each child its own `path`.\n *\n * @throws {Error} When the registration's schema validates asynchronously, as {@link safeParseStandardSchema} does.\n */\nexport function safeParseNode<TRegistration extends Pick<BaseRegistration, 'schema'>>(\n\tregistry: NodeLookup<TRegistration>,\n\tnode: unknown,\n\tpath: NonNullable<StandardSchemaIssue['path']> = [],\n): SafeParseNodeResult<TRegistration> {\n\tif (!isRecord(node)) {\n\t\treturn { success: false, issues: [{ message: 'Expected an object with a string $type.', path }] };\n\t}\n\tconst type = node.$type;\n\tif (typeof type !== 'string') {\n\t\treturn { success: false, issues: [{ message: 'Expected a string $type.', path: [...path, '$type'] }] };\n\t}\n\tconst registration = registry.get(type);\n\tif (!registration) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: [{ message: unregisteredTypeMessage(type, registry.hint), path: [...path, '$type'] }],\n\t\t};\n\t}\n\tconst parsed = safeParseStandardSchema(registration.schema, node);\n\tif (parsed.success) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\t$type: type,\n\t\t\tregistration,\n\t\t\tdata: parsed.data,\n\t\t} as SafeParseNodeResult<TRegistration>;\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\tissues: parsed.error.issues.map((issue) => ({ ...issue, path: [...path, ...(issue.path ?? [])] })),\n\t};\n}\n", "import { safeParseNode, type NodeLookup } from './parse-node.js';\nimport type { StandardSchemaIssue } from './standard-schema.js';\nimport type { BaseRegistration } from './types.js';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\ntype TreeRegistration = Pick<BaseRegistration, 'schema' | 'childPaths'>;\n\n/**\n * One node of a validated document: its registration, the data its schema returned, where it sits and its children.\n *\n * @remarks\n * `$type` is the node's own, repeated at the top for the same reason as on {@link SafeParseNodeResult}: checking it\n * narrows `registration` and `data` together. `children` has one entry per child path the registration declares that\n * the node has a value at, keyed by the keys of the path joined with dots (`['engine', 'controls']` is\n * `'engine.controls'`): a list of nodes for an array, one node otherwise, in document order. A child may be of any\n * registration of the lookup, so `children` holds nodes of the whole union, not of the parent's registration.\n */\nexport type ParsedNode<TRegistration extends TreeRegistration> = ParsedNodeOf<TRegistration, TRegistration>;\n\n/**\n * One member of {@link ParsedNode} per registration.\n *\n * @remarks\n * `TAll` carries the whole union past the distribution over `TMember`: inside the distributive branch `TMember` is one\n * registration, which would type every child as a node of its parent's registration.\n */\ntype ParsedNodeOf<TMember extends TreeRegistration, TAll extends TreeRegistration> = TMember extends unknown\n\t? {\n\t\t\t$type: TMember extends { $type: infer TType extends string } ? TType : string;\n\t\t\tregistration: TMember;\n\t\t\tdata: StandardSchemaV1.InferOutput<TMember['schema']>;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: Readonly<Record<string, ParsedNode<TAll> | readonly ParsedNode<TAll>[]>>;\n\t\t}\n\t: never;\n\n/** What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found. */\nexport type SafeParseTreeResult<TRegistration extends TreeRegistration = BaseRegistration> =\n\t{ success: true; tree: ParsedNode<TRegistration> } | { success: false; issues: StandardSchemaIssue[] };\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * The value a document holds at a child path.\n *\n * @remarks\n * Only the document's own keys count: a key a plain object inherits, such as `constructor`, is no child.\n */\nfunction valueAt(node: Record<PropertyKey, unknown>, keys: readonly string[]): unknown {\n\tlet current: unknown = node;\n\tfor (const key of keys) {\n\t\tif (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;\n\t\tcurrent = current[key];\n\t}\n\treturn current;\n}\n\n/**\n * Add a child under its path key as an own, enumerable entry.\n *\n * @remarks\n * A plain assignment under the key `__proto__` would replace the object's prototype instead of adding an entry.\n */\nfunction setChild<TValue>(children: Record<string, TValue>, key: string, value: TValue): void {\n\tObject.defineProperty(children, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/**\n * Check a whole document, node by node, without throwing.\n *\n * @param registry - Where each node's `$type` finds its registration\n * @param root - The document's root node, as it arrived\n * @param path - Where the root sits in a larger document; every issue's `path` starts with it\n *\n * @remarks\n * Each node goes through {@link safeParseNode} with its full path, so the issues are those of one node, at the\n * position the document has them. A registration says where its children are with `childPaths`: each path is read\n * from the node as authored, a missing value is no children, an array is walked item by item and an object is one\n * child. Any other value at a child path is an issue at that path (`Expected a node or a list of nodes.`), and so is a\n * node that contains itself. A node whose own schema fails is not walked further, but its siblings still are, so one\n * call reports every issue of the document. The tree is returned only when there are none.\n *\n * One lookup serves the whole tree; which `$type`s a position accepts is the parent's schema to say.\n *\n * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does.\n */\nexport function safeParseTree<TRegistration extends TreeRegistration>(\n\tregistry: NodeLookup<TRegistration>,\n\troot: unknown,\n\tpath: NonNullable<StandardSchemaIssue['path']> = [],\n): SafeParseTreeResult<TRegistration> {\n\tconst issues: StandardSchemaIssue[] = [];\n\n\tfunction walk(\n\t\tnode: unknown,\n\t\tnodePath: NonNullable<StandardSchemaIssue['path']>,\n\t\tancestors: readonly unknown[],\n\t): ParsedNode<TRegistration> | undefined {\n\t\tif (ancestors.includes(node)) {\n\t\t\tissues.push({ message: 'A node cannot contain itself.', path: nodePath });\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parsed = safeParseNode(registry, node, nodePath);\n\t\tif (!parsed.success) {\n\t\t\tissues.push(...parsed.issues);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst children: Record<string, ParsedNode<TRegistration> | ParsedNode<TRegistration>[]> = {};\n\t\tif (isRecord(node)) {\n\t\t\tfor (const keys of parsed.registration.childPaths ?? []) {\n\t\t\t\tconst value = valueAt(node, keys);\n\t\t\t\tconst childPath = [...nodePath, ...keys];\n\t\t\t\tconst trail = [...ancestors, node];\n\t\t\t\tif (Array.isArray(value)) {\n\t\t\t\t\tconst items = value.map((item, index) => walk(item, [...childPath, index], trail));\n\t\t\t\t\tsetChild(\n\t\t\t\t\t\tchildren,\n\t\t\t\t\t\tkeys.join('.'),\n\t\t\t\t\t\titems.filter((item) => item !== undefined),\n\t\t\t\t\t);\n\t\t\t\t} else if (isRecord(value)) {\n\t\t\t\t\tconst child = walk(value, childPath, trail);\n\t\t\t\t\tif (child) setChild(children, keys.join('.'), child);\n\t\t\t\t} else if (value !== undefined) {\n\t\t\t\t\tissues.push({ message: 'Expected a node or a list of nodes.', path: childPath });\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t$type: parsed.$type,\n\t\t\tregistration: parsed.registration,\n\t\t\tdata: parsed.data,\n\t\t\tpath: nodePath,\n\t\t\tchildren,\n\t\t} as ParsedNode<TRegistration>;\n\t}\n\n\tconst tree = walk(root, path, []);\n\treturn tree && issues.length === 0 ? { success: true, tree } : { success: false, issues };\n}\n", "import type { StandardSchemaIssue } from './standard-schema.js';\n\nfunction childOf(node: unknown, key: PropertyKey): unknown {\n\treturn typeof node === 'object' && node !== null ? Reflect.get(node, key) : undefined;\n}\n\n/**\n * A Standard Schema issue path as it reads in an error message: object keys joined by dots, array\n * indexes in brackets, for example `steps[0].elements[2].grid.width`. A missing or empty path is the\n * empty string.\n *\n * @param path The `path` of a Standard Schema issue. A segment is a key or an object `{ key }`.\n * @param source The document the path points into. With it, an array item that has a string `id` is\n * followed by the id in parentheses, `steps[0] (main).elements[2] (email).grid.width`, so a log of a\n * document with many nodes names the one it means.\n */\nexport function formatIssuePath(path: StandardSchemaIssue['path'], source?: unknown): string {\n\tlet node = source;\n\tlet text = '';\n\tfor (const segment of path ?? []) {\n\t\tconst key = typeof segment === 'object' ? segment.key : segment;\n\t\tnode = childOf(node, key);\n\t\tif (typeof key === 'number') {\n\t\t\tconst id = childOf(node, 'id');\n\t\t\ttext += typeof id === 'string' && id ? `[${key}] (${id})` : `[${key}]`;\n\t\t} else {\n\t\t\ttext += text ? `.${String(key)}` : String(key);\n\t\t}\n\t}\n\treturn text;\n}\n"],
5
- "mappings": "AAAA,OAAS,UAAAA,MAAc,mBAGvB,IAAMC,EAAS,IAAID,EAAO,2BAA2B,EAa/BE,EAAf,KAAkF,CAC9E,MAAQ,IAAI,IAYZ,WAAWC,EAAoB,CACxC,OAAOA,EAAK,KACb,CAOU,YAAYA,EAAsB,CAC3C,OAAOA,EAAK,SAAS,IACtB,CAOA,SAASA,EAAoB,CAC5B,IAAMC,EAAM,KAAK,WAAWD,CAAI,EAC1BE,EAAO,KAAK,YAAYF,CAAI,EAElC,GAAI,KAAK,MAAM,IAAIC,CAAG,EAAG,CACxB,IAAME,EAAW,KAAK,MAAM,IAAIF,CAAG,EAC7BG,EAAeD,EAAW,K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,GAASA,IAAS,MAAS,CAC1C,CACD,SAAWtB,EAASC,CAAK,EAAG,CAC3B,IAAMuB,EAAQV,EAAKb,EAAOkB,EAAWC,CAAK,EACtCI,GAAOjB,EAASC,EAAUJ,EAAK,KAAK,GAAG,EAAGoB,CAAK,CACpD,MAAWvB,IAAU,QACpBY,EAAO,KAAK,CAAE,QAAS,sCAAuC,KAAMM,CAAU,CAAC,CAEjF,CAED,MAAO,CACN,MAAOF,EAAO,MACd,aAAcA,EAAO,aACrB,KAAMA,EAAO,KACb,KAAMF,EACN,SAAAP,CACD,CACD,CAEA,IAAMiB,EAAOX,EAAKH,EAAMC,EAAM,CAAC,CAAC,EAChC,OAAOa,GAAQZ,EAAO,SAAW,EAAI,CAAE,QAAS,GAAM,KAAAY,CAAK,EAAI,CAAE,QAAS,GAAO,OAAAZ,CAAO,CACzF,CC3IA,SAASa,EAAQC,EAAeC,EAA2B,CAC1D,OAAO,OAAOD,GAAS,UAAYA,IAAS,KAAO,QAAQ,IAAIA,EAAMC,CAAG,EAAI,MAC7E,CAYO,SAASC,EAAgBC,EAAmCC,EAA0B,CAC5F,IAAIJ,EAAOI,EACPC,EAAO,GACX,QAAWC,KAAWH,GAAQ,CAAC,EAAG,CACjC,IAAMF,EAAM,OAAOK,GAAY,SAAWA,EAAQ,IAAMA,EAExD,GADAN,EAAOD,EAAQC,EAAMC,CAAG,EACpB,OAAOA,GAAQ,SAAU,CAC5B,IAAMM,EAAKR,EAAQC,EAAM,IAAI,EAC7BK,GAAQ,OAAOE,GAAO,UAAYA,EAAK,IAAIN,CAAG,MAAMM,CAAE,IAAM,IAAIN,CAAG,GACpE,MACCI,GAAQA,EAAO,IAAI,OAAOJ,CAAG,CAAC,GAAK,OAAOA,CAAG,CAE/C,CACA,OAAOI,CACR",
6
- "names": ["Logger", "logger", "BaseRegistry", "item", "key", "name", "existing", "existingName", "assertStandardSchema", "schema", "context", "assertChildPaths", "childPaths", "paths", "keys", "key", "joined", "index", "name", "outer", "other", "position", "createRegistry", "kind", "registrations", "options", "winners", "registration", "entries", "all", "bindRegistry", "contracts", "bindings", "kind", "key", "bound", "contract", "binding", "createRegistry", "safeParseStandardSchema", "schema", "value", "result", "syncResult", "standardSchema", "validate", "unregisteredTypeMessage", "type", "hint", "message", "isRecord", "value", "safeParseNode", "registry", "node", "path", "registration", "parsed", "safeParseStandardSchema", "issue", "isRecord", "value", "valueAt", "node", "keys", "current", "key", "setChild", "children", "safeParseTree", "registry", "root", "path", "issues", "walk", "nodePath", "ancestors", "parsed", "safeParseNode", "childPath", "trail", "items", "item", "index", "child", "tree", "childOf", "node", "key", "formatIssuePath", "path", "source", "text", "segment", "id"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }
@@ -0,0 +1,119 @@
1
+ import { type JSONSchemaObject, type JSONSchemaTarget } from './standard.js';
2
+ /** Where the JSON Schema being written keeps its definitions. */
3
+ export type JSONSchemaPlacement = {
4
+ readonly kind: 'document';
5
+ } | {
6
+ readonly kind: 'collection';
7
+ /** The URI the collection refers to an entry by. */
8
+ readonly uri: (id: string) => string;
9
+ };
10
+ /** The keyword a target writes a schema's identifier under: `id` for draft-04, `$id` for every other target. */
11
+ export declare const idKeyword: (target: JSONSchemaTarget) => "id" | "$id";
12
+ /**
13
+ * Whether a schema is the root of a resource of its own, which resolves its references against itself: it sets the
14
+ * identifier of its target ({@link idKeyword}) to something other than a fragment. An identifier that is only a
15
+ * fragment (`#node`) names an anchor instead.
16
+ */
17
+ export declare const startsResource: (schema: Record<string, unknown>, target: JSONSchemaTarget) => boolean;
18
+ /** The keyword a document keeps its definitions under, as Zod writes it for the target. */
19
+ export declare const definitionsKeyword: (target: JSONSchemaTarget) => "$defs" | "definitions";
20
+ /**
21
+ * Embeds JSON Schemas that were written as documents of their own (by a Standard JSON Schema converter or a separate
22
+ * Zod conversion) into one JSON Schema being written.
23
+ */
24
+ export interface JSONSchemaEmbedder {
25
+ /** The schema to write in place of `own`, which is not changed. */
26
+ embed(own: JSONSchemaObject): JSONSchemaObject;
27
+ /**
28
+ * The schema to write as the definition named `name` of a document, or as the entry of that name of a collection,
29
+ * where `own` is not changed.
30
+ *
31
+ * @remarks
32
+ * The schema stays at its own place, so a container found by its name is the schema itself and not a reference to
33
+ * another definition. In a document, `#` points at the definition, a pointer into the schema's own definitions at the
34
+ * definition lifted to the document as `<name>.<its name>` and anchors are renamed under `name`, as
35
+ * {@link createJSONSchemaEmbedder} explains. In a collection the entry is its own resource, so the schema is kept as it is, with
36
+ * its own definitions, without `$schema`, and a root fragment identifier (`$id: '#node'`, `id: '#node'` for draft-04) is
37
+ * dropped with its references turned into `#`, since the entry is addressed by the identifier the collection gives
38
+ * it. A schema with an identifier of its own (`$id`, or `id` for draft-04) is a
39
+ * resource that keeps its base: in a document it is kept as it is, and in a collection the entry is an `allOf` of a
40
+ * reference to it, with the schema beside it under the name (a `$ref` beside other keywords is ignored before 2019-09), so the entry keeps the collection's URI and the schema keeps its
41
+ * identifier.
42
+ */
43
+ embedDefinition(own: JSONSchemaObject, name: string): JSONSchemaObject;
44
+ /**
45
+ * Adds the definitions `embed` and `embedDefinition` moved to the finished document or collection, in place.
46
+ *
47
+ * @throws {RegistryError} Code `'definition-name-clash'` when a definition `embedDefinition` lifted takes a name
48
+ * `written` already defines
49
+ * @throws {Error} When `written` already defines an `embedded-<n>` key `embed` hoisted: the embedder reserves them
50
+ */
51
+ finish(written: JSONSchemaObject): JSONSchemaObject;
52
+ }
53
+ /**
54
+ * Create the embedder for one JSON Schema being written.
55
+ *
56
+ * @param target - The target the schema is written for
57
+ * @throws {Error} When `target` is not one of the four {@link JSONSchemaTarget}s, before anything is embedded
58
+ * @param placement - Whether it is one document or a collection of entries
59
+ *
60
+ * @remarks
61
+ * `$schema` is dropped, since the document being written declares the dialect. A schema whose `$ref` points into
62
+ * itself from its root (`#`, `#/$defs/node`, as ArkType writes a recursive type) would point at the wrong root once
63
+ * embedded, so it is hoisted: in a document, into its definitions under a key of its own (`embedded-1`), with each of
64
+ * its local pointers prefixed by that place; in a collection, as an entry of its own, referred to by its URI. The
65
+ * references stay `#/...` pointers and `#name` anchors, which is what AI tool APIs resolve, rather than `$id` URIs (`id` for draft-04).
66
+ *
67
+ * A plain-name anchor (`$anchor`, `$dynamicAnchor`, a draft-07 `$id: '#node'`, a draft-04 `id: '#node'`) resolves anywhere in the document, so
68
+ * two schemas that each declare `node` would declare it twice. Each embedded schema's anchors, and the `#node`
69
+ * references to them, are renamed to carry its key (`embedded-1-node`), whether it is hoisted into a document or
70
+ * embedded where it stands. A schema hoisted into a collection is a resource of its own by its `$id` (`id` for draft-04), which scopes
71
+ * its anchors, so they keep their names. Only a root fragment identifier (`$id: '#node'`, `id: '#node'` for draft-04) cannot stay: the entry's identifier is its
72
+ * assigned URI, so the root's anchor is dropped and its `#node` references become `#`, as
73
+ * {@link withoutRootAnchor} explains.
74
+ *
75
+ * Only the schema's root resource is rewritten. A schema with its own `$id` (`id` for draft-04), and any subschema that sets one, resolves
76
+ * its pointers and anchors against that and is left as it is.
77
+ *
78
+ * A definition written into a document by `embedDefinition(own, owner)` is named, and its anchors renamed, by the
79
+ * owner, so that no two owners share a name:
80
+ *
81
+ * - A definition `name` of the schema's own `$defs` (`definitions` for a draft-07 target) is lifted to
82
+ * `<owner>.<name>`, with the owner written so that it holds no `.`: each `.` and `_` in it is replaced by `_` and its
83
+ * code point in hex and `_` again (`_2e_`, `_5f_`), any other character stays. Owner `element:a.b` with a definition
84
+ * `c` is lifted as `element:a_2e_b.c` and owner `element:a` with `b.c` as `element:a.b.c`, so the first `.` of a
85
+ * lifted name always ends the owner.
86
+ * - An anchor `name` is renamed `<owner part>.<name>`, where the owner part is `o` followed by the owner with every
87
+ * character outside `[A-Za-z0-9-]` (`.` and `_` included) replaced by `_`, its code point in hex and `_` (`ui/button`
88
+ * becomes `oui_2f_button`, `a.b` becomes `oa_2e_b`, `my-card` stays `omy-card`). The part starts with a letter, holds
89
+ * only characters every dialect allows in an anchor, and no `.`, so the first `.` ends it, and the keys of `embed`
90
+ * (`embedded-1`) never start with `o`.
91
+ *
92
+ * In both, the owner part never holds a `.`, and a `_` in the owner is always escaped, so the first `.` ends the owner
93
+ * and its `_<hex>_` tokens decode one way. Both are one-to-one, so two owners never write the same name. A name that is still taken, by another definition
94
+ * lifted into the document or one `finish` finds in the document it completes, is a `RegistryError` with the code
95
+ * `'definition-name-clash'`; nothing is overwritten.
96
+ */
97
+ export declare function createJSONSchemaEmbedder(target: JSONSchemaTarget, placement: JSONSchemaPlacement): JSONSchemaEmbedder;
98
+ /**
99
+ * A JSON Pointer reference token, written for a URI fragment: `~` and `/` escaped, then percent-encoded for what a
100
+ * fragment does not allow.
101
+ *
102
+ * @remarks
103
+ * RFC 3986 lets a fragment hold the `pchar` characters raw, so `:`, `@` and the sub-delimiters (`$&+,;=` and `!'()*`)
104
+ * stay as they are and a name like `element:tab` reads as written.
105
+ */
106
+ export declare function pointerToken(name: string): string;
107
+ /**
108
+ * The `$ref` to the definition of a name in a document written for a target: `#/$defs/<name>` for `'draft-2020-12'`,
109
+ * `#/definitions/<name>` for every other target, with the name written as a JSON Pointer token.
110
+ *
111
+ * @param target - The target the document is written for, which decides the keyword of its definitions
112
+ * @param name - The key of the definition, for example `'ui/button'`
113
+ *
114
+ * @remarks
115
+ * A name holds any character. `~` and `/` are escaped as the pointer syntax requires, and what a URI fragment does not
116
+ * allow (a space, `%`, `#`, `?`) is percent-encoded, so a tool that resolves the reference finds the key whatever the
117
+ * name is.
118
+ */
119
+ export declare function definitionRef(target: JSONSchemaTarget, name: string): string;
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f}from"../chunk-DDOMNXV7.js";import"../chunk-GX6PAJLU.js";import"../chunk-BY4BKVNV.js";export{d as createJSONSchemaEmbedder,f as definitionRef,c as definitionsKeyword,a as idKeyword,e as pointerToken,b as startsResource};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,5 @@
1
+ export { createJSONSchemaEmbedder, definitionRef, definitionsKeyword, idKeyword, startsResource } from './embedder.js';
2
+ export type { JSONSchemaEmbedder, JSONSchemaPlacement } from './embedder.js';
3
+ export { readStandardJSONSchema } from './standard.js';
4
+ export { replaceChildSlot } from './slot.js';
5
+ export { assertJSONSchemaTarget } from './standard.js';
@@ -0,0 +1 @@
1
+ import{a as S}from"../chunk-L3ZXHX7S.js";import{a as o,b as t,c as d,d as a,f as m}from"../chunk-DDOMNXV7.js";import{a as e,b as r}from"../chunk-GX6PAJLU.js";import"../chunk-BY4BKVNV.js";export{e as assertJSONSchemaTarget,a as createJSONSchemaEmbedder,m as definitionRef,d as definitionsKeyword,o as idKeyword,r as readStandardJSONSchema,S as replaceChildSlot,t as startsResource};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,46 @@
1
+ import { type JSONSchemaObject, type JSONSchemaTarget } from './standard.js';
2
+ /**
3
+ * Replace the slot a child path names in a registration's JSON Schema, and nothing around it. The definition is
4
+ * changed in place.
5
+ *
6
+ * @param definition - The registration's JSON Schema, as the definition of its `$type`
7
+ * @param path - The registration's `$type`, for the error, and the `keys` and `list` of the child path whose slot to
8
+ * replace
9
+ * @param union - The schema every child must match, already resolved: each `$ref` is written as the document it goes in
10
+ * refers to a definition. Each place the slot takes it gets its own copy
11
+ * @param options - The `target` the schema is written for, which decides the identifier (`$id`, or `id` for draft-04)
12
+ * that makes a schema a resource of its own
13
+ * @throws {RegistryError} Code `'unreachable-child-path'` when the slot is not where the definition declares it, is
14
+ * nullable, is not an object, an array or open, or is an object where the path sets `list`, and `'invalid-child-paths'` when `path.keys` is empty
15
+ *
16
+ * @remarks
17
+ * `required`, list bounds and every sibling keyword of the slot's parent stay, since the registration's schema owns
18
+ * them. The slot is read by what it is: an array (`type: 'array'`, `items` or `prefixItems`) gets its items replaced, an
19
+ * object (`type: 'object'` or `properties`) becomes the union, and an open slot (no keyword but annotations) becomes the
20
+ * union or a list of it, matching a child or a list of children. A path that sets `list` holds a list and never one
21
+ * node, so its open slot becomes an array of the union, and an object slot is unreachable, since the schema would refuse
22
+ * the list the document holds. An array slot of such a path that declares only array keywords (`items`) gets
23
+ * `type: 'array'`, so an object is refused as the walk refuses it, and one whose `type` is another is unreachable.
24
+ * Annotations of the slot are kept. A slot inside a
25
+ * schema with an `$id` (`id` for draft-04) of its own cannot be reached: a `$ref` there resolves against that `$id`, not against the
26
+ * document. That holds for each schema between the definition and the slot. The definition's own root is the caller's
27
+ * to check, since only the caller knows whether the references it writes resolve against that root: a collection entry
28
+ * has an `$id` that is its address, and its references are written for that collection. A nullable slot (`type: ['array', 'null']` or an `anyOf` with `null`, or `nullable: true` as OpenAPI 3.0
29
+ * writes it) cannot be reached either, since `safeParseTree` refuses `null` at a slot and keeping the keyword would
30
+ * leave the slot accepting it.
31
+ *
32
+ * A tuple is an array whose every item is a child, as `safeParseTree` reads it, so each position takes the union:
33
+ * every `prefixItems` entry (2020-12), every array-form `items` entry and `additionalItems` (draft-07), and the
34
+ * `items` that follows `prefixItems`. A rest that the schema closes with `false` stays closed, since the tuple's arity
35
+ * is the registration's to decide. Throwing instead would refuse a fixed-arity pair of children that is valid, while
36
+ * replacing only `items` would leave the prefix positions accepting any `$type`.
37
+ *
38
+ * The check that the union's names are registered belongs to the caller, as it does in `exportTreeSchema`.
39
+ */
40
+ export declare function replaceChildSlot(definition: JSONSchemaObject, path: {
41
+ readonly $type: string;
42
+ readonly keys: readonly string[];
43
+ readonly list?: true;
44
+ }, union: JSONSchemaObject, options: {
45
+ readonly target: JSONSchemaTarget;
46
+ }): void;
@@ -0,0 +1 @@
1
+ import{a}from"../chunk-L3ZXHX7S.js";import"../chunk-DDOMNXV7.js";import"../chunk-GX6PAJLU.js";import"../chunk-BY4BKVNV.js";export{a as replaceChildSlot};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -0,0 +1,44 @@
1
+ import type { StandardJSONSchemaV1 } from '@standard-schema/spec';
2
+ /**
3
+ * A JSON Schema as a plain object.
4
+ *
5
+ * @remarks
6
+ * The export reads and writes schemas of any dialect, so the type names no keyword: callers narrow what they inspect.
7
+ */
8
+ export type JSONSchemaObject = Record<string, unknown>;
9
+ declare const JSON_SCHEMA_TARGETS: readonly ["draft-2020-12", "draft-07", "draft-04", "openapi-3.0"];
10
+ /**
11
+ * The JSON Schema dialects a schema can be written for, by their Standard JSON Schema names.
12
+ *
13
+ * @remarks
14
+ * The set is closed, though the Standard JSON Schema type is open, so that each API names the targets it supports and
15
+ * refuses the others. A target added later widens the union, which is additive.
16
+ */
17
+ export type JSONSchemaTarget = (typeof JSON_SCHEMA_TARGETS)[number];
18
+ /**
19
+ * Throw unless `target` is a {@link JSONSchemaTarget}, and narrow it to one.
20
+ *
21
+ * @param target - A target as a caller wrote it, for example the `target` of a Standard JSON Schema converter's options,
22
+ * which the Standard JSON Schema type leaves open
23
+ * @throws {Error} When `target` is any other string, naming it and the four that are supported
24
+ */
25
+ export declare function assertJSONSchemaTarget(target: string): asserts target is JSONSchemaTarget;
26
+ /**
27
+ * The Standard JSON Schema converter of a schema (`~standard.jsonSchema`), when it provides one.
28
+ *
29
+ * @remarks
30
+ * {@link exportTreeSchema} reads each registration's schema through it unless the caller passes its own `resolve`.
31
+ */
32
+ export declare function readStandardJSONSchema(schema: unknown): StandardJSONSchemaV1.Converter | undefined;
33
+ /** Only ordinary records and null-prototype value maps are walked as schemas. */
34
+ export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
35
+ /**
36
+ * The own entry of `record` under `key`, or `undefined`.
37
+ *
38
+ * @remarks
39
+ * A child path key is data, and `__proto__` is a valid key. Reading and writing keys through these two functions keeps
40
+ * every one on the document's own properties, so none reaches the prototype chain, whatever its name.
41
+ */
42
+ export declare function getOwn(record: Record<string, unknown>, key: string): unknown;
43
+ export declare function setOwn(record: Record<string, unknown>, key: string, value: unknown): void;
44
+ export {};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"../chunk-GX6PAJLU.js";export{a as assertJSONSchemaTarget,d as getOwn,c as isPlainObject,b as readStandardJSONSchema,e as setOwn};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -7,11 +7,20 @@ import type { BaseRegistration } from './types.js';
7
7
  */
8
8
  export interface NodeLookup<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> {
9
9
  get(key: string): TRegistration | undefined;
10
+ /**
11
+ * The registry's label, for example `Widget`, as it is used in errors.
12
+ *
13
+ * @remarks
14
+ * {@link safeParseTree} names it in the `RegistryError` it throws when a schema contradicts its registration, and
15
+ * leaves it out for a lookup that has none, such as a function that tries several registries.
16
+ */
17
+ readonly kind?: string;
10
18
  /**
11
19
  * A sentence that follows the message of a `$type` `get` does not answer, such as where to register it.
12
20
  *
13
21
  * @remarks
14
- * The message is `No registration for $type 'x'.`, a space and the hint.
22
+ * The message is `No registration for $type 'x'.`, a space and the hint. A registry built with the `hint` option
23
+ * has it.
15
24
  */
16
25
  hint?: string;
17
26
  }
@@ -34,7 +43,7 @@ export type SafeParseNodeResult<TRegistration extends Pick<BaseRegistration, 'sc
34
43
  data: StandardSchemaV1.InferOutput<TRegistration['schema']>;
35
44
  } : never) | {
36
45
  success: false;
37
- issues: StandardSchemaIssue[];
46
+ issues: RegistryIssue[];
38
47
  };
39
48
  /**
40
49
  * The message for a `$type` no registration answers, as {@link safeParseNode} reports it.
@@ -46,27 +55,77 @@ export type SafeParseNodeResult<TRegistration extends Pick<BaseRegistration, 'sc
46
55
  * Exported so a caller that has to throw for the same case, instead of returning an issue, says the same thing.
47
56
  */
48
57
  export declare function unregisteredTypeMessage(type: string, hint?: string): string;
58
+ /**
59
+ * An issue of a node or a document, as {@link safeParseNode} and {@link safeParseTree} report it.
60
+ *
61
+ * @remarks
62
+ * The issues the engine creates itself carry a namespaced `code`, so a consumer can branch on it and a schema library's
63
+ * own `code`, which an issue from a schema keeps untouched, cannot be mistaken for one:
64
+ *
65
+ * - `'registry/not-an-object'`: the node is not an object.
66
+ * - `'registry/missing-type'`: the node has no string `$type`.
67
+ * - `'registry/unregistered-type'`: no registration answers the `$type` (`received`).
68
+ * - `'registry/not-accepted'`: the `$type` (`received`) is not in the `accepts` list (`expected`) of its position.
69
+ * - `'registry/not-a-node'`: a value at a child path is neither an object nor a list.
70
+ * - `'registry/not-a-list'`: a value at a child path that sets `list` is not an array.
71
+ * - `'registry/contains-itself'`: a node is reached again through its own ancestors.
72
+ *
73
+ * The messages are written for a person and may be reworded; the codes stay.
74
+ */
75
+ export interface RegistryIssue extends StandardSchemaIssue {
76
+ /** The namespaced code of an issue the engine created, or whatever the schema library put on its own issue. */
77
+ readonly code?: string;
78
+ /**
79
+ * What would have fitted, for `'registry/not-accepted'`: the `accepts` list.
80
+ *
81
+ * @remarks
82
+ * Set only on an issue the engine created. An issue from a schema keeps its library's own fields untouched, and some
83
+ * libraries have an `expected` or `received` of their own, so check `code` first.
84
+ */
85
+ readonly expected?: readonly string[];
86
+ /** What was there, for `'registry/not-accepted'` and `'registry/unregistered-type'`: the `$type`. */
87
+ readonly received?: string;
88
+ }
89
+ /**
90
+ * What a call of {@link safeParseNode} or {@link safeParseTree} may be told besides the node.
91
+ *
92
+ * @remarks
93
+ * For {@link safeParseTree}, `TType` is the `$type`s of the lookup, so a name it lacks is a type error and a literal
94
+ * `accepts` narrows the root.
95
+ */
96
+ export interface ParseOptions<TType extends string = string> {
97
+ /** Where the node sits in its document. Every issue's `path` starts with it. */
98
+ readonly path?: NonNullable<StandardSchemaIssue['path']>;
99
+ /**
100
+ * The `$type`s the node may have, as a position of a document accepts them. Not empty when present, or the call
101
+ * throws: an empty list is a caller bug, like an asynchronous schema.
102
+ */
103
+ readonly accepts?: readonly TType[];
104
+ }
49
105
  /**
50
106
  * Check one node against the registration its `$type` names, without throwing.
51
107
  *
52
108
  * @param registry - Where the node's `$type` finds its registration
53
109
  * @param node - The node as it arrived, for example one entry of a parsed JSON document
54
- * @param path - Where the node sits in its document. Every issue's `path` starts with it.
110
+ * @param options - Where the node sits (`path`) and which `$type`s it may have (`accepts`), see {@link ParseOptions}
55
111
  *
56
112
  * @remarks
57
113
  * An issue points at the value that is wrong, as a schema reports it, so an editor can mark that value and a YAML
58
- * mapper finds its line: a node that is not an object is an issue at `path`; an object without a string `$type`, and
59
- * a `$type` no registration answers, are issues at `[...path, '$type']`, where a schema reports a missing required key.
60
- * The lookup's `hint` adds to the message of the last.
114
+ * mapper finds its line: a node that is not an object is an issue at `path`; an object without a string `$type`, a
115
+ * `$type` outside `accepts` and a `$type` no registration answers are issues at `[...path, '$type']`, where a schema
116
+ * reports a missing required key. `accepts` is checked before the lookup, so a `$type` outside the list is not
117
+ * accepted whether or not it is registered, and the issue names what would fit. The lookup's `hint` adds to the message
118
+ * of an unregistered `$type` only.
61
119
  * Otherwise the issues are those of the registration's schema, with `path` in front of the path the schema reported.
62
120
  *
63
121
  * `data` is what the schema returned, so its defaults and transforms apply. Its type is the schema output of the
64
122
  * registration that `registration.$type` names, for a registry typed by registrations with literal `$type`s, and
65
123
  * `unknown` for one typed as `BaseRegistration`. TypeScript cannot follow the runtime lookup from the node's string
66
124
  * `$type` to a registration, so the function returns `data` through one cast to that type: it is the value the matched
67
- * registration's own schema returned. The node is checked on its own: {@link safeParseTree} walks a tree with it,
68
- * passing each child its own `path`.
125
+ * registration's own schema returned. The node is checked on its own, whatever its `childPaths` say, and its schema
126
+ * may omit `$type`: {@link safeParseTree} walks a tree with it and holds the schema to the registration's contract.
69
127
  *
70
- * @throws {Error} When the registration's schema validates asynchronously, as {@link safeParseStandardSchema} does.
128
+ * @throws {Error} When the registration's schema validates asynchronously, as {@link safeParseStandardSchema} does,
129
+ * and when `accepts` is an empty list.
71
130
  */
72
- export declare function safeParseNode<TRegistration extends Pick<BaseRegistration, 'schema'>>(registry: NodeLookup<TRegistration>, node: unknown, path?: NonNullable<StandardSchemaIssue['path']>): SafeParseNodeResult<TRegistration>;
131
+ export declare function safeParseNode<TRegistration extends Pick<BaseRegistration, 'schema'>>(registry: NodeLookup<TRegistration>, node: unknown, options?: ParseOptions): SafeParseNodeResult<TRegistration>;
@@ -1 +1 @@
1
- function u(t,s){let e=t["~standard"].validate(s);if(e&&typeof e.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(e===null||typeof e!="object")throw new Error("Standard Schema validation returned an invalid result");let a=e;return a.issues!==void 0?{success:!1,error:{issues:[...a.issues]}}:{success:!0,data:a.value}}function o(t,s){let e=`No registration for $type '${t}'.`;return s?`${e} ${s}`:e}function c(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function S(t,s,e=[]){if(!c(s))return{success:!1,issues:[{message:"Expected an object with a string $type.",path:e}]};let a=s.$type;if(typeof a!="string")return{success:!1,issues:[{message:"Expected a string $type.",path:[...e,"$type"]}]};let r=t.get(a);if(!r)return{success:!1,issues:[{message:o(a,t.hint),path:[...e,"$type"]}]};let n=u(r.schema,s);return n.success?{success:!0,$type:a,registration:r,data:n.data}:{success:!1,issues:n.error.issues.map(i=>({...i,path:[...e,...i.path??[]]}))}}export{S as safeParseNode,o as unregisteredTypeMessage};
1
+ import{a,b}from"./chunk-O5CRFISG.js";import"./chunk-P3DDHPDA.js";export{b as safeParseNode,a as unregisteredTypeMessage};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/standard-schema.ts", "../src/parse-node.ts"],
4
- "sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\n\nexport type StandardSchemaIssue = StandardSchemaV1.Issue;\n\nexport type StandardSchemaSafeParseResult<T> =\n\t{ success: true; data: T } | { success: false; error: { issues: StandardSchemaIssue[] } };\n\n/**\n * Validate `value` with a Standard Schema without throwing.\n *\n * @param schema - Standard Schema to run\n * @param value - Input to validate\n * @throws {Error} When the schema validates asynchronously or returns a malformed result\n *\n * @remarks\n * Only synchronous validation is supported, because the callers (registry lookups, form validation,\n * action parsing) need an immediate result.\n */\nexport function safeParseStandardSchema<TInput, TOutput>(\n\tschema: StandardSchemaV1<TInput, TOutput>,\n\tvalue: TInput,\n): StandardSchemaSafeParseResult<TOutput> {\n\tconst result = schema['~standard'].validate(value);\n\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\tthrow new Error('Async Standard Schema validation is not supported in this context');\n\t}\n\tif (result === null || typeof result !== 'object') {\n\t\tthrow new Error('Standard Schema validation returned an invalid result');\n\t}\n\n\tconst syncResult = result as StandardSchemaV1.Result<TOutput>;\n\n\tif (syncResult.issues !== undefined) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror: {\n\t\t\t\tissues: [...syncResult.issues],\n\t\t\t},\n\t\t};\n\t}\n\n\treturn { success: true, data: syncResult.value };\n}\n\n/**\n * A Standard Schema that validates with a function, for a check that is not a schema library's.\n *\n * @param validate - Returns `{ value }` for an input that passes, or `{ issues }` for one that does not\n *\n * @remarks\n * The schema reports `schema-engine` as its vendor and is synchronous, as {@link safeParseStandardSchema} requires.\n * `TInput` only types what the schema accepts, so an authoring type can be inferred from it; `validate` still receives `unknown`.\n */\nexport function standardSchema<TOutput, TInput = unknown>(\n\tvalidate: (value: unknown) => StandardSchemaV1.Result<TOutput>,\n): StandardSchemaV1<TInput, TOutput> {\n\treturn { '~standard': { version: 1, vendor: 'schema-engine', validate } };\n}\n", "import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseStandardSchema, type StandardSchemaIssue } from './standard-schema.js';\nimport type { BaseRegistration } from './types.js';\n\n/**\n * What {@link safeParseNode} needs of a registry: the registration of a `$type`, of which it reads the schema.\n * Both registry kinds fit.\n */\nexport interface NodeLookup<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> {\n\tget(key: string): TRegistration | undefined;\n\t/**\n\t * A sentence that follows the message of a `$type` `get` does not answer, such as where to register it.\n\t *\n\t * @remarks\n\t * The message is `No registration for $type 'x'.`, a space and the hint.\n\t */\n\thint?: string;\n}\n\n/**\n * What {@link safeParseNode} returns: the registration with the node's validated configuration, or every issue found.\n *\n * @remarks\n * The success branch has one member per registration of a typed registry, so checking `$type` (the node's, repeated at\n * the top of the result because TypeScript narrows a union only by a property of the union itself) narrows\n * `registration` and `data` together. A registration that does not declare its `$type`, such as a lookup typed by\n * `{ schema }` alone, leaves it a `string`. A registry typed as plain `BaseRegistration` has no concrete schema to\n * read, so its `data` is `unknown`.\n */\nexport type SafeParseNodeResult<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> =\n\t| (TRegistration extends unknown\n\t\t\t? {\n\t\t\t\t\tsuccess: true;\n\t\t\t\t\t$type: TRegistration extends { $type: infer TType extends string } ? TType : string;\n\t\t\t\t\tregistration: TRegistration;\n\t\t\t\t\tdata: StandardSchemaV1.InferOutput<TRegistration['schema']>;\n\t\t\t\t}\n\t\t\t: never)\n\t| { success: false; issues: StandardSchemaIssue[] };\n\n/**\n * The message for a `$type` no registration answers, as {@link safeParseNode} reports it.\n *\n * @param type - The `$type` that found nothing\n * @param hint - A sentence that follows the message, as {@link NodeLookup.hint} gives it\n *\n * @remarks\n * Exported so a caller that has to throw for the same case, instead of returning an issue, says the same thing.\n */\nexport function unregisteredTypeMessage(type: string, hint?: string): string {\n\tconst message = `No registration for $type '${type}'.`;\n\treturn hint ? `${message} ${hint}` : message;\n}\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Check one node against the registration its `$type` names, without throwing.\n *\n * @param registry - Where the node's `$type` finds its registration\n * @param node - The node as it arrived, for example one entry of a parsed JSON document\n * @param path - Where the node sits in its document. Every issue's `path` starts with it.\n *\n * @remarks\n * An issue points at the value that is wrong, as a schema reports it, so an editor can mark that value and a YAML\n * mapper finds its line: a node that is not an object is an issue at `path`; an object without a string `$type`, and\n * a `$type` no registration answers, are issues at `[...path, '$type']`, where a schema reports a missing required key.\n * The lookup's `hint` adds to the message of the last.\n * Otherwise the issues are those of the registration's schema, with `path` in front of the path the schema reported.\n *\n * `data` is what the schema returned, so its defaults and transforms apply. Its type is the schema output of the\n * registration that `registration.$type` names, for a registry typed by registrations with literal `$type`s, and\n * `unknown` for one typed as `BaseRegistration`. TypeScript cannot follow the runtime lookup from the node's string\n * `$type` to a registration, so the function returns `data` through one cast to that type: it is the value the matched\n * registration's own schema returned. The node is checked on its own: {@link safeParseTree} walks a tree with it,\n * passing each child its own `path`.\n *\n * @throws {Error} When the registration's schema validates asynchronously, as {@link safeParseStandardSchema} does.\n */\nexport function safeParseNode<TRegistration extends Pick<BaseRegistration, 'schema'>>(\n\tregistry: NodeLookup<TRegistration>,\n\tnode: unknown,\n\tpath: NonNullable<StandardSchemaIssue['path']> = [],\n): SafeParseNodeResult<TRegistration> {\n\tif (!isRecord(node)) {\n\t\treturn { success: false, issues: [{ message: 'Expected an object with a string $type.', path }] };\n\t}\n\tconst type = node.$type;\n\tif (typeof type !== 'string') {\n\t\treturn { success: false, issues: [{ message: 'Expected a string $type.', path: [...path, '$type'] }] };\n\t}\n\tconst registration = registry.get(type);\n\tif (!registration) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\tissues: [{ message: unregisteredTypeMessage(type, registry.hint), path: [...path, '$type'] }],\n\t\t};\n\t}\n\tconst parsed = safeParseStandardSchema(registration.schema, node);\n\tif (parsed.success) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\t$type: type,\n\t\t\tregistration,\n\t\t\tdata: parsed.data,\n\t\t} as SafeParseNodeResult<TRegistration>;\n\t}\n\treturn {\n\t\tsuccess: false,\n\t\tissues: parsed.error.issues.map((issue) => ({ ...issue, path: [...path, ...(issue.path ?? [])] })),\n\t};\n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E,OAAIG,EAAO,QACH,CACN,QAAS,GACT,MAAOV,EACP,aAAAS,EACA,KAAMC,EAAO,IACd,EAEM,CACN,QAAS,GACT,OAAQA,EAAO,MAAM,OAAO,IAAKE,IAAW,CAAE,GAAGA,EAAO,KAAM,CAAC,GAAGJ,EAAM,GAAII,EAAM,MAAQ,CAAC,CAAE,CAAE,EAAE,CAClG,CACD",
6
- "names": ["safeParseStandardSchema", "schema", "value", "result", "syncResult", "unregisteredTypeMessage", "type", "hint", "message", "isRecord", "value", "safeParseNode", "registry", "node", "path", "registration", "parsed", "safeParseStandardSchema", "issue"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }