@schema-engine/registry 0.6.0 → 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.
- package/README.md +4 -3
- package/dist/bind-registry.js +1 -1
- package/dist/chunk-BY4BKVNV.js +1 -0
- package/dist/chunk-BY4BKVNV.js.map +7 -0
- package/dist/{chunk-NSLF54GM.js → chunk-DDOMNXV7.js} +1 -1
- package/dist/chunk-FRJ453UJ.js +1 -0
- package/dist/chunk-FRJ453UJ.js.map +7 -0
- package/dist/{chunk-LG33VSKX.js → chunk-HBQNBR6L.js} +1 -1
- package/dist/{chunk-FMWSZRDV.js → chunk-L3ZXHX7S.js} +1 -1
- package/dist/{chunk-RVS7JY2Y.js → chunk-M3SYVKZK.js} +1 -1
- package/dist/chunk-MWH2GNPD.js +1 -0
- package/dist/chunk-MWH2GNPD.js.map +7 -0
- package/dist/create-registry.js +1 -1
- package/dist/export-tree-schema.d.ts +21 -9
- package/dist/export-tree-schema.js +1 -1
- package/dist/index.js +1 -1
- package/dist/json-schema/embedder.js +1 -1
- package/dist/json-schema/index.js +1 -1
- package/dist/json-schema/slot.js +1 -1
- package/dist/parse-tree.d.ts +21 -15
- package/dist/parse-tree.js +1 -1
- package/dist/registry-error.d.ts +3 -1
- package/dist/registry-error.js +1 -1
- package/package.json +1 -1
- package/skill/reference/registry.md +3 -3
- package/dist/chunk-IYIWS4LW.js +0 -1
- package/dist/chunk-IYIWS4LW.js.map +0 -7
- package/dist/chunk-QHVQ4S4D.js +0 -1
- package/dist/chunk-QHVQ4S4D.js.map +0 -7
- package/dist/chunk-XG4EZ5VP.js +0 -1
- package/dist/chunk-XG4EZ5VP.js.map +0 -7
- /package/dist/{chunk-NSLF54GM.js.map → chunk-DDOMNXV7.js.map} +0 -0
- /package/dist/{chunk-LG33VSKX.js.map → chunk-HBQNBR6L.js.map} +0 -0
- /package/dist/{chunk-FMWSZRDV.js.map → chunk-L3ZXHX7S.js.map} +0 -0
- /package/dist/{chunk-RVS7JY2Y.js.map → chunk-M3SYVKZK.js.map} +0 -0
package/README.md
CHANGED
|
@@ -70,11 +70,11 @@ export function titles(document: unknown): string[] {
|
|
|
70
70
|
}
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
-
When the document has issues, the failure also carries `tree`, a `PartialNode`, when the root's own schema passed: every node whose own schema passed, with `output` (its own schema output) and `children` (the children that parsed, in document order
|
|
73
|
+
When the document has issues, the failure also carries `tree`, a `PartialNode`, when the root's own schema passed: every node whose own schema passed, typed like a parsed node, with `output` (its own schema output), `data` (its composed data, `undefined` where something below the node failed) and `children` (the children that parsed, in document order, typed by their `accepts`). One function over `children` reads the success tree and this one alike. Use it to run your own checks on what parsed. The parent's schema keeps the slot opaque (`z.array(z.unknown())`) and declares every child key; `accepts` is the only way to restrict it. The parent's schema keeps `$type` and the slot's shape in its output, or `safeParseTree` throws a `RegistryError`. The issues the engine creates carry a namespaced `code` (`registry/not-accepted`, `registry/unregistered-type`, `registry/missing-type`, `registry/not-an-object`, `registry/not-a-node`, `registry/not-a-list`, `registry/contains-itself`); an issue from a schema keeps whatever its library wrote.
|
|
74
74
|
|
|
75
75
|
## JSON Schema of a whole document
|
|
76
76
|
|
|
77
|
-
`exportTreeSchema` writes the JSON Schema of the same tree, composed from each registration's own JSON Schema,
|
|
77
|
+
`exportTreeSchema` writes the JSON Schema of the same tree, composed from each registration's own JSON Schema, and the registry depends on no validator. Each registration's schema is read from `~standard.jsonSchema`, which classic `zod`, ArkType and a hand-written schema that sets it provide. `zod/mini` and Valibot do not, so the default throws a `RegistryError` (`'schema-without-json-schema'`) that names the `$type`, and a classic Zod schema that embeds a `zod/mini` one (every schema of `@schema-engine/layout` is one) throws in that converter, which Zod keeps partial so an app bundles only the flavour it uses. `z.toJSONSchema`, Zod's complete converter, writes all three, so for Zod pass a `resolve` that calls it; `instanceof` narrows the Standard Schema `resolve` receives, and `undefined` lists a schema that is not Zod as an open node. The second argument also carries the `$type` of the registration being written, for a `resolve` that throws and names it:
|
|
78
78
|
|
|
79
79
|
```typescript
|
|
80
80
|
import * as z from 'zod/mini';
|
|
@@ -101,7 +101,7 @@ export const documentSchema = exportTreeSchema(nodes, {
|
|
|
101
101
|
});
|
|
102
102
|
```
|
|
103
103
|
|
|
104
|
-
The result is `{ $schema, $defs, anyOf }`: one definition per `$type`, and the root as the union of `accepts` (every `$type` without it). Only the slot of each child path is replaced, by the union of what it accepts, so `required`, `minItems` and `maxItems` stay. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside a schema with an `$id` (`id` for draft-04) of its own) throws a `RegistryError`.
|
|
104
|
+
The result is `{ $schema, $defs, anyOf }`: one definition per `$type`, and the root as the union of `accepts` (every `$type` without it). Only the slot of each child path is replaced, by the union of what it accepts, so `required`, `minItems` and `maxItems` stay. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside a schema with an `$id` (`id` for draft-04) of its own) throws a `RegistryError`. Zod writes a union of primitives as a `type` list (`type: ['string', 'number']`), which is valid JSON Schema, but strict Ajv refuses it unless it is created with `allowUnionTypes: true`.
|
|
105
105
|
|
|
106
106
|
## Errors
|
|
107
107
|
|
|
@@ -120,6 +120,7 @@ Building or binding a registry from registrations that break a rule throws a `Re
|
|
|
120
120
|
| `'schema-changes-type'` | `safeParseTree` parsed a node whose schema returned an output without the node's own `$type` | |
|
|
121
121
|
| `'schema-breaks-child-path'` | `safeParseTree` parsed a node whose schema returned an output that does not keep a child path as the document has it | `childPath` |
|
|
122
122
|
| `'unreachable-child-path'` | `exportTreeSchema` found no slot for a child path in a registration's JSON Schema: not declared, behind `allOf`, a `$ref` or a union, inside an `$id` (`id` for draft-04) of its own, or not an object, an array or open | `childPath` |
|
|
123
|
+
| `'schema-without-json-schema'` | `exportTreeSchema`, with its default `resolve`, met a schema that sets no `~standard.jsonSchema` | |
|
|
123
124
|
| `'unknown-accepted-type'` | `exportTreeSchema` got a lookup that lacks a `$type` a child path accepts | `childPath`, and `key`, the `$type` |
|
|
124
125
|
| `'definition-name-clash'` | A definition a schema brought along takes the name of a `$type` or of another definition | `key`, the name; `$type`, the owner |
|
|
125
126
|
| `'invalid-declaration'` | A domain package refuses a declaration of a registration other than its child paths | None; `$type` is the registration |
|
package/dist/bind-registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-HBQNBR6L.js";import"./chunk-M3SYVKZK.js";import"./chunk-P3DDHPDA.js";import"./chunk-BY4BKVNV.js";export{a as bindRegistry};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i=class extends Error{code;kind;$type;key;childPath;outerChildPath;constructor(r,n,e){super(n),this.name="RegistryError",this.code=r,e.kind!==void 0&&(this.kind=e.kind),this.$type=e.$type,e.key!==void 0&&(this.key=e.key),e.childPath!==void 0&&(this.childPath=e.childPath),e.outerChildPath!==void 0&&(this.outerChildPath=e.outerChildPath)}};export{i as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/registry-error.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Why building or binding a registry, or parsing a tree, failed. Each code names one mistake in the registrations or\n * bindings.\n *\n * @remarks\n * The codes are the contract: depend on a code, not on the wording of `message`, which may change. A code is only\n * added, never renamed or reused for another mistake.\n *\n * - `'invalid-schema'`: a registration's `schema` has no `~standard.validate` function.\n * - `'invalid-child-paths'`: a registration's `childPaths` is not a list, or holds an entry that is not an object\n * `{ keys, accepts?, list? }` with a non-empty list of non-empty string `keys`, no other property, an `accepts` that\n * is absent or a non-empty list of non-empty strings without repeats, and a `list` that is absent or `true`.\n * `replaceChildSlot` throws it too for a path with no keys. A domain package throws it too for a `childPaths` its own\n * rules refuse.\n * - `'duplicate-child-path'`: a registration declares the same child path (`childPath`) twice, key by key.\n * - `'nested-child-path'`: a child path (`childPath`) runs through another child path (`outerChildPath`) of the same\n * registration.\n * - `'duplicate-type'`: a `$type` is registered twice while `duplicates` is `'error'`.\n * - `'unknown-binding'`: {@link bindRegistry} got a binding whose key (`$type`) is no contract's `$type`.\n * - `'missing-binding'`: {@link bindRegistry} got no binding for a contract.\n * - `'binding-overrides-contract'`: a binding sets a key (`key`) its contract already defines.\n * - `'schema-changes-type'`: {@link safeParseTree} parsed a node whose schema returned an output with another `$type`\n * than the node's, or none.\n * - `'schema-breaks-child-path'`: {@link safeParseTree} parsed a node whose schema returned an output that does not\n * keep a child path (`childPath`) the document fills, or fills one the document leaves empty.\n * - `'unreachable-child-path'`: {@link exportTreeSchema} found no slot for a child path (`childPath`) in the JSON\n * Schema of a registration, because the schema does not declare its keys, or it sits behind `allOf`, a `$ref` or a\n * union, or inside a schema with an `$id` of its own, or because the slot is nullable.\n * - `'schema-without-json-schema'`: {@link exportTreeSchema} met a registration (`$type`) whose schema sets no\n * `~standard.jsonSchema`, while its `resolve` was the default.\n * - `'unknown-accepted-type'`: {@link exportTreeSchema} was given a lookup that lacks a `$type` a child path\n * (`childPath`) accepts (`key`).\n * - `'definition-name-clash'`: {@link exportTreeSchema}, or the JSON Schema embedder it writes through, found that a\n * definition a schema brought along (`key`, brought by `$type`) takes the name of a `$type` or of another definition.\n * - `'invalid-declaration'`: a domain package refuses a declaration of a registration other than its child paths.\n */\nexport type RegistryErrorCode =\n\t| 'invalid-schema'\n\t| 'invalid-child-paths'\n\t| 'duplicate-child-path'\n\t| 'nested-child-path'\n\t| 'duplicate-type'\n\t| 'unknown-binding'\n\t| 'missing-binding'\n\t| 'binding-overrides-contract'\n\t| 'schema-changes-type'\n\t| 'schema-breaks-child-path'\n\t| 'unreachable-child-path'\n\t| 'schema-without-json-schema'\n\t| 'unknown-accepted-type'\n\t| 'definition-name-clash'\n\t| 'invalid-declaration';\n\n/** Where a {@link RegistryError} happened, and what its code needs to be described without the message. */\nexport interface RegistryErrorDetails {\n\t/**\n\t * The registry's label, for example `Widget`.\n\t *\n\t * @remarks\n\t * Absent when a parse failed through a lookup that is not a registry, a function say, which has no label.\n\t */\n\treadonly kind?: string;\n\t/** The `$type` of the registration at fault, or the key of a binding that names no registration. */\n\treadonly $type: string;\n\t/**\n\t * The key a binding sets that its contract defines, for `'binding-overrides-contract'`, the `$type` a child path\n\t * accepts that the lookup lacks, for `'unknown-accepted-type'`, and the name of the definition that clashes, for\n\t * `'definition-name-clash'`.\n\t */\n\treadonly key?: string;\n\t/**\n\t * The keys of the child path at fault, for `'duplicate-child-path'`, `'nested-child-path'` and\n\t * `'schema-breaks-child-path'`, `'unreachable-child-path'` and `'unknown-accepted-type'`.\n\t */\n\treadonly childPath?: readonly string[];\n\t/** The keys of the child path that `childPath` runs through, for `'nested-child-path'`. */\n\treadonly outerChildPath?: readonly string[];\n}\n\n/**\n * Thrown while a registry is built ({@link createRegistry}) or bound ({@link bindRegistry}) from registrations that\n * break a rule, and while a tree is parsed ({@link safeParseTree}) when a schema contradicts its registration.\n *\n * @remarks\n * Branch on `code`, not on `message`: the message is written for a person and may be reworded, while the codes of\n * {@link RegistryErrorCode} stay. `code` with the details is enough to write the message again, in another language\n * say, without parsing it. A parse throws a `RegistryError` only when a schema contradicts its registration, which is\n * a bug of the registration and no issue of the document. Other errors raised while parsing a node or a document (an\n * asynchronous Standard Schema, say), and by {@link assertStandardSchema} on its own, are not `RegistryError`s.\n */\nexport class RegistryError extends Error implements RegistryErrorDetails {\n\treadonly code: RegistryErrorCode;\n\treadonly kind?: string;\n\treadonly $type: string;\n\treadonly key?: string;\n\treadonly childPath?: readonly string[];\n\treadonly outerChildPath?: readonly string[];\n\n\tconstructor(code: RegistryErrorCode, message: string, details: RegistryErrorDetails) {\n\t\tsuper(message);\n\t\tthis.name = 'RegistryError';\n\t\tthis.code = code;\n\t\tif (details.kind !== undefined) this.kind = details.kind;\n\t\tthis.$type = details.$type;\n\t\tif (details.key !== undefined) this.key = details.key;\n\t\tif (details.childPath !== undefined) this.childPath = details.childPath;\n\t\tif (details.outerChildPath !== undefined) this.outerChildPath = details.outerChildPath;\n\t}\n}\n"],
|
|
5
|
+
"mappings": "AA0FO,IAAMA,EAAN,cAA4B,KAAsC,CAC/D,KACA,KACA,MACA,IACA,UACA,eAET,YAAYC,EAAyBC,EAAiBC,EAA+B,CACpF,MAAMD,CAAO,EACb,KAAK,KAAO,gBACZ,KAAK,KAAOD,EACRE,EAAQ,OAAS,SAAW,KAAK,KAAOA,EAAQ,MACpD,KAAK,MAAQA,EAAQ,MACjBA,EAAQ,MAAQ,SAAW,KAAK,IAAMA,EAAQ,KAC9CA,EAAQ,YAAc,SAAW,KAAK,UAAYA,EAAQ,WAC1DA,EAAQ,iBAAmB,SAAW,KAAK,eAAiBA,EAAQ,eACzE,CACD",
|
|
6
|
+
"names": ["RegistryError", "code", "message", "details"]
|
|
7
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as $,c as u}from"./chunk-GX6PAJLU.js";import{a as N}from"./chunk-
|
|
1
|
+
import{a as $,c as u}from"./chunk-GX6PAJLU.js";import{a as N}from"./chunk-BY4BKVNV.js";var x=new Set(["const","enum","default","examples"]),E=new Set(["properties","patternProperties","$defs","definitions","dependentSchemas","dependencies"]),y=e=>e==="#"||e.startsWith("#/"),l=e=>e==="draft-04"?"id":"$id",b=(e,n)=>{let t=e[l(n)];return typeof t=="string"&&!t.startsWith("#")};function m(e,n,t,s=!0){if(Array.isArray(e))return e.map(o=>m(o,n,t,!1));if(!u(e))return e;if(!s&&b(e,n))return structuredClone(e);let i={};for(let[o,c]of Object.entries(e))typeof c=="string"?i[o]=t(o,c):x.has(o)?i[o]=structuredClone(c):E.has(o)&&u(c)?i[o]=Object.fromEntries(Object.entries(c).map(([r,a])=>[r,m(a,n,t,!1)])):i[o]=m(c,n,t,!1);return i}function R(e,n){let t=new Set,s=l(n);return m(e,n,(i,o)=>(i==="$anchor"||i==="$dynamicAnchor"?t.add(o):i===s&&o.startsWith("#")&&t.add(o.slice(1)),o)),t}function A(e,n,t){let s=l(n),i=t.anchor?R(e,n):new Set,o=c=>t.anchor&&i.has(c)?t.anchor(c):c;return m(e,n,(c,r)=>c==="$anchor"||c==="$dynamicAnchor"?o(r):c===s&&r.startsWith("#")?`#${o(r.slice(1))}`:c!=="$ref"&&c!=="$dynamicRef"?r:y(r)?t.pointer?t.pointer(r):r:r.startsWith("#")?`#${o(r.slice(1))}`:r)}function g(e){let{$schema:n,...t}=e;return structuredClone(t)}function D(e,n){let t=!1;return m(e,n,(s,i)=>(s==="$ref"&&y(i)&&(t=!0),i)),t}function J(e,n){let t=l(n),s=e[t];if(typeof s!="string"||!s.startsWith("#"))return e;let{[t]:i,...o}=m(e,n,(c,r)=>(c==="$ref"||c==="$dynamicRef")&&r===s?"#":r);return o}var T=e=>e==="draft-2020-12"?"$defs":"definitions";function M(e,n){$(e);let t=T(e),s=l(e),i={},o=new Map,c=0;return{embed(r){let a=g(r);if(b(a,e))return a;let d=D(a,e);if(!d&&R(a,e).size===0)return a;c+=1;let h=`embedded-${c}`;if(d&&n.kind==="collection"){let O=n.uri(h);return i[h]={...r.$schema===void 0?{}:{$schema:r.$schema},...J(a,e),[s]:O},{$ref:O}}let f=w(e,h),S=A(a,e,{pointer:d?O=>`${f}${O.slice(1)}`:void 0,anchor:O=>`${h}-${O}`});return d?(i[h]=S,{$ref:f}):S},embedDefinition(r,a){if(n.kind==="collection"){let f=J(g(r),e);return b(f,e)?{allOf:[{$ref:f[s]}],[t]:{[a]:f}}:f}let{definition:d,nested:h}=K(r,a,e);for(let[f,S]of Object.entries(h)){if(Object.hasOwn(i,f))throw p(a,f);i[f]=S,o.set(f,a)}return d},finish(r){if(Object.keys(i).length===0)return r;let a=n.kind==="collection"?"schemas":t,d=u(r[a])?r[a]:{};for(let h of Object.keys(i)){if(!Object.hasOwn(d,h))continue;let f=o.get(h);throw f===void 0?new Error(`The embedder reserves '${h}'; the document already defines it.`):p(f,h)}return r[a]={...d,...i},r}}}function p(e,n){return new N("definition-name-clash",`The definition '${n}' that '${e}' brought along takes the name of another definition of the export.`,{$type:e,key:n})}function k(e,n){let t="";for(let s of e)t+=n.test(s)?s:`_${s.codePointAt(0).toString(16)}_`;return t}var C=e=>`o${k(e,/[A-Za-z0-9-]/)}`,P=(e,n)=>`${k(e,/[^._]/)}.${n}`;function W(e){return encodeURIComponent(e.replaceAll("~","~0").replaceAll("/","~1")).replaceAll(/%(?:24|26|2B|2C|3A|3B|3D|40)/g,decodeURIComponent)}function w(e,n){return`#/${T(e)}/${W(n)}`}var _=e=>e==="$defs"||e==="definitions";function j(e){return decodeURIComponent(e).replaceAll("~1","/").replaceAll("~0","~")}function K(e,n,t){let s=g(e);if(b(s,t))return{definition:s,nested:{}};let i=d=>P(n,d),o=d=>w(t,d),c=C(n),r=A(s,t,{pointer(d){if(d==="#")return o(n);let h=d.slice(2).split("/"),[f,S,...O]=h;return f!==void 0&&_(j(f))&&S!==void 0?[o(i(j(S))),...O].join("/"):`${o(n)}/${h.join("/")}`},anchor:d=>`${c}.${d}`}),a={};for(let d of["$defs","definitions"]){let h=r[d];if(u(h)){for(let[f,S]of Object.entries(h)){if(Object.hasOwn(a,i(f)))throw p(n,i(f));a[i(f)]=S}delete r[d]}}return{definition:r,nested:a}}export{l as a,b,T as c,M as d,W as e,w as f};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as k}from"./chunk-L3ZXHX7S.js";import{b as E,c as j,d as b,f as N}from"./chunk-DDOMNXV7.js";import{b as $,c as S,d as u,e as T}from"./chunk-GX6PAJLU.js";import{a as f}from"./chunk-BY4BKVNV.js";var v={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"};function P(r,{$type:o,io:a,target:c}){let t=$(r);if(t===void 0)throw new f("schema-without-json-schema",`The schema of '${o}' sets no ~standard.jsonSchema, so the export cannot write it. Pass a resolve that converts it, or resolve: () => undefined to list '${o}' as an open node.`,{$type:o});return t[a]({target:c})}function C(r){return!("all"in r)}function V(r){let o={type:"object",properties:{$type:{const:r.$type}},required:["$type"]};for(let{keys:a}of r.childPaths??[]){let c=o;a.forEach((t,m)=>{let n=c.properties,p=m===a.length-1,h=u(n,t),s=S(h)?h:p?{}:{type:"object",properties:{}};T(n,t,s),!p&&!S(u(s,"properties"))&&(s.properties={}),c=s})}return o}function A(r,o){return new f("unreachable-child-path",`The JSON Schema of '${r}' sets an $id of its own, so the export cannot reach the child path '${o.join(".")}': a $ref written there resolves against that $id, not against the document.`,{$type:r,childPath:o})}function I(r,o={}){let{accepts:a,io:c="input",target:t="draft-2020-12",resolve:m}=o;if(!Object.hasOwn(v,t))throw new Error(`exportTreeSchema writes 'draft-2020-12' or 'draft-07', not '${t}'.`);let n=new Map;for(let e of C(r)?r:[r])for(let i of e.all())n.has(i.$type)||n.set(i.$type,i);if(n.size===0)throw new Error("exportTreeSchema needs at least one registration.");if(a?.length===0)throw new Error("accepts must list at least one $type.");for(let e of a??[])if(!n.has(e))throw new Error(`accepts names '${e}', which is not registered.`);let p=j(t),h=e=>({$ref:N(t,e)}),s=[...n.keys()],g=e=>({anyOf:e.map(h)}),O=b(t,{kind:"document"}),w=new Map;for(let e of n.values()){let i={$type:e.$type,io:c,target:t},J=(m??P)(e.schema,i),l=O.embedDefinition(J??V(e),e.$type);for(let{keys:d,accepts:x,list:R}of e.childPaths??[]){if(E(l,t))throw A(e.$type,d);let y=x?.find(L=>!n.has(L));if(y!==void 0)throw new f("unknown-accepted-type",`The child path '${d.join(".")}' of '${e.$type}' accepts '${y}', which the lookup does not list. Pass every registry of the vocabulary.`,{$type:e.$type,childPath:d,key:y});k(l,{$type:e.$type,keys:d,list:R},g(x??s),{target:t})}w.set(e.$type,l)}return O.finish({$schema:v[t],[p]:Object.fromEntries(w),...g(a??s)})}export{I as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/export-tree-schema.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { createJSONSchemaEmbedder, definitionRef, definitionsKeyword, startsResource } from './json-schema/embedder.js';\nimport { replaceChildSlot } from './json-schema/slot.js';\nimport {\n\tgetOwn,\n\tisPlainObject,\n\treadStandardJSONSchema,\n\tsetOwn,\n\ttype JSONSchemaObject,\n\ttype JSONSchemaTarget,\n} from './json-schema/standard.js';\nimport { RegistryError } from './registry-error.js';\nimport type { TreeRegistration } from './tree-types.js';\n\n/**\n * What {@link exportTreeSchema} needs of a registry: the registrations it lists.\n *\n * @remarks\n * Both registry kinds ({@link createRegistry}, {@link createMutableRegistry}) provide it. A vocabulary spread over several\n * registries is passed as a list of them.\n */\nexport interface ExportLookup {\n\tall(): readonly TreeRegistration[];\n}\n\n/** The two dialects {@link exportTreeSchema} knows the `$schema` and the definitions keyword of. */\ntype TreeSchemaTarget = Extract<JSONSchemaTarget, 'draft-2020-12' | 'draft-07'>;\n\n/** What a `resolve` function is told about the export it takes part in. */\nexport interface ExportSchemaContext {\n\t/** The `$type` of the registration whose schema is being written, to name in an error. */\n\treadonly $type: string;\n\t/** `'input'` is the authored shape, `'output'` the parsed one. */\n\treadonly io: 'input' | 'output';\n\t/** The target the document is written for. */\n\treadonly target: TreeSchemaTarget;\n}\n\n/** Options of {@link exportTreeSchema}. */\nexport interface ExportTreeSchemaOptions {\n\t/**\n\t * The `$type`s the document's root may have. Absent: every `$type` of the lookup.\n\t *\n\t * @remarks\n\t * Each name must be registered in the lookup, and the list must not be empty.\n\t */\n\treadonly accepts?: readonly string[];\n\t/** Which shape of each schema to write. Default `'input'`, the shape an author writes. */\n\treadonly io?: 'input' | 'output';\n\t/**\n\t * The JSON Schema dialect to write. Default `'draft-2020-12'`.\n\t *\n\t * @remarks\n\t * Any other value throws before a schema is read, since a document without `$schema`, or with the wrong keyword for\n\t * its definitions, would be written silently.\n\t */\n\treadonly target?: TreeSchemaTarget;\n\t/**\n\t * Writes the JSON Schema of one registration's schema, or returns `undefined` to list it as an open node.\n\t *\n\t * @remarks\n\t * The default reads `~standard.jsonSchema`, so any schema library that implements Standard JSON Schema exports\n\t * without a function here, and a schema that has none makes the export throw, naming its `$type`, instead of\n\t * writing a document that accepts anything there. Pass a `resolve` for a library that does not provide it, or to\n\t * prefer another converter, and name `context.$type` in an error it throws, as the default does. The registry takes no\n\t * validator dependency.\n\t *\n\t * Classic Zod provides `~standard.jsonSchema`, `zod/mini` does not, and a classic schema that embeds a `zod/mini`\n\t * one (every schema of `@schema-engine/layout`) throws in that converter, which Zod keeps partial so an app bundles\n\t * only the flavour it uses. `z.toJSONSchema`, Zod's complete converter, reads all three:\n\t * `(schema, { io, target }) => (schema instanceof z.core.$ZodType ? z.toJSONSchema(schema, { io, target }) : undefined)`.\n\t *\n\t * A schema that resolves to `undefined` is listed by an open object, as {@link exportTreeSchema} explains:\n\t * `resolve: () => undefined` lists every node open, on purpose. The result is not changed.\n\t */\n\treadonly resolve?: (schema: StandardSchemaV1, context: ExportSchemaContext) => JSONSchemaObject | undefined;\n}\n\nconst DIALECTS: Readonly<Record<TreeSchemaTarget, string>> = {\n\t'draft-2020-12': 'https://json-schema.org/draft/2020-12/schema',\n\t'draft-07': 'http://json-schema.org/draft-07/schema#',\n};\n\n/**\n * Writes a registration's schema through its own `~standard.jsonSchema`.\n *\n * @throws {RegistryError} Code `'schema-without-json-schema'` when the schema sets none, since the document would\n * otherwise accept anything under the `$type` without a sign\n */\nfunction defaultResolve(schema: StandardSchemaV1, { $type, io, target }: ExportSchemaContext): JSONSchemaObject {\n\tconst converter = readStandardJSONSchema(schema);\n\tif (converter === undefined) {\n\t\tthrow new RegistryError(\n\t\t\t'schema-without-json-schema',\n\t\t\t`The schema of '${$type}' sets no ~standard.jsonSchema, so the export cannot write it. Pass a resolve that converts it, or resolve: () => undefined to list '${$type}' as an open node.`,\n\t\t\t{ $type },\n\t\t);\n\t}\n\treturn converter[io]({ target });\n}\n\nfunction isLookupList(lookup: ExportLookup | readonly ExportLookup[]): lookup is readonly ExportLookup[] {\n\treturn !('all' in lookup);\n}\n\n/**\n * The object a schema is listed by when it cannot be read: a node of its `$type` with its child paths in place, each\n * slot left open for {@link exportTreeSchema} to fill.\n */\nfunction openNode(registration: TreeRegistration): JSONSchemaObject {\n\tconst root: JSONSchemaObject = {\n\t\ttype: 'object',\n\t\tproperties: { $type: { const: registration.$type } },\n\t\trequired: ['$type'],\n\t};\n\tfor (const { keys } of registration.childPaths ?? []) {\n\t\tlet current = root;\n\t\tkeys.forEach((key, index) => {\n\t\t\tconst properties = current.properties as Record<string, unknown>;\n\t\t\tconst isLast = index === keys.length - 1;\n\t\t\tconst existing = getOwn(properties, key);\n\t\t\tconst next = isPlainObject(existing) ? existing : isLast ? {} : { type: 'object', properties: {} };\n\t\t\tsetOwn(properties, key, next);\n\t\t\tif (!isLast && !isPlainObject(getOwn(next, 'properties'))) next.properties = {};\n\t\t\tcurrent = next;\n\t\t});\n\t}\n\treturn root;\n}\n\n/**\n * The error for a registration whose own JSON Schema is a resource of its own (it sets an `$id`), so the references\n * written into it would resolve against that `$id` and not against the document.\n */\nfunction unreachableSlot($type: string, keys: readonly string[]): RegistryError {\n\treturn new RegistryError(\n\t\t'unreachable-child-path',\n\t\t`The JSON Schema of '${$type}' sets an $id of its own, so the export cannot reach the child path '${keys.join('.')}': a $ref written there resolves against that $id, not against the document.`,\n\t\t{ $type, childPath: keys },\n\t);\n}\n\n/**\n * Write the JSON Schema of a whole tree of registrations, composed at the JSON Schema level.\n *\n * @param lookup - The registrations to export: a registry, or a list of registries that make up one vocabulary. When\n * two list a `$type`, the first wins, as it does for a lookup that tries them in turn\n * @param options - The root's `accepts`, the `io` and `target` of the schemas, and a `resolve` function, see\n * {@link ExportTreeSchemaOptions}\n * @returns One document, `{ $schema, $defs, anyOf }`: a definition per `$type` under `$defs` (`definitions` for a\n * draft-07 target), and the root as the union of the root's accepted `$type`s\n * @throws {RegistryError} Code `'schema-without-json-schema'` when the default `resolve` meets a schema that sets no\n * `~standard.jsonSchema`, `'unreachable-child-path'` when a slot cannot be found where a registration's JSON\n * Schema declares it, `'unknown-accepted-type'` when a child path accepts a `$type` the lookup lacks, and\n * `'definition-name-clash'` when a definition a schema brought along takes the name of a `$type` or of another definition\n * @throws {Error} When `target` is not `'draft-2020-12'` or `'draft-07'`, before any schema is read, when the lookup\n * holds no registration, when `accepts` is empty, and when it names a `$type` the lookup lacks\n *\n * @remarks\n * Each registration's schema is written by `options.resolve`, by default the schema's own `~standard.jsonSchema`, so\n * any schema library that provides it exports the same way and the registry depends on none of them. A schema that\n * sets none makes the default throw, since the document would accept anything under its `$type`. A `resolve` that\n * returns `undefined` lists the schema by an open object that holds its `$type` and its child paths, so the document\n * still shows where children go: pass `resolve: () => undefined` for that on purpose.\n *\n * Each child path is then replaced in the definition, and only the slot: `required`, `minItems` and `maxItems`, and the\n * sibling keys stay as the registration's schema wrote them. The slot takes the union of the path's `accepts` as\n * `$ref`s to the definitions, or of every `$type` of the lookup without `accepts`:\n *\n * | Slot in the registration's JSON Schema | Becomes |\n * | --- | --- |\n * | an array (`type: 'array'`, `items` or `prefixItems`) | the same array, `items: U`, and `U` at each tuple position |\n * | an object | `U` |\n * | open (`{}`) | `{ anyOf: [U, { type: 'array', items: U }] }`, a child or a list of children |\n *\n * `U` is `{ anyOf: [{ $ref }, ...] }`. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside\n * a schema with an `$id` of its own) throws, since guessing would write a document that disagrees with the registration.\n *\n * A schema that was written as a document of its own is moved into the document by\n * {@link createJSONSchemaEmbedder}, and every local pointer follows. Its `$defs` are lifted to the top as\n * `<owner>.<name>` (`page.address` for the `address` definition of `page`), and each anchor is renamed\n * `<owner part>.<name>`. Both write the owner so that two owners never write the same name: in a lifted name each `.`\n * and `_` of the `$type` is `_2e_` and `_5f_` (`a.b` with `c` is `a_2e_b.c`, `a` with `b.c` is `a.b.c`), and in an anchor\n * the owner part is `o` and the `$type` with every character outside `[A-Za-z0-9-]` written as `_<hex>_`\n * (`ui/button` with `x` is `oui_2f_button.x`, `my-card` with `x` is `omy-card.x`). The anchors it renames are `$anchor`,\n * `$dynamicAnchor`, a draft-07 `$id: '#name'` and a draft-04 `id: '#name'`. A name that is still taken, by a `$type` say, is an error, since the two\n * definitions could not both stay. A name in a `$ref` is a JSON Pointer token (`~` as `~0`, `/` as `~1`) and\n * percent-encoded for the URI fragment.\n */\nexport function exportTreeSchema(\n\tlookup: ExportLookup | readonly ExportLookup[],\n\toptions: ExportTreeSchemaOptions = {},\n): JSONSchemaObject {\n\tconst { accepts, io = 'input', target = 'draft-2020-12', resolve } = options;\n\tif (!Object.hasOwn(DIALECTS, target)) {\n\t\tthrow new Error(`exportTreeSchema writes 'draft-2020-12' or 'draft-07', not '${target}'.`);\n\t}\n\tconst registrations = new Map<string, TreeRegistration>();\n\tfor (const source of isLookupList(lookup) ? lookup : [lookup]) {\n\t\tfor (const registration of source.all()) {\n\t\t\tif (!registrations.has(registration.$type)) registrations.set(registration.$type, registration);\n\t\t}\n\t}\n\tif (registrations.size === 0) throw new Error('exportTreeSchema needs at least one registration.');\n\tif (accepts?.length === 0) throw new Error('accepts must list at least one $type.');\n\tfor (const name of accepts ?? []) {\n\t\tif (!registrations.has(name)) throw new Error(`accepts names '${name}', which is not registered.`);\n\t}\n\n\tconst keyword = definitionsKeyword(target);\n\tconst reference = (name: string) => ({ $ref: definitionRef(target, name) });\n\tconst everyType = [...registrations.keys()];\n\tconst unionOf = (names: readonly string[]): JSONSchemaObject => ({ anyOf: names.map(reference) });\n\n\tconst embedder = createJSONSchemaEmbedder(target, { kind: 'document' });\n\tconst definitions = new Map<string, JSONSchemaObject>();\n\tfor (const registration of registrations.values()) {\n\t\tconst context: ExportSchemaContext = { $type: registration.$type, io, target };\n\t\tconst resolved = (resolve ?? defaultResolve)(registration.schema, context);\n\t\tconst definition = embedder.embedDefinition(resolved ?? openNode(registration), registration.$type);\n\t\tfor (const { keys, accepts: slotAccepts, list } of registration.childPaths ?? []) {\n\t\t\tif (startsResource(definition, target)) throw unreachableSlot(registration.$type, keys);\n\t\t\tconst missing = slotAccepts?.find((name) => !registrations.has(name));\n\t\t\tif (missing !== undefined) {\n\t\t\t\tthrow new RegistryError(\n\t\t\t\t\t'unknown-accepted-type',\n\t\t\t\t\t`The child path '${keys.join('.')}' of '${registration.$type}' accepts '${missing}', which the lookup does not list. Pass every registry of the vocabulary.`,\n\t\t\t\t\t{ $type: registration.$type, childPath: keys, key: missing },\n\t\t\t\t);\n\t\t\t}\n\t\t\treplaceChildSlot(definition, { $type: registration.$type, keys, list }, unionOf(slotAccepts ?? everyType), {\n\t\t\t\ttarget,\n\t\t\t});\n\t\t}\n\t\tdefinitions.set(registration.$type, definition);\n\t}\n\n\treturn embedder.finish({\n\t\t$schema: DIALECTS[target],\n\t\t[keyword]: Object.fromEntries(definitions),\n\t\t...unionOf(accepts ?? everyType),\n\t});\n}\n"],
|
|
5
|
+
"mappings": "0MA8EA,IAAMA,EAAuD,CAC5D,gBAAiB,+CACjB,WAAY,yCACb,EAQA,SAASC,EAAeC,EAA0B,CAAE,MAAAC,EAAO,GAAAC,EAAI,OAAAC,CAAO,EAA0C,CAC/G,IAAMC,EAAYC,EAAuBL,CAAM,EAC/C,GAAII,IAAc,OACjB,MAAM,IAAIE,EACT,6BACA,kBAAkBL,CAAK,wIAAwIA,CAAK,qBACpK,CAAE,MAAAA,CAAM,CACT,EAED,OAAOG,EAAUF,CAAE,EAAE,CAAE,OAAAC,CAAO,CAAC,CAChC,CAEA,SAASI,EAAaC,EAAmF,CACxG,MAAO,EAAE,QAASA,EACnB,CAMA,SAASC,EAASC,EAAkD,CACnE,IAAMC,EAAyB,CAC9B,KAAM,SACN,WAAY,CAAE,MAAO,CAAE,MAAOD,EAAa,KAAM,CAAE,EACnD,SAAU,CAAC,OAAO,CACnB,EACA,OAAW,CAAE,KAAAE,CAAK,IAAKF,EAAa,YAAc,CAAC,EAAG,CACrD,IAAIG,EAAUF,EACdC,EAAK,QAAQ,CAACE,EAAKC,IAAU,CAC5B,IAAMC,EAAaH,EAAQ,WACrBI,EAASF,IAA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": ["DIALECTS", "defaultResolve", "schema", "$type", "io", "target", "converter", "readStandardJSONSchema", "RegistryError", "isLookupList", "lookup", "openNode", "registration", "root", "keys", "current", "key", "index", "properties", "isLast", "existing", "getOwn", "next", "isPlainObject", "setOwn", "unreachableSlot", "exportTreeSchema", "options", "accepts", "resolve", "registrations", "source", "name", "keyword", "definitionsKeyword", "reference", "definitionRef", "everyType", "unionOf", "names", "embedder", "createJSONSchemaEmbedder", "definitions", "context", "resolved", "definition", "slotAccepts", "list", "startsResource", "missing", "replaceChildSlot"]
|
|
7
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as d}from"./chunk-
|
|
1
|
+
import{b as d}from"./chunk-M3SYVKZK.js";import{a as i}from"./chunk-BY4BKVNV.js";function T(r,s){let{kind:t}=r;for(let n of Object.keys(s))if(!r.has(n))throw new i("unknown-binding",`${t} binding '${n}' names no registration.`,{kind:t,$type:n});let a=r.all().map(n=>{let e=Object.hasOwn(s,n.$type)?s[n.$type]:void 0;if(typeof e!="object"||e===null)throw new i("missing-binding",`${t} '${n.$type}' has no binding.`,{kind:t,$type:n.$type});for(let o of Object.keys(e))if(Object.hasOwn(n,o))throw new i("binding-overrides-contract",`${t} '${n.$type}' binding sets '${o}', which the contract defines.`,{kind:t,$type:n.$type,key:o});return{...n,...e}});return d(t,a)}export{T as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as O}from"./chunk-
|
|
1
|
+
import{b as O}from"./chunk-DDOMNXV7.js";import{c as s,d,e as m}from"./chunk-GX6PAJLU.js";import{a as y}from"./chunk-BY4BKVNV.js";var g=["$ref","$dynamicRef","allOf","anyOf","oneOf","not","if","then","else"],N=["title","description","default","examples","deprecated","$comment"];function x(w,b,j,A){let{target:u}=A,{$type:c,keys:r,list:h}=b;if(r.length===0)throw new y("invalid-child-paths",`The child path of '${c}' has no keys, so there is no slot to replace.`,{$type:c,childPath:r});let n=()=>structuredClone(j),o=()=>new y("unreachable-child-path",`The JSON Schema of '${c}' has no slot the export can reach for the child path '${r.join(".")}'. The slot must be a declared property, not behind a reference, allOf or a union, nor inside a schema with an $id (id for draft-04) of its own, and an object, an array or open.`,{$type:c,childPath:r}),l=w;for(let t of r.slice(0,-1)){let i=s(l.properties)?d(l.properties,t):void 0;if(!s(i)||O(i,u))throw o();l=i}let p=r[r.length-1],a=l.properties;if(!s(a)||!Object.hasOwn(a,p))throw o();let S=d(a,p),e=S===!0?{}:S;if(!s(e)||g.some(t=>t in e)||Array.isArray(e.type)||e.nullable===!0||O(e,u))throw o();let f=Object.fromEntries(N.filter(t=>t in e).map(t=>[t,e[t]]));if(e.type==="array"||"items"in e||"prefixItems"in e){if(h===!0){if(e.type!==void 0&&e.type!=="array")throw o();e.type="array"}let t=Array.isArray(e.items),i=t?"additionalItems":"items";Array.isArray(e.prefixItems)&&(e.prefixItems=e.prefixItems.map(n)),t&&(e.items=e.items.map(n)),e[i]!==!1&&(e[i]=n())}else if(e.type==="object"||"properties"in e){if(h===!0)throw o();m(a,p,{...f,...n()})}else if(e.type===void 0&&Object.keys(e).every(t=>t in f)){let t={type:"array",items:n()};m(a,p,h===!0?{...f,...t}:{...f,anyOf:[n(),t]})}else throw o()}export{x as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as f}from"./chunk-P3DDHPDA.js";import{a as g}from"./chunk-
|
|
1
|
+
import{a as f}from"./chunk-P3DDHPDA.js";import{a as g}from"./chunk-BY4BKVNV.js";var u=e=>`${e} must implement Standard Schema (~standard.validate).`;function O(e,t="Registration schema"){if(!f(e))throw new Error(u(t));return e}function b(e,t){return e.length===t.length&&e.every((n,s)=>n===t[s])}function p(e){return typeof e=="string"&&e!==""}function k(e,t,n){if(e===void 0)return;let s=i=>new g("invalid-child-paths",`${t} ${i}`,n);if(!Array.isArray(e))throw s("childPaths must be a list of child paths.");let a=[];for(let[i,o]of e.entries()){let r=`childPaths[${i}]`;if(typeof o!="object"||o===null||Array.isArray(o))throw s(`${r} must be an object { keys, accepts?, list? }.`);let d=Object.keys(o).find(y=>y!=="keys"&&y!=="accepts"&&y!=="list");if(d!==void 0)throw s(`${r} has the property '${d}', which a child path does not have.`);let{keys:c,accepts:h,list:l}=o;if(!Array.isArray(c)||c.length===0||!c.every(p))throw s(`${r}.keys must be a non-empty list of non-empty strings.`);if(h!==void 0){if(!Array.isArray(h)||h.length===0||!h.every(p))throw s(`${r}.accepts must be a non-empty list of non-empty $types when present.`);let y=h.find((w,$)=>h.indexOf(w)!==$);if(y!==void 0)throw s(`${r}.accepts names '${y}' twice.`)}if(l!==void 0&&l!==!0)throw s(`${r}.list must be true when present.`);a.push(c)}for(let[i,o]of a.entries()){let r=o.join(".");if(a.findIndex(c=>b(c,o))!==i)throw new g("duplicate-child-path",`${t} declares the child path '${r}' twice.`,{...n,childPath:[...o]});let d=a.find(c=>c.length<o.length&&c.every((h,l)=>h===o[l]));if(d)throw new g("nested-child-path",`${t} child path '${r}' runs through the child path '${d.join(".")}'.`,{...n,childPath:[...o],outerChildPath:[...d]})}}function R(e,t){let n={kind:e,$type:t.$type};if(!f(t.schema))throw new g("invalid-schema",u(`${e} '${t.$type}' schema`),n);k(t.childPaths,`${e} '${t.$type}'`,n)}function m(e,t){return new g("duplicate-type",`${e} '${t}' is registered twice.`,{kind:e,$type:t})}function j(e,t,n={}){let s=new Map;for(let r of t){if(n.duplicates==="error"&&s.has(r.$type))throw m(e,r.$type);s.set(r.$type,r)}let a=new Map;for(let[r,d]of s)R(e,d),a.set(r,Object.freeze({...d}));let i=Object.freeze([...a.values()]),o=Object.freeze([...a.keys()]);return Object.freeze({kind:e,...n.hint===void 0?{}:{hint:n.hint},size:a.size,get:r=>a.get(r),has:r=>a.has(r),all:()=>i,keys:()=>o})}function x(e,t={}){let n=new Map,s,a;return Object.freeze({kind:e,...t.hint===void 0?{}:{hint:t.hint},get size(){return n.size},get:i=>n.get(i),has:i=>n.has(i),all:()=>s??=Object.freeze([...n.values()]),keys:()=>a??=Object.freeze([...n.keys()]),register:i=>{if(t.duplicates==="error"&&n.has(i.$type))throw m(e,i.$type);R(e,i),n.set(i.$type,Object.freeze({...i})),s=a=void 0},clear:()=>{n.clear(),s=a=void 0}})}export{O as a,j as b,x as c};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as D}from"./chunk-O5CRFISG.js";import{a as j}from"./chunk-BY4BKVNV.js";function B(t,o){let a=s=>({$type:s.$type,registration:s.registration,output:o.get(s)??s.data,data:s.data,path:s.path,children:[]}),n=a(t),e=[[t,n]];for(let s=e.pop();s;s=e.pop()){let[l,h]=s;for(let{keys:r,nodes:A}of l.children){let f=[];h.children.push({keys:r,nodes:f});for(let y of A){let i=a(y);f.push(i),e.push([y,i])}}}return n}function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function E(t){if(!b(t))return!1;let o=Object.getPrototypeOf(t);return o===Object.prototype||o===null}function M(t,o,a){let n=t;for(let e of o){if(!a(n)||!Object.hasOwn(n,e))return;n=n[e]}return n}function V(t,o,a){Object.defineProperty(t,o,{value:a,enumerable:!0,writable:!0,configurable:!0})}function F(t,o){let a={...t},n=new Set([a]);for(let{keys:e,value:s}of o){let l=a;for(let h of e.slice(0,-1)){let r=l[h];n.has(r)||(r={...r},n.add(r),V(l,h,r)),l=r}V(l,e[e.length-1],s)}return a}function J(t,o,a){let n=t,e=[],s=new Map,l=n.kind===void 0?"":`${n.kind} `,h=n.kind===void 0?{}:{kind:n.kind};function r(i,T){return new j("schema-breaks-child-path",`${l}'${i}' schema output does not keep the child path '${T.join(".")}' as the document has it.`,{...h,$type:i,childPath:T})}function A(i,T,S,K){if(S.includes(i)){e.push({code:"registry/contains-itself",message:"A node cannot contain itself.",path:T});return}let m=D(n,i,{path:T,accepts:K});if(!m.success){e.push(...m.issues);return}let{$type:u,registration:I}=m,p=m.data;if(!E(p)||!Object.hasOwn(p,"$type")||p.$type!==u)throw new j("schema-changes-type",`${l}'${u}' schema output must keep its $type '${u}'.`,{...h,$type:u});let q=i,v=[...S,i],C=[],N=[],k=!0;for(let{keys:d,accepts:L,list:z}of I.childPaths??[]){let w=[];C.push({keys:d,nodes:w});let c=M(q,d,b),P=M(p,d,E),O=[...T,...d];if(c===void 0){if(P!==void 0&&!(Array.isArray(P)&&P.length===0))throw r(u,d)}else if(z===!0&&!Array.isArray(c))e.push({code:"registry/not-a-list",message:"Expected a list of nodes.",path:O}),k=!1;else if(Array.isArray(c)){if(!Array.isArray(P)||P.length!==c.length)throw r(u,d);let g=0;for(let R=0;R<c.length;R+=1){let $=A(c[R],[...O,R],v,L);$&&(w.push($),$.data!==void 0&&(g+=1))}g===c.length?N.push({keys:d,value:w.map(R=>R.data)}):k=!1}else if(b(c)){if(!b(P))throw r(u,d);let g=A(c,O,v,L);g?(w.push(g),g.data!==void 0?N.push({keys:d,value:g.data}):k=!1):k=!1}else e.push({code:"registry/not-a-node",message:"Expected a node or a list of nodes.",path:O}),k=!1}let x;k&&(x=N.length===0?p:F(p,N));let W={$type:u,registration:I,data:x,path:T,children:C};return x!==p&&s.set(W,p),W}let f=A(o,a?.path??[],[],a?.accepts),y;return f?.data!==void 0&&e.length===0?y={success:!0,tree:f}:f?y={success:!1,issues:e,tree:B(f,s)}:y={success:!1,issues:e},y}export{J as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/parse-tree.ts"],
|
|
4
|
+
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseNode, type NodeLookup, type ParseOptions, type RegistryIssue } from './parse-node.js';\nimport { RegistryError } from './registry-error.js';\nimport type { Accepted, AcceptedOf, CheckLookup, NodeData, TreeRegistration } from './tree-types.js';\nimport type { StandardSchemaIssue } from './standard-schema.js';\nimport type { ChildPath } from './types.js';\n\n/**\n * One node of a validated document: its registration, its data, 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. `data` is the node's composed data: the schema output with each child\n * path replaced by the data of the children found there, so it is the same object the parent's data holds at that\n * position, and `tree.data` is the whole parsed document. `children` has one entry per child path the registration\n * declares, in declaration order, each `{ keys, nodes }` with `nodes` empty when the node holds none there, in document\n * order. Find an entry by its `keys`, compared key by key and never by index or by a joined string (`['a.b']` and\n * `['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\n * path accepts, or by the whole union without `accepts`.\n */\nexport type ParsedNode<\n\tTAll extends TreeRegistration,\n\tTRegistration extends TreeRegistration = TAll,\n> = TRegistration extends unknown\n\t? {\n\t\t\t$type: TRegistration['$type'];\n\t\t\tregistration: TRegistration;\n\t\t\tdata: NodeData<TAll, TRegistration>;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: ParsedChildren<TAll, TRegistration['childPaths']>;\n\t\t}\n\t: never;\n\n/** The `children` of a node: a tuple over the declared child paths, each `nodes` typed by its `accepts`. */\ntype ParsedChildren<TAll extends TreeRegistration, TPaths> = TPaths extends readonly ChildPath[]\n\t? {\n\t\t\treadonly [I in keyof TPaths]: TPaths[I] extends ChildPath\n\t\t\t\t? { keys: TPaths[I]['keys']; nodes: readonly ParsedNode<TAll, Accepted<TAll, TPaths[I]>>[] }\n\t\t\t\t: never;\n\t\t}\n\t: readonly [];\n\n/**\n * One node of a document that has issues: its registration, its own schema output, its data when its subtree parsed,\n * where it sits and the children that parsed.\n *\n * @remarks\n * `output` is exactly what {@link safeParseNode} returned for the node. No child data is written into it, so a child\n * slot holds whatever the parent's schema returned there (the authored items, for an opaque slot), including children\n * that failed or were pruned. `data` is the node's composed data, as on a {@link ParsedNode}, and is `undefined` when\n * the node's own schema passed but something below it failed, was pruned or was no node. `children` has the type of\n * a {@link ParsedNode}'s: one `{ keys, nodes }` entry per child path the registration declares, in declaration order,\n * with `nodes` holding the children that parsed in document order, each with its own `path` and typed by the path's\n * `accepts`. A child that failed is missing, so the issues, not the position in `nodes`, say where it was. Read the\n * children from `children`, never from a slot of `output`.\n */\nexport type PartialNode<\n\tTAll extends TreeRegistration,\n\tTRegistration extends TreeRegistration = TAll,\n> = TRegistration extends unknown\n\t? {\n\t\t\t$type: TRegistration['$type'];\n\t\t\tregistration: TRegistration;\n\t\t\toutput: StandardSchemaV1.InferOutput<TRegistration['schema']>;\n\t\t\tdata: NodeData<TAll, TRegistration> | undefined;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: PartialChildren<TAll, TRegistration['childPaths']>;\n\t\t}\n\t: never;\n\n/** The `children` of a partial node: the tuple of a {@link ParsedNode}'s, over the nodes that parsed. */\ntype PartialChildren<TAll extends TreeRegistration, TPaths> = TPaths extends readonly ChildPath[]\n\t? {\n\t\t\treadonly [I in keyof TPaths]: TPaths[I] extends ChildPath\n\t\t\t\t? { keys: TPaths[I]['keys']; nodes: readonly PartialNode<TAll, Accepted<TAll, TPaths[I]>>[] }\n\t\t\t\t: never;\n\t\t}\n\t: readonly [];\n\n/**\n * What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found and the nodes that\n * parsed.\n *\n * @remarks\n * `tree` on the failure branch is present exactly when the root's own schema passed, and is absent when the root\n * failed, was not accepted or has no registration.\n */\nexport type SafeParseTreeResult<TAll extends TreeRegistration, TRoot extends TreeRegistration = TAll> =\n\t| { success: true; tree: ParsedNode<TAll, TRoot> }\n\t| { success: false; issues: RegistryIssue[]; tree?: PartialNode<TAll, TRoot> };\n\n/**\n * The registrations a root may be: those `accepts` names, but only when the options type has `accepts`, not when it\n * only may.\n */\ntype RootOf<TAll extends TreeRegistration, TOptions> = TOptions extends {\n\treadonly accepts: readonly (infer TName)[];\n}\n\t? AcceptedOf<TAll, TName>\n\t: TAll;\n\n/**\n * A node the walk kept, in the shape of a {@link ParsedNode}, which the success path returns as it is.\n *\n * @remarks\n * `data` is the composed data, and is `undefined` exactly when something below the node failed, was pruned or was no\n * node: a complete node's data is always an object, so `data !== undefined` is the completeness test and the node\n * carries no flag. The schema output of a node whose `data` is not that same object is kept apart, in the walk's\n * `outputs`, so a node costs no field the caller would see.\n */\ninterface WalkedNode {\n\t$type: string;\n\tregistration: TreeRegistration;\n\tdata: unknown;\n\tpath: NonNullable<StandardSchemaIssue['path']>;\n\tchildren: { keys: readonly string[]; nodes: WalkedNode[] }[];\n}\n\ninterface PartialRuntimeNode {\n\t$type: string;\n\tregistration: TreeRegistration;\n\toutput: unknown;\n\tdata: unknown;\n\tpath: NonNullable<StandardSchemaIssue['path']>;\n\tchildren: { keys: readonly string[]; nodes: PartialRuntimeNode[] }[];\n}\n\n/**\n * The {@link PartialNode} shape of a walked tree, built without recursion so that a document as deep as the walk can\n * handle converts too.\n *\n * @remarks\n * A node's `output` is its entry in `outputs`, or its `data` when it has none: a node with no child to write has the\n * schema output itself as `data`.\n */\nfunction toPartial(root: WalkedNode, outputs: ReadonlyMap<WalkedNode, unknown>): PartialRuntimeNode {\n\tconst partialOf = (node: WalkedNode): PartialRuntimeNode => ({\n\t\t$type: node.$type,\n\t\tregistration: node.registration,\n\t\toutput: outputs.get(node) ?? node.data,\n\t\tdata: node.data,\n\t\tpath: node.path,\n\t\tchildren: [],\n\t});\n\tconst top = partialOf(root);\n\tconst pending: [WalkedNode, PartialRuntimeNode][] = [[root, top]];\n\tfor (let next = pending.pop(); next; next = pending.pop()) {\n\t\tconst [source, target] = next;\n\t\tfor (const { keys, nodes } of source.children) {\n\t\t\tconst kept: PartialRuntimeNode[] = [];\n\t\t\ttarget.children.push({ keys, nodes: kept });\n\t\t\tfor (const child of nodes) {\n\t\t\t\tconst converted = partialOf(child);\n\t\t\t\tkept.push(converted);\n\t\t\t\tpending.push([child, converted]);\n\t\t\t}\n\t\t}\n\t}\n\treturn top;\n}\n\ntype PlainObject = Record<PropertyKey, unknown>;\n\nfunction isRecord(value: unknown): value is PlainObject {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n\tif (!isRecord(value)) return false;\n\tconst prototype: unknown = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/**\n * The value an object holds at keys, through own entries only, or `undefined` when an intermediate is absent or not an\n * object that `isObject` accepts.\n *\n * @remarks\n * Only own keys count: a key a plain object inherits, such as `constructor`, is no child.\n */\nfunction valueAt(\n\troot: PlainObject,\n\tkeys: readonly string[],\n\tisObject: (value: unknown) => value is PlainObject,\n): unknown {\n\tlet current: unknown = root;\n\tfor (const key of keys) {\n\t\tif (!isObject(current) || !Object.hasOwn(current, key)) return undefined;\n\t\tcurrent = current[key];\n\t}\n\treturn current;\n}\n\n/**\n * Set 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 setOwn(target: PlainObject, key: string, value: unknown): void {\n\tObject.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/**\n * A copy of a node's schema output with each child slot replaced, without touching the output.\n *\n * @remarks\n * The output shares references with the authored document (a loose object returns the authored array), so it is\n * never written to. The root and each object on a path are shallow-copied once, and two paths with a shared prefix\n * share that copy.\n */\nfunction withChildData(\n\toutput: PlainObject,\n\twrites: readonly { keys: readonly string[]; value: unknown }[],\n): PlainObject {\n\tconst root: PlainObject = { ...output };\n\tconst copies = new Set<object>([root]);\n\tfor (const { keys, value } of writes) {\n\t\tlet current = root;\n\t\tfor (const key of keys.slice(0, -1)) {\n\t\t\tlet next = current[key] as PlainObject;\n\t\t\tif (!copies.has(next)) {\n\t\t\t\tnext = { ...next };\n\t\t\t\tcopies.add(next);\n\t\t\t\tsetOwn(current, key, next);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t}\n\t\tsetOwn(current, keys[keys.length - 1]!, value);\n\t}\n\treturn root;\n}\n\n/**\n * Check a whole document, node by node, without throwing for a bad document.\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 options - Where the root sits in a larger document (`path`, which starts every issue's `path`) and which\n * `$type`s the root may have (`accepts`), see {@link ParseOptions}\n *\n * @remarks\n * Each node goes through {@link safeParseNode} with its full path, and `accepts` of the position it sits in (the\n * option for the root, the child path's own below), so the issues are those of one node, at the position the document\n * has them. A registration says where its children are with `childPaths`, each path read from the node as authored:\n *\n * | Value at the child path | Result |\n * | --- | --- |\n * | key absent, or an intermediate absent or not an object | no children; `data` keeps the schema output there |\n * | `undefined` | no children, as absent |\n * | `null` or another primitive | issue `registry/not-a-node` at the path |\n * | an object | one child |\n * | an array | each item is a child, at `[...path, index]`; an item that is not an object is an issue |\n * | an empty array | no children; `data` holds `[]` |\n * | anything but an array or a missing value, on a path that sets `list` | issue `registry/not-a-list` at the path |\n *\n * A node that contains itself is `registry/contains-itself`. A node whose own schema fails is not walked further, but\n * its siblings still are, so one call reports every issue of the document. When there are none, `tree.data` is the\n * parsed document, each node's schema output with the children's data at its child paths, in document order. When\n * there are issues, `tree` is a {@link PartialNode} of the nodes that parsed, present exactly when the root's own\n * schema passed: every node whose own schema passed and whose parent was kept, with `output`, `data` (`undefined`\n * where something below the node failed) and `children`, typed as on the success branch. A failed node, a child the\n * slot does not accept and the edge of a cycle are left out. Each child is parsed once, from the authored value, and\n * the authored document and the schema outputs are never written to.\n *\n * The parent schema owns, at a child path, whether the value may be missing, list or single, and list bounds; it does\n * not own the children, whose data replaces whatever the schema returned there. For each node it parses, `safeParseTree`\n * holds the schema to that contract and throws a {@link RegistryError} when it breaks it, since that is a bug of the\n * registration and no issue of the document: `'schema-changes-type'` when the output is not a plain object whose own\n * `$type` equals the node's, and `'schema-breaks-child-path'` when, where the document fills a child path, the output\n * lacks the keys down to it as plain objects or the same cardinality (an array of the same length for an array, an\n * object for an object), or when, where the document leaves a path empty, the output holds anything but nothing,\n * `undefined` or `[]`: a default that holds nodes. A transform of the parent at a filled slot (a reorder, say) is\n * discarded, not detected, so slots stay opaque to the parent's schema.\n *\n * The result is typed from the registrations: with a literal `accepts` the root narrows, and `tree.data` types each\n * child path by what it accepts. The walk itself reads registrations through one widened view of the lookup, and\n * the function returns the tree through one cast to that type: every node in it was built from a registration of the\n * lookup by its own `$type`, which TypeScript cannot follow at runtime.\n *\n * @throws {RegistryError} Code `'schema-changes-type'` or `'schema-breaks-child-path'`, as above\n * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does, and when\n * `accepts` is an empty list\n */\nexport function safeParseTree<\n\tTAll extends TreeRegistration,\n\tconst TOptions extends ParseOptions<TAll['$type']> = ParseOptions<TAll['$type']>,\n>(\n\tregistry: NodeLookup<TAll> & CheckLookup<TAll>,\n\troot: unknown,\n\toptions?: TOptions,\n): SafeParseTreeResult<TAll, RootOf<TAll, TOptions>> {\n\tconst lookup: NodeLookup<TreeRegistration> = registry;\n\tconst issues: RegistryIssue[] = [];\n\tconst outputs = new Map<WalkedNode, unknown>();\n\tconst label = lookup.kind === undefined ? '' : `${lookup.kind} `;\n\n\tconst kind = lookup.kind === undefined ? {} : { kind: lookup.kind };\n\n\tfunction brokenSlot(type: string, keys: readonly string[]): RegistryError {\n\t\treturn new RegistryError(\n\t\t\t'schema-breaks-child-path',\n\t\t\t`${label}'${type}' schema output does not keep the child path '${keys.join('.')}' as the document has it.`,\n\t\t\t{ ...kind, $type: type, childPath: keys },\n\t\t);\n\t}\n\n\tfunction walk(\n\t\tnode: unknown,\n\t\tnodePath: NonNullable<StandardSchemaIssue['path']>,\n\t\tancestors: readonly unknown[],\n\t\taccepts: readonly string[] | undefined,\n\t): WalkedNode | undefined {\n\t\tif (ancestors.includes(node)) {\n\t\t\tissues.push({ code: 'registry/contains-itself', message: 'A node cannot contain itself.', path: nodePath });\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parsed = safeParseNode(lookup, node, { path: nodePath, accepts });\n\t\tif (!parsed.success) {\n\t\t\tissues.push(...parsed.issues);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst { $type: type, registration } = parsed;\n\t\tconst output: unknown = parsed.data;\n\t\tif (!isPlainObject(output) || !Object.hasOwn(output, '$type') || output.$type !== type) {\n\t\t\tthrow new RegistryError(\n\t\t\t\t'schema-changes-type',\n\t\t\t\t`${label}'${type}' schema output must keep its $type '${type}'.`,\n\t\t\t\t{ ...kind, $type: type },\n\t\t\t);\n\t\t}\n\n\t\tconst authored = node as PlainObject;\n\t\tconst trail = [...ancestors, node];\n\t\tconst groups: WalkedNode['children'] = [];\n\t\tconst writes: { keys: readonly string[]; value: unknown }[] = [];\n\t\tlet complete = true;\n\t\tfor (const { keys, accepts: childAccepts, list } of registration.childPaths ?? []) {\n\t\t\tconst nodes: WalkedNode[] = [];\n\t\t\tgroups.push({ keys, nodes });\n\t\t\tconst slot = valueAt(authored, keys, isRecord);\n\t\t\tconst held = valueAt(output, keys, isPlainObject);\n\t\t\tconst childPath = [...nodePath, ...keys];\n\t\t\tif (slot === undefined) {\n\t\t\t\tif (held !== undefined && !(Array.isArray(held) && held.length === 0)) {\n\t\t\t\t\tthrow brokenSlot(type, keys);\n\t\t\t\t}\n\t\t\t} else if (list === true && !Array.isArray(slot)) {\n\t\t\t\tissues.push({ code: 'registry/not-a-list', message: 'Expected a list of nodes.', path: childPath });\n\t\t\t\tcomplete = false;\n\t\t\t} else if (Array.isArray(slot)) {\n\t\t\t\tif (!Array.isArray(held) || held.length !== slot.length) throw brokenSlot(type, keys);\n\t\t\t\tlet kept = 0;\n\t\t\t\tfor (let index = 0; index < slot.length; index += 1) {\n\t\t\t\t\tconst child = walk(slot[index], [...childPath, index], trail, childAccepts);\n\t\t\t\t\tif (child) {\n\t\t\t\t\t\tnodes.push(child);\n\t\t\t\t\t\tif (child.data !== undefined) kept += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (kept === slot.length) {\n\t\t\t\t\twrites.push({ keys, value: nodes.map((item) => item.data) });\n\t\t\t\t} else {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t}\n\t\t\t} else if (isRecord(slot)) {\n\t\t\t\tif (!isRecord(held)) throw brokenSlot(type, keys);\n\t\t\t\tconst child = walk(slot, childPath, trail, childAccepts);\n\t\t\t\tif (child) {\n\t\t\t\t\tnodes.push(child);\n\t\t\t\t\tif (child.data !== undefined) writes.push({ keys, value: child.data });\n\t\t\t\t\telse complete = false;\n\t\t\t\t} else {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'registry/not-a-node',\n\t\t\t\t\tmessage: 'Expected a node or a list of nodes.',\n\t\t\t\t\tpath: childPath,\n\t\t\t\t});\n\t\t\t\tcomplete = false;\n\t\t\t}\n\t\t}\n\t\tlet data: unknown;\n\t\tif (complete) data = writes.length === 0 ? output : withChildData(output, writes);\n\t\tconst kept: WalkedNode = { $type: type, registration, data, path: nodePath, children: groups };\n\t\tif (data !== output) outputs.set(kept, output);\n\t\treturn kept;\n\t}\n\n\tconst walked = walk(root, options?.path ?? [], [], options?.accepts);\n\tlet result: unknown;\n\tif (walked?.data !== undefined && issues.length === 0) result = { success: true, tree: walked };\n\telse if (walked) result = { success: false, issues, tree: toPartial(walked, outputs) };\n\telse result = { success: false, issues };\n\treturn result as SafeParseTreeResult<TAll, RootOf<TAll, TOptions>>;\n}\n"],
|
|
5
|
+
"mappings": "gFAuIA,SAASA,EAAUC,EAAkBC,EAA+D,CACnG,IAAMC,EAAaC,IAA0C,CAC5D,MAAOA,EAAK,MACZ,aAAcA,EAAK,aACnB,OAAQF,EAAQ,IAAIE,CAAI,GAAKA,EAAK,KAClC,KAAMA,EAAK,KACX,KAAMA,EAAK,KACX,SAAU,CAAC,CACZ,GACMC,EAAMF,EAAUF,CAAI,EACpBK,EAA8C,CAAC,CAACL,EAAMI,CAAG,CAAC,EAChE,QAASE,EAAOD,EAAQ,IAAI,EAAGC,EAAMA,EAAOD,EAAQ,IAAI,EAAG,CAC1D,GAAM,CAACE,EAAQC,CAAM,EAAIF,EACzB,OAAW,CAAE,KAAAG,EAAM,MAAAC,CAAM,IAAKH,EAAO,SAAU,CAC9C,IAAM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AASqC,CAAI,EAAG,MAAMjB,EAAWC,EAAM1B,CAAI,EAChD,IAAMG,EAAQyB,EAAKa,EAAME,EAAWP,EAAOG,CAAY,EACnDpC,GACHF,EAAM,KAAKE,CAAK,EACZA,EAAM,OAAS,OAAWa,EAAO,KAAK,CAAE,KAAAhB,EAAM,MAAOG,EAAM,IAAK,CAAC,EAChEmC,EAAW,IAEhBA,EAAW,EAEb,MACChB,EAAO,KAAK,CACX,KAAM,sBACN,QAAS,sCACT,KAAMqB,CACP,CAAC,EACDL,EAAW,EAEb,CACA,IAAIQ,EACAR,IAAUQ,EAAO9B,EAAO,SAAW,EAAID,EAASD,EAAcC,EAAQC,CAAM,GAChF,IAAMd,EAAmB,CAAE,MAAOwB,EAAM,aAAAQ,EAAc,KAAAY,EAAM,KAAMjB,EAAU,SAAUQ,CAAO,EAC7F,OAAIS,IAAS/B,GAAQvB,EAAQ,IAAIU,EAAMa,CAAM,EACtCb,CACR,CAEA,IAAM6C,EAASnB,EAAKrC,EAAM6B,GAAS,MAAQ,CAAC,EAAG,CAAC,EAAGA,GAAS,OAAO,EAC/D4B,EACJ,OAAID,GAAQ,OAAS,QAAazB,EAAO,SAAW,EAAG0B,EAAS,CAAE,QAAS,GAAM,KAAMD,CAAO,EACrFA,EAAQC,EAAS,CAAE,QAAS,GAAO,OAAA1B,EAAQ,KAAMhC,EAAUyD,EAAQvD,CAAO,CAAE,EAChFwD,EAAS,CAAE,QAAS,GAAO,OAAA1B,CAAO,EAChC0B,CACR",
|
|
6
|
+
"names": ["toPartial", "root", "outputs", "partialOf", "node", "top", "pending", "next", "source", "target", "keys", "nodes", "kept", "child", "converted", "isRecord", "value", "isPlainObject", "prototype", "valueAt", "isObject", "current", "key", "setOwn", "withChildData", "output", "writes", "copies", "safeParseTree", "registry", "options", "lookup", "issues", "label", "kind", "brokenSlot", "type", "RegistryError", "walk", "nodePath", "ancestors", "accepts", "parsed", "safeParseNode", "registration", "authored", "trail", "groups", "complete", "childAccepts", "list", "slot", "held", "childPath", "index", "item", "data", "walked", "result"]
|
|
7
|
+
}
|
package/dist/create-registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-M3SYVKZK.js";import"./chunk-P3DDHPDA.js";import"./chunk-BY4BKVNV.js";export{a as assertStandardSchema,c as createMutableRegistry,b as createRegistry};
|
|
@@ -15,6 +15,8 @@ export interface ExportLookup {
|
|
|
15
15
|
type TreeSchemaTarget = Extract<JSONSchemaTarget, 'draft-2020-12' | 'draft-07'>;
|
|
16
16
|
/** What a `resolve` function is told about the export it takes part in. */
|
|
17
17
|
export interface ExportSchemaContext {
|
|
18
|
+
/** The `$type` of the registration whose schema is being written, to name in an error. */
|
|
19
|
+
readonly $type: string;
|
|
18
20
|
/** `'input'` is the authored shape, `'output'` the parsed one. */
|
|
19
21
|
readonly io: 'input' | 'output';
|
|
20
22
|
/** The target the document is written for. */
|
|
@@ -40,14 +42,22 @@ export interface ExportTreeSchemaOptions {
|
|
|
40
42
|
*/
|
|
41
43
|
readonly target?: TreeSchemaTarget;
|
|
42
44
|
/**
|
|
43
|
-
* Writes the JSON Schema of one registration's schema, or returns `undefined`
|
|
45
|
+
* Writes the JSON Schema of one registration's schema, or returns `undefined` to list it as an open node.
|
|
44
46
|
*
|
|
45
47
|
* @remarks
|
|
46
48
|
* The default reads `~standard.jsonSchema`, so any schema library that implements Standard JSON Schema exports
|
|
47
|
-
* without a function here
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
49
|
+
* without a function here, and a schema that has none makes the export throw, naming its `$type`, instead of
|
|
50
|
+
* writing a document that accepts anything there. Pass a `resolve` for a library that does not provide it, or to
|
|
51
|
+
* prefer another converter, and name `context.$type` in an error it throws, as the default does. The registry takes no
|
|
52
|
+
* validator dependency.
|
|
53
|
+
*
|
|
54
|
+
* Classic Zod provides `~standard.jsonSchema`, `zod/mini` does not, and a classic schema that embeds a `zod/mini`
|
|
55
|
+
* one (every schema of `@schema-engine/layout`) throws in that converter, which Zod keeps partial so an app bundles
|
|
56
|
+
* only the flavour it uses. `z.toJSONSchema`, Zod's complete converter, reads all three:
|
|
57
|
+
* `(schema, { io, target }) => (schema instanceof z.core.$ZodType ? z.toJSONSchema(schema, { io, target }) : undefined)`.
|
|
58
|
+
*
|
|
59
|
+
* A schema that resolves to `undefined` is listed by an open object, as {@link exportTreeSchema} explains:
|
|
60
|
+
* `resolve: () => undefined` lists every node open, on purpose. The result is not changed.
|
|
51
61
|
*/
|
|
52
62
|
readonly resolve?: (schema: StandardSchemaV1, context: ExportSchemaContext) => JSONSchemaObject | undefined;
|
|
53
63
|
}
|
|
@@ -60,7 +70,8 @@ export interface ExportTreeSchemaOptions {
|
|
|
60
70
|
* {@link ExportTreeSchemaOptions}
|
|
61
71
|
* @returns One document, `{ $schema, $defs, anyOf }`: a definition per `$type` under `$defs` (`definitions` for a
|
|
62
72
|
* draft-07 target), and the root as the union of the root's accepted `$type`s
|
|
63
|
-
* @throws {RegistryError} Code `'
|
|
73
|
+
* @throws {RegistryError} Code `'schema-without-json-schema'` when the default `resolve` meets a schema that sets no
|
|
74
|
+
* `~standard.jsonSchema`, `'unreachable-child-path'` when a slot cannot be found where a registration's JSON
|
|
64
75
|
* Schema declares it, `'unknown-accepted-type'` when a child path accepts a `$type` the lookup lacks, and
|
|
65
76
|
* `'definition-name-clash'` when a definition a schema brought along takes the name of a `$type` or of another definition
|
|
66
77
|
* @throws {Error} When `target` is not `'draft-2020-12'` or `'draft-07'`, before any schema is read, when the lookup
|
|
@@ -68,9 +79,10 @@ export interface ExportTreeSchemaOptions {
|
|
|
68
79
|
*
|
|
69
80
|
* @remarks
|
|
70
81
|
* Each registration's schema is written by `options.resolve`, by default the schema's own `~standard.jsonSchema`, so
|
|
71
|
-
*
|
|
72
|
-
*
|
|
73
|
-
*
|
|
82
|
+
* any schema library that provides it exports the same way and the registry depends on none of them. A schema that
|
|
83
|
+
* sets none makes the default throw, since the document would accept anything under its `$type`. A `resolve` that
|
|
84
|
+
* returns `undefined` lists the schema by an open object that holds its `$type` and its child paths, so the document
|
|
85
|
+
* still shows where children go: pass `resolve: () => undefined` for that on purpose.
|
|
74
86
|
*
|
|
75
87
|
* Each child path is then replaced in the definition, and only the slot: `required`, `minItems` and `maxItems`, and the
|
|
76
88
|
* sibling keys stay as the registration's schema wrote them. The slot takes the union of the path's `accepts` as
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-FRJ453UJ.js";import"./chunk-L3ZXHX7S.js";import"./chunk-DDOMNXV7.js";import"./chunk-GX6PAJLU.js";import"./chunk-BY4BKVNV.js";export{a as exportTreeSchema};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-55J6XMHW.js";import{a as x}from"./chunk-
|
|
1
|
+
import"./chunk-55J6XMHW.js";import{a as x}from"./chunk-HBQNBR6L.js";import{a as m,b as p,c as f}from"./chunk-M3SYVKZK.js";import{a}from"./chunk-FRJ453UJ.js";import"./chunk-L3ZXHX7S.js";import"./chunk-DDOMNXV7.js";import"./chunk-GX6PAJLU.js";import{a as s}from"./chunk-UH3CEF45.js";import{a as d}from"./chunk-MWH2GNPD.js";import{a as h,b as c}from"./chunk-O5CRFISG.js";import{a as e,b as o,c as t}from"./chunk-P3DDHPDA.js";import{a as r}from"./chunk-BY4BKVNV.js";export{r as RegistryError,m as assertStandardSchema,x as bindRegistry,f as createMutableRegistry,p as createRegistry,a as exportTreeSchema,s as formatIssuePath,e as isStandardSchema,c as safeParseNode,o as safeParseStandardSchema,d as safeParseTree,t as standardSchema,h as unregisteredTypeMessage};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"../chunk-
|
|
1
|
+
import{a,b,c,d,e,f}from"../chunk-DDOMNXV7.js";import"../chunk-GX6PAJLU.js";import"../chunk-BY4BKVNV.js";export{d as createJSONSchemaEmbedder,f as definitionRef,c as definitionsKeyword,a as idKeyword,e as pointerToken,b as startsResource};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as S}from"../chunk-
|
|
1
|
+
import{a as S}from"../chunk-L3ZXHX7S.js";import{a as o,b as t,c as d,d as a,f as m}from"../chunk-DDOMNXV7.js";import{a as e,b as r}from"../chunk-GX6PAJLU.js";import"../chunk-BY4BKVNV.js";export{e as assertJSONSchemaTarget,a as createJSONSchemaEmbedder,m as definitionRef,d as definitionsKeyword,o as idKeyword,r as readStandardJSONSchema,S as replaceChildSlot,t as startsResource};
|
package/dist/json-schema/slot.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"../chunk-
|
|
1
|
+
import{a}from"../chunk-L3ZXHX7S.js";import"../chunk-DDOMNXV7.js";import"../chunk-GX6PAJLU.js";import"../chunk-BY4BKVNV.js";export{a as replaceChildSlot};
|
package/dist/parse-tree.d.ts
CHANGED
|
@@ -31,29 +31,34 @@ type ParsedChildren<TAll extends TreeRegistration, TPaths> = TPaths extends read
|
|
|
31
31
|
} : never;
|
|
32
32
|
} : readonly [];
|
|
33
33
|
/**
|
|
34
|
-
* One node of a document that has issues: its registration, its own schema output,
|
|
35
|
-
* parsed.
|
|
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.
|
|
36
36
|
*
|
|
37
37
|
* @remarks
|
|
38
38
|
* `output` is exactly what {@link safeParseNode} returned for the node. No child data is written into it, so a child
|
|
39
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.
|
|
41
|
-
* the
|
|
42
|
-
* `{ keys, nodes }` entry per child path the registration declares, in declaration order,
|
|
43
|
-
* children that parsed in document order, each with its own `path
|
|
44
|
-
* the position in `nodes`, say where it was.
|
|
45
|
-
* `
|
|
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`.
|
|
46
46
|
*/
|
|
47
47
|
export type PartialNode<TAll extends TreeRegistration, TRegistration extends TreeRegistration = TAll> = TRegistration extends unknown ? {
|
|
48
48
|
$type: TRegistration['$type'];
|
|
49
49
|
registration: TRegistration;
|
|
50
50
|
output: StandardSchemaV1.InferOutput<TRegistration['schema']>;
|
|
51
|
+
data: NodeData<TAll, TRegistration> | undefined;
|
|
51
52
|
path: NonNullable<StandardSchemaIssue['path']>;
|
|
52
|
-
children:
|
|
53
|
-
keys: readonly string[];
|
|
54
|
-
nodes: readonly PartialNode<TAll>[];
|
|
55
|
-
}[];
|
|
53
|
+
children: PartialChildren<TAll, TRegistration['childPaths']>;
|
|
56
54
|
} : never;
|
|
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 [];
|
|
57
62
|
/**
|
|
58
63
|
* What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found and the nodes that
|
|
59
64
|
* parsed.
|
|
@@ -104,9 +109,10 @@ type RootOf<TAll extends TreeRegistration, TOptions> = TOptions extends {
|
|
|
104
109
|
* its siblings still are, so one call reports every issue of the document. When there are none, `tree.data` is the
|
|
105
110
|
* parsed document, each node's schema output with the children's data at its child paths, in document order. When
|
|
106
111
|
* there are issues, `tree` is a {@link PartialNode} of the nodes that parsed, present exactly when the root's own
|
|
107
|
-
* schema passed: every node whose own schema passed and whose parent was kept, with `output`
|
|
108
|
-
*
|
|
109
|
-
*
|
|
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.
|
|
110
116
|
*
|
|
111
117
|
* The parent schema owns, at a child path, whether the value may be missing, list or single, and list bounds; it does
|
|
112
118
|
* not own the children, whose data replaces whatever the schema returned there. For each node it parses, `safeParseTree`
|
package/dist/parse-tree.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-MWH2GNPD.js";import"./chunk-O5CRFISG.js";import"./chunk-P3DDHPDA.js";import"./chunk-BY4BKVNV.js";export{a as safeParseTree};
|
package/dist/registry-error.d.ts
CHANGED
|
@@ -26,13 +26,15 @@
|
|
|
26
26
|
* - `'unreachable-child-path'`: {@link exportTreeSchema} found no slot for a child path (`childPath`) in the JSON
|
|
27
27
|
* Schema of a registration, because the schema does not declare its keys, or it sits behind `allOf`, a `$ref` or a
|
|
28
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.
|
|
29
31
|
* - `'unknown-accepted-type'`: {@link exportTreeSchema} was given a lookup that lacks a `$type` a child path
|
|
30
32
|
* (`childPath`) accepts (`key`).
|
|
31
33
|
* - `'definition-name-clash'`: {@link exportTreeSchema}, or the JSON Schema embedder it writes through, found that a
|
|
32
34
|
* definition a schema brought along (`key`, brought by `$type`) takes the name of a `$type` or of another definition.
|
|
33
35
|
* - `'invalid-declaration'`: a domain package refuses a declaration of a registration other than its child paths.
|
|
34
36
|
*/
|
|
35
|
-
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' | 'unknown-accepted-type' | 'definition-name-clash' | 'invalid-declaration';
|
|
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';
|
|
36
38
|
/** Where a {@link RegistryError} happened, and what its code needs to be described without the message. */
|
|
37
39
|
export interface RegistryErrorDetails {
|
|
38
40
|
/**
|
package/dist/registry-error.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-BY4BKVNV.js";export{a as RegistryError};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@schema-engine/registry",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.7.0",
|
|
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",
|
|
@@ -67,7 +67,7 @@ Errors while building or binding, and a tree parse whose schema contradicts its
|
|
|
67
67
|
- `'invalid-declaration'`: a domain package refuses a declaration of a registration other than its child paths.
|
|
68
68
|
- `'duplicate-type'`: a repeated `$type` with `duplicates: 'error'`.
|
|
69
69
|
- `'unknown-binding'`: a binding key no contract answers (`$type` is that key). `'missing-binding'`: a contract with no binding. `'binding-overrides-contract'`: a binding that sets a key (`key`) its contract defines.
|
|
70
|
-
- `'unreachable-child-path'` (`childPath`): `exportTreeSchema` found no slot for a child path in a registration's JSON Schema. `'unknown-accepted-type'` (`childPath`, `key`): a child path accepts a `$type` the lookup lacks. `'definition-name-clash'` (`key`): a definition a schema brought along takes the name of a `$type`.
|
|
70
|
+
- `'unreachable-child-path'` (`childPath`): `exportTreeSchema` found no slot for a child path in a registration's JSON Schema. `'schema-without-json-schema'`: `exportTreeSchema`, with its default `resolve`, met a registration (`$type`) whose schema sets no `~standard.jsonSchema`. `'unknown-accepted-type'` (`childPath`, `key`): a child path accepts a `$type` the lookup lacks. `'definition-name-clash'` (`key`): a definition a schema brought along takes the name of a `$type`.
|
|
71
71
|
- `'schema-changes-type'` and `'schema-breaks-child-path'` (`childPath`): `safeParseTree` parsed a node whose schema returned an output without the node's own `$type`, or that does not keep a child path as the document has it. They are bugs of the registration, never issues of the document.
|
|
72
72
|
|
|
73
73
|
`assertStandardSchema` on its own and errors while parsing (`safeParseStandardSchema` and `safeParseNode` with an asynchronous schema) are plain `Error`s, and `parseYaml` throws `YamlDocumentError`.
|
|
@@ -86,7 +86,7 @@ export function nodeIssues(node: unknown, index: number): string[] {
|
|
|
86
86
|
}
|
|
87
87
|
```
|
|
88
88
|
|
|
89
|
-
`safeParseTree(registry, root, options?)` checks a whole document in one call. A registration says where its children are with `childPaths`, a list of `{ keys, accepts?, list? }`: `keys` is the list of keys from the node to the slot (`['sections']`, or `['engine', 'controls']`), relative and without indexes, and `accepts` is a closed, non-empty list of the `$type`s allowed there (leave it out and the slot puts no limit on the `$type`). The slot holds one node or an array of nodes, or only an array when `list: true`: anything else there is `registry/not-a-list` at the path, an open slot is exported as an array, and `data` types the slot as an array. Keep the slot opaque in the parent's schema (`z.array(z.unknown())`) and declare every child key there: `accepts` is the only way to restrict a slot, and `createRegistry` fails to compile a child path whose key the schema output does not declare. `options.accepts` restricts the root and `options.path` is where it sits in a larger document. Every node goes through `safeParseNode` at its full path and the `accepts` of its position, a node whose schema fails is not walked further but its siblings still are, a value at a child path that is no node (`null`, a primitive) is `registry/not-a-node` at that path (`registry/not-a-list` on a path that sets `list`), and a node that contains itself is `registry/contains-itself`, not an overflow. It returns `{ success: true, tree }` or `{ success: false, issues, tree? }` with every issue and the nodes that parsed. `tree.data` is the parsed document, typed per child path, with defaults and transforms of every level applied; a `tree` node is a `ParsedNode`, `{ $type, registration, data, path, children }`, whose `data` is that node's composed data and whose `children` is a list of `{ keys, nodes }`, one per declared path in declaration order (find one with `children.find(({ keys }) => ...)`, never by index). On failure, `tree` is a `PartialNode` when the root's own schema passed (absent when the root failed): every node whose own schema passed and whose parent was kept, `{ $type, registration, output, path, children }`, with `output` the node's own schema output and
|
|
89
|
+
`safeParseTree(registry, root, options?)` checks a whole document in one call. A registration says where its children are with `childPaths`, a list of `{ keys, accepts?, list? }`: `keys` is the list of keys from the node to the slot (`['sections']`, or `['engine', 'controls']`), relative and without indexes, and `accepts` is a closed, non-empty list of the `$type`s allowed there (leave it out and the slot puts no limit on the `$type`). The slot holds one node or an array of nodes, or only an array when `list: true`: anything else there is `registry/not-a-list` at the path, an open slot is exported as an array, and `data` types the slot as an array. Keep the slot opaque in the parent's schema (`z.array(z.unknown())`) and declare every child key there: `accepts` is the only way to restrict a slot, and `createRegistry` fails to compile a child path whose key the schema output does not declare. `options.accepts` restricts the root and `options.path` is where it sits in a larger document. Every node goes through `safeParseNode` at its full path and the `accepts` of its position, a node whose schema fails is not walked further but its siblings still are, a value at a child path that is no node (`null`, a primitive) is `registry/not-a-node` at that path (`registry/not-a-list` on a path that sets `list`), and a node that contains itself is `registry/contains-itself`, not an overflow. It returns `{ success: true, tree }` or `{ success: false, issues, tree? }` with every issue and the nodes that parsed. `tree.data` is the parsed document, typed per child path, with defaults and transforms of every level applied; a `tree` node is a `ParsedNode`, `{ $type, registration, data, path, children }`, whose `data` is that node's composed data and whose `children` is a list of `{ keys, nodes }`, one per declared path in declaration order (find one with `children.find(({ keys }) => ...)`, never by index). On failure, `tree` is a `PartialNode` when the root's own schema passed (absent when the root failed): every node whose own schema passed and whose parent was kept, `{ $type, registration, output, data, path, children }`, with `output` the node's own schema output and `data` its composed data, `undefined` where something below the node failed (so the failure `tree.data` is not the parsed document, which exists only when there are no issues). A failed node is left out and not walked, as are a rejected `accepts` and a cycle edge; `children` keeps one `{ keys, nodes }` per path with the kept children in document order, each with its own `path`. `children` is typed as on the success tree, so one function over `children` reads both branches. Read children from `children`, never from a slot of `output`, which holds what the document had there. The parent schema must keep `$type` and the slot the way the document has it, or `safeParseTree` throws a `RegistryError`. The root narrows from a literal `accepts`. Two registries in one parse go through one lookup: `{ get: (type) => a.get(type) ?? b.get(type) }`, and the first that answers wins.
|
|
90
90
|
|
|
91
91
|
```ts title="registry/check-tree.ts"
|
|
92
92
|
import * as z from 'zod/mini';
|
|
@@ -121,7 +121,7 @@ export function sectionTitles(document: unknown): string[] {
|
|
|
121
121
|
|
|
122
122
|
`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`.
|
|
123
123
|
|
|
124
|
-
`exportTreeSchema(lookup, options?)` writes the JSON Schema of the whole tree, composed at the JSON Schema level so it does not depend on the validator. `lookup` is a registry (anything with `all()`) or a list of registries, the first winning a `$type` both list. It returns `{ $schema, $defs, anyOf }`: one definition per `$type` under `$defs` (`definitions` for target `'draft-07'`), referred to by `#/$defs/<$type>` with `~` and `/` escaped as `~0` and `~1`, and the root as the union of `options.accepts`, or of every `$type`. Each schema is read by `options.resolve(schema, { io, target })
|
|
124
|
+
`exportTreeSchema(lookup, options?)` writes the JSON Schema of the whole tree, composed at the JSON Schema level so it does not depend on the validator. `lookup` is a registry (anything with `all()`) or a list of registries, the first winning a `$type` both list. It returns `{ $schema, $defs, anyOf }`: one definition per `$type` under `$defs` (`definitions` for target `'draft-07'`), referred to by `#/$defs/<$type>` with `~` and `/` escaped as `~0` and `~1`, and the root as the union of `options.accepts`, or of every `$type`. Each schema is read by `options.resolve(schema, { $type, io, target })` (`$type` is the registration's, for an error a custom `resolve` throws), by default its `~standard.jsonSchema`, and a schema that sets no `~standard.jsonSchema` makes the default throw `RegistryError` `'schema-without-json-schema'` naming its `$type`, while a `resolve` that returns `undefined` for a schema (`resolve: () => undefined` for all) lists it by an open object that holds its `$type` and its child paths, on purpose. Classic `zod` sets `~standard.jsonSchema`; `zod/mini` and Valibot do not, and a classic Zod schema that embeds a `zod/mini` one (every schema of `@schema-engine/layout` is one) throws in that converter (Zod keeps it partial so an app bundles only the flavour it uses), so for Zod pass `resolve: (schema, { io, target }) => (schema instanceof z.core.$ZodType ? z.toJSONSchema(schema, { io, target }) : undefined)`: `z.toJSONSchema` is Zod's complete converter, `instanceof` narrows the Standard Schema `resolve` receives, and `undefined` lists a schema that is not Zod as an open node. Zod writes a union of primitives as a `type` list, which strict Ajv refuses unless it is created with `allowUnionTypes: true`. `options.io` is `'input'` (the authored shape, the default) or `'output'`, and `options.target` the dialect: `'draft-2020-12'` (the default) or `'draft-07'`, and any other target (`'openapi-3.0'`, a misspelling, Zod's older spelling of draft-07) throws an `Error` before a schema is read. `JSONSchemaTarget`, the closed set of the Standard JSON Schema names `'draft-2020-12'`, `'draft-07'`, `'draft-04'` and `'openapi-3.0'`, is exported from the root. Each child path is then replaced, and only its slot, so `required`, `minItems`, `maxItems` and sibling keys stay: an array slot gets `items: U`, an object slot becomes `U`, an open slot (`{}`) becomes `{ anyOf: [U, { type: 'array', items: U }] }`, where `U` is `{ anyOf: [{ $ref }, ...] }` of the path's `accepts`, or of every `$type` without it. A slot behind `allOf`, a `$ref` or a union, inside a schema with an `$id` (`id` for draft-04) of its own, or one a schema does not declare, throws `RegistryError` `'unreachable-child-path'`. Definitions a schema wrote into its own `$defs` are lifted to the top as `<$type>.<name>` and their pointers follow, with each `.` and `_` of the `$type` written as `_2e_` and `_5f_` (so `a.b` with `c` is `a_2e_b.c`, apart from `a` with `b.c`), and its anchors (`$anchor`, `$dynamicAnchor`, a draft-07 `$id: '#name'`, a draft-04 `id: '#name'`) become `<owner part>.<name>` where the owner part is `o` and the `$type` with every character outside `[A-Za-z0-9-]` written as `_<hex>_` (`ui/button` and `x` give `oui_2f_button.x`, `my-card` gives `omy-card.x`); a name already in the document (a `$type` with that name, say) throws `'definition-name-clash'`. `@schema-engine/registry/json-schema` holds the pieces for code that writes JSON Schema itself: `readStandardJSONSchema(schema)` returns a schema's `~standard.jsonSchema` converter or `undefined` (what the default `resolve` reads, so a custom `resolve` can fall back to it and throw when it is `undefined`, as the default does, since returning `undefined` lists the node open), `createJSONSchemaEmbedder(target, placement)` embeds schemas written as documents of their own into one being written, as the forms export does (it takes a `JSONSchemaTarget` and throws for any other string), `assertJSONSchemaTarget(target)` throws unless a string is a `JSONSchemaTarget` and narrows it to one (for the open `target` of a Standard JSON Schema converter's options), `idKeyword(target)` is the keyword a target writes a schema's identifier under (`'id'` for `'draft-04'`, `'$id'` otherwise), `startsResource(schema, target)` is whether a schema sets it to something other than a fragment (`#node`), which makes it a resource that resolves its own references and anchors, `replaceChildSlot(definition, { $type, keys }, union, { target })` replaces, in place, the slot a child path names in a registration's JSON Schema, which is the step `exportTreeSchema` takes per child path (an unreachable slot, or an `$id` (`id` for draft-04) between the definition and the slot, throws `RegistryError` `'unreachable-child-path'`; the `$id` of the definition's own root is the caller's to check; a path with `list: true` writes an open slot as an array instead of a child or a list, and an object slot of it is unreachable), `definitionRef(target, name)` writes the `$ref` to a definition (`#/$defs/<name>` for `'draft-2020-12'`, `#/definitions/<name>` otherwise, the name as a JSON Pointer token percent-encoded only where a URI fragment needs it, so `element:tab` stays as written), and `definitionsKeyword(target)` is the keyword it writes. A schema that is itself a definition or an entry is written in place by the embedder's `embedDefinition(own, name)` (one with an `$id` (`id` for draft-04) of its own is a collection entry that refers to it, so the entry keeps the collection's URI). A registry user needs only `exportTreeSchema`.
|
|
125
125
|
|
|
126
126
|
```ts title="registry/export-tree.ts"
|
|
127
127
|
import * as z from 'zod/mini';
|
package/dist/chunk-IYIWS4LW.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as k}from"./chunk-FMWSZRDV.js";import{b as E,c as b,d as j,f as N}from"./chunk-NSLF54GM.js";import{b as $,c as S,d as u,e as T}from"./chunk-GX6PAJLU.js";import{a as y}from"./chunk-XG4EZ5VP.js";var J={"draft-2020-12":"https://json-schema.org/draft/2020-12/schema","draft-07":"http://json-schema.org/draft-07/schema#"};function v(t,{io:n,target:a}){return $(t)?.[n]({target:a})}function P(t){return!("all"in t)}function C(t){let n={type:"object",properties:{$type:{const:t.$type}},required:["$type"]};for(let{keys:a}of t.childPaths??[]){let i=n;a.forEach((r,f)=>{let o=i.properties,p=f===a.length-1,h=u(o,r),s=S(h)?h:p?{}:{type:"object",properties:{}};T(o,r,s),!p&&!S(u(s,"properties"))&&(s.properties={}),i=s})}return n}function V(t,n){return new y("unreachable-child-path",`The JSON Schema of '${t}' sets an $id of its own, so the export cannot reach the child path '${n.join(".")}': a $ref written there resolves against that $id, not against the document.`,{$type:t,childPath:n})}function z(t,n={}){let{accepts:a,io:i="input",target:r="draft-2020-12",resolve:f=v}=n;if(!Object.hasOwn(J,r))throw new Error(`exportTreeSchema writes 'draft-2020-12' or 'draft-07', not '${r}'.`);let o=new Map;for(let e of P(t)?t:[t])for(let c of e.all())o.has(c.$type)||o.set(c.$type,c);if(o.size===0)throw new Error("exportTreeSchema needs at least one registration.");if(a?.length===0)throw new Error("accepts must list at least one $type.");for(let e of a??[])if(!o.has(e))throw new Error(`accepts names '${e}', which is not registered.`);let p=b(r),h=e=>({$ref:N(r,e)}),s=[...o.keys()],g=e=>({anyOf:e.map(h)}),O=j(r,{kind:"document"}),w=new Map;for(let e of o.values()){let c=f(e.schema,{io:i,target:r}),m=O.embedDefinition(c??C(e),e.$type);for(let{keys:d,accepts:x,list:R}of e.childPaths??[]){if(E(m,r))throw V(e.$type,d);let l=x?.find(L=>!o.has(L));if(l!==void 0)throw new y("unknown-accepted-type",`The child path '${d.join(".")}' of '${e.$type}' accepts '${l}', which the lookup does not list. Pass every registry of the vocabulary.`,{$type:e.$type,childPath:d,key:l});k(m,{$type:e.$type,keys:d,list:R},g(x??s),{target:r})}w.set(e.$type,m)}return O.finish({$schema:J[r],[p]:Object.fromEntries(w),...g(a??s)})}export{z as a};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/export-tree-schema.ts"],
|
|
4
|
-
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { createJSONSchemaEmbedder, definitionRef, definitionsKeyword, startsResource } from './json-schema/embedder.js';\nimport { replaceChildSlot } from './json-schema/slot.js';\nimport {\n\tgetOwn,\n\tisPlainObject,\n\treadStandardJSONSchema,\n\tsetOwn,\n\ttype JSONSchemaObject,\n\ttype JSONSchemaTarget,\n} from './json-schema/standard.js';\nimport { RegistryError } from './registry-error.js';\nimport type { TreeRegistration } from './tree-types.js';\n\n/**\n * What {@link exportTreeSchema} needs of a registry: the registrations it lists.\n *\n * @remarks\n * Both registry kinds ({@link createRegistry}, {@link createMutableRegistry}) provide it. A vocabulary spread over several\n * registries is passed as a list of them.\n */\nexport interface ExportLookup {\n\tall(): readonly TreeRegistration[];\n}\n\n/** The two dialects {@link exportTreeSchema} knows the `$schema` and the definitions keyword of. */\ntype TreeSchemaTarget = Extract<JSONSchemaTarget, 'draft-2020-12' | 'draft-07'>;\n\n/** What a `resolve` function is told about the export it takes part in. */\nexport interface ExportSchemaContext {\n\t/** `'input'` is the authored shape, `'output'` the parsed one. */\n\treadonly io: 'input' | 'output';\n\t/** The target the document is written for. */\n\treadonly target: TreeSchemaTarget;\n}\n\n/** Options of {@link exportTreeSchema}. */\nexport interface ExportTreeSchemaOptions {\n\t/**\n\t * The `$type`s the document's root may have. Absent: every `$type` of the lookup.\n\t *\n\t * @remarks\n\t * Each name must be registered in the lookup, and the list must not be empty.\n\t */\n\treadonly accepts?: readonly string[];\n\t/** Which shape of each schema to write. Default `'input'`, the shape an author writes. */\n\treadonly io?: 'input' | 'output';\n\t/**\n\t * The JSON Schema dialect to write. Default `'draft-2020-12'`.\n\t *\n\t * @remarks\n\t * Any other value throws before a schema is read, since a document without `$schema`, or with the wrong keyword for\n\t * its definitions, would be written silently.\n\t */\n\treadonly target?: TreeSchemaTarget;\n\t/**\n\t * Writes the JSON Schema of one registration's schema, or returns `undefined` for a schema it cannot write.\n\t *\n\t * @remarks\n\t * The default reads `~standard.jsonSchema`, so any schema library that implements Standard JSON Schema exports\n\t * without a function here. Pass one for a library that does not, or to prefer another converter, Zod's own say:\n\t * `(schema, { io, target }) => z.toJSONSchema(schema, { io, target })`. The registry takes no validator dependency.\n\t * A schema that resolves to `undefined` is listed by an open object, as {@link exportTreeSchema} explains. The\n\t * result is not changed.\n\t */\n\treadonly resolve?: (schema: StandardSchemaV1, context: ExportSchemaContext) => JSONSchemaObject | undefined;\n}\n\nconst DIALECTS: Readonly<Record<TreeSchemaTarget, string>> = {\n\t'draft-2020-12': 'https://json-schema.org/draft/2020-12/schema',\n\t'draft-07': 'http://json-schema.org/draft-07/schema#',\n};\n\nfunction defaultResolve(schema: StandardSchemaV1, { io, target }: ExportSchemaContext): JSONSchemaObject | undefined {\n\treturn readStandardJSONSchema(schema)?.[io]({ target });\n}\n\nfunction isLookupList(lookup: ExportLookup | readonly ExportLookup[]): lookup is readonly ExportLookup[] {\n\treturn !('all' in lookup);\n}\n\n/**\n * The object a schema is listed by when it cannot be read: a node of its `$type` with its child paths in place, each\n * slot left open for {@link exportTreeSchema} to fill.\n */\nfunction openNode(registration: TreeRegistration): JSONSchemaObject {\n\tconst root: JSONSchemaObject = {\n\t\ttype: 'object',\n\t\tproperties: { $type: { const: registration.$type } },\n\t\trequired: ['$type'],\n\t};\n\tfor (const { keys } of registration.childPaths ?? []) {\n\t\tlet current = root;\n\t\tkeys.forEach((key, index) => {\n\t\t\tconst properties = current.properties as Record<string, unknown>;\n\t\t\tconst isLast = index === keys.length - 1;\n\t\t\tconst existing = getOwn(properties, key);\n\t\t\tconst next = isPlainObject(existing) ? existing : isLast ? {} : { type: 'object', properties: {} };\n\t\t\tsetOwn(properties, key, next);\n\t\t\tif (!isLast && !isPlainObject(getOwn(next, 'properties'))) next.properties = {};\n\t\t\tcurrent = next;\n\t\t});\n\t}\n\treturn root;\n}\n\n/**\n * The error for a registration whose own JSON Schema is a resource of its own (it sets an `$id`), so the references\n * written into it would resolve against that `$id` and not against the document.\n */\nfunction unreachableSlot($type: string, keys: readonly string[]): RegistryError {\n\treturn new RegistryError(\n\t\t'unreachable-child-path',\n\t\t`The JSON Schema of '${$type}' sets an $id of its own, so the export cannot reach the child path '${keys.join('.')}': a $ref written there resolves against that $id, not against the document.`,\n\t\t{ $type, childPath: keys },\n\t);\n}\n\n/**\n * Write the JSON Schema of a whole tree of registrations, composed at the JSON Schema level.\n *\n * @param lookup - The registrations to export: a registry, or a list of registries that make up one vocabulary. When\n * two list a `$type`, the first wins, as it does for a lookup that tries them in turn\n * @param options - The root's `accepts`, the `io` and `target` of the schemas, and a `resolve` function, see\n * {@link ExportTreeSchemaOptions}\n * @returns One document, `{ $schema, $defs, anyOf }`: a definition per `$type` under `$defs` (`definitions` for a\n * draft-07 target), and the root as the union of the root's accepted `$type`s\n * @throws {RegistryError} Code `'unreachable-child-path'` when a slot cannot be found where a registration's JSON\n * Schema declares it, `'unknown-accepted-type'` when a child path accepts a `$type` the lookup lacks, and\n * `'definition-name-clash'` when a definition a schema brought along takes the name of a `$type` or of another definition\n * @throws {Error} When `target` is not `'draft-2020-12'` or `'draft-07'`, before any schema is read, when the lookup\n * holds no registration, when `accepts` is empty, and when it names a `$type` the lookup lacks\n *\n * @remarks\n * Each registration's schema is written by `options.resolve`, by default the schema's own `~standard.jsonSchema`, so\n * Zod, Valibot, ArkType and a hand-written schema export the same way and the registry depends on none of them. A\n * schema it cannot write (`resolve` returns `undefined`) is listed by an open object that holds its `$type` and its child\n * paths, so the document still shows where children go.\n *\n * Each child path is then replaced in the definition, and only the slot: `required`, `minItems` and `maxItems`, and the\n * sibling keys stay as the registration's schema wrote them. The slot takes the union of the path's `accepts` as\n * `$ref`s to the definitions, or of every `$type` of the lookup without `accepts`:\n *\n * | Slot in the registration's JSON Schema | Becomes |\n * | --- | --- |\n * | an array (`type: 'array'`, `items` or `prefixItems`) | the same array, `items: U`, and `U` at each tuple position |\n * | an object | `U` |\n * | open (`{}`) | `{ anyOf: [U, { type: 'array', items: U }] }`, a child or a list of children |\n *\n * `U` is `{ anyOf: [{ $ref }, ...] }`. A slot the walk cannot reach (behind `allOf`, a `$ref` or a union, or inside\n * a schema with an `$id` of its own) throws, since guessing would write a document that disagrees with the registration.\n *\n * A schema that was written as a document of its own is moved into the document by\n * {@link createJSONSchemaEmbedder}, and every local pointer follows. Its `$defs` are lifted to the top as\n * `<owner>.<name>` (`page.address` for the `address` definition of `page`), and each anchor is renamed\n * `<owner part>.<name>`. Both write the owner so that two owners never write the same name: in a lifted name each `.`\n * and `_` of the `$type` is `_2e_` and `_5f_` (`a.b` with `c` is `a_2e_b.c`, `a` with `b.c` is `a.b.c`), and in an anchor\n * the owner part is `o` and the `$type` with every character outside `[A-Za-z0-9-]` written as `_<hex>_`\n * (`ui/button` with `x` is `oui_2f_button.x`, `my-card` with `x` is `omy-card.x`). The anchors it renames are `$anchor`,\n * `$dynamicAnchor`, a draft-07 `$id: '#name'` and a draft-04 `id: '#name'`. A name that is still taken, by a `$type` say, is an error, since the two\n * definitions could not both stay. A name in a `$ref` is a JSON Pointer token (`~` as `~0`, `/` as `~1`) and\n * percent-encoded for the URI fragment.\n */\nexport function exportTreeSchema(\n\tlookup: ExportLookup | readonly ExportLookup[],\n\toptions: ExportTreeSchemaOptions = {},\n): JSONSchemaObject {\n\tconst { accepts, io = 'input', target = 'draft-2020-12', resolve = defaultResolve } = options;\n\tif (!Object.hasOwn(DIALECTS, target)) {\n\t\tthrow new Error(`exportTreeSchema writes 'draft-2020-12' or 'draft-07', not '${target}'.`);\n\t}\n\tconst registrations = new Map<string, TreeRegistration>();\n\tfor (const source of isLookupList(lookup) ? lookup : [lookup]) {\n\t\tfor (const registration of source.all()) {\n\t\t\tif (!registrations.has(registration.$type)) registrations.set(registration.$type, registration);\n\t\t}\n\t}\n\tif (registrations.size === 0) throw new Error('exportTreeSchema needs at least one registration.');\n\tif (accepts?.length === 0) throw new Error('accepts must list at least one $type.');\n\tfor (const name of accepts ?? []) {\n\t\tif (!registrations.has(name)) throw new Error(`accepts names '${name}', which is not registered.`);\n\t}\n\n\tconst keyword = definitionsKeyword(target);\n\tconst reference = (name: string) => ({ $ref: definitionRef(target, name) });\n\tconst everyType = [...registrations.keys()];\n\tconst unionOf = (names: readonly string[]): JSONSchemaObject => ({ anyOf: names.map(reference) });\n\n\tconst embedder = createJSONSchemaEmbedder(target, { kind: 'document' });\n\tconst definitions = new Map<string, JSONSchemaObject>();\n\tfor (const registration of registrations.values()) {\n\t\tconst resolved = resolve(registration.schema, { io, target });\n\t\tconst definition = embedder.embedDefinition(resolved ?? openNode(registration), registration.$type);\n\t\tfor (const { keys, accepts: slotAccepts, list } of registration.childPaths ?? []) {\n\t\t\tif (startsResource(definition, target)) throw unreachableSlot(registration.$type, keys);\n\t\t\tconst missing = slotAccepts?.find((name) => !registrations.has(name));\n\t\t\tif (missing !== undefined) {\n\t\t\t\tthrow new RegistryError(\n\t\t\t\t\t'unknown-accepted-type',\n\t\t\t\t\t`The child path '${keys.join('.')}' of '${registration.$type}' accepts '${missing}', which the lookup does not list. Pass every registry of the vocabulary.`,\n\t\t\t\t\t{ $type: registration.$type, childPath: keys, key: missing },\n\t\t\t\t);\n\t\t\t}\n\t\t\treplaceChildSlot(definition, { $type: registration.$type, keys, list }, unionOf(slotAccepts ?? everyType), {\n\t\t\t\ttarget,\n\t\t\t});\n\t\t}\n\t\tdefinitions.set(registration.$type, definition);\n\t}\n\n\treturn embedder.finish({\n\t\t$schema: DIALECTS[target],\n\t\t[keyword]: Object.fromEntries(definitions),\n\t\t...unionOf(accepts ?? everyType),\n\t});\n}\n"],
|
|
5
|
-
"mappings": "0MAoEA,IAAMA,EAAuD,CAC5D,gBAAiB,+CACjB,WAAY,yCACb,EAEA,SAASC,EAAeC,EAA0B,CAAE,GAAAC,EAAI,OAAAC,CAAO,EAAsD,CACpH,OAAOC,EAAuBH,CAAM,IAAIC,CAAE,EAAE,CAAE,OAAAC,CAAO,CAAC,CACvD,CAEA,SAASE,EAAaC,EAAmF,CACxG,MAAO,EAAE,QAASA,EACnB,CAMA,SAASC,EAASC,EAAkD,CACnE,IAAMC,EAAyB,CAC9B,KAAM,SACN,WAAY,CAAE,MAAO,CAAE,MAAOD,EAAa,KAAM,CAAE,EACnD,SAAU,CAAC,OAAO,CACnB,EACA,OAAW,CAAE,KAAAE,CAAK,IAAKF,EAAa,YAAc,CAAC,EAAG,CACrD,IAAIG,EAAUF,EACdC,EAAK,QAAQ,CAACE,EAAKC,IAAU,CAC5B,IAAMC,EAAaH,EAAQ,WACrBI,EAASF,IAAUH,EAAK,OAAS,EACjCM,EAAWC,EAAOH,EAAYF,CAAG,EACjCM,EAAOC,EAAcH,CAAQ,EAAIA,EAAWD,EAAS,CAAC,EAAI,CAAE,KAAM,SAAU,WAAY,CAAC,CAAE,EACjGK,EAAON,EAAYF,EAAKM,CAAI,EACxB,CAACH,GAAU,CAACI,EAAcF,EAAOC,EAAM,YAAY,CAAC,IAAGA,EAAK,WAAa,CAAC,GAC9EP,EAAUO,CACX,CAAC,CACF,CACA,OAAOT,CACR,CAMA,SAASY,EAAgBC,EAAeZ,EAAwC,CAC/E,OAAO,IAAIa,EACV,yBACA,uBAAuBD,CAAK,wEAAwEZ,EAAK,KAAK,GAAG,CAAC,+EAClH,CAAE,MAAAY,EAAO,UAAWZ,CAAK,CAC1B,CACD,CA+CO,S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c,CAAC,EAAG,CACjF,GAAIqC,EAAeH,EAAYvC,CAAM,EAAG,MAAMkB,EAAgBb,EAAa,MAAOE,CAAI,EACtF,IAAMoC,EAAUH,GAAa,KAAMb,GAAS,CAACF,EAAc,IAAIE,CAAI,CAAC,EACpE,GAAIgB,IAAY,OACf,MAAM,IAAIvB,EACT,wBACA,mBAAmBb,EAAK,KAAK,GAAG,CAAC,SAASF,EAAa,KAAK,cAAcsC,CAAO,4EACjF,CAAE,MAAOtC,EAAa,MAAO,UAAWE,EAAM,IAAKoC,CAAQ,CAC5D,EAEDC,EAAiBL,EAAY,CAAE,MAAOlC,EAAa,MAAO,KAAAE,EAAM,KAAAkC,CAAK,EAAGR,EAAQO,GAAeR,CAAS,EAAG,CAC1G,OAAAhC,CACD,CAAC,CACF,CACAqC,EAAY,IAAIhC,EAAa,MAAOkC,CAAU,CAC/C,CAEA,OAAOJ,EAAS,OAAO,CACtB,QAASvC,EAASI,CAAM,EACxB,CAAC4B,CAAO,EAAG,OAAO,YAAYS,CAAW,EACzC,GAAGJ,EAAQV,GAAWS,CAAS,CAChC,CAAC,CACF",
|
|
6
|
-
"names": ["DIALECTS", "defaultResolve", "schema", "io", "target", "readStandardJSONSchema", "isLookupList", "lookup", "openNode", "registration", "root", "keys", "current", "key", "index", "properties", "isLast", "existing", "getOwn", "next", "isPlainObject", "setOwn", "unreachableSlot", "$type", "RegistryError", "exportTreeSchema", "options", "accepts", "resolve", "registrations", "source", "name", "keyword", "definitionsKeyword", "reference", "definitionRef", "everyType", "unionOf", "names", "embedder", "createJSONSchemaEmbedder", "definitions", "resolved", "definition", "slotAccepts", "list", "startsResource", "missing", "replaceChildSlot"]
|
|
7
|
-
}
|
package/dist/chunk-QHVQ4S4D.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{b as E}from"./chunk-O5CRFISG.js";import{a as j}from"./chunk-XG4EZ5VP.js";function B(t,o){let a=s=>({$type:s.$type,registration:s.registration,output:o.get(s)??s.data,path:s.path,children:[]}),n=a(t),e=[[t,n]];for(let s=e.pop();s;s=e.pop()){let[l,h]=s;for(let{keys:r,nodes:m}of l.children){let f=[];h.children.push({keys:r,nodes:f});for(let y of m){let i=a(y);f.push(i),e.push([y,i])}}}return n}function b(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function D(t){if(!b(t))return!1;let o=Object.getPrototypeOf(t);return o===Object.prototype||o===null}function M(t,o,a){let n=t;for(let e of o){if(!a(n)||!Object.hasOwn(n,e))return;n=n[e]}return n}function V(t,o,a){Object.defineProperty(t,o,{value:a,enumerable:!0,writable:!0,configurable:!0})}function F(t,o){let a={...t},n=new Set([a]);for(let{keys:e,value:s}of o){let l=a;for(let h of e.slice(0,-1)){let r=l[h];n.has(r)||(r={...r},n.add(r),V(l,h,r)),l=r}V(l,e[e.length-1],s)}return a}function J(t,o,a){let n=t,e=[],s=new Map,l=n.kind===void 0?"":`${n.kind} `,h=n.kind===void 0?{}:{kind:n.kind};function r(i,T){return new j("schema-breaks-child-path",`${l}'${i}' schema output does not keep the child path '${T.join(".")}' as the document has it.`,{...h,$type:i,childPath:T})}function m(i,T,S,K){if(S.includes(i)){e.push({code:"registry/contains-itself",message:"A node cannot contain itself.",path:T});return}let A=E(n,i,{path:T,accepts:K});if(!A.success){e.push(...A.issues);return}let{$type:u,registration:I}=A,p=A.data;if(!D(p)||!Object.hasOwn(p,"$type")||p.$type!==u)throw new j("schema-changes-type",`${l}'${u}' schema output must keep its $type '${u}'.`,{...h,$type:u});let q=i,v=[...S,i],W=[],N=[],k=!0;for(let{keys:d,accepts:L,list:z}of I.childPaths??[]){let w=[];W.push({keys:d,nodes:w});let c=M(q,d,b),P=M(p,d,D),O=[...T,...d];if(c===void 0){if(P!==void 0&&!(Array.isArray(P)&&P.length===0))throw r(u,d)}else if(z===!0&&!Array.isArray(c))e.push({code:"registry/not-a-list",message:"Expected a list of nodes.",path:O}),k=!1;else if(Array.isArray(c)){if(!Array.isArray(P)||P.length!==c.length)throw r(u,d);let g=0;for(let R=0;R<c.length;R+=1){let $=m(c[R],[...O,R],v,L);$&&(w.push($),$.data!==void 0&&(g+=1))}g===c.length?N.push({keys:d,value:w.map(R=>R.data)}):k=!1}else if(b(c)){if(!b(P))throw r(u,d);let g=m(c,O,v,L);g?(w.push(g),g.data!==void 0?N.push({keys:d,value:g.data}):k=!1):k=!1}else e.push({code:"registry/not-a-node",message:"Expected a node or a list of nodes.",path:O}),k=!1}let x;k&&(x=N.length===0?p:F(p,N));let C={$type:u,registration:I,data:x,path:T,children:W};return x!==p&&s.set(C,p),C}let f=m(o,a?.path??[],[],a?.accepts),y;return f?.data!==void 0&&e.length===0?y={success:!0,tree:f}:f?y={success:!1,issues:e,tree:B(f,s)}:y={success:!1,issues:e},y}export{J as a};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/parse-tree.ts"],
|
|
4
|
-
"sourcesContent": ["import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { safeParseNode, type NodeLookup, type ParseOptions, type RegistryIssue } from './parse-node.js';\nimport { RegistryError } from './registry-error.js';\nimport type { Accepted, AcceptedOf, CheckLookup, NodeData, TreeRegistration } from './tree-types.js';\nimport type { StandardSchemaIssue } from './standard-schema.js';\nimport type { ChildPath } from './types.js';\n\n/**\n * One node of a validated document: its registration, its data, 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. `data` is the node's composed data: the schema output with each child\n * path replaced by the data of the children found there, so it is the same object the parent's data holds at that\n * position, and `tree.data` is the whole parsed document. `children` has one entry per child path the registration\n * declares, in declaration order, each `{ keys, nodes }` with `nodes` empty when the node holds none there, in document\n * order. Find an entry by its `keys`, compared key by key and never by index or by a joined string (`['a.b']` and\n * `['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\n * path accepts, or by the whole union without `accepts`.\n */\nexport type ParsedNode<\n\tTAll extends TreeRegistration,\n\tTRegistration extends TreeRegistration = TAll,\n> = TRegistration extends unknown\n\t? {\n\t\t\t$type: TRegistration['$type'];\n\t\t\tregistration: TRegistration;\n\t\t\tdata: NodeData<TAll, TRegistration>;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: ParsedChildren<TAll, TRegistration['childPaths']>;\n\t\t}\n\t: never;\n\n/** The `children` of a node: a tuple over the declared child paths, each `nodes` typed by its `accepts`. */\ntype ParsedChildren<TAll extends TreeRegistration, TPaths> = TPaths extends readonly ChildPath[]\n\t? {\n\t\t\treadonly [I in keyof TPaths]: TPaths[I] extends ChildPath\n\t\t\t\t? { keys: TPaths[I]['keys']; nodes: readonly ParsedNode<TAll, Accepted<TAll, TPaths[I]>>[] }\n\t\t\t\t: never;\n\t\t}\n\t: readonly [];\n\n/**\n * One node of a document that has issues: its registration, its own schema output, where it sits and the children that\n * parsed.\n *\n * @remarks\n * `output` is exactly what {@link safeParseNode} returned for the node. No child data is written into it, so a child\n * slot holds whatever the parent's schema returned there (the authored items, for an opaque slot), including children\n * that failed or were pruned. Read the children from `children`, never from a slot of `output`. There is no `data`:\n * the composed document exists only when there are no issues, as `data` of a {@link ParsedNode}. `children` has one\n * `{ keys, nodes }` entry per child path the registration declares, in declaration order, with `nodes` holding the\n * children that parsed in document order, each with its own `path`. A child that failed is missing, so the issues, not\n * the position in `nodes`, say where it was. A child is any `PartialNode<TAll>`, narrowed by its `$type`, not by\n * `accepts`.\n */\nexport type PartialNode<\n\tTAll extends TreeRegistration,\n\tTRegistration extends TreeRegistration = TAll,\n> = TRegistration extends unknown\n\t? {\n\t\t\t$type: TRegistration['$type'];\n\t\t\tregistration: TRegistration;\n\t\t\toutput: StandardSchemaV1.InferOutput<TRegistration['schema']>;\n\t\t\tpath: NonNullable<StandardSchemaIssue['path']>;\n\t\t\tchildren: readonly { keys: readonly string[]; nodes: readonly PartialNode<TAll>[] }[];\n\t\t}\n\t: never;\n\n/**\n * What {@link safeParseTree} returns: the tree of a document with no issue, or every issue found and the nodes that\n * parsed.\n *\n * @remarks\n * `tree` on the failure branch is present exactly when the root's own schema passed, and is absent when the root\n * failed, was not accepted or has no registration.\n */\nexport type SafeParseTreeResult<TAll extends TreeRegistration, TRoot extends TreeRegistration = TAll> =\n\t| { success: true; tree: ParsedNode<TAll, TRoot> }\n\t| { success: false; issues: RegistryIssue[]; tree?: PartialNode<TAll, TRoot> };\n\n/**\n * The registrations a root may be: those `accepts` names, but only when the options type has `accepts`, not when it\n * only may.\n */\ntype RootOf<TAll extends TreeRegistration, TOptions> = TOptions extends {\n\treadonly accepts: readonly (infer TName)[];\n}\n\t? AcceptedOf<TAll, TName>\n\t: TAll;\n\n/**\n * A node the walk kept, in the shape of a {@link ParsedNode}, which the success path returns as it is.\n *\n * @remarks\n * `data` is the composed data, and is `undefined` exactly when something below the node failed, was pruned or was no\n * node: a complete node's data is always an object, so `data !== undefined` is the completeness test and the node\n * carries no flag. The schema output of a node whose `data` is not that same object is kept apart, in the walk's\n * `outputs`, so a node costs no field the caller would see.\n */\ninterface WalkedNode {\n\t$type: string;\n\tregistration: TreeRegistration;\n\tdata: unknown;\n\tpath: NonNullable<StandardSchemaIssue['path']>;\n\tchildren: { keys: readonly string[]; nodes: WalkedNode[] }[];\n}\n\ninterface PartialRuntimeNode {\n\t$type: string;\n\tregistration: TreeRegistration;\n\toutput: unknown;\n\tpath: NonNullable<StandardSchemaIssue['path']>;\n\tchildren: { keys: readonly string[]; nodes: PartialRuntimeNode[] }[];\n}\n\n/**\n * The {@link PartialNode} shape of a walked tree, built without recursion so that a document as deep as the walk can\n * handle converts too.\n *\n * @remarks\n * A node's `output` is its entry in `outputs`, or its `data` when it has none: a node with no child to write has the\n * schema output itself as `data`.\n */\nfunction toPartial(root: WalkedNode, outputs: ReadonlyMap<WalkedNode, unknown>): PartialRuntimeNode {\n\tconst partialOf = (node: WalkedNode): PartialRuntimeNode => ({\n\t\t$type: node.$type,\n\t\tregistration: node.registration,\n\t\toutput: outputs.get(node) ?? node.data,\n\t\tpath: node.path,\n\t\tchildren: [],\n\t});\n\tconst top = partialOf(root);\n\tconst pending: [WalkedNode, PartialRuntimeNode][] = [[root, top]];\n\tfor (let next = pending.pop(); next; next = pending.pop()) {\n\t\tconst [source, target] = next;\n\t\tfor (const { keys, nodes } of source.children) {\n\t\t\tconst kept: PartialRuntimeNode[] = [];\n\t\t\ttarget.children.push({ keys, nodes: kept });\n\t\t\tfor (const child of nodes) {\n\t\t\t\tconst converted = partialOf(child);\n\t\t\t\tkept.push(converted);\n\t\t\t\tpending.push([child, converted]);\n\t\t\t}\n\t\t}\n\t}\n\treturn top;\n}\n\ntype PlainObject = Record<PropertyKey, unknown>;\n\nfunction isRecord(value: unknown): value is PlainObject {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n\tif (!isRecord(value)) return false;\n\tconst prototype: unknown = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/**\n * The value an object holds at keys, through own entries only, or `undefined` when an intermediate is absent or not an\n * object that `isObject` accepts.\n *\n * @remarks\n * Only own keys count: a key a plain object inherits, such as `constructor`, is no child.\n */\nfunction valueAt(\n\troot: PlainObject,\n\tkeys: readonly string[],\n\tisObject: (value: unknown) => value is PlainObject,\n): unknown {\n\tlet current: unknown = root;\n\tfor (const key of keys) {\n\t\tif (!isObject(current) || !Object.hasOwn(current, key)) return undefined;\n\t\tcurrent = current[key];\n\t}\n\treturn current;\n}\n\n/**\n * Set 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 setOwn(target: PlainObject, key: string, value: unknown): void {\n\tObject.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });\n}\n\n/**\n * A copy of a node's schema output with each child slot replaced, without touching the output.\n *\n * @remarks\n * The output shares references with the authored document (a loose object returns the authored array), so it is\n * never written to. The root and each object on a path are shallow-copied once, and two paths with a shared prefix\n * share that copy.\n */\nfunction withChildData(\n\toutput: PlainObject,\n\twrites: readonly { keys: readonly string[]; value: unknown }[],\n): PlainObject {\n\tconst root: PlainObject = { ...output };\n\tconst copies = new Set<object>([root]);\n\tfor (const { keys, value } of writes) {\n\t\tlet current = root;\n\t\tfor (const key of keys.slice(0, -1)) {\n\t\t\tlet next = current[key] as PlainObject;\n\t\t\tif (!copies.has(next)) {\n\t\t\t\tnext = { ...next };\n\t\t\t\tcopies.add(next);\n\t\t\t\tsetOwn(current, key, next);\n\t\t\t}\n\t\t\tcurrent = next;\n\t\t}\n\t\tsetOwn(current, keys[keys.length - 1]!, value);\n\t}\n\treturn root;\n}\n\n/**\n * Check a whole document, node by node, without throwing for a bad document.\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 options - Where the root sits in a larger document (`path`, which starts every issue's `path`) and which\n * `$type`s the root may have (`accepts`), see {@link ParseOptions}\n *\n * @remarks\n * Each node goes through {@link safeParseNode} with its full path, and `accepts` of the position it sits in (the\n * option for the root, the child path's own below), so the issues are those of one node, at the position the document\n * has them. A registration says where its children are with `childPaths`, each path read from the node as authored:\n *\n * | Value at the child path | Result |\n * | --- | --- |\n * | key absent, or an intermediate absent or not an object | no children; `data` keeps the schema output there |\n * | `undefined` | no children, as absent |\n * | `null` or another primitive | issue `registry/not-a-node` at the path |\n * | an object | one child |\n * | an array | each item is a child, at `[...path, index]`; an item that is not an object is an issue |\n * | an empty array | no children; `data` holds `[]` |\n * | anything but an array or a missing value, on a path that sets `list` | issue `registry/not-a-list` at the path |\n *\n * A node that contains itself is `registry/contains-itself`. A node whose own schema fails is not walked further, but\n * its siblings still are, so one call reports every issue of the document. When there are none, `tree.data` is the\n * parsed document, each node's schema output with the children's data at its child paths, in document order. When\n * there are issues, `tree` is a {@link PartialNode} of the nodes that parsed, present exactly when the root's own\n * schema passed: every node whose own schema passed and whose parent was kept, with `output` and `children`, and\n * without `data`. A failed node, a child the slot does not accept and the edge of a cycle are left out. Each child is\n * parsed once, from the authored value, and the authored document and the schema outputs are never written to.\n *\n * The parent schema owns, at a child path, whether the value may be missing, list or single, and list bounds; it does\n * not own the children, whose data replaces whatever the schema returned there. For each node it parses, `safeParseTree`\n * holds the schema to that contract and throws a {@link RegistryError} when it breaks it, since that is a bug of the\n * registration and no issue of the document: `'schema-changes-type'` when the output is not a plain object whose own\n * `$type` equals the node's, and `'schema-breaks-child-path'` when, where the document fills a child path, the output\n * lacks the keys down to it as plain objects or the same cardinality (an array of the same length for an array, an\n * object for an object), or when, where the document leaves a path empty, the output holds anything but nothing,\n * `undefined` or `[]`: a default that holds nodes. A transform of the parent at a filled slot (a reorder, say) is\n * discarded, not detected, so slots stay opaque to the parent's schema.\n *\n * The result is typed from the registrations: with a literal `accepts` the root narrows, and `tree.data` types each\n * child path by what it accepts. The walk itself reads registrations through one widened view of the lookup, and\n * the function returns the tree through one cast to that type: every node in it was built from a registration of the\n * lookup by its own `$type`, which TypeScript cannot follow at runtime.\n *\n * @throws {RegistryError} Code `'schema-changes-type'` or `'schema-breaks-child-path'`, as above\n * @throws {Error} When a registration's schema validates asynchronously, as {@link safeParseNode} does, and when\n * `accepts` is an empty list\n */\nexport function safeParseTree<\n\tTAll extends TreeRegistration,\n\tconst TOptions extends ParseOptions<TAll['$type']> = ParseOptions<TAll['$type']>,\n>(\n\tregistry: NodeLookup<TAll> & CheckLookup<TAll>,\n\troot: unknown,\n\toptions?: TOptions,\n): SafeParseTreeResult<TAll, RootOf<TAll, TOptions>> {\n\tconst lookup: NodeLookup<TreeRegistration> = registry;\n\tconst issues: RegistryIssue[] = [];\n\tconst outputs = new Map<WalkedNode, unknown>();\n\tconst label = lookup.kind === undefined ? '' : `${lookup.kind} `;\n\n\tconst kind = lookup.kind === undefined ? {} : { kind: lookup.kind };\n\n\tfunction brokenSlot(type: string, keys: readonly string[]): RegistryError {\n\t\treturn new RegistryError(\n\t\t\t'schema-breaks-child-path',\n\t\t\t`${label}'${type}' schema output does not keep the child path '${keys.join('.')}' as the document has it.`,\n\t\t\t{ ...kind, $type: type, childPath: keys },\n\t\t);\n\t}\n\n\tfunction walk(\n\t\tnode: unknown,\n\t\tnodePath: NonNullable<StandardSchemaIssue['path']>,\n\t\tancestors: readonly unknown[],\n\t\taccepts: readonly string[] | undefined,\n\t): WalkedNode | undefined {\n\t\tif (ancestors.includes(node)) {\n\t\t\tissues.push({ code: 'registry/contains-itself', message: 'A node cannot contain itself.', path: nodePath });\n\t\t\treturn undefined;\n\t\t}\n\t\tconst parsed = safeParseNode(lookup, node, { path: nodePath, accepts });\n\t\tif (!parsed.success) {\n\t\t\tissues.push(...parsed.issues);\n\t\t\treturn undefined;\n\t\t}\n\t\tconst { $type: type, registration } = parsed;\n\t\tconst output: unknown = parsed.data;\n\t\tif (!isPlainObject(output) || !Object.hasOwn(output, '$type') || output.$type !== type) {\n\t\t\tthrow new RegistryError(\n\t\t\t\t'schema-changes-type',\n\t\t\t\t`${label}'${type}' schema output must keep its $type '${type}'.`,\n\t\t\t\t{ ...kind, $type: type },\n\t\t\t);\n\t\t}\n\n\t\tconst authored = node as PlainObject;\n\t\tconst trail = [...ancestors, node];\n\t\tconst groups: WalkedNode['children'] = [];\n\t\tconst writes: { keys: readonly string[]; value: unknown }[] = [];\n\t\tlet complete = true;\n\t\tfor (const { keys, accepts: childAccepts, list } of registration.childPaths ?? []) {\n\t\t\tconst nodes: WalkedNode[] = [];\n\t\t\tgroups.push({ keys, nodes });\n\t\t\tconst slot = valueAt(authored, keys, isRecord);\n\t\t\tconst held = valueAt(output, keys, isPlainObject);\n\t\t\tconst childPath = [...nodePath, ...keys];\n\t\t\tif (slot === undefined) {\n\t\t\t\tif (held !== undefined && !(Array.isArray(held) && held.length === 0)) {\n\t\t\t\t\tthrow brokenSlot(type, keys);\n\t\t\t\t}\n\t\t\t} else if (list === true && !Array.isArray(slot)) {\n\t\t\t\tissues.push({ code: 'registry/not-a-list', message: 'Expected a list of nodes.', path: childPath });\n\t\t\t\tcomplete = false;\n\t\t\t} else if (Array.isArray(slot)) {\n\t\t\t\tif (!Array.isArray(held) || held.length !== slot.length) throw brokenSlot(type, keys);\n\t\t\t\tlet kept = 0;\n\t\t\t\tfor (let index = 0; index < slot.length; index += 1) {\n\t\t\t\t\tconst child = walk(slot[index], [...childPath, index], trail, childAccepts);\n\t\t\t\t\tif (child) {\n\t\t\t\t\t\tnodes.push(child);\n\t\t\t\t\t\tif (child.data !== undefined) kept += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (kept === slot.length) {\n\t\t\t\t\twrites.push({ keys, value: nodes.map((item) => item.data) });\n\t\t\t\t} else {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t}\n\t\t\t} else if (isRecord(slot)) {\n\t\t\t\tif (!isRecord(held)) throw brokenSlot(type, keys);\n\t\t\t\tconst child = walk(slot, childPath, trail, childAccepts);\n\t\t\t\tif (child) {\n\t\t\t\t\tnodes.push(child);\n\t\t\t\t\tif (child.data !== undefined) writes.push({ keys, value: child.data });\n\t\t\t\t\telse complete = false;\n\t\t\t\t} else {\n\t\t\t\t\tcomplete = false;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'registry/not-a-node',\n\t\t\t\t\tmessage: 'Expected a node or a list of nodes.',\n\t\t\t\t\tpath: childPath,\n\t\t\t\t});\n\t\t\t\tcomplete = false;\n\t\t\t}\n\t\t}\n\t\tlet data: unknown;\n\t\tif (complete) data = writes.length === 0 ? output : withChildData(output, writes);\n\t\tconst kept: WalkedNode = { $type: type, registration, data, path: nodePath, children: groups };\n\t\tif (data !== output) outputs.set(kept, output);\n\t\treturn kept;\n\t}\n\n\tconst walked = walk(root, options?.path ?? [], [], options?.accepts);\n\tlet result: unknown;\n\tif (walked?.data !== undefined && issues.length === 0) result = { success: true, tree: walked };\n\telse if (walked) result = { success: false, issues, tree: toPartial(walked, outputs) };\n\telse result = { success: false, issues };\n\treturn result as SafeParseTreeResult<TAll, RootOf<TAll, TOptions>>;\n}\n"],
|
|
5
|
-
"mappings": "gFA4HA,SAASA,EAAUC,EAAkBC,EAA+D,CACnG,IAAMC,EAAaC,IAA0C,CAC5D,MAAOA,EAAK,MACZ,aAAcA,EAAK,aACnB,OAAQF,EAAQ,IAAIE,CAAI,GAAKA,EAAK,KAClC,KAAMA,EAAK,KACX,SAAU,CAAC,CACZ,GACMC,EAAMF,EAAUF,CAAI,EACpBK,EAA8C,CAAC,CAACL,EAAMI,CAAG,CAAC,EAChE,QAASE,EAAOD,EAAQ,IAAI,EAAGC,EAAMA,EAAOD,EAAQ,IAAI,EAAG,CAC1D,GAAM,CAACE,EAAQC,CAAM,EAAIF,EACzB,OAAW,CAAE,KAAAG,EAAM,MAAAC,CAAM,IAAKH,EAAO,SAAU,CAC9C,IAAMI,EAA6B,CAAC,EACpCH,EAAO,SAAS,KAAK,CAAE,KAAAC,EAAM,MAAOE,CAAK,CAAC,EAC1C,QAAWC,KAASF,EAAO,CAC1B,IAAMG,EAAYX,EAAUU,CAAK,EACjCD,EAAK,KAAKE,CAAS,EACnBR,EAAQ,KAAK,CAACO,EAAOC,CAAS,CAAC,CAChC,CACD,CACD,CACA,OAAOT,CACR,CAIA,SAASU,EAASC,EAAsC,CACvD,OAAO,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,CAC3E,CAEA,SAASC,EAAcD,EAAsC,CAC5D,GAAI,CAACD,EAASC,CAAK,EAAG,MAAO,GAC7B,IAAME,EAAqB,OAAO,eAAeF,CAAK,EACtD,OAAOE,IAAc,OAAO,WAAaA,IAAc,IACxD,CASA,SAASC,EACRlB,EACAS,EACAU,EACU,CACV,IAAIC,EAAmBpB,EACvB,QAAWqB,KAAOZ,EAAM,CACvB,GAAI,CAACU,EAASC,CAAO,GAAK,CAAC,OAAO,OAAOA,EAASC,CAAG,EAAG,OACxDD,EAAUA,EAAQC,CA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,EACJ,OAAID,GAAQ,OAAS,QAAazB,EAAO,SAAW,EAAG0B,EAAS,CAAE,QAAS,GAAM,KAAMD,CAAO,EACrFA,EAAQC,EAAS,CAAE,QAAS,GAAO,OAAA1B,EAAQ,KAAMhC,EAAUyD,EAAQvD,CAAO,CAAE,EAChFwD,EAAS,CAAE,QAAS,GAAO,OAAA1B,CAAO,EAChC0B,CACR",
|
|
6
|
-
"names": ["toPartial", "root", "outputs", "partialOf", "node", "top", "pending", "next", "source", "target", "keys", "nodes", "kept", "child", "converted", "isRecord", "value", "isPlainObject", "prototype", "valueAt", "isObject", "current", "key", "setOwn", "withChildData", "output", "writes", "copies", "safeParseTree", "registry", "options", "lookup", "issues", "label", "kind", "brokenSlot", "type", "RegistryError", "walk", "nodePath", "ancestors", "accepts", "parsed", "safeParseNode", "registration", "authored", "trail", "groups", "complete", "childAccepts", "list", "slot", "held", "childPath", "index", "item", "data", "walked", "result"]
|
|
7
|
-
}
|
package/dist/chunk-XG4EZ5VP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var r=class extends Error{code;kind;$type;key;childPath;outerChildPath;constructor(i,n,e){super(n),this.name="RegistryError",this.code=i,e.kind!==void 0&&(this.kind=e.kind),this.$type=e.$type,e.key!==void 0&&(this.key=e.key),e.childPath!==void 0&&(this.childPath=e.childPath),e.outerChildPath!==void 0&&(this.outerChildPath=e.outerChildPath)}};export{r as a};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/registry-error.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Why building or binding a registry, or parsing a tree, failed. Each code names one mistake in the registrations or\n * bindings.\n *\n * @remarks\n * The codes are the contract: depend on a code, not on the wording of `message`, which may change. A code is only\n * added, never renamed or reused for another mistake.\n *\n * - `'invalid-schema'`: a registration's `schema` has no `~standard.validate` function.\n * - `'invalid-child-paths'`: a registration's `childPaths` is not a list, or holds an entry that is not an object\n * `{ keys, accepts?, list? }` with a non-empty list of non-empty string `keys`, no other property, an `accepts` that\n * is absent or a non-empty list of non-empty strings without repeats, and a `list` that is absent or `true`.\n * `replaceChildSlot` throws it too for a path with no keys. A domain package throws it too for a `childPaths` its own\n * rules refuse.\n * - `'duplicate-child-path'`: a registration declares the same child path (`childPath`) twice, key by key.\n * - `'nested-child-path'`: a child path (`childPath`) runs through another child path (`outerChildPath`) of the same\n * registration.\n * - `'duplicate-type'`: a `$type` is registered twice while `duplicates` is `'error'`.\n * - `'unknown-binding'`: {@link bindRegistry} got a binding whose key (`$type`) is no contract's `$type`.\n * - `'missing-binding'`: {@link bindRegistry} got no binding for a contract.\n * - `'binding-overrides-contract'`: a binding sets a key (`key`) its contract already defines.\n * - `'schema-changes-type'`: {@link safeParseTree} parsed a node whose schema returned an output with another `$type`\n * than the node's, or none.\n * - `'schema-breaks-child-path'`: {@link safeParseTree} parsed a node whose schema returned an output that does not\n * keep a child path (`childPath`) the document fills, or fills one the document leaves empty.\n * - `'unreachable-child-path'`: {@link exportTreeSchema} found no slot for a child path (`childPath`) in the JSON\n * Schema of a registration, because the schema does not declare its keys, or it sits behind `allOf`, a `$ref` or a\n * union, or inside a schema with an `$id` of its own, or because the slot is nullable.\n * - `'unknown-accepted-type'`: {@link exportTreeSchema} was given a lookup that lacks a `$type` a child path\n * (`childPath`) accepts (`key`).\n * - `'definition-name-clash'`: {@link exportTreeSchema}, or the JSON Schema embedder it writes through, found that a\n * definition a schema brought along (`key`, brought by `$type`) takes the name of a `$type` or of another definition.\n * - `'invalid-declaration'`: a domain package refuses a declaration of a registration other than its child paths.\n */\nexport type RegistryErrorCode =\n\t| 'invalid-schema'\n\t| 'invalid-child-paths'\n\t| 'duplicate-child-path'\n\t| 'nested-child-path'\n\t| 'duplicate-type'\n\t| 'unknown-binding'\n\t| 'missing-binding'\n\t| 'binding-overrides-contract'\n\t| 'schema-changes-type'\n\t| 'schema-breaks-child-path'\n\t| 'unreachable-child-path'\n\t| 'unknown-accepted-type'\n\t| 'definition-name-clash'\n\t| 'invalid-declaration';\n\n/** Where a {@link RegistryError} happened, and what its code needs to be described without the message. */\nexport interface RegistryErrorDetails {\n\t/**\n\t * The registry's label, for example `Widget`.\n\t *\n\t * @remarks\n\t * Absent when a parse failed through a lookup that is not a registry, a function say, which has no label.\n\t */\n\treadonly kind?: string;\n\t/** The `$type` of the registration at fault, or the key of a binding that names no registration. */\n\treadonly $type: string;\n\t/**\n\t * The key a binding sets that its contract defines, for `'binding-overrides-contract'`, the `$type` a child path\n\t * accepts that the lookup lacks, for `'unknown-accepted-type'`, and the name of the definition that clashes, for\n\t * `'definition-name-clash'`.\n\t */\n\treadonly key?: string;\n\t/**\n\t * The keys of the child path at fault, for `'duplicate-child-path'`, `'nested-child-path'` and\n\t * `'schema-breaks-child-path'`, `'unreachable-child-path'` and `'unknown-accepted-type'`.\n\t */\n\treadonly childPath?: readonly string[];\n\t/** The keys of the child path that `childPath` runs through, for `'nested-child-path'`. */\n\treadonly outerChildPath?: readonly string[];\n}\n\n/**\n * Thrown while a registry is built ({@link createRegistry}) or bound ({@link bindRegistry}) from registrations that\n * break a rule, and while a tree is parsed ({@link safeParseTree}) when a schema contradicts its registration.\n *\n * @remarks\n * Branch on `code`, not on `message`: the message is written for a person and may be reworded, while the codes of\n * {@link RegistryErrorCode} stay. `code` with the details is enough to write the message again, in another language\n * say, without parsing it. A parse throws a `RegistryError` only when a schema contradicts its registration, which is\n * a bug of the registration and no issue of the document. Other errors raised while parsing a node or a document (an\n * asynchronous Standard Schema, say), and by {@link assertStandardSchema} on its own, are not `RegistryError`s.\n */\nexport class RegistryError extends Error implements RegistryErrorDetails {\n\treadonly code: RegistryErrorCode;\n\treadonly kind?: string;\n\treadonly $type: string;\n\treadonly key?: string;\n\treadonly childPath?: readonly string[];\n\treadonly outerChildPath?: readonly string[];\n\n\tconstructor(code: RegistryErrorCode, message: string, details: RegistryErrorDetails) {\n\t\tsuper(message);\n\t\tthis.name = 'RegistryError';\n\t\tthis.code = code;\n\t\tif (details.kind !== undefined) this.kind = details.kind;\n\t\tthis.$type = details.$type;\n\t\tif (details.key !== undefined) this.key = details.key;\n\t\tif (details.childPath !== undefined) this.childPath = details.childPath;\n\t\tif (details.outerChildPath !== undefined) this.outerChildPath = details.outerChildPath;\n\t}\n}\n"],
|
|
5
|
-
"mappings": "AAuFO,IAAMA,EAAN,cAA4B,KAAsC,CAC/D,KACA,KACA,MACA,IACA,UACA,eAET,YAAYC,EAAyBC,EAAiBC,EAA+B,CACpF,MAAMD,CAAO,EACb,KAAK,KAAO,gBACZ,KAAK,KAAOD,EACRE,EAAQ,OAAS,SAAW,KAAK,KAAOA,EAAQ,MACpD,KAAK,MAAQA,EAAQ,MACjBA,EAAQ,MAAQ,SAAW,KAAK,IAAMA,EAAQ,KAC9CA,EAAQ,YAAc,SAAW,KAAK,UAAYA,EAAQ,WAC1DA,EAAQ,iBAAmB,SAAW,KAAK,eAAiBA,EAAQ,eACzE,CACD",
|
|
6
|
-
"names": ["RegistryError", "code", "message", "details"]
|
|
7
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|