@orkestrel/scaffold 0.0.123 → 0.0.125
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agents/skills/orkestrel-publish/scripts/steps.js +523 -0
- package/dist/agents/skills/orkestrel-publish/scripts/wave.js +70 -11
- package/dist/bin/main.js +18 -18
- package/dist/bin/main.js.map +1 -1
- package/dist/host/agents/orchestration.md +5 -1
- package/dist/host/agents/platforms/windows.md +9 -1
- package/dist/host/agents/skills/orkestrel-dispatch/SKILL.md +1 -1
- package/dist/host/agents/skills/orkestrel-falsify/references/brief.md +1 -0
- package/dist/host/agents/skills/orkestrel-harden/references/methods.md +30 -2
- package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +1 -0
- package/dist/host/agents/skills/orkestrel-parallel/references/t3.md +5 -1
- package/dist/host/agents/skills/orkestrel-publish/SKILL.md +1 -0
- package/dist/host/agents/skills/orkestrel-publish/references/release.md +2 -2
- package/dist/host/agents/skills/orkestrel-publish/references/wave.md +23 -6
- package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +654 -0
- package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +79 -14
- package/dist/host/claude/agents/orkestrel.md +45 -45
- package/dist/host/claude/rules/patterns.md +1 -1
- package/dist/host/claude/rules/portability.md +2 -0
- package/dist/host/claude/rules/quality.md +3 -1
- package/dist/host/claude/rules/tests.md +3 -1
- package/dist/host/guides/agent.md +349 -244
- package/dist/host/guides/brief.md +52 -48
- package/dist/host/guides/browser.md +2 -2
- package/dist/host/guides/contract.md +226 -104
- package/dist/host/guides/database.md +12 -12
- package/dist/host/guides/interpret.md +531 -155
- package/dist/host/guides/mcp.md +183 -61
- package/dist/host/guides/ndjson.md +47 -34
- package/dist/host/guides/ollama.md +123 -66
- package/dist/host/guides/program.md +117 -39
- package/dist/host/guides/qualifier.md +110 -59
- package/dist/host/guides/rater.md +85 -32
- package/dist/host/guides/reason.md +377 -114
- package/dist/host/guides/scaffold.md +20 -12
- package/dist/host/guides/study.md +580 -483
- package/dist/host/guides/tool.md +163 -58
- package/dist/host/guides/toolbox.md +159 -80
- package/dist/host/guides/workflow.md +44 -25
- package/dist/host/manifest.json +41 -35
- package/dist/src/core/index.cjs +17 -17
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.js +17 -17
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +23 -11
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +10 -6
- package/dist/src/server/index.d.ts +10 -6
- package/dist/src/server/index.js +23 -11
- package/dist/src/server/index.js.map +1 -1
- package/package.json +17 -17
|
@@ -9,6 +9,62 @@ Validation is where untrusted data — an HTTP body, a parsed JSON blob, a tool
|
|
|
9
9
|
|
|
10
10
|
## Surface
|
|
11
11
|
|
|
12
|
+
### Lossless admission and fault text
|
|
13
|
+
|
|
14
|
+
These exports compose an already compiled contract and format its faults.
|
|
15
|
+
|
|
16
|
+
| Name | Kind | Signature | Summary |
|
|
17
|
+
| ----------------------- | --------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
|
|
18
|
+
| `ContractAdmission` | interface | `{ value, repairs }` | Carries an admitted value and the lossless repairs made while parsing it. |
|
|
19
|
+
| `ContractRefusal` | interface | `{ faults, cause? }` | Carries bounded admission faults and the cause of an unreadable value when present. |
|
|
20
|
+
| `FaultTextOptions` | interface | `{ limit? }` | Reserves a caller's text budget for a bounded fault report. |
|
|
21
|
+
| `AuditFaultShape` | type | `ReturnType<FaultShaper['build']>` | Describes the closed shape built for audit faults, including paired discriminator hints. |
|
|
22
|
+
| `admitValue` | function | `<T>(contract: ContractInterface<T>, value: unknown) => Result<ContractAdmission<T>, ContractRefusal>` | Admits a stable readable value with only lossless repairs and returns the parser's value. |
|
|
23
|
+
| `describeFaults` | function | `(faults: readonly AuditFault[], schema?: JSONSchema, options?: FaultTextOptions) => string` | Describes bounded faults with encoded values and a schema-derived correction summary. |
|
|
24
|
+
| `matchesUndefinedField` | function | `(fault: AuditFault, value: unknown, parsed: unknown) => boolean` | Checks whether a type fault describes an own undefined field omitted or defaulted by a successful parse. |
|
|
25
|
+
| `truncateFaultText` | function | `(text: string, limit: number) => string` | Truncates text to a UTF-16 budget without splitting a surrogate pair. |
|
|
26
|
+
| `auditFaultShape` | function | `() => AuditFaultShape` | Returns the shared closed audit-fault shape, building it on the first call. |
|
|
27
|
+
| `extractPath` | function | `(fault: AuditFault) => readonly string[]` | Extracts a fault's path as its segments, reading a string path as one segment. |
|
|
28
|
+
| `extractForms` | function | `(schema: JSONSchema \| undefined) => readonly JSONSchema[]` | Extracts a schema's forms: the schema itself, then its union arms, so a read looks through a nullable the same way everywhere. |
|
|
29
|
+
| `extractSchema` | function | `(schema: JSONSchema, path: readonly string[]) => JSONSchema \| undefined` | Extracts the part of a schema a path reaches, through properties, array items, record values, and the arms of a union. |
|
|
30
|
+
| `renderPath` | function | `(path: readonly string[]) => string` | Renders a path as text, encoding what a caller could have sent and eliding the middle of a long one. |
|
|
31
|
+
| `renderList` | function | `(entries: readonly string[]) => string` | Renders a list as text, naming at most `FAULT_LIST_LIMIT` of its entries and counting the rest. |
|
|
32
|
+
| `renderForm` | function | `(schema: JSONSchema, room?: number) => string` | Renders a schema as a short summary of what to send, such as `{"city": string, "note"?: string}`. |
|
|
33
|
+
| `describeFaultLine` | function | `(fault: AuditFault, schema: JSONSchema) => string` | Describes one fault as the line a caller corrects from, naming what to send where the schema says. |
|
|
34
|
+
| `FAULT_TEXT_LIMIT` | const | `2048` | Caps a fault message at 2048 UTF-16 code units. |
|
|
35
|
+
| `FAULT_LIST_LIMIT` | const | `12` | Caps the keys or literal candidates named in a fault line. |
|
|
36
|
+
| `FAULT_SCHEMA_LIMIT` | const | `160` | Caps a schema summary's UTF-16 code units. |
|
|
37
|
+
|
|
38
|
+
The admission helper requires stable reads across its guard, reports, and parser. It parses once,
|
|
39
|
+
refuses lossy repairs and capped audits, and returns the parser's ownership unchanged. An own
|
|
40
|
+
undefined optional field can be omitted or filled by its declared default; neither counts as a repair.
|
|
41
|
+
A guard-valid
|
|
42
|
+
union can retain input identity. A successful undefined result is distinct from a refusal through
|
|
43
|
+
the result discriminant; the root shape builders do not expose that undefined-only domain.
|
|
44
|
+
|
|
45
|
+
Snapshot a foreign object before admission, as Tool.execute does. A getter changing between
|
|
46
|
+
is and parse can publish a value that no recorded repair describes. A shallow snapshot stabilizes
|
|
47
|
+
only its own level; nested foreign values must also provide stable reads.
|
|
48
|
+
|
|
49
|
+
On a host with a polluted Object.prototype, a builder may read an inherited option; that host is outside the honest-intrinsics guarantee.
|
|
50
|
+
|
|
51
|
+
The fault shape builds lazily and is reused. Its inferred values are assignable to the audit-fault
|
|
52
|
+
type, with discriminator hints coupled more narrowly than that type's independent optional fields.
|
|
53
|
+
Fault guards refuse non-finite limits, counts, and numeric discriminator hints.
|
|
54
|
+
|
|
55
|
+
Fault text is bounded in UTF-16 code units, with room for omitted-fault and cap notices and a final
|
|
56
|
+
send summary when a schema is supplied. Pass a smaller limit to reserve a heading's budget.
|
|
57
|
+
Across union arms, a fault line names literal candidates only when the declarations at that path
|
|
58
|
+
agree, and lists declared keys only when the declaring arms have the same keys. Lists are deduplicated;
|
|
59
|
+
the final send summary still shows the arms. The root subject reads `value`. A `received` preview
|
|
60
|
+
of at most `PREVIEW_LIMIT` characters without controls or line separators stays as written;
|
|
61
|
+
other received text and foreign type words pass through `preview`. Received, constraint, and limit
|
|
62
|
+
details use own fields.
|
|
63
|
+
Schema conversion refusal messages append a rendered path bounded by `FAULT_SCHEMA_LIMIT`, while
|
|
64
|
+
their structured context retains the complete path.
|
|
65
|
+
The generated-law regression covers stable values; it does not prove accessor read discipline,
|
|
66
|
+
reentrancy, refusal identity or paths, or capture limits.
|
|
67
|
+
|
|
12
68
|
A guard is the `Guard<T>` type from [`types.ts`](../src/core/types.ts):
|
|
13
69
|
|
|
14
70
|
```ts
|
|
@@ -39,6 +95,9 @@ The `*Field` parsers read a (possibly nested) record field through a `FieldPath`
|
|
|
39
95
|
| `isNonNegativeNumber` | function | `(value: unknown) => value is number` | Determines whether a value is a finite primitive number at or above positive zero. |
|
|
40
96
|
| `isNonNegativeInteger` | function | `(value: unknown) => value is number` | Determines whether a value is a non-negative finite primitive integer. |
|
|
41
97
|
| `isBoolean` | function | `(value: unknown) => value is boolean` | Determines whether a value is a boolean. |
|
|
98
|
+
| `isFaultPath` | function | `(value: unknown) => value is FieldPath` | Determines whether a value is the `FieldPath` a fault carries: a key, or a dense list of keys. |
|
|
99
|
+
| `isFault` | function | `(value: unknown) => value is Fault` | Determines whether a value is exactly one `Fault`. |
|
|
100
|
+
| `isAuditFault` | function | `(value: unknown) => value is AuditFault` | Determines whether a value is exactly one `AuditFault`. |
|
|
42
101
|
| `isLiteralValue` | function | `(value: unknown) => value is LiteralValue` | Determines whether a value belongs to the string, number, or boolean literal domain. |
|
|
43
102
|
| `isTrue` | function | `(value: unknown) => value is true` | Determines whether a value is exactly `true`. |
|
|
44
103
|
| `isFalse` | function | `(value: unknown) => value is false` | Determines whether a value is exactly `false`. |
|
|
@@ -193,21 +252,22 @@ the constant's own literal:
|
|
|
193
252
|
|
|
194
253
|
The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, while `parseJSONAs` walks only the guard shape supplied by its caller. `isJSONValue` and `parseJSONValue` are shipped explicit deep whole-tree gates; `isBoundedJSONValue` adds the fixed resource boundary, and `isBoundedJSONRecord` adds the record-root invariant. `JSONRecord` and `cloneJSONRecord` provide the record-root ownership contract required by metadata and persistence consumers, while `cloneJSONValue` owns any JSON root. A dedicated `JSONArray` alias, broad deep `isJSONObject` / `isJSONSchema` validators, and the ~50-field `JSONSchemaDefinition` remain deliberately omitted. Compose narrower shapes from the combinators and read a parsed blob field-by-field with the `parse*Field` readers when whole-tree work is unnecessary.
|
|
195
254
|
|
|
196
|
-
| Name
|
|
197
|
-
|
|
|
198
|
-
| `isJSONPrimitive`
|
|
199
|
-
| `isJSONValue`
|
|
200
|
-
| `isBoundedJSONValue`
|
|
201
|
-
| `isBoundedJSONRecord`
|
|
202
|
-
| `parseJSON`
|
|
203
|
-
| `parseJSONAs`
|
|
204
|
-
| `JSON_SCHEMA_TYPES`
|
|
205
|
-
| `
|
|
206
|
-
| `
|
|
207
|
-
| `
|
|
208
|
-
| `
|
|
209
|
-
| `
|
|
210
|
-
| `
|
|
255
|
+
| Name | Kind | Signature | Summary |
|
|
256
|
+
| ------------------------ | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
257
|
+
| `isJSONPrimitive` | function | `(value: unknown) => value is JSONPrimitive` | Determines whether a value is a primitive JSON value. |
|
|
258
|
+
| `isJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is a cycle-safe JSON value. |
|
|
259
|
+
| `isBoundedJSONValue` | function | `(value: unknown) => value is JSONValue` | Determines whether a value is JSON-valid within the fixed container-depth limit. |
|
|
260
|
+
| `isBoundedJSONRecord` | function | `(value: unknown) => value is JSONRecord` | Determines whether a value is a depth-bounded JSON record. |
|
|
261
|
+
| `parseJSON` | function | `(value: string) => unknown` | Parses a JSON string, returning `undefined` instead of throwing. |
|
|
262
|
+
| `parseJSONAs` | function | `<T>(value: string, guard: Guard<T>) => T \| undefined` | Parses a JSON string and validates the result against a guard. |
|
|
263
|
+
| `JSON_SCHEMA_TYPES` | const | `readonly JSONSchemaType[]` | Lists the seven standard JSON Schema `type` names, frozen. |
|
|
264
|
+
| `STRICT_SCHEMA_KEYWORDS` | const | `readonly string[]` | Lists the JSON Schema keywords a strict `schemaToShape` conversion reads, frozen. |
|
|
265
|
+
| `JSONPrimitive` | type | `string \| number \| boolean \| null` | Represents a primitive JSON value — the flat leaf of any JSON document. |
|
|
266
|
+
| `JSONRecord` | type | `{ readonly [key: string]: JSONValue; }` | Represents a readonly string-keyed JSON object record. |
|
|
267
|
+
| `JSONValue` | type | `JSONPrimitive \| readonly JSONValue[] \| JSONRecord` | Represents a recursive JSON value — primitives, arrays, and object records. |
|
|
268
|
+
| `JSONSchemaType` | type | `'null' \| 'boolean' \| 'object' \| 'array' \| 'number' \| 'integer' \| 'string'` | Lists the seven standard JSON Schema `type` names. |
|
|
269
|
+
| `JSONSchema` | interface | `{ type?, description?, default?, enum?, minLength?, maxLength?, pattern?, format?, minimum?, maximum?, minItems?, maxItems?, items?, properties?, required?, additionalProperties?, anyOf?, oneOf? }` | Represents a JSON Schema fragment — the supported keyword vocabulary the contract compiler emits and `RawShape` validates before embedding. |
|
|
270
|
+
| `SchemaFormat` | type | `'date-time' \| 'date' \| 'time' \| 'uuid' \| 'email' \| 'uri'` | Lists the closed set of string formats `stringToFormat` recognizes. |
|
|
211
271
|
|
|
212
272
|
### Helper
|
|
213
273
|
|
|
@@ -236,9 +296,10 @@ The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, wh
|
|
|
236
296
|
| `holds` | function | `(callback: () => boolean) => boolean` | Invokes a predicate through the sanctioned never-throw boundary. |
|
|
237
297
|
| `enumerableKeys` | function | `(value: object) => readonly string[] \| undefined` | Snapshots an object's own enumerable string keys through a total boundary. |
|
|
238
298
|
| `readOptions` | function | `<T extends object>(source: T \| undefined, keys: ReadonlyArray<keyof T & string>, builder: string, shape: string) => T \| undefined` | Validates and snapshots a shape-builder options record through every reflective operation the builder relies on. |
|
|
299
|
+
| `refuseOptionKeys` | function | `(source: object \| undefined, keys: readonly string[], builder: string, shape: string) => void` | Refuses an options record that holds a key its builder does not read. |
|
|
239
300
|
| `drawRandom` | function | `(random: RandomFunction, shape: string) => number` | Draws and validates one generator random sample. |
|
|
240
301
|
| `enumerableSymbolCount` | function | `(value: object) => number` | Counts the enumerable own-symbol keys on a value. |
|
|
241
|
-
| `matchesJSONValue` | function | `(entry: unknown, ancestors: WeakSet<object
|
|
302
|
+
| `matchesJSONValue` | function | `(entry: unknown, ancestors: WeakSet<object>, budget?: { left: number; }) => entry is JSONValue` | Matches an unknown value against the recursive JSON value structure. |
|
|
242
303
|
| `matchesRecordBrand` | function | `(value: unknown) => boolean` | Determines whether a value carries the plain-record brand, raising a hostile prototype observation instead of answering it. |
|
|
243
304
|
| `matchesJSONDepth` | function | `(value: unknown) => boolean` | Determines whether a readable value stays within the fixed JSON container-depth limit. |
|
|
244
305
|
| `resolveField` | function | `(record: Readonly<Record<string, unknown>>, path: FieldPath) => unknown` | Resolves a (possibly nested) field value from a record by a key or key path. |
|
|
@@ -256,6 +317,8 @@ The safe JSON surface keeps text parsing lazy: `parseJSON` returns `unknown`, wh
|
|
|
256
317
|
| `readSetEntries` | function | `(value: ReadonlySet<unknown>) => Result<readonly unknown[]>` | Snapshots the genuine contents of a caller's `Set` without running an iterator. |
|
|
257
318
|
| `readMapEntries` | function | `(value: ReadonlyMap<unknown, unknown>) => Result<ReadonlyArray<readonly unknown[]>>` | Snapshots the genuine entries of a caller's `Map` without running an iterator. |
|
|
258
319
|
| `matchesPattern` | function | `(pattern: RegExp, value: string) => boolean` | Determines whether a string is in the language of a pattern this package owns. |
|
|
320
|
+
| `matchesStringLength` | function | `(value: string, min: number \| undefined, max: number \| undefined) => boolean` | Checks whether a string's length in code points falls within optional bounds. |
|
|
321
|
+
| `computeSurrogatePairs` | function | `(value: string, limit: number) => number` | Counts the surrogate pairs in a string, stopping at a limit. |
|
|
259
322
|
| `escapeRegExp` | function | `(value: string) => string` | Escapes every regular-expression metacharacter in a text, so the text matches literally inside a larger `RegExp` source. |
|
|
260
323
|
| `readPatternSource` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's source text through the captured accessor. |
|
|
261
324
|
| `readPatternFlags` | function | `(pattern: unknown) => string \| undefined` | Reads a regular expression's flag text through the captured accessor. |
|
|
@@ -314,10 +377,12 @@ What IS guaranteed, with honest intrinsics and hostile DATA:
|
|
|
314
377
|
- **Published snapshots are frozen and faithful.** A builder freezes what it returns and copies what you hand it; `cloneShape` / `cloneSchema` / `cloneJSONValue` publish deeply frozen graphs that retain no caller reference, and a snapshot that cannot be faithful refuses instead of normalizing.
|
|
315
378
|
- **`is`, `parse`, `audit` and `explain` agree.** No input is certified clean by one door and refused by another: the laws in Domains hold for readable, stably-read values, and where a door must perform a read that can fail, every door that answers about the same value performs it.
|
|
316
379
|
- **Hostile data is refused with a coded `ContractError`.** Cycles, excessive depth, exotic objects, foreign realms, revoked proxies, throwing accessors and unstable reads reach a coded refusal or a documented non-match, never a raw host error and never an unbounded walk.
|
|
317
|
-
- **A shared reference costs one visit, a published bound, or nothing at all.** `COMPILE_DEPTH_LIMIT`, `GUARD_DEPTH_LIMIT`, `FAULT_LIMIT`, `INFER_DEPTH_LIMIT`, `INFER_BREADTH_LIMIT`, `CLONE_NODE_LIMIT` and `COMPILE_NODE_LIMIT` are the published bounds, and where a bound is the wrong instrument the walk carries an identity memo instead. Sharing arrives on BOTH sides and both are answered: `COMPILE_NODE_LIMIT` caps what a shared-child DECLARATION expands into (see Compilers), and `is`, `audit` and `explain` answer a shared-reference VALUE in one visit per (compiled node, object) pair however many paths reach that object. Both halves are needed: without the value-side memo an ordinary graph with several references per level — a few hundred bytes, no attacker, shared references are normal data — costs node reads exponential in its depth. A faulted node is re-walked at its new path, because a fault carries one, and stays bounded by `FAULT_LIMIT`. `cloneJSONValue` and `parse` deliberately still expand and each says so here: `cloneJSONValue` duplicates an alias by contract and caps that at `CLONE_NODE_LIMIT`, and `parse` materializes a tree — see the line below. The claim is about those doors, not about a guard a caller composes: nesting `arrayOf` twenty levels deep builds a walker of your own, and it pays per path.
|
|
380
|
+
- **A shared reference costs one visit, a published bound, or nothing at all.** Declaration capture has a per-door-call budget of `CLONE_NODE_LIMIT` (262,144): each retained edge and each copied default node spends one unit, including edges in a container shared by several owners. Ownership and validation-only walks enforce this before retention and refuse with `clone`; a shape-valued `is` reports the refusal as `false`. `COMPILE_DEPTH_LIMIT`, `GUARD_DEPTH_LIMIT`, `FAULT_LIMIT`, `INFER_DEPTH_LIMIT`, `INFER_BREADTH_LIMIT`, `CLONE_NODE_LIMIT` and `COMPILE_NODE_LIMIT` are the published bounds, and where a bound is the wrong instrument the walk carries an identity memo instead. Sharing arrives on BOTH sides and both are answered: `COMPILE_NODE_LIMIT` caps what a shared-child DECLARATION expands into (see Compilers), and `is`, `audit` and `explain` answer a shared-reference VALUE in one visit per (compiled node, object) pair however many paths reach that object. Both halves are needed: without the value-side memo an ordinary graph with several references per level — a few hundred bytes, no attacker, shared references are normal data — costs node reads exponential in its depth. A faulted node is re-walked at its new path, because a fault carries one, and stays bounded by `FAULT_LIMIT`. `cloneJSONValue` and `parse` deliberately still expand and each says so here: `cloneJSONValue` duplicates an alias by contract and caps that at `CLONE_NODE_LIMIT`, and `parse` materializes a tree — see the line below. The claim is about those doors, not about a guard a caller composes: nesting `arrayOf` twenty levels deep builds a walker of your own, and it pays per path.
|
|
318
381
|
|
|
319
382
|
What is NOT guaranteed, beyond the realm assumption above: a value whose observable reads CHANGE between two calls can leave any two-call law unsatisfied (see Domains), `Date` and `undefined` fall outside the round-trip law, and `schemaToShape`'s memo is ancestor-context-sensitive across graphs (see its row). Two more follow from the memo above and are named rather than left to be discovered. `parse` returns a TREE, so it pays for the tree its input expands into: eighteen shared arrays parse into 262,143 of them in about 370 ms, where `is`, `audit` and `explain` answer the same value in under a millisecond and `cloneJSONValue` refuses that exact graph at `CLONE_NODE_LIMIT`. That cost is the RESULT rather than the walk, which is why it carries no cap — a cap here would refuse a value the caller asked to be handed — so measure an untrusted graph's expansion before parsing it. And within ONE call, `is`, `audit` and `explain` read a given object once per compiled node rather than once per path, so a value whose reads change BETWEEN two reads of the same node can answer differently than it did when every path re-read it. Both are consequences of trading repeated reads for bounded work, and the trade is stated so it can be checked rather than discovered. A third limit belongs to the guards you compose YOURSELF: the memo above lives in a compiled artifact, so a chain you build by hand out of combinators — `arrayOf(arrayOf(...))` and its siblings — has no shared ledger between its independently constructed links and re-reads a shared object once per PATH. Measured: a depth-18 hand-composed chain over an 18-level shared graph answers in about 250 ms, growing fourfold every two levels, where the same value through `createContract` answers in under a millisecond. Compile the declaration when the value may share references; the compiled route is the one this bound covers.
|
|
320
383
|
|
|
384
|
+
`cloneShape` and `validateShape` agree on acceptance. Their refusal diagnoses agree only below the capture limit: ownership may spend that allowance before depth diagnosis, so an excessive declaration can report `clone` through ownership and `depth` through validation.
|
|
385
|
+
|
|
321
386
|
### Types
|
|
322
387
|
|
|
323
388
|
| Name | Kind | Signature | Summary |
|
|
@@ -449,30 +514,55 @@ schemaCloner.clone() === schema // true — terminal success replays exactly
|
|
|
449
514
|
|
|
450
515
|
Declarative constructors for the `ContractShape` union (`src/core/shapers.ts`). The `deriveLengthBounds` and `deriveRangeBounds` rows sit in this section because schema inversion consumes them, and they live in `src/core/helpers.ts`: they build no shape, they reduce a keyword pair to a numeric bound. One shape compiles into a JSON Schema, a guard, a parser, a strict audit, a parse report, and a generator (see the compilers, below). Builders omit absent options from the produced shape object: an option left `undefined` is not present as a key, so `Object.keys`, `in` checks, and spreads see only the options actually provided.
|
|
451
516
|
|
|
452
|
-
**The snapshot-ownership model.** A builder freezes the node it returns and copies every collection you hand it — a `values` list, a `properties` map, a variant list, a `rawShape` fragment — while a `pattern` is captured and re-exposed as a fresh frozen `RegExp` per read, so editing your originals afterwards cannot reach the shape. `objectShape` enumerates a caller-owned property declaration once and carries that key/value snapshot. `cloneShape`, which must also validate a hand-authored graph, first requires every node to be a plain, null-prototype, or foreign-realm record before it reads the discriminant, then captures each declared field through own descriptors plus two agreeing reads before it builds the shell. Missing fields are carried as absent without a read; inherited fields and ordinary accessors are refused without invocation. The documented `pattern` accessor is the one exception, and its two frozen genuine-RegExp results must independently expose agreeing primitive-string `source` and `flags` pairs; no caller scalar object or conversion hook is retained. Structural children, literal values, variants, property maps, and raw-schema roots are then wired only from those captured references, never by rereading the source node. Property maps retain their separate stability mechanism: `cloneShape` compares exactly two caller enumerations and refuses second-population disagreement, while the first enumeration obtains every property child's own data descriptor and requires its value plus two reads to agree by identity. The complete declaration gate validates the carried cloned root; it does not repair or replace a captured population. Consequently, `createContract` reads a property entry exactly as often as `cloneShape` does — twice, and the two readings must agree — because it reaches the declaration the same way: there is no discarded pre-ownership walk, so there is no second caller population to disagree with the captured one. That single captured clone controls every artifact, an invalid captured population is refused by the gate that runs over the clone, and no third caller value read occurs. `ownShape` retains the already-performed `cloneShape` result for frozen and unfrozen inputs alike, so no caller-owned root or reference-bearing child is returned by identity. Thus a malformed value container, raw-schema child, discriminant, scalar, or structural slot cannot become plausible merely because copying would normalize it. A hand-authored `{ category: 'string', pattern }` node receives the same accessor-owned pattern snapshot as builder output and must likewise use an unflagged genuine local- or foreign-realm `RegExp`; inline constructs express the supported flag-like behavior. `createContract` takes its own `cloneShape` snapshot of the whole graph, so its `schema` / `is` / `parse` / `audit` / `explain` / `generate` are fixed at construction and cannot drift with a later edit to the shape you passed. The practical rule: build shapes with the builders, and treat a shape you assemble by hand as caller-owned until a compiler or `ownShape` has copied it.
|
|
453
|
-
|
|
454
|
-
| Name | Kind | Signature | Summary
|
|
455
|
-
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
456
|
-
| `stringShape` | function | `(options?: StringShapeOptions) => StringShape` | Builds a string `StringShape`.
|
|
457
|
-
| `numberShape` | function | `(options?: NumberShapeOptions) => NumberShape` | Builds a numeric `NumberShape`.
|
|
458
|
-
| `integerShape` | function | `(options?: Omit<NumberShapeOptions, 'integer'>) => NumberShape` | Builds an integer `NumberShape` — forces `integer: true`.
|
|
459
|
-
| `booleanShape` | function | `(options?: BooleanShapeOptions) => BooleanShape` | Builds a `BooleanShape`.
|
|
460
|
-
| `nullShape` | function | `(options?: NullShapeOptions) => NullShape` | Builds a `NullShape`.
|
|
461
|
-
| `literalShape` | function | `<const T extends readonly LiteralValue[]>(values: T, options?: LiteralShapeOptions) => LiteralShape<Readonly<T>>` | Builds a literal shape from a fixed set of primitive values.
|
|
462
|
-
| `arrayShape` | function | `<S extends ContractShape>(items: S, options?: ArrayShapeOptions) => ArrayShape<S>` | Builds an `ArrayShape` from an element shape.
|
|
463
|
-
| `objectShape` | function | `<P extends Readonly<Record<string, ContractShape>>, const A extends boolean \| ContractShape = false>(properties: P, options?: ObjectShapeOptions<A>) => ObjectShape<P, A>` | Builds an `ObjectShape` from a property map.
|
|
464
|
-
| `recordShape` | function | `<S extends ContractShape>(values: S, options?: RecordShapeOptions) => ObjectShape<Record<never, never>, S>` | Builds an open `ObjectShape` with no fixed properties — a dictionary.
|
|
465
|
-
| `unionShape` | function | `<V extends readonly ContractShape[]>(...variants: V) => UnionShape<Readonly<V>>` | Builds a `UnionShape` from a list of variant shapes (`anyOf` in JSON Schema).
|
|
466
|
-
| `oneOfShape` | function | `<V extends readonly ContractShape[]>(...variants: V) => UnionShape<Readonly<V>>` | Builds a `UnionShape` that emits `oneOf` (exactly one match) in JSON Schema.
|
|
467
|
-
| `optionalShape` | function | `<S extends ContractShape>(inner: S) => OptionalShape<S>`
|
|
468
|
-
| `nullableShape` | function | `<S extends ContractShape>(inner: S) => NullableShape<S>` | Wraps a shape so it may be `null`.
|
|
469
|
-
| `jsonShape` | function | `(options?: JSONShapeOptions) => JSONShape` | Builds a `JSONShape`.
|
|
470
|
-
| `rawShape` | function | `(schema: JSONSchema) => RawShape` | Builds a `RawShape` from a supported JSON Schema fragment.
|
|
471
|
-
| `schemaToShape` | function | `(schema: JSONSchema) => ContractShape`
|
|
472
|
-
| `deriveLengthBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of non-negative-integer JSON Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`).
|
|
473
|
-
| `deriveRangeBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of finite-number JSON Schema range keywords (`minimum`/`maximum`).
|
|
474
|
-
|
|
475
|
-
|
|
517
|
+
**The snapshot-ownership model.** A builder freezes the node it returns and copies every collection you hand it — a `values` list, a `properties` map, a variant list, a `rawShape` fragment — while a `pattern` is captured and re-exposed as a fresh frozen `RegExp` per read, so editing your originals afterwards cannot reach the shape. `objectShape` enumerates a caller-owned property declaration once and carries that key/value snapshot. `cloneShape`, which must also validate a hand-authored graph, first requires every node to be a plain, null-prototype, or foreign-realm record before it reads the discriminant, then captures each declared field through own descriptors plus two agreeing reads before it builds the shell. Missing fields are carried as absent without a read; inherited fields and ordinary accessors are refused without invocation. The documented `pattern` accessor is the one exception, and its two frozen genuine-RegExp results must independently expose agreeing primitive-string `source` and `flags` pairs; no caller scalar object or conversion hook is retained. Structural children, literal values, variants, property maps, and raw-schema roots are then wired only from those captured references, never by rereading the source node. Property maps retain their separate stability mechanism: `cloneShape` compares exactly two caller enumerations and refuses second-population disagreement, while the first enumeration obtains every property child's own data descriptor and requires its value plus two reads to agree by identity. The complete declaration gate validates the carried cloned root; it does not repair or replace a captured population. Consequently, `createContract` reads a property entry exactly as often as `cloneShape` does — twice, and the two readings must agree — because it reaches the declaration the same way: there is no discarded pre-ownership walk, so there is no second caller population to disagree with the captured one. That single captured clone controls every artifact, an invalid captured population is refused by the gate that runs over the clone, and no third caller value read occurs. `ownShape` retains the already-performed `cloneShape` result for frozen and unfrozen inputs alike, so no caller-owned root or reference-bearing child is returned by identity. Thus a malformed value container, raw-schema child, discriminant, scalar, or structural slot cannot become plausible merely because copying would normalize it. A hand-authored `{ category: 'string', pattern }` node receives the same accessor-owned pattern snapshot as builder output and must likewise use an unflagged genuine local- or foreign-realm `RegExp`; inline constructs express the supported flag-like behavior. `createContract` takes its own `cloneShape` snapshot of the whole graph, unless the builders made all of it, when it is frozen all the way down and no snapshot could add anything, so its `schema` / `is` / `parse` / `audit` / `explain` / `generate` are fixed by the declaration at construction and cannot drift with a later edit to the shape you passed. The practical rule: build shapes with the builders, and treat a shape you assemble by hand as caller-owned until a compiler or `ownShape` has copied it.
|
|
518
|
+
|
|
519
|
+
| Name | Kind | Signature | Summary |
|
|
520
|
+
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
521
|
+
| `stringShape` | function | `(options?: StringShapeOptions) => StringShape` | Builds a string `StringShape`. |
|
|
522
|
+
| `numberShape` | function | `(options?: NumberShapeOptions) => NumberShape` | Builds a numeric `NumberShape`. |
|
|
523
|
+
| `integerShape` | function | `(options?: Omit<NumberShapeOptions, 'integer'>) => NumberShape` | Builds an integer `NumberShape` — forces `integer: true`. |
|
|
524
|
+
| `booleanShape` | function | `(options?: BooleanShapeOptions) => BooleanShape` | Builds a `BooleanShape`. |
|
|
525
|
+
| `nullShape` | function | `(options?: NullShapeOptions) => NullShape` | Builds a `NullShape`. |
|
|
526
|
+
| `literalShape` | function | `<const T extends readonly LiteralValue[]>(values: T, options?: LiteralShapeOptions) => LiteralShape<Readonly<T>>` | Builds a literal shape from a fixed set of primitive values. |
|
|
527
|
+
| `arrayShape` | function | `<S extends ContractShape>(items: S, options?: ArrayShapeOptions) => ArrayShape<S>` | Builds an `ArrayShape` from an element shape. |
|
|
528
|
+
| `objectShape` | function | `<P extends Readonly<Record<string, ContractShape>>, const A extends boolean \| ContractShape = false>(properties: P, options?: ObjectShapeOptions<A>) => ObjectShape<P, A>` | Builds an `ObjectShape` from a property map. |
|
|
529
|
+
| `recordShape` | function | `<S extends ContractShape>(values: S, options?: RecordShapeOptions) => ObjectShape<Record<never, never>, S>` | Builds an open `ObjectShape` with no fixed properties — a dictionary. |
|
|
530
|
+
| `unionShape` | function | `<V extends readonly ContractShape[]>(...variants: V) => UnionShape<Readonly<V>>` | Builds a `UnionShape` from a list of variant shapes (`anyOf` in JSON Schema). |
|
|
531
|
+
| `oneOfShape` | function | `<V extends readonly ContractShape[]>(...variants: V) => UnionShape<Readonly<V>>` | Builds a `UnionShape` that emits `oneOf` (exactly one match) in JSON Schema. |
|
|
532
|
+
| `optionalShape` | function | `<S extends ContractShape>(inner: S, options?: OptionalShapeOptions) => OptionalShape<S>` | Wraps a shape so it may be absent (`undefined`). |
|
|
533
|
+
| `nullableShape` | function | `<S extends ContractShape>(inner: S) => NullableShape<S>` | Wraps a shape so it may be `null`. |
|
|
534
|
+
| `jsonShape` | function | `(options?: JSONShapeOptions) => JSONShape` | Builds a `JSONShape`. |
|
|
535
|
+
| `rawShape` | function | `(schema: JSONSchema) => RawShape` | Builds a `RawShape` from a supported JSON Schema fragment. |
|
|
536
|
+
| `schemaToShape` | function | `(schema: JSONSchema, options?: SchemaToShapeOptions) => ContractShape` | Converts a runtime `JSONSchema` value into a validating `ContractShape` — the inverse of `compileSchema`. Unlike direct `rawShape` construction, which rejects malformed supported-vocabulary keywords, the lenient conversion is total and widens an inexpressible input to a valid raw `{}`, and a strict conversion refuses that input. |
|
|
537
|
+
| `deriveLengthBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of non-negative-integer JSON Schema length keywords (`minLength`/`maxLength`, `minItems`/`maxItems`). |
|
|
538
|
+
| `deriveRangeBounds` | function | `(min: unknown, max: unknown) => BoundsRead` | Derives `min`/`max` shape bounds from a pair of finite-number JSON Schema range keywords (`minimum`/`maximum`). |
|
|
539
|
+
|
|
540
|
+
An ordinary `oneOfShape` parser returns the input itself when exactly one arm accepts it. It makes no defensive copy: mutating the result mutates the input. Object key order and prototype, frozen state, and hidden and symbol members are retained. Copy explicitly if you need an independent result. Primitive and JSON-valued arms, no-match and ambiguous refusals, and the prohibition on defaults under unions keep their existing behavior. A required literal discriminator can still select an arm for coercion.
|
|
541
|
+
|
|
542
|
+
**String bounds count code points.** `min` and `max` on a string count what the `minLength` and `maxLength` the shape emits count, so one astral character has a length of one and a lone surrogate counts as one. `stringOf` and the two reports share `matchesStringLength`, which decides from `.length` where it can: a string holds at most `.length` code points and at least half that. Only where a bound sits between those two figures does it call `computeSurrogatePairs`, which stops as soon as the pairs it has found settle the bound.
|
|
543
|
+
|
|
544
|
+
**Field defaults.** `optionalShape(inner, { default })` lets a declaration state what an absent field reads as. The compiled parser fills the default where the property is absent or `undefined`, through the inner parser, on a fresh copy when the default is a container, so nested defaults apply and two parses share no tree. A default on a `jsonShape`, a `rawShape`, or a union inner reaches you as a frozen copy, because those parsers return their input by identity. `is`, `audit`, `explain`, and `generate` do not read a default: an absent optional stays canonical, so `is({})` is `true`, and `generate` keeps omitting the key or drawing from `inner`. The emitted property schema carries the keyword. `null` is a value and fills; a present `undefined` is a `structure` refusal, because absence is not a value.
|
|
545
|
+
|
|
546
|
+
The builder and `cloneShape` own a frozen copy of a value that passes `isJSONValue`, so a stored shape survives a JSON round trip. Every compiler refuses a default its `inner` guard refuses, refinements included, with code `structure` at `[…path, 'default']`: a restored declaration never met a builder, and `validateShape` judges structure only. A shape holding a default builds the guard family for that check whichever artifact you read first; a shape holding none builds what it always built.
|
|
547
|
+
|
|
548
|
+
Two positions refuse with code `placement`. A default under a `union` ancestor refuses, because a union's parser returns a guard-valid value by identity, so `{ n: 5 }` would never fill while `{ n: '5' }` filled unreported. A default on a property of an open object refuses, because `{ licenced: false }` would pass as an extra and fill `licensed` with `audit` and `explain` both empty. A `nullable` ancestor, an array ancestor, and an open object's tail shape are legal. Because a shared node is discovered through one route alone, the validator asks both questions over the captured graph, after discovery, so an earlier domain refusal outranks them.
|
|
549
|
+
|
|
550
|
+
This compiles a defaulted field, showing the parser fill it while `is` stays on canonical absence.
|
|
551
|
+
|
|
552
|
+
```ts
|
|
553
|
+
import { createContract, integerShape, objectShape, optionalShape } from '@orkestrel/contract'
|
|
554
|
+
|
|
555
|
+
const retries = createContract(
|
|
556
|
+
objectShape({ limit: optionalShape(integerShape({ min: 0 }), { default: 3 }) }),
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
retries.parse({}) // { limit: 3 }
|
|
560
|
+
retries.parse({ limit: '5' }) // { limit: 5 }
|
|
561
|
+
retries.is({}) // true — an absent optional stays canonical
|
|
562
|
+
retries.schema.properties?.limit?.default // 3
|
|
563
|
+
```
|
|
564
|
+
|
|
565
|
+
Raw-schema validation is deliberately structural and vocabulary-domain validation, not a full JSON Schema solver. It checks that every keyword is supported, every keyword value has the declared runtime domain, arrays are dense and vocabularies unique where required, every member captured from a present `properties`, dense `anyOf`, or dense `oneOf` population is a plain record, patterns compile, and the graph stays acyclic and within the depth limit. A `default` keyword must hold a JSON value, so a present `undefined` is refused, and neither the node's guard nor its parser reads it. Population is determined by membership, so a present member valued `undefined` is refused rather than erased as absence; omitted optional keywords, plus explicitly `undefined` `items` and `additionalProperties`, retain their absence behavior. It does not resolve cross-keyword contradictions such as `minLength: 5` with `maxLength: 1`, require each `required` name to appear in `properties`, enforce keyword/type coherence, compare `enum` members with `type`, or restrict `format` to a known vocabulary; those semantic interactions remain the responsibility of a full JSON Schema implementation.
|
|
476
566
|
|
|
477
567
|
`rawShape` first validates the caller-visible fragment, clones it exactly once, validates that exact owned clone, and returns that same frozen clone. A caller phase change that makes the captured population invalid is therefore refused; a valid captured population is the one published, and failures during the single clone retain the established `cloneSchema` diagnostic.
|
|
478
568
|
|
|
@@ -480,9 +570,15 @@ Direct declaration populations are dense data arrays too. A sparse literal is re
|
|
|
480
570
|
|
|
481
571
|
`schemaToShape` is the sole entry point for the conversion. The walk behind it is interned, so the door's name is the only one a refusal ever carries and the caller reaches the host failure through one `cause`.
|
|
482
572
|
|
|
483
|
-
The precedence below assumes a readable node. A readable malformed keyword is ignored and widens according to the listed rule; a keyword access, enumeration, or recursive traversal that throws is not malformed schema vocabulary and is refused with `ContractError { code: 'structure', context: { shape: 'schema' } }`.
|
|
573
|
+
The precedence below assumes a readable node and a lenient conversion. A readable malformed keyword is ignored and widens according to the listed rule; a keyword access, enumeration, or recursive traversal that throws is not malformed schema vocabulary and is refused with `ContractError { code: 'structure', context: { shape: 'schema' } }`.
|
|
574
|
+
|
|
575
|
+
`schemaToShape`'s precedence, top-down at each node (every keyword read is type-guarded; a malformed keyword is IGNORED, not thrown): (0) `$ref` widens the node to `rawShape` before anything beside it is read, because this walk resolves no reference and under draft-07 a reference replaces its siblings. (1) `enum` partitions its entries: finite string/number/boolean entries → `literalShape`, a `null` entry wraps it in `nullableShape`, `null` alone → `nullShape`, and any object, array, or non-finite entry widens the node to `rawShape`, because dropping it would narrow; an empty list falls through. (2) `oneOf` (≥ 1 arm) → `unionShape` over the recursed arms, PROVIDED the arm count is at or under `INFER_BREADTH_LIMIT`; over the cap, building a subset union would be strictly narrower than the schema's full union, so the node widens to `rawShape` instead of sampling a subset. The union is inclusive because this walk does not read `const`, `pattern`, `format`, or `multipleOf`: arms those keywords keep apart overlap here, and exactly-one over them refuses a value the schema accepts, as a Pydantic discriminated union showed. (3) `anyOf` identically → `unionShape`, with the same over-cap widen-to-`rawShape` rule rather than a subset union. In both, a `true` arm is a `rawShape({})` variant in declaration order, a `false` arm is dropped because it admits nothing, and a list its `false` arms leave empty widens to `rawShape`. Two arms, one of them `{ type: 'null' }`, read as `nullableShape` of the other, which therefore stays outside a union: a default under it fills, and `nullableShape` over a defaulted object survives its own schema. Only a strict `oneOf` keeps the union, for its exactly-one. A `description` beside the keyword carries onto the union, or onto the arm of a nullable, overriding that arm's own text, because `NullableShape` holds no description and the keyword describes the field. (4) An array-valued `type` → `unionShape` over each distinct recognized name, converting `{ ...schema, type: member }` at the same depth so bounds, `items`, `properties`, and `description` apply to each member. A single distinct name returns its shape directly. Two distinct names, one of them `null`, read as `nullableShape` of the other in both lenient and strict conversions, because the list means what the `anyOf` spelling in rule (3) means and has no exactly-one to keep. An empty array or any unrecognized member widens the whole node to `rawShape`, even when `properties` is present; no member is dropped to narrow the union. The distinct-name count is checked against `INFER_BREADTH_LIMIT`; the recognized vocabulary fits below that cap, so repeated names do not exhaust it. This is runtime conversion support: the declared `JSONSchema.type` remains a single name because direct raw-schema validation supports only that vocabulary. (5) `type: 'string'/'number'/'integer'/'boolean'/'null'` → the matching primitive shape, with `minLength`/`maxLength`/`minimum`/`maximum` bounds kept only when well-formed and non-contradictory (a malformed or `min > max` pair drops to unbounded — widening, never narrowing). (6) `type: 'array'` → `arrayShape`, recursing into a record-valued `items` (else `rawShape`), with `minItems`/`maxItems` bounds. A present `prefixItems` makes the element shape `rawShape({})`, because `items` then applies only past the prefix. (7) `type: 'object'` → `objectShape`; no `type`/`enum`/`oneOf`/`anyOf` but a record `properties` → `unionShape` of that object first, then `stringShape`, `numberShape`, `booleanShape`, `nullShape`, and `arrayShape(rawShape({}))`, because `properties` and `required` constrain only an object, so `5` is valid there, while a rejected field stays rejected because no arm admits every object. The object branch: a property not listed in `required` is wrapped `optionalShape`; `additionalProperties: false` closes, a record value recurses into it (`objectShape` validates extras against that shape directly — no widening needed), and `true` / ABSENT / anything malformed leaves it open (`true`) — absent matches JSON Schema's own default, and `valueToSchema` / `samplesToSchema` always emit the keyword explicitly, so an absent value only arises from a hand-written schema. A present `patternProperties` reads the object open whatever its own `additionalProperties` says, because a key that keyword admits is unread here; `propertyNames` exempts no key from `additionalProperties`, so it opens nothing. When `properties` has MORE keys than `INFER_BREADTH_LIMIT`, the schema's own `additionalProperties` is OVERRIDDEN and forced open (`true`) regardless of `false` or a record value — a key dropped past the sampling cap was never checked against a closed or record-valued rest shape, so forcing the object open is the only sound widening — mirroring the inferers' own `truncated ? true : !closed` rule. (8) Everything else — `{}`, an unrecognized `type`, exhausted depth (`INFER_DEPTH_LIMIT`), or a cyclic re-encounter — widens to `rawShape` (NOT `jsonShape`: `{}` is JSON Schema’s accept-anything schema, and `rawShape` is its exact inverse — its guard accepts every defined value and it re-emits `{}` verbatim, whereas `jsonShape`’s `isJSONValue` guard would reject the exotic originals (`Map`, `Set`, a class instance, a function, `NaN`) whose inferred schema is exactly `{}`). A `WeakMap` memo (keyed by schema-node identity + remaining depth), mirroring the inferers, guards a shared-reference schema DAG against exponential re-conversion. **Its key does not carry the active-ancestor set, and that is observable**: a node first reached through a CYCLIC path is cached with the shape it widened to at the back-edge, and a later ACYCLIC path is served that cached shape instead of descending further. Two schemas differing only in which sibling holds the cyclic node therefore convert to different shapes. Every such difference is a WIDENING — an accept-anything `rawShape` — so no value is wrongly rejected and the round-trip law is unaffected; what it costs is determinism ACROSS graphs, not within one, since the same input always converts the same way. This is stated as a limit rather than repaired because both repairs (dropping the ancestor set, or threading a cycle-affected flag through three public signatures) change the published surface.
|
|
484
576
|
|
|
485
|
-
|
|
577
|
+
**The lenient law.** A value a JSON Schema accepts is never refused by the shape a lenient conversion builds from it, and the conversion always compiles: a schema that would expand past `COMPILE_NODE_LIMIT` keeps only its root rather than leave a real tool uncallable: the root's type, an array's bounds, and an object's required keys and closure, with every value below them `rawShape({})`. A root with none of those, such as a union, widens whole. The check costs a validator pass only for a schema large enough to reach the limit or one that shares a node. `nullable: true`, the OpenAPI keyword `JSONSchema` does not declare, wraps the converted node in `nullableShape`. The walk leaves `const`, `multipleOf`, `exclusiveMinimum`, `exclusiveMaximum`, `allOf`, `$ref`, `$defs`, `not`, `if`, `contains`, `uniqueItems`, `minProperties`, `maxProperties`, `dependentRequired`, `unevaluatedProperties`, `pattern`, and `format` unread, and an unread keyword widens: an untrusted `pattern` is never compiled. The advertised schema stays the host's own record, so `oneOf` still reaches a model verbatim.
|
|
578
|
+
|
|
579
|
+
A lenient conversion carries a property's `default` when the key is not in `required`, the object is closed with no union ancestor, and the value is one the property's primitive or literal guard accepts. It drops every other `default`, because a carried default that cannot compile would end the conversion's totality.
|
|
580
|
+
|
|
581
|
+
**Strict conversion.** `schemaToShape(schema, { strict: true })` is the door for a foreign schema. It refuses, with code `structure` and the keyword's path, what the lenient walk would widen or read past: every node the walk would widen to `rawShape` (an empty schema, a `type` typo at any depth, a non-record child, an array with no `items`, exhausted depth, and a cycle), a keyword outside `STRICT_SCHEMA_KEYWORDS` (`$ref`, `$defs`, `definitions`, `const`, `allOf`, `$anchor`, `$dynamicAnchor`, the `content*` keywords, `nullable`, `discriminator`, `example`, `patternProperties`, `propertyNames`, and `prefixItems`), `pattern` and `format`, which no compiled shape asserts, a malformed keyword value or annotation, a boolean schema, an `enum` entry that is neither a finite primitive nor `null`, a contradictory or malformed bound, a keyword the node's type never reads, a `type` beside a union, a pair of keywords only one of which the walk would keep, an enum member its `type` contradicts, a `required` name not in `properties`, breadth past `INFER_BREADTH_LIMIT`, and a `default` with no optional property to fill or one its schema refuses. `oneOf` keeps exactly-one here, because this walk reads every keyword that could keep two arms apart. An object with no `additionalProperties` closes, unlike JSON Schema's own default, because a misspelled key at a foreign door must reach `audit`; an explicit `true` or schema value stays open. Below a `oneOf` it refuses instead, at any depth, because closing it could change which arms match: two arms declaring optional `a` and `b` both match `{ a: 'x' }` as written, and only one does once closed. It accepts the annotations a schema generator emits, which assert nothing and which the shape drops: `title`, `$schema`, `$id`, and `$comment` when strings, `examples` when an array, and `deprecated`, `readOnly`, and `writeOnly` when booleans. A default under a union or on an open object refuses with `placement` at its path in the schema, ending `properties`, the key, and `default`.
|
|
486
582
|
|
|
487
583
|
**Round-trip law:** for any READABLE value `v` — including `NaN`, `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a bigint, and readable cyclic hosts — `compileGuard(schemaToShape(valueToSchema(v)))(v) === true`, with widening as the ONLY source of looseness, never narrowing. An unreadable host is refused before the law produces a schema. The law otherwise retains its three limits: JSON absence, `Date` serialization, and unstable reads between inference and validation. A widened node cannot be auto-generated: `createContract(schemaToShape(x)).generate()` throws when the conversion widened anywhere; its parser returns `undefined` for readable invalid input and propagates the shared coded refusal when a required read fails.
|
|
488
584
|
|
|
@@ -503,36 +599,38 @@ contract.parse({ id: 'nope', name: 'x' }) // undefined
|
|
|
503
599
|
A resolver whose value is a multi-branch conditional carries none, and its `Summary` states
|
|
504
600
|
what the resolution produces.
|
|
505
601
|
|
|
506
|
-
| Name
|
|
507
|
-
|
|
|
508
|
-
| `ContractShape`
|
|
509
|
-
| `StringShape`
|
|
510
|
-
| `NumberShape`
|
|
511
|
-
| `BooleanShape`
|
|
512
|
-
| `NullShape`
|
|
513
|
-
| `LiteralShape`
|
|
514
|
-
| `ArrayShape`
|
|
515
|
-
| `ObjectShape`
|
|
516
|
-
| `UnionShape`
|
|
517
|
-
| `OptionalShape`
|
|
518
|
-
| `NullableShape`
|
|
519
|
-
| `JSONShape`
|
|
520
|
-
| `RawShape`
|
|
521
|
-
| `Infer`
|
|
522
|
-
| `InferObject`
|
|
523
|
-
| `InferIndex`
|
|
524
|
-
| `InferOpenIndex`
|
|
525
|
-
| `InferMutable`
|
|
526
|
-
| `InferUnion`
|
|
527
|
-
| `StringShapeOptions`
|
|
528
|
-
| `NumberShapeOptions`
|
|
529
|
-
| `BooleanShapeOptions`
|
|
530
|
-
| `NullShapeOptions`
|
|
531
|
-
| `JSONShapeOptions`
|
|
532
|
-
| `LiteralShapeOptions`
|
|
533
|
-
| `ArrayShapeOptions`
|
|
534
|
-
| `ObjectShapeOptions`
|
|
535
|
-
| `RecordShapeOptions`
|
|
602
|
+
| Name | Kind | Signature | Summary |
|
|
603
|
+
| ---------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
604
|
+
| `ContractShape` | type | `StringShape \| NumberShape \| BooleanShape \| NullShape \| LiteralShape \| ArrayShape \| ObjectShape \| UnionShape \| OptionalShape \| NullableShape \| JSONShape \| ShapeShape \| RawShape` | Describes a value declaratively — a declaration the shape builders build and the compilers turn into a guard, a parser, a JSON Schema, and a generator. |
|
|
605
|
+
| `StringShape` | interface | `{ category, min?, max?, pattern?, description? }` | Describes a string with optional length and pattern constraints. |
|
|
606
|
+
| `NumberShape` | interface | `{ category, min?, max?, integer?, description? }` | Describes a number with optional bounds; `integer` restricts to whole numbers. |
|
|
607
|
+
| `BooleanShape` | interface | `{ category, description? }` | Describes a boolean — accepts only `true` or `false`. |
|
|
608
|
+
| `NullShape` | interface | `{ category, description? }` | Describes a null value — accepts only `null`. |
|
|
609
|
+
| `LiteralShape` | interface | `{ category, values, description? }` | Describes a literal — accepts exactly one of a fixed set of primitive values. |
|
|
610
|
+
| `ArrayShape` | interface | `{ category, items, min?, max?, description? }` | Describes an array with an element shape and optional length bounds. |
|
|
611
|
+
| `ObjectShape` | interface | `{ category, properties, additionalProperties?, description? }` | Describes an object — a map of property names to child shapes. |
|
|
612
|
+
| `UnionShape` | interface | `{ category, variants, mode?, description? }` | Describes a union — accepts a value matching any one variant (first match wins). |
|
|
613
|
+
| `OptionalShape` | interface | `{ category, inner, default? }` | Wraps an inner shape that may be absent (`undefined`). |
|
|
614
|
+
| `NullableShape` | interface | `{ category, inner }` | Wraps an inner shape that may be `null`. |
|
|
615
|
+
| `JSONShape` | interface | `{ category, description? }` | Describes a JSON passthrough — accepts any JSON value. |
|
|
616
|
+
| `RawShape` | interface | `{ category, schema }` | Describes a validated raw JSON Schema passthrough — embeds a supported schema fragment directly. |
|
|
617
|
+
| `Infer` | type | `[ContractShape] extends [S] ? unknown : S extends ShapeShape ? ContractShape : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends { readonly category: 'literal'; readonly values: infer V; } ? V extends ReadonlyArray<infer L> ? L : never : S extends { readonly category: 'array'; readonly items: infer I; } ? I extends ContractShape ? ReadonlyArray<Infer<I>> : never : S extends ObjectShape<infer P, infer A> ? P extends Readonly<Record<string, ContractShape>> ? [A] extends [boolean \| ContractShape] ? InferObject<P, A> : never : never : S extends { readonly category: 'union'; readonly variants: infer V; } ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| undefined : never : S extends { readonly category: 'nullable'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> \| null : never : S extends JSONShape ? JSONValue : unknown` | Resolves the static TypeScript type a `ContractShape` describes. |
|
|
618
|
+
| `InferObject` | type | `[keyof P] extends [never] ? [A] extends [false] ? Readonly<Record<never, never>> : InferIndex<A> : Readonly<{ [K in keyof P as P[K] extends { readonly category: 'optional'; } ? never : K]: Infer<P[K]>; } & { [K in keyof P as P[K] extends { readonly category: 'optional'; } ? K : never]?: P[K] extends { readonly category: 'optional'; readonly inner: infer I; } ? I extends ContractShape ? Infer<I> : never : never; }> & InferOpenIndex<A>` | Resolves `Infer` of an object shape's `properties` — the required keys, plus the `optional`-wrapped keys as optional members, plus the index-signature contribution of `additionalProperties` (see `InferIndex`). |
|
|
619
|
+
| `InferIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: Infer<A>; } : unknown` | Computes the index-signature contribution of a pure record shape's `additionalProperties` — the `recordShape` case, where `properties` is empty. |
|
|
620
|
+
| `InferOpenIndex` | type | `[A] extends [false] ? unknown : [A] extends [true] ? { readonly [k: string]: unknown; } : [A] extends [ContractShape] ? { readonly [k: string]: unknown; } : unknown` | Computes the index-signature contribution of a MIXED object shape's `additionalProperties` — one with both fixed `properties` and an open tail. |
|
|
621
|
+
| `InferMutable` | type | `{ -readonly [K in keyof Infer<S>]: Infer<S>[K]; }` | Strips the TOP-LEVEL `readonly` modifiers from `Infer` (a shallow strip — nested object/array properties stay readonly) — for consumers writing the parsed value's own fields. |
|
|
622
|
+
| `InferUnion` | type | `V extends ReadonlyArray<infer U> ? (U extends ContractShape ? Infer<U> : never) : never` | Resolves `Infer` of a union shape's `variants` — the union of each variant's inferred type. |
|
|
623
|
+
| `StringShapeOptions` | interface | `{ min?, max?, pattern?, description? }` | Groups the options for `StringShape` (through `stringShape`). |
|
|
624
|
+
| `NumberShapeOptions` | interface | `{ min?, max?, integer?, description? }` | Groups the options for `NumberShape` (through `numberShape` / `integerShape`). |
|
|
625
|
+
| `BooleanShapeOptions` | interface | `{ description? }` | Groups the options for `BooleanShape` (through `booleanShape`). |
|
|
626
|
+
| `NullShapeOptions` | interface | `{ description? }` | Groups the options for `NullShape` (through `nullShape`). |
|
|
627
|
+
| `JSONShapeOptions` | interface | `{ description? }` | Groups the options for `JSONShape` (through `jsonShape`). |
|
|
628
|
+
| `LiteralShapeOptions` | interface | `{ description? }` | Groups the options for `LiteralShape` (through `literalShape`). |
|
|
629
|
+
| `ArrayShapeOptions` | interface | `{ min?, max?, description? }` | Groups the options for `ArrayShape` (through `arrayShape`). |
|
|
630
|
+
| `ObjectShapeOptions` | interface | `{ additionalProperties?, description? }` | Groups the options for `ObjectShape` (through `objectShape`). |
|
|
631
|
+
| `RecordShapeOptions` | interface | `{ description? }` | Groups the options for record shapes (through `recordShape`). |
|
|
632
|
+
| `OptionalShapeOptions` | interface | `{ default? }` | Groups the options for `OptionalShape` (through `optionalShape`). |
|
|
633
|
+
| `SchemaToShapeOptions` | interface | `{ strict? }` | Groups the options for converting a JSON Schema (through `schemaToShape`). |
|
|
536
634
|
|
|
537
635
|
### Compilers
|
|
538
636
|
|
|
@@ -540,9 +638,9 @@ Turn one `ContractShape` into the six lockstep outputs — `schema` / `is` / `pa
|
|
|
540
638
|
|
|
541
639
|
| Name | Kind | Signature | Summary |
|
|
542
640
|
| --------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
543
|
-
| `ShapeValidator` | class | `new (shape:
|
|
641
|
+
| `ShapeValidator` | class | `new (shape: unknown) => ShapeValidatorInterface` | Validates one retained contract-shape source live on every call. |
|
|
544
642
|
| `ShapeValidatorInterface` | interface | `{ expansion, validate() }` | Validates one retained contract-shape source on demand. |
|
|
545
|
-
| `validateShape` | function | `(shape:
|
|
643
|
+
| `validateShape` | function | `(shape: unknown) => void` | Gates recursive compiler work on shape structure, depth, and cycles. |
|
|
546
644
|
| `compileGuard` | function | `(<S extends ContractShape>(shape: S) => Guard<Infer<S>>) & ((shape: ContractShape) => Guard<unknown>)` | Compiles a `ContractShape` into a runtime type guard. |
|
|
547
645
|
| `compileParser` | function | `(<S extends ContractShape>(shape: S) => Parser<Infer<S>>) & ((shape: ContractShape) => Parser<unknown>)` | Compiles a `ContractShape` into an input parser. |
|
|
548
646
|
| `compileSchema` | function | `(shape: ContractShape) => JSONSchema` | Compiles a `ContractShape` into a JSON Schema document. |
|
|
@@ -569,7 +667,7 @@ whole surface is the readonly data properties — `schema` (a `JSONSchema`), `gu
|
|
|
569
667
|
value the corresponding getter publishes — `contract.is` is exactly `compiler.guard`, by
|
|
570
668
|
identity rather than as a copy of it.
|
|
571
669
|
|
|
572
|
-
Compilation costs ONE ownership and ONE validation per call, not one per node. Every `compile*` entry and `createContract` construct a `ContractCompiler`, which owns the declaration once, validates that owned graph once, and indexes each unique node and structural edge once; the artifact families are postorder passes over that index. This is what replaced the arrangement where each recursive invocation re-ran `ownShape` AND `validateShape` over the subgraph it received — quadratic work for a linear declaration, and the reason a 129-node depth chain used to measure 6.3 ms of gate plus 7.9 ms of ownership and a 257-node chain 26.0 + 41.9 ms. A 30-alias depth-100 declaration now compiles a guard in 3 ms and a whole contract in 4 ms, against 640 ms and 1.87 s before.
|
|
670
|
+
Compilation costs ONE ownership and ONE validation per call, not one per node. Every `compile*` entry and `createContract` construct a `ContractCompiler`, which owns the declaration once, validates that owned graph once, and indexes each unique node and structural edge once; the artifact families are postorder passes over that index. A builder records what it validated, so wrapping a built child observes only the new node, and a declaration made entirely by builders is compiled as it stands, with no snapshot and no walk. A hand-written node anywhere in the graph, or a field a node may leave out appearing on `Object.prototype`, takes the whole walk instead, and that walk authors every refusal, so a refusal reads the same and fires at the same call either way. This is what replaced the arrangement where each recursive invocation re-ran `ownShape` AND `validateShape` over the subgraph it received — quadratic work for a linear declaration, and the reason a 129-node depth chain used to measure 6.3 ms of gate plus 7.9 ms of ownership and a 257-node chain 26.0 + 41.9 ms. A 30-alias depth-100 declaration now compiles a guard in 3 ms and a whole contract in 4 ms, against 640 ms and 1.87 s before. Every artifact compiles once, so `audit`, `explain` and `generate` re-walk and re-gate nothing on a later call either; `contract.audit` and `compileAuditor` run the same compiled plan reached by different names. A union whose arms are all objects declaring a required literal property answers through one arm when a value's own property exactly equals a literal only that arm holds: `explain` and `audit` report that arm's faults at their real paths in place of `variant`, and `parse` repairs through it alone, so `{ operation: 'find', limit: '5' }` parses to `limit: 5` however many arms precede it. No other arm's guard could accept that value, so the three laws hold and `is` does not change. A value that names no one arm, because its property is absent, matches no literal, or matches one two arms share, keeps `variant` or `oneOf`, with `key` and `expected` naming the property and what it may hold. `oneOfShape` behaves the same way: its parser refuses to coerce only because an ambiguous value has no target, and a named arm is one. An arm that is not an object, a discriminator that is optional or inside a nullable, and a nested union all change nothing at that union. `createContract` over a declaration made entirely by builders compiles its schema at that call and its function members together on the first call to any of them, so a module can declare contracts as data and pay only for the ones it uses; any other declaration, and a bare leaf, compiles every member at that call. Every refusal a declaration can earn still fires at `createContract` either way, because preparation and the schema ask them all, and each member is one plain function, so destructuring and spreading compile nothing. A member compiling after the call reads its declaration through own fields, so a field added to `Object.prototype` since cannot reach it. A host member replaced since is the one thing that can stop it: compiling there would outlive the replacement, so the member refuses to compile until the host is restored, with its guard answering `false`, its parser `undefined`, and its diagnostics and generator refusing, and the next call on a restored host compiles as usual. A first call near the stack limit recovers the same way. A compiled artifact is no longer a TREE either. Each family holds one entry per unique node and a parent points at its children, so a shared child is compiled once and the emitted schema preserves that sharing — which is why the cap boundary stopped being expensive: `createContract` over the two-edge-per-level DAG at the 16,383-node boundary now takes under a millisecond where it took 1,342 ms, because it compiles fourteen nodes rather than sixteen thousand. Cost tracks AUTHORED nodes and edges instead: measured here, a depth-100 chain and a 30-alias depth-100 staircase answer every door in 1–5 ms, and a flat 10,001-node object takes 52–68 ms per artifact and 110 ms for a whole contract. One level past the cap boundary — 32,767 emitted nodes over thirty-one authored ones — still refuses in about two milliseconds with code `expansion`, because the count is measured over the captured graph rather than by walking the expansion. What the cap now protects is the consumer's side of the artifacts rather than the compiler's: `generate` materializes the whole tree, and so does serializing the schema. The JSON cloner is capped for the opposite reason — it DUPLICATES a shared alias by contract rather than re-walking it: see `CLONE_NODE_LIMIT`. The `samplesToSchema` family is not on this list and was never meant to be reachable: its record path carried neither an ancestor set nor a memo, so an ordinary shared reference bought `k^depth` visits; it now memoizes a single-row slot on `(row, remaining depth)` exactly as the record branch of `valueToSchema` does. Everything above is the DECLARATION side, and for one release that was the only side measured. A compiled artifact applies each child artifact once per OCCURRENCE, which is right for a tree and wrong for a graph, so a value whose levels each held two references to one object was walked once per PATH: twenty-two shared arrays against a twenty-three-node chain of `arrayShape` — zero aliases in the declaration, every published limit satisfied — cost 524,286 node reads, 4.4 s for `is` and 8.4 s for `audit`, growing fourfold per two levels, while the same declaration over a TREE value answered instantly and `valueToSchema` answered the same graph in 4 ms because it already memoized. The verdict families now carry a per-CALL identity memo keyed by `(compiled node, value object)`, and the same value now costs thirty-six reads and under a millisecond. These details are exact rather than incidental. The guard reuses either answer while the auditor and reporter reuse only the CLEAN one, because a fault carries the path it was found at and emptiness carries nothing — a faulted node is re-walked and bounded by `FAULT_LIMIT` instead. The active synchronous call owns each node's memo and releases the scope on settlement, so an answer never survives into a later call where the caller may have changed the value. And a leaf is not tracked at all: it descends into no child, so tracking one would buy nothing and would replace the package's own guards and parsers in the artifacts a leaf-rooted declaration publishes. `parse` is deliberately absent from that list, because its result IS the expansion; the threat model names what that costs.
|
|
573
671
|
|
|
574
672
|
String and array length bounds deliberately use the builders' FULL rule — every present bound is a non-negative safe integer — rather than merely checking finiteness. A finiteness-only gate would close the `NaN` / infinity bypass but still admit hand-authored negative, fractional, and unsafe-integer length keywords that no builder can produce and that are not valid JSON Schema length bounds. Matching the builders costs compatibility only for those already-malformed hand-authored shapes; it preserves every legitimate builder output and keeps guard, parser, audit, and schema semantics on one domain.
|
|
575
673
|
|
|
@@ -588,7 +686,7 @@ validateShape(deep) // throws a ContractError with code 'depth'
|
|
|
588
686
|
compileGuard(deep) // the same throw — every compile* entry fidelity-checks ownership, then gates
|
|
589
687
|
```
|
|
590
688
|
|
|
591
|
-
Every builder validates every runtime argument position before freezing its result. At every options position, a primitive or readable array/class instance throws a `structure` `ContractError` saying that the builder's options must be a plain record. A failure while reading any option key that builder consumes, or while snapshotting the options record, routes through the shared constructor as `<builder>: options could not be read`; no failed read becomes an absent option. Each consumed option is read once and its one non-`undefined` answer is copied into the snapshot as own enumerable data, including inherited and non-enumerable answers; unrelated properties remain irrelevant. `{}` is accepted and constrains nothing. Invalid bounds use the total `preview` diagnostic, so even a hostile `Symbol.toPrimitive` receives the existing `bound` refusal instead of leaking its raw error. The wider construction gate also covers `description` domains, child-shape slots, finite/ranged bounds, non-empty dense unique literal/union vocabularies, integer-range satisfiability, optional placement, and `rawShape`'s recursive supported-schema vocabulary. A malformed builder call therefore throws a coded `ContractError` at construction instead of leaking a raw host error or returning a node that only a later compiler rejects. Hand-authored declarations remain checked at ownership and by `validateShape` before artifact recursion.
|
|
689
|
+
Every builder validates every runtime argument position before freezing its result. At every options position, a primitive or readable array/class instance throws a `structure` `ContractError` saying that the builder's options must be a plain record. A failure while reading any option key that builder consumes, or while snapshotting the options record, routes through the shared constructor as `<builder>: options could not be read`; no failed read becomes an absent option. Each consumed option is read once and its one non-`undefined` answer is copied into the snapshot as own enumerable data, including inherited and non-enumerable answers; unrelated properties remain irrelevant. Two options differ, because each decides what a contract accepts rather than how it describes itself: `optionalShape`'s `default` and `schemaToShape`'s `strict` count only as own keys, and those two doors refuse any other own key through `refuseOptionKeys`, so a misspelled option cannot read as an absent one. `{}` is accepted and constrains nothing. Invalid bounds use the total `preview` diagnostic, so even a hostile `Symbol.toPrimitive` receives the existing `bound` refusal instead of leaking its raw error. The wider construction gate also covers `description` domains, child-shape slots, finite/ranged bounds, non-empty dense unique literal/union vocabularies, integer-range satisfiability, optional placement, and `rawShape`'s recursive supported-schema vocabulary. A malformed builder call therefore throws a coded `ContractError` at construction instead of leaking a raw host error or returning a node that only a later compiler rejects. Hand-authored declarations remain checked at ownership and by `validateShape` before artifact recursion.
|
|
592
690
|
|
|
593
691
|
```ts
|
|
594
692
|
import type { ContractShape } from '@orkestrel/contract'
|
|
@@ -657,23 +755,27 @@ schemaToParameters(valueToSchema(row)) // the open record a tool advertises as `
|
|
|
657
755
|
|
|
658
756
|
One diagnostic for each artifact that answers yes-or-no. `compileReporter` is the counterpart of `compileParser`: instead of a coerced value it returns every structured `Fault` a value has against a shape — MIRROR-PARSE semantics, so it reuses the exact leaf parsers/guards `compileParser` uses and the soundness invariant `explain(v).length === 0 ⟺ parse(v) !== undefined` holds structurally for READABLE input (`explain` mirrors `parse`'s coercion leniency, not the stricter `is`). `compileAuditor` is the counterpart of `compileGuard`: instead of a `boolean` it returns every `AuditFault` a value has against the STRICT domain, reusing the leaf guards `compileGuard` uses, so `audit(v).length === 0 ⟺ is(v)`. Each report mirrors exactly one artifact, and neither mirrors both, because `is` and `parse` accept different values — which is the subject of the next section. Before either pair compiles, `validateShape` rejects structural and bound-domain malformations; the laws are evaluated only for a valid declaration. Both biconditionals span two separate calls, so both require STABLE reads; the parse biconditional additionally requires the read to succeed rather than raise its coded refusal (see Domains).
|
|
659
757
|
|
|
660
|
-
| Name
|
|
661
|
-
|
|
|
662
|
-
| `compileAuditor`
|
|
663
|
-
| `compileReporter`
|
|
664
|
-
| `buildStringFaults`
|
|
665
|
-
| `buildNumberFaults`
|
|
666
|
-
| `buildArrayFaults`
|
|
667
|
-
| `
|
|
668
|
-
| `
|
|
669
|
-
| `
|
|
670
|
-
| `
|
|
671
|
-
| `
|
|
672
|
-
| `
|
|
673
|
-
| `
|
|
674
|
-
| `
|
|
675
|
-
| `
|
|
676
|
-
| `
|
|
758
|
+
| Name | Kind | Signature | Summary |
|
|
759
|
+
| ----------------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
|
760
|
+
| `compileAuditor` | function | `(shape: ContractShape, value: unknown, path?: readonly string[]) => readonly AuditFault[]` | Audits a value against the strict acceptance domain of a `ContractShape`. |
|
|
761
|
+
| `compileReporter` | function | `(shape: ContractShape, value: unknown, path?: readonly string[]) => readonly Fault[]` | Compiles a `ContractShape` into a structured fault report for a value — the diagnostic counterpart of `compileGuard` / `compileParser`. |
|
|
762
|
+
| `buildStringFaults` | function | `(shape: StringShape, value: string, path: readonly string[], pattern?: RegExp) => readonly Fault[]` | Builds the refinement faults a string value has against a `StringShape`. |
|
|
763
|
+
| `buildNumberFaults` | function | `(shape: NumberShape, value: number, path: readonly string[]) => readonly Fault[]` | Builds the refinement faults a number value has against a `NumberShape`. |
|
|
764
|
+
| `buildArrayFaults` | function | `(shape: ArrayShape, length: number, path: readonly string[]) => readonly Fault[]` | Builds the length faults an array has against an `ArrayShape`. |
|
|
765
|
+
| `matchesLosslessRepair` | function | `(fault: AuditFault, input: unknown, parsed: unknown) => boolean` | Determines whether a repair `parse` made kept everything the value said. |
|
|
766
|
+
| `matchesExactKeys` | function | `(value: object, required: readonly string[], optional?: readonly string[]) => boolean` | Determines whether an object holds exactly the named own keys. |
|
|
767
|
+
| `selectClosestFaults` | function | `<T extends AuditFault>(reports: ReadonlyArray<readonly T[]>) => readonly T[]` | Selects the report of the variant that came closest to matching. |
|
|
768
|
+
| `shapeToKind` | function | `(shape: ContractShape) => FaultKind` | Projects a `ContractShape` to the `FaultKind` it describes. |
|
|
769
|
+
| `preview` | function | `(value: unknown) => string` | Renders an unknown value as a short, safe, TOTAL string for a `Fault`'s `received` field. |
|
|
770
|
+
| `FAULT_KINDS` | const | `readonly FaultKind[]` | Lists every `FaultKind`, frozen. |
|
|
771
|
+
| `FAULT_CONSTRAINTS` | const | `readonly FaultConstraint[]` | Lists every `FaultConstraint`, frozen. |
|
|
772
|
+
| `FAULT_LIMIT` | const | `64` | Caps at `64` the number of `Fault` / `AuditFault` entries a single `explain` or `audit` report ever returns, frozen. |
|
|
773
|
+
| `PREVIEW_LIMIT` | const | `64` | Caps at `64` the character length of a `preview`-rendered string, frozen. |
|
|
774
|
+
| `Fault` | type | `{ readonly reason: 'type'; readonly path: FieldPath; readonly expected: FaultKind; readonly received: string; } \| { readonly reason: 'missing'; readonly path: FieldPath; readonly expected: FaultKind; } \| { readonly reason: 'constraint'; readonly path: FieldPath; readonly expected: FaultKind; readonly constraint: FaultConstraint; readonly limit?: number \| string; readonly received: string; } \| { readonly reason: 'variant'; readonly path: FieldPath; readonly variants: number; readonly key?: string; readonly expected?: readonly LiteralValue[]; } \| { readonly reason: 'oneOf'; readonly path: FieldPath; readonly matched: number; readonly key?: string; readonly expected?: readonly LiteralValue[]; }` | Represents a single structured parse-failure diagnostic — one entry of an `ContractInterface.explain` report. |
|
|
775
|
+
| `ExtraFault` | interface | `{ reason, path }` | Represents a key present on a value that its closed object shape does not declare. |
|
|
776
|
+
| `AuditFault` | type | `Fault \| ExtraFault` | Covers every fault an audit reports — the parse faults plus undeclared keys. |
|
|
777
|
+
| `FaultKind` | type | `'string' \| 'number' \| 'integer' \| 'boolean' \| 'null' \| 'literal' \| 'array' \| 'object' \| 'union' \| 'json' \| 'shape'` | Names the kind of value a `Fault` expected — the shape-projected counterpart of a `ContractShape`'s `category`. |
|
|
778
|
+
| `FaultConstraint` | type | `'min' \| 'max' \| 'pattern' \| 'integer'` | Names the refinement a `Fault` of reason `'constraint'` violates. |
|
|
677
779
|
|
|
678
780
|
#### How a union is audited and reported
|
|
679
781
|
|
|
@@ -707,10 +809,11 @@ Under the module-wide READABLE and STABLE definitions at the top of this guide,
|
|
|
707
809
|
|
|
708
810
|
The ordering between the two reports follows from those three rather than standing as a fourth law: `audit(v).length === 0 ⟹ explain(v).length === 0`. Every value in the canonical domain is inside `parse`'s preimage, so a clean audit implies a clean explain; the converse fails for exactly the inputs `parse` had to work on. Reach for `audit` when you need to know what `parse` silently repaired, and for `explain` when you need to know why it gave up.
|
|
709
811
|
|
|
710
|
-
`parse` therefore is not the identity function on the values `is` already accepts. It differs in
|
|
812
|
+
`parse` therefore is not the identity function on the values `is` already accepts. It differs in four ways:
|
|
711
813
|
|
|
712
814
|
- **Coercion.** `'36'` parses to `36` against an `integerShape`, and a string that trims to a declared literal parses to that literal. The input fails `is` and earns a `'type'` fault from `audit`; `explain` reports nothing, because nothing failed the parse.
|
|
713
815
|
- **Dropped extras.** A key a closed object shape does not declare is dropped from the parsed result. `is` rejects the object, `audit` reports one `'extra'` fault at the key, `schema` forbids it with `additionalProperties: false`, and `explain` stays silent — the parser repaired it, so there is nothing to explain.
|
|
816
|
+
- **A filled default.** A property absent from the input, whose optional carries a `default`, parses to that default. `is` accepts the absent form, `audit` and `explain` report nothing, and `is` accepts the filled result. An own `undefined` fills too, and it keeps its standing at the strict doors: it fails `is` and earns an `audit` fault, as it does with no default.
|
|
714
817
|
- **A null-prototype copy.** The compiled object parser assembles its result on `Object.create(null)` and copies the declared keys into it, so `parse` returns a NEW null-prototype record and never the record you handed it — `contract.parse(v) !== v` holds even when `contract.is(v)` was already `true`. The copy satisfies `is` (`isRecord` accepts a `null` prototype directly) and is not frozen; the cloners build null-prototype records for the same reason — a key literally named `__proto__` has to land as own data instead of mutating a prototype. An array shape likewise returns a fresh standard array. A leaf returns its input by identity, and a union returns a guard-valid value unchanged — its identity pass runs before any coercion — so the rebuild belongs to the object and array branches, not to every `parse`.
|
|
715
818
|
|
|
716
819
|
```ts
|
|
@@ -724,6 +827,25 @@ contract.parse(input) === input // false — an object parse always rebuilds
|
|
|
724
827
|
Object.getPrototypeOf(contract.parse(input)) // null
|
|
725
828
|
```
|
|
726
829
|
|
|
830
|
+
### Shape-valued declarations
|
|
831
|
+
|
|
832
|
+
For `rawShape`, a structure refusal names its nested schema keyword or member in `context.path`, starting with `schema`. For example, an invalid type under the second union arm reports `['schema', 'anyOf', '1', 'type']`. A non-record root reports `['schema']`. Reflection failures that prevent locating a member remain at the containing schema boundary.
|
|
833
|
+
|
|
834
|
+
Use `shapeShape` for a field that carries a contract declaration. Its guard accepts exactly a successful `validateShape`, including the depth and expansion limits. Each call reads the value again. Its parser returns that same value by identity, fills no defaults, and never compiles the supplied declaration. Structural validation accepts a default whose inner guard refuses it; compilation of that declaration still refuses it. A legal `RegExp` pattern remains valid.
|
|
835
|
+
|
|
836
|
+
The emitted schema is shallow: an object with a required `category` enum and explicit `additionalProperties: true`. It over-approximates declarations whose JSON projection preserves their own enumerable data. A value with a different projection or no JSON projection falls outside this schema: a non-enumerable category, `toJSON` returning `42` or `{}`, a proxy omitting its own keys, or an extra member containing a BigInt or a cycle can pass `is` and `validateShape` while producing no JSON instance this schema accepts. Structural acceptance is unchanged. The default description states that limit and that `is` decides; a caller description replaces it. This schema cannot teach a language model to author a complete nested declaration. Both schema conversion modes preserve its shallow acceptance, and `rawShape` accepts it.
|
|
837
|
+
|
|
838
|
+
The public surface includes these declarations:
|
|
839
|
+
|
|
840
|
+
| Name | Kind | Signature | Summary |
|
|
841
|
+
| ------------------- | --------- | --------------------------------------------- | ---------------------------------------------------------------------------- |
|
|
842
|
+
| `shapeShape` | function | `(options?: ShapeShapeOptions) => ShapeShape` | Builds a `ShapeShape`. |
|
|
843
|
+
| `ShapeShape` | interface | `{ category, description? }` | Describes a value that is a structurally valid contract declaration. |
|
|
844
|
+
| `ShapeShapeOptions` | interface | `{ description? }` | Configures the description of a shape-valued declaration. |
|
|
845
|
+
| `SHAPE_FIELDS` | const | `Readonly<Record<string, readonly string[]>>` | Lists the fields recognized for every contract declaration category, frozen. |
|
|
846
|
+
|
|
847
|
+
The category table drives both validation and the emitted category enum. `Infer` of a `ShapeShape` is `ContractShape`; refusal diagnostics use the `shape` fault kind at the containing field.
|
|
848
|
+
|
|
727
849
|
## Methods
|
|
728
850
|
|
|
729
851
|
The public methods of each behavioral interface — one table per type, keyed by its backticked name, every call-signature member listed (its `readonly` data members, `schema` / `is`, stay in the Surface row above). `ContractInterface` has no implementing class: `createContract` builds it as a plain object whose shape conforms to the interface exactly, so the table below is its per-instance surface (`AGENTS.md`, Documentation contract).
|
|
@@ -771,7 +893,7 @@ because neither measured one. `validateShape` reads it to apply `COMPILE_NODE_LI
|
|
|
771
893
|
|
|
772
894
|
##### Diagnostic precedence and reentry
|
|
773
895
|
|
|
774
|
-
|
|
896
|
+
Cycle detection precedes depth measurement. A cyclic graph reports structure before cycle; an acyclic graph reports depth before structure and domain diagnoses. Within a string declaration the fixed domain order is invalid `min`, invalid `max`, flagged pattern, then contradictory range.
|
|
775
897
|
|
|
776
898
|
Every nested and outer call inside an active pass shares the exact reentry poison object, which carries no own cause. Cleanup restores idle state, so a later independent call observes the source again. A failed pass, including a caught-reentry-poisoned outer pass, leaves `expansion` undefined, and a later successful pass replaces it.
|
|
777
899
|
|
|
@@ -794,9 +916,9 @@ These invariants hold across `src/core` ↔ `contract.md`:
|
|
|
794
916
|
2. **Guards are total.** `.claude/rules/patterns.md` § Validation and contracts requires it: every guard takes one `unknown`, returns a `boolean` type predicate, and **never throws** — adversarial input yields `false`. The only deferral is `lazyOf`, whose thunk runs per call; `whereOf` / `lazyOf` / `transformOf` contain a callback throw as a non-match through the core `attempt` helper.
|
|
795
917
|
3. **Parse ↔ guard soundness.** `.claude/rules/patterns.md` § Validation and contracts mandates it. On readable input, each standalone leaf parser (`parseString`, …) pairs with the guard for its **output type**: a guard-valid input is returned unchanged (by identity, never rejected), and every non-`undefined` output satisfies that type guard. Coercion of otherwise-invalid inputs is a bonus on top, not a violation; a failed required read is a coded refusal, not an `undefined` parse result. The **compiled** contract goes further: `compileParser` (and thus `createContract`'s `parse`) re-applies every leaf REFINEMENT after coercion through the same combinators (`stringOf` / `boundsOf`) `compileGuard` uses — so a non-`undefined` `contract.parse` always satisfies `contract.is`, refinements (`min` / `max` / `pattern`) included. That law is about parse's OUTPUT. Its readable INPUT domain is deliberately wider than `is` — a coercible leaf, a closed object's extra key — and no amount of shared machinery closes that gap, because it is the feature. What cannot drift is `compileGuard` and `compileParser`, both compiled from one snapshot; what differs, permanently, is the set each accepts (see Domains). `audit` is the report for the stricter of the two.
|
|
796
918
|
4. **Types are the source of truth.** `Guard`, `Parser`, and the guard-shape types are declared in [`types.ts`](../src/core/types.ts) first; guards and parsers conform to them, never the reverse.
|
|
797
|
-
5. **`createContract` validates before it compiles.** The declaration is owned once and that OWNED graph is validated once, before any artifact is built, and the same is true at every `compile*` entry — a malformed shape (a structural child that is not a shape, `min > max`, a non-finite number bound, an empty integer range, an empty literal/union, a literal shape holding a non-finite number value, an `optionalShape` placed anywhere but a direct object-property value, a structural cycle, or nesting past `COMPILE_DEPTH_LIMIT`) throws a coded `ContractError` immediately instead of silently producing a wrong guard, parser, schema, audit, report, or generator. `optionalShape` is legal in exactly one position: as the value of an object property. ONE population, one rule set: ownership refuses a malformed structural slot, scalar field, or bound rather than normalizing it, so the graph the gate judges is the graph the artifacts compile from — there is no earlier reading of the caller's live source that is validated and then thrown away.
|
|
919
|
+
5. **`createContract` validates before it compiles.** The declaration is owned once and that OWNED graph is validated once, or was already by the builders that made it, before any artifact is built, and the same is true at every `compile*` entry — a malformed shape (a structural child that is not a shape, `min > max`, a non-finite number bound, an empty integer range, an empty literal/union, a literal shape holding a non-finite number value, an `optionalShape` placed anywhere but a direct object-property value, a `default` under a union or on a property of an open object, a `default` its inner shape refuses, a structural cycle, or nesting past `COMPILE_DEPTH_LIMIT`) throws a coded `ContractError` immediately instead of silently producing a wrong guard, parser, schema, audit, report, or generator. `optionalShape` is legal in exactly one position: as the value of an object property. ONE population, one rule set: ownership refuses a malformed structural slot, scalar field, or bound rather than normalizing it, so the graph the gate judges is the graph the artifacts compile from — there is no earlier reading of the caller's live source that is validated and then thrown away.
|
|
798
920
|
6. **DOC ↔ SOURCE method bijection.** Every behavioral interface's `## Methods` table lists exactly its public methods (call-signature members) — exhaustive, both directions — and each implementing class exposes the same public methods, no more (`AGENTS.md`, Documentation contract). A renamed / added / removed method breaks the gate until the table is reconciled.
|
|
799
|
-
7. **Compilation owns its input.** A builder freezes what it produces, copies what you hand it, and re-exposes a `pattern` as a fresh frozen `RegExp` per read; every `compile*` entry point
|
|
921
|
+
7. **Compilation owns its input.** A builder freezes what it produces, copies what you hand it, and re-exposes a `pattern` as a fresh frozen `RegExp` per read; every `compile*` entry point and `createContract` take their argument through `ownShape`, which always returns an independent clone, unless the builders made all of it, when it is frozen and validated all the way down already and nothing a caller holds can change it. Ownership refuses a non-record node before discriminant normalization and retains only primitive-string RegExp `source` / `flags` pairs. A shape you keep a reference to can never change what an already-compiled artifact does, and a compiled `schema` is deeply frozen — so the six outputs stay in lockstep with the declaration they came from, lockstep meaning derived from that one snapshot rather than agreeing on which values to accept.
|
|
800
922
|
|
|
801
923
|
The `parseJSON` / `parseJSONAs` text boundary is **lazy by default**: keep the result unknown, validate only a supplied shape, or read fields individually. Whole-tree work is explicit through the shipped `isJSONValue`, fixed-cap `isBoundedJSONValue` / `isBoundedJSONRecord`, `parseJSONValue`, `cloneJSONValue`, and record-root `cloneJSONRecord`; `JSONRecord` is the reusable record-root type. A dedicated `JSONArray` alias and broad deep JSON-Schema validators / `JSONSchemaDefinition` remain omitted; compose any narrower contract a consumer actually needs.
|
|
802
924
|
|
|
@@ -1162,7 +1284,7 @@ contract.explain({ id: 'nope', name: 'x', role: 'y' })
|
|
|
1162
1284
|
- [`tests/src/core/SchemaCloner.test.ts`](../tests/src/core/SchemaCloner.test.ts) — direct root-imported `SchemaCloner`/interface contract: inert construction, exact prototype, terminal replay and zero rereads, caught/uncaught reentry precedence, independent instances, exact provenance and paths, enumerable-string observation, aliases/cycles, shells/order/freeze/depth, atomic settlement while every terminal-path intrinsic is redirected, and success/failure working-state release with a real collection control.
|
|
1163
1285
|
- [`tests/src/core/cloners.test.ts`](../tests/src/core/cloners.test.ts) — eager JSON and schema behavior plus the shape function boundaries: fresh `cloneShape` roots/failures/source observation, overload/runtime and compact class parity, and genuine `ownShape` frozen-failure precedence and independent-success behavior.
|
|
1164
1286
|
- [`tests/src/core/combinators.test.ts`](../tests/src/core/combinators.test.ts) — guard-combinator semantics, refinement composition, exact records/tuples, open-object and member-carrying-callable controls including the prototype-accessor proof, lazy recursion, thrown-value containment, dense array membership, genuine foreign-pattern ownership/flag stripping, and the unreadable-brand versus proxy/forgery diagnostic split.
|
|
1165
|
-
- [`tests/src/core/ContractCompiler.test.ts`](../tests/src/core/ContractCompiler.test.ts) — the lazy engine's own contract: the pinned getters, construction that observes nothing, per-root replay identity and the frozen bundle, one entry per unique node, terminal adoption/reentry poison, release, the shared-edge staircase and the bounded expansion refusal,
|
|
1287
|
+
- [`tests/src/core/ContractCompiler.test.ts`](../tests/src/core/ContractCompiler.test.ts) — the lazy engine's own contract: the pinned getters, construction that observes nothing, per-root replay identity and the frozen bundle, one entry per unique node, terminal adoption/reentry poison, release, the shared-edge staircase and the bounded expansion refusal, door-versus-getter agreement across every shape category, and field defaults: the fill at both absence sites, a distinct tree per parse for every inner category, nested defaults, the emitted keyword, the JSON round trip, the refusal at every door with its path, and what `generate` does with a default.
|
|
1166
1288
|
- [`tests/src/core/compilers.test.ts`](../tests/src/core/compilers.test.ts) — the `compile*` exports and `createContract`, including schema/guard/parser/generator behavior, the public depth boundary, strict auditor and coercive reporter fault semantics, hostile input containment, and contract wiring. It binds genuine foreign patterns through every compiler, exact captured property populations read twice (including refusal of an invalid captured population, and the absence of any further caller read), and the validator/cloner/compiler/contract forgery matrix. The explicit declaration matrix covers non-record roots and children, object-valued RegExp `source` / `flags`, present raw `undefined` populations, and flagged-pattern refusal, with plain/null-prototype/foreign records plus valid local/foreign/accessor patterns as controls; no generated message inventory or source pin participates.
|
|
1167
1289
|
- [`tests/src/core/errors.test.ts`](../tests/src/core/errors.test.ts) — cross-copy `ContractError` recognition through distinct source-module instances, including transparent-wrapper, stripped-brand subclass, plain-error, complete self-branded forgery, and undeclared-code controls.
|
|
1168
1290
|
- [`tests/src/core/factories.test.ts`](../tests/src/core/factories.test.ts) — the entity door `createContract` driven directly: an eager bundle whose roots are data properties carrying one artifact identity through destructuring and through a spread, the generic overload and the widened-`ContractShape` overload each answering at every root, a malformed declaration refused at the call itself with the authoring door's own diagnosis rather than a rewrap, and `is` agreeing with `compileGuard` over a corpus that exercises each verdict.
|
|
@@ -1170,12 +1292,12 @@ contract.explain({ id: 'nope', name: 'x', role: 'y' })
|
|
|
1170
1292
|
- [`tests/src/core/SampleInferer.test.ts`](../tests/src/core/SampleInferer.test.ts) — the interned `SampleInferer` reached by relative source path: the ordered row-prefix memo served to a slot collecting the same rows in the same order and missed by slots whose rows arrive in a different order or at a different remaining depth, no memo carried across two walks over one row list, and the closed flag reaching the emitted opening.
|
|
1171
1293
|
- [`tests/src/core/ValueInferer.test.ts`](../tests/src/core/ValueInferer.test.ts) — the interned `ValueInferer` reached by relative source path and driven with the depth and breadth budgets its door sanitizes away: a container root widened at every budget not above zero, a leaf root classified without consulting the budget, one level of descent on a fractional budget, descent past the cap the door imposes, and a negative breadth budget that samples no member and forces the record open.
|
|
1172
1294
|
- [`tests/src/core/inferers.test.ts`](../tests/src/core/inferers.test.ts) — schema inference, unification, depth/breadth limits, deterministic sampling, readable widening, hostile traversal, sparse populations, and canonical serialization, including direct/public/consumer failed-prototype classification plus readable record/exotic controls.
|
|
1173
|
-
- [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — the one explicit layout exception: genuine public cross-module composition, seeded generation/guard/parser/schema round trips,
|
|
1295
|
+
- [`tests/src/core/integration.test.ts`](../tests/src/core/integration.test.ts) — the one explicit layout exception: genuine public cross-module composition, seeded generation/guard/parser/schema round trips, guard-combinator integration, and the three laws over shapes that carry a default, curated and seeded. Unit and type-carrier behavior remains in mirrored suites.
|
|
1174
1296
|
- [`tests/src/core/parsers.test.ts`](../tests/src/core/parsers.test.ts) — coercion, field parsing, parse/guard soundness, reflected dense arrays, record/JSON boundaries, and coded unreadable-input refusal.
|
|
1175
|
-
- [`tests/src/core/SchemaShaper.test.ts`](../tests/src/core/SchemaShaper.test.ts) — the interned `SchemaShaper` reached by relative source path: a node two branches share converted exactly once and re-converted at a different remaining depth, a cyclic schema widened at the re-encountered node instead of recursed into,
|
|
1176
|
-
- [`tests/src/core/ShapeCloner.test.ts`](../tests/src/core/ShapeCloner.test.ts) — canonical direct root-imported `ShapeCloner`/interface contract: inert source-only construction, exact prototype, terminal success/failure replay without rereads, caught/uncaught/replacement reentry poison, independent instances, exact error provenance and foreign containment, plain-record branding before discriminant observation, category/field/population observation and ordering, sharing/paths/optional placement, raw-schema composition, completed-root validation before deferred fidelity, primitive RegExp scalar ownership without coercion, freezing/mutation isolation, iterative depth refusal, atomic settlement while every terminal-path intrinsic is redirected,
|
|
1177
|
-
- [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — builders and `Infer`/`InferMutable`, with explicit `BUILDER_CASES` option positions and public keys driving real plain/frozen/null-prototype and hostile get/has/descriptor/own-key/revoked controls. It also covers caller/post-clone raw-schema populations and diagnostic precedence, genuine foreign-pattern ownership and flag policy, inverse schema construction,
|
|
1178
|
-
- [`tests/src/core/ShapeValidator.test.ts`](../tests/src/core/ShapeValidator.test.ts) — direct public validator behavior: inert construction, repeatable live passes and reentry poison, precedence, depth/cycle handling, dense populations, raw-schema keywords, the present-`undefined` rule — an own raw-population member holding `undefined` is a present declaration rather than an absent one, so it is validated —
|
|
1297
|
+
- [`tests/src/core/SchemaShaper.test.ts`](../tests/src/core/SchemaShaper.test.ts) — the interned `SchemaShaper` reached by relative source path: a node two branches share converted exactly once and re-converted at a different remaining depth, a cyclic schema widened at the re-encountered node instead of recursed into, an unreadable keyword's read failure escaping the walk carrying no door name of its own, the lenient `default` carry and drop tables with a shared node beside and below a union, the foreign-schema table with an authored expectation per row, the `oneOf`, boolean-arm, `enum`, `nullable`, `patternProperties`, `prefixItems`, typeless-`properties`, two-arm-null, carried-description, and large-schema rows, and the strict refusal and annotation tables with the path each row names.
|
|
1298
|
+
- [`tests/src/core/ShapeCloner.test.ts`](../tests/src/core/ShapeCloner.test.ts) — canonical direct root-imported `ShapeCloner`/interface contract: inert source-only construction, exact prototype, terminal success/failure replay without rereads, caught/uncaught/replacement reentry poison, independent instances, exact error provenance and foreign containment, plain-record branding before discriminant observation, category/field/population observation and ordering, sharing/paths/optional placement, raw-schema composition, completed-root validation before deferred fidelity, primitive RegExp scalar ownership without coercion, freezing/mutation isolation, iterative depth refusal, atomic settlement while every terminal-path intrinsic is redirected, symmetric terminal working-state release with a real three-reference collection control, and the frozen owned copy of a `default` with its non-JSON, present-`undefined`, accessor, and inherited refusals.
|
|
1299
|
+
- [`tests/src/core/shapers.test.ts`](../tests/src/core/shapers.test.ts) — builders and `Infer`/`InferMutable`, with explicit `BUILDER_CASES` option positions and public keys driving real plain/frozen/null-prototype and hostile get/has/descriptor/own-key/revoked controls. It also covers caller/post-clone raw-schema populations and diagnostic precedence, genuine foreign-pattern ownership and flag policy, inverse schema construction, inference depth/breadth behavior, and the `optionalShape` `default` option, without reading or parsing project source.
|
|
1300
|
+
- [`tests/src/core/ShapeValidator.test.ts`](../tests/src/core/ShapeValidator.test.ts) — direct public validator behavior: inert construction, repeatable live passes and reentry poison, precedence, depth/cycle handling, dense populations, raw-schema keywords, the present-`undefined` rule — an own raw-population member holding `undefined` is a present declaration rather than an absent one, so it is validated — flagged-pattern observation/order/repair, default placement over every route to a shared node, and the raw `default` keyword.
|
|
1179
1301
|
- [`tests/src/core/validators.test.ts`](../tests/src/core/validators.test.ts) — primitive, non-negative numeric, structural, bounded-JSON, and JSON/record/RegExp guards; genuine `node:vm` record/RegExp values; depth-versus-validity and sequential-observation controls; zero-read duck/tag/accessor/proxy/revoked opposites; hostile-value totality; and parser/guard soundness corpora.
|
|
1180
1302
|
|
|
1181
1303
|
## See also
|