@orkestrel/contract 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -5
- package/dist/src/core/index.cjs +1870 -611
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +696 -143
- package/dist/src/core/index.d.ts +696 -143
- package/dist/src/core/index.js +1855 -611
- package/dist/src/core/index.js.map +1 -1
- package/package.json +14 -15
package/dist/src/core/index.d.ts
CHANGED
|
@@ -62,6 +62,7 @@ export declare interface ArrayShape<S extends ContractShape = ContractShape> {
|
|
|
62
62
|
* @param items - The element shape
|
|
63
63
|
* @param options - Optional length bounds and `description`
|
|
64
64
|
* @returns An array shape
|
|
65
|
+
* @throws {ContractError} When a present bound is not a non-negative safe integer
|
|
65
66
|
*
|
|
66
67
|
* @example
|
|
67
68
|
* ```ts
|
|
@@ -82,13 +83,14 @@ export declare interface ArrayShapeOptions {
|
|
|
82
83
|
* a throw escape.
|
|
83
84
|
*
|
|
84
85
|
* @remarks
|
|
85
|
-
* The
|
|
86
|
+
* The sanctioned never-throw boundary for the guards (AGENTS §14). The
|
|
86
87
|
* `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
|
|
87
88
|
* callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
|
|
88
89
|
* `boolean`. This converts a throwing callback into a `Failure` so the
|
|
89
90
|
* surrounding guard can treat it as a non-match instead of propagating the
|
|
90
91
|
* exception, written once and shared rather than copy-pasted as ad-hoc
|
|
91
|
-
* `try`/`catch`.
|
|
92
|
+
* `try`/`catch`. The sole hand-written exception is {@link isContractError},
|
|
93
|
+
* whose local boundary avoids an `errors` → `helpers` dependency inversion.
|
|
92
94
|
*
|
|
93
95
|
* @param callback - The callback to invoke with no arguments
|
|
94
96
|
* @returns A `Success` carrying the return value, or a `Failure` carrying the
|
|
@@ -159,7 +161,7 @@ export declare function boundsOf(min?: number, max?: number): Guard<number>;
|
|
|
159
161
|
* `properties` (when a record) contributes one child shape per own key, capped
|
|
160
162
|
* at {@link INFER_BREADTH_LIMIT}; a key is wrapped in {@link optionalShape}
|
|
161
163
|
* unless it appears as a string entry of `required`. A property whose value is
|
|
162
|
-
* not itself a record widens to {@link
|
|
164
|
+
* not itself a record widens to {@link rawShape}. `additionalProperties`:
|
|
163
165
|
* `false` closes the object; a record value recurses into it (`objectShape`
|
|
164
166
|
* validates extras against that shape); anything else — `true`, absent, or
|
|
165
167
|
* malformed — leaves the object OPEN (`true`), matching JSON Schema's own
|
|
@@ -169,8 +171,8 @@ export declare function boundsOf(min?: number, max?: number): Guard<number>;
|
|
|
169
171
|
* keys than {@link INFER_BREADTH_LIMIT}, the schema's own
|
|
170
172
|
* `additionalProperties` is OVERRIDDEN and forced to `true` (fully open) —
|
|
171
173
|
* a dropped key's value could otherwise fail a `false` or record-valued rest
|
|
172
|
-
* shape it was never checked against — mirroring
|
|
173
|
-
*
|
|
174
|
+
* shape it was never checked against — mirroring {@link inferObject}'s
|
|
175
|
+
* partial-key handling in `inferers.ts`. The accumulator uses a
|
|
174
176
|
* null-prototype record so a property literally named `__proto__` becomes an
|
|
175
177
|
* own data key rather than mutating the prototype, mirroring
|
|
176
178
|
* {@link inferObject} (inferers.ts).
|
|
@@ -222,7 +224,7 @@ export declare function buildObjectShape(schema: JSONSchema, depth: number, visi
|
|
|
222
224
|
* record-entry count is at or under {@link INFER_BREADTH_LIMIT}; OVER the
|
|
223
225
|
* limit, building a subset union would be strictly narrower than the
|
|
224
226
|
* schema's full union (a value matching only a dropped variant would be
|
|
225
|
-
* wrongly rejected), so the whole node widens to {@link
|
|
227
|
+
* wrongly rejected), so the whole node widens to {@link rawShape} instead
|
|
226
228
|
* of sampling a subset.
|
|
227
229
|
* 3. `anyOf` — identically, via {@link unionShape}.
|
|
228
230
|
* 4. `type: 'string'` / `'number'` / `'integer'` / `'boolean'` / `'null'` —
|
|
@@ -232,14 +234,16 @@ export declare function buildObjectShape(schema: JSONSchema, depth: number, visi
|
|
|
232
234
|
* (e.g. `minimum: 1.5, maximum: 1.6`) — the same emptiness `validateShape`
|
|
233
235
|
* rejects — so the result is always a valid shape.
|
|
234
236
|
* 5. `type: 'array'` — an {@link arrayShape} whose element shape recurses into
|
|
235
|
-
* a record-valued `items` (widening to {@link
|
|
237
|
+
* a record-valued `items` (widening to {@link rawShape} otherwise), with
|
|
236
238
|
* bounds from `minItems` / `maxItems`.
|
|
237
239
|
* 6. `type: 'object'`, OR no `type` / `enum` / `oneOf` / `anyOf` but a
|
|
238
240
|
* record-valued `properties` — delegates to {@link buildObjectShape}.
|
|
239
241
|
* 7. Everything else — an empty schema, an unrecognized/absent `type`,
|
|
240
242
|
* exhausted depth/breadth, or an attempt failure — widens to
|
|
241
|
-
* {@link
|
|
242
|
-
*
|
|
243
|
+
* {@link rawShape}, whose guard accepts every defined value and whose
|
|
244
|
+
* emitted schema is the same `{}` (plus `description`) the node carried.
|
|
245
|
+
* This is the exact inverse of `{}`, JSON Schema's accept-anything schema,
|
|
246
|
+
* and where the inferers themselves bottom out at their own limits.
|
|
243
247
|
*
|
|
244
248
|
* `format` and `pattern` are NEVER read into the compiled shape — `format` is
|
|
245
249
|
* annotation-only and `pattern` compiling an attacker-supplied string into a
|
|
@@ -247,7 +251,7 @@ export declare function buildObjectShape(schema: JSONSchema, depth: number, visi
|
|
|
247
251
|
* the produced shape's `description` option.
|
|
248
252
|
*
|
|
249
253
|
* @param schema - The schema node to convert
|
|
250
|
-
* @param depth - Remaining descent budget (0 halts recursion with `
|
|
254
|
+
* @param depth - Remaining descent budget (0 halts recursion with `rawShape({})`)
|
|
251
255
|
* @param visited - The ancestor set guarding against cycles — recursion
|
|
252
256
|
* state owned by the {@link schemaToShape} entry point; passing a shared or
|
|
253
257
|
* pre-populated `WeakSet` changes cycle-detection behavior and is not
|
|
@@ -269,26 +273,196 @@ export declare function buildObjectShape(schema: JSONSchema, depth: number, visi
|
|
|
269
273
|
export declare function buildShapeFromNode(schema: JSONSchema, depth: number, visited: WeakSet<object>, memo: WeakMap<object, Map<number, ContractShape>>): ContractShape;
|
|
270
274
|
|
|
271
275
|
/**
|
|
272
|
-
*
|
|
276
|
+
* Encode one value as a deterministic, key-sorted JSON string — the recursive
|
|
277
|
+
* spine of {@link canonicalStringify}.
|
|
278
|
+
*
|
|
279
|
+
* @remarks
|
|
280
|
+
* Arrays keep their element order; records sort their own keys before encoding,
|
|
281
|
+
* recursively at every nesting level. Every other value is encoded by
|
|
282
|
+
* `JSON.stringify`, so `NaN` / `±Infinity` collapse to `'null'` and `-0`
|
|
283
|
+
* encodes as `'0'` — the same lossy-but-deterministic mapping real JSON makes.
|
|
284
|
+
*
|
|
285
|
+
* Returns `undefined` for anything JSON cannot encode: `undefined` itself, a
|
|
286
|
+
* function, a symbol, an array hole, or a cyclic back-edge to an ancestor. A
|
|
287
|
+
* container carrying such a member is itself un-encodable and returns
|
|
288
|
+
* `undefined` too, so the result is either a faithful encoding of the WHOLE
|
|
289
|
+
* value or nothing — a partially-encoded key is never emitted. Traversal is NOT
|
|
290
|
+
* contained here: a hostile getter or `Proxy` trap throws through to
|
|
291
|
+
* {@link canonicalStringify}, which owns the single {@link attempt} boundary
|
|
292
|
+
* for the walk.
|
|
293
|
+
*
|
|
294
|
+
* @param value - The value to encode
|
|
295
|
+
* @param ancestors - Objects on the active traversal path, guarding cycles
|
|
296
|
+
* @returns The deterministic encoding, or `undefined` when JSON cannot encode
|
|
297
|
+
* `value`
|
|
298
|
+
*
|
|
299
|
+
* @example
|
|
300
|
+
* ```ts
|
|
301
|
+
* canonicalizeValue({ b: 1, a: 2 }, new WeakSet()) // '{"a":2,"b":1}'
|
|
302
|
+
* canonicalizeValue(undefined, new WeakSet()) // undefined
|
|
303
|
+
* ```
|
|
304
|
+
*/
|
|
305
|
+
export declare function canonicalizeValue(value: unknown, ancestors: WeakSet<object>): string | undefined;
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Render a value as a deterministic, key-sorted JSON string — or `undefined`
|
|
309
|
+
* when it has no faithful JSON encoding.
|
|
273
310
|
*
|
|
274
311
|
* @remarks
|
|
275
312
|
* The stable-stringify backing {@link unifySchemas}'s de-duplication and
|
|
276
313
|
* ordering: unlike `JSON.stringify`, object keys are sorted before encoding
|
|
277
314
|
* (recursively, at every nesting level), so two structurally-equal
|
|
278
315
|
* `JSONSchema` fragments built independently always canonicalize to the same
|
|
279
|
-
* string. Pure ECMAScript
|
|
316
|
+
* string. Pure host-independent ECMAScript with no environment-specific imports.
|
|
317
|
+
*
|
|
318
|
+
* TOTAL: it NEVER throws, for any input. It returns `undefined` — never a
|
|
319
|
+
* partial or invalid encoding — for every value JSON cannot faithfully encode:
|
|
320
|
+
*
|
|
321
|
+
* - `undefined` itself, a function, a symbol, or an array hole (JSON encodes
|
|
322
|
+
* none of them), at the top level or anywhere inside a container;
|
|
323
|
+
* - a bigint (`JSON.stringify` throws on one);
|
|
324
|
+
* - cyclic input, tracked with the same ancestor-{@link WeakSet} discipline
|
|
325
|
+
* {@link inferArray} / {@link inferObject} use, so a shared (non-cyclic)
|
|
326
|
+
* reference reached twice through different paths still encodes;
|
|
327
|
+
* - hostile traversal — a throwing own-getter, a hostile `ownKeys` trap, or a
|
|
328
|
+
* revoked `Proxy` anywhere in the value — contained via {@link attempt}.
|
|
329
|
+
*
|
|
330
|
+
* A caller therefore treats `undefined` as "this value has no canonical key",
|
|
331
|
+
* never as an encoding: see {@link unifySchemas} (an un-keyed member cannot
|
|
332
|
+
* participate in de-duplication or ordering) and {@link inferPrimitiveEnum} (an
|
|
333
|
+
* un-keyed member makes the slot enum-ineligible).
|
|
280
334
|
*
|
|
281
335
|
* @param value - The value to canonicalize (a `JSONSchema` fragment, or any
|
|
282
336
|
* nested piece of one)
|
|
283
|
-
* @returns A deterministic string encoding of `value`
|
|
337
|
+
* @returns A deterministic string encoding of `value`, or `undefined` when JSON
|
|
338
|
+
* cannot encode it
|
|
284
339
|
*
|
|
285
340
|
* @example
|
|
286
341
|
* ```ts
|
|
287
342
|
* canonicalStringify({ type: 'object', properties: {} }) ===
|
|
288
343
|
* canonicalStringify({ properties: {}, type: 'object' }) // true
|
|
344
|
+
* canonicalStringify(Number.NaN) // 'null' — JSON.stringify semantics
|
|
345
|
+
* canonicalStringify(undefined) // undefined
|
|
346
|
+
* canonicalStringify(cyclicValue) // undefined
|
|
347
|
+
* ```
|
|
348
|
+
*/
|
|
349
|
+
export declare function canonicalStringify(value: unknown): string | undefined;
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Deep-clone an exact JSON object record into an owned frozen snapshot.
|
|
353
|
+
*
|
|
354
|
+
* @remarks
|
|
355
|
+
* Adds a record-root boundary to {@link cloneJSONValue}. The output is a
|
|
356
|
+
* deeply frozen null-prototype record, and repeated noncyclic aliases are
|
|
357
|
+
* duplicated as independent JSON tree branches.
|
|
358
|
+
*
|
|
359
|
+
* @param value - The unknown record value to validate and snapshot
|
|
360
|
+
* @returns A deeply cloned and frozen JSON record
|
|
361
|
+
* @throws {ContractError} When the root is not a record, nested data is inexact, or traversal fails
|
|
362
|
+
*
|
|
363
|
+
* @example
|
|
364
|
+
* ```ts
|
|
365
|
+
* cloneJSONRecord({ attempt: 1 }) // frozen null-prototype record
|
|
366
|
+
* ```
|
|
367
|
+
*/
|
|
368
|
+
export declare function cloneJSONRecord(value: unknown): JSONRecord;
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Deep-clone exact JSON data into an owned frozen snapshot.
|
|
372
|
+
*
|
|
373
|
+
* @remarks
|
|
374
|
+
* Traverses iteratively so deeply nested input cannot exhaust the call stack.
|
|
375
|
+
* Repeated noncyclic aliases are duplicated because JSON persistence represents
|
|
376
|
+
* a tree, while a structural back-edge on the active path is rejected as a
|
|
377
|
+
* cycle. Arrays are rebuilt as standard dense arrays and records as
|
|
378
|
+
* null-prototype objects; every produced node is frozen after its children are
|
|
379
|
+
* wired. Array keys must be exactly `length` plus every canonical index.
|
|
380
|
+
* Writable and configurable index flags are normalized rather than treated as
|
|
381
|
+
* JSON data, so frozen arrays remain valid. Property descriptors are inspected
|
|
382
|
+
* without reading values through accessors, and every hostile reflective
|
|
383
|
+
* operation is contained before a new clone-coded error is exposed.
|
|
384
|
+
*
|
|
385
|
+
* @param value - The unknown value to validate and snapshot
|
|
386
|
+
* @returns The primitive unchanged, or a deeply cloned and frozen JSON graph
|
|
387
|
+
* @throws {ContractError} When the value is not exact acyclic JSON data or traversal fails
|
|
388
|
+
*
|
|
389
|
+
* @example
|
|
390
|
+
* ```ts
|
|
391
|
+
* const source = { settings: { enabled: true } }
|
|
392
|
+
* const clone = cloneJSONValue(source)
|
|
393
|
+
* source.settings.enabled = false
|
|
394
|
+
* clone // { settings: { enabled: true } }
|
|
395
|
+
* ```
|
|
396
|
+
*/
|
|
397
|
+
export declare function cloneJSONValue(value: unknown): JSONValue;
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Deep-clone a JSON Schema graph into an owned frozen snapshot.
|
|
401
|
+
*
|
|
402
|
+
* @remarks
|
|
403
|
+
* Walks arrays and records iteratively with a memo, preserving shared
|
|
404
|
+
* references and closing cyclic edges onto their cloned nodes. Primitive
|
|
405
|
+
* values and own enumerable string-keyed edges are copied; record nodes use
|
|
406
|
+
* null prototypes, arrays retain only their intrinsic array prototype, and
|
|
407
|
+
* every produced object is frozen after its edges are wired. Hostile traversal
|
|
408
|
+
* throws a clone-coded {@link ContractError}, never a caller-owned raw error.
|
|
409
|
+
*
|
|
410
|
+
* @param schema - The JSON Schema graph to snapshot
|
|
411
|
+
* @returns A deeply cloned and frozen JSON Schema graph
|
|
412
|
+
* @throws {ContractError} When hostile schema traversal prevents ownership
|
|
413
|
+
*
|
|
414
|
+
* @example
|
|
415
|
+
* ```ts
|
|
416
|
+
* const child = { type: 'string' }
|
|
417
|
+
* const clone = cloneSchema({ anyOf: [child, child] })
|
|
418
|
+
* clone.anyOf?.[0] === clone.anyOf?.[1] // true
|
|
419
|
+
* ```
|
|
420
|
+
*/
|
|
421
|
+
export declare function cloneSchema(schema: JSONSchema): JSONSchema;
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Deep-clone a contract shape graph into an owned frozen snapshot.
|
|
425
|
+
*
|
|
426
|
+
* @remarks
|
|
427
|
+
* Uses an explicit memo to preserve shared-child identity and close cyclic
|
|
428
|
+
* edges onto their cloned nodes. Shape-node shells are created iteratively,
|
|
429
|
+
* then their structural edges are wired and their copied collections frozen.
|
|
430
|
+
* String patterns are captured by source and flags behind an enumerable
|
|
431
|
+
* accessor that returns a fresh frozen zero-state `RegExp` on every read.
|
|
432
|
+
* A raw schema delegates to {@link cloneSchema}; every shape-graph read is
|
|
433
|
+
* contained, so hostile traversal throws only a clone-coded
|
|
434
|
+
* {@link ContractError}.
|
|
435
|
+
*
|
|
436
|
+
* @param shape - The contract shape graph to snapshot
|
|
437
|
+
* @returns A deeply cloned and frozen shape graph
|
|
438
|
+
* @throws {ContractError} When hostile shape or raw-schema traversal prevents ownership
|
|
439
|
+
*
|
|
440
|
+
* @example
|
|
441
|
+
* ```ts
|
|
442
|
+
* const child = arrayShape(stringShape())
|
|
443
|
+
* const clone = cloneShape(objectShape({ first: child, second: child }))
|
|
444
|
+
* clone.type === 'object' && clone.properties.first === clone.properties.second // true
|
|
445
|
+
* ```
|
|
446
|
+
*/
|
|
447
|
+
export declare function cloneShape(shape: StringShape): StringShape;
|
|
448
|
+
|
|
449
|
+
export declare function cloneShape(shape: ContractShape): ContractShape;
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* The maximum supported nesting depth of a compiled contract shape, frozen.
|
|
453
|
+
*
|
|
454
|
+
* @remarks
|
|
455
|
+
* {@link validateShape} rejects the next level with a depth-coded
|
|
456
|
+
* {@link ContractError} before recursive artifact compilation begins, so a
|
|
457
|
+
* finite but pathologically deep developer-authored shape fails predictably
|
|
458
|
+
* instead of reaching the JavaScript call-stack limit.
|
|
459
|
+
*
|
|
460
|
+
* @example
|
|
461
|
+
* ```ts
|
|
462
|
+
* COMPILE_DEPTH_LIMIT // 512
|
|
289
463
|
* ```
|
|
290
464
|
*/
|
|
291
|
-
export declare
|
|
465
|
+
export declare const COMPILE_DEPTH_LIMIT = 512;
|
|
292
466
|
|
|
293
467
|
/**
|
|
294
468
|
* Compile a {@link ContractShape} into a deterministic seed value.
|
|
@@ -296,18 +470,25 @@ export declare function canonicalStringify(value: unknown): string;
|
|
|
296
470
|
* @remarks
|
|
297
471
|
* The same shape and the same `random` source always produce the same value, so
|
|
298
472
|
* seed data is reproducible. Defaults to a {@link seededRandom} source seeded
|
|
299
|
-
* from the wall clock when none is supplied.
|
|
300
|
-
*
|
|
301
|
-
*
|
|
302
|
-
*
|
|
303
|
-
*
|
|
473
|
+
* from the wall clock when none is supplied. Shape-generation failures throw a
|
|
474
|
+
* {@link ContractError} with code `'generate'`; {@link drawRandom} failures use
|
|
475
|
+
* code `'random'` and retain the consuming shape category in context.
|
|
476
|
+
* Failures include a degenerate empty `literalShape` / `unionShape`, a
|
|
477
|
+
* pattern-constrained `stringShape` whose generated sample cannot satisfy the
|
|
478
|
+
* pattern, an invalid random sample, and a `rawShape` whose arbitrary embedded
|
|
479
|
+
* schema cannot be auto-generated. {@link validateShapeDepth} iteratively
|
|
480
|
+
* rejects excessive nesting or cycles before recursive generation begins.
|
|
481
|
+
* `createContract` runs
|
|
304
482
|
* {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /
|
|
305
483
|
* bounded shape is normally caught there; these throws remain here as defense
|
|
306
|
-
* for standalone `compileGenerator` use.
|
|
484
|
+
* for standalone `compileGenerator` use. Union candidates are bounded by
|
|
485
|
+
* {@link GENERATION_ATTEMPT_LIMIT} and accepted only when they satisfy the
|
|
486
|
+
* union's compiled guard.
|
|
307
487
|
*
|
|
308
488
|
* @param shape - The shape to generate from
|
|
309
489
|
* @param random - A seeded random source (defaults to `seededRandom(Date.now())`)
|
|
310
490
|
* @returns A value matching the shape
|
|
491
|
+
* @throws {ContractError} When the shape or random source cannot produce a valid value
|
|
311
492
|
*
|
|
312
493
|
* @example
|
|
313
494
|
* ```ts
|
|
@@ -322,10 +503,14 @@ export declare function compileGenerator(shape: ContractShape, random?: RandomFu
|
|
|
322
503
|
* Compile a {@link ContractShape} into a runtime type guard.
|
|
323
504
|
*
|
|
324
505
|
* @remarks
|
|
325
|
-
* Reuses the combinators
|
|
326
|
-
*
|
|
327
|
-
*
|
|
328
|
-
*
|
|
506
|
+
* Reuses the combinators for structural and refined shapes, including
|
|
507
|
+
* {@link literalOf} for SameValueZero literal matching. Compiled object shapes
|
|
508
|
+
* observe own enumerable string keys through {@link enumerableKeys}, matching
|
|
509
|
+
* their parser, reporter, and inference view for both open and closed objects.
|
|
510
|
+
* Like every guard it is total — it never throws (AGENTS §14). The shape is
|
|
511
|
+
* taken through {@link ownShape} first, so an unfrozen caller-owned graph
|
|
512
|
+
* compiles from a snapshot. {@link validateShapeDepth} iteratively rejects
|
|
513
|
+
* excessive nesting or cycles before recursive guard compilation begins.
|
|
329
514
|
*
|
|
330
515
|
* @param shape - The shape to compile
|
|
331
516
|
* @returns A guard narrowing to the shape's inferred type
|
|
@@ -350,11 +535,16 @@ export declare function compileGuard(shape: ContractShape): Guard<unknown>;
|
|
|
350
535
|
* unchanged, otherwise the first variant that both parses and guards wins.
|
|
351
536
|
*
|
|
352
537
|
* After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same
|
|
353
|
-
* combinators `compileGuard` uses — `stringOf` for a string's length/pattern
|
|
354
|
-
* `boundsOf` for a number's value and an array's length
|
|
355
|
-
*
|
|
356
|
-
* soundness (AGENTS §14): a
|
|
357
|
-
* `is`, refinements
|
|
538
|
+
* combinators `compileGuard` uses — `stringOf` for a string's length/pattern,
|
|
539
|
+
* `boundsOf` for a number's value and an array's length, and {@link literalOf}
|
|
540
|
+
* for literal membership — so a value that coerces but violates a bound parses
|
|
541
|
+
* to `undefined`. The result is full parse↔guard soundness (AGENTS §14): a
|
|
542
|
+
* non-`undefined` parse always satisfies the contract's `is`, refinements
|
|
543
|
+
* included. Object presence and extra-key processing use the same
|
|
544
|
+
* own-enumerable-string snapshot as the guard, reporter, and inference. The
|
|
545
|
+
* shape is taken through {@link ownShape} first, so an unfrozen caller-owned
|
|
546
|
+
* graph compiles from a snapshot. {@link validateShapeDepth} iteratively
|
|
547
|
+
* rejects excessive nesting or cycles before recursive parser compilation.
|
|
358
548
|
*
|
|
359
549
|
* @param shape - The shape to compile
|
|
360
550
|
* @returns A parser yielding the shape's inferred type or `undefined`
|
|
@@ -393,7 +583,8 @@ export declare function compileParser(shape: ContractShape): Parser<unknown>;
|
|
|
393
583
|
* open object with a constraining `additionalProperties` shape recurses extras
|
|
394
584
|
* against it instead. A hostile getter or throwing `Proxy` trap is contained
|
|
395
585
|
* via {@link attempt} and surfaces as a single top-level type fault, never a
|
|
396
|
-
* throw (AGENTS §14).
|
|
586
|
+
* throw (AGENTS §14). {@link validateShapeDepth} iteratively rejects excessive
|
|
587
|
+
* shape nesting or cycles before recursive reporting begins.
|
|
397
588
|
*
|
|
398
589
|
* @param shape - The shape to report against
|
|
399
590
|
* @param value - The value to check
|
|
@@ -416,7 +607,10 @@ export declare function compileReporter(shape: ContractShape, value: unknown, pa
|
|
|
416
607
|
* @remarks
|
|
417
608
|
* Object shapes emit `additionalProperties: false` (unless opened) and list only
|
|
418
609
|
* required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
|
|
419
|
-
* 'null' }`.
|
|
610
|
+
* 'null' }`. The result is an owned deeply frozen graph; raw schemas are cloned
|
|
611
|
+
* rather than retained by reference. Emission only — it never inspects a
|
|
612
|
+
* runtime value. {@link validateShapeDepth} iteratively rejects excessive
|
|
613
|
+
* nesting or cycles before recursive emission begins.
|
|
420
614
|
*
|
|
421
615
|
* @param shape - The shape to compile
|
|
422
616
|
* @returns The emitted JSON Schema
|
|
@@ -441,14 +635,86 @@ export declare function compileSchema(shape: ContractShape): JSONSchema;
|
|
|
441
635
|
*/
|
|
442
636
|
export declare function complementOf<TBase, TExcluded extends TBase>(base: Guard<TBase>, excluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded)): Guard<Exclude<TBase, TExcluded>>;
|
|
443
637
|
|
|
638
|
+
/** Machine-readable category carried by a {@link ContractError}. */
|
|
639
|
+
export declare type ContractCode =
|
|
640
|
+
/** Identifies a bound contract error. */
|
|
641
|
+
'bound'
|
|
642
|
+
/** Identifies a range contract error. */
|
|
643
|
+
| 'range'
|
|
644
|
+
/** Identifies an empty-value contract error. */
|
|
645
|
+
| 'empty'
|
|
646
|
+
/** Identifies a placement contract error. */
|
|
647
|
+
| 'placement'
|
|
648
|
+
/** Identifies a literal contract error. */
|
|
649
|
+
| 'literal'
|
|
650
|
+
/** Identifies a cycle contract error. */
|
|
651
|
+
| 'cycle'
|
|
652
|
+
/** Identifies a pattern contract error. */
|
|
653
|
+
| 'pattern'
|
|
654
|
+
/** Identifies a generation contract error. */
|
|
655
|
+
| 'generate'
|
|
656
|
+
/** Identifies a random-source contract error. */
|
|
657
|
+
| 'random'
|
|
658
|
+
/** Identifies an owned-clone contract error. */
|
|
659
|
+
| 'clone'
|
|
660
|
+
/** Identifies a compilation-depth contract error. */
|
|
661
|
+
| 'depth';
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Error carrying a machine-readable contract category and optional context.
|
|
665
|
+
*
|
|
666
|
+
* @example
|
|
667
|
+
* ```ts
|
|
668
|
+
* const error = new ContractError('Minimum exceeds maximum', {
|
|
669
|
+
* code: 'range',
|
|
670
|
+
* context: { path: ['properties', 'age'] },
|
|
671
|
+
* })
|
|
672
|
+
* ```
|
|
673
|
+
*/
|
|
674
|
+
export declare class ContractError extends Error {
|
|
675
|
+
readonly name = "ContractError";
|
|
676
|
+
readonly code: ContractCode;
|
|
677
|
+
readonly context: ContractErrorContext | undefined;
|
|
678
|
+
/**
|
|
679
|
+
* Create a contract error.
|
|
680
|
+
*
|
|
681
|
+
* @param message - Human-readable error description
|
|
682
|
+
* @param options - Machine-readable category, optional context, and optional cause
|
|
683
|
+
*/
|
|
684
|
+
constructor(message: string, options: ContractErrorOptions);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Optional structured details carried by a {@link ContractError}. */
|
|
688
|
+
export declare interface ContractErrorContext {
|
|
689
|
+
/** Location associated with the error. */
|
|
690
|
+
readonly path?: FieldPath;
|
|
691
|
+
/** Shape label associated with the error. */
|
|
692
|
+
readonly shape?: string;
|
|
693
|
+
/** Numeric or textual limit associated with the error. */
|
|
694
|
+
readonly limit?: number | string;
|
|
695
|
+
/** Received-value description associated with the error. */
|
|
696
|
+
readonly received?: string;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/** Construction options for a {@link ContractError}. */
|
|
700
|
+
export declare interface ContractErrorOptions {
|
|
701
|
+
/** Machine-readable error category. */
|
|
702
|
+
readonly code: ContractCode;
|
|
703
|
+
/** Optional structured error details. */
|
|
704
|
+
readonly context?: ContractErrorContext;
|
|
705
|
+
/** Optional originating thrown value. */
|
|
706
|
+
readonly cause?: unknown;
|
|
707
|
+
}
|
|
708
|
+
|
|
444
709
|
/**
|
|
445
|
-
* A compiled contract — the
|
|
710
|
+
* A compiled contract — the five lockstep outputs derived from one shape.
|
|
446
711
|
*
|
|
447
712
|
* @remarks
|
|
448
713
|
* Built by `createContract`: `is` narrows, `parse` coerces (returning the typed
|
|
449
|
-
* value or `undefined`), `schema` is
|
|
450
|
-
*
|
|
451
|
-
*
|
|
714
|
+
* value or `undefined`), `schema` is an owned deeply frozen emitted JSON
|
|
715
|
+
* Schema, `explain` reports the structured faults behind a failed `parse`, and
|
|
716
|
+
* `generate` produces deterministic seed data from a {@link RandomFunction}
|
|
717
|
+
* (defaulting to a wall-clock-seeded source when none is supplied).
|
|
452
718
|
*/
|
|
453
719
|
export declare interface ContractInterface<T> {
|
|
454
720
|
readonly schema: JSONSchema;
|
|
@@ -476,22 +742,25 @@ export declare interface ContractInterface<T> {
|
|
|
476
742
|
*
|
|
477
743
|
* @remarks
|
|
478
744
|
* A discriminated union keyed on `type`. Shapes nest (an `ArrayShape` holds an
|
|
479
|
-
* element shape, an `ObjectShape` a map of them)
|
|
480
|
-
*
|
|
745
|
+
* element shape, an `ObjectShape` a map of them). {@link validateShape}
|
|
746
|
+
* enforces an acyclic graph within {@link COMPILE_DEPTH_LIMIT}.
|
|
481
747
|
*/
|
|
482
748
|
export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape;
|
|
483
749
|
|
|
484
750
|
/**
|
|
485
|
-
* Compile a {@link ContractShape} into a {@link ContractInterface} — the
|
|
751
|
+
* Compile a {@link ContractShape} into a {@link ContractInterface} — the five
|
|
486
752
|
* lockstep outputs from one declaration.
|
|
487
753
|
*
|
|
488
754
|
* @remarks
|
|
489
755
|
* Runs {@link validateShape} first — a malformed shape throws immediately
|
|
490
|
-
* rather than compiling into a silently-wrong contract (AGENTS §12).
|
|
491
|
-
*
|
|
492
|
-
*
|
|
756
|
+
* rather than compiling into a silently-wrong contract (AGENTS §12). It always
|
|
757
|
+
* takes its own {@link cloneShape} snapshot — never merely a frozen node's word
|
|
758
|
+
* — and hands that same graph to every artifact compiler.
|
|
759
|
+
* Then it precompiles the deeply frozen owned schema, guard, and parser once;
|
|
760
|
+
* `generate` walks the
|
|
761
|
+
* snapshot per call with the supplied random source, and `explain` compiles the
|
|
493
762
|
* diagnostic report via {@link compileReporter} at zero added compile-time cost
|
|
494
|
-
* (it re-walks the
|
|
763
|
+
* (it re-walks the snapshot per call, exactly like `generate`).
|
|
495
764
|
*
|
|
496
765
|
* @param shape - The shape to compile
|
|
497
766
|
* @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`
|
|
@@ -514,10 +783,11 @@ export declare function createContract(shape: ContractShape): ContractInterface<
|
|
|
514
783
|
*
|
|
515
784
|
* @remarks
|
|
516
785
|
* Total and pure. Either keyword is used only when it is a non-negative
|
|
517
|
-
* integer (`
|
|
518
|
-
* number, `NaN`, `Infinity`, a fraction
|
|
519
|
-
* bounds are present and `min` exceeds `max`,
|
|
520
|
-
* (an unbounded shape is always a legal widening
|
|
786
|
+
* safe integer (`Number.isSafeInteger` + `>= 0`); a malformed value (a string,
|
|
787
|
+
* a negative number, `NaN`, `Infinity`, a fraction, or an unsafe integer) is
|
|
788
|
+
* dropped as if absent. When both bounds are present and `min` exceeds `max`,
|
|
789
|
+
* the PAIR is dropped entirely (an unbounded shape is always a legal widening
|
|
790
|
+
* of a contradictory schema).
|
|
521
791
|
*
|
|
522
792
|
* @param min - The raw `minLength` / `minItems` keyword value
|
|
523
793
|
* @param max - The raw `maxLength` / `maxItems` keyword value
|
|
@@ -560,6 +830,41 @@ export declare function deriveRangeBounds(min: unknown, max: unknown): {
|
|
|
560
830
|
readonly max?: number;
|
|
561
831
|
};
|
|
562
832
|
|
|
833
|
+
/**
|
|
834
|
+
* Draw and validate one generator random sample.
|
|
835
|
+
*
|
|
836
|
+
* @param random - The caller-supplied random source
|
|
837
|
+
* @param shape - The shape category consuming the sample
|
|
838
|
+
* @returns A finite sample in `[0, 1)`
|
|
839
|
+
* @throws {ContractError} When the source throws or returns outside `[0, 1)`
|
|
840
|
+
*
|
|
841
|
+
* @example
|
|
842
|
+
* ```ts
|
|
843
|
+
* drawRandom(() => 0.5, 'number') // 0.5
|
|
844
|
+
* ```
|
|
845
|
+
*/
|
|
846
|
+
export declare function drawRandom(random: RandomFunction, shape: string): number;
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Snapshot an object's own enumerable string keys through a total boundary.
|
|
850
|
+
*
|
|
851
|
+
* @remarks
|
|
852
|
+
* This is the package-wide runtime property view used by compiled object
|
|
853
|
+
* guards, parsers, reporters, schema inference, and owned schema cloning. It
|
|
854
|
+
* matches the object-key view serialized by `JSON.stringify`: inherited,
|
|
855
|
+
* symbol, and non-enumerable properties are excluded. A hostile Proxy trap
|
|
856
|
+
* returns `undefined` rather than escaping.
|
|
857
|
+
*
|
|
858
|
+
* @param value - The object whose keys to snapshot
|
|
859
|
+
* @returns A frozen owned key list, or `undefined` when enumeration throws
|
|
860
|
+
*
|
|
861
|
+
* @example
|
|
862
|
+
* ```ts
|
|
863
|
+
* enumerableKeys({ visible: 1 }) // ['visible']
|
|
864
|
+
* ```
|
|
865
|
+
*/
|
|
866
|
+
export declare function enumerableKeys(value: object): readonly string[] | undefined;
|
|
867
|
+
|
|
563
868
|
/**
|
|
564
869
|
* Count the enumerable own-symbol keys on a value.
|
|
565
870
|
*
|
|
@@ -706,9 +1011,40 @@ export declare type FromGuards<G extends GuardsShape> = Readonly<{
|
|
|
706
1011
|
[K in keyof G]: GuardType<G[K]>;
|
|
707
1012
|
}>;
|
|
708
1013
|
|
|
1014
|
+
/**
|
|
1015
|
+
* The maximum number of candidate-generation attempts for a constrained
|
|
1016
|
+
* generated value, frozen.
|
|
1017
|
+
*
|
|
1018
|
+
* @remarks
|
|
1019
|
+
* Provides one deterministic work bound for generators that must retry a
|
|
1020
|
+
* candidate against a contract constraint.
|
|
1021
|
+
*
|
|
1022
|
+
* @example
|
|
1023
|
+
* ```ts
|
|
1024
|
+
* GENERATION_ATTEMPT_LIMIT // 32
|
|
1025
|
+
* ```
|
|
1026
|
+
*/
|
|
1027
|
+
export declare const GENERATION_ATTEMPT_LIMIT = 32;
|
|
1028
|
+
|
|
709
1029
|
/** A runtime type guard: returns `true` when `value` satisfies `T` and narrows it. */
|
|
710
1030
|
export declare type Guard<T> = (value: unknown) => value is T;
|
|
711
1031
|
|
|
1032
|
+
/**
|
|
1033
|
+
* The maximum number of active {@link lazyOf} invocations for one lazy guard,
|
|
1034
|
+
* frozen.
|
|
1035
|
+
*
|
|
1036
|
+
* @remarks
|
|
1037
|
+
* Bounds explicitly recursive guards before the JavaScript call stack becomes
|
|
1038
|
+
* the limiting mechanism. An invocation beyond this depth returns `false`, and
|
|
1039
|
+
* the counter unwinds after every contained guard call.
|
|
1040
|
+
*
|
|
1041
|
+
* @example
|
|
1042
|
+
* ```ts
|
|
1043
|
+
* GUARD_DEPTH_LIMIT // 512
|
|
1044
|
+
* ```
|
|
1045
|
+
*/
|
|
1046
|
+
export declare const GUARD_DEPTH_LIMIT = 512;
|
|
1047
|
+
|
|
712
1048
|
/**
|
|
713
1049
|
* A mapping of string keys to guards.
|
|
714
1050
|
*
|
|
@@ -720,6 +1056,19 @@ export declare type GuardsShape = Readonly<Record<string, Guard<unknown>>>;
|
|
|
720
1056
|
/** Extract the guarded type `T` from a `Guard<T>`. */
|
|
721
1057
|
export declare type GuardType<G> = G extends Guard<infer T> ? T : never;
|
|
722
1058
|
|
|
1059
|
+
/**
|
|
1060
|
+
* Invoke a predicate through the sanctioned never-throw boundary.
|
|
1061
|
+
*
|
|
1062
|
+
* @param callback - The predicate to invoke with no arguments
|
|
1063
|
+
* @returns `true` only when the callback returns the boolean value `true`
|
|
1064
|
+
*
|
|
1065
|
+
* @example
|
|
1066
|
+
* ```ts
|
|
1067
|
+
* holds(() => value instanceof Widget) // false when inspection throws
|
|
1068
|
+
* ```
|
|
1069
|
+
*/
|
|
1070
|
+
export declare function holds(callback: () => boolean): boolean;
|
|
1071
|
+
|
|
723
1072
|
/**
|
|
724
1073
|
* Infer the static TypeScript type a {@link ContractShape} describes.
|
|
725
1074
|
*
|
|
@@ -904,22 +1253,28 @@ export declare type InferObject<P extends Readonly<Record<string, ContractShape>
|
|
|
904
1253
|
* properties.
|
|
905
1254
|
*
|
|
906
1255
|
* @remarks
|
|
907
|
-
* Own enumerable string keys via
|
|
908
|
-
* deterministic output, capped at `breadth`.
|
|
909
|
-
*
|
|
910
|
-
*
|
|
911
|
-
*
|
|
912
|
-
*
|
|
913
|
-
*
|
|
914
|
-
*
|
|
915
|
-
*
|
|
916
|
-
*
|
|
917
|
-
*
|
|
918
|
-
*
|
|
919
|
-
*
|
|
920
|
-
*
|
|
921
|
-
*
|
|
922
|
-
*
|
|
1256
|
+
* Own enumerable string keys via {@link enumerableKeys}, sorted
|
|
1257
|
+
* lexicographically for deterministic output, capped at `breadth`. This is the
|
|
1258
|
+
* same property view compiled object guards, parsers, and reporters use. Each
|
|
1259
|
+
* property value is read through {@link attempt} so a hostile getter cannot
|
|
1260
|
+
* escape as a thrown error; a property whose value is `undefined` is DROPPED
|
|
1261
|
+
* — JSON encodes no such property (`JSON.stringify({ a: undefined })` is
|
|
1262
|
+
* `'{}'`), so it contributes neither a `properties` entry nor a `required`
|
|
1263
|
+
* entry. Every other present key is required (single-value mode).
|
|
1264
|
+
*
|
|
1265
|
+
* Emits `additionalProperties: false` when `closed`, `true` otherwise —
|
|
1266
|
+
* mirroring {@link compileSchema}'s object-emission convention — EXCEPT when
|
|
1267
|
+
* the sampled key list no longer describes every key `value` actually carries,
|
|
1268
|
+
* which happens two ways: the own-key list exceeds `breadth` (truncation), or
|
|
1269
|
+
* a key was dropped for holding `undefined`. Either way `additionalProperties`
|
|
1270
|
+
* is forced to `true` regardless of `closed`, because a CLOSED schema built
|
|
1271
|
+
* from an incomplete key list would reject the very object it was inferred
|
|
1272
|
+
* from (`recordOf` rejects any own key the shape does not declare).
|
|
1273
|
+
*
|
|
1274
|
+
* Depth exhaustion or a cyclic re-encounter of `value` both yield `{}`. A
|
|
1275
|
+
* same-object re-inference at the same remaining `depth` is served from `memo`
|
|
1276
|
+
* instead of recomputing (guards a shared-reference DAG against exponential
|
|
1277
|
+
* blowup).
|
|
923
1278
|
*
|
|
924
1279
|
* @param value - The record to infer from
|
|
925
1280
|
* @param depth - Remaining descent budget
|
|
@@ -984,6 +1339,12 @@ export declare type InferOpenIndex<A extends boolean | ContractShape> = [A] exte
|
|
|
984
1339
|
* `literalShape` emission. Members are sorted by canonical key for
|
|
985
1340
|
* deterministic output.
|
|
986
1341
|
*
|
|
1342
|
+
* A member {@link canonicalStringify} cannot key has no identity to
|
|
1343
|
+
* de-duplicate against, so the whole slot is enum-INELIGIBLE and returns
|
|
1344
|
+
* `undefined` — widening to the caller's bare `type` rather than emitting an
|
|
1345
|
+
* `enum` that might silently omit a value. (A string or finite number always
|
|
1346
|
+
* canonicalizes, so this only guards the total contract.)
|
|
1347
|
+
*
|
|
987
1348
|
* @param values - The collected slot values
|
|
988
1349
|
* @param limit - The maximum distinct-value count before giving up
|
|
989
1350
|
* @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
|
|
@@ -1013,14 +1374,20 @@ export declare function inferPrimitiveEnum(values: readonly unknown[], limit: nu
|
|
|
1013
1374
|
* {@link inferArray}, this path carries no `visited` `WeakSet` — a value
|
|
1014
1375
|
* shared by reference across multiple sample rows is legitimate (not a
|
|
1015
1376
|
* cycle back to an ancestor), so termination on cyclic row data relies on
|
|
1016
|
-
* the decrementing `depth` budget alone.
|
|
1017
|
-
*
|
|
1018
|
-
* forced to `true` regardless of `closed`
|
|
1019
|
-
*
|
|
1020
|
-
*
|
|
1021
|
-
*
|
|
1022
|
-
*
|
|
1023
|
-
*
|
|
1377
|
+
* the decrementing `depth` budget alone.
|
|
1378
|
+
*
|
|
1379
|
+
* `additionalProperties` is forced to `true` regardless of `closed` whenever
|
|
1380
|
+
* the declared key list stops describing every key the rows carry — the same
|
|
1381
|
+
* incomplete-sample-opens-the-schema rule {@link inferObject} applies, so a
|
|
1382
|
+
* closed schema never rejects the very rows it was inferred from. That happens
|
|
1383
|
+
* three ways: the union of sample keys exceeds `breadth` (truncation); a
|
|
1384
|
+
* hostile getter defeats a key's value walk (which drops that key for ALL
|
|
1385
|
+
* rows — a deliberate all-or-nothing scope, not a per-row partial failure);
|
|
1386
|
+
* or some row carries the key as an own property holding `undefined`, which
|
|
1387
|
+
* JSON encodes as no property at all, so the key is dropped rather than
|
|
1388
|
+
* declared with a shape that row would fail. When the KEY walk itself fails
|
|
1389
|
+
* (a hostile `ownKeys` trap on any row), nothing is known and the whole slot
|
|
1390
|
+
* widens to `{}`.
|
|
1024
1391
|
*
|
|
1025
1392
|
* @param samples - The plain-record samples
|
|
1026
1393
|
* @param depth - Remaining descent budget
|
|
@@ -1083,13 +1450,21 @@ export declare type InferUnion<V extends readonly ContractShape[]> = V extends r
|
|
|
1083
1450
|
* @remarks
|
|
1084
1451
|
* Total: never throws, and terminates on cyclic input via `visited`. Leaf
|
|
1085
1452
|
* classification order: `null`, boolean, integer (`Number.isInteger`
|
|
1086
|
-
* semantics — `-0` counts), finite non-integer number,
|
|
1087
|
-
* (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
|
|
1453
|
+
* semantics — `-0` counts), finite non-integer number, string (gaining a
|
|
1088
1454
|
* `format` keyword when `format` is on and {@link stringToFormat} matches),
|
|
1089
1455
|
* array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
|
|
1090
|
-
* plus `format: 'date-time'` when `format` is on); everything else
|
|
1091
|
-
* (
|
|
1092
|
-
* `Map` / `Set`
|
|
1456
|
+
* plus `format: 'date-time'` when `format` is on); everything else — a
|
|
1457
|
+
* NON-FINITE number (`NaN` / `±Infinity`), a function, a symbol, a bigint,
|
|
1458
|
+
* `undefined`, and other non-plain objects such as `Map` / `Set` — is the
|
|
1459
|
+
* empty accept-anything schema `{}`.
|
|
1460
|
+
*
|
|
1461
|
+
* A non-finite number bottoms out with the other JSON-inexpressible values on
|
|
1462
|
+
* purpose: JSON carries no `NaN` / `±Infinity` (`JSON.stringify(Number.NaN)`
|
|
1463
|
+
* is `'null'`), so `{ type: 'number' }` would ASSERT something a JSON Schema
|
|
1464
|
+
* validator rejects — and the shape {@link schemaToShape} builds from it would
|
|
1465
|
+
* reject the very sample it was inferred from. `{}` is the truthful
|
|
1466
|
+
* description, and it inverts to an accept-anything shape, keeping
|
|
1467
|
+
* `compileGuard(schemaToShape(valueToSchema(v)))(v)` true.
|
|
1093
1468
|
*
|
|
1094
1469
|
* @param value - The value to classify
|
|
1095
1470
|
* @param depth - Remaining descent budget (0 halts recursion with `{}`)
|
|
@@ -1133,6 +1508,7 @@ export declare function instanceOf<C extends abstract new (...args: never) => ob
|
|
|
1133
1508
|
*
|
|
1134
1509
|
* @param options - Optional bounds and `description` (no `integer` key)
|
|
1135
1510
|
* @returns An integer number shape
|
|
1511
|
+
* @throws {ContractError} When a present bound is not finite
|
|
1136
1512
|
*/
|
|
1137
1513
|
export declare function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape;
|
|
1138
1514
|
|
|
@@ -1284,6 +1660,20 @@ export declare function isBoolean(value: unknown): value is boolean;
|
|
|
1284
1660
|
*/
|
|
1285
1661
|
export declare function isConstructor(value: unknown): value is AnyConstructor<object>;
|
|
1286
1662
|
|
|
1663
|
+
/**
|
|
1664
|
+
* Determine whether an unknown value is a {@link ContractError}.
|
|
1665
|
+
*
|
|
1666
|
+
* @param value - The value to inspect
|
|
1667
|
+
* @returns `true` only when the value is a `ContractError`
|
|
1668
|
+
*
|
|
1669
|
+
* @example
|
|
1670
|
+
* ```ts
|
|
1671
|
+
* isContractError(new ContractError('Invalid shape', { code: 'placement' })) // true
|
|
1672
|
+
* isContractError(new Error('Invalid shape')) // false
|
|
1673
|
+
* ```
|
|
1674
|
+
*/
|
|
1675
|
+
export declare function isContractError(value: unknown): value is ContractError;
|
|
1676
|
+
|
|
1287
1677
|
/** Determine whether a value is a `DataView`.
|
|
1288
1678
|
*
|
|
1289
1679
|
* @example
|
|
@@ -1446,7 +1836,7 @@ export declare function isGeneratorFunction(value: unknown): value is (...args:
|
|
|
1446
1836
|
* NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
|
|
1447
1837
|
* revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
|
|
1448
1838
|
* `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
|
|
1449
|
-
* wraps the check in {@link
|
|
1839
|
+
* wraps the check in {@link holds} (see ./helpers.js) so any such throw
|
|
1450
1840
|
* yields `false` instead of escaping.
|
|
1451
1841
|
*
|
|
1452
1842
|
* @param value - The value to test
|
|
@@ -1552,7 +1942,7 @@ export declare function isJSONPrimitive(value: unknown): value is JSONPrimitive;
|
|
|
1552
1942
|
* Total guard: never throws, returns `false` for cycles, functions, `Date`
|
|
1553
1943
|
* instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
|
|
1554
1944
|
* are walked with an ancestor set so recursive input fails instead of hanging.
|
|
1555
|
-
* The whole walk runs inside `
|
|
1945
|
+
* The whole walk runs inside `holds` (AGENTS §14): a hostile getter on a
|
|
1556
1946
|
* record property, or a revoked `Proxy` anywhere in the structure, is caught
|
|
1557
1947
|
* and yields `false` instead of escaping as a thrown error.
|
|
1558
1948
|
*
|
|
@@ -1746,7 +2136,7 @@ export declare function isPromiseLike<T = unknown>(value: unknown): value is Pro
|
|
|
1746
2136
|
* above `null`. Arrays and class instances are still rejected: an array's
|
|
1747
2137
|
* prototype chain runs through `Array.prototype` before `null`, and a class
|
|
1748
2138
|
* instance's runs through the class's own prototype. The whole body runs
|
|
1749
|
-
* inside `
|
|
2139
|
+
* inside `holds` (AGENTS §14) so a revoked `Proxy` or a hostile
|
|
1750
2140
|
* `getPrototypeOf` trap cannot escape as a thrown error.
|
|
1751
2141
|
*
|
|
1752
2142
|
* @example
|
|
@@ -1955,22 +2345,6 @@ export declare function isZeroArgAsyncGenerator(value: unknown): value is () =>
|
|
|
1955
2345
|
*/
|
|
1956
2346
|
export declare function isZeroArgGenerator(value: unknown): value is () => Generator<unknown, unknown, unknown>;
|
|
1957
2347
|
|
|
1958
|
-
/**
|
|
1959
|
-
* Build a guard that accepts any iterable whose every element satisfies
|
|
1960
|
-
* `elementGuard`.
|
|
1961
|
-
*
|
|
1962
|
-
* @example
|
|
1963
|
-
* ```ts
|
|
1964
|
-
* const isNumberIterable = iterableOf(isNumber)
|
|
1965
|
-
* isNumberIterable([1, 2, 3]) // true
|
|
1966
|
-
* isNumberIterable(new Set([1, 2])) // true
|
|
1967
|
-
* isNumberIterable([1, 'two']) // false
|
|
1968
|
-
* ```
|
|
1969
|
-
*/
|
|
1970
|
-
export declare function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>;
|
|
1971
|
-
|
|
1972
|
-
export declare function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>;
|
|
1973
|
-
|
|
1974
2348
|
/**
|
|
1975
2349
|
* The seven standard JSON Schema `type` names, frozen.
|
|
1976
2350
|
*
|
|
@@ -1996,12 +2370,30 @@ export declare const JSON_SCHEMA_TYPES: readonly JSONSchemaType[];
|
|
|
1996
2370
|
*
|
|
1997
2371
|
* @remarks
|
|
1998
2372
|
* The recursive {@link JSONValue} tree type is shipped for consumers that need a
|
|
1999
|
-
* reusable JSON metadata contract.
|
|
2000
|
-
*
|
|
2001
|
-
*
|
|
2373
|
+
* reusable JSON metadata contract. {@link JSONRecord} supplies the record-root
|
|
2374
|
+
* contract needed by persistence and metadata consumers; a dedicated
|
|
2375
|
+
* `JSONArray` alias remains unnecessary because `readonly JSONValue[]` already
|
|
2376
|
+
* expresses that branch directly.
|
|
2002
2377
|
*/
|
|
2003
2378
|
export declare type JSONPrimitive = string | number | boolean | null;
|
|
2004
2379
|
|
|
2380
|
+
/**
|
|
2381
|
+
* A readonly string-keyed JSON object record.
|
|
2382
|
+
*
|
|
2383
|
+
* @remarks
|
|
2384
|
+
* Runtime ownership through
|
|
2385
|
+
* {@link import('./cloners.js').cloneJSONRecord} normalizes records to a frozen
|
|
2386
|
+
* null-prototype object after exact descriptor validation.
|
|
2387
|
+
*
|
|
2388
|
+
* @example
|
|
2389
|
+
* ```ts
|
|
2390
|
+
* const metadata: JSONRecord = { attempt: 1, labels: ['ready'] }
|
|
2391
|
+
* ```
|
|
2392
|
+
*/
|
|
2393
|
+
export declare type JSONRecord = {
|
|
2394
|
+
readonly [key: string]: JSONValue;
|
|
2395
|
+
};
|
|
2396
|
+
|
|
2005
2397
|
/**
|
|
2006
2398
|
* A JSON Schema fragment — the subset of keywords the contract compiler emits
|
|
2007
2399
|
* and {@link RawShape} embeds.
|
|
@@ -2012,8 +2404,9 @@ export declare type JSONPrimitive = string | number | boolean | null;
|
|
|
2012
2404
|
* emitted by the {@link stringToFormat} / {@link samplesToFormat} inference
|
|
2013
2405
|
* heuristics (`valueToSchema` / `samplesToSchema`), never by `compileSchema`.
|
|
2014
2406
|
* Recursive via `items` / `properties` / `additionalProperties` / `anyOf` /
|
|
2015
|
-
* `oneOf
|
|
2016
|
-
*
|
|
2407
|
+
* `oneOf`. {@link createContract} owns and validates developer-authored shape
|
|
2408
|
+
* graphs; cycles and nesting past {@link COMPILE_DEPTH_LIMIT} fail with a coded
|
|
2409
|
+
* {@link ContractError} before artifact compilation.
|
|
2017
2410
|
*/
|
|
2018
2411
|
export declare interface JSONSchema {
|
|
2019
2412
|
readonly type?: JSONSchemaType;
|
|
@@ -2046,7 +2439,7 @@ export declare type JSONSchemaType = 'null' | 'boolean' | 'object' | 'array' | '
|
|
|
2046
2439
|
* functions, `NaN`, and `±Infinity`); the parser gates through that guard; the
|
|
2047
2440
|
* schema is the empty schema `{}` (matches any JSON instance); the generator
|
|
2048
2441
|
* emits a small deterministic {@link JSONValue}. Unlike {@link RawShape}, whose
|
|
2049
|
-
* guard accepts
|
|
2442
|
+
* guard accepts every defined value, this shape validates that a value is real JSON.
|
|
2050
2443
|
*/
|
|
2051
2444
|
export declare interface JSONShape {
|
|
2052
2445
|
readonly type: 'json';
|
|
@@ -2058,8 +2451,8 @@ export declare interface JSONShape {
|
|
|
2058
2451
|
*
|
|
2059
2452
|
* @remarks
|
|
2060
2453
|
* The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
|
|
2061
|
-
* schema fragment and accepts
|
|
2062
|
-
* that a value is real JSON (via {@link isJSONValue}).
|
|
2454
|
+
* schema fragment and accepts every defined value at runtime, while `jsonShape`
|
|
2455
|
+
* validates that a value is real JSON (via {@link isJSONValue}).
|
|
2063
2456
|
*
|
|
2064
2457
|
* @param options - Optional `description`
|
|
2065
2458
|
* @returns A JSON passthrough shape
|
|
@@ -2089,9 +2482,7 @@ export declare interface JSONShapeOptions {
|
|
|
2089
2482
|
* const value: JSONValue = { nested: [1, 'x', null] }
|
|
2090
2483
|
* ```
|
|
2091
2484
|
*/
|
|
2092
|
-
export declare type JSONValue = JSONPrimitive | readonly JSONValue[] |
|
|
2093
|
-
readonly [key: string]: JSONValue;
|
|
2094
|
-
};
|
|
2485
|
+
export declare type JSONValue = JSONPrimitive | readonly JSONValue[] | JSONRecord;
|
|
2095
2486
|
|
|
2096
2487
|
/**
|
|
2097
2488
|
* Build a guard that accepts values that are own keys of the provided object.
|
|
@@ -2122,10 +2513,10 @@ export declare function keyOf<const O extends Readonly<Record<PropertyKey, unkno
|
|
|
2122
2513
|
* self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
|
|
2123
2514
|
* it resolves to) is contained and reported as a non-match.
|
|
2124
2515
|
*
|
|
2125
|
-
*
|
|
2126
|
-
*
|
|
2127
|
-
*
|
|
2128
|
-
*
|
|
2516
|
+
* Each lazy guard tracks its active invocation depth. An invocation that would
|
|
2517
|
+
* exceed {@link GUARD_DEPTH_LIMIT} returns `false` before resolving `thunk`; the
|
|
2518
|
+
* counter always unwinds after the contained call, so one deep or cyclic input
|
|
2519
|
+
* cannot poison later guard calls.
|
|
2129
2520
|
*
|
|
2130
2521
|
* @example
|
|
2131
2522
|
* ```ts
|
|
@@ -2137,16 +2528,32 @@ export declare function keyOf<const O extends Readonly<Record<PropertyKey, unkno
|
|
|
2137
2528
|
export declare function lazyOf<T>(thunk: () => Guard<T>): Guard<T>;
|
|
2138
2529
|
|
|
2139
2530
|
/**
|
|
2140
|
-
* Build a guard that accepts
|
|
2141
|
-
*
|
|
2531
|
+
* Build a guard that accepts a provided literal primitive using SameValueZero
|
|
2532
|
+
* comparison.
|
|
2533
|
+
*
|
|
2534
|
+
* @remarks
|
|
2535
|
+
* Signed zero compares equal, while `NaN` compares equal to `NaN`. Two call
|
|
2536
|
+
* forms, one meaning: list the literals inline, or hand in one array of them.
|
|
2537
|
+
* The array form exists for a vocabulary that is machine-generated rather than
|
|
2538
|
+
* hand-written — a `literalShape` built from an untrusted schema's `enum`, say
|
|
2539
|
+
* — where spreading a list of tens of thousands of entries would exhaust the
|
|
2540
|
+
* engine's argument limit. `compileGuard` / `compileParser` / `compileReporter`
|
|
2541
|
+
* take the array form for exactly that reason.
|
|
2542
|
+
*
|
|
2543
|
+
* @param literals - The permitted literal primitives, listed inline or as one array
|
|
2544
|
+
* @returns A guard narrowing to the provided literal union
|
|
2142
2545
|
*
|
|
2143
2546
|
* @example
|
|
2144
2547
|
* ```ts
|
|
2145
2548
|
* const isRole = literalOf('admin', 'member', 'guest')
|
|
2146
2549
|
* isRole('admin') // true
|
|
2147
2550
|
* isRole('owner') // false
|
|
2551
|
+
*
|
|
2552
|
+
* const isSameRole = literalOf(['admin', 'member', 'guest']) // the same guard, from an array
|
|
2148
2553
|
* ```
|
|
2149
2554
|
*/
|
|
2555
|
+
export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(literals: Literals): Guard<Literals[number]>;
|
|
2556
|
+
|
|
2150
2557
|
export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(...literals: Literals): Guard<Literals[number]>;
|
|
2151
2558
|
|
|
2152
2559
|
/** A literal shape — accepts exactly one of a fixed set of primitive values. */
|
|
@@ -2171,7 +2578,7 @@ export declare interface LiteralShape<T extends readonly (string | number | bool
|
|
|
2171
2578
|
* const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
|
|
2172
2579
|
* ```
|
|
2173
2580
|
*/
|
|
2174
|
-
export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<T
|
|
2581
|
+
export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<Readonly<T>>;
|
|
2175
2582
|
|
|
2176
2583
|
/** Options for {@link LiteralShape} (via `literalShape`). */
|
|
2177
2584
|
export declare interface LiteralShapeOptions {
|
|
@@ -2193,9 +2600,38 @@ export declare function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): G
|
|
|
2193
2600
|
|
|
2194
2601
|
export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard<ReadonlyMap<unknown, unknown>>;
|
|
2195
2602
|
|
|
2603
|
+
/**
|
|
2604
|
+
* Match an unknown value against the recursive JSON value structure.
|
|
2605
|
+
*
|
|
2606
|
+
* @remarks
|
|
2607
|
+
* The caller-owned ancestor set tracks only the active traversal path, so
|
|
2608
|
+
* cycles fail while shared references across sibling branches remain valid.
|
|
2609
|
+
* The set belongs to one traversal from one entry point; passing a shared or
|
|
2610
|
+
* pre-populated set is unsupported. Arrays and plain records recurse through
|
|
2611
|
+
* this helper; class instances and non-finite numbers are rejected.
|
|
2612
|
+
*
|
|
2613
|
+
* @param entry - The value to inspect
|
|
2614
|
+
* @param ancestors - Objects on the active traversal path
|
|
2615
|
+
* @returns `true` when the value is a cycle-free JSON value
|
|
2616
|
+
*
|
|
2617
|
+
* @example
|
|
2618
|
+
* ```ts
|
|
2619
|
+
* matchesJSONValue({ nested: [1, 'x', null] }, new WeakSet()) // true
|
|
2620
|
+
* matchesJSONValue(Number.NaN, new WeakSet()) // false
|
|
2621
|
+
* ```
|
|
2622
|
+
*/
|
|
2623
|
+
export declare function matchesJSONValue(entry: unknown, ancestors: WeakSet<object>): boolean;
|
|
2624
|
+
|
|
2196
2625
|
/**
|
|
2197
2626
|
* Build a guard that accepts strings matching a regular expression.
|
|
2198
2627
|
*
|
|
2628
|
+
* @remarks
|
|
2629
|
+
* Clones the pattern for the guard and strips the stateful `g` / `y` flags, so
|
|
2630
|
+
* repeated checks are stable and never change the caller's `lastIndex`.
|
|
2631
|
+
*
|
|
2632
|
+
* @param pattern - The regular expression to own and apply
|
|
2633
|
+
* @returns A stateless string guard
|
|
2634
|
+
*
|
|
2199
2635
|
* @example
|
|
2200
2636
|
* ```ts
|
|
2201
2637
|
* const isHex = matchOf(/^[0-9a-f]+$/)
|
|
@@ -2290,6 +2726,7 @@ export declare interface NumberShape {
|
|
|
2290
2726
|
*
|
|
2291
2727
|
* @param options - Optional bounds (`min` / `max`), `integer`, and `description`
|
|
2292
2728
|
* @returns A number shape
|
|
2729
|
+
* @throws {ContractError} When a present bound is not finite
|
|
2293
2730
|
*
|
|
2294
2731
|
* @example
|
|
2295
2732
|
* ```ts
|
|
@@ -2396,7 +2833,7 @@ export declare function omitOf<S extends GuardsShape, K extends ReadonlyArray<ke
|
|
|
2396
2833
|
* // 3.5 passes — matches numberShape only
|
|
2397
2834
|
* ```
|
|
2398
2835
|
*/
|
|
2399
|
-
export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V
|
|
2836
|
+
export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<Readonly<V>>;
|
|
2400
2837
|
|
|
2401
2838
|
/**
|
|
2402
2839
|
* Like {@link FromGuards}, but every key listed in `K` becomes a true optional
|
|
@@ -2461,6 +2898,38 @@ export declare function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B
|
|
|
2461
2898
|
|
|
2462
2899
|
export declare function orOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
|
|
2463
2900
|
|
|
2901
|
+
/**
|
|
2902
|
+
* Take ownership of a contract shape node — the node itself when it is already
|
|
2903
|
+
* frozen, otherwise a {@link cloneShape} snapshot of its graph.
|
|
2904
|
+
*
|
|
2905
|
+
* @remarks
|
|
2906
|
+
* Builder- and `cloneShape`-produced frozen means owned: those nodes have frozen
|
|
2907
|
+
* `properties` / `variants` / `values` collections and pattern accessors that
|
|
2908
|
+
* return fresh frozen snapshots, so they cannot drift under a caller who still
|
|
2909
|
+
* holds an input reference or a previously read pattern. `Object.freeze` on a
|
|
2910
|
+
* hand-authored pattern shape is not an ownership marker because it cannot
|
|
2911
|
+
* protect `RegExp` internal slots; leave that shape unfrozen for this function
|
|
2912
|
+
* to snapshot, or pass it through {@link cloneShape} first.
|
|
2913
|
+
*
|
|
2914
|
+
* Every compiler entry point (`compileSchema` / `compileGuard` /
|
|
2915
|
+
* `compileParser` / `compileGenerator` / `compileReporter`) opens with this
|
|
2916
|
+
* call, and the check applies per node as the recursion descends: a frozen
|
|
2917
|
+
* parent is trusted for its own fields while each child is owned again at its
|
|
2918
|
+
* own level, so a hand-assembled graph that froze only part of itself is still
|
|
2919
|
+
* compiled from owned data.
|
|
2920
|
+
*
|
|
2921
|
+
* @param shape - The contract shape to own
|
|
2922
|
+
* @returns The shape itself when frozen, otherwise a deeply cloned frozen snapshot
|
|
2923
|
+
*
|
|
2924
|
+
* @example
|
|
2925
|
+
* ```ts
|
|
2926
|
+
* const authored = stringShape() // builders freeze
|
|
2927
|
+
* ownShape(authored) === authored // true
|
|
2928
|
+
* ownShape({ type: 'string' }) // a frozen snapshot — the literal is caller-owned
|
|
2929
|
+
* ```
|
|
2930
|
+
*/
|
|
2931
|
+
export declare function ownShape(shape: ContractShape): ContractShape;
|
|
2932
|
+
|
|
2464
2933
|
/**
|
|
2465
2934
|
* Parse an unknown value to an array — the input reference, never cloned —
|
|
2466
2935
|
* optionally guarding every element.
|
|
@@ -2537,14 +3006,16 @@ export declare function parseBooleanField(record: Record<string, unknown>, path:
|
|
|
2537
3006
|
* Parse an unknown value as one of the allowed literal primitives.
|
|
2538
3007
|
*
|
|
2539
3008
|
* @remarks
|
|
2540
|
-
* Pairs with {@link literalOf} — both match by
|
|
3009
|
+
* Pairs with {@link literalOf} — both match by SameValueZero, so the
|
|
2541
3010
|
* `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
|
|
2542
3011
|
* (string, number, or boolean), not only strings. Matching is identity, never
|
|
2543
|
-
* cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
|
|
3012
|
+
* cross-type coercion: `parseEnum('1', [1])` stays `undefined`. The allowed
|
|
3013
|
+
* values are copied into an owned frozen `Set`; hostile iteration returns
|
|
3014
|
+
* `undefined` rather than escaping.
|
|
2544
3015
|
*
|
|
2545
3016
|
* @param value - The value to parse
|
|
2546
3017
|
* @param allowed - The permitted literal values
|
|
2547
|
-
* @returns The
|
|
3018
|
+
* @returns The input when it matches an allowed literal by SameValueZero, or `undefined`
|
|
2548
3019
|
*
|
|
2549
3020
|
* @example
|
|
2550
3021
|
* ```ts
|
|
@@ -2554,6 +3025,8 @@ export declare function parseBooleanField(record: Record<string, unknown>, path:
|
|
|
2554
3025
|
*/
|
|
2555
3026
|
export declare function parseEnum<const T extends string | number | boolean>(value: unknown, allowed: readonly T[]): T | undefined;
|
|
2556
3027
|
|
|
3028
|
+
export declare function parseEnum(value: unknown, allowed: readonly (string | number | boolean)[]): string | number | boolean | undefined;
|
|
3029
|
+
|
|
2557
3030
|
/**
|
|
2558
3031
|
* Read and parse an enum field from a record by key or nested key path.
|
|
2559
3032
|
*
|
|
@@ -2857,8 +3330,11 @@ export declare type RandomFunction = () => number;
|
|
|
2857
3330
|
* A raw JSON Schema passthrough — embeds a schema fragment directly.
|
|
2858
3331
|
*
|
|
2859
3332
|
* @remarks
|
|
2860
|
-
* For values the shape DSL can't express. The compiled guard accepts
|
|
2861
|
-
*
|
|
3333
|
+
* For values the shape DSL can't express. The compiled guard accepts every
|
|
3334
|
+
* top-level value except `undefined`, which is reserved as the parser failure
|
|
3335
|
+
* sentinel. Wrap the shape with {@link OptionalShape} to admit absence. Defined
|
|
3336
|
+
* values pass through unchanged, and the schema is emitted structurally
|
|
3337
|
+
* verbatim as an owned deeply frozen copy.
|
|
2862
3338
|
*/
|
|
2863
3339
|
export declare interface RawShape {
|
|
2864
3340
|
readonly type: 'raw';
|
|
@@ -2869,11 +3345,18 @@ export declare interface RawShape {
|
|
|
2869
3345
|
* Build a {@link RawShape} from a JSON Schema fragment.
|
|
2870
3346
|
*
|
|
2871
3347
|
* @remarks
|
|
2872
|
-
* For values the shape DSL can't express. The compiled guard accepts
|
|
2873
|
-
*
|
|
3348
|
+
* For values the shape DSL can't express. The compiled guard accepts every
|
|
3349
|
+
* DEFINED value — `undefined` alone fails, because it is the parser's failure
|
|
3350
|
+
* sentinel; wrap the shape in {@link optionalShape} to admit absence. The
|
|
3351
|
+
* parser passes a defined value through unchanged, and the fragment is
|
|
3352
|
+
* deep-cloned into an owned frozen snapshot ({@link cloneSchema}), so
|
|
3353
|
+
* `rawShape(fragment).schema !== fragment` and later edits to the caller's
|
|
3354
|
+
* fragment cannot reach the shape. `compileSchema` re-emits that snapshot
|
|
3355
|
+
* structurally verbatim; `compileGenerator` throws, since an arbitrary embedded
|
|
3356
|
+
* schema has no auto-generatable sample.
|
|
2874
3357
|
*
|
|
2875
3358
|
* @param schema - The JSON Schema fragment to embed
|
|
2876
|
-
* @returns A raw shape
|
|
3359
|
+
* @returns A raw shape owning a frozen copy of the fragment
|
|
2877
3360
|
*
|
|
2878
3361
|
* @example
|
|
2879
3362
|
* ```ts
|
|
@@ -3048,13 +3531,13 @@ export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'ema
|
|
|
3048
3531
|
* @remarks
|
|
3049
3532
|
* Total: never throws. Guards depth exhaustion, a non-record node (the
|
|
3050
3533
|
* node's static `JSONSchema` type is not trusted at runtime), and a cyclic
|
|
3051
|
-
* re-encounter of `schema` — all three widen to {@link
|
|
3534
|
+
* re-encounter of `schema` — all three widen to {@link rawShape}. The
|
|
3052
3535
|
* ancestor set is added to and removed from around the WHOLE subtree
|
|
3053
3536
|
* conversion (not permanently), so a DAG-shaped schema reached twice via two
|
|
3054
3537
|
* different, non-cyclic paths does not false-positive as a cycle. The
|
|
3055
3538
|
* subtree conversion itself runs inside {@link attempt}, so a hostile
|
|
3056
3539
|
* throwing getter/Proxy anywhere in `schema` cannot escape as a thrown error
|
|
3057
|
-
* — it degrades to {@link
|
|
3540
|
+
* — it degrades to {@link rawShape} instead. A same-node re-conversion at
|
|
3058
3541
|
* the same remaining `depth` is served from `memo` (guards a
|
|
3059
3542
|
* shared-reference schema DAG against exponential blowup), mirroring
|
|
3060
3543
|
* {@link inferObject} / {@link inferArray} (inferers.ts).
|
|
@@ -3069,7 +3552,7 @@ export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'ema
|
|
|
3069
3552
|
* recursion state owned by the {@link schemaToShape} entry point; passing
|
|
3070
3553
|
* a shared or pre-populated `WeakMap` changes caching behavior and is not
|
|
3071
3554
|
* supported usage
|
|
3072
|
-
* @returns The built shape for `schema`, or {@link
|
|
3555
|
+
* @returns The built shape for `schema`, or {@link rawShape} on any failure
|
|
3073
3556
|
*
|
|
3074
3557
|
* @example
|
|
3075
3558
|
* ```ts
|
|
@@ -3139,7 +3622,7 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
|
|
|
3139
3622
|
* @remarks
|
|
3140
3623
|
* Total: NEVER throws, for any input — a malformed, cyclic, deeply-nested, or
|
|
3141
3624
|
* outright hostile (throwing-getter Proxy) `schema` value all degrade to
|
|
3142
|
-
* {@link
|
|
3625
|
+
* {@link rawShape} rather than escaping as an error, so
|
|
3143
3626
|
* `createContract(schemaToShape(x))` is safe to call for any `x`. See
|
|
3144
3627
|
* {@link buildShapeFromNode} for the exact per-keyword precedence.
|
|
3145
3628
|
*
|
|
@@ -3149,9 +3632,36 @@ export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<
|
|
|
3149
3632
|
* `RegExp` is a ReDoS vector; both keywords are read only far enough to be
|
|
3150
3633
|
* ignored. Any node the walk cannot express — an empty `{}`, an
|
|
3151
3634
|
* unrecognized `type`, a schema past {@link INFER_DEPTH_LIMIT} deep, or a
|
|
3152
|
-
* cyclic re-encounter — widens to {@link
|
|
3153
|
-
*
|
|
3154
|
-
*
|
|
3635
|
+
* cyclic re-encounter — widens to {@link rawShape} (accept any defined
|
|
3636
|
+
* value), never narrows.
|
|
3637
|
+
*
|
|
3638
|
+
* ROUND TRIP: `compileGuard(schemaToShape(valueToSchema(v)))(v)` is `true` for
|
|
3639
|
+
* every `v` — including the values no JSON Schema keyword describes (`NaN`,
|
|
3640
|
+
* `±Infinity`, a `Map`, a `Set`, a class instance, a function, a symbol, a
|
|
3641
|
+
* bigint, a cyclic or hostile host), which infer `{}` and widen back to an
|
|
3642
|
+
* accept-anything {@link rawShape}. Widening is the only source of looseness.
|
|
3643
|
+
* The law has three explicit host limits:
|
|
3644
|
+
*
|
|
3645
|
+
* - **Absence.** `undefined` is not a value: no compiled guard accepts it
|
|
3646
|
+
* (`rawShape` reserves it as the parser failure sentinel). So `undefined`
|
|
3647
|
+
* itself, an array element holding it, and an array HOLE (`arrayOf` requires
|
|
3648
|
+
* every index to be an own property, the same rule `isJSONValue` applies)
|
|
3649
|
+
* all fall outside the law. An OBJECT property holding `undefined` does not:
|
|
3650
|
+
* `valueToSchema` drops the key and opens the object, so the source object
|
|
3651
|
+
* is still accepted.
|
|
3652
|
+
* - **`Date` serialization.** A `Date` infers the schema of its JSON form
|
|
3653
|
+
* (`{ type: 'string' }`, plus `format: 'date-time'` when `format` is on), so
|
|
3654
|
+
* the law applies to `date.toISOString()` rather than the runtime instance.
|
|
3655
|
+
* - **Stateful access.** A getter whose result changes between inference and
|
|
3656
|
+
* guard evaluation can invalidate the sampled fact. Likewise, an array that
|
|
3657
|
+
* overrides iteration behavior can present different elements to the two
|
|
3658
|
+
* phases. The law applies only while the sampled host's observable own
|
|
3659
|
+
* enumerable string properties and array iteration remain stable.
|
|
3660
|
+
*
|
|
3661
|
+
* A widened node cannot be auto-generated: `rawShape` embeds an arbitrary
|
|
3662
|
+
* schema fragment, so `createContract(schemaToShape(x)).generate()` throws
|
|
3663
|
+
* when the conversion widened anywhere — `schema` / `is` / `parse` / `explain`
|
|
3664
|
+
* stay total.
|
|
3155
3665
|
*
|
|
3156
3666
|
* @param schema - The JSON Schema value to convert
|
|
3157
3667
|
* @returns The built {@link ContractShape}
|
|
@@ -3229,10 +3739,14 @@ export declare function shapeToKind(shape: ContractShape): FaultKind;
|
|
|
3229
3739
|
*
|
|
3230
3740
|
* @remarks
|
|
3231
3741
|
* Composes {@link isString} with {@link boundsOf} on the string's `.length` and
|
|
3232
|
-
* an
|
|
3233
|
-
* the bare {@link isString} guard
|
|
3234
|
-
* unrefined string leaf pays no wrapping
|
|
3235
|
-
* refinement shared by the compiled guard
|
|
3742
|
+
* an owned stateless pattern (the same refinement {@link matchOf} performs).
|
|
3743
|
+
* When all three options are absent it returns the bare {@link isString} guard
|
|
3744
|
+
* (the unconstrained fast path), so an unrefined string leaf pays no wrapping
|
|
3745
|
+
* cost. The single source of the string refinement shared by the compiled guard
|
|
3746
|
+
* and parser (compilers.ts).
|
|
3747
|
+
*
|
|
3748
|
+
* @param options - Optional length bounds and regular expression refinement
|
|
3749
|
+
* @returns A string guard enforcing the requested refinements
|
|
3236
3750
|
*
|
|
3237
3751
|
* @example
|
|
3238
3752
|
* ```ts
|
|
@@ -3255,6 +3769,7 @@ export declare interface StringShape {
|
|
|
3255
3769
|
readonly type: 'string';
|
|
3256
3770
|
readonly min?: number;
|
|
3257
3771
|
readonly max?: number;
|
|
3772
|
+
/** A pattern constraint; builders and cloners expose an owned fresh frozen zero-state copy per read. */
|
|
3258
3773
|
readonly pattern?: RegExp;
|
|
3259
3774
|
readonly description?: string;
|
|
3260
3775
|
}
|
|
@@ -3262,8 +3777,14 @@ export declare interface StringShape {
|
|
|
3262
3777
|
/**
|
|
3263
3778
|
* Build a string {@link StringShape}.
|
|
3264
3779
|
*
|
|
3780
|
+
* @remarks
|
|
3781
|
+
* A supplied pattern is captured by source and flags. The shape exposes a fresh
|
|
3782
|
+
* frozen zero-state `RegExp` on every `pattern` read, so neither the caller's
|
|
3783
|
+
* original nor a value read from the shape can drift later compiled artifacts.
|
|
3784
|
+
*
|
|
3265
3785
|
* @param options - Optional length (`min` / `max`), `pattern`, and `description`
|
|
3266
3786
|
* @returns A string shape
|
|
3787
|
+
* @throws {ContractError} When a present bound is invalid or `pattern` has flags
|
|
3267
3788
|
*
|
|
3268
3789
|
* @example
|
|
3269
3790
|
* ```ts
|
|
@@ -3324,9 +3845,8 @@ export declare interface Success<T> {
|
|
|
3324
3845
|
*
|
|
3325
3846
|
* @remarks
|
|
3326
3847
|
* `project` is a plain `(value: T) => U`. Per §14 the returned guard never
|
|
3327
|
-
* throws: a throw from `project` is contained and reported as a
|
|
3328
|
-
*
|
|
3329
|
-
* contained region. (Unlike the reference implementation, there is no
|
|
3848
|
+
* throws: a throw from `project` or `target` is contained and reported as a
|
|
3849
|
+
* non-match. (Unlike the reference implementation, there is no
|
|
3330
3850
|
* "curried projector" branch — a projection that legitimately returns a function
|
|
3331
3851
|
* would be double-invoked under that scheme. Compose explicitly if you need it.)
|
|
3332
3852
|
*
|
|
@@ -3377,6 +3897,14 @@ export declare function tupleOf(...predicates: ReadonlyArray<(value: unknown) =>
|
|
|
3377
3897
|
* `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
|
|
3378
3898
|
* An empty input list returns the empty accept-anything schema `{}`.
|
|
3379
3899
|
*
|
|
3900
|
+
* A member {@link canonicalStringify} cannot key — a cyclic, hostile, or
|
|
3901
|
+
* otherwise JSON-inexpressible fragment, which only a direct caller can supply
|
|
3902
|
+
* since the inferers always build plain encodable fragments — has NO
|
|
3903
|
+
* de-duplication key, so it can participate in neither de-duplication nor the
|
|
3904
|
+
* canonical-key ordering. It is KEPT (dropping a variant would narrow the
|
|
3905
|
+
* union, and unification only ever widens), appended in input order after the
|
|
3906
|
+
* sorted keyed members, so the result stays total and deterministic.
|
|
3907
|
+
*
|
|
3380
3908
|
* @param schemas - The schemas to unify
|
|
3381
3909
|
* @returns The unified schema
|
|
3382
3910
|
*
|
|
@@ -3406,8 +3934,9 @@ export declare function unionOf(...predicates: ReadonlyArray<(value: unknown) =>
|
|
|
3406
3934
|
* A union shape — accepts a value matching any one variant (first match wins).
|
|
3407
3935
|
*
|
|
3408
3936
|
* @remarks
|
|
3409
|
-
* `mode` selects the emitted JSON Schema keyword
|
|
3410
|
-
* `'
|
|
3937
|
+
* `mode` selects the emitted JSON Schema keyword and runtime matching rule:
|
|
3938
|
+
* `'anyOf'` (default) accepts the first matching variant, while `'oneOf'`
|
|
3939
|
+
* requires exactly one variant to match.
|
|
3411
3940
|
*/
|
|
3412
3941
|
export declare interface UnionShape<V extends readonly ContractShape[] = readonly ContractShape[]> {
|
|
3413
3942
|
readonly type: 'union';
|
|
@@ -3428,19 +3957,21 @@ export declare interface UnionShape<V extends readonly ContractShape[] = readonl
|
|
|
3428
3957
|
* // Infer<typeof id> = string | number
|
|
3429
3958
|
* ```
|
|
3430
3959
|
*/
|
|
3431
|
-
export declare function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V
|
|
3960
|
+
export declare function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<Readonly<V>>;
|
|
3432
3961
|
|
|
3433
3962
|
/** Convert a union type to an intersection type. */
|
|
3434
3963
|
export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
|
|
3435
3964
|
|
|
3436
3965
|
/**
|
|
3437
|
-
* Validate that a {@link ContractShape}
|
|
3438
|
-
*
|
|
3966
|
+
* Validate that a {@link ContractShape} graph is well-formed before
|
|
3967
|
+
* compilation.
|
|
3439
3968
|
*
|
|
3440
3969
|
* @remarks
|
|
3441
3970
|
* Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
|
|
3442
|
-
* throws a
|
|
3443
|
-
* guard, parser, schema, or generator later.
|
|
3971
|
+
* throws a coded {@link ContractError} immediately rather than surfacing as a
|
|
3972
|
+
* silently-wrong guard, parser, schema, or generator later. The iterative walk
|
|
3973
|
+
* tracks active ancestors, so a structural cycle reports its precise path while
|
|
3974
|
+
* a shared child reached through separate paths remains legal. Checks:
|
|
3444
3975
|
*
|
|
3445
3976
|
* - An {@link OptionalShape} is only legal as a direct object-property value —
|
|
3446
3977
|
* `optionalShape` wrapping an array item, a union variant, another
|
|
@@ -3453,14 +3984,19 @@ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void
|
|
|
3453
3984
|
* `-Infinity`) number values.
|
|
3454
3985
|
* - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
|
|
3455
3986
|
* needs `min <= max` when both are set.
|
|
3987
|
+
* - Every present number bound is finite.
|
|
3456
3988
|
* - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
|
|
3457
3989
|
* range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
|
|
3990
|
+
* - Shape nesting may not exceed {@link COMPILE_DEPTH_LIMIT}; excessive depth
|
|
3991
|
+
* fails before recursive artifact compilation begins. Because the depth check
|
|
3992
|
+
* runs before the active-ancestor check, a back-edge first reached beyond the
|
|
3993
|
+
* limit reports `depth`; a cycle reached within the limit reports `cycle`.
|
|
3458
3994
|
* - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
|
|
3459
3995
|
* continues into array items, object properties (and `additionalProperties`
|
|
3460
3996
|
* when it is a shape), union variants, and optional/nullable inner shapes.
|
|
3461
3997
|
*
|
|
3462
3998
|
* @param shape - The shape to validate
|
|
3463
|
-
* @throws {
|
|
3999
|
+
* @throws {ContractError} When the shape is malformed or cyclic
|
|
3464
4000
|
*
|
|
3465
4001
|
* @example
|
|
3466
4002
|
* ```ts
|
|
@@ -3470,6 +4006,23 @@ export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void
|
|
|
3470
4006
|
*/
|
|
3471
4007
|
export declare function validateShape(shape: ContractShape): void;
|
|
3472
4008
|
|
|
4009
|
+
/**
|
|
4010
|
+
* Gate recursive compiler work on shape depth and structural cycles.
|
|
4011
|
+
*
|
|
4012
|
+
* @remarks
|
|
4013
|
+
* Walks the shape graph iteratively in linear time and stack space, tracking
|
|
4014
|
+
* active ancestors so shared children remain legal. Every standalone compiler
|
|
4015
|
+
* calls this gate before its recursive branch begins. The depth check runs
|
|
4016
|
+
* before the active-ancestor check, so a back-edge first reached beyond
|
|
4017
|
+
* {@link COMPILE_DEPTH_LIMIT} reports `depth`; a shallower cycle reports
|
|
4018
|
+
* `cycle`.
|
|
4019
|
+
*
|
|
4020
|
+
* @param shape - The shape graph to gate
|
|
4021
|
+
* @returns Nothing; successful return means recursive compilation is depth-safe
|
|
4022
|
+
* @throws {ContractError} When the shape is cyclic or exceeds the compilation depth limit
|
|
4023
|
+
*/
|
|
4024
|
+
export declare function validateShapeDepth(shape: ContractShape): void;
|
|
4025
|
+
|
|
3473
4026
|
/**
|
|
3474
4027
|
* Infer a `JSONSchema` for one unknown value — the reverse direction of
|
|
3475
4028
|
* {@link compileSchema}.
|