@schema-engine/registry 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +94 -7
  2. package/dist/bind-registry.d.ts +6 -3
  3. package/dist/bind-registry.js +1 -1
  4. package/dist/bind-registry.js.map +4 -4
  5. package/dist/chunk-24SNVXNP.js +2 -0
  6. package/dist/chunk-24SNVXNP.js.map +7 -0
  7. package/dist/chunk-55J6XMHW.js +0 -0
  8. package/dist/chunk-55J6XMHW.js.map +7 -0
  9. package/dist/chunk-BY4BKVNV.js +1 -0
  10. package/dist/chunk-BY4BKVNV.js.map +7 -0
  11. package/dist/chunk-DDOMNXV7.js +1 -0
  12. package/dist/chunk-DDOMNXV7.js.map +7 -0
  13. package/dist/chunk-DE7GQKZP.js +3 -0
  14. package/dist/chunk-DE7GQKZP.js.map +7 -0
  15. package/dist/chunk-FRJ453UJ.js +1 -0
  16. package/dist/chunk-FRJ453UJ.js.map +7 -0
  17. package/dist/chunk-GX6PAJLU.js +1 -0
  18. package/dist/chunk-GX6PAJLU.js.map +7 -0
  19. package/dist/chunk-HBQNBR6L.js +1 -0
  20. package/dist/chunk-HBQNBR6L.js.map +7 -0
  21. package/dist/chunk-L3ZXHX7S.js +1 -0
  22. package/dist/chunk-L3ZXHX7S.js.map +7 -0
  23. package/dist/chunk-M3SYVKZK.js +1 -0
  24. package/dist/chunk-M3SYVKZK.js.map +7 -0
  25. package/dist/chunk-MWH2GNPD.js +1 -0
  26. package/dist/chunk-MWH2GNPD.js.map +7 -0
  27. package/dist/chunk-O5CRFISG.js +1 -0
  28. package/dist/chunk-O5CRFISG.js.map +7 -0
  29. package/dist/chunk-P3DDHPDA.js +1 -0
  30. package/dist/chunk-P3DDHPDA.js.map +7 -0
  31. package/dist/chunk-UH3CEF45.js +1 -0
  32. package/dist/chunk-UH3CEF45.js.map +7 -0
  33. package/dist/create-registry.d.ts +70 -10
  34. package/dist/create-registry.js +1 -1
  35. package/dist/create-registry.js.map +4 -4
  36. package/dist/export-tree-schema.d.ts +112 -0
  37. package/dist/export-tree-schema.js +1 -0
  38. package/dist/export-tree-schema.js.map +7 -0
  39. package/dist/format-issue-path.js +1 -1
  40. package/dist/format-issue-path.js.map +4 -4
  41. package/dist/index.d.ts +4 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +4 -4
  44. package/dist/json-schema/embedder.d.ts +119 -0
  45. package/dist/json-schema/embedder.js +1 -0
  46. package/dist/json-schema/embedder.js.map +7 -0
  47. package/dist/json-schema/index.d.ts +5 -0
  48. package/dist/json-schema/index.js +1 -0
  49. package/dist/json-schema/index.js.map +7 -0
  50. package/dist/json-schema/slot.d.ts +46 -0
  51. package/dist/json-schema/slot.js +1 -0
  52. package/dist/json-schema/slot.js.map +7 -0
  53. package/dist/json-schema/standard.d.ts +44 -0
  54. package/dist/json-schema/standard.js +1 -0
  55. package/dist/json-schema/standard.js.map +7 -0
  56. package/dist/parse-node.d.ts +69 -10
  57. package/dist/parse-node.js +1 -1
  58. package/dist/parse-node.js.map +4 -4
  59. package/dist/parse-tree.d.ts +111 -35
  60. package/dist/parse-tree.js +1 -1
  61. package/dist/parse-tree.js.map +4 -4
  62. package/dist/registry-error.d.ts +82 -0
  63. package/dist/registry-error.js +1 -0
  64. package/dist/registry-error.js.map +7 -0
  65. package/dist/standard-schema.d.ts +9 -0
  66. package/dist/standard-schema.js +1 -1
  67. package/dist/standard-schema.js.map +4 -4
  68. package/dist/tree-types.d.ts +152 -0
  69. package/dist/tree-types.js +0 -0
  70. package/dist/tree-types.js.map +7 -0
  71. package/dist/types.d.ts +37 -7
  72. package/dist/types.js +1 -0
  73. package/dist/yaml/index.js +1 -4
  74. package/dist/yaml/index.js.map +4 -4
  75. package/dist/yaml/parse.js +1 -2
  76. package/dist/yaml/parse.js.map +4 -4
  77. package/dist/yaml/stringify.js +1 -3
  78. package/dist/yaml/stringify.js.map +4 -4
  79. package/package.json +13 -9
  80. package/skill/SKILL.md +9 -9
  81. package/skill/reference/registry.md +57 -18
  82. package/dist/base-registry.d.ts +0 -73
  83. package/dist/base-registry.js +0 -1
  84. package/dist/base-registry.js.map +0 -7
