@schema-engine/registry 0.5.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,7 +14,7 @@ Install the [Standard Schema](https://standardschema.dev/) validator you prefer.
14
14
 
15
15
  ```typescript
16
16
  import * as z from 'zod/mini';
17
- import { createRegistry, safeParseStandardSchema, type BaseRegistration } from '@schema-engine/registry';
17
+ import { createRegistry, safeParseNode, type BaseRegistration } from '@schema-engine/registry';
18
18
 
19
19
  z.config(z.locales.en());
20
20
 
@@ -33,28 +33,26 @@ const badge: Badge = {
33
33
 
34
34
  const badges = createRegistry('Badge', [badge]);
35
35
 
36
- export function resolve(node: { $type: string }): string {
37
- const registration = badges.get(node.$type);
38
- if (!registration) return `No registration for $type '${node.$type}'.`;
39
- const parsed = safeParseStandardSchema(registration.schema, node);
36
+ export function resolve(node: unknown): string {
37
+ const parsed = safeParseNode(badges, node);
40
38
  return parsed.success
41
- ? registration.render(parsed.data)
42
- : parsed.error.issues.map((issue) => issue.message).join('; ');
39
+ ? parsed.registration.render(parsed.data)
40
+ : parsed.issues.map((issue) => issue.message).join('; ');
43
41
  }
44
42
  ```
45
43
 
46
44
  ## Entry points
47
45
 
48
- | Import | Holds |
49
- | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
50
- | `@schema-engine/registry` | `createRegistry`, `BaseRegistry`, the registration types, `safeParseStandardSchema` and `assertStandardSchema` |
51
- | `@schema-engine/registry/yaml` | `parseYaml`, `safeParseYaml` and `stringifyYaml`, which report errors by line and column. Needs the optional peer dependency `yaml` |
46
+ | Import | Holds |
47
+ | ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | `@schema-engine/registry` | `createRegistry`, `bindRegistry`, `BaseRegistry`, the registration types, `safeParseNode`, `safeParseTree`, `safeParseStandardSchema`, `assertStandardSchema`, `standardSchema` and `formatIssuePath` |
49
+ | `@schema-engine/registry/yaml` | `parseYaml`, `safeParseYaml` and `stringifyYaml`, which report errors by line and column. Needs the optional peer dependency `yaml` |
52
50
 
53
51
  ## Documentation
54
52
 
55
53
  - [Registry](https://schema-engine.com/docs/registry/overview): install, build a registry and resolve a JSON node.
56
54
  - [Read-only and mutable registries](https://schema-engine.com/docs/registry/registries): `createRegistry` and `BaseRegistry`.
57
- - [Resolve a document](https://schema-engine.com/docs/registry/resolve-a-document): walk a tree of nodes through registries.
55
+ - [Resolve a document](https://schema-engine.com/docs/registry/resolve-a-document): validate a whole tree of nodes with `safeParseTree` and render it.
58
56
  - [API reference](https://schema-engine.com/docs/registry/api-reference): every export.
59
57
  - [For AI agents](https://schema-engine.com/docs/schema-engine/agent-skill): the package ships its part of the agent skill.
60
58
 
@@ -0,0 +1,65 @@
1
+ import { type ReadOnlyRegistry } from './create-registry.js';
2
+ import type { BaseRegistration } from './types.js';
3
+ /** What a binding may not set: the keys its contract already defines. */
4
+ type ContractKeys<TContract> = {
5
+ readonly [K in keyof TContract]?: never;
6
+ };
7
+ /** The binding each `$type` of a contracts registry takes, which may not set a key of its own contract. */
8
+ type BindingsOf<TContract extends BaseRegistration> = {
9
+ readonly [K in TContract['$type']]: Readonly<Record<string, unknown>> & ContractKeys<Extract<TContract, {
10
+ $type: K;
11
+ }>>;
12
+ };
13
+ /** The keys of `TBindings` that no contract answers; each is typed `never`, so naming one is a compile error. */
14
+ type ExtraBindings<TBindings, TContract extends BaseRegistration> = {
15
+ readonly [K in Exclude<keyof TBindings, TContract['$type']>]: never;
16
+ };
17
+ /**
18
+ * One binding per `$type` of a contracts registry, every binding of the same shape.
19
+ *
20
+ * @remarks
21
+ * Use it with `satisfies` to fix what one renderer binds:
22
+ * `{ card: { render: Card } } satisfies RegistryBindings<typeof contracts, ReactBinding>`.
23
+ * A contracts registry whose `$type` is a plain `string` has no known keys to require, so only {@link bindRegistry}'s
24
+ * build-time checks apply to it.
25
+ */
26
+ export type RegistryBindings<TRegistry extends ReadOnlyRegistry, TBinding extends object = object> = TRegistry extends ReadOnlyRegistry<infer TContract> ? {
27
+ readonly [K in TContract['$type']]: TBinding;
28
+ } : never;
29
+ /** A contract merged with the binding its `$type` names, member by member. */
30
+ export type BoundRegistration<TContract extends BaseRegistration, TBindings> = TContract extends unknown ? TContract & TBindings[TContract['$type'] & keyof TBindings] : never;
31
+ /** The `$type`s of a contracts registry that are known literals; `never` when the contracts are typed only as `string`. */
32
+ type KnownTypes<TContract extends BaseRegistration> = string extends TContract['$type'] ? never : TContract['$type'];
33
+ /**
34
+ * What {@link bindRegistry} returns: a read-only registry whose `get` also answers a known `$type` without `undefined`.
35
+ *
36
+ * @remarks
37
+ * `get` returns the registration of that exact `$type` when the contracts name their `$type`s as literals, because
38
+ * `bindRegistry` guarantees every contract is bound. The `string` overload stays for a `$type` read from a document.
39
+ */
40
+ export interface BoundRegistry<TContract extends BaseRegistration, TBindings> extends ReadOnlyRegistry<BoundRegistration<TContract, TBindings>> {
41
+ get<K extends KnownTypes<TContract>>(key: K): Extract<BoundRegistration<TContract, TBindings>, {
42
+ $type: K;
43
+ }>;
44
+ get(key: string): BoundRegistration<TContract, TBindings> | undefined;
45
+ }
46
+ /**
47
+ * Build a renderer's registry from a registry of contracts and one binding per `$type`.
48
+ *
49
+ * @param contracts - Registrations without the renderer's part: the `$type`, schema and metadata, plus what the domain fixes
50
+ * @param bindings - What this renderer adds to each contract, keyed by `$type`, such as `render` or a tag name
51
+ * @throws {Error} `Widget 'card' has no binding.` when a contract has no binding
52
+ * @throws {Error} `Widget binding 'crad' names no registration.` when a binding's key is no contract's `$type`
53
+ * @throws {Error} `Widget 'card' binding sets 'schema', which the contract defines.` when a binding sets a contract key
54
+ *
55
+ * @remarks
56
+ * The result is a frozen registry built with {@link createRegistry}, so it keeps the contracts' order and checks every
57
+ * schema again. Each registration is a shallow merge, so `schema`, `metadata` and every other value of a contract is
58
+ * shared by identity between all the renderers that bind it. A binding is renderer-only data (a `render` function, a
59
+ * tag name) and never carries schema or metadata.
60
+ *
61
+ * With contracts typed by literal `$type`, a missing binding, an extra one and a binding that sets a contract key are
62
+ * also compile errors. With contracts typed only as `string` the three checks run when the registry is built.
63
+ */
64
+ export declare function bindRegistry<TContract extends BaseRegistration, const TBindings extends BindingsOf<TContract>>(contracts: ReadOnlyRegistry<TContract>, bindings: TBindings & ExtraBindings<TBindings, TContract>): BoundRegistry<TContract, TBindings>;
65
+ export {};
@@ -0,0 +1 @@
1
+ function p(t,i="Registration schema"){if(typeof(t!==null&&(typeof t=="object"||typeof t=="function")?t["~standard"]:void 0)?.validate!="function")throw new Error(`${i} must implement Standard Schema (~standard.validate).`);return t}function f(t,i){if(t===void 0)return;if(!Array.isArray(t))throw new Error(`${i} childPaths must be a list of key paths.`);let s=[];for(let e of t){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||r===""))throw new Error(`${i} childPaths must hold non-empty lists of non-empty keys.`);s.push(e)}let a=s.map(e=>e.join("."));for(let[e,r]of s.entries()){let o=r.join(".");if(a.indexOf(o)!==e)throw new Error(`${i} declares the child path '${o}' twice.`);let n=s.find(d=>d.length<r.length&&d.every((g,c)=>g===r[c]));if(n)throw new Error(`${i} child path '${o}' runs through the child path '${n.join(".")}'.`)}}function y(t,i,s={}){let a=new Map;for(let n of i){if(s.duplicates==="error"&&a.has(n.$type))throw new Error(`${t} '${n.$type}' is registered twice.`);a.set(n.$type,n)}let e=new Map;for(let[n,d]of a)p(d.schema,`${t} '${n}' schema`),f(d.childPaths,`${t} '${n}'`),e.set(n,Object.freeze({...d}));let r=Object.freeze([...e.values()]),o=Object.freeze([...e.keys()]);return Object.freeze({kind:t,size:e.size,get:n=>e.get(n),has:n=>e.has(n),all:()=>r,keys:()=>o})}function T(t,i){let{kind:s}=t;for(let e of Object.keys(i))if(!t.has(e))throw new Error(`${s} binding '${e}' names no registration.`);let a=t.all().map(e=>{let r=Object.hasOwn(i,e.$type)?i[e.$type]:void 0;if(typeof r!="object"||r===null)throw new Error(`${s} '${e.$type}' has no binding.`);for(let o of Object.keys(r))if(Object.hasOwn(e,o))throw new Error(`${s} '${e.$type}' binding sets '${o}', which the contract defines.`);return{...e,...r}});return y(s,a)}export{T as bindRegistry};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/create-registry.ts", "../src/bind-registry.ts"],
4
+ "sourcesContent": ["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"],
5
+ "mappings": "AA2BO,SAASA,EAAqBC,EAAiBC,EAAU,sBAAyC,CAKxG,GAAI,OAHHD,IAAW,OAAS,OAAOA,GAAW,UAAY,OAAOA,GAAW,YAChEA,EAAqC,WAAW,EACjD,SACiB,UAAa,WACjC,MAAM,IAAI,MAAM,GAAGC,CAAO,uDAAuD,EAElF,OAAOD,CACR,CAUA,SAASE,EAAiBC,EAAqBF,EAAuB,CACrE,GAAIE,IAAe,OAAW,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Paths", "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"]
7
+ }
@@ -24,15 +24,31 @@ export interface ReadOnlyRegistry<TRegistration extends BaseRegistration = BaseR
24
24
  * @throws {Error} When `schema` has no `~standard.validate` function
25
25
  */
26
26
  export declare function assertStandardSchema(schema: unknown, context?: string): StandardSchemaV1;
27
+ /** Options of {@link createRegistry}. */
28
+ export interface CreateRegistryOptions {
29
+ /**
30
+ * What a second registration of one `$type` does: replace the first (`'override'`, the default) or fail the build
31
+ * (`'error'`).
32
+ *
33
+ * @remarks
34
+ * `'override'` is how `[...defaults, custom]` replaces a built-in. Use `'error'` for a catalog where a repeated
35
+ * key is always a mistake, such as component keys.
36
+ */
37
+ readonly duplicates?: 'override' | 'error';
38
+ }
27
39
  /**
28
40
  * Build a frozen, read-only registry from a list of registrations.
29
41
  *
30
42
  * @param kind - Label for errors, for example `Element`
31
43
  * @param registrations - Registrations to store, keyed by `$type`
44
+ * @param options - How to treat a repeated `$type`, see {@link CreateRegistryOptions}
45
+ * @throws {Error} `Widget 'card' is registered twice.` when `duplicates` is `'error'` and a `$type` repeats, before any
46
+ * schema is checked
32
47
  * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema
48
+ * @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
33
49
  *
34
50
  * @remarks
35
- * A later registration with the same `$type` replaces the earlier one without a
51
+ * By default a later registration with the same `$type` replaces the earlier one without a
36
52
  * warning, so `[...defaults, custom]` is the way to override. A replaced key
37
53
  * keeps its first position. Only the winning registration of each key is
38
54
  * checked. The registry stores a frozen shallow copy of each winner, taken at
@@ -43,4 +59,4 @@ export declare function assertStandardSchema(schema: unknown, context?: string):
43
59
  *
44
60
  * Use {@link BaseRegistry} instead when registrations arrive at runtime.
45
61
  */
46
- export declare function createRegistry<TRegistration extends BaseRegistration>(kind: string, registrations: readonly TRegistration[]): ReadOnlyRegistry<TRegistration>;
62
+ export declare function createRegistry<const TRegistration extends BaseRegistration>(kind: string, registrations: readonly TRegistration[], options?: CreateRegistryOptions): ReadOnlyRegistry<TRegistration>;
@@ -1 +1 @@
1
- function d(t,a="Registration schema"){if(typeof(t!==null&&(typeof t=="object"||typeof t=="function")?t["~standard"]:void 0)?.validate!="function")throw new Error(`${a} must implement Standard Schema (~standard.validate).`);return t}function g(t,a){let r=new Map;for(let e of a)r.set(e.$type,e);let n=new Map;for(let[e,s]of r)d(s.schema,`${t} '${e}' schema`),n.set(e,Object.freeze({...s}));let i=Object.freeze([...n.values()]),o=Object.freeze([...n.keys()]);return Object.freeze({kind:t,size:n.size,get:e=>n.get(e),has:e=>n.has(e),all:()=>i,keys:()=>o})}export{d as assertStandardSchema,g as createRegistry};
1
+ function c(r,n="Registration schema"){if(typeof(r!==null&&(typeof r=="object"||typeof r=="function")?r["~standard"]:void 0)?.validate!="function")throw new Error(`${n} must implement Standard Schema (~standard.validate).`);return r}function f(r,n){if(r===void 0)return;if(!Array.isArray(r))throw new Error(`${n} childPaths must be a list of key paths.`);let a=[];for(let e of r){if(!Array.isArray(e)||e.length===0||e.some(s=>typeof s!="string"||s===""))throw new Error(`${n} childPaths must hold non-empty lists of non-empty keys.`);a.push(e)}let o=a.map(e=>e.join("."));for(let[e,s]of a.entries()){let d=s.join(".");if(o.indexOf(d)!==e)throw new Error(`${n} declares the child path '${d}' twice.`);let t=a.find(i=>i.length<s.length&&i.every((g,y)=>g===s[y]));if(t)throw new Error(`${n} child path '${d}' runs through the child path '${t.join(".")}'.`)}}function l(r,n,a={}){let o=new Map;for(let t of n){if(a.duplicates==="error"&&o.has(t.$type))throw new Error(`${r} '${t.$type}' is registered twice.`);o.set(t.$type,t)}let e=new Map;for(let[t,i]of o)c(i.schema,`${r} '${t}' schema`),f(i.childPaths,`${r} '${t}'`),e.set(t,Object.freeze({...i}));let s=Object.freeze([...e.values()]),d=Object.freeze([...e.keys()]);return Object.freeze({kind:r,size:e.size,get:t=>e.get(t),has:t=>e.has(t),all:()=>s,keys:()=>d})}export{c as assertStandardSchema,l as createRegistry};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/create-registry.ts"],
4
- "sourcesContent": ["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 * 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 * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema\n *\n * @remarks\n * 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<TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly TRegistration[],\n): ReadOnlyRegistry<TRegistration> {\n\tconst winners = new Map<string, TRegistration>();\n\tfor (const registration of registrations) {\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\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"],
5
- "mappings": "AA2BO,SAASA,EAAqBC,EAAiBC,EAAU,sBAAyC,CAKxG,GAAI,OAHHD,IAAW,OAAS,OAAOA,GAAW,UAAY,OAAOA,GAAW,YAChEA,EAAqC,WAAW,EACjD,SACiB,UAAa,WACjC,MAAM,IAAI,MAAM,GAAGC,CAAO,uDAAuD,EAElF,OAAOD,CACR,CAqBO,SAASE,EACfC,EACAC,EACkC,CAClC,IAAMC,EAAU,IAAI,IACpB,QAAWC,KAAgBF,EAC1BC,EAAQ,IAAIC,EAAa,MAAOA,CAAY,EAE7C,IAAMC,EAAU,IAAI,IACpB,OAAW,CAACC,EAAKF,CAAY,IAAKD,EACjCN,EAAqBO,EAAa,OAAQ,GAAGH,CAAI,KAAKK,CAAG,UAAU,EACnED,EAAQ,IAAIC,EAAK,OAAO,OAAO,CAAE,GAAGF,CAAa,CAAC,CAAC,EAEpD,IAAMG,EAAM,OAAO,OAAO,CAAC,GAAGF,EAAQ,OAAO,CAAC,CAAC,EACzCG,EAAO,OAAO,OAAO,CAAC,GAAGH,EAAQ,KAAK,CAAC,CAAC,EAE9C,OAAO,OAAO,OAAO,CACpB,KAAAJ,EACA,KAAMI,EAAQ,KACd,IAAMC,GAAgBD,EAAQ,IAAIC,CAAG,EACrC,IAAMA,GAAgBD,EAAQ,IAAIC,CAAG,EACrC,IAAK,IAAMC,EACX,KAAM,IAAMC,CACb,CAAC,CACF",
6
- "names": ["assertStandardSchema", "schema", "context", "createRegistry", "kind", "registrations", "winners", "registration", "entries", "key", "all", "keys"]
4
+ "sourcesContent": ["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"],
5
+ "mappings": "AA2BO,SAASA,EAAqBC,EAAiBC,EAAU,sBAAyC,CAKxG,GAAI,OAHHD,IAAW,OAAS,OAAOA,GAAW,UAAY,OAAOA,GAAW,YAChEA,EAAqC,WAAW,EACjD,SACiB,UAAa,WACjC,MAAM,IAAI,MAAM,GAAGC,CAAO,uDAAuD,EAElF,OAAOD,CACR,CAUA,SAASE,EA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KD,EACjClB,EAAqBmB,EAAa,OAAQ,GAAGJ,CAAI,KAAKR,CAAG,UAAU,EACnEJ,EAAiBgB,EAAa,WAAY,GAAGJ,CAAI,KAAKR,CAAG,GAAG,EAC5Da,EAAQ,IAAIb,EAAK,OAAO,OAAO,CAAE,GAAGY,CAAa,CAAC,CAAC,EAEpD,IAAME,EAAM,OAAO,OAAO,CAAC,GAAGD,EAAQ,OAAO,CAAC,CAAC,EACzCd,EAAO,OAAO,OAAO,CAAC,GAAGc,EAAQ,KAAK,CAAC,CAAC,EAE9C,OAAO,OAAO,OAAO,CACpB,KAAAL,EACA,KAAMK,EAAQ,KACd,IAAMb,GAAgBa,EAAQ,IAAIb,CAAG,EACrC,IAAMA,GAAgBa,EAAQ,IAAIb,CAAG,EACrC,IAAK,IAAMc,EACX,KAAM,IAAMf,CACb,CAAC,CACF",
6
+ "names": ["assertStandardSchema", "schema", "context", "assertChildPaths", "childPaths", "paths", "keys", "key", "joined", "index", "name", "outer", "other", "position", "createRegistry", "kind", "registrations", "options", "winners", "registration", "entries", "all"]
7
7
  }
@@ -0,0 +1,12 @@
1
+ import type { StandardSchemaIssue } from './standard-schema.js';
2
+ /**
3
+ * A Standard Schema issue path as it reads in an error message: object keys joined by dots, array
4
+ * indexes in brackets, for example `steps[0].elements[2].grid.width`. A missing or empty path is the
5
+ * empty string.
6
+ *
7
+ * @param path The `path` of a Standard Schema issue. A segment is a key or an object `{ key }`.
8
+ * @param source The document the path points into. With it, an array item that has a string `id` is
9
+ * followed by the id in parentheses, `steps[0] (main).elements[2] (email).grid.width`, so a log of a
10
+ * document with many nodes names the one it means.
11
+ */
12
+ export declare function formatIssuePath(path: StandardSchemaIssue['path'], source?: unknown): string;
@@ -0,0 +1 @@
1
+ function u(e,o){return typeof e=="object"&&e!==null?Reflect.get(e,o):void 0}function a(e,o){let r=o,n="";for(let s of e??[]){let t=typeof s=="object"?s.key:s;if(r=u(r,t),typeof t=="number"){let f=u(r,"id");n+=typeof f=="string"&&f?`[${t}] (${f})`:`[${t}]`}else n+=n?`.${String(t)}`:String(t)}return n}export{a as formatIssuePath};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/format-issue-path.ts"],
4
+ "sourcesContent": ["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": "AAEA,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": ["childOf", "node", "key", "formatIssuePath", "path", "source", "text", "segment", "id"]
7
+ }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  export * from './types.js';
2
2
  export * from './base-registry.js';
3
3
  export * from './create-registry.js';
4
+ export * from './bind-registry.js';
4
5
  export * from './standard-schema.js';
6
+ export * from './parse-node.js';
7
+ export * from './parse-tree.js';
8
+ export * from './format-issue-path.js';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{Logger as c}from"@ecopages/logger";var o=new c("[@schema-engine/registry]"),u=class{items=new Map;getItemKey(e){return e.$type}getItemName(e){return e.metadata.name}register(e){let t=this.getItemKey(e),s=this.getItemName(e);if(this.items.has(t)){let n=this.items.get(t),i=n?this.getItemName(n):"unknown";o.warn(`Overriding ${this.registryName}: ${t}`,{previousName:i,newName:s})}this.items.set(t,e),o.debug(`Registered ${this.registryName}: ${t}`,{name:s})}has(e){return this.items.has(e)}get(e){return this.items.get(e)}getAll(){return Array.from(this.items.values())}getAllKeys(){return Array.from(this.items.keys())}get size(){return this.items.size}clear(){this.items.clear(),o.debug(`${this.registryName} cleared`)}};function m(r,e="Registration schema"){if(typeof(r!==null&&(typeof r=="object"||typeof r=="function")?r["~standard"]:void 0)?.validate!="function")throw new Error(`${e} must implement Standard Schema (~standard.validate).`);return r}function y(r,e){let t=new Map;for(let a of e)t.set(a.$type,a);let s=new Map;for(let[a,d]of t)m(d.schema,`${r} '${a}' schema`),s.set(a,Object.freeze({...d}));let n=Object.freeze([...s.values()]),i=Object.freeze([...s.keys()]);return Object.freeze({kind:r,size:s.size,get:a=>s.get(a),has:a=>s.has(a),all:()=>n,keys:()=>i})}function f(r,e){let t=r["~standard"].validate(e);if(t&&typeof t.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(t===null||typeof t!="object")throw new Error("Standard Schema validation returned an invalid result");let s=t;return s.issues!==void 0?{success:!1,error:{issues:[...s.issues]}}:{success:!0,data:s.value}}export{u as BaseRegistry,m as assertStandardSchema,y as createRegistry,f as safeParseStandardSchema};
1
+ import{Logger as B}from"@ecopages/logger";var m=new B("[@schema-engine/registry]"),R=class{items=new Map;getItemKey(n){return n.$type}getItemName(n){return n.metadata.name}register(n){let t=this.getItemKey(n),r=this.getItemName(n);if(this.items.has(t)){let s=this.items.get(t),a=s?this.getItemName(s):"unknown";m.warn(`Overriding ${this.registryName}: ${t}`,{previousName:a,newName:r})}this.items.set(t,n),m.debug(`Registered ${this.registryName}: ${t}`,{name:r})}has(n){return this.items.has(n)}get(n){return this.items.get(n)}getAll(){return Array.from(this.items.values())}getAllKeys(){return Array.from(this.items.keys())}get size(){return this.items.size}clear(){this.items.clear(),m.debug(`${this.registryName} cleared`)}};function O(e,n="Registration schema"){if(typeof(e!==null&&(typeof e=="object"||typeof e=="function")?e["~standard"]:void 0)?.validate!="function")throw new Error(`${n} must implement Standard Schema (~standard.validate).`);return e}function N(e,n){if(e===void 0)return;if(!Array.isArray(e))throw new Error(`${n} childPaths must be a list of key paths.`);let t=[];for(let s of e){if(!Array.isArray(s)||s.length===0||s.some(a=>typeof a!="string"||a===""))throw new Error(`${n} childPaths must hold non-empty lists of non-empty keys.`);t.push(s)}let r=t.map(s=>s.join("."));for(let[s,a]of t.entries()){let i=a.join(".");if(r.indexOf(i)!==s)throw new Error(`${n} declares the child path '${i}' twice.`);let o=t.find(d=>d.length<a.length&&d.every((c,u)=>c===a[u]));if(o)throw new Error(`${n} child path '${i}' runs through the child path '${o.join(".")}'.`)}}function S(e,n,t={}){let r=new Map;for(let o of n){if(t.duplicates==="error"&&r.has(o.$type))throw new Error(`${e} '${o.$type}' is registered twice.`);r.set(o.$type,o)}let s=new Map;for(let[o,d]of r)O(d.schema,`${e} '${o}' schema`),N(d.childPaths,`${e} '${o}'`),s.set(o,Object.freeze({...d}));let a=Object.freeze([...s.values()]),i=Object.freeze([...s.keys()]);return Object.freeze({kind:e,size:s.size,get:o=>s.get(o),has:o=>s.has(o),all:()=>a,keys:()=>i})}function A(e,n){let{kind:t}=e;for(let s of Object.keys(n))if(!e.has(s))throw new Error(`${t} binding '${s}' names no registration.`);let r=e.all().map(s=>{let a=Object.hasOwn(n,s.$type)?n[s.$type]:void 0;if(typeof a!="object"||a===null)throw new Error(`${t} '${s.$type}' has no binding.`);for(let i of Object.keys(a))if(Object.hasOwn(s,i))throw new Error(`${t} '${s.$type}' binding sets '${i}', which the contract defines.`);return{...s,...a}});return S(t,r)}function x(e,n){let t=e["~standard"].validate(n);if(t&&typeof t.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(t===null||typeof t!="object")throw new Error("Standard Schema validation returned an invalid result");let r=t;return r.issues!==void 0?{success:!1,error:{issues:[...r.issues]}}:{success:!0,data:r.value}}function z(e){return{"~standard":{version:1,vendor:"schema-engine",validate:e}}}function P(e,n){let t=`No registration for $type '${e}'.`;return n?`${t} ${n}`:t}function j(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function w(e,n,t=[]){if(!j(n))return{success:!1,issues:[{message:"Expected an object with a string $type.",path:t}]};let r=n.$type;if(typeof r!="string")return{success:!1,issues:[{message:"Expected a string $type.",path:[...t,"$type"]}]};let s=e.get(r);if(!s)return{success:!1,issues:[{message:P(r,e.hint),path:[...t,"$type"]}]};let a=x(s.schema,n);return a.success?{success:!0,$type:r,registration:s,data:a.data}:{success:!1,issues:a.error.issues.map(i=>({...i,path:[...t,...i.path??[]]}))}}function h(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function C(e,n){let t=e;for(let r of n){if(!h(t)||!Object.hasOwn(t,r))return;t=t[r]}return t}function $(e,n,t){Object.defineProperty(e,n,{value:t,enumerable:!0,writable:!0,configurable:!0})}function F(e,n,t=[]){let r=[];function s(i,o,d){if(d.includes(i)){r.push({message:"A node cannot contain itself.",path:o});return}let c=w(e,i,o);if(!c.success){r.push(...c.issues);return}let u={};if(h(i))for(let p of c.registration.childPaths??[]){let g=C(i,p),f=[...o,...p],T=[...d,i];if(Array.isArray(g)){let y=g.map((l,b)=>s(l,[...f,b],T));$(u,p.join("."),y.filter(l=>l!==void 0))}else if(h(g)){let y=s(g,f,T);y&&$(u,p.join("."),y)}else g!==void 0&&r.push({message:"Expected a node or a list of nodes.",path:f})}return{$type:c.$type,registration:c.registration,data:c.data,path:o,children:u}}let a=s(n,t,[]);return a&&r.length===0?{success:!0,tree:a}:{success:!1,issues:r}}function k(e,n){return typeof e=="object"&&e!==null?Reflect.get(e,n):void 0}function H(e,n){let t=n,r="";for(let s of e??[]){let a=typeof s=="object"?s.key:s;if(t=k(t,a),typeof a=="number"){let i=k(t,"id");r+=typeof i=="string"&&i?`[${a}] (${i})`:`[${a}]`}else r+=r?`.${String(a)}`:String(a)}return r}export{R as BaseRegistry,O as assertStandardSchema,A as bindRegistry,S as createRegistry,H as formatIssuePath,w as safeParseNode,x as safeParseStandardSchema,F as safeParseTree,z as standardSchema,P as unregisteredTypeMessage};
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/standard-schema.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 * 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 * @throws {Error} Naming the `$type` when a winning registration's schema is not a Standard Schema\n *\n * @remarks\n * 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<TRegistration extends BaseRegistration>(\n\tkind: string,\n\tregistrations: readonly TRegistration[],\n): ReadOnlyRegistry<TRegistration> {\n\tconst winners = new Map<string, TRegistration>();\n\tfor (const registration of registrations) {\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\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 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"],
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,KAAK,YAAYA,CAAQ,EAAI,UAC7DL,EAAO,KAAK,cAAc,KAAK,YAAY,KAAKG,CAAG,GAAI,CACtD,aAAcG,EACd,QAASF,CACV,CAAC,CACF,CAEA,KAAK,MAAM,IAAID,EAAKD,CAAI,EACxBF,EAAO,MAAM,cAAc,KAAK,YAAY,KAAKG,CAAG,GAAI,CACvD,KAAAC,CACD,CAAC,CACF,CAQA,IAAID,EAAoB,CACvB,OAAO,KAAK,MAAM,IAAIA,CAAG,CAC1B,CAQA,IAAIA,EAA+B,CAClC,OAAO,KAAK,MAAM,IAAIA,CAAG,CAC1B,CAOA,QAAmB,CAClB,OAAO,MAAM,KAAK,KAAK,MAAM,OAAO,CAAC,CACtC,CAOA,YAAqB,CACpB,OAAO,MAAM,KAAK,KAAK,MAAM,KAAK,CAAC,CACpC,CAOA,IAAI,MAAe,CAClB,OAAO,KAAK,MAAM,IACnB,CAKA,OAAc,CACb,KAAK,MAAM,MAAM,EACjBH,EAAO,MAAM,GAAG,KAAK,YAAY,UAAU,CAC5C,CACD,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M,KAAMA,EAAW,KAAM,CAChD",
6
- "names": ["Logger", "logger", "BaseRegistry", "item", "key", "name", "existing", "existingName", "assertStandardSchema", "schema", "context", "createRegistry", "kind", "registrations", "winners", "registration", "entries", "key", "all", "keys", "safeParseStandardSchema", "schema", "value", "result", "syncResult"]
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,KAAK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ASA,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"]
7
7
  }
@@ -0,0 +1,72 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import { type StandardSchemaIssue } from './standard-schema.js';
3
+ import type { BaseRegistration } from './types.js';
4
+ /**
5
+ * What {@link safeParseNode} needs of a registry: the registration of a `$type`, of which it reads the schema.
6
+ * Both registry kinds fit.
7
+ */
8
+ export interface NodeLookup<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> {
9
+ get(key: string): TRegistration | undefined;
10
+ /**
11
+ * A sentence that follows the message of a `$type` `get` does not answer, such as where to register it.
12
+ *
13
+ * @remarks
14
+ * The message is `No registration for $type 'x'.`, a space and the hint.
15
+ */
16
+ hint?: string;
17
+ }
18
+ /**
19
+ * What {@link safeParseNode} returns: the registration with the node's validated configuration, or every issue found.
20
+ *
21
+ * @remarks
22
+ * The success branch has one member per registration of a typed registry, so checking `$type` (the node's, repeated at
23
+ * the top of the result because TypeScript narrows a union only by a property of the union itself) narrows
24
+ * `registration` and `data` together. A registration that does not declare its `$type`, such as a lookup typed by
25
+ * `{ schema }` alone, leaves it a `string`. A registry typed as plain `BaseRegistration` has no concrete schema to
26
+ * read, so its `data` is `unknown`.
27
+ */
28
+ export type SafeParseNodeResult<TRegistration extends Pick<BaseRegistration, 'schema'> = BaseRegistration> = (TRegistration extends unknown ? {
29
+ success: true;
30
+ $type: TRegistration extends {
31
+ $type: infer TType extends string;
32
+ } ? TType : string;
33
+ registration: TRegistration;
34
+ data: StandardSchemaV1.InferOutput<TRegistration['schema']>;
35
+ } : never) | {
36
+ success: false;
37
+ issues: StandardSchemaIssue[];
38
+ };
39
+ /**
40
+ * The message for a `$type` no registration answers, as {@link safeParseNode} reports it.
41
+ *
42
+ * @param type - The `$type` that found nothing
43
+ * @param hint - A sentence that follows the message, as {@link NodeLookup.hint} gives it
44
+ *
45
+ * @remarks
46
+ * Exported so a caller that has to throw for the same case, instead of returning an issue, says the same thing.
47
+ */
48
+ export declare function unregisteredTypeMessage(type: string, hint?: string): string;
49
+ /**
50
+ * Check one node against the registration its `$type` names, without throwing.
51
+ *
52
+ * @param registry - Where the node's `$type` finds its registration
53
+ * @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.
55
+ *
56
+ * @remarks
57
+ * 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.
61
+ * Otherwise the issues are those of the registration's schema, with `path` in front of the path the schema reported.
62
+ *
63
+ * `data` is what the schema returned, so its defaults and transforms apply. Its type is the schema output of the
64
+ * registration that `registration.$type` names, for a registry typed by registrations with literal `$type`s, and
65
+ * `unknown` for one typed as `BaseRegistration`. TypeScript cannot follow the runtime lookup from the node's string
66
+ * `$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`.
69
+ *
70
+ * @throws {Error} When the registration's schema validates asynchronously, as {@link safeParseStandardSchema} does.
71
+ */
72
+ export declare function safeParseNode<TRegistration extends Pick<BaseRegistration, 'schema'>>(registry: NodeLookup<TRegistration>, node: unknown, path?: NonNullable<StandardSchemaIssue['path']>): SafeParseNodeResult<TRegistration>;
@@ -0,0 +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};
@@ -0,0 +1,7 @@
1
+ {
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}\n"],
5
+ "mappings": "AAkBO,SAASA,EACfC,EACAC,EACyC,CACzC,IAAMC,EAASF,EAAO,WAAW,EAAE,SAASC,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD,CCOO,SAASC,EAAwBC,EAAcC,EAAuB,CAC5E,IAAMC,EAAU,8BAA8BF,CAAI,KAClD,OAAOC,EAAO,GAAGC,CAAO,IAAID,CAAI,GAAKC,CACtC,CAEA,SAASC,EAASC,EAAuD,CACxE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC3E,CAyBO,SAASC,EACfC,EACAC,EACAC,EAAiD,CAAC,EACb,CACrC,GAAI,CAACL,EAASI,CAAI,EACjB,MAAO,CAAE,QAAS,GAAO,OAAQ,CAAC,CAAE,QAAS,0CAA2C,KAAAC,CAAK,CAAC,CAAE,EAEjG,IAAMR,EAAOO,EAAK,MAClB,GAAI,OAAOP,GAAS,SACnB,MAAO,CAAE,QAAS,GAAO,OAAQ,CAAC,CAAE,QAAS,2BAA4B,KAAM,CAAC,GAAGQ,EAAM,OAAO,CAAE,CAAC,CAAE,EAEtG,IAAMC,EAAeH,EAAS,IAAIN,CAAI,EACtC,GAAI,CAACS,EACJ,MAAO,CACN,QAAS,GACT,OAAQ,CAAC,CAAE,QAASV,EAAwBC,EAAMM,EAAS,IAAI,EAAG,KAAM,CAAC,GAAGE,EAAM,OAAO,CAAE,CAAC,CAC7F,EAED,IAAME,EAASC,EAAwBF,EAAa,OAAQF,CAAI,EAChE,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"]
7
+ }
@@ -0,0 +1,61 @@
1
+ import { type NodeLookup } from './parse-node.js';
2
+ import type { StandardSchemaIssue } from './standard-schema.js';
3
+ import type { BaseRegistration } from './types.js';
4
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
5
+ type TreeRegistration = Pick<BaseRegistration, 'schema' | 'childPaths'>;
6
+ /**
7
+ * One node of a validated document: its registration, the data its schema returned, where it sits and its children.
8
+ *
9
+ * @remarks
10
+ * `$type` is the node's own, repeated at the top for the same reason as on {@link SafeParseNodeResult}: checking it
11
+ * narrows `registration` and `data` together. `children` has one entry per child path the registration declares that
12
+ * the node has a value at, keyed by the keys of the path joined with dots (`['engine', 'controls']` is
13
+ * `'engine.controls'`): a list of nodes for an array, one node otherwise, in document order. A child may be of any
14
+ * registration of the lookup, so `children` holds nodes of the whole union, not of the parent's registration.
15
+ */
16
+ export type ParsedNode<TRegistration extends TreeRegistration> = ParsedNodeOf<TRegistration, TRegistration>;
17
+ /**
18
+ * One member of {@link ParsedNode} per registration.
19
+ *
20
+ * @remarks
21
+ * `TAll` carries the whole union past the distribution over `TMember`: inside the distributive branch `TMember` is one
22
+ * registration, which would type every child as a node of its parent's registration.
23
+ */
24
+ type ParsedNodeOf<TMember extends TreeRegistration, TAll extends TreeRegistration> = TMember extends unknown ? {
25
+ $type: TMember extends {
26
+ $type: infer TType extends string;
27
+ } ? TType : string;
28
+ registration: TMember;
29
+ data: StandardSchemaV1.InferOutput<TMember['schema']>;
30
+ path: NonNullable<StandardSchemaIssue['path']>;
31
+ children: Readonly<Record<string, ParsedNode<TAll> | readonly ParsedNode<TAll>[]>>;
32
+ } : never;
33
+ /** What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found. */
34
+ export type SafeParseTreeResult<TRegistration extends TreeRegistration = BaseRegistration> = {
35
+ success: true;
36
+ tree: ParsedNode<TRegistration>;
37
+ } | {
38
+ success: false;
39
+ issues: StandardSchemaIssue[];
40
+ };
41
+ /**
42
+ * Check a whole document, node by node, without throwing.
43
+ *
44
+ * @param registry - Where each node's `$type` finds its registration
45
+ * @param root - The document's root node, as it arrived
46
+ * @param path - Where the root sits in a larger document; every issue's `path` starts with it
47
+ *
48
+ * @remarks
49
+ * Each node goes through {@link safeParseNode} with its full path, so the issues are those of one node, at the
50
+ * position the document has them. A registration says where its children are with `childPaths`: each path is read
51
+ * from the node as authored, a missing value is no children, an array is walked item by item and an object is one
52
+ * 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
53
+ * node that contains itself. A node whose own schema fails is not walked further, but its siblings still are, so one
54
+ * call reports every issue of the document. The tree is returned only when there are none.
55
+ *
56
+ * One lookup serves the whole tree; which `$type`s a position accepts is the parent's schema to say.
57
+ *
58
+ * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does.
59
+ */
60
+ export declare function safeParseTree<TRegistration extends TreeRegistration>(registry: NodeLookup<TRegistration>, root: unknown, path?: NonNullable<StandardSchemaIssue['path']>): SafeParseTreeResult<TRegistration>;
61
+ export {};
@@ -0,0 +1 @@
1
+ function y(t,r){let e=t["~standard"].validate(r);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 s=e;return s.issues!==void 0?{success:!1,error:{issues:[...s.issues]}}:{success:!0,data:s.value}}function x(t,r){let e=`No registration for $type '${t}'.`;return r?`${e} ${r}`:e}function k(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function S(t,r,e=[]){if(!k(r))return{success:!1,issues:[{message:"Expected an object with a string $type.",path:e}]};let s=r.$type;if(typeof s!="string")return{success:!1,issues:[{message:"Expected a string $type.",path:[...e,"$type"]}]};let n=t.get(s);if(!n)return{success:!1,issues:[{message:x(s,t.hint),path:[...e,"$type"]}]};let i=y(n.schema,r);return i.success?{success:!0,$type:s,registration:n,data:i.data}:{success:!1,issues:i.error.issues.map(a=>({...a,path:[...e,...a.path??[]]}))}}function m(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function N(t,r){let e=t;for(let s of r){if(!m(e)||!Object.hasOwn(e,s))return;e=e[s]}return e}function R(t,r,e){Object.defineProperty(t,r,{value:e,enumerable:!0,writable:!0,configurable:!0})}function O(t,r,e=[]){let s=[];function n(a,u,h){if(h.includes(a)){s.push({message:"A node cannot contain itself.",path:u});return}let o=S(t,a,u);if(!o.success){s.push(...o.issues);return}let f={};if(m(a))for(let c of o.registration.childPaths??[]){let d=N(a,c),l=[...u,...c],T=[...h,a];if(Array.isArray(d)){let p=d.map((g,P)=>n(g,[...l,P],T));R(f,c.join("."),p.filter(g=>g!==void 0))}else if(m(d)){let p=n(d,l,T);p&&R(f,c.join("."),p)}else d!==void 0&&s.push({message:"Expected a node or a list of nodes.",path:l})}return{$type:o.$type,registration:o.registration,data:o.data,path:u,children:f}}let i=n(r,e,[]);return i&&s.length===0?{success:!0,tree:i}:{success:!1,issues:s}}export{O as safeParseTree};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/standard-schema.ts", "../src/parse-node.ts", "../src/parse-tree.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}\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"],
5
+ "mappings": "AAkBO,SAASA,EACfC,EACAC,EACyC,CACzC,IAAMC,EAASF,EAAO,WAAW,EAAE,SAASC,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD,CCOO,SAASC,EAAwBC,EAAcC,EAAuB,CAC5E,IAAMC,EAAU,8BAA8BF,CAAI,KAClD,OAAOC,EAAO,GAAGC,CAAO,IAAID,CAAI,GAAKC,CACtC,CAEA,SAASC,EAASC,EAAuD,CACxE,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC3E,CAyBO,SAASC,EACfC,EACAC,EACAC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Oa,GAAQZ,EAAO,SAAW,EAAI,CAAE,QAAS,GAAM,KAAAY,CAAK,EAAI,CAAE,QAAS,GAAO,OAAAZ,CAAO,CACzF",
6
+ "names": ["safeParseStandardSchema", "schema", "value", "result", "syncResult", "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"]
7
+ }
@@ -21,3 +21,13 @@ export type StandardSchemaSafeParseResult<T> = {
21
21
  * action parsing) need an immediate result.
22
22
  */
23
23
  export declare function safeParseStandardSchema<TInput, TOutput>(schema: StandardSchemaV1<TInput, TOutput>, value: TInput): StandardSchemaSafeParseResult<TOutput>;
24
+ /**
25
+ * A Standard Schema that validates with a function, for a check that is not a schema library's.
26
+ *
27
+ * @param validate - Returns `{ value }` for an input that passes, or `{ issues }` for one that does not
28
+ *
29
+ * @remarks
30
+ * The schema reports `schema-engine` as its vendor and is synchronous, as {@link safeParseStandardSchema} requires.
31
+ * `TInput` only types what the schema accepts, so an authoring type can be inferred from it; `validate` still receives `unknown`.
32
+ */
33
+ export declare function standardSchema<TOutput, TInput = unknown>(validate: (value: unknown) => StandardSchemaV1.Result<TOutput>): StandardSchemaV1<TInput, TOutput>;
@@ -1 +1 @@
1
- function r(a,s){let e=a["~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 t=e;return t.issues!==void 0?{success:!1,error:{issues:[...t.issues]}}:{success:!0,data:t.value}}export{r as safeParseStandardSchema};
1
+ function s(e,n){let t=e["~standard"].validate(n);if(t&&typeof t.then=="function")throw new Error("Async Standard Schema validation is not supported in this context");if(t===null||typeof t!="object")throw new Error("Standard Schema validation returned an invalid result");let a=t;return a.issues!==void 0?{success:!1,error:{issues:[...a.issues]}}:{success:!0,data:a.value}}function r(e){return{"~standard":{version:1,vendor:"schema-engine",validate:e}}}export{s as safeParseStandardSchema,r as standardSchema};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/standard-schema.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"],
5
- "mappings": "AAkBO,SAASA,EACfC,EACAC,EACyC,CACzC,IAAMC,EAASF,EAAO,WAAW,EAAE,SAASC,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD",
6
- "names": ["safeParseStandardSchema", "schema", "value", "result", "syncResult"]
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"],
5
+ "mappings": "AAkBO,SAASA,EACfC,EACAC,EACyC,CACzC,IAAMC,EAASF,EAAO,WAAW,EAAE,SAASC,CAAK,EACjD,GAAIC,GAAU,OAAQA,EAA4B,MAAS,WAC1D,MAAM,IAAI,MAAM,mEAAmE,EAEpF,GAAIA,IAAW,MAAQ,OAAOA,GAAW,SACxC,MAAM,IAAI,MAAM,uDAAuD,EAGxE,IAAMC,EAAaD,EAEnB,OAAIC,EAAW,SAAW,OAClB,CACN,QAAS,GACT,MAAO,CACN,OAAQ,CAAC,GAAGA,EAAW,MAAM,CAC9B,CACD,EAGM,CAAE,QAAS,GAAM,KAAMA,EAAW,KAAM,CAChD,CAWO,SAASC,EACfC,EACoC,CACpC,MAAO,CAAE,YAAa,CAAE,QAAS,EAAG,OAAQ,gBAAiB,SAAAA,CAAS,CAAE,CACzE",
6
+ "names": ["safeParseStandardSchema", "schema", "value", "result", "syncResult", "standardSchema", "validate"]
7
7
  }
package/dist/types.d.ts CHANGED
@@ -41,6 +41,17 @@ export interface BaseRegistration<_TConfig = unknown, TMeta extends Registration
41
41
  schema: StandardSchemaV1;
42
42
  /** Registration metadata (display name, description, and type-specific fields) */
43
43
  metadata: TMeta;
44
+ /**
45
+ * Where a node of this `$type` holds child nodes: key paths into the node, each to one node or to an array of nodes.
46
+ *
47
+ * @remarks
48
+ * `[['blocks'], ['engine', 'controls']]` says a node has children at `node.blocks` and at `node.engine.controls`.
49
+ * A path is read from the node as authored, so the issues {@link safeParseTree} reports point at the document. A
50
+ * missing value is no children, and the schema decides whether it may be missing. An array holds nodes only;
51
+ * what is not a node is reached by its keys, which is why a path is a list of keys. `createRegistry` checks each
52
+ * path when it builds the registry.
53
+ */
54
+ readonly childPaths?: readonly (readonly string[])[];
44
55
  }
45
56
  /**
46
57
  * Component registration interface.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@schema-engine/registry",
3
3
  "type": "module",
4
- "version": "0.5.1",
4
+ "version": "0.5.2",
5
5
  "description": "The registration contract and registries of Schema Engine: documents name registrations by $type, and each registration validates its own configuration",
6
6
  "keywords": [
7
7
  "schema-engine",
package/skill/SKILL.md CHANGED
@@ -19,7 +19,7 @@ This file is the router. It defines the concepts once; the references assume the
19
19
  ## Core concepts
20
20
 
21
21
  - **registration**: `{ $type, schema, metadata, ... }`, where `$type` is the stable key, `schema` is any Standard Schema that describes its config, and `metadata` names it. Elements, recipes, actions, validation rules and appearance axes are all registrations.
22
- - **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list. The last registration of a `$type` wins without a warning, which is how you replace a built-in.
22
+ - **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list. The last registration of a `$type` wins without a warning, which is how you replace a built-in; pass `{ duplicates: 'error' }` to make a repeat a build error instead.
23
23
  - **document**: serializable data whose every node names a registration by `$type`. It is checked against the registrations at the boundary, so what is rendered or run has passed its schema.
24
24
  - **action**: a registration with `execute` that runs on a trigger. Actions run as a sequence, an inner array is a parallel group, and a failure that sets `shouldContinue: false` stops what follows and cancels the group's siblings through their `signal`.
25
25
 
@@ -27,7 +27,7 @@ This file is the router. It defines the concepts once; the references assume the
27
27
 
28
28
  - **config**: a form is plain data, a `FormConfig` of steps holding elements, each with a `$type`, a `name`, `rules` and `constraints`. `engine.defineForm()` (typed, in TypeScript) or `engine.validateForm(unknown)` (portable JSON) checks it against the engine's registrations and returns a frozen `NormalizedFormConfig` that the engine owns.
29
29
  - **container**: the form's state, a `FormStateContainer` from `@schema-engine/forms/state-container`. It owns the nested values, errors, warnings, touched and dirty marks, field-array row ids and the validation in flight. Paths are dotted (`contacts.1.email`) and `FORM_ROOT` is the form itself. Every change is a command (`setValue`, `blur`, `reportNative`, `validate`, `submit`, `reset`, `fieldArray`), and every read is a pure selector over an immutable snapshot.
30
- - **runtime**: `createFormRuntime` is the lifecycle every renderer shares. It builds the container and owns the submission, the wizard steps and their navigation, `form_mount` and `form_change`, and every action dispatch. A renderer supplies only what an element can do, such as focus.
30
+ - **runtime**: for renderer authors, `createFormRuntime` is the lifecycle every renderer shares, and a renderer creates one for each form it draws. It builds the container and owns the submission, the wizard steps and their navigation, `form_mount` and `form_change`, and every action dispatch. A renderer supplies only what an element can do, such as focus. An app does not create one: it gives the engine and a config to a renderer.
31
31
  - **issues and the formatter**: the engine reports what is wrong as an issue (`type`, `source`, `ruleId`, `params`, `message`) and never makes up text. `formatIssue`, a function of the application, turns an issue into the words shown, and falls back to the issue's own `message`.
32
32
 
33
33
  Outcomes use one vocabulary: a check or a submission ends `passed`, `invalid` or `overtaken`. `overtaken` means an edit or a reset outran the check, so there is no verdict and nothing to show.
@@ -49,31 +49,32 @@ A symbol has one import path. `@schema-engine/forms` has these entries: `.` (the
49
49
 
50
50
  Each package ships this router as its own `skill/SKILL.md` and its references in its `skill/reference/` folder, so a reference is `node_modules/@schema-engine/<package>/skill/reference/<file>`, and any installed package has the router. Read the rows of the packages the project depends on and skip the others: a package that is not installed has no file. The deployed site serves the latest version of the router and of every reference at `/skill/`, with the references flat at `/skill/reference/<file>`.
51
51
 
52
- | To do | Package | Reference |
53
- | ---------------------------------------------------------------------------- | ------------------------------ | ------------------------------------ |
54
- | Register something, build a registry, or read a YAML document | `@schema-engine/registry` | `reference/registry.md` |
55
- | Parse, dispatch or cancel actions outside a form | `@schema-engine/actions` | `reference/actions.md` |
56
- | Build a grid, an appearance axis or a layout theme | `@schema-engine/layout` | `reference/layout.md` |
57
- | Create an engine, author a config, use the container or the runtime directly | `@schema-engine/forms` | `reference/forms.md` |
58
- | Add a rule, explain a validation result, or translate messages | `@schema-engine/forms` | `reference/forms-validation.md` |
59
- | Handle submit, server errors, CSRF or wizard steps | `@schema-engine/forms` | `reference/forms-submission.md` |
60
- | Run code on a form event, or define a form action | `@schema-engine/forms` | `reference/forms-actions.md` |
61
- | Render a form in React, or use its hooks | `@schema-engine/forms-react` | `reference/forms-react.md` |
62
- | Write or change a React field widget, and test it | `@schema-engine/forms-react` | `reference/forms-react-widgets.md` |
63
- | Render a form in Radiant, or reach the container from an element | `@schema-engine/forms-radiant` | `reference/forms-radiant.md` |
64
- | Write or change a Radiant field widget, and test it | `@schema-engine/forms-radiant` | `reference/forms-radiant-widgets.md` |
52
+ | To do | Package | Reference |
53
+ | ---------------------------------------------------------------- | ------------------------------ | ------------------------------------ |
54
+ | Register something, build a registry, or read a YAML document | `@schema-engine/registry` | `reference/registry.md` |
55
+ | Parse, dispatch or cancel actions outside a form | `@schema-engine/actions` | `reference/actions.md` |
56
+ | Build a grid, an appearance axis or a layout theme | `@schema-engine/layout` | `reference/layout.md` |
57
+ | Create an engine, author a config, or use the container directly | `@schema-engine/forms` | `reference/forms.md` |
58
+ | Add a rule, explain a validation result, or translate messages | `@schema-engine/forms` | `reference/forms-validation.md` |
59
+ | Handle submit, server errors, CSRF or wizard steps | `@schema-engine/forms` | `reference/forms-submission.md` |
60
+ | Run code on a form event, or define a form action | `@schema-engine/forms` | `reference/forms-actions.md` |
61
+ | Render a form in React, or use its hooks | `@schema-engine/forms-react` | `reference/forms-react.md` |
62
+ | Write or change a React field widget, and test it | `@schema-engine/forms-react` | `reference/forms-react-widgets.md` |
63
+ | Render a form in Radiant, or reach the container from an element | `@schema-engine/forms-radiant` | `reference/forms-radiant.md` |
64
+ | Write or change a Radiant field widget, and test it | `@schema-engine/forms-radiant` | `reference/forms-radiant-widgets.md` |
65
65
 
66
66
  ## Documentation map
67
67
 
68
68
  The full documentation is at `/docs` on the deployed site. The LLM-exported corpus is `/llms.txt` (index) and `/docs-llm/<section>/<slug>.md` (page bodies).
69
69
 
70
- | Section | Path prefix |
71
- | ------------------------------ | ---------------------------------- |
72
- | Schema Engine | `/docs/schema-engine/introduction` |
73
- | `@schema-engine/registry` | `/docs/registry/overview` |
74
- | `@schema-engine/actions` | `/docs/actions/overview` |
75
- | `@schema-engine/forms` | `/docs/forms/overview` |
76
- | `@schema-engine/forms-react` | `/docs/forms-react/overview` |
77
- | `@schema-engine/forms-radiant` | `/docs/forms-radiant/overview` |
78
- | `@schema-engine/layout` | `/docs/layout/overview` |
79
- | Examples | `/docs/examples/overview` |
70
+ | Section | Path prefix |
71
+ | ------------------------------ | ----------------------------------------- |
72
+ | Schema Engine | `/docs/schema-engine/introduction` |
73
+ | `@schema-engine/registry` | `/docs/registry/overview` |
74
+ | `@schema-engine/actions` | `/docs/actions/overview` |
75
+ | `@schema-engine/forms` | `/docs/forms/overview` |
76
+ | `@schema-engine/forms-react` | `/docs/forms-react/overview` |
77
+ | `@schema-engine/forms-radiant` | `/docs/forms-radiant/overview` |
78
+ | `@schema-engine/layout` | `/docs/layout/overview` |
79
+ | Examples | `/docs/examples/overview` |
80
+ | Renderer authors | `/docs/renderer-authors/write-a-renderer` |
@@ -8,7 +8,7 @@ Every registration is `{ $type, schema, metadata }`: `$type` is the stable key,
8
8
 
9
9
  ## createRegistry
10
10
 
11
- `createRegistry(kind, registrations)` builds a frozen registry once, from a list. `kind` is the label in errors.
11
+ `createRegistry(kind, registrations, options?)` builds a frozen registry once, from a list. `kind` is the label in errors.
12
12
 
13
13
  ```ts title="registry/widgets.ts"
14
14
  import * as z from 'zod/mini';
@@ -29,11 +29,85 @@ export const widgets = createRegistry('Widget', [...defaults, custom]);
29
29
  ```
30
30
 
31
31
  - A later registration with the same `$type` replaces the earlier one with no warning, so `[...defaults, custom]` is how you override. The key keeps its first position.
32
+ - `createRegistry(kind, registrations, { duplicates: 'error' })` makes a repeated `$type` a build error instead (`Widget 'card' is registered twice.`, thrown before any schema is checked). Use it for a catalog where a repeat is always a mistake, such as component keys; the default is `'override'`.
32
33
  - Each winning `schema` is checked at build: a value without `~standard.validate` throws, naming the `kind` and the `$type`.
33
34
  - The result has `get`, `has`, `all`, `keys` and `size`, and no `register` or `clear`. It holds a frozen shallow copy of each winner taken at build, so patch a registration before building, or build a new registry from a new list.
34
35
  - Type it with `ReadOnlyRegistry<TRegistration>`.
35
36
 
36
- `safeParseStandardSchema(schema, value)` runs a registration's schema without throwing and returns `{ success: true, data }` or `{ success: false, error: { issues } }` (it throws for a schema that validates asynchronously). Form validation and `parseActions` both go through it; `assertStandardSchema` is the build-time check on its own.
37
+ `bindRegistry(contracts, bindings)` builds a renderer's registry from one registry of contracts (the `$type`, schema and metadata) and one binding per `$type` (a `render`, a tag name: renderer-only data). Two renderers bind the same contracts and share each `schema` by identity:
38
+
39
+ ```ts title="registry/bound-widgets.ts"
40
+ import * as z from 'zod/mini';
41
+ import { bindRegistry, createRegistry } from '@schema-engine/registry';
42
+
43
+ const contracts = createRegistry('Widget', [
44
+ { $type: 'card', schema: z.object({ title: z.string() }), metadata: { name: 'Card' } },
45
+ { $type: 'badge', schema: z.object({ label: z.string() }), metadata: { name: 'Badge' } },
46
+ ]);
47
+
48
+ export const reactWidgets = bindRegistry(contracts, {
49
+ card: { render: (props: { title: string }) => `<h1>${props.title}</h1>` },
50
+ badge: { render: (props: { label: string }) => `<b>${props.label}</b>` },
51
+ });
52
+
53
+ export const radiantWidgets = bindRegistry(contracts, {
54
+ card: { tag: 'se-card' },
55
+ badge: { tag: 'se-badge' },
56
+ });
57
+ ```
58
+
59
+ - The result is a frozen registry built with `createRegistry`: the contracts' order, every schema checked again. For contracts typed by literal `$type` (an inline list), `get('card')` returns that registration without `undefined`, and a missing binding, an extra one (`crad`) and a binding that sets a contract key (`schema`, `metadata`) are compile errors. `RegistryBindings<typeof contracts, ReactBinding>` with `satisfies` fixes the shape every binding of a renderer takes.
60
+ - Whatever the typing, the build throws naming the `kind`: `Widget 'badge' has no binding.`, `Widget binding 'crad' names no registration.` and `Widget 'card' binding sets 'schema', which the contract defines.`
61
+
62
+ `safeParseStandardSchema(schema, value)` runs a registration's schema without throwing and returns `{ success: true, data }` or `{ success: false, error: { issues } }` (it throws for a schema that validates asynchronously). Form validation and `parseActions` both go through it; `assertStandardSchema` is the build-time check on its own. `standardSchema(validate)` builds a Standard Schema from a function that returns `{ value }` or `{ issues }`, for a registration whose check is not a schema library's.
63
+
64
+ `safeParseNode(registry, node, path?)` checks one node of a document: it looks `node.$type` up in the registry (anything with `get(key)`, and optionally `hint`, a sentence added to the message of an unregistered `$type`, such as where to register it), validates the node with the registration's schema and returns `{ success: true, $type, registration, data }` or `{ success: false, issues }`. For a registry typed by its registrations (`createRegistry` keeps the literal `$type` of an inline list), checking `parsed.$type` narrows `registration` and `data` to that registration's schema output with no cast; `data` is `unknown` for a registry typed as `BaseRegistration`. A node that is not an object with a string `$type`, and a `$type` no registration answers, are issues, not throws. Every issue's `path` starts with `path`, the position of the node in its document, so a walk over a tree passes each child its own.
65
+
66
+ ```ts title="registry/draw-node.ts"
67
+ import { formatIssuePath, safeParseNode } from '@schema-engine/registry';
68
+ import { widgets } from './widgets';
69
+
70
+ export function nodeIssues(node: unknown, index: number): string[] {
71
+ const parsed = safeParseNode(widgets, node, ['children', index]);
72
+ return parsed.success ? [] : parsed.issues.map((issue) => `${formatIssuePath(issue.path)}: ${issue.message}`);
73
+ }
74
+ ```
75
+
76
+ `safeParseTree(registry, root, path?)` checks a whole document in one call. A registration says where its children are with `childPaths`, a list of key paths into the node (`[['sections']]`, or `[['blocks'], ['engine', 'controls']]`), each to one node or an array of nodes; `createRegistry` checks the paths when it builds. Every node goes through `safeParseNode` at its full path, a node whose schema fails is not walked further but its siblings still are, a value at a child path that is no node is `Expected a node or a list of nodes.` at that path, and a node that contains itself is an issue, not an overflow. It returns `{ success: true, tree }` or `{ success: false, issues }` with every issue and no tree. A `tree` node is `{ $type, registration, data, path, children }`, with `children` keyed by the child path joined with dots (`'engine.controls'`); checking `$type` narrows `data` as it does on `safeParseNode`.
77
+
78
+ ```ts title="registry/check-tree.ts"
79
+ import * as z from 'zod/mini';
80
+ import { createRegistry, formatIssuePath, safeParseTree } from '@schema-engine/registry';
81
+
82
+ const nodes = createRegistry('Node', [
83
+ {
84
+ $type: 'page',
85
+ schema: z.looseObject({ $type: z.literal('page'), sections: z.array(z.looseObject({ $type: z.string() })) }),
86
+ metadata: { name: 'Page' },
87
+ childPaths: [['sections']],
88
+ },
89
+ {
90
+ $type: 'section',
91
+ schema: z.looseObject({ $type: z.literal('section'), title: z.string() }),
92
+ metadata: { name: 'Section' },
93
+ },
94
+ ]);
95
+
96
+ export function documentIssues(document: unknown): string[] {
97
+ const parsed = safeParseTree(nodes, document);
98
+ return parsed.success
99
+ ? []
100
+ : parsed.issues.map((issue) => `${formatIssuePath(issue.path, document)}: ${issue.message}`);
101
+ }
102
+
103
+ export function sectionTitles(document: unknown): string[] {
104
+ const parsed = safeParseTree(nodes, document);
105
+ const sections = parsed.success ? [parsed.tree.children.sections ?? []].flat() : [];
106
+ return sections.flatMap((section) => (section.$type === 'section' ? [section.data.title] : []));
107
+ }
108
+ ```
109
+
110
+ `formatIssuePath(path, source?)` writes the `path` of an issue as text: keys joined by dots and indexes in brackets (`children[1].label`), the empty string for a missing or empty path. A segment may be a key or a Standard Schema `{ key }` object. Given the document as `source`, an array item with a string `id` is followed by it, `children[1] (hero).label`.
37
111
 
38
112
  ## BaseRegistry
39
113