@@ -1,61 +1,137 @@
1
- import { type NodeLookup } from './parse-node.js';
2
- import type { StandardSchemaIssue } from './standard-schema.js';
3
- import type { BaseRegistration } from './types.js';
4
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
5
- type TreeRegistration = Pick<BaseRegistration, 'schema' | 'childPaths'>;
2
+ import { type NodeLookup, type ParseOptions, type RegistryIssue } from './parse-node.js';
3
+ import type { Accepted, AcceptedOf, CheckLookup, NodeData, TreeRegistration } from './tree-types.js';
4
+ import type { StandardSchemaIssue } from './standard-schema.js';
5
+ import type { ChildPath } from './types.js';
6
6
  /**
7
- * One node of a validated document: its registration, the data its schema returned, where it sits and its children.
7
+ * One node of a validated document: its registration, its data, where it sits and its children.
8
8
  *
9
9
  * @remarks
10
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.
11
+ * narrows `registration` and `data` together. `data` is the node's composed data: the schema output with each child
12
+ * path replaced by the data of the children found there, so it is the same object the parent's data holds at that
13
+ * position, and `tree.data` is the whole parsed document. `children` has one entry per child path the registration
14
+ * declares, in declaration order, each `{ keys, nodes }` with `nodes` empty when the node holds none there, in document
15
+ * order. Find an entry by its `keys`, compared key by key and never by index or by a joined string (`['a.b']` and
16
+ * `['a', 'b']` are two paths), or read `data`, which is typed per path. `TAll` is the whole union of registrations, so a child is typed by what its
17
+ * path accepts, or by the whole union without `accepts`.
15
18
  */
16
- export type ParsedNode<TRegistration extends TreeRegistration> = ParsedNodeOf<TRegistration, TRegistration>;
19
+ export type ParsedNode<TAll extends TreeRegistration, TRegistration extends TreeRegistration = TAll> = TRegistration extends unknown ? {
20
+ $type: TRegistration['$type'];
21
+ registration: TRegistration;
22
+ data: NodeData<TAll, TRegistration>;
23
+ path: NonNullable<StandardSchemaIssue['path']>;
24
+ children: ParsedChildren<TAll, TRegistration['childPaths']>;
25
+ } : never;
26
+ /** The `children` of a node: a tuple over the declared child paths, each `nodes` typed by its `accepts`. */
27
+ type ParsedChildren<TAll extends TreeRegistration, TPaths> = TPaths extends readonly ChildPath[] ? {
28
+ readonly [I in keyof TPaths]: TPaths[I] extends ChildPath ? {
29
+ keys: TPaths[I]['keys'];
30
+ nodes: readonly ParsedNode<TAll, Accepted<TAll, TPaths[I]>>[];
31
+ } : never;
32
+ } : readonly [];
17
33
  /**
18
- * One member of {@link ParsedNode} per registration.
34
+ * One node of a document that has issues: its registration, its own schema output, its data when its subtree parsed,
35
+ * where it sits and the children that parsed.
19
36
  *
20
37
  * @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.
38
+ * `output` is exactly what {@link safeParseNode} returned for the node. No child data is written into it, so a child
39
+ * slot holds whatever the parent's schema returned there (the authored items, for an opaque slot), including children
40
+ * that failed or were pruned. `data` is the node's composed data, as on a {@link ParsedNode}, and is `undefined` when
41
+ * the node's own schema passed but something below it failed, was pruned or was no node. `children` has the type of
42
+ * a {@link ParsedNode}'s: one `{ keys, nodes }` entry per child path the registration declares, in declaration order,
43
+ * with `nodes` holding the children that parsed in document order, each with its own `path` and typed by the path's
44
+ * `accepts`. A child that failed is missing, so the issues, not the position in `nodes`, say where it was. Read the
45
+ * children from `children`, never from a slot of `output`.
23
46
  */
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']>;
47
+ export type PartialNode<TAll extends TreeRegistration, TRegistration extends TreeRegistration = TAll> = TRegistration extends unknown ? {
48
+ $type: TRegistration['$type'];
49
+ registration: TRegistration;
50
+ output: StandardSchemaV1.InferOutput<TRegistration['schema']>;
51
+ data: NodeData<TAll, TRegistration> | undefined;
30
52
  path: NonNullable<StandardSchemaIssue['path']>;
31
- children: Readonly<Record<string, ParsedNode<TAll> | readonly ParsedNode<TAll>[]>>;
53
+ children: PartialChildren<TAll, TRegistration['childPaths']>;
32
54
  } : 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> = {
55
+ /** The `children` of a partial node: the tuple of a {@link ParsedNode}'s, over the nodes that parsed. */
56
+ type PartialChildren<TAll extends TreeRegistration, TPaths> = TPaths extends readonly ChildPath[] ? {
57
+ readonly [I in keyof TPaths]: TPaths[I] extends ChildPath ? {
58
+ keys: TPaths[I]['keys'];
59
+ nodes: readonly PartialNode<TAll, Accepted<TAll, TPaths[I]>>[];
60
+ } : never;
61
+ } : readonly [];
62
+ /**
63
+ * What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found and the nodes that
64
+ * parsed.
65
+ *
66
+ * @remarks
67
+ * `tree` on the failure branch is present exactly when the root's own schema passed, and is absent when the root
68
+ * failed, was not accepted or has no registration.
69
+ */
70
+ export type SafeParseTreeResult<TAll extends TreeRegistration, TRoot extends TreeRegistration = TAll> = {
35
71
  success: true;
36
- tree: ParsedNode<TRegistration>;
72
+ tree: ParsedNode<TAll, TRoot>;
37
73
  } | {
38
74
  success: false;
39
- issues: StandardSchemaIssue[];
75
+ issues: RegistryIssue[];
76
+ tree?: PartialNode<TAll, TRoot>;
40
77
  };
41
78
  /**
42
- * Check a whole document, node by node, without throwing.
79
+ * The registrations a root may be: those `accepts` names, but only when the options type has `accepts`, not when it
80
+ * only may.
81
+ */
82
+ type RootOf<TAll extends TreeRegistration, TOptions> = TOptions extends {
83
+ readonly accepts: readonly (infer TName)[];
84
+ } ? AcceptedOf<TAll, TName> : TAll;
85
+ /**
86
+ * Check a whole document, node by node, without throwing for a bad document.
43
87
  *
44
88
  * @param registry - Where each node's `$type` finds its registration
45
89
  * @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
90
+ * @param options - Where the root sits in a larger document (`path`, which starts every issue's `path`) and which
91
+ * `$type`s the root may have (`accepts`), see {@link ParseOptions}
47
92
  *
48
93
  * @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.
94
+ * Each node goes through {@link safeParseNode} with its full path, and `accepts` of the position it sits in (the
95
+ * option for the root, the child path's own below), so the issues are those of one node, at the position the document
96
+ * has them. A registration says where its children are with `childPaths`, each path read from the node as authored:
97
+ *
98
+ * | Value at the child path | Result |
99
+ * | --- | --- |
100
+ * | key absent, or an intermediate absent or not an object | no children; `data` keeps the schema output there |
101
+ * | `undefined` | no children, as absent |
102
+ * | `null` or another primitive | issue `registry/not-a-node` at the path |
103
+ * | an object | one child |
104
+ * | an array | each item is a child, at `[...path, index]`; an item that is not an object is an issue |
105
+ * | an empty array | no children; `data` holds `[]` |
106
+ * | anything but an array or a missing value, on a path that sets `list` | issue `registry/not-a-list` at the path |
107
+ *
108
+ * A node that contains itself is `registry/contains-itself`. A node whose own schema fails is not walked further, but
109
+ * its siblings still are, so one call reports every issue of the document. When there are none, `tree.data` is the
110
+ * parsed document, each node's schema output with the children's data at its child paths, in document order. When
111
+ * there are issues, `tree` is a {@link PartialNode} of the nodes that parsed, present exactly when the root's own
112
+ * schema passed: every node whose own schema passed and whose parent was kept, with `output`, `data` (`undefined`
113
+ * where something below the node failed) and `children`, typed as on the success branch. A failed node, a child the
114
+ * slot does not accept and the edge of a cycle are left out. Each child is parsed once, from the authored value, and
115
+ * the authored document and the schema outputs are never written to.
116
+ *
117
+ * The parent schema owns, at a child path, whether the value may be missing, list or single, and list bounds; it does
118
+ * not own the children, whose data replaces whatever the schema returned there. For each node it parses, `safeParseTree`
119
+ * holds the schema to that contract and throws a {@link RegistryError} when it breaks it, since that is a bug of the
120
+ * registration and no issue of the document: `'schema-changes-type'` when the output is not a plain object whose own
121
+ * `$type` equals the node's, and `'schema-breaks-child-path'` when, where the document fills a child path, the output
122
+ * lacks the keys down to it as plain objects or the same cardinality (an array of the same length for an array, an
123
+ * object for an object), or when, where the document leaves a path empty, the output holds anything but nothing,
124
+ * `undefined` or `[]`: a default that holds nodes. A transform of the parent at a filled slot (a reorder, say) is
125
+ * discarded, not detected, so slots stay opaque to the parent's schema.
55
126
  *
56
- * One lookup serves the whole tree; which `$type`s a position accepts is the parent's schema to say.
127
+ * The result is typed from the registrations: with a literal `accepts` the root narrows, and `tree.data` types each
128
+ * child path by what it accepts. The walk itself reads registrations through one widened view of the lookup, and
129
+ * the function returns the tree through one cast to that type: every node in it was built from a registration of the
130
+ * lookup by its own `$type`, which TypeScript cannot follow at runtime.
57
131
  *
58
- * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does.
132
+ * @throws {RegistryError} Code `'schema-changes-type'` or `'schema-breaks-child-path'`, as above
133
+ * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does, and when
134
+ * `accepts` is an empty list
59
135
  */
60
- export declare function safeParseTree<TRegistration extends TreeRegistration>(registry: NodeLookup<TRegistration>, root: unknown, path?: NonNullable<StandardSchemaIssue['path']>): SafeParseTreeResult<TRegistration>;
136
+ export declare function safeParseTree<TAll extends TreeRegistration, const TOptions extends ParseOptions<TAll['$type']> = ParseOptions<TAll['$type']>>(registry: NodeLookup<TAll> & CheckLookup<TAll>, root: unknown, options?: TOptions): SafeParseTreeResult<TAll, RootOf<TAll, TOptions>>;
61
137
  export {};
@@ -1 +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};
1
+ import{a}from"./chunk-MWH2GNPD.js";import"./chunk-O5CRFISG.js";import"./chunk-P3DDHPDA.js";import"./chunk-BY4BKVNV.js";export{a as safeParseTree};
@@ -1,7 +1,7 @@
1
1
  {
2
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": "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",
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"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Why building or binding a registry, or parsing a tree, failed. Each code names one mistake in the registrations or
3
+ * bindings.
4
+ *
5
+ * @remarks
6
+ * The codes are the contract: depend on a code, not on the wording of `message`, which may change. A code is only
7
+ * added, never renamed or reused for another mistake.
8
+ *
9
+ * - `'invalid-schema'`: a registration's `schema` has no `~standard.validate` function.
10
+ * - `'invalid-child-paths'`: a registration's `childPaths` is not a list, or holds an entry that is not an object
11
+ * `{ keys, accepts?, list? }` with a non-empty list of non-empty string `keys`, no other property, an `accepts` that
12
+ * is absent or a non-empty list of non-empty strings without repeats, and a `list` that is absent or `true`.
13
+ * `replaceChildSlot` throws it too for a path with no keys. A domain package throws it too for a `childPaths` its own
14
+ * rules refuse.
15
+ * - `'duplicate-child-path'`: a registration declares the same child path (`childPath`) twice, key by key.
16
+ * - `'nested-child-path'`: a child path (`childPath`) runs through another child path (`outerChildPath`) of the same
17
+ * registration.
18
+ * - `'duplicate-type'`: a `$type` is registered twice while `duplicates` is `'error'`.
19
+ * - `'unknown-binding'`: {@link bindRegistry} got a binding whose key (`$type`) is no contract's `$type`.
20
+ * - `'missing-binding'`: {@link bindRegistry} got no binding for a contract.
21
+ * - `'binding-overrides-contract'`: a binding sets a key (`key`) its contract already defines.
22
+ * - `'schema-changes-type'`: {@link safeParseTree} parsed a node whose schema returned an output with another `$type`
23
+ * than the node's, or none.
24
+ * - `'schema-breaks-child-path'`: {@link safeParseTree} parsed a node whose schema returned an output that does not
25
+ * keep a child path (`childPath`) the document fills, or fills one the document leaves empty.
26
+ * - `'unreachable-child-path'`: {@link exportTreeSchema} found no slot for a child path (`childPath`) in the JSON
27
+ * Schema of a registration, because the schema does not declare its keys, or it sits behind `allOf`, a `$ref` or a
28
+ * union, or inside a schema with an `$id` of its own, or because the slot is nullable.
29
+ * - `'schema-without-json-schema'`: {@link exportTreeSchema} met a registration (`$type`) whose schema sets no
30
+ * `~standard.jsonSchema`, while its `resolve` was the default.
31
+ * - `'unknown-accepted-type'`: {@link exportTreeSchema} was given a lookup that lacks a `$type` a child path
32
+ * (`childPath`) accepts (`key`).
33
+ * - `'definition-name-clash'`: {@link exportTreeSchema}, or the JSON Schema embedder it writes through, found that a
34
+ * definition a schema brought along (`key`, brought by `$type`) takes the name of a `$type` or of another definition.
35
+ * - `'invalid-declaration'`: a domain package refuses a declaration of a registration other than its child paths.
36
+ */
37
+ export type RegistryErrorCode = 'invalid-schema' | 'invalid-child-paths' | 'duplicate-child-path' | 'nested-child-path' | 'duplicate-type' | 'unknown-binding' | 'missing-binding' | 'binding-overrides-contract' | 'schema-changes-type' | 'schema-breaks-child-path' | 'unreachable-child-path' | 'schema-without-json-schema' | 'unknown-accepted-type' | 'definition-name-clash' | 'invalid-declaration';
38
+ /** Where a {@link RegistryError} happened, and what its code needs to be described without the message. */
39
+ export interface RegistryErrorDetails {
40
+ /**
41
+ * The registry's label, for example `Widget`.
42
+ *
43
+ * @remarks
44
+ * Absent when a parse failed through a lookup that is not a registry, a function say, which has no label.
45
+ */
46
+ readonly kind?: string;
47
+ /** The `$type` of the registration at fault, or the key of a binding that names no registration. */
48
+ readonly $type: string;
49
+ /**
50
+ * The key a binding sets that its contract defines, for `'binding-overrides-contract'`, the `$type` a child path
51
+ * accepts that the lookup lacks, for `'unknown-accepted-type'`, and the name of the definition that clashes, for
52
+ * `'definition-name-clash'`.
53
+ */
54
+ readonly key?: string;
55
+ /**
56
+ * The keys of the child path at fault, for `'duplicate-child-path'`, `'nested-child-path'` and
57
+ * `'schema-breaks-child-path'`, `'unreachable-child-path'` and `'unknown-accepted-type'`.
58
+ */
59
+ readonly childPath?: readonly string[];
60
+ /** The keys of the child path that `childPath` runs through, for `'nested-child-path'`. */
61
+ readonly outerChildPath?: readonly string[];
62
+ }
63
+ /**
64
+ * Thrown while a registry is built ({@link createRegistry}) or bound ({@link bindRegistry}) from registrations that
65
+ * break a rule, and while a tree is parsed ({@link safeParseTree}) when a schema contradicts its registration.
66
+ *
67
+ * @remarks
68
+ * Branch on `code`, not on `message`: the message is written for a person and may be reworded, while the codes of
69
+ * {@link RegistryErrorCode} stay. `code` with the details is enough to write the message again, in another language
70
+ * say, without parsing it. A parse throws a `RegistryError` only when a schema contradicts its registration, which is
71
+ * a bug of the registration and no issue of the document. Other errors raised while parsing a node or a document (an
72
+ * asynchronous Standard Schema, say), and by {@link assertStandardSchema} on its own, are not `RegistryError`s.
73
+ */
74
+ export declare class RegistryError extends Error implements RegistryErrorDetails {
75
+ readonly code: RegistryErrorCode;
76
+ readonly kind?: string;
77
+ readonly $type: string;
78
+ readonly key?: string;
79
+ readonly childPath?: readonly string[];
80
+ readonly outerChildPath?: readonly string[];
81
+ constructor(code: RegistryErrorCode, message: string, details: RegistryErrorDetails);
82
+ }
@@ -0,0 +1 @@
1
+ import{a}from"./chunk-BY4BKVNV.js";export{a as RegistryError};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -9,6 +9,15 @@ export type StandardSchemaSafeParseResult<T> = {
9
9
  issues: StandardSchemaIssue[];
10
10
  };
11
11
  };
12
+ /**
13
+ * Whether `schema` is a Standard Schema: an object or function with a `~standard.validate` function.
14
+ *
15
+ * @remarks
16
+ * It looks at the shape only and never runs the schema. {@link assertStandardSchema} throws where this returns `false`, and
17
+ * {@link createRegistry} reports a registration for which it is `false` as `'invalid-schema'`. A domain package that checks
18
+ * schemas of its own, such as the slot schemas of a recipe, uses it to throw a {@link RegistryError} with its own details.
19
+ */
20
+ export declare function isStandardSchema(schema: unknown): schema is StandardSchemaV1;
12
21
  /**
13
22
  * Validate `value` with a Standard Schema without throwing.
14
23
  *
@@ -1 +1 @@
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
+ import{a,b,c}from"./chunk-P3DDHPDA.js";export{a as isStandardSchema,b as safeParseStandardSchema,c as standardSchema};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 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\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"]
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
7
  }
@@ -0,0 +1,152 @@
1
+ import type { StandardSchemaV1 } from '@standard-schema/spec';
2
+ import type { BaseRegistration, ChildPath } from './types.js';
3
+ /**
4
+ * What the tree types need of a registration: its `$type`, its schema and where its children are.
5
+ *
6
+ * @remarks
7
+ * `$type` is required, unlike for {@link safeParseNode}, because `accepts` names `$type`s and the data of a child is
8
+ * found by one.
9
+ */
10
+ export type TreeRegistration = Pick<BaseRegistration, '$type' | 'schema' | 'childPaths'>;
11
+ type Output<TRegistration extends Pick<BaseRegistration, 'schema'>> = StandardSchemaV1.InferOutput<TRegistration['schema']>;
12
+ /**
13
+ * The keys an object type declares, without the keys an index signature (a loose schema) only allows.
14
+ *
15
+ * @remarks
16
+ * A parent schema has to declare every key of a child path, so its exported JSON Schema shows the whole node. A loose
17
+ * object type allows any key through its index signature, which does not count as declaring one.
18
+ */
19
+ export type DeclaredKeys<T> = T extends object ? keyof {
20
+ [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: 0;
21
+ } : never;
22
+ /**
23
+ * Whether every key of a child path is declared, walking through optional objects.
24
+ *
25
+ * @remarks
26
+ * A widened `keys` (`string[]`, from a registration that was not written with literals) is not checked.
27
+ */
28
+ type PathDeclared<T, TKeys> = TKeys extends readonly [] ? true : TKeys extends readonly [infer THead extends string, ...infer TRest] ? THead extends DeclaredKeys<NonNullable<T>> ? PathDeclared<NonNullable<T>[THead & keyof NonNullable<T>], TRest> : false : true;
29
+ /** The child paths a registration declares that its schema output does not declare, as `{ $type, keys }`. */
30
+ type UndeclaredChildPaths<T> = T extends {
31
+ $type: infer TType;
32
+ schema: infer TSchema extends StandardSchemaV1;
33
+ readonly childPaths: readonly (infer TPath)[];
34
+ } ? unknown extends StandardSchemaV1.InferOutput<TSchema> ? never : TPath extends {
35
+ readonly keys: infer TKeys;
36
+ } ? PathDeclared<StandardSchemaV1.InferOutput<TSchema>, TKeys> extends true ? never : {
37
+ $type: TType;
38
+ keys: TKeys;
39
+ } : never : never;
40
+ /** The type a schema output has at `TKeys`, or `unknown` when the keys are widened or name nothing it declares. */
41
+ type SlotAt<T, TKeys> = TKeys extends readonly [infer THead extends string, ...infer TRest] ? THead extends keyof NonNullable<T> ? TRest extends readonly [] ? NonNullable<T>[THead] : SlotAt<NonNullable<T>[THead], TRest> : unknown : unknown;
42
+ /** Whether a slot type may hold a list: an array (optional or nullable), or a type that says nothing. */
43
+ type HoldsList<TSlot> = unknown extends TSlot ? true : [NonNullable<TSlot>] extends [never] ? true : [NonNullable<TSlot>] extends [readonly unknown[]] ? true : false;
44
+ /** The child paths that set `list` over a slot the schema output types as no array, as `{ $type, keys }`. */
45
+ type ListPathsNotArrays<T> = T extends {
46
+ readonly childPaths: readonly (infer TPath)[];
47
+ } ? TPath extends {
48
+ readonly keys: infer TKeys;
49
+ readonly list: true;
50
+ } ? T extends {
51
+ $type: infer TType;
52
+ schema: infer TSchema extends StandardSchemaV1;
53
+ } ? HoldsList<SlotAt<StandardSchemaV1.InferOutput<TSchema>, TKeys>> extends true ? never : {
54
+ $type: TType;
55
+ keys: TKeys;
56
+ } : never : never : never;
57
+ /**
58
+ * The properties of a child path entry other than `keys`, `accepts` and `list`, as `{ $type, property }`.
59
+ *
60
+ * @remarks
61
+ * `createRegistry` infers its registrations with a `const` type parameter, which keeps a property the constraint does
62
+ * not know (`accept` for `accepts`) instead of rejecting it as an excess property.
63
+ */
64
+ type UnknownChildPathProperties<T> = T extends {
65
+ $type: infer TType;
66
+ readonly childPaths: readonly (infer TPath)[];
67
+ } ? TPath extends unknown ? [Exclude<keyof TPath, keyof ChildPath>] extends [never] ? never : {
68
+ $type: TType;
69
+ property: Exclude<keyof TPath, keyof ChildPath>;
70
+ } : never : never;
71
+ /**
72
+ * What `createRegistry` intersects with its `registrations` parameter, so a child path the schema does not declare is
73
+ * an error that names it: `Property 'childPathNotInSchema' is missing`, with the `$type` and the keys. A child path
74
+ * entry with a property other than `keys`, `accepts` and `list` is `childPathUnknownProperty`, with the `$type` and the
75
+ * property. A child path that sets `list` over a slot the schema types as no array (an object, a string) is
76
+ * `listPathNotAnArray`, with the `$type` and the keys, since the walk and the export would refuse every value there.
77
+ *
78
+ * @remarks
79
+ * `unknown` when every path is declared and well formed, which is the identity of an intersection. A schema whose
80
+ * output type cannot be read (`unknown`, a plain `StandardSchemaV1`) is not checked here; `safeParseTree` checks it at
81
+ * runtime.
82
+ */
83
+ export type CheckChildPaths<T> = ([UndeclaredChildPaths<T>] extends [never] ? unknown : {
84
+ readonly childPathNotInSchema: UndeclaredChildPaths<T>;
85
+ }) & ([UnknownChildPathProperties<T>] extends [never] ? unknown : {
86
+ readonly childPathUnknownProperty: UnknownChildPathProperties<T>;
87
+ }) & ([ListPathsNotArrays<T>] extends [never] ? unknown : {
88
+ readonly listPathNotAnArray: ListPathsNotArrays<T>;
89
+ });
90
+ type AcceptedNames<T extends TreeRegistration> = T extends {
91
+ readonly childPaths: readonly (infer TPath)[];
92
+ } ? TPath extends {
93
+ readonly accepts: readonly (infer TName)[];
94
+ } ? TName : never : never;
95
+ /** The registrations whose schema output, when it can be read, declares no `$type`. */
96
+ type WithoutType<T extends TreeRegistration> = T extends unknown ? unknown extends Output<T> ? never : '$type' extends DeclaredKeys<Output<T>> ? never : T['$type'] : never;
97
+ /**
98
+ * What `safeParseTree` intersects with its lookup: an `accepts` name the lookup lacks is `acceptsUnknownType`, and a
99
+ * registration whose output declares no `$type` is `schemaOutputWithoutType`.
100
+ *
101
+ * @remarks
102
+ * The check is here, not in `createRegistry`, because a registry is not always the whole vocabulary of a document (a
103
+ * layout names components of another registry), while the lookup handed to `safeParseTree` is whole. Widened
104
+ * declarations skip it.
105
+ */
106
+ export type CheckLookup<T extends TreeRegistration> = ([Exclude<AcceptedNames<T>, T['$type']>] extends [never] ? unknown : {
107
+ readonly acceptsUnknownType: Exclude<AcceptedNames<T>, T['$type']>;
108
+ }) & ([WithoutType<T>] extends [never] ? unknown : {
109
+ readonly schemaOutputWithoutType: WithoutType<T>;
110
+ });
111
+ /**
112
+ * The registrations of a union that may answer one of the names `TName`: every one whose `$type` overlaps them.
113
+ *
114
+ * @remarks
115
+ * A literal `$type` overlaps when it is one of the names, a union of literals when any member is, and a widened
116
+ * `$type` (`string`, as `BaseRegistration` has) or a missing one always does, since it may hold any name at run time.
117
+ */
118
+ export type AcceptedOf<TAll extends TreeRegistration, TName> = TAll extends {
119
+ $type: infer TType;
120
+ } ? string extends TType ? TAll : [Extract<TType, TName>] extends [never] ? never : TAll : TAll;
121
+ /** The registrations a child path accepts: those {@link AcceptedOf} its `accepts`, or all without one. */
122
+ export type Accepted<TAll extends TreeRegistration, TPath> = TPath extends {
123
+ readonly accepts: readonly (infer TName)[];
124
+ } ? AcceptedOf<TAll, TName> : TAll;
125
+ /**
126
+ * The value at a child path once its children are parsed. A list stays a list, an absent slot stays absent, and `null`
127
+ * is not a slot value (it is an issue at runtime).
128
+ */
129
+ type Replace<TValue, TChild, TList> = unknown extends TValue ? (TList extends true ? TChild[] : TChild | TChild[]) | undefined : TValue extends undefined ? TValue : TValue extends null ? never : TValue extends readonly unknown[] ? TChild[] : TChild;
130
+ type SetAt<T, TKeys, TPath, TAll extends TreeRegistration> = TKeys extends readonly [
131
+ infer THead extends string,
132
+ ...infer TRest
133
+ ] ? T extends object ? {
134
+ [P in keyof T]: P extends THead ? TRest extends readonly [] ? Replace<T[P], NodeData<TAll, Accepted<TAll, TPath>>, TPath extends {
135
+ readonly list: true;
136
+ } ? true : false> : SetAt<T[P], TRest, TPath, TAll> : T[P];
137
+ } : T : T;
138
+ type WithChildren<T, TPaths, TAll extends TreeRegistration> = TPaths extends readonly [infer THead, ...infer TRest] ? THead extends ChildPath ? WithChildren<SetAt<T, THead['keys'], THead, TAll>, TRest, TAll> : T : T;
139
+ /**
140
+ * The data of a node once its children are parsed: the schema output of the registration with each child path replaced
141
+ * by the data of what the document holds there.
142
+ *
143
+ * @remarks
144
+ * Optional stays optional, an array slot is an array and an object slot an object. A slot typed `unknown` becomes
145
+ * `child | child[] | undefined`, and `child[] | undefined` for a path that sets `list`. The child type is computed inside the mapped property, so a registration that accepts
146
+ * itself does not recurse eagerly. `child` is the union of the registrations the path accepts, or of the whole lookup
147
+ * without `accepts`. A registry typed as plain `BaseRegistration` has no concrete schema to read, so its data is
148
+ * `unknown`. A `childPaths` that lost its literal keys (a registration declared apart without `as const`) leaves the
149
+ * schema output unchanged.
150
+ */
151
+ export type NodeData<TAll extends TreeRegistration, TRegistration extends TreeRegistration = TAll> = TRegistration extends unknown ? WithChildren<Output<TRegistration>, TRegistration['childPaths'], TAll> : never;
152
+ export {};
File without changes
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
package/dist/types.d.ts CHANGED
@@ -27,6 +27,35 @@ declare const __brand: unique symbol;
27
27
  export type Brand<T, TBrand> = T & {
28
28
  readonly [__brand]?: TBrand;
29
29
  };
30
+ /**
31
+ * One place where a node holds child nodes, as a registration declares it in `childPaths`.
32
+ *
33
+ * @remarks
34
+ * Plain data, so a registration stays serializable. `keys` is relative to the node and holds no indexes, which is why
35
+ * it is not called `path`: a `path` in this package is an absolute document path with indexes. The value there is one
36
+ * node or an array of nodes, unless `list` says the slot holds a list. `accepts` is a closed list of `$type`s, the only way to restrict a slot: it reads no
37
+ * role, tag or category, and `metadata` decides nothing. Adding a leaf to `[...defaults, custom]` means overriding each
38
+ * container that should take it. Without `accepts`, the slot puts no limit on the `$type`, so any `$type` the lookup
39
+ * answers is accepted. The parent's schema keeps the slot opaque (`z.array(z.unknown())`, `z.unknown()`). A tool that
40
+ * reads child paths does not decide what a slot takes: it checks a document with `safeParseTree`, or validates it
41
+ * against the JSON Schema that `exportTreeSchema` writes.
42
+ */
43
+ export interface ChildPath {
44
+ /** The keys from the node to the slot, for example `['engine', 'controls']` for `node.engine.controls`. */
45
+ readonly keys: readonly string[];
46
+ /** The `$type`s allowed at the slot, at least one when present. Absent: `accepts` puts no limit on the `$type`. */
47
+ readonly accepts?: readonly string[];
48
+ /**
49
+ * The slot holds a list of nodes, never one node. Absent: it holds a node or a list.
50
+ *
51
+ * @remarks
52
+ * With `list`, a value that is not an array is the issue `registry/not-a-list` at the path, the exported JSON Schema
53
+ * writes an open slot as an array, and the types read the slot as an array of the children. A missing value is still
54
+ * no children. A registration whose schema declares the slot as an array sets it, so the document, the export and the
55
+ * types agree.
56
+ */
57
+ readonly list?: true;
58
+ }
30
59
  /**
31
60
  * Base registration interface - common fields for all registration types.
32
61
  *
@@ -42,16 +71,17 @@ export interface BaseRegistration<_TConfig = unknown, TMeta extends Registration
42
71
  /** Registration metadata (display name, description, and type-specific fields) */
43
72
  metadata: TMeta;
44
73
  /**
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.
74
+ * Where a node of this `$type` holds child nodes, and which `$type`s each place accepts.
46
75
  *
47
76
  * @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.
77
+ * `[{ keys: ['blocks'], accepts: ['block'] }, { keys: ['engine', 'controls'] }]` says a node has children at
78
+ * `node.blocks` and at `node.engine.controls`. A path is read from the node as authored, so the issues
79
+ * {@link safeParseTree} reports point at the document. A missing value is no children, and the schema decides
80
+ * whether it may be missing. An array holds nodes only; what is not a node is reached by its keys, which is why a
81
+ * path is a list of keys. `createRegistry` checks each path when it builds the registry, and at the type level that
82
+ * the schema declares every key of it.
53
83
  */
54
- readonly childPaths?: readonly (readonly string[])[];
84
+ readonly childPaths?: readonly ChildPath[];
55
85
  }
56
86
  /**
57
87
  * Component registration interface.
package/dist/types.js CHANGED
@@ -0,0 +1 @@
1
+ import"./chunk-55J6XMHW.js";