@orkestrel/contract 0.0.4 → 0.0.6
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/src/core/index.cjs +1082 -0
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +3320 -8
- package/dist/src/core/index.d.ts +3320 -8
- package/dist/src/core/index.js +1058 -1
- package/dist/src/core/index.js.map +1 -1
- package/package.json +7 -2
- package/dist/src/core/combinators.d.ts +0 -384
- package/dist/src/core/compilers.d.ts +0 -150
- package/dist/src/core/constants.d.ts +0 -20
- package/dist/src/core/helpers.d.ts +0 -112
- package/dist/src/core/parsers.d.ts +0 -310
- package/dist/src/core/shapers.d.ts +0 -231
- package/dist/src/core/types.d.ts +0 -450
- package/dist/src/core/validators.d.ts +0 -717
package/dist/src/core/index.d.ts
CHANGED
|
@@ -1,8 +1,3320 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Combine two guards with logical AND — passes only when both pass.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Use {@link whereOf} when the right side refines an already-narrowed type; use
|
|
6
|
+
* `andOf` to combine two independent guards.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const isShortString = andOf(isString, isNonEmptyString)
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export declare function andOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A & B>;
|
|
14
|
+
|
|
15
|
+
export declare function andOf<T, U extends T>(left: Guard<T>, right: (value: T) => value is U): Guard<U>;
|
|
16
|
+
|
|
17
|
+
export declare function andOf<T>(left: Guard<T>, right: (value: T) => boolean): Guard<T>;
|
|
18
|
+
|
|
19
|
+
export declare function andOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
|
|
20
|
+
|
|
21
|
+
/** An async function accepting any arguments and returning a `Promise`. */
|
|
22
|
+
export declare type AnyAsyncFunction = (...args: unknown[]) => Promise<unknown>;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Any constructor signature that produces instances of `T`.
|
|
26
|
+
*
|
|
27
|
+
* @remarks
|
|
28
|
+
* Uses `unknown[]` parameters to stay maximally assignable from specific
|
|
29
|
+
* constructors without resorting to `any`.
|
|
30
|
+
*/
|
|
31
|
+
export declare type AnyConstructor<T = unknown> = new (...args: unknown[]) => T;
|
|
32
|
+
|
|
33
|
+
/** A function accepting any arguments and returning `unknown`. */
|
|
34
|
+
export declare type AnyFunction = (...args: unknown[]) => unknown;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Build a guard that accepts arrays whose every element satisfies `elementGuard`.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* ```ts
|
|
41
|
+
* const isStringArray = arrayOf(isString)
|
|
42
|
+
* isStringArray(['a', 'b']) // true
|
|
43
|
+
* isStringArray(['a', 1]) // false
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export declare function arrayOf<T>(elementGuard: Guard<T>): Guard<readonly T[]>;
|
|
47
|
+
|
|
48
|
+
export declare function arrayOf(elementGuard: (value: unknown) => boolean): Guard<readonly unknown[]>;
|
|
49
|
+
|
|
50
|
+
/** An array shape with an element shape and optional length bounds. */
|
|
51
|
+
export declare interface ArrayShape<S extends ContractShape = ContractShape> {
|
|
52
|
+
readonly type: 'array';
|
|
53
|
+
readonly items: S;
|
|
54
|
+
readonly min?: number;
|
|
55
|
+
readonly max?: number;
|
|
56
|
+
readonly description?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Build an {@link ArrayShape} from an element shape.
|
|
61
|
+
*
|
|
62
|
+
* @param items - The element shape
|
|
63
|
+
* @param options - Optional length bounds and `description`
|
|
64
|
+
* @returns An array shape
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* const tags = arrayShape(stringShape(), { max: 10 })
|
|
69
|
+
* ```
|
|
70
|
+
*/
|
|
71
|
+
export declare function arrayShape<S extends ContractShape>(items: S, options?: ArrayShapeOptions): ArrayShape<S>;
|
|
72
|
+
|
|
73
|
+
/** Options for {@link ArrayShape} (via `arrayShape`). */
|
|
74
|
+
export declare interface ArrayShapeOptions {
|
|
75
|
+
readonly min?: number;
|
|
76
|
+
readonly max?: number;
|
|
77
|
+
readonly description?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Invoke a callback and capture its outcome as a {@link Result}, never letting
|
|
82
|
+
* a throw escape.
|
|
83
|
+
*
|
|
84
|
+
* @remarks
|
|
85
|
+
* The single sanctioned never-throw boundary for the guards (AGENTS §14). The
|
|
86
|
+
* `whereOf`, `lazyOf`, and `transformOf` combinators invoke caller-supplied
|
|
87
|
+
* callbacks *inside* a guard body, yet a guard must NEVER throw — it returns a
|
|
88
|
+
* `boolean`. This converts a throwing callback into a `Failure` so the
|
|
89
|
+
* surrounding guard can treat it as a non-match instead of propagating the
|
|
90
|
+
* exception, written once and shared rather than copy-pasted as ad-hoc
|
|
91
|
+
* `try`/`catch`.
|
|
92
|
+
*
|
|
93
|
+
* @param callback - The callback to invoke with no arguments
|
|
94
|
+
* @returns A `Success` carrying the return value, or a `Failure` carrying the
|
|
95
|
+
* thrown reason normalised to an `Error`
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* const outcome = attempt(() => predicate(value))
|
|
100
|
+
* return outcome.success && outcome.value
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
103
|
+
export declare function attempt<T>(callback: () => T): Result<T>;
|
|
104
|
+
|
|
105
|
+
/** A boolean shape — accepts only `true` or `false`. */
|
|
106
|
+
export declare interface BooleanShape {
|
|
107
|
+
readonly type: 'boolean';
|
|
108
|
+
readonly description?: string;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Build a {@link BooleanShape}.
|
|
113
|
+
*
|
|
114
|
+
* @param options - Optional `description`
|
|
115
|
+
* @returns A boolean shape
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* const active = booleanShape({ description: 'Whether the record is active' })
|
|
120
|
+
* ```
|
|
121
|
+
*/
|
|
122
|
+
export declare function booleanShape(options?: BooleanShapeOptions): BooleanShape;
|
|
123
|
+
|
|
124
|
+
/** Options for {@link BooleanShape} (via `booleanShape`). */
|
|
125
|
+
export declare interface BooleanShapeOptions {
|
|
126
|
+
readonly description?: string;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Build a guard that accepts finite numbers within an inclusive `[min, max]`
|
|
131
|
+
* range.
|
|
132
|
+
*
|
|
133
|
+
* @remarks
|
|
134
|
+
* Refines {@link isFiniteNumber} with the bound comparison, so `NaN` /
|
|
135
|
+
* `±Infinity` are rejected before any comparison runs. An absent bound never
|
|
136
|
+
* constrains that side. Reused for a number's own value AND, applied to a
|
|
137
|
+
* `.length`, for string and array length refinements — the single source of the
|
|
138
|
+
* bound logic shared by the compiled guard and parser (compilers.ts).
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* const inRange = boundsOf(1, 5)
|
|
143
|
+
* inRange(3) // true
|
|
144
|
+
* inRange(0) // false — below min
|
|
145
|
+
* inRange(6) // false — above max
|
|
146
|
+
*
|
|
147
|
+
* const atLeastTwo = boundsOf(2)
|
|
148
|
+
* atLeastTwo(2) // true — unbounded above
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
export declare function boundsOf(min?: number, max?: number): Guard<number>;
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Render a value as a deterministic, key-sorted JSON string.
|
|
155
|
+
*
|
|
156
|
+
* @remarks
|
|
157
|
+
* The stable-stringify backing {@link unifySchemas}'s de-duplication and
|
|
158
|
+
* ordering: unlike `JSON.stringify`, object keys are sorted before encoding
|
|
159
|
+
* (recursively, at every nesting level), so two structurally-equal
|
|
160
|
+
* `JSONSchema` fragments built independently always canonicalize to the same
|
|
161
|
+
* string. Pure ECMAScript — no `structuredClone`, no `node:*` import.
|
|
162
|
+
*
|
|
163
|
+
* @param value - The value to canonicalize (a `JSONSchema` fragment, or any
|
|
164
|
+
* nested piece of one)
|
|
165
|
+
* @returns A deterministic string encoding of `value`
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```ts
|
|
169
|
+
* canonicalStringify({ type: 'object', properties: {} }) ===
|
|
170
|
+
* canonicalStringify({ properties: {}, type: 'object' }) // true
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
export declare function canonicalStringify(value: unknown): string;
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Compile a {@link ContractShape} into a deterministic seed value.
|
|
177
|
+
*
|
|
178
|
+
* @remarks
|
|
179
|
+
* The same shape and the same `random` source always produce the same value, so
|
|
180
|
+
* seed data is reproducible. Defaults to a {@link seededRandom} source seeded
|
|
181
|
+
* from the wall clock when none is supplied. Throws on a degenerate empty
|
|
182
|
+
* `literalShape` / `unionShape`, on a pattern-constrained `stringShape` whose
|
|
183
|
+
* generated sample cannot satisfy the pattern, or on a `rawShape` (its embedded
|
|
184
|
+
* schema is arbitrary and cannot be auto-generated) — a programmer error that
|
|
185
|
+
* cannot generate a value (AGENTS §12). `createContract` runs
|
|
186
|
+
* {@link validateShape} first, so a degenerate `literalShape` / `unionShape` /
|
|
187
|
+
* bounded shape is normally caught there; these throws remain here as defense
|
|
188
|
+
* for standalone `compileGenerator` use.
|
|
189
|
+
*
|
|
190
|
+
* @param shape - The shape to generate from
|
|
191
|
+
* @param random - A seeded random source (defaults to `seededRandom(Date.now())`)
|
|
192
|
+
* @returns A value matching the shape
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* ```ts
|
|
196
|
+
* compileGenerator(stringShape({ min: 1, max: 4 })) // a random string of 1-4 characters (seed a RandomFunction for determinism)
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
export declare function compileGenerator<S extends ContractShape>(shape: S, random?: RandomFunction): Infer<S>;
|
|
200
|
+
|
|
201
|
+
export declare function compileGenerator(shape: ContractShape, random?: RandomFunction): unknown;
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Compile a {@link ContractShape} into a runtime type guard.
|
|
205
|
+
*
|
|
206
|
+
* @remarks
|
|
207
|
+
* Reuses the combinators: `literalOf` for literals, `arrayOf` for arrays,
|
|
208
|
+
* `recordOf` for closed objects, `unionOf` for unions, `nullableOf` for nullable,
|
|
209
|
+
* and `whereOf` for constraint refinement. Like every guard it is total — it
|
|
210
|
+
* never throws (AGENTS §14).
|
|
211
|
+
*
|
|
212
|
+
* @param shape - The shape to compile
|
|
213
|
+
* @returns A guard narrowing to the shape's inferred type
|
|
214
|
+
*
|
|
215
|
+
* @example
|
|
216
|
+
* ```ts
|
|
217
|
+
* const isUser = compileGuard(objectShape({ name: stringShape() }))
|
|
218
|
+
* isUser({ name: 'Ada' }) // true
|
|
219
|
+
* ```
|
|
220
|
+
*/
|
|
221
|
+
export declare function compileGuard<S extends ContractShape>(shape: S): Guard<Infer<S>>;
|
|
222
|
+
|
|
223
|
+
export declare function compileGuard(shape: ContractShape): Guard<unknown>;
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Compile a {@link ContractShape} into an input parser.
|
|
227
|
+
*
|
|
228
|
+
* @remarks
|
|
229
|
+
* Reuses the leaf parsers (`parseString` / `parseInteger` / `parseNumber` /
|
|
230
|
+
* `parseBoolean` / `parseRecord`) and coerces structurally. An object fails as a
|
|
231
|
+
* whole on any required-field failure; a union returns a guard-valid value
|
|
232
|
+
* unchanged, otherwise the first variant that both parses and guards wins.
|
|
233
|
+
*
|
|
234
|
+
* After coercing a leaf, it re-applies that leaf's REFINEMENTS through the same
|
|
235
|
+
* combinators `compileGuard` uses — `stringOf` for a string's length/pattern and
|
|
236
|
+
* `boundsOf` for a number's value and an array's length — so a value that coerces
|
|
237
|
+
* but violates a bound parses to `undefined`. The result is full parse↔guard
|
|
238
|
+
* soundness (AGENTS §14): a non-`undefined` parse always satisfies the contract's
|
|
239
|
+
* `is`, refinements included.
|
|
240
|
+
*
|
|
241
|
+
* @param shape - The shape to compile
|
|
242
|
+
* @returns A parser yielding the shape's inferred type or `undefined`
|
|
243
|
+
*
|
|
244
|
+
* @example
|
|
245
|
+
* ```ts
|
|
246
|
+
* const parseUser = compileParser(objectShape({ name: stringShape() }))
|
|
247
|
+
* parseUser({ name: 'Ada' }) // { name: 'Ada' }
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
250
|
+
export declare function compileParser<S extends ContractShape>(shape: S): Parser<Infer<S>>;
|
|
251
|
+
|
|
252
|
+
export declare function compileParser(shape: ContractShape): Parser<unknown>;
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Compile a {@link ContractShape} into a structured fault report for a value —
|
|
256
|
+
* the diagnostic counterpart of {@link compileGuard} / {@link compileParser}.
|
|
257
|
+
*
|
|
258
|
+
* @remarks
|
|
259
|
+
* MIRROR-PARSE semantics: reuses the exact leaf parsers/guards
|
|
260
|
+
* {@link compileParser} uses (`parseString` / `parseNumber` / `parseBoolean` /
|
|
261
|
+
* `isJSONValue` / …), so the soundness invariant
|
|
262
|
+
* `compileReporter(shape, v).length === 0 ⟺ compileParser(shape)(v) !== undefined`
|
|
263
|
+
* holds structurally — `explain` mirrors `parse`, not the stricter `is` (a
|
|
264
|
+
* coercible value like `'42'` against a `numberShape` reports no fault, the
|
|
265
|
+
* same leniency `parse` grants, even though the strict guard would reject it).
|
|
266
|
+
*
|
|
267
|
+
* Faults are collected in stable pre-order (declared key/index order); every
|
|
268
|
+
* call — object, array, and union alike, including a union's `oneOf` "no
|
|
269
|
+
* match" / "no consensus" summary fault prepended to its closest variant's
|
|
270
|
+
* faults — slices its return to at most {@link FAULT_LIMIT} entries, so the
|
|
271
|
+
* bound holds at every level of nesting, not just the outermost container, on
|
|
272
|
+
* adversarial input (a huge array, a wide record, a wide union of wide
|
|
273
|
+
* records). A closed object's extra keys never
|
|
274
|
+
* fault — `parse` silently drops them, so `explain` mirrors that leniency; an
|
|
275
|
+
* open object with a constraining `additionalProperties` shape recurses extras
|
|
276
|
+
* against it instead. A hostile getter or throwing `Proxy` trap is contained
|
|
277
|
+
* via {@link attempt} and surfaces as a single top-level type fault, never a
|
|
278
|
+
* throw (AGENTS §14).
|
|
279
|
+
*
|
|
280
|
+
* @param shape - The shape to report against
|
|
281
|
+
* @param value - The value to check
|
|
282
|
+
* @param path - The path prefix for faults produced at this call (defaults to the root)
|
|
283
|
+
* @returns The faults found, empty when the value parses successfully
|
|
284
|
+
*
|
|
285
|
+
* @example
|
|
286
|
+
* ```ts
|
|
287
|
+
* const user = objectShape({ name: stringShape({ min: 1 }) })
|
|
288
|
+
* compileReporter(user, { name: '' })
|
|
289
|
+
* // [{ reason: 'constraint', path: ['name'], expected: 'string', constraint: 'min', limit: 1, received: '""' }]
|
|
290
|
+
* compileReporter(user, { name: 'Ada' }) // []
|
|
291
|
+
* ```
|
|
292
|
+
*/
|
|
293
|
+
export declare function compileReporter(shape: ContractShape, value: unknown, path?: string[]): readonly Fault[];
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Compile a {@link ContractShape} into a JSON Schema document.
|
|
297
|
+
*
|
|
298
|
+
* @remarks
|
|
299
|
+
* Object shapes emit `additionalProperties: false` (unless opened) and list only
|
|
300
|
+
* required keys in `required`; nullable shapes emit an `anyOf` with `{ type:
|
|
301
|
+
* 'null' }`. Emission only — it never inspects a runtime value.
|
|
302
|
+
*
|
|
303
|
+
* @param shape - The shape to compile
|
|
304
|
+
* @returns The emitted JSON Schema
|
|
305
|
+
*
|
|
306
|
+
* @example
|
|
307
|
+
* ```ts
|
|
308
|
+
* compileSchema(stringShape({ min: 1 })) // { type: 'string', minLength: 1 }
|
|
309
|
+
* ```
|
|
310
|
+
*/
|
|
311
|
+
export declare function compileSchema(shape: ContractShape): JSONSchema;
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Build a guard for `Exclude<TBase, TExcluded>` — accepts values that pass
|
|
315
|
+
* `base` but not `excluded`.
|
|
316
|
+
*
|
|
317
|
+
* @example
|
|
318
|
+
* ```ts
|
|
319
|
+
* const isNonEmpty = complementOf(isString, isEmptyString)
|
|
320
|
+
* isNonEmpty('hi') // true
|
|
321
|
+
* isNonEmpty('') // false
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
export declare function complementOf<TBase, TExcluded extends TBase>(base: Guard<TBase>, excluded: Guard<TExcluded> | ((value: TBase) => value is TExcluded)): Guard<Exclude<TBase, TExcluded>>;
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* A compiled contract — the four lockstep outputs derived from one shape.
|
|
328
|
+
*
|
|
329
|
+
* @remarks
|
|
330
|
+
* Built by `createContract`: `is` narrows, `parse` coerces (returning the typed
|
|
331
|
+
* value or `undefined`), `schema` is the emitted JSON Schema, and `generate`
|
|
332
|
+
* produces deterministic seed data from a {@link RandomFunction} (defaulting to
|
|
333
|
+
* a wall-clock-seeded source when none is supplied).
|
|
334
|
+
*/
|
|
335
|
+
export declare interface ContractInterface<T> {
|
|
336
|
+
readonly schema: JSONSchema;
|
|
337
|
+
readonly is: Guard<T>;
|
|
338
|
+
parse(value: unknown): T | undefined;
|
|
339
|
+
/**
|
|
340
|
+
* Report every structured parse fault a value has against this contract.
|
|
341
|
+
*
|
|
342
|
+
* @remarks
|
|
343
|
+
* An empty report means the value is valid. Soundness invariant:
|
|
344
|
+
* `explain(v).length === 0` if and only if `parse(v) !== undefined` — explain
|
|
345
|
+
* mirrors `parse`'s coercion, not the stricter `is`. Faults are listed in
|
|
346
|
+
* stable pre-order (declared key/index order).
|
|
347
|
+
*
|
|
348
|
+
* @param value - The value to check
|
|
349
|
+
* @returns The faults found, empty when the value parses successfully
|
|
350
|
+
*/
|
|
351
|
+
explain(value: unknown): readonly Fault[];
|
|
352
|
+
generate(random?: RandomFunction): T;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* A contract shape — a declarative description of a value, built with the shape
|
|
357
|
+
* builders and compiled into a guard, a parser, a JSON Schema, and a generator.
|
|
358
|
+
*
|
|
359
|
+
* @remarks
|
|
360
|
+
* A discriminated union keyed on `type`. Shapes nest (an `ArrayShape` holds an
|
|
361
|
+
* element shape, an `ObjectShape` a map of them), so a contract is a finite,
|
|
362
|
+
* developer-authored tree — never cyclic.
|
|
363
|
+
*/
|
|
364
|
+
export declare type ContractShape = StringShape | NumberShape | BooleanShape | NullShape | LiteralShape | ArrayShape | ObjectShape | UnionShape | OptionalShape | NullableShape | JSONShape | RawShape;
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Compile a {@link ContractShape} into a {@link ContractInterface} — the four
|
|
368
|
+
* lockstep outputs from one declaration.
|
|
369
|
+
*
|
|
370
|
+
* @remarks
|
|
371
|
+
* Runs {@link validateShape} first — a malformed shape throws immediately
|
|
372
|
+
* rather than compiling into a silently-wrong contract (AGENTS §12). Then
|
|
373
|
+
* precompiles the schema, guard, and parser once; `generate` walks the shape
|
|
374
|
+
* per call with the supplied random source, and `explain` compiles the
|
|
375
|
+
* diagnostic report via {@link compileReporter} at zero added compile-time cost
|
|
376
|
+
* (it re-walks the shape per call, exactly like `generate`).
|
|
377
|
+
*
|
|
378
|
+
* @param shape - The shape to compile
|
|
379
|
+
* @returns A contract bundling `schema` / `is` / `parse` / `explain` / `generate`
|
|
380
|
+
*
|
|
381
|
+
* @example
|
|
382
|
+
* ```ts
|
|
383
|
+
* const user = createContract(objectShape({ name: stringShape(), age: integerShape() }))
|
|
384
|
+
* user.is({ name: 'Ada', age: 36 }) // true
|
|
385
|
+
* user.parse({ name: 'Ada', age: '36' }) // { name: 'Ada', age: 36 }
|
|
386
|
+
* user.schema // { type: 'object', properties: { … }, … }
|
|
387
|
+
* ```
|
|
388
|
+
*/
|
|
389
|
+
export declare function createContract<S extends ContractShape>(shape: S): ContractInterface<Infer<S>>;
|
|
390
|
+
|
|
391
|
+
export declare function createContract(shape: ContractShape): ContractInterface<unknown>;
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Count the enumerable own-symbol keys on a value.
|
|
395
|
+
*
|
|
396
|
+
* @remarks
|
|
397
|
+
* String keys are ignored — only `Object.getOwnPropertySymbols` entries whose
|
|
398
|
+
* descriptor is `enumerable` are counted. Backs the object-emptiness guards
|
|
399
|
+
* (`isEmptyObject` / `isNonEmptyObject`) so a record keyed only by an
|
|
400
|
+
* enumerable symbol is not mistaken for empty.
|
|
401
|
+
*
|
|
402
|
+
* @param value - The object to inspect
|
|
403
|
+
* @returns The number of enumerable own-symbol keys
|
|
404
|
+
*
|
|
405
|
+
* @example
|
|
406
|
+
* ```ts
|
|
407
|
+
* const flag = Symbol('flag')
|
|
408
|
+
* enumerableSymbolCount(Object.defineProperty({}, flag, { value: 1, enumerable: true })) // 1
|
|
409
|
+
* enumerableSymbolCount({}) // 0
|
|
410
|
+
* ```
|
|
411
|
+
*/
|
|
412
|
+
export declare function enumerableSymbolCount(value: object): number;
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Build a guard from a native `enum` or any object whose values are strings or
|
|
416
|
+
* numbers.
|
|
417
|
+
*
|
|
418
|
+
* @example
|
|
419
|
+
* ```ts
|
|
420
|
+
* enum Direction { Up = 'up', Down = 'down' }
|
|
421
|
+
* const isDirection = enumOf(Direction)
|
|
422
|
+
* isDirection('up') // true
|
|
423
|
+
* isDirection('left') // false
|
|
424
|
+
* ```
|
|
425
|
+
*/
|
|
426
|
+
export declare function enumOf<const E extends Record<string, string | number>>(enumeration: E): Guard<E[keyof E]>;
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Discriminated failure branch of a {@link Result}.
|
|
430
|
+
*
|
|
431
|
+
* @remarks
|
|
432
|
+
* Carries the error value when an operation does not succeed.
|
|
433
|
+
*/
|
|
434
|
+
export declare interface Failure<E> {
|
|
435
|
+
readonly success: false;
|
|
436
|
+
readonly error: E;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* A single structured parse-failure diagnostic — one entry of an
|
|
441
|
+
* {@link ContractInterface.explain} report.
|
|
442
|
+
*
|
|
443
|
+
* @remarks
|
|
444
|
+
* A discriminated union on `reason`:
|
|
445
|
+
* - `'type'` — the value could not coerce to `expected` at all.
|
|
446
|
+
* - `'missing'` — a required object property was absent.
|
|
447
|
+
* - `'constraint'` — the value coerced to `expected` but violated one
|
|
448
|
+
* refinement (`min` / `max` / `pattern` / `integer`); `limit` carries the
|
|
449
|
+
* violated bound/pattern when applicable.
|
|
450
|
+
* - `'variant'` — an `anyOf`-mode union matched no variant; `variants` is the
|
|
451
|
+
* variant count, followed (in the report) by the closest variant's own faults.
|
|
452
|
+
* - `'oneOf'` — a `oneOf`-mode union matched zero or two-or-more variants;
|
|
453
|
+
* `matched` is the raw match count.
|
|
454
|
+
*/
|
|
455
|
+
export declare type Fault = {
|
|
456
|
+
readonly reason: 'type';
|
|
457
|
+
readonly path: FieldPath;
|
|
458
|
+
readonly expected: FaultKind;
|
|
459
|
+
readonly received: string;
|
|
460
|
+
} | {
|
|
461
|
+
readonly reason: 'missing';
|
|
462
|
+
readonly path: FieldPath;
|
|
463
|
+
readonly expected: FaultKind;
|
|
464
|
+
} | {
|
|
465
|
+
readonly reason: 'constraint';
|
|
466
|
+
readonly path: FieldPath;
|
|
467
|
+
readonly expected: FaultKind;
|
|
468
|
+
readonly constraint: FaultConstraint;
|
|
469
|
+
readonly limit?: number | string;
|
|
470
|
+
readonly received: string;
|
|
471
|
+
} | {
|
|
472
|
+
readonly reason: 'variant';
|
|
473
|
+
readonly path: FieldPath;
|
|
474
|
+
readonly variants: number;
|
|
475
|
+
} | {
|
|
476
|
+
readonly reason: 'oneOf';
|
|
477
|
+
readonly path: FieldPath;
|
|
478
|
+
readonly matched: number;
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* The maximum number of {@link Fault} entries a single `explain` report ever
|
|
483
|
+
* returns, frozen.
|
|
484
|
+
*
|
|
485
|
+
* @remarks
|
|
486
|
+
* Bounds the report against adversarial input (a giant array, a wide record) —
|
|
487
|
+
* `compileReporter` collects faults in stable pre-order and stops once this cap
|
|
488
|
+
* is reached, so the report size (and the work to build it) stays finite and
|
|
489
|
+
* deterministic regardless of the input's size.
|
|
490
|
+
*/
|
|
491
|
+
export declare const FAULT_LIMIT = 64;
|
|
492
|
+
|
|
493
|
+
/** The refinement a {@link Fault} of reason `'constraint'` violates. */
|
|
494
|
+
export declare type FaultConstraint = 'min' | 'max' | 'pattern' | 'integer';
|
|
495
|
+
|
|
496
|
+
/** The kind of value a {@link Fault} expected — the shape-projected counterpart of a `ContractShape`'s `type`. */
|
|
497
|
+
export declare type FaultKind = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'literal' | 'array' | 'object' | 'union' | 'json';
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* A field path into a record: a single key, or an ordered list of keys to
|
|
501
|
+
* descend through nested objects.
|
|
502
|
+
*
|
|
503
|
+
* @remarks
|
|
504
|
+
* A single `string` is ONE key — it is never split on `.`, so keys that contain
|
|
505
|
+
* dots stay safe. Use a `readonly string[]` to descend into nested objects.
|
|
506
|
+
*/
|
|
507
|
+
export declare type FieldPath = string | readonly string[];
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* The maximum string length {@link stringToFormat} attempts to classify,
|
|
511
|
+
* frozen.
|
|
512
|
+
*
|
|
513
|
+
* @remarks
|
|
514
|
+
* Bounds per-string format-detection work: a value longer than this returns
|
|
515
|
+
* `undefined` immediately, before any pattern match runs. 128 sits
|
|
516
|
+
* comfortably above the longest real format token — an RFC 3339 date-time
|
|
517
|
+
* with fractional seconds and a UTC offset — so no legitimate classification
|
|
518
|
+
* changes; only pathologically long strings (a multi-megabyte payload passed
|
|
519
|
+
* as a candidate email/URI) are skipped.
|
|
520
|
+
*/
|
|
521
|
+
export declare const FORMAT_MAX_LENGTH = 128;
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Pure-regex matchers backing {@link stringToFormat}'s pattern-only formats
|
|
525
|
+
* (`uuid` / `email` / `uri`), frozen as data.
|
|
526
|
+
*
|
|
527
|
+
* @remarks
|
|
528
|
+
* The ISO-8601 date/time formats are NOT listed here — they additionally
|
|
529
|
+
* require an attempt-guarded `Date` validity check, so their pattern lives
|
|
530
|
+
* inline in `stringToFormat` rather than as reusable standalone data.
|
|
531
|
+
*/
|
|
532
|
+
export declare const FORMAT_PATTERNS: Readonly<Record<'uuid' | 'email' | 'uri', RegExp>>;
|
|
533
|
+
|
|
534
|
+
/** Resolve a {@link GuardsShape} to a readonly object type of its guarded property types. */
|
|
535
|
+
export declare type FromGuards<G extends GuardsShape> = Readonly<{
|
|
536
|
+
[K in keyof G]: GuardType<G[K]>;
|
|
537
|
+
}>;
|
|
538
|
+
|
|
539
|
+
/** A runtime type guard: returns `true` when `value` satisfies `T` and narrows it. */
|
|
540
|
+
export declare type Guard<T> = (value: unknown) => value is T;
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* A mapping of string keys to guards.
|
|
544
|
+
*
|
|
545
|
+
* @remarks
|
|
546
|
+
* The shape parameter for the `recordOf`, `pickOf`, and `omitOf` combinators.
|
|
547
|
+
*/
|
|
548
|
+
export declare type GuardsShape = Readonly<Record<string, Guard<unknown>>>;
|
|
549
|
+
|
|
550
|
+
/** Extract the guarded type `T` from a `Guard<T>`. */
|
|
551
|
+
export declare type GuardType<G> = G extends Guard<infer T> ? T : never;
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Infer the static TypeScript type a {@link ContractShape} describes.
|
|
555
|
+
*
|
|
556
|
+
* @remarks
|
|
557
|
+
* Structural and recursive: optional object fields surface as optional
|
|
558
|
+
* properties, nullable wrappers add `| null`, and a literal tuple becomes a
|
|
559
|
+
* string/number/boolean-literal union.
|
|
560
|
+
*
|
|
561
|
+
* The first, non-distributive branch bails out to `unknown` when `S` is the
|
|
562
|
+
* full widened {@link ContractShape} union. Five members of that union recurse
|
|
563
|
+
* back into the whole union through their defaulted generics, so inferring the
|
|
564
|
+
* full union is a fixed point that can never shrink — the compiler would fan
|
|
565
|
+
* out until it aborts with TS2589. Bailing out lazily short-circuits that
|
|
566
|
+
* fixed point (the untaken branch is never instantiated) while every narrow
|
|
567
|
+
* shape and every partial union still flows through the exact chain below.
|
|
568
|
+
*
|
|
569
|
+
* The `ObjectShape` branch's `additionalProperties` guard (`[A] extends
|
|
570
|
+
* [boolean | ContractShape]`) is likewise wrapped in a tuple to stay
|
|
571
|
+
* non-distributive: a naked `A extends boolean | ContractShape` distributes
|
|
572
|
+
* over a union `A`, fanning a wide `additionalProperties` type into one
|
|
573
|
+
* {@link InferObject} instantiation per union member instead of one
|
|
574
|
+
* instantiation over the whole union — the same TS2589 risk under repeated
|
|
575
|
+
* nesting. {@link InferIndex} and {@link InferOpenIndex} apply the identical
|
|
576
|
+
* tuple guard to their own `A` parameter for the same reason.
|
|
577
|
+
*/
|
|
578
|
+
export declare type Infer<S extends ContractShape> = [ContractShape] extends [S] ? unknown : S extends StringShape ? string : S extends NumberShape ? number : S extends BooleanShape ? boolean : S extends NullShape ? null : S extends {
|
|
579
|
+
readonly type: 'literal';
|
|
580
|
+
readonly values: infer V;
|
|
581
|
+
} ? V extends readonly (infer L)[] ? L : never : S extends {
|
|
582
|
+
readonly type: 'array';
|
|
583
|
+
readonly items: infer I;
|
|
584
|
+
} ? I extends ContractShape ? readonly 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 {
|
|
585
|
+
readonly type: 'union';
|
|
586
|
+
readonly variants: infer V;
|
|
587
|
+
} ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends {
|
|
588
|
+
readonly type: 'optional';
|
|
589
|
+
readonly inner: infer I;
|
|
590
|
+
} ? I extends ContractShape ? Infer<I> | undefined : never : S extends {
|
|
591
|
+
readonly type: 'nullable';
|
|
592
|
+
readonly inner: infer I;
|
|
593
|
+
} ? I extends ContractShape ? Infer<I> | null : never : S extends JSONShape ? JSONValue : unknown;
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* The default maximum number of object properties / array elements
|
|
597
|
+
* {@link valueToSchema} samples per container, frozen.
|
|
598
|
+
*
|
|
599
|
+
* @remarks
|
|
600
|
+
* Bounds the work (and the emitted schema's size) against a wide record or a
|
|
601
|
+
* huge array — properties/elements beyond this cap are never inspected.
|
|
602
|
+
* Overridable per call via {@link ValueToSchemaOptions.maxProperties}.
|
|
603
|
+
*/
|
|
604
|
+
export declare const INFER_BREADTH_LIMIT = 256;
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* The default maximum object/array nesting depth {@link valueToSchema} walks,
|
|
608
|
+
* frozen.
|
|
609
|
+
*
|
|
610
|
+
* @remarks
|
|
611
|
+
* Bounds inference against adversarial or cyclic runtime input — once the
|
|
612
|
+
* remaining depth budget reaches zero, inference stops descending and emits
|
|
613
|
+
* the empty accept-anything schema `{}` for that branch instead of recursing
|
|
614
|
+
* further. Overridable per call via {@link ValueToSchemaOptions.maxDepth}.
|
|
615
|
+
*/
|
|
616
|
+
export declare const INFER_DEPTH_LIMIT = 32;
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* The default maximum number of distinct values a multi-sample slot may hold
|
|
620
|
+
* before enum inference gives up and falls back to a bare `type`, frozen.
|
|
621
|
+
*
|
|
622
|
+
* @remarks
|
|
623
|
+
* Bounds how large an `enum` list {@link samplesToSchema} / {@link inferRecordSamples}
|
|
624
|
+
* will emit — a slot with distinct-value count at or above this limit is
|
|
625
|
+
* treated as unbounded (an ID column, not a category) and never gets an
|
|
626
|
+
* `enum` keyword. Overridable per call via {@link ValueToSchemaOptions.enum}
|
|
627
|
+
* (which gates whether enum inference runs at all).
|
|
628
|
+
*/
|
|
629
|
+
export declare const INFER_ENUM_LIMIT = 12;
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* Infer a `JSONSchema` array fragment from an array's sampled elements.
|
|
633
|
+
*
|
|
634
|
+
* @remarks
|
|
635
|
+
* An empty array infers `{ type: 'array' }` with no `items`. Otherwise the
|
|
636
|
+
* first `breadth` elements are classified via {@link inferValue} (one less
|
|
637
|
+
* depth) and unified with {@link unifySchemas}: a single distinct element
|
|
638
|
+
* schema becomes `items` directly; multiple distinct schemas become
|
|
639
|
+
* `items: { anyOf: [...] }`. Depth exhaustion or a cyclic re-encounter of
|
|
640
|
+
* `value` both yield the empty schema `{}` instead of descending. A sparse
|
|
641
|
+
* array (holes, e.g. `[1, , 3]`) is densified via `Array.from` before
|
|
642
|
+
* sampling so every slot — including a hole — is visited as an explicit
|
|
643
|
+
* `undefined` leaf (which {@link inferValue} maps to `{}`), rather than left
|
|
644
|
+
* as a hole that would otherwise reach {@link unifySchemas} as `undefined`.
|
|
645
|
+
*
|
|
646
|
+
* ALL reads of `value` — including its `length` — happen inside
|
|
647
|
+
* {@link attempt}: a hostile `length` getter (e.g. a Proxy-over-array whose
|
|
648
|
+
* `get` trap throws) is exactly as contained as a throwing own-getter element
|
|
649
|
+
* or a Proxy-over-array element access, and cannot escape as a thrown error.
|
|
650
|
+
* On failure — or when the sampled/classified list ends up empty — this
|
|
651
|
+
* returns `{ type: 'array' }` (no `items`), since `value` is still known to
|
|
652
|
+
* be an array, mirroring the empty-array emission. A same-object
|
|
653
|
+
* re-inference at the same remaining `depth` is served from `memo` instead
|
|
654
|
+
* of recomputing (guards a shared-reference DAG against exponential blowup).
|
|
655
|
+
*
|
|
656
|
+
* @param value - The array to infer from
|
|
657
|
+
* @param depth - Remaining descent budget
|
|
658
|
+
* @param breadth - The maximum number of elements sampled
|
|
659
|
+
* @param closed - Threaded through to nested object elements
|
|
660
|
+
* @param format - Threaded through to nested string/`Date` elements
|
|
661
|
+
* @param visited - The ancestor set guarding against cycles
|
|
662
|
+
* @param memo - A per-call `(object, remaining depth) → schema` cache guarding
|
|
663
|
+
* against exponential re-inference of a shared-reference DAG
|
|
664
|
+
* @returns The inferred array schema
|
|
665
|
+
*
|
|
666
|
+
* @example
|
|
667
|
+
* ```ts
|
|
668
|
+
* inferArray([1, 2.5], 32, 256, true, false, new WeakSet(), new WeakMap())
|
|
669
|
+
* // { type: 'array', items: { type: 'number' } }
|
|
670
|
+
* ```
|
|
671
|
+
*/
|
|
672
|
+
export declare function inferArray(value: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet<object>, memo: WeakMap<object, Map<number, JSONSchema>>): JSONSchema;
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* The index-signature contribution of a pure record shape's `additionalProperties`
|
|
676
|
+
* — the `recordShape` case, where `properties` is empty.
|
|
677
|
+
*
|
|
678
|
+
* @remarks
|
|
679
|
+
* `false` (closed) contributes `unknown`, which collapses away in an
|
|
680
|
+
* intersection — a closed object's {@link Infer} is unaffected. `true` (open,
|
|
681
|
+
* unconstrained) contributes an `unknown`-valued index signature. A
|
|
682
|
+
* {@link ContractShape} (open, constrained) contributes an index signature
|
|
683
|
+
* typed to that shape's own `Infer` — sound here because there are no fixed
|
|
684
|
+
* properties for the index to collide with.
|
|
685
|
+
*
|
|
686
|
+
* @remarks
|
|
687
|
+
* The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay
|
|
688
|
+
* non-distributive, matching {@link Infer}'s own object-branch guard — see
|
|
689
|
+
* that type's remarks for why a naked `extends` here would fan a wide `A`
|
|
690
|
+
* into a union of `InferIndex` instantiations instead of one.
|
|
691
|
+
*/
|
|
692
|
+
export declare type InferIndex<A extends boolean | ContractShape> = [A] extends [false] ? unknown : [A] extends [true] ? {
|
|
693
|
+
readonly [k: string]: unknown;
|
|
694
|
+
} : [A] extends [ContractShape] ? {
|
|
695
|
+
readonly [k: string]: Infer<A>;
|
|
696
|
+
} : unknown;
|
|
697
|
+
|
|
698
|
+
/** {@link Infer} with its TOP-LEVEL `readonly` modifiers stripped (a shallow strip — nested object/array properties stay readonly) — for consumers writing the parsed value's own fields. */
|
|
699
|
+
export declare type InferMutable<S extends ContractShape> = {
|
|
700
|
+
-readonly [K in keyof Infer<S>]: Infer<S>[K];
|
|
701
|
+
};
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* {@link Infer} of an object shape's `properties` — the required keys, plus the
|
|
705
|
+
* `optional`-wrapped keys as optional members, plus the index-signature
|
|
706
|
+
* contribution of `additionalProperties` (see {@link InferIndex}).
|
|
707
|
+
*
|
|
708
|
+
* @remarks
|
|
709
|
+
* The `[keyof P] extends [never]` split is hoisted to the front (rather than
|
|
710
|
+
* folded into the intersection's second operand) so a pure record shape
|
|
711
|
+
* (`P` empty) short-circuits straight to {@link InferIndex} without ever
|
|
712
|
+
* building the `Readonly<{} & {}>` intersection shell — the clean
|
|
713
|
+
* `Readonly<Record<string, V>>` {@link InferIndex} already returns. A closed
|
|
714
|
+
* empty object (`P` empty, `A` `false`/absent) still resolves through
|
|
715
|
+
* {@link InferIndex}'s own `[A] extends [false]` branch to
|
|
716
|
+
* `Readonly<Record<never, never>>`, preserving the empty-closed-object result.
|
|
717
|
+
* A shape with fixed properties always routes through {@link InferOpenIndex}.
|
|
718
|
+
*/
|
|
719
|
+
export declare type InferObject<P extends Readonly<Record<string, ContractShape>>, A extends boolean | ContractShape = false> = [keyof P] extends [never] ? [A] extends [false] ? Readonly<Record<never, never>> : InferIndex<A> : Readonly<{
|
|
720
|
+
[K in keyof P as P[K] extends {
|
|
721
|
+
readonly type: 'optional';
|
|
722
|
+
} ? never : K]: Infer<P[K]>;
|
|
723
|
+
} & {
|
|
724
|
+
[K in keyof P as P[K] extends {
|
|
725
|
+
readonly type: 'optional';
|
|
726
|
+
} ? K : never]?: P[K] extends {
|
|
727
|
+
readonly type: 'optional';
|
|
728
|
+
readonly inner: infer I;
|
|
729
|
+
} ? I extends ContractShape ? Infer<I> : never : never;
|
|
730
|
+
}> & InferOpenIndex<A>;
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* Infer a `JSONSchema` object fragment from a plain record's sampled
|
|
734
|
+
* properties.
|
|
735
|
+
*
|
|
736
|
+
* @remarks
|
|
737
|
+
* Own enumerable string keys via `Object.keys`, sorted lexicographically for
|
|
738
|
+
* deterministic output, capped at `breadth`. Each property value is read
|
|
739
|
+
* through {@link attempt} so a hostile getter cannot escape as a thrown
|
|
740
|
+
* error; a property whose value is `undefined` (hostile-getter failure
|
|
741
|
+
* included) is treated as ABSENT — it contributes neither a `properties`
|
|
742
|
+
* entry nor a `required` entry. Every other present key is required (single-
|
|
743
|
+
* value mode). Emits `additionalProperties: false` when `closed`, `true`
|
|
744
|
+
* otherwise — mirroring {@link compileSchema}'s object-emission convention —
|
|
745
|
+
* EXCEPT when the own-key list exceeds `breadth`: a truncated key list means
|
|
746
|
+
* the sampled schema no longer describes every property `value` actually
|
|
747
|
+
* carries, so `additionalProperties` is forced to `true` regardless of
|
|
748
|
+
* `closed` (a closed schema built from a truncated sample would otherwise
|
|
749
|
+
* reject the very object it was inferred from). Depth exhaustion or a cyclic
|
|
750
|
+
* re-encounter of `value` both yield `{}`. A same-object re-inference at the
|
|
751
|
+
* same remaining `depth` is served from `memo` instead of recomputing
|
|
752
|
+
* (guards a shared-reference DAG against exponential blowup).
|
|
753
|
+
*
|
|
754
|
+
* @param value - The record to infer from
|
|
755
|
+
* @param depth - Remaining descent budget
|
|
756
|
+
* @param breadth - The maximum number of properties sampled
|
|
757
|
+
* @param closed - Whether the emitted schema closes to unknown keys
|
|
758
|
+
* @param format - Threaded through to nested string/`Date` properties
|
|
759
|
+
* @param visited - The ancestor set guarding against cycles
|
|
760
|
+
* @param memo - A per-call `(object, remaining depth) → schema` cache guarding
|
|
761
|
+
* against exponential re-inference of a shared-reference DAG
|
|
762
|
+
* @returns The inferred object schema
|
|
763
|
+
*
|
|
764
|
+
* @example
|
|
765
|
+
* ```ts
|
|
766
|
+
* inferObject({ id: 1 }, 32, 256, true, false, new WeakSet(), new WeakMap())
|
|
767
|
+
* // { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'],
|
|
768
|
+
* // additionalProperties: false }
|
|
769
|
+
* ```
|
|
770
|
+
*/
|
|
771
|
+
export declare function inferObject(value: Record<string, unknown>, depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet<object>, memo: WeakMap<object, Map<number, JSONSchema>>): JSONSchema;
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* The index-signature contribution of a MIXED object shape's
|
|
775
|
+
* `additionalProperties` — one with both fixed `properties` and an open tail.
|
|
776
|
+
*
|
|
777
|
+
* @remarks
|
|
778
|
+
* A typed index (`{ readonly [k: string]: Infer<A> }`) collapses any
|
|
779
|
+
* differently-typed fixed property to `never` on intersection and makes the
|
|
780
|
+
* object type unconstructable — TypeScript rejects assigning any property
|
|
781
|
+
* whose type differs from the index value type. So when `A` is a
|
|
782
|
+
* {@link ContractShape} here, the index is deliberately widened to
|
|
783
|
+
* `{ readonly [k: string]: unknown }`: the static type stops over-claiming the
|
|
784
|
+
* extra-key type while the runtime guard still validates extras against `A`.
|
|
785
|
+
* `false` / `true` behave exactly as {@link InferIndex}.
|
|
786
|
+
*
|
|
787
|
+
* @remarks
|
|
788
|
+
* The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay
|
|
789
|
+
* non-distributive, matching {@link Infer}'s own object-branch guard and
|
|
790
|
+
* {@link InferIndex}'s tail — see {@link Infer}'s remarks for why a naked
|
|
791
|
+
* `extends` here would fan a wide `A` into a union of instantiations.
|
|
792
|
+
*/
|
|
793
|
+
export declare type InferOpenIndex<A extends boolean | ContractShape> = [A] extends [false] ? unknown : [A] extends [true] ? {
|
|
794
|
+
readonly [k: string]: unknown;
|
|
795
|
+
} : [A] extends [ContractShape] ? {
|
|
796
|
+
readonly [k: string]: unknown;
|
|
797
|
+
} : unknown;
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Infer an `{ enum: [...] }` fragment for a low-cardinality, repeated
|
|
801
|
+
* primitive slot — the multi-sample-only counterpart to
|
|
802
|
+
* {@link stringToFormat} ({@link valueToSchema} never emits `enum`).
|
|
803
|
+
*
|
|
804
|
+
* @remarks
|
|
805
|
+
* Fires only when ALL of: every value is the same primitive kind (all string
|
|
806
|
+
* or all FINITE number via {@link isFiniteNumber} — any `null`/boolean/mixed
|
|
807
|
+
* slot never qualifies, and a slot containing `NaN` / `±Infinity` never
|
|
808
|
+
* qualifies either, since {@link canonicalStringify} collapses `NaN` to
|
|
809
|
+
* `'null'` and would otherwise risk an invalid-JSON `enum`); at least 2
|
|
810
|
+
* values are given; the distinct-by-{@link canonicalStringify} count is LESS
|
|
811
|
+
* than the value count (repetition required — separates a categorical column
|
|
812
|
+
* from an ID column); and the distinct count is at most `limit`. The emitted
|
|
813
|
+
* schema carries `enum` with NO `type` key, byte-matching `compileSchema`'s
|
|
814
|
+
* `literalShape` emission. Members are sorted by canonical key for
|
|
815
|
+
* deterministic output.
|
|
816
|
+
*
|
|
817
|
+
* @param values - The collected slot values
|
|
818
|
+
* @param limit - The maximum distinct-value count before giving up
|
|
819
|
+
* @returns The `{ enum: [...] }` fragment, or `undefined` when ineligible
|
|
820
|
+
*
|
|
821
|
+
* @example
|
|
822
|
+
* ```ts
|
|
823
|
+
* inferPrimitiveEnum(['active', 'inactive', 'active'], 12)
|
|
824
|
+
* // { enum: ['active', 'inactive'] }
|
|
825
|
+
* inferPrimitiveEnum(['a', 'b', 'c'], 12) // undefined — no repetition
|
|
826
|
+
* ```
|
|
827
|
+
*/
|
|
828
|
+
export declare function inferPrimitiveEnum(values: readonly unknown[], limit: number): JSONSchema | undefined;
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* Infer a `JSONSchema` object fragment from a set of plain-record samples
|
|
832
|
+
* (e.g. database rows) — the record-specialized branch of
|
|
833
|
+
* {@link samplesToSchema}.
|
|
834
|
+
*
|
|
835
|
+
* @remarks
|
|
836
|
+
* `properties` is the union of every sample's own keys (sorted, capped at
|
|
837
|
+
* `breadth`); a key is `required` only when present (and non-`undefined`) in
|
|
838
|
+
* EVERY sample. Each key's schema is inferred over the collected values for
|
|
839
|
+
* that key via {@link inferSamples} itself (one less depth), so a
|
|
840
|
+
* property that is itself an array/object of varying shape across rows is
|
|
841
|
+
* unified the same way the top level is, and the same `format` / `enum`
|
|
842
|
+
* gating applies per key. Unlike {@link inferObject}/
|
|
843
|
+
* {@link inferArray}, this path carries no `visited` `WeakSet` — a value
|
|
844
|
+
* shared by reference across multiple sample rows is legitimate (not a
|
|
845
|
+
* cycle back to an ancestor), so termination on cyclic row data relies on
|
|
846
|
+
* the decrementing `depth` budget alone. When the union of sample keys
|
|
847
|
+
* exceeds `breadth`, the key list is truncated and `additionalProperties` is
|
|
848
|
+
* forced to `true` regardless of `closed` — the same truncation-opens-the-
|
|
849
|
+
* schema rule {@link inferObject} applies, so a closed schema built from a
|
|
850
|
+
* truncated key union never rejects the very rows it was inferred from. A
|
|
851
|
+
* hostile getter on ONE sample row drops that key for ALL rows (the whole
|
|
852
|
+
* per-key value collection is a single {@link attempt}-contained walk) —
|
|
853
|
+
* this is a deliberate all-or-nothing scope, not a per-row partial failure.
|
|
854
|
+
*
|
|
855
|
+
* @param samples - The plain-record samples
|
|
856
|
+
* @param depth - Remaining descent budget
|
|
857
|
+
* @param breadth - The maximum number of properties sampled
|
|
858
|
+
* @param closed - Whether the emitted schema closes to unknown keys
|
|
859
|
+
* @param format - Whether a unanimous string column gains a `format` keyword
|
|
860
|
+
* @param enumOn - Whether a low-cardinality column may emit `enum`
|
|
861
|
+
* @returns The inferred object schema
|
|
862
|
+
*
|
|
863
|
+
* @example
|
|
864
|
+
* ```ts
|
|
865
|
+
* inferRecordSamples([{ id: 1 }, { id: 2, name: 'Ada' }], 32, 256, true, false, false)
|
|
866
|
+
* // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
|
|
867
|
+
* // required: ['id'], additionalProperties: false }
|
|
868
|
+
* ```
|
|
869
|
+
*/
|
|
870
|
+
export declare function inferRecordSamples(samples: readonly Record<string, unknown>[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean): JSONSchema;
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Infer a `JSONSchema` for a collected slot of sample values — the shared
|
|
874
|
+
* non-record recursion step behind {@link samplesToSchema} (top level) and
|
|
875
|
+
* {@link inferRecordSamples} (per collected property).
|
|
876
|
+
*
|
|
877
|
+
* @remarks
|
|
878
|
+
* When every value is itself a plain record, delegates to
|
|
879
|
+
* {@link inferRecordSamples}. Otherwise: enum inference runs FIRST when
|
|
880
|
+
* `enumOn` — {@link inferPrimitiveEnum} fires only for a low-cardinality,
|
|
881
|
+
* repeated, single-primitive-kind slot, and its `{ enum: [...] }` result wins
|
|
882
|
+
* outright (ENUM > FORMAT > bare string). Failing that, each value is
|
|
883
|
+
* classified independently via {@link inferValue} with `format` FORCED OFF
|
|
884
|
+
* (the multi-sample seam: nested formats never compound into an `anyOf`) and
|
|
885
|
+
* unified with {@link unifySchemas}; only when that unified result is exactly
|
|
886
|
+
* `{ type: 'string' }` and the outer `format` flag is on does
|
|
887
|
+
* {@link samplesToFormat} run to (maybe) reattach a unanimous `format`.
|
|
888
|
+
*
|
|
889
|
+
* @param samples - The collected slot values
|
|
890
|
+
* @param depth - Remaining descent budget
|
|
891
|
+
* @param breadth - The maximum number of properties/elements sampled per nested container
|
|
892
|
+
* @param closed - Whether nested objects close to unknown keys
|
|
893
|
+
* @param format - Whether a unanimous string slot gains a `format` keyword
|
|
894
|
+
* @param enumOn - Whether low-cardinality primitive slots may emit `enum`
|
|
895
|
+
* @returns The inferred schema for the slot
|
|
896
|
+
*
|
|
897
|
+
* @example
|
|
898
|
+
* ```ts
|
|
899
|
+
* inferSamples(['2024-01-01', '2024-02-02'], 32, 256, true, true, false)
|
|
900
|
+
* // { type: 'string', format: 'date' }
|
|
901
|
+
* ```
|
|
902
|
+
*/
|
|
903
|
+
export declare function inferSamples(samples: readonly unknown[], depth: number, breadth: number, closed: boolean, format: boolean, enumOn: boolean): JSONSchema;
|
|
904
|
+
|
|
905
|
+
/** {@link Infer} of a union shape's `variants` — the union of each variant's inferred type. */
|
|
906
|
+
export declare type InferUnion<V extends readonly ContractShape[]> = V extends readonly (infer U)[] ? U extends ContractShape ? Infer<U> : never : never;
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* Infer a `JSONSchema` fragment for one runtime value — the recursive spine
|
|
910
|
+
* shared by {@link valueToSchema} and, per collected property/element, by
|
|
911
|
+
* {@link inferArray} / {@link inferObject}.
|
|
912
|
+
*
|
|
913
|
+
* @remarks
|
|
914
|
+
* Total: never throws, and terminates on cyclic input via `visited`. Leaf
|
|
915
|
+
* classification order: `null`, boolean, integer (`Number.isInteger`
|
|
916
|
+
* semantics — `-0` counts), finite non-integer number, non-finite number
|
|
917
|
+
* (`NaN` / `±Infinity`, widened to `{ type: 'number' }`), string (gaining a
|
|
918
|
+
* `format` keyword when `format` is on and {@link stringToFormat} matches),
|
|
919
|
+
* array (recurse), plain record (recurse), `Date` (`{ type: 'string' }`,
|
|
920
|
+
* plus `format: 'date-time'` when `format` is on); everything else
|
|
921
|
+
* (function, symbol, bigint, `undefined`, and other non-plain objects such as
|
|
922
|
+
* `Map` / `Set`) is the empty accept-anything schema `{}`.
|
|
923
|
+
*
|
|
924
|
+
* @param value - The value to classify
|
|
925
|
+
* @param depth - Remaining descent budget (0 halts recursion with `{}`)
|
|
926
|
+
* @param breadth - The per-container sampling cap passed through to children
|
|
927
|
+
* @param closed - Whether descended objects emit `additionalProperties: false`
|
|
928
|
+
* @param format - Whether a string/`Date` leaf gains a `format` keyword
|
|
929
|
+
* @param visited - The ancestor set guarding against cycles
|
|
930
|
+
* @param memo - A per-call `(object, remaining depth) → schema` cache guarding
|
|
931
|
+
* against exponential re-inference of a shared-reference DAG
|
|
932
|
+
* @returns The inferred schema fragment for `value`
|
|
933
|
+
*
|
|
934
|
+
* @example
|
|
935
|
+
* ```ts
|
|
936
|
+
* inferValue(42, 32, 256, true, false, new WeakSet(), new WeakMap()) // { type: 'integer' }
|
|
937
|
+
* ```
|
|
938
|
+
*/
|
|
939
|
+
export declare function inferValue(value: unknown, depth: number, breadth: number, closed: boolean, format: boolean, visited: WeakSet<object>, memo: WeakMap<object, Map<number, JSONSchema>>): JSONSchema;
|
|
940
|
+
|
|
941
|
+
/**
|
|
942
|
+
* Build a guard that accepts instances of the provided constructor.
|
|
943
|
+
*
|
|
944
|
+
* @remarks
|
|
945
|
+
* Verifies that `ctor` is a real constructor (via {@link isConstructor}) first,
|
|
946
|
+
* so passing an arrow function does not silently produce a broken guard.
|
|
947
|
+
*
|
|
948
|
+
* @example
|
|
949
|
+
* ```ts
|
|
950
|
+
* const isDateValue = instanceOf(Date)
|
|
951
|
+
* isDateValue(new Date()) // true
|
|
952
|
+
* isDateValue({}) // false
|
|
953
|
+
* ```
|
|
954
|
+
*/
|
|
955
|
+
export declare function instanceOf<C extends abstract new (...args: never) => object>(ctor: C): Guard<InstanceType<C>>;
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* Build an integer {@link NumberShape} — forces `integer: true`.
|
|
959
|
+
*
|
|
960
|
+
* @remarks
|
|
961
|
+
* The emitted JSON Schema uses `"type": "integer"` and the guard rejects
|
|
962
|
+
* fractional numbers.
|
|
963
|
+
*
|
|
964
|
+
* @param options - Optional bounds and `description` (no `integer` key)
|
|
965
|
+
* @returns An integer number shape
|
|
966
|
+
*/
|
|
967
|
+
export declare function integerShape(options?: Omit<NumberShapeOptions, 'integer'>): NumberShape;
|
|
968
|
+
|
|
969
|
+
/** Intersection of the types guarded by a tuple of guards — backs `intersectionOf`. */
|
|
970
|
+
export declare type IntersectionFromGuards<Gs extends ReadonlyArray<Guard<unknown>>> = UnionToIntersection<GuardType<Gs[number]>>;
|
|
971
|
+
|
|
972
|
+
/**
|
|
973
|
+
* Build a guard that accepts values matching ALL of the provided guards — the
|
|
974
|
+
* variadic form of {@link andOf}.
|
|
975
|
+
*
|
|
976
|
+
* @example
|
|
977
|
+
* ```ts
|
|
978
|
+
* const isNonEmpty = intersectionOf(isString, isNonEmptyString)
|
|
979
|
+
* ```
|
|
980
|
+
*/
|
|
981
|
+
export declare function intersectionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<IntersectionFromGuards<Gs>>;
|
|
982
|
+
|
|
983
|
+
export declare function intersectionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>;
|
|
984
|
+
|
|
985
|
+
/** Determine whether a value is an array.
|
|
986
|
+
*
|
|
987
|
+
* @example
|
|
988
|
+
* ```ts
|
|
989
|
+
* isArray([1, 2]) // true
|
|
990
|
+
* isArray('12') // false
|
|
991
|
+
* ```
|
|
992
|
+
*/
|
|
993
|
+
export declare function isArray<T = unknown>(value: unknown): value is readonly T[];
|
|
994
|
+
|
|
995
|
+
/** Determine whether a value is an `ArrayBuffer`.
|
|
996
|
+
*
|
|
997
|
+
* @example
|
|
998
|
+
* ```ts
|
|
999
|
+
* isArrayBuffer(new ArrayBuffer(8)) // true
|
|
1000
|
+
* isArrayBuffer([]) // false
|
|
1001
|
+
* ```
|
|
1002
|
+
*/
|
|
1003
|
+
export declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
|
|
1004
|
+
|
|
1005
|
+
/** Determine whether a value is an `ArrayBufferView` (any typed array or `DataView`).
|
|
1006
|
+
*
|
|
1007
|
+
* @example
|
|
1008
|
+
* ```ts
|
|
1009
|
+
* isArrayBufferView(new Uint8Array(4)) // true
|
|
1010
|
+
* isArrayBufferView([1, 2, 3, 4]) // false
|
|
1011
|
+
* ```
|
|
1012
|
+
*/
|
|
1013
|
+
export declare function isArrayBufferView(value: unknown): value is ArrayBufferView;
|
|
1014
|
+
|
|
1015
|
+
/**
|
|
1016
|
+
* Determine whether a value is a native `async function`.
|
|
1017
|
+
*
|
|
1018
|
+
* @remarks
|
|
1019
|
+
* Uses `constructor.name === 'AsyncFunction'` — not `instanceof`, which is
|
|
1020
|
+
* unreliable across realms. The `?.` keeps the guard total (§14): a function
|
|
1021
|
+
* whose `constructor` was nulled yields `undefined`, never a thrown `null.name`.
|
|
1022
|
+
*
|
|
1023
|
+
* @example
|
|
1024
|
+
* ```ts
|
|
1025
|
+
* isAsyncFunction(async () => {}) // true
|
|
1026
|
+
* isAsyncFunction(() => {}) // false
|
|
1027
|
+
* ```
|
|
1028
|
+
*/
|
|
1029
|
+
export declare function isAsyncFunction(value: unknown): value is AnyAsyncFunction;
|
|
1030
|
+
|
|
1031
|
+
/** Determine whether a value is an async generator function (`async function*`).
|
|
1032
|
+
*
|
|
1033
|
+
* @example
|
|
1034
|
+
* ```ts
|
|
1035
|
+
* isAsyncGeneratorFunction(async function* () {}) // true
|
|
1036
|
+
* isAsyncGeneratorFunction(function* () {}) // false
|
|
1037
|
+
* ```
|
|
1038
|
+
*/
|
|
1039
|
+
export declare function isAsyncGeneratorFunction(value: unknown): value is (...args: unknown[]) => AsyncGenerator<unknown, unknown, unknown>;
|
|
1040
|
+
|
|
1041
|
+
/** Determine whether a value implements the async iterable protocol (`Symbol.asyncIterator`).
|
|
1042
|
+
*
|
|
1043
|
+
* @example
|
|
1044
|
+
* ```ts
|
|
1045
|
+
* isAsyncIterable({ [Symbol.asyncIterator]() {} }) // true
|
|
1046
|
+
* isAsyncIterable([1, 2]) // false
|
|
1047
|
+
* ```
|
|
1048
|
+
*/
|
|
1049
|
+
export declare function isAsyncIterable<T = unknown>(value: unknown): value is AsyncIterable<T>;
|
|
1050
|
+
|
|
1051
|
+
/** Determine whether a value is a bigint.
|
|
1052
|
+
*
|
|
1053
|
+
* @example
|
|
1054
|
+
* ```ts
|
|
1055
|
+
* isBigInt(1n) // true
|
|
1056
|
+
* isBigInt(1) // false
|
|
1057
|
+
* ```
|
|
1058
|
+
*/
|
|
1059
|
+
export declare function isBigInt(value: unknown): value is bigint;
|
|
1060
|
+
|
|
1061
|
+
/**
|
|
1062
|
+
* Determine whether a value is a `BigInt64Array`.
|
|
1063
|
+
*
|
|
1064
|
+
* @remarks
|
|
1065
|
+
* Guards the global existence of `BigInt64Array` first — safe in environments
|
|
1066
|
+
* that pre-date the BigInt typed-array additions.
|
|
1067
|
+
*
|
|
1068
|
+
* @example
|
|
1069
|
+
* ```ts
|
|
1070
|
+
* isBigInt64Array(new BigInt64Array(2)) // true
|
|
1071
|
+
* isBigInt64Array(new Float64Array(2)) // false
|
|
1072
|
+
* ```
|
|
1073
|
+
*/
|
|
1074
|
+
export declare function isBigInt64Array(value: unknown): value is BigInt64Array;
|
|
1075
|
+
|
|
1076
|
+
/**
|
|
1077
|
+
* Determine whether a value is a `BigUint64Array`.
|
|
1078
|
+
*
|
|
1079
|
+
* @remarks
|
|
1080
|
+
* Guards the global existence of `BigUint64Array` first — safe in environments
|
|
1081
|
+
* that pre-date the BigInt typed-array additions.
|
|
1082
|
+
*
|
|
1083
|
+
* @example
|
|
1084
|
+
* ```ts
|
|
1085
|
+
* isBigUint64Array(new BigUint64Array(2)) // true
|
|
1086
|
+
* isBigUint64Array(new BigInt64Array(2)) // false
|
|
1087
|
+
* ```
|
|
1088
|
+
*/
|
|
1089
|
+
export declare function isBigUint64Array(value: unknown): value is BigUint64Array;
|
|
1090
|
+
|
|
1091
|
+
/** Determine whether a value is a boolean.
|
|
1092
|
+
*
|
|
1093
|
+
* @example
|
|
1094
|
+
* ```ts
|
|
1095
|
+
* isBoolean(true) // true
|
|
1096
|
+
* isBoolean(1) // false
|
|
1097
|
+
* ```
|
|
1098
|
+
*/
|
|
1099
|
+
export declare function isBoolean(value: unknown): value is boolean;
|
|
1100
|
+
|
|
1101
|
+
/**
|
|
1102
|
+
* Determine whether a value can be used as a `new`-target constructor.
|
|
1103
|
+
*
|
|
1104
|
+
* @remarks
|
|
1105
|
+
* Probes with `Reflect.construct(String, [], value)`: a real constructor
|
|
1106
|
+
* succeeds, while arrow functions, plain functions, and non-functions throw
|
|
1107
|
+
* and yield `false`. Never throws. Backs the `instanceOf` combinator.
|
|
1108
|
+
*
|
|
1109
|
+
* @example
|
|
1110
|
+
* ```ts
|
|
1111
|
+
* isConstructor(class X {}) // true
|
|
1112
|
+
* isConstructor(() => {}) // false
|
|
1113
|
+
* ```
|
|
1114
|
+
*/
|
|
1115
|
+
export declare function isConstructor(value: unknown): value is AnyConstructor<object>;
|
|
1116
|
+
|
|
1117
|
+
/** Determine whether a value is a `DataView`.
|
|
1118
|
+
*
|
|
1119
|
+
* @example
|
|
1120
|
+
* ```ts
|
|
1121
|
+
* isDataView(new DataView(new ArrayBuffer(8))) // true
|
|
1122
|
+
* isDataView(new ArrayBuffer(8)) // false
|
|
1123
|
+
* ```
|
|
1124
|
+
*/
|
|
1125
|
+
export declare function isDataView(value: unknown): value is DataView<ArrayBufferLike>;
|
|
1126
|
+
|
|
1127
|
+
/** Determine whether a value is a `Date`.
|
|
1128
|
+
*
|
|
1129
|
+
* @example
|
|
1130
|
+
* ```ts
|
|
1131
|
+
* isDate(new Date()) // true
|
|
1132
|
+
* isDate('2024-01-01') // false
|
|
1133
|
+
* ```
|
|
1134
|
+
*/
|
|
1135
|
+
export declare function isDate(value: unknown): value is Date;
|
|
1136
|
+
|
|
1137
|
+
/** Determine whether a value is defined (neither `null` nor `undefined`).
|
|
1138
|
+
*
|
|
1139
|
+
* @example
|
|
1140
|
+
* ```ts
|
|
1141
|
+
* isDefined('hi') // true
|
|
1142
|
+
* isDefined(null) // false
|
|
1143
|
+
* isDefined(undefined) // false
|
|
1144
|
+
* ```
|
|
1145
|
+
*/
|
|
1146
|
+
export declare function isDefined<T>(value: T | null | undefined): value is T;
|
|
1147
|
+
|
|
1148
|
+
/** Determine whether a value is an empty array.
|
|
1149
|
+
*
|
|
1150
|
+
* @example
|
|
1151
|
+
* ```ts
|
|
1152
|
+
* isEmptyArray([]) // true
|
|
1153
|
+
* isEmptyArray([1]) // false
|
|
1154
|
+
* ```
|
|
1155
|
+
*/
|
|
1156
|
+
export declare function isEmptyArray(value: unknown): value is readonly [];
|
|
1157
|
+
|
|
1158
|
+
/** Determine whether a value is an empty `Map`.
|
|
1159
|
+
*
|
|
1160
|
+
* @example
|
|
1161
|
+
* ```ts
|
|
1162
|
+
* isEmptyMap(new Map()) // true
|
|
1163
|
+
* isEmptyMap(new Map([['a', 1]])) // false
|
|
1164
|
+
* ```
|
|
1165
|
+
*/
|
|
1166
|
+
export declare function isEmptyMap(value: unknown): value is ReadonlyMap<never, never>;
|
|
1167
|
+
|
|
1168
|
+
/** Determine whether a value is an empty plain object (no own string or enumerable symbol keys).
|
|
1169
|
+
*
|
|
1170
|
+
* @example
|
|
1171
|
+
* ```ts
|
|
1172
|
+
* isEmptyObject({}) // true
|
|
1173
|
+
* isEmptyObject({ a: 1 }) // false
|
|
1174
|
+
* ```
|
|
1175
|
+
*/
|
|
1176
|
+
export declare function isEmptyObject(value: unknown): value is Record<string | symbol, never>;
|
|
1177
|
+
|
|
1178
|
+
/** Determine whether a value is an empty `Set`.
|
|
1179
|
+
*
|
|
1180
|
+
* @example
|
|
1181
|
+
* ```ts
|
|
1182
|
+
* isEmptySet(new Set()) // true
|
|
1183
|
+
* isEmptySet(new Set([1])) // false
|
|
1184
|
+
* ```
|
|
1185
|
+
*/
|
|
1186
|
+
export declare function isEmptySet(value: unknown): value is ReadonlySet<never>;
|
|
1187
|
+
|
|
1188
|
+
/** Determine whether a value is the empty string `''`.
|
|
1189
|
+
*
|
|
1190
|
+
* @example
|
|
1191
|
+
* ```ts
|
|
1192
|
+
* isEmptyString('') // true
|
|
1193
|
+
* isEmptyString('a') // false
|
|
1194
|
+
* ```
|
|
1195
|
+
*/
|
|
1196
|
+
export declare function isEmptyString(value: unknown): value is '';
|
|
1197
|
+
|
|
1198
|
+
/** Determine whether a value is an `Error`.
|
|
1199
|
+
*
|
|
1200
|
+
* @example
|
|
1201
|
+
* ```ts
|
|
1202
|
+
* isError(new Error('boom')) // true
|
|
1203
|
+
* isError('boom') // false
|
|
1204
|
+
* ```
|
|
1205
|
+
*/
|
|
1206
|
+
export declare function isError(value: unknown): value is Error;
|
|
1207
|
+
|
|
1208
|
+
/** Determine whether a value is exactly `false`.
|
|
1209
|
+
*
|
|
1210
|
+
* @example
|
|
1211
|
+
* ```ts
|
|
1212
|
+
* isFalse(false) // true
|
|
1213
|
+
* isFalse(true) // false
|
|
1214
|
+
* ```
|
|
1215
|
+
*/
|
|
1216
|
+
export declare function isFalse(value: unknown): value is false;
|
|
1217
|
+
|
|
1218
|
+
/** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).
|
|
1219
|
+
*
|
|
1220
|
+
* @example
|
|
1221
|
+
* ```ts
|
|
1222
|
+
* isFiniteNumber(42) // true
|
|
1223
|
+
* isFiniteNumber(Number.NaN) // false
|
|
1224
|
+
* isFiniteNumber(Infinity) // false
|
|
1225
|
+
* ```
|
|
1226
|
+
*/
|
|
1227
|
+
export declare function isFiniteNumber(value: unknown): value is number;
|
|
1228
|
+
|
|
1229
|
+
/** Determine whether a value is a `Float32Array`.
|
|
1230
|
+
*
|
|
1231
|
+
* @example
|
|
1232
|
+
* ```ts
|
|
1233
|
+
* isFloat32Array(new Float32Array(2)) // true
|
|
1234
|
+
* isFloat32Array(new Float64Array(2)) // false
|
|
1235
|
+
* ```
|
|
1236
|
+
*/
|
|
1237
|
+
export declare function isFloat32Array(value: unknown): value is Float32Array;
|
|
1238
|
+
|
|
1239
|
+
/** Determine whether a value is a `Float64Array`.
|
|
1240
|
+
*
|
|
1241
|
+
* @example
|
|
1242
|
+
* ```ts
|
|
1243
|
+
* isFloat64Array(new Float64Array(2)) // true
|
|
1244
|
+
* isFloat64Array(new Float32Array(2)) // false
|
|
1245
|
+
* ```
|
|
1246
|
+
*/
|
|
1247
|
+
export declare function isFloat64Array(value: unknown): value is Float64Array;
|
|
1248
|
+
|
|
1249
|
+
/** Determine whether a value is callable.
|
|
1250
|
+
*
|
|
1251
|
+
* @example
|
|
1252
|
+
* ```ts
|
|
1253
|
+
* isFunction(() => {}) // true
|
|
1254
|
+
* isFunction({}) // false
|
|
1255
|
+
* ```
|
|
1256
|
+
*/
|
|
1257
|
+
export declare function isFunction(value: unknown): value is AnyFunction;
|
|
1258
|
+
|
|
1259
|
+
/** Determine whether a value is a generator function (`function*`).
|
|
1260
|
+
*
|
|
1261
|
+
* @example
|
|
1262
|
+
* ```ts
|
|
1263
|
+
* isGeneratorFunction(function* () {}) // true
|
|
1264
|
+
* isGeneratorFunction(() => {}) // false
|
|
1265
|
+
* ```
|
|
1266
|
+
*/
|
|
1267
|
+
export declare function isGeneratorFunction(value: unknown): value is (...args: unknown[]) => Generator<unknown, unknown, unknown>;
|
|
1268
|
+
|
|
1269
|
+
/**
|
|
1270
|
+
* Determine whether a value is an instance of a constructor, contained against
|
|
1271
|
+
* a throwing `instanceof` check.
|
|
1272
|
+
*
|
|
1273
|
+
* @remarks
|
|
1274
|
+
* The low-level total helper every `instanceof`-based guard in this file (and
|
|
1275
|
+
* the `instanceOf` combinator) routes through. A bare `value instanceof X` is
|
|
1276
|
+
* NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
|
|
1277
|
+
* revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
|
|
1278
|
+
* `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
|
|
1279
|
+
* wraps the check in {@link attempt} (see ./helpers.js) so any such throw
|
|
1280
|
+
* yields `false` instead of escaping.
|
|
1281
|
+
*
|
|
1282
|
+
* @param value - The value to test
|
|
1283
|
+
* @param ctor - The constructor to test against
|
|
1284
|
+
* @returns `true` when `value instanceof ctor`, `false` on a non-match or a
|
|
1285
|
+
* contained throw
|
|
1286
|
+
*
|
|
1287
|
+
* @example
|
|
1288
|
+
* ```ts
|
|
1289
|
+
* isInstance(new Date(), Date) // true
|
|
1290
|
+
* isInstance({}, Date) // false
|
|
1291
|
+
* ```
|
|
1292
|
+
*/
|
|
1293
|
+
export declare function isInstance<C>(value: unknown, ctor: C): value is InstanceType<C & AnyConstructor<object>>;
|
|
1294
|
+
|
|
1295
|
+
/** Determine whether a value is an `Int16Array`.
|
|
1296
|
+
*
|
|
1297
|
+
* @example
|
|
1298
|
+
* ```ts
|
|
1299
|
+
* isInt16Array(new Int16Array(2)) // true
|
|
1300
|
+
* isInt16Array(new Int8Array(2)) // false
|
|
1301
|
+
* ```
|
|
1302
|
+
*/
|
|
1303
|
+
export declare function isInt16Array(value: unknown): value is Int16Array;
|
|
1304
|
+
|
|
1305
|
+
/** Determine whether a value is an `Int32Array`.
|
|
1306
|
+
*
|
|
1307
|
+
* @example
|
|
1308
|
+
* ```ts
|
|
1309
|
+
* isInt32Array(new Int32Array(2)) // true
|
|
1310
|
+
* isInt32Array(new Int16Array(2)) // false
|
|
1311
|
+
* ```
|
|
1312
|
+
*/
|
|
1313
|
+
export declare function isInt32Array(value: unknown): value is Int32Array;
|
|
1314
|
+
|
|
1315
|
+
/** Determine whether a value is an `Int8Array`.
|
|
1316
|
+
*
|
|
1317
|
+
* @example
|
|
1318
|
+
* ```ts
|
|
1319
|
+
* isInt8Array(new Int8Array(2)) // true
|
|
1320
|
+
* isInt8Array(new Uint8Array(2)) // false
|
|
1321
|
+
* ```
|
|
1322
|
+
*/
|
|
1323
|
+
export declare function isInt8Array(value: unknown): value is Int8Array;
|
|
1324
|
+
|
|
1325
|
+
/** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).
|
|
1326
|
+
*
|
|
1327
|
+
* @example
|
|
1328
|
+
* ```ts
|
|
1329
|
+
* isInteger(3) // true
|
|
1330
|
+
* isInteger(3.5) // false
|
|
1331
|
+
* ```
|
|
1332
|
+
*/
|
|
1333
|
+
export declare function isInteger(value: unknown): value is number;
|
|
1334
|
+
|
|
1335
|
+
/**
|
|
1336
|
+
* Determine whether a value implements the iterable protocol (`Symbol.iterator`).
|
|
1337
|
+
*
|
|
1338
|
+
* @remarks
|
|
1339
|
+
* Strings are explicitly included: a string has a callable `Symbol.iterator`
|
|
1340
|
+
* but is not an object, so the generic object path alone would miss it.
|
|
1341
|
+
*
|
|
1342
|
+
* @example
|
|
1343
|
+
* ```ts
|
|
1344
|
+
* isIterable([1, 2]) // true
|
|
1345
|
+
* isIterable('abc') // true
|
|
1346
|
+
* isIterable({ a: 1 }) // false
|
|
1347
|
+
* ```
|
|
1348
|
+
*/
|
|
1349
|
+
export declare function isIterable<T = unknown>(value: unknown): value is Iterable<T>;
|
|
1350
|
+
|
|
1351
|
+
/**
|
|
1352
|
+
* Determine whether a value is a primitive JSON value.
|
|
1353
|
+
*
|
|
1354
|
+
* @remarks
|
|
1355
|
+
* The flat leaf of any JSON document: `null`, a string, a **finite** number, or
|
|
1356
|
+
* a boolean. Uses {@link isFiniteNumber} (not {@link isNumber}) because real JSON
|
|
1357
|
+
* carries no `NaN` / `±Infinity` — `JSON.stringify(NaN)` is `'null'`.
|
|
1358
|
+
*
|
|
1359
|
+
* The recursive {@link isJSONValue} guard is shipped and stays total with
|
|
1360
|
+
* cycle-safe walking. Dedicated `isJSONObject` / `isJSONSchema` validators and
|
|
1361
|
+
* the broad `JSONSchemaDefinition` remain omitted; compose narrower shapes with
|
|
1362
|
+
* the combinators and gate untrusted strings with `parseJSON` / `parseJSONAs`.
|
|
1363
|
+
*
|
|
1364
|
+
* @param value - The value to test
|
|
1365
|
+
* @returns `true` when `value` is `null`, a string, a finite number, or a boolean
|
|
1366
|
+
*
|
|
1367
|
+
* @example
|
|
1368
|
+
* ```ts
|
|
1369
|
+
* isJSONPrimitive(null) // true
|
|
1370
|
+
* isJSONPrimitive('hi') // true
|
|
1371
|
+
* isJSONPrimitive(42) // true
|
|
1372
|
+
* isJSONPrimitive(Number.NaN) // false — not representable in JSON
|
|
1373
|
+
* isJSONPrimitive({}) // false
|
|
1374
|
+
* ```
|
|
1375
|
+
*/
|
|
1376
|
+
export declare function isJSONPrimitive(value: unknown): value is JSONPrimitive;
|
|
1377
|
+
|
|
1378
|
+
/**
|
|
1379
|
+
* Determine whether a value is a cycle-safe JSON value.
|
|
1380
|
+
*
|
|
1381
|
+
* @remarks
|
|
1382
|
+
* Total guard: never throws, returns `false` for cycles, functions, `Date`
|
|
1383
|
+
* instances, class instances, `NaN`, and `±Infinity`. Arrays and plain records
|
|
1384
|
+
* are walked with an ancestor set so recursive input fails instead of hanging.
|
|
1385
|
+
* The whole walk runs inside `attempt` (AGENTS §14): a hostile getter on a
|
|
1386
|
+
* record property, or a revoked `Proxy` anywhere in the structure, is caught
|
|
1387
|
+
* and yields `false` instead of escaping as a thrown error.
|
|
1388
|
+
*
|
|
1389
|
+
* @param value - The value to test
|
|
1390
|
+
* @returns `true` when the value has a JSON representation
|
|
1391
|
+
*
|
|
1392
|
+
* @example
|
|
1393
|
+
* ```ts
|
|
1394
|
+
* isJSONValue({ nested: [1, 'x', null] }) // true
|
|
1395
|
+
* isJSONValue(Number.NaN) // false
|
|
1396
|
+
* ```
|
|
1397
|
+
*/
|
|
1398
|
+
export declare function isJSONValue(value: unknown): value is JSONValue;
|
|
1399
|
+
|
|
1400
|
+
/** Determine whether a value is a `Map`.
|
|
1401
|
+
*
|
|
1402
|
+
* @example
|
|
1403
|
+
* ```ts
|
|
1404
|
+
* isMap(new Map()) // true
|
|
1405
|
+
* isMap({}) // false
|
|
1406
|
+
* ```
|
|
1407
|
+
*/
|
|
1408
|
+
export declare function isMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V>;
|
|
1409
|
+
|
|
1410
|
+
/** Determine whether a value is a non-empty array (at least one element).
|
|
1411
|
+
*
|
|
1412
|
+
* @example
|
|
1413
|
+
* ```ts
|
|
1414
|
+
* isNonEmptyArray([1]) // true
|
|
1415
|
+
* isNonEmptyArray([]) // false
|
|
1416
|
+
* ```
|
|
1417
|
+
*/
|
|
1418
|
+
export declare function isNonEmptyArray<T = unknown>(value: unknown): value is readonly [T, ...T[]];
|
|
1419
|
+
|
|
1420
|
+
/** Determine whether a value is a non-empty `Map` (at least one entry).
|
|
1421
|
+
*
|
|
1422
|
+
* @example
|
|
1423
|
+
* ```ts
|
|
1424
|
+
* isNonEmptyMap(new Map([['a', 1]])) // true
|
|
1425
|
+
* isNonEmptyMap(new Map()) // false
|
|
1426
|
+
* ```
|
|
1427
|
+
*/
|
|
1428
|
+
export declare function isNonEmptyMap<K = unknown, V = unknown>(value: unknown): value is ReadonlyMap<K, V>;
|
|
1429
|
+
|
|
1430
|
+
/** Determine whether a value is a non-empty plain object (at least one own string or enumerable symbol key).
|
|
1431
|
+
*
|
|
1432
|
+
* @example
|
|
1433
|
+
* ```ts
|
|
1434
|
+
* isNonEmptyObject({ a: 1 }) // true
|
|
1435
|
+
* isNonEmptyObject({}) // false
|
|
1436
|
+
* ```
|
|
1437
|
+
*/
|
|
1438
|
+
export declare function isNonEmptyObject(value: unknown): value is Record<string | symbol, unknown>;
|
|
1439
|
+
|
|
1440
|
+
/** Determine whether a value is a non-empty `Set` (at least one element).
|
|
1441
|
+
*
|
|
1442
|
+
* @example
|
|
1443
|
+
* ```ts
|
|
1444
|
+
* isNonEmptySet(new Set([1])) // true
|
|
1445
|
+
* isNonEmptySet(new Set()) // false
|
|
1446
|
+
* ```
|
|
1447
|
+
*/
|
|
1448
|
+
export declare function isNonEmptySet<T = unknown>(value: unknown): value is ReadonlySet<T>;
|
|
1449
|
+
|
|
1450
|
+
/** Determine whether a value is a non-empty string (at least one character).
|
|
1451
|
+
*
|
|
1452
|
+
* @example
|
|
1453
|
+
* ```ts
|
|
1454
|
+
* isNonEmptyString('a') // true
|
|
1455
|
+
* isNonEmptyString('') // false
|
|
1456
|
+
* ```
|
|
1457
|
+
*/
|
|
1458
|
+
export declare function isNonEmptyString(value: unknown): value is string;
|
|
1459
|
+
|
|
1460
|
+
/** Determine whether a value is `null`.
|
|
1461
|
+
*
|
|
1462
|
+
* @example
|
|
1463
|
+
* ```ts
|
|
1464
|
+
* isNull(null) // true
|
|
1465
|
+
* isNull(undefined) // false
|
|
1466
|
+
* ```
|
|
1467
|
+
*/
|
|
1468
|
+
export declare function isNull(value: unknown): value is null;
|
|
1469
|
+
|
|
1470
|
+
/** Determine whether a value is a boolean or `null`.
|
|
1471
|
+
*
|
|
1472
|
+
* @example
|
|
1473
|
+
* ```ts
|
|
1474
|
+
* isNullableBoolean(true) // true
|
|
1475
|
+
* isNullableBoolean(null) // true
|
|
1476
|
+
* isNullableBoolean(1) // false
|
|
1477
|
+
* ```
|
|
1478
|
+
*/
|
|
1479
|
+
export declare function isNullableBoolean(value: unknown): value is boolean | null;
|
|
1480
|
+
|
|
1481
|
+
/** Determine whether a value is a number or `null` (the number may be `NaN` / `±Infinity`).
|
|
1482
|
+
*
|
|
1483
|
+
* @example
|
|
1484
|
+
* ```ts
|
|
1485
|
+
* isNullableNumber(42) // true
|
|
1486
|
+
* isNullableNumber(null) // true
|
|
1487
|
+
* isNullableNumber('hi') // false
|
|
1488
|
+
* ```
|
|
1489
|
+
*/
|
|
1490
|
+
export declare function isNullableNumber(value: unknown): value is number | null;
|
|
1491
|
+
|
|
1492
|
+
/** Determine whether a value is a string or `null`.
|
|
1493
|
+
*
|
|
1494
|
+
* @example
|
|
1495
|
+
* ```ts
|
|
1496
|
+
* isNullableString('hi') // true
|
|
1497
|
+
* isNullableString(null) // true
|
|
1498
|
+
* isNullableString(42) // false
|
|
1499
|
+
* ```
|
|
1500
|
+
*/
|
|
1501
|
+
export declare function isNullableString(value: unknown): value is string | null;
|
|
1502
|
+
|
|
1503
|
+
/**
|
|
1504
|
+
* Determine whether a value is a number.
|
|
1505
|
+
*
|
|
1506
|
+
* @remarks
|
|
1507
|
+
* Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.
|
|
1508
|
+
*
|
|
1509
|
+
* @example
|
|
1510
|
+
* ```ts
|
|
1511
|
+
* isNumber(42) // true
|
|
1512
|
+
* isNumber(Number.NaN) // true — NaN is still a number
|
|
1513
|
+
* isNumber('42') // false
|
|
1514
|
+
* ```
|
|
1515
|
+
*/
|
|
1516
|
+
export declare function isNumber(value: unknown): value is number;
|
|
1517
|
+
|
|
1518
|
+
/**
|
|
1519
|
+
* Determine whether a value is a non-null object.
|
|
1520
|
+
*
|
|
1521
|
+
* @remarks
|
|
1522
|
+
* `true` for arrays, class instances, plain objects, `Map`, `Set`, etc. — use
|
|
1523
|
+
* {@link isRecord} when you need a plain-record check.
|
|
1524
|
+
*
|
|
1525
|
+
* @example
|
|
1526
|
+
* ```ts
|
|
1527
|
+
* isObject({}) // true
|
|
1528
|
+
* isObject([]) // true
|
|
1529
|
+
* isObject(null) // false
|
|
1530
|
+
* ```
|
|
1531
|
+
*/
|
|
1532
|
+
export declare function isObject(value: unknown): value is object;
|
|
1533
|
+
|
|
1534
|
+
/** Determine whether a value is a native `Promise` (use {@link isPromiseLike} for any thenable).
|
|
1535
|
+
*
|
|
1536
|
+
* @example
|
|
1537
|
+
* ```ts
|
|
1538
|
+
* isPromise(Promise.resolve()) // true
|
|
1539
|
+
* isPromise({ then() {} }) // false
|
|
1540
|
+
* ```
|
|
1541
|
+
*/
|
|
1542
|
+
export declare function isPromise<T = unknown>(value: unknown): value is Promise<T>;
|
|
1543
|
+
|
|
1544
|
+
/**
|
|
1545
|
+
* Determine whether a value is promise-like — an object exposing callable
|
|
1546
|
+
* `then`, `catch`, and `finally` methods.
|
|
1547
|
+
*
|
|
1548
|
+
* @remarks
|
|
1549
|
+
* Accepts any object with all three methods, not only native `Promise`
|
|
1550
|
+
* instances. Use {@link isPromise} when you specifically need `instanceof Promise`.
|
|
1551
|
+
*
|
|
1552
|
+
* @example
|
|
1553
|
+
* ```ts
|
|
1554
|
+
* isPromiseLike(Promise.resolve()) // true
|
|
1555
|
+
* isPromiseLike({ then() {}, catch() {}, finally() {} }) // true
|
|
1556
|
+
* isPromiseLike({ then() {} }) // false
|
|
1557
|
+
* ```
|
|
1558
|
+
*/
|
|
1559
|
+
export declare function isPromiseLike<T = unknown>(value: unknown): value is Promise<T> | (PromiseLike<T> & {
|
|
1560
|
+
catch: unknown;
|
|
1561
|
+
finally: unknown;
|
|
1562
|
+
});
|
|
1563
|
+
|
|
1564
|
+
/**
|
|
1565
|
+
* Determine whether a value is a plain record (object literal or null-prototype),
|
|
1566
|
+
* not an array or class instance.
|
|
1567
|
+
*
|
|
1568
|
+
* @remarks
|
|
1569
|
+
* Use instead of {@link isObject} to distinguish a plain `{}` /
|
|
1570
|
+
* `Object.create(null)` from arrays, `Date`, `Map`, etc. The prototype-chain
|
|
1571
|
+
* test is realm-agnostic: rather than comparing against the current realm's
|
|
1572
|
+
* `Object.prototype` (which a plain object from another `vm.Context`, iframe,
|
|
1573
|
+
* or worker would fail), it accepts any value whose prototype is `null`, OR
|
|
1574
|
+
* whose prototype's own prototype is `null` — the shape every plain object
|
|
1575
|
+
* has in every realm, since `Object.prototype` itself always sits one step
|
|
1576
|
+
* above `null`. Arrays and class instances are still rejected: an array's
|
|
1577
|
+
* prototype chain runs through `Array.prototype` before `null`, and a class
|
|
1578
|
+
* instance's runs through the class's own prototype. The whole body runs
|
|
1579
|
+
* inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
|
|
1580
|
+
* `getPrototypeOf` trap cannot escape as a thrown error.
|
|
1581
|
+
*
|
|
1582
|
+
* @example
|
|
1583
|
+
* ```ts
|
|
1584
|
+
* isRecord({ a: 1 }) // true
|
|
1585
|
+
* isRecord(Object.create(null)) // true
|
|
1586
|
+
* isRecord([]) // false
|
|
1587
|
+
* isRecord(new Date()) // false
|
|
1588
|
+
* ```
|
|
1589
|
+
*/
|
|
1590
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
1591
|
+
|
|
1592
|
+
/** Determine whether a value is a `RegExp`.
|
|
1593
|
+
*
|
|
1594
|
+
* @example
|
|
1595
|
+
* ```ts
|
|
1596
|
+
* isRegExp(/a/) // true
|
|
1597
|
+
* isRegExp('a') // false
|
|
1598
|
+
* ```
|
|
1599
|
+
*/
|
|
1600
|
+
export declare function isRegExp(value: unknown): value is RegExp;
|
|
1601
|
+
|
|
1602
|
+
/** Determine whether a value is a `Set`.
|
|
1603
|
+
*
|
|
1604
|
+
* @example
|
|
1605
|
+
* ```ts
|
|
1606
|
+
* isSet(new Set()) // true
|
|
1607
|
+
* isSet([]) // false
|
|
1608
|
+
* ```
|
|
1609
|
+
*/
|
|
1610
|
+
export declare function isSet<T = unknown>(value: unknown): value is ReadonlySet<T>;
|
|
1611
|
+
|
|
1612
|
+
/**
|
|
1613
|
+
* Determine whether a value is a `SharedArrayBuffer`.
|
|
1614
|
+
*
|
|
1615
|
+
* @remarks
|
|
1616
|
+
* Guards the global existence of `SharedArrayBuffer` first — safe where it is
|
|
1617
|
+
* absent or disabled (e.g. a context that is not cross-origin isolated).
|
|
1618
|
+
*
|
|
1619
|
+
* @example
|
|
1620
|
+
* ```ts
|
|
1621
|
+
* isSharedArrayBuffer(new SharedArrayBuffer(8)) // true
|
|
1622
|
+
* isSharedArrayBuffer(new ArrayBuffer(8)) // false
|
|
1623
|
+
* ```
|
|
1624
|
+
*/
|
|
1625
|
+
export declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer;
|
|
1626
|
+
|
|
1627
|
+
/** Determine whether a value is a string.
|
|
1628
|
+
*
|
|
1629
|
+
* @example
|
|
1630
|
+
* ```ts
|
|
1631
|
+
* isString('hi') // true
|
|
1632
|
+
* isString(42) // false
|
|
1633
|
+
* ```
|
|
1634
|
+
*/
|
|
1635
|
+
export declare function isString(value: unknown): value is string;
|
|
1636
|
+
|
|
1637
|
+
/** Determine whether a value is a symbol.
|
|
1638
|
+
*
|
|
1639
|
+
* @example
|
|
1640
|
+
* ```ts
|
|
1641
|
+
* isSymbol(Symbol('x')) // true
|
|
1642
|
+
* isSymbol('x') // false
|
|
1643
|
+
* ```
|
|
1644
|
+
*/
|
|
1645
|
+
export declare function isSymbol(value: unknown): value is symbol;
|
|
1646
|
+
|
|
1647
|
+
/** Determine whether a value is exactly `true`.
|
|
1648
|
+
*
|
|
1649
|
+
* @example
|
|
1650
|
+
* ```ts
|
|
1651
|
+
* isTrue(true) // true
|
|
1652
|
+
* isTrue(false) // false
|
|
1653
|
+
* ```
|
|
1654
|
+
*/
|
|
1655
|
+
export declare function isTrue(value: unknown): value is true;
|
|
1656
|
+
|
|
1657
|
+
/** Determine whether a value is a `Uint16Array`.
|
|
1658
|
+
*
|
|
1659
|
+
* @example
|
|
1660
|
+
* ```ts
|
|
1661
|
+
* isUint16Array(new Uint16Array(2)) // true
|
|
1662
|
+
* isUint16Array(new Int16Array(2)) // false
|
|
1663
|
+
* ```
|
|
1664
|
+
*/
|
|
1665
|
+
export declare function isUint16Array(value: unknown): value is Uint16Array;
|
|
1666
|
+
|
|
1667
|
+
/** Determine whether a value is a `Uint32Array`.
|
|
1668
|
+
*
|
|
1669
|
+
* @example
|
|
1670
|
+
* ```ts
|
|
1671
|
+
* isUint32Array(new Uint32Array(2)) // true
|
|
1672
|
+
* isUint32Array(new Int32Array(2)) // false
|
|
1673
|
+
* ```
|
|
1674
|
+
*/
|
|
1675
|
+
export declare function isUint32Array(value: unknown): value is Uint32Array;
|
|
1676
|
+
|
|
1677
|
+
/** Determine whether a value is a `Uint8Array`.
|
|
1678
|
+
*
|
|
1679
|
+
* @example
|
|
1680
|
+
* ```ts
|
|
1681
|
+
* isUint8Array(new Uint8Array(2)) // true
|
|
1682
|
+
* isUint8Array(new Int8Array(2)) // false
|
|
1683
|
+
* ```
|
|
1684
|
+
*/
|
|
1685
|
+
export declare function isUint8Array(value: unknown): value is Uint8Array;
|
|
1686
|
+
|
|
1687
|
+
/** Determine whether a value is a `Uint8ClampedArray`.
|
|
1688
|
+
*
|
|
1689
|
+
* @example
|
|
1690
|
+
* ```ts
|
|
1691
|
+
* isUint8ClampedArray(new Uint8ClampedArray(2)) // true
|
|
1692
|
+
* isUint8ClampedArray(new Uint8Array(2)) // false
|
|
1693
|
+
* ```
|
|
1694
|
+
*/
|
|
1695
|
+
export declare function isUint8ClampedArray(value: unknown): value is Uint8ClampedArray;
|
|
1696
|
+
|
|
1697
|
+
/** Determine whether a value is `undefined`.
|
|
1698
|
+
*
|
|
1699
|
+
* @example
|
|
1700
|
+
* ```ts
|
|
1701
|
+
* isUndefined(undefined) // true
|
|
1702
|
+
* isUndefined(null) // false
|
|
1703
|
+
* ```
|
|
1704
|
+
*/
|
|
1705
|
+
export declare function isUndefined(value: unknown): value is undefined;
|
|
1706
|
+
|
|
1707
|
+
/**
|
|
1708
|
+
* Determine whether an ISO-8601-shaped string parses to a valid instant.
|
|
1709
|
+
*
|
|
1710
|
+
* @remarks
|
|
1711
|
+
* A pure, attempt-guarded `Date` validity probe: `new Date(value)` never
|
|
1712
|
+
* throws on a string input, but a value like `2020-13-45` parses to an
|
|
1713
|
+
* `Invalid Date` whose `getTime()` is `NaN` — this is the real validation
|
|
1714
|
+
* step behind {@link stringToFormat}'s `date` / `date-time` / `time`
|
|
1715
|
+
* branches, which pattern-match the shape first and confirm validity here.
|
|
1716
|
+
*
|
|
1717
|
+
* @param value - The candidate ISO-8601 string
|
|
1718
|
+
* @returns `true` when `value` parses to a real instant
|
|
1719
|
+
*
|
|
1720
|
+
* @example
|
|
1721
|
+
* ```ts
|
|
1722
|
+
* isValidISOInstant('2020-01-01') // true
|
|
1723
|
+
* isValidISOInstant('2020-13-45') // false
|
|
1724
|
+
* ```
|
|
1725
|
+
*/
|
|
1726
|
+
export declare function isValidISOInstant(value: string): boolean;
|
|
1727
|
+
|
|
1728
|
+
/** Determine whether a value is a `WeakMap`.
|
|
1729
|
+
*
|
|
1730
|
+
* @example
|
|
1731
|
+
* ```ts
|
|
1732
|
+
* isWeakMap(new WeakMap()) // true
|
|
1733
|
+
* isWeakMap({}) // false
|
|
1734
|
+
* ```
|
|
1735
|
+
*/
|
|
1736
|
+
export declare function isWeakMap(value: unknown): value is WeakMap<object, unknown>;
|
|
1737
|
+
|
|
1738
|
+
/** Determine whether a value is a `WeakSet`.
|
|
1739
|
+
*
|
|
1740
|
+
* @example
|
|
1741
|
+
* ```ts
|
|
1742
|
+
* isWeakSet(new WeakSet()) // true
|
|
1743
|
+
* isWeakSet({}) // false
|
|
1744
|
+
* ```
|
|
1745
|
+
*/
|
|
1746
|
+
export declare function isWeakSet(value: unknown): value is WeakSet<object>;
|
|
1747
|
+
|
|
1748
|
+
/** Determine whether a value is a function that declares zero parameters (`Function.length === 0`).
|
|
1749
|
+
*
|
|
1750
|
+
* @example
|
|
1751
|
+
* ```ts
|
|
1752
|
+
* isZeroArg(() => {}) // true
|
|
1753
|
+
* isZeroArg((a) => a) // false
|
|
1754
|
+
* ```
|
|
1755
|
+
*/
|
|
1756
|
+
export declare function isZeroArg(value: unknown): value is ZeroArgFunction;
|
|
1757
|
+
|
|
1758
|
+
/** Determine whether a value is a zero-argument async function.
|
|
1759
|
+
*
|
|
1760
|
+
* @example
|
|
1761
|
+
* ```ts
|
|
1762
|
+
* isZeroArgAsync(async () => {}) // true
|
|
1763
|
+
* isZeroArgAsync(async (a) => a) // false
|
|
1764
|
+
* ```
|
|
1765
|
+
*/
|
|
1766
|
+
export declare function isZeroArgAsync(value: unknown): value is ZeroArgAsyncFunction;
|
|
1767
|
+
|
|
1768
|
+
/** Determine whether a value is a zero-argument async generator function.
|
|
1769
|
+
*
|
|
1770
|
+
* @example
|
|
1771
|
+
* ```ts
|
|
1772
|
+
* isZeroArgAsyncGenerator(async function* () {}) // true
|
|
1773
|
+
* isZeroArgAsyncGenerator(async function* (a) {}) // false
|
|
1774
|
+
* ```
|
|
1775
|
+
*/
|
|
1776
|
+
export declare function isZeroArgAsyncGenerator(value: unknown): value is () => AsyncGenerator<unknown, unknown, unknown>;
|
|
1777
|
+
|
|
1778
|
+
/** Determine whether a value is a zero-argument generator function.
|
|
1779
|
+
*
|
|
1780
|
+
* @example
|
|
1781
|
+
* ```ts
|
|
1782
|
+
* isZeroArgGenerator(function* () {}) // true
|
|
1783
|
+
* isZeroArgGenerator(function* (a) {}) // false
|
|
1784
|
+
* ```
|
|
1785
|
+
*/
|
|
1786
|
+
export declare function isZeroArgGenerator(value: unknown): value is () => Generator<unknown, unknown, unknown>;
|
|
1787
|
+
|
|
1788
|
+
/**
|
|
1789
|
+
* Build a guard that accepts any iterable whose every element satisfies
|
|
1790
|
+
* `elementGuard`.
|
|
1791
|
+
*
|
|
1792
|
+
* @example
|
|
1793
|
+
* ```ts
|
|
1794
|
+
* const isNumberIterable = iterableOf(isNumber)
|
|
1795
|
+
* isNumberIterable([1, 2, 3]) // true
|
|
1796
|
+
* isNumberIterable(new Set([1, 2])) // true
|
|
1797
|
+
* isNumberIterable([1, 'two']) // false
|
|
1798
|
+
* ```
|
|
1799
|
+
*/
|
|
1800
|
+
export declare function iterableOf<T>(elementGuard: Guard<T>): Guard<Iterable<T>>;
|
|
1801
|
+
|
|
1802
|
+
export declare function iterableOf(elementGuard: (value: unknown) => boolean): Guard<Iterable<unknown>>;
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* The seven standard JSON Schema `type` names, frozen.
|
|
1806
|
+
*
|
|
1807
|
+
* @remarks
|
|
1808
|
+
* The runtime source of truth for the {@link JSONSchemaType} vocabulary. Compose
|
|
1809
|
+
* it with the shipped primitives instead of reaching for a bespoke guard:
|
|
1810
|
+
* `literalOf(...JSON_SCHEMA_TYPES)` is the guard, and
|
|
1811
|
+
* `parseEnum(value, JSON_SCHEMA_TYPES)` / `parseEnumField(record, path, JSON_SCHEMA_TYPES)`
|
|
1812
|
+
* is the parser.
|
|
1813
|
+
*
|
|
1814
|
+
* @example
|
|
1815
|
+
* ```ts
|
|
1816
|
+
* import { JSON_SCHEMA_TYPES, literalOf, parseEnumField } from '@src/core'
|
|
1817
|
+
*
|
|
1818
|
+
* const isSchemaType = literalOf(...JSON_SCHEMA_TYPES) // Guard<JSONSchemaType>
|
|
1819
|
+
* parseEnumField(schema, 'type', JSON_SCHEMA_TYPES) // JSONSchemaType | undefined
|
|
1820
|
+
* ```
|
|
1821
|
+
*/
|
|
1822
|
+
export declare const JSON_SCHEMA_TYPES: readonly JSONSchemaType[];
|
|
1823
|
+
|
|
1824
|
+
/**
|
|
1825
|
+
* A primitive JSON value — the flat leaf of any JSON document.
|
|
1826
|
+
*
|
|
1827
|
+
* @remarks
|
|
1828
|
+
* The recursive {@link JSONValue} tree type is shipped for consumers that need a
|
|
1829
|
+
* reusable JSON metadata contract. Dedicated `JSONObject` / `JSONArray` aliases
|
|
1830
|
+
* remain unshipped; compose those narrower shapes with the combinators, or keep
|
|
1831
|
+
* an untrusted parse result as `unknown` and narrow it.
|
|
1832
|
+
*/
|
|
1833
|
+
export declare type JSONPrimitive = string | number | boolean | null;
|
|
1834
|
+
|
|
1835
|
+
/**
|
|
1836
|
+
* A JSON Schema fragment — the subset of keywords the contract compiler emits
|
|
1837
|
+
* and {@link RawShape} embeds.
|
|
1838
|
+
*
|
|
1839
|
+
* @remarks
|
|
1840
|
+
* Intentionally lean (not the full ~50-keyword vocabulary): it carries only the
|
|
1841
|
+
* keywords {@link Infer}-driven `compileSchema` produces, plus `format` —
|
|
1842
|
+
* emitted by the {@link stringToFormat} / {@link samplesToFormat} inference
|
|
1843
|
+
* heuristics (`valueToSchema` / `samplesToSchema`), never by `compileSchema`.
|
|
1844
|
+
* Recursive via `items` / `properties` / `additionalProperties` / `anyOf` /
|
|
1845
|
+
* `oneOf`, but every walk is over a finite, developer-authored shape — there
|
|
1846
|
+
* is no cycle/depth risk.
|
|
1847
|
+
*/
|
|
1848
|
+
export declare interface JSONSchema {
|
|
1849
|
+
readonly type?: JSONSchemaType;
|
|
1850
|
+
readonly description?: string;
|
|
1851
|
+
readonly enum?: readonly (string | number | boolean)[];
|
|
1852
|
+
readonly minLength?: number;
|
|
1853
|
+
readonly maxLength?: number;
|
|
1854
|
+
readonly pattern?: string;
|
|
1855
|
+
readonly format?: string;
|
|
1856
|
+
readonly minimum?: number;
|
|
1857
|
+
readonly maximum?: number;
|
|
1858
|
+
readonly minItems?: number;
|
|
1859
|
+
readonly maxItems?: number;
|
|
1860
|
+
readonly items?: JSONSchema;
|
|
1861
|
+
readonly properties?: Readonly<Record<string, JSONSchema>>;
|
|
1862
|
+
readonly required?: readonly string[];
|
|
1863
|
+
readonly additionalProperties?: boolean | JSONSchema;
|
|
1864
|
+
readonly anyOf?: readonly JSONSchema[];
|
|
1865
|
+
readonly oneOf?: readonly JSONSchema[];
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
/** The seven standard JSON Schema `type` names. */
|
|
1869
|
+
export declare type JSONSchemaType = 'null' | 'boolean' | 'object' | 'array' | 'number' | 'integer' | 'string';
|
|
1870
|
+
|
|
1871
|
+
/**
|
|
1872
|
+
* A JSON passthrough shape — accepts any JSON value.
|
|
1873
|
+
*
|
|
1874
|
+
* @remarks
|
|
1875
|
+
* The compiled guard is a sound {@link isJSONValue} check (rejecting cycles,
|
|
1876
|
+
* functions, `NaN`, and `±Infinity`); the parser gates through that guard; the
|
|
1877
|
+
* schema is the empty schema `{}` (matches any JSON instance); the generator
|
|
1878
|
+
* emits a small deterministic {@link JSONValue}. Unlike {@link RawShape}, whose
|
|
1879
|
+
* guard accepts anything, this shape validates that a value is real JSON.
|
|
1880
|
+
*/
|
|
1881
|
+
export declare interface JSONShape {
|
|
1882
|
+
readonly type: 'json';
|
|
1883
|
+
readonly description?: string;
|
|
1884
|
+
}
|
|
1885
|
+
|
|
1886
|
+
/**
|
|
1887
|
+
* Build a {@link JSONShape}.
|
|
1888
|
+
*
|
|
1889
|
+
* @remarks
|
|
1890
|
+
* The sound counterpart of {@link rawShape}: `rawShape` embeds an arbitrary
|
|
1891
|
+
* schema fragment and accepts anything at runtime, while `jsonShape` validates
|
|
1892
|
+
* that a value is real JSON (via {@link isJSONValue}).
|
|
1893
|
+
*
|
|
1894
|
+
* @param options - Optional `description`
|
|
1895
|
+
* @returns A JSON passthrough shape
|
|
1896
|
+
*
|
|
1897
|
+
* @example
|
|
1898
|
+
* ```ts
|
|
1899
|
+
* const payload = jsonShape({ description: 'Arbitrary JSON payload' })
|
|
1900
|
+
* ```
|
|
1901
|
+
*/
|
|
1902
|
+
export declare function jsonShape(options?: JSONShapeOptions): JSONShape;
|
|
1903
|
+
|
|
1904
|
+
/** Options for {@link JSONShape} (via `jsonShape`). */
|
|
1905
|
+
export declare interface JSONShapeOptions {
|
|
1906
|
+
readonly description?: string;
|
|
1907
|
+
}
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* A recursive JSON value — primitives, arrays, and object records.
|
|
1911
|
+
*
|
|
1912
|
+
* @remarks
|
|
1913
|
+
* The static type admits any `number` because TypeScript cannot express
|
|
1914
|
+
* finiteness. The {@link isJSONValue} guard rejects `NaN` and `±Infinity` since
|
|
1915
|
+
* they have no JSON representation.
|
|
1916
|
+
*
|
|
1917
|
+
* @example
|
|
1918
|
+
* ```ts
|
|
1919
|
+
* const value: JSONValue = { nested: [1, 'x', null] }
|
|
1920
|
+
* ```
|
|
1921
|
+
*/
|
|
1922
|
+
export declare type JSONValue = JSONPrimitive | readonly JSONValue[] | {
|
|
1923
|
+
readonly [key: string]: JSONValue;
|
|
1924
|
+
};
|
|
1925
|
+
|
|
1926
|
+
/**
|
|
1927
|
+
* Build a guard that accepts values that are own keys of the provided object.
|
|
1928
|
+
*
|
|
1929
|
+
* @remarks
|
|
1930
|
+
* Membership is tested with `Object.hasOwn`, so inherited prototype-chain keys
|
|
1931
|
+
* (`toString`, `constructor`, …) are rejected. An own property that shadows a
|
|
1932
|
+
* prototype name is accepted.
|
|
1933
|
+
*
|
|
1934
|
+
* @example
|
|
1935
|
+
* ```ts
|
|
1936
|
+
* const COLORS = { red: '#f00', green: '#0f0', blue: '#00f' } as const
|
|
1937
|
+
* const isColorKey = keyOf(COLORS)
|
|
1938
|
+
* isColorKey('red') // true
|
|
1939
|
+
* isColorKey('purple') // false
|
|
1940
|
+
* isColorKey('toString') // false — inherited, not an own key
|
|
1941
|
+
* ```
|
|
1942
|
+
*/
|
|
1943
|
+
export declare function keyOf<const O extends Readonly<Record<PropertyKey, unknown>>>(value: O): Guard<keyof O>;
|
|
1944
|
+
|
|
1945
|
+
/**
|
|
1946
|
+
* Defer guard creation until first use by calling `thunk()` on every
|
|
1947
|
+
* invocation.
|
|
1948
|
+
*
|
|
1949
|
+
* @remarks
|
|
1950
|
+
* `thunk` is called on every guard call, not cached — this lets it close over a
|
|
1951
|
+
* binding assigned *after* `lazyOf` is called, the primary use case for
|
|
1952
|
+
* self-referential recursive guards. Per §14 a throw from `thunk` (or the guard
|
|
1953
|
+
* it resolves to) is contained and reported as a non-match.
|
|
1954
|
+
*
|
|
1955
|
+
* A recursive guard built this way has no cycle/depth detection: a cyclic or
|
|
1956
|
+
* pathologically deep input is stack-bounded — the overflow is contained and the
|
|
1957
|
+
* guard returns `false` rather than throwing, but it is not validated correctly
|
|
1958
|
+
* past that bound.
|
|
1959
|
+
*
|
|
1960
|
+
* @example
|
|
1961
|
+
* ```ts
|
|
1962
|
+
* type Tree = { value: number; children: Tree[] }
|
|
1963
|
+
* let isTree: Guard<Tree>
|
|
1964
|
+
* isTree = recordOf({ value: isNumber, children: arrayOf(lazyOf(() => isTree)) })
|
|
1965
|
+
* ```
|
|
1966
|
+
*/
|
|
1967
|
+
export declare function lazyOf<T>(thunk: () => Guard<T>): Guard<T>;
|
|
1968
|
+
|
|
1969
|
+
/**
|
|
1970
|
+
* Build a guard that accepts values identical (via `Object.is`) to one of the
|
|
1971
|
+
* provided literal primitives.
|
|
1972
|
+
*
|
|
1973
|
+
* @example
|
|
1974
|
+
* ```ts
|
|
1975
|
+
* const isRole = literalOf('admin', 'member', 'guest')
|
|
1976
|
+
* isRole('admin') // true
|
|
1977
|
+
* isRole('owner') // false
|
|
1978
|
+
* ```
|
|
1979
|
+
*/
|
|
1980
|
+
export declare function literalOf<const Literals extends ReadonlyArray<string | number | boolean>>(...literals: Literals): Guard<Literals[number]>;
|
|
1981
|
+
|
|
1982
|
+
/** A literal shape — accepts exactly one of a fixed set of primitive values. */
|
|
1983
|
+
export declare interface LiteralShape<T extends readonly (string | number | boolean)[] = readonly (string | number | boolean)[]> {
|
|
1984
|
+
readonly type: 'literal';
|
|
1985
|
+
readonly values: T;
|
|
1986
|
+
readonly description?: string;
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
/**
|
|
1990
|
+
* Build a literal shape from a fixed set of primitive values.
|
|
1991
|
+
*
|
|
1992
|
+
* @param values - The permitted literals
|
|
1993
|
+
* @param options - Optional `description`
|
|
1994
|
+
* @returns A literal shape whose `Infer` is the union of `values`
|
|
1995
|
+
*
|
|
1996
|
+
* @example
|
|
1997
|
+
* ```ts
|
|
1998
|
+
* const role = literalShape(['admin', 'member', 'guest'])
|
|
1999
|
+
* // Infer<typeof role> = 'admin' | 'member' | 'guest'
|
|
2000
|
+
*
|
|
2001
|
+
* const via = literalShape(['function', 'tool', 'agent'], { description: 'How to run the step.' })
|
|
2002
|
+
* ```
|
|
2003
|
+
*/
|
|
2004
|
+
export declare function literalShape<const T extends readonly (string | number | boolean)[]>(values: T, options?: LiteralShapeOptions): LiteralShape<T>;
|
|
2005
|
+
|
|
2006
|
+
/** Options for {@link LiteralShape} (via `literalShape`). */
|
|
2007
|
+
export declare interface LiteralShapeOptions {
|
|
2008
|
+
readonly description?: string;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
/**
|
|
2012
|
+
* Build a guard that accepts `Map` instances where every key satisfies
|
|
2013
|
+
* `keyGuard` and every value satisfies `valueGuard`.
|
|
2014
|
+
*
|
|
2015
|
+
* @example
|
|
2016
|
+
* ```ts
|
|
2017
|
+
* const isStringNumberMap = mapOf(isString, isNumber)
|
|
2018
|
+
* isStringNumberMap(new Map([['a', 1]])) // true
|
|
2019
|
+
* isStringNumberMap(new Map([[1, 'a']])) // false
|
|
2020
|
+
* ```
|
|
2021
|
+
*/
|
|
2022
|
+
export declare function mapOf<K, V>(keyGuard: Guard<K>, valueGuard: Guard<V>): Guard<ReadonlyMap<K, V>>;
|
|
2023
|
+
|
|
2024
|
+
export declare function mapOf(keyPredicate: (value: unknown) => boolean, valuePredicate: (value: unknown) => boolean): Guard<ReadonlyMap<unknown, unknown>>;
|
|
2025
|
+
|
|
2026
|
+
/**
|
|
2027
|
+
* Build a guard that accepts strings matching a regular expression.
|
|
2028
|
+
*
|
|
2029
|
+
* @example
|
|
2030
|
+
* ```ts
|
|
2031
|
+
* const isHex = matchOf(/^[0-9a-f]+$/)
|
|
2032
|
+
* isHex('1a2f') // true
|
|
2033
|
+
* isHex('xyz') // false
|
|
2034
|
+
* ```
|
|
2035
|
+
*/
|
|
2036
|
+
export declare function matchOf(pattern: RegExp): Guard<string>;
|
|
2037
|
+
|
|
2038
|
+
/**
|
|
2039
|
+
* Negate a guard or predicate — passes when `guard` returns `false`.
|
|
2040
|
+
*
|
|
2041
|
+
* @remarks
|
|
2042
|
+
* Typed as `Guard<unknown>` because `Exclude<unknown, T>` is not useful; use
|
|
2043
|
+
* {@link complementOf} when you need the narrowed `Exclude<TBase, TExcluded>`.
|
|
2044
|
+
*
|
|
2045
|
+
* @example
|
|
2046
|
+
* ```ts
|
|
2047
|
+
* const isNotNull = notOf(isNull)
|
|
2048
|
+
* ```
|
|
2049
|
+
*/
|
|
2050
|
+
export declare function notOf(guard: (value: unknown) => boolean): Guard<unknown>;
|
|
2051
|
+
|
|
2052
|
+
/**
|
|
2053
|
+
* Extend a guard to also allow `null`.
|
|
2054
|
+
*
|
|
2055
|
+
* @example
|
|
2056
|
+
* ```ts
|
|
2057
|
+
* const isNullableString = nullableOf(isString)
|
|
2058
|
+
* isNullableString('hi') // true
|
|
2059
|
+
* isNullableString(null) // true
|
|
2060
|
+
* isNullableString(42) // false
|
|
2061
|
+
* ```
|
|
2062
|
+
*/
|
|
2063
|
+
export declare function nullableOf<T>(guard: Guard<T>): Guard<T | null>;
|
|
2064
|
+
|
|
2065
|
+
/** A nullable wrapper — the inner shape may be `null`. */
|
|
2066
|
+
export declare interface NullableShape<S extends ContractShape = ContractShape> {
|
|
2067
|
+
readonly type: 'nullable';
|
|
2068
|
+
readonly inner: S;
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
/**
|
|
2072
|
+
* Wrap a shape so it may be `null`.
|
|
2073
|
+
*
|
|
2074
|
+
* @param inner - The wrapped shape
|
|
2075
|
+
* @returns A nullable shape
|
|
2076
|
+
*
|
|
2077
|
+
* @example
|
|
2078
|
+
* ```ts
|
|
2079
|
+
* const bio = nullableShape(stringShape())
|
|
2080
|
+
* // Infer<typeof bio> = string | null
|
|
2081
|
+
* ```
|
|
2082
|
+
*/
|
|
2083
|
+
export declare function nullableShape<S extends ContractShape>(inner: S): NullableShape<S>;
|
|
2084
|
+
|
|
2085
|
+
/** A null shape — accepts only `null`. */
|
|
2086
|
+
export declare interface NullShape {
|
|
2087
|
+
readonly type: 'null';
|
|
2088
|
+
readonly description?: string;
|
|
2089
|
+
}
|
|
2090
|
+
|
|
2091
|
+
/**
|
|
2092
|
+
* Build a {@link NullShape}.
|
|
2093
|
+
*
|
|
2094
|
+
* @param options - Optional `description`
|
|
2095
|
+
* @returns A null shape
|
|
2096
|
+
*
|
|
2097
|
+
* @example
|
|
2098
|
+
* ```ts
|
|
2099
|
+
* const empty = nullShape()
|
|
2100
|
+
* ```
|
|
2101
|
+
*/
|
|
2102
|
+
export declare function nullShape(options?: NullShapeOptions): NullShape;
|
|
2103
|
+
|
|
2104
|
+
/** Options for {@link NullShape} (via `nullShape`). */
|
|
2105
|
+
export declare interface NullShapeOptions {
|
|
2106
|
+
readonly description?: string;
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
/** A numeric shape with optional bounds; `integer` restricts to whole numbers. */
|
|
2110
|
+
export declare interface NumberShape {
|
|
2111
|
+
readonly type: 'number';
|
|
2112
|
+
readonly min?: number;
|
|
2113
|
+
readonly max?: number;
|
|
2114
|
+
readonly integer?: boolean;
|
|
2115
|
+
readonly description?: string;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
2118
|
+
/**
|
|
2119
|
+
* Build a numeric {@link NumberShape}.
|
|
2120
|
+
*
|
|
2121
|
+
* @param options - Optional bounds (`min` / `max`), `integer`, and `description`
|
|
2122
|
+
* @returns A number shape
|
|
2123
|
+
*
|
|
2124
|
+
* @example
|
|
2125
|
+
* ```ts
|
|
2126
|
+
* const age = numberShape({ min: 0, max: 120 })
|
|
2127
|
+
* ```
|
|
2128
|
+
*/
|
|
2129
|
+
export declare function numberShape(options?: NumberShapeOptions): NumberShape;
|
|
2130
|
+
|
|
2131
|
+
/** Options for {@link NumberShape} (via `numberShape` / `integerShape`). */
|
|
2132
|
+
export declare interface NumberShapeOptions {
|
|
2133
|
+
readonly min?: number;
|
|
2134
|
+
readonly max?: number;
|
|
2135
|
+
readonly integer?: boolean;
|
|
2136
|
+
readonly description?: string;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
/**
|
|
2140
|
+
* An object shape — a map of property names to child shapes.
|
|
2141
|
+
*
|
|
2142
|
+
* @remarks
|
|
2143
|
+
* A property whose shape is an {@link OptionalShape} may be absent; all others
|
|
2144
|
+
* are required. `additionalProperties` controls unknown keys: `undefined` /
|
|
2145
|
+
* `false` rejects them (closed), `true` accepts them as-is, a `ContractShape`
|
|
2146
|
+
* validates them.
|
|
2147
|
+
*/
|
|
2148
|
+
export declare interface ObjectShape<P extends Readonly<Record<string, ContractShape>> = Readonly<Record<string, ContractShape>>, A extends boolean | ContractShape = boolean | ContractShape> {
|
|
2149
|
+
readonly type: 'object';
|
|
2150
|
+
readonly properties: P;
|
|
2151
|
+
readonly additionalProperties?: A;
|
|
2152
|
+
readonly description?: string;
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
/**
|
|
2156
|
+
* Build an {@link ObjectShape} from a property map.
|
|
2157
|
+
*
|
|
2158
|
+
* @remarks
|
|
2159
|
+
* Wrap any property in {@link optionalShape} to allow its absence. By default
|
|
2160
|
+
* the compiled guard rejects unknown keys; pass `additionalProperties` to open
|
|
2161
|
+
* the object.
|
|
2162
|
+
*
|
|
2163
|
+
* @param properties - Map of property names to child shapes
|
|
2164
|
+
* @param options - Optional `additionalProperties` and `description`
|
|
2165
|
+
* @returns An object shape
|
|
2166
|
+
*
|
|
2167
|
+
* @example
|
|
2168
|
+
* ```ts
|
|
2169
|
+
* const user = objectShape({
|
|
2170
|
+
* name: stringShape({ min: 1 }),
|
|
2171
|
+
* age: integerShape({ min: 0, max: 120 }),
|
|
2172
|
+
* bio: optionalShape(stringShape()),
|
|
2173
|
+
* })
|
|
2174
|
+
* ```
|
|
2175
|
+
*/
|
|
2176
|
+
export declare function objectShape<P extends Readonly<Record<string, ContractShape>>, const A extends boolean | ContractShape = false>(properties: P, options?: ObjectShapeOptions<A>): ObjectShape<P, A>;
|
|
2177
|
+
|
|
2178
|
+
/** Options for {@link ObjectShape} (via `objectShape`). */
|
|
2179
|
+
export declare interface ObjectShapeOptions<A extends boolean | ContractShape = boolean | ContractShape> {
|
|
2180
|
+
readonly additionalProperties?: A;
|
|
2181
|
+
readonly description?: string;
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
/**
|
|
2185
|
+
* Build a new guard shape by removing the listed keys — the structural
|
|
2186
|
+
* equivalent of `Omit<T, K>`. Produces a shape for {@link recordOf}, not a guard.
|
|
2187
|
+
*
|
|
2188
|
+
* @example
|
|
2189
|
+
* ```ts
|
|
2190
|
+
* const full = { name: isString, age: isNumber, role: isString }
|
|
2191
|
+
* const isPublic = recordOf(omitOf(full, ['role']))
|
|
2192
|
+
* isPublic({ name: 'Ada', age: 36 }) // true
|
|
2193
|
+
* ```
|
|
2194
|
+
*/
|
|
2195
|
+
export declare function omitOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, keys: K): Omit<S, K[number]>;
|
|
2196
|
+
|
|
2197
|
+
/**
|
|
2198
|
+
* Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
|
|
2199
|
+
*
|
|
2200
|
+
* @remarks
|
|
2201
|
+
* Unlike {@link unionShape} (`anyOf` — at least one variant matches),
|
|
2202
|
+
* `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:
|
|
2203
|
+
*
|
|
2204
|
+
* - **Guard**: accepts the value only when exactly one variant's guard
|
|
2205
|
+
* accepts it. A value matching two-or-more variants — which would violate
|
|
2206
|
+
* the emitted `oneOf` schema — is rejected, even though it would pass
|
|
2207
|
+
* {@link unionShape}'s guard.
|
|
2208
|
+
* - **Parser**: judged on the RAW input's guard matches only, with NO
|
|
2209
|
+
* coercion fallback for an ambiguous input. When exactly one variant's
|
|
2210
|
+
* guard accepts the raw value, that variant's parser runs. Zero matches or
|
|
2211
|
+
* two-or-more matches both parse to `undefined` — a value ambiguous
|
|
2212
|
+
* between variants has no well-defined coercion target.
|
|
2213
|
+
*
|
|
2214
|
+
* Prefer {@link unionShape} when a value may legitimately satisfy more than
|
|
2215
|
+
* one variant (e.g. overlapping shapes) and any match is acceptable. Prefer
|
|
2216
|
+
* `oneOfShape` when overlap between variants indicates malformed input that
|
|
2217
|
+
* must be rejected.
|
|
2218
|
+
*
|
|
2219
|
+
* @param variants - The candidate shapes
|
|
2220
|
+
* @returns A union shape with `mode: 'oneOf'`
|
|
2221
|
+
*
|
|
2222
|
+
* @example
|
|
2223
|
+
* ```ts
|
|
2224
|
+
* const id = oneOfShape(numberShape(), integerShape())
|
|
2225
|
+
* // 3 fails — matches both numberShape and integerShape
|
|
2226
|
+
* // 3.5 passes — matches numberShape only
|
|
2227
|
+
* ```
|
|
2228
|
+
*/
|
|
2229
|
+
export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
|
|
2230
|
+
|
|
2231
|
+
/**
|
|
2232
|
+
* Like {@link FromGuards}, but every key listed in `K` becomes a true optional
|
|
2233
|
+
* member (`?`) rather than a required key widened with `| undefined`.
|
|
2234
|
+
*
|
|
2235
|
+
* @remarks
|
|
2236
|
+
* A key present in `K` may be omitted entirely; if present, its value must
|
|
2237
|
+
* still satisfy the key's guard — a present key holding `undefined` is not
|
|
2238
|
+
* accepted.
|
|
2239
|
+
*
|
|
2240
|
+
* @typeParam S - The full guard shape
|
|
2241
|
+
* @typeParam K - Tuple of keys to make optional
|
|
2242
|
+
*/
|
|
2243
|
+
export declare type OptionalFromGuards<S extends GuardsShape, K extends ReadonlyArray<keyof S>> = Readonly<{
|
|
2244
|
+
[P in Exclude<keyof S, K[number]>]: FromGuards<S>[P];
|
|
2245
|
+
} & {
|
|
2246
|
+
[P in Extract<keyof S, K[number]>]?: FromGuards<S>[P];
|
|
2247
|
+
}>;
|
|
2248
|
+
|
|
2249
|
+
/**
|
|
2250
|
+
* Extend a guard to also allow `undefined` — the optional counterpart of
|
|
2251
|
+
* {@link nullableOf}.
|
|
2252
|
+
*
|
|
2253
|
+
* @example
|
|
2254
|
+
* ```ts
|
|
2255
|
+
* const isOptionalString = optionalOf(isString)
|
|
2256
|
+
* isOptionalString('hi') // true
|
|
2257
|
+
* isOptionalString(undefined) // true
|
|
2258
|
+
* isOptionalString(null) // false
|
|
2259
|
+
* ```
|
|
2260
|
+
*/
|
|
2261
|
+
export declare function optionalOf<T>(guard: Guard<T>): Guard<T | undefined>;
|
|
2262
|
+
|
|
2263
|
+
/** An optional wrapper — the inner shape may be absent (`undefined`). */
|
|
2264
|
+
export declare interface OptionalShape<S extends ContractShape = ContractShape> {
|
|
2265
|
+
readonly type: 'optional';
|
|
2266
|
+
readonly inner: S;
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
/**
|
|
2270
|
+
* Wrap a shape so it may be absent (`undefined`).
|
|
2271
|
+
*
|
|
2272
|
+
* @remarks
|
|
2273
|
+
* As an {@link objectShape} property, the field becomes a true optional property
|
|
2274
|
+
* in the inferred type.
|
|
2275
|
+
*
|
|
2276
|
+
* @param inner - The wrapped shape
|
|
2277
|
+
* @returns An optional shape
|
|
2278
|
+
*/
|
|
2279
|
+
export declare function optionalShape<S extends ContractShape>(inner: S): OptionalShape<S>;
|
|
2280
|
+
|
|
2281
|
+
/**
|
|
2282
|
+
* Combine two guards with logical OR — passes when at least one passes. For more
|
|
2283
|
+
* than two variants prefer {@link unionOf}.
|
|
2284
|
+
*
|
|
2285
|
+
* @example
|
|
2286
|
+
* ```ts
|
|
2287
|
+
* const isStringOrNumber = orOf(isString, isNumber)
|
|
2288
|
+
* ```
|
|
2289
|
+
*/
|
|
2290
|
+
export declare function orOf<A, B>(left: Guard<A>, right: Guard<B>): Guard<A | B>;
|
|
2291
|
+
|
|
2292
|
+
export declare function orOf(left: (value: unknown) => boolean, right: (value: unknown) => boolean): Guard<unknown>;
|
|
2293
|
+
|
|
2294
|
+
/**
|
|
2295
|
+
* Parse an unknown value to an array — the input reference, never cloned —
|
|
2296
|
+
* optionally guarding every element.
|
|
2297
|
+
*
|
|
2298
|
+
* @remarks
|
|
2299
|
+
* Without a `guard`, element types are NOT verified; let `T` default to
|
|
2300
|
+
* `unknown` rather than asserting a specific element type.
|
|
2301
|
+
*
|
|
2302
|
+
* @param value - The value to parse
|
|
2303
|
+
* @param guard - Optional element guard
|
|
2304
|
+
* @returns The array, or `undefined`
|
|
2305
|
+
*
|
|
2306
|
+
* @example
|
|
2307
|
+
* ```ts
|
|
2308
|
+
* parseArray([1, 2]) // [1, 2]
|
|
2309
|
+
* parseArray([1, 'x'], isNumber) // undefined
|
|
2310
|
+
* ```
|
|
2311
|
+
*/
|
|
2312
|
+
export declare function parseArray<T = unknown>(value: unknown, guard?: Guard<T>): readonly T[] | undefined;
|
|
2313
|
+
|
|
2314
|
+
/**
|
|
2315
|
+
* Read and parse an array field from a record by key or nested key path,
|
|
2316
|
+
* optionally guarding elements.
|
|
2317
|
+
*
|
|
2318
|
+
* @param record - The source record
|
|
2319
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2320
|
+
* @param guard - Optional element guard
|
|
2321
|
+
* @returns An array, or `undefined`
|
|
2322
|
+
*
|
|
2323
|
+
* @example
|
|
2324
|
+
* ```ts
|
|
2325
|
+
* parseArrayField({ tags: [1, 2] }, 'tags') // [1, 2]
|
|
2326
|
+
* parseArrayField({}, 'tags') // undefined
|
|
2327
|
+
* ```
|
|
2328
|
+
*/
|
|
2329
|
+
export declare function parseArrayField<T = unknown>(record: Record<string, unknown>, path: FieldPath, guard?: Guard<T>): readonly T[] | undefined;
|
|
2330
|
+
|
|
2331
|
+
/**
|
|
2332
|
+
* Parse an unknown value to a boolean.
|
|
2333
|
+
*
|
|
2334
|
+
* @remarks
|
|
2335
|
+
* A boolean is returned unchanged. The strings `'true'` / `'false'` / `'1'` /
|
|
2336
|
+
* `'0'` and the numbers `1` / `0` coerce to the matching boolean. Everything
|
|
2337
|
+
* else → `undefined`.
|
|
2338
|
+
*
|
|
2339
|
+
* @param value - The value to parse
|
|
2340
|
+
* @returns A boolean, or `undefined`
|
|
2341
|
+
*
|
|
2342
|
+
* @example
|
|
2343
|
+
* ```ts
|
|
2344
|
+
* parseBoolean(true) // true
|
|
2345
|
+
* parseBoolean('1') // true
|
|
2346
|
+
* parseBoolean('nope') // undefined
|
|
2347
|
+
* ```
|
|
2348
|
+
*/
|
|
2349
|
+
export declare function parseBoolean(value: unknown): boolean | undefined;
|
|
2350
|
+
|
|
2351
|
+
/**
|
|
2352
|
+
* Read and parse a boolean field from a record by key or nested key path.
|
|
2353
|
+
*
|
|
2354
|
+
* @param record - The source record
|
|
2355
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2356
|
+
* @returns A boolean, or `undefined`
|
|
2357
|
+
*
|
|
2358
|
+
* @example
|
|
2359
|
+
* ```ts
|
|
2360
|
+
* parseBooleanField({ on: 'true' }, 'on') // true
|
|
2361
|
+
* parseBooleanField({}, 'on') // undefined
|
|
2362
|
+
* ```
|
|
2363
|
+
*/
|
|
2364
|
+
export declare function parseBooleanField(record: Record<string, unknown>, path: FieldPath): boolean | undefined;
|
|
2365
|
+
|
|
2366
|
+
/**
|
|
2367
|
+
* Parse an unknown value as one of the allowed literal primitives.
|
|
2368
|
+
*
|
|
2369
|
+
* @remarks
|
|
2370
|
+
* Pairs with {@link literalOf} — both match by `Object.is`, so the
|
|
2371
|
+
* `parseEnum ↔ literalOf(...allowed)` pairing covers every literal primitive
|
|
2372
|
+
* (string, number, or boolean), not only strings. Matching is identity, never
|
|
2373
|
+
* cross-type coercion: `parseEnum('1', [1])` stays `undefined`.
|
|
2374
|
+
*
|
|
2375
|
+
* @param value - The value to parse
|
|
2376
|
+
* @param allowed - The permitted literal values
|
|
2377
|
+
* @returns The matched literal (by identity), or `undefined`
|
|
2378
|
+
*
|
|
2379
|
+
* @example
|
|
2380
|
+
* ```ts
|
|
2381
|
+
* parseEnum('b', ['a', 'b', 'c']) // 'b'
|
|
2382
|
+
* parseEnum('z', ['a', 'b', 'c']) // undefined
|
|
2383
|
+
* ```
|
|
2384
|
+
*/
|
|
2385
|
+
export declare function parseEnum<const T extends string | number | boolean>(value: unknown, allowed: readonly T[]): T | undefined;
|
|
2386
|
+
|
|
2387
|
+
/**
|
|
2388
|
+
* Read and parse an enum field from a record by key or nested key path.
|
|
2389
|
+
*
|
|
2390
|
+
* @param record - The source record
|
|
2391
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2392
|
+
* @param allowed - The permitted literal values
|
|
2393
|
+
* @returns The matched literal, or `undefined`
|
|
2394
|
+
*/
|
|
2395
|
+
export declare function parseEnumField<const T extends string | number | boolean>(record: Record<string, unknown>, path: FieldPath, allowed: readonly T[]): T | undefined;
|
|
2396
|
+
|
|
2397
|
+
/**
|
|
2398
|
+
* Parse an unknown value to a finite integer.
|
|
2399
|
+
*
|
|
2400
|
+
* @remarks
|
|
2401
|
+
* Accepts whatever {@link parseNumber} accepts, then requires the result to have
|
|
2402
|
+
* no fractional part. `3.14` / `'3.14'` → `undefined`.
|
|
2403
|
+
*
|
|
2404
|
+
* @param value - The value to parse
|
|
2405
|
+
* @returns A finite integer, or `undefined`
|
|
2406
|
+
*
|
|
2407
|
+
* @example
|
|
2408
|
+
* ```ts
|
|
2409
|
+
* parseInteger(42) // 42
|
|
2410
|
+
* parseInteger(3.14) // undefined
|
|
2411
|
+
* ```
|
|
2412
|
+
*/
|
|
2413
|
+
export declare function parseInteger(value: unknown): number | undefined;
|
|
2414
|
+
|
|
2415
|
+
/**
|
|
2416
|
+
* Read and parse a finite-integer field from a record by key or nested key path.
|
|
2417
|
+
*
|
|
2418
|
+
* @param record - The source record
|
|
2419
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2420
|
+
* @returns A finite integer, or `undefined`
|
|
2421
|
+
*/
|
|
2422
|
+
export declare function parseIntegerField(record: Record<string, unknown>, path: FieldPath): number | undefined;
|
|
2423
|
+
|
|
2424
|
+
/**
|
|
2425
|
+
* Parse a JSON string, returning `undefined` instead of throwing.
|
|
2426
|
+
*
|
|
2427
|
+
* @remarks
|
|
2428
|
+
* The safe boundary for untrusted JSON text: a malformed string yields
|
|
2429
|
+
* `undefined`, never an exception. Returns `unknown` — a successful parse proves
|
|
2430
|
+
* nothing about shape, so narrow the result with a guard (or use
|
|
2431
|
+
* {@link parseJSONAs}). A large document is not walked here; parsing is shallow
|
|
2432
|
+
* and lazy validation is the caller's to compose.
|
|
2433
|
+
*
|
|
2434
|
+
* @param value - The JSON string to parse
|
|
2435
|
+
* @returns The parsed value, or `undefined` when `value` is not valid JSON
|
|
2436
|
+
*/
|
|
2437
|
+
export declare function parseJSON(value: string): unknown;
|
|
2438
|
+
|
|
2439
|
+
/**
|
|
2440
|
+
* Parse a JSON string and validate the result against a guard.
|
|
2441
|
+
*
|
|
2442
|
+
* @remarks
|
|
2443
|
+
* The lazy, safe path from an untrusted string to a typed `T`: parse, then check
|
|
2444
|
+
* the parsed value with the guard you bring — typically one composed from the
|
|
2445
|
+
* combinators (`recordOf`, `arrayOf`, …). Only the shape the guard inspects is
|
|
2446
|
+
* validated, so a large document is never walked in full unless the guard does.
|
|
2447
|
+
*
|
|
2448
|
+
* @param value - The JSON string to parse
|
|
2449
|
+
* @param guard - The guard for the expected shape
|
|
2450
|
+
* @returns The parsed value when it satisfies `guard`, otherwise `undefined`
|
|
2451
|
+
*
|
|
2452
|
+
* @example
|
|
2453
|
+
* ```ts
|
|
2454
|
+
* const isConfig = recordOf({ host: isString, tags: arrayOf(isString) })
|
|
2455
|
+
* parseJSONAs('{"host":"localhost","tags":["a"]}', isConfig) // { host: 'localhost', tags: ['a'] }
|
|
2456
|
+
* parseJSONAs('{"host":"localhost"}', isConfig) // undefined — guard fails
|
|
2457
|
+
* parseJSONAs('not json', isConfig) // undefined — never throws
|
|
2458
|
+
* ```
|
|
2459
|
+
*/
|
|
2460
|
+
export declare function parseJSONAs<T>(value: string, guard: Guard<T>): T | undefined;
|
|
2461
|
+
|
|
2462
|
+
/**
|
|
2463
|
+
* Parse an unknown value to a cycle-safe JSON value — the input reference,
|
|
2464
|
+
* never cloned.
|
|
2465
|
+
*
|
|
2466
|
+
* @remarks
|
|
2467
|
+
* Unlike {@link parseRecord} / {@link parseArray}, this is a DEEP gate: it
|
|
2468
|
+
* walks the entire tree via {@link isJSONValue} rather than checking only the
|
|
2469
|
+
* top-level shape. That walk is cycle-safe and total (never throws) because
|
|
2470
|
+
* `isJSONValue` runs its own probe inside a guard, so an adversarial
|
|
2471
|
+
* structure (a cycle, a hostile getter) yields `undefined` instead of hanging
|
|
2472
|
+
* or throwing.
|
|
2473
|
+
*
|
|
2474
|
+
* @param value - The value to parse
|
|
2475
|
+
* @returns The value, or `undefined` when it is not a valid JSON value
|
|
2476
|
+
*
|
|
2477
|
+
* @example
|
|
2478
|
+
* ```ts
|
|
2479
|
+
* parseJSONValue({ a: 1 }) // { a: 1 }
|
|
2480
|
+
* parseJSONValue(Number.NaN) // undefined
|
|
2481
|
+
* ```
|
|
2482
|
+
*/
|
|
2483
|
+
export declare function parseJSONValue(value: unknown): JSONValue | undefined;
|
|
2484
|
+
|
|
2485
|
+
/**
|
|
2486
|
+
* Read and parse a JSON-value field from a record by key or nested key path.
|
|
2487
|
+
*
|
|
2488
|
+
* @remarks
|
|
2489
|
+
* Deep-gates the field's whole subtree via {@link parseJSONValue} — see that
|
|
2490
|
+
* function's remarks for why this differs from the shallow
|
|
2491
|
+
* {@link parseRecordField} / {@link parseArrayField}.
|
|
2492
|
+
*
|
|
2493
|
+
* @param record - The source record
|
|
2494
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2495
|
+
* @returns The value, or `undefined`
|
|
2496
|
+
*
|
|
2497
|
+
* @example
|
|
2498
|
+
* ```ts
|
|
2499
|
+
* parseJSONValueField({ data: { a: 1 } }, 'data') // { a: 1 }
|
|
2500
|
+
* parseJSONValueField({}, 'data') // undefined
|
|
2501
|
+
* ```
|
|
2502
|
+
*/
|
|
2503
|
+
export declare function parseJSONValueField(record: Record<string, unknown>, path: FieldPath): JSONValue | undefined;
|
|
2504
|
+
|
|
2505
|
+
/**
|
|
2506
|
+
* Parse an unknown value to `null`.
|
|
2507
|
+
*
|
|
2508
|
+
* @remarks
|
|
2509
|
+
* A successful parse returns `null` itself — distinct from the `undefined`
|
|
2510
|
+
* failure sentinel every other parser in this file uses. Only `null` passes;
|
|
2511
|
+
* every other value (including `undefined`) → `undefined`.
|
|
2512
|
+
*
|
|
2513
|
+
* @param value - The value to parse
|
|
2514
|
+
* @returns `null` on a successful parse, or `undefined`
|
|
2515
|
+
*
|
|
2516
|
+
* @example
|
|
2517
|
+
* ```ts
|
|
2518
|
+
* parseNull(null) // null
|
|
2519
|
+
* parseNull(undefined) // undefined
|
|
2520
|
+
* ```
|
|
2521
|
+
*/
|
|
2522
|
+
export declare function parseNull(value: unknown): null | undefined;
|
|
2523
|
+
|
|
2524
|
+
/**
|
|
2525
|
+
* Read and parse a `null` field from a record by key or nested key path.
|
|
2526
|
+
*
|
|
2527
|
+
* @remarks
|
|
2528
|
+
* A successful parse returns `null` itself — distinct from the `undefined`
|
|
2529
|
+
* failure sentinel, which also covers a missing field.
|
|
2530
|
+
*
|
|
2531
|
+
* @param record - The source record
|
|
2532
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2533
|
+
* @returns `null` on a successful parse, or `undefined`
|
|
2534
|
+
*
|
|
2535
|
+
* @example
|
|
2536
|
+
* ```ts
|
|
2537
|
+
* parseNullField({ value: null }, 'value') // null
|
|
2538
|
+
* parseNullField({}, 'value') // undefined
|
|
2539
|
+
* ```
|
|
2540
|
+
*/
|
|
2541
|
+
export declare function parseNullField(record: Record<string, unknown>, path: FieldPath): null | undefined;
|
|
2542
|
+
|
|
2543
|
+
/**
|
|
2544
|
+
* Parse an unknown value to a finite number.
|
|
2545
|
+
*
|
|
2546
|
+
* @remarks
|
|
2547
|
+
* A finite number is returned unchanged; a non-blank numeric string is parsed
|
|
2548
|
+
* via `Number(...)`. `NaN`, `±Infinity`, blank/non-numeric strings, and every
|
|
2549
|
+
* other type → `undefined`.
|
|
2550
|
+
*
|
|
2551
|
+
* @param value - The value to parse
|
|
2552
|
+
* @returns A finite number, or `undefined`
|
|
2553
|
+
*
|
|
2554
|
+
* @example
|
|
2555
|
+
* ```ts
|
|
2556
|
+
* parseNumber(42) // 42
|
|
2557
|
+
* parseNumber('42') // 42
|
|
2558
|
+
* parseNumber('abc') // undefined
|
|
2559
|
+
* ```
|
|
2560
|
+
*/
|
|
2561
|
+
export declare function parseNumber(value: unknown): number | undefined;
|
|
2562
|
+
|
|
2563
|
+
/**
|
|
2564
|
+
* Read and parse a finite-number field from a record by key or nested key path.
|
|
2565
|
+
*
|
|
2566
|
+
* @param record - The source record
|
|
2567
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2568
|
+
* @returns A finite number, or `undefined`
|
|
2569
|
+
*
|
|
2570
|
+
* @example
|
|
2571
|
+
* ```ts
|
|
2572
|
+
* parseNumberField({ age: '42' }, 'age') // 42
|
|
2573
|
+
* parseNumberField({}, 'age') // undefined
|
|
2574
|
+
* ```
|
|
2575
|
+
*/
|
|
2576
|
+
export declare function parseNumberField(record: Record<string, unknown>, path: FieldPath): number | undefined;
|
|
2577
|
+
|
|
2578
|
+
/**
|
|
2579
|
+
* A parser: coerces an unknown value to `T`, or returns `undefined`.
|
|
2580
|
+
*
|
|
2581
|
+
* @remarks
|
|
2582
|
+
* The runtime parallel of {@link Guard}. A parser pairs soundly with the guard
|
|
2583
|
+
* for its output type: a guard-valid input is returned unchanged, and every
|
|
2584
|
+
* non-`undefined` output satisfies that guard.
|
|
2585
|
+
*/
|
|
2586
|
+
export declare type Parser<T> = (value: unknown) => T | undefined;
|
|
2587
|
+
|
|
2588
|
+
/**
|
|
2589
|
+
* Parse an unknown value to a plain record — the input reference, never cloned.
|
|
2590
|
+
*
|
|
2591
|
+
* @param value - The value to parse
|
|
2592
|
+
* @returns The record, or `undefined`
|
|
2593
|
+
*/
|
|
2594
|
+
export declare function parseRecord(value: unknown): Record<string, unknown> | undefined;
|
|
2595
|
+
|
|
2596
|
+
/**
|
|
2597
|
+
* Read and parse a nested record field from a record by key or nested key path.
|
|
2598
|
+
*
|
|
2599
|
+
* @param record - The source record
|
|
2600
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2601
|
+
* @returns A plain record, or `undefined`
|
|
2602
|
+
*/
|
|
2603
|
+
export declare function parseRecordField(record: Record<string, unknown>, path: FieldPath): Record<string, unknown> | undefined;
|
|
2604
|
+
|
|
2605
|
+
/**
|
|
2606
|
+
* Parse an unknown value to a string.
|
|
2607
|
+
*
|
|
2608
|
+
* @remarks
|
|
2609
|
+
* A string is returned unchanged; a finite number is coerced to its decimal
|
|
2610
|
+
* string (`42` → `'42'`). `NaN`, `±Infinity`, and every other type → `undefined`.
|
|
2611
|
+
*
|
|
2612
|
+
* @param value - The value to parse
|
|
2613
|
+
* @returns A string, or `undefined`
|
|
2614
|
+
*
|
|
2615
|
+
* @example
|
|
2616
|
+
* ```ts
|
|
2617
|
+
* parseString('hi') // 'hi'
|
|
2618
|
+
* parseString(42) // '42'
|
|
2619
|
+
* parseString(true) // undefined
|
|
2620
|
+
* ```
|
|
2621
|
+
*/
|
|
2622
|
+
export declare function parseString(value: unknown): string | undefined;
|
|
2623
|
+
|
|
2624
|
+
/**
|
|
2625
|
+
* Read and parse a string field from a record by key or nested key path.
|
|
2626
|
+
*
|
|
2627
|
+
* @param record - The source record
|
|
2628
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2629
|
+
* @returns A string, or `undefined`
|
|
2630
|
+
*/
|
|
2631
|
+
export declare function parseStringField(record: Record<string, unknown>, path: FieldPath): string | undefined;
|
|
2632
|
+
|
|
2633
|
+
/**
|
|
2634
|
+
* Build a new guard shape by keeping only the listed keys — the structural
|
|
2635
|
+
* equivalent of `Pick<T, K>`. Produces a shape for {@link recordOf}, not a guard.
|
|
2636
|
+
*
|
|
2637
|
+
* @example
|
|
2638
|
+
* ```ts
|
|
2639
|
+
* const full = { name: isString, age: isNumber, role: isString }
|
|
2640
|
+
* const isName = recordOf(pickOf(full, ['name']))
|
|
2641
|
+
* isName({ name: 'Ada' }) // true
|
|
2642
|
+
* ```
|
|
2643
|
+
*/
|
|
2644
|
+
export declare function pickOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, keys: K): Pick<S, K[number]>;
|
|
2645
|
+
|
|
2646
|
+
/**
|
|
2647
|
+
* Render a short, safe, TOTAL preview of an unknown value for a {@link Fault}'s
|
|
2648
|
+
* `received` field.
|
|
2649
|
+
*
|
|
2650
|
+
* @remarks
|
|
2651
|
+
* A primitive renders as its literal: a string is `JSON.stringify`-escaped and
|
|
2652
|
+
* clipped to {@link PREVIEW_LIMIT} characters (with a trailing `…` when
|
|
2653
|
+
* clipped); a number / boolean / bigint / symbol renders via `String`; `null`
|
|
2654
|
+
* and `undefined` render as their own name. Everything else — a plain object,
|
|
2655
|
+
* an array, a function, a class instance, a `Map` — is NEVER traversed or
|
|
2656
|
+
* stringified; it renders as its bare `typeof` tag (`'object'` / `'function'`),
|
|
2657
|
+
* so a hostile or enormous structure can never blow up the preview.
|
|
2658
|
+
*
|
|
2659
|
+
* @param value - The value to preview
|
|
2660
|
+
* @returns A short descriptive string, always safe to embed in a diagnostic
|
|
2661
|
+
*
|
|
2662
|
+
* @example
|
|
2663
|
+
* ```ts
|
|
2664
|
+
* preview('hi') // '"hi"'
|
|
2665
|
+
* preview(42) // '42'
|
|
2666
|
+
* preview(null) // 'null'
|
|
2667
|
+
* preview({ a: 1 }) // 'object'
|
|
2668
|
+
* preview([1, 2, 3]) // 'object'
|
|
2669
|
+
* ```
|
|
2670
|
+
*/
|
|
2671
|
+
export declare function preview(value: unknown): string;
|
|
2672
|
+
|
|
2673
|
+
/**
|
|
2674
|
+
* The maximum character length of a {@link preview}-rendered string, frozen.
|
|
2675
|
+
*
|
|
2676
|
+
* @remarks
|
|
2677
|
+
* A previewed string longer than this is clipped with a trailing `…` so a
|
|
2678
|
+
* {@link Fault}'s `received` field never embeds an unbounded amount of
|
|
2679
|
+
* untrusted text.
|
|
2680
|
+
*/
|
|
2681
|
+
export declare const PREVIEW_LIMIT = 64;
|
|
2682
|
+
|
|
2683
|
+
/** A deterministic random source returning a value in `[0, 1)`. */
|
|
2684
|
+
export declare type RandomFunction = () => number;
|
|
2685
|
+
|
|
2686
|
+
/**
|
|
2687
|
+
* A raw JSON Schema passthrough — embeds a schema fragment directly.
|
|
2688
|
+
*
|
|
2689
|
+
* @remarks
|
|
2690
|
+
* For values the shape DSL can't express. The compiled guard accepts any value
|
|
2691
|
+
* and the parser passes it through unchanged; the schema is emitted verbatim.
|
|
2692
|
+
*/
|
|
2693
|
+
export declare interface RawShape {
|
|
2694
|
+
readonly type: 'raw';
|
|
2695
|
+
readonly schema: JSONSchema;
|
|
2696
|
+
}
|
|
2697
|
+
|
|
2698
|
+
/**
|
|
2699
|
+
* Build a {@link RawShape} from a JSON Schema fragment.
|
|
2700
|
+
*
|
|
2701
|
+
* @remarks
|
|
2702
|
+
* For values the shape DSL can't express. The compiled guard accepts any value;
|
|
2703
|
+
* the parser passes it through; the schema is emitted verbatim.
|
|
2704
|
+
*
|
|
2705
|
+
* @param schema - The JSON Schema fragment to embed
|
|
2706
|
+
* @returns A raw shape
|
|
2707
|
+
*
|
|
2708
|
+
* @example
|
|
2709
|
+
* ```ts
|
|
2710
|
+
* const custom = rawShape({ type: 'string', format: 'uuid' })
|
|
2711
|
+
* ```
|
|
2712
|
+
*/
|
|
2713
|
+
export declare function rawShape(schema: JSONSchema): RawShape;
|
|
2714
|
+
|
|
2715
|
+
export declare function recordOf<S extends GuardsShape>(shape: S): Guard<FromGuards<S>>;
|
|
2716
|
+
|
|
2717
|
+
export declare function recordOf<S extends GuardsShape, K extends ReadonlyArray<keyof S & string>>(shape: S, optional: K): Guard<OptionalFromGuards<S, K>>;
|
|
2718
|
+
|
|
2719
|
+
export declare function recordOf<S extends GuardsShape>(shape: S, optional: true): Guard<Readonly<{
|
|
2720
|
+
[P in keyof S]?: FromGuards<S>[P];
|
|
2721
|
+
}>>;
|
|
2722
|
+
|
|
2723
|
+
/**
|
|
2724
|
+
* Build an open {@link ObjectShape} with no fixed properties — a dictionary.
|
|
2725
|
+
*
|
|
2726
|
+
* @remarks
|
|
2727
|
+
* Every value is validated against `values`; keys are unconstrained. Equivalent
|
|
2728
|
+
* to `objectShape({}, { additionalProperties: values })`.
|
|
2729
|
+
*
|
|
2730
|
+
* @param values - The shape every value must match
|
|
2731
|
+
* @param options - Optional `description`
|
|
2732
|
+
* @returns An open object shape
|
|
2733
|
+
*
|
|
2734
|
+
* @example
|
|
2735
|
+
* ```ts
|
|
2736
|
+
* const bindings = recordShape(numberShape()) // ~ Record<string, number>
|
|
2737
|
+
* ```
|
|
2738
|
+
*/
|
|
2739
|
+
export declare function recordShape<S extends ContractShape>(values: S, options?: RecordShapeOptions): ObjectShape<Record<never, never>, S>;
|
|
2740
|
+
|
|
2741
|
+
/** Options for record shapes (via `recordShape`). */
|
|
2742
|
+
export declare interface RecordShapeOptions {
|
|
2743
|
+
readonly description?: string;
|
|
2744
|
+
}
|
|
2745
|
+
|
|
2746
|
+
/**
|
|
2747
|
+
* Resolve a (possibly nested) field value from a record by a key or key path.
|
|
2748
|
+
*
|
|
2749
|
+
* @remarks
|
|
2750
|
+
* A single `string` is ONE key (never split on `.`, so dotted keys are safe); a
|
|
2751
|
+
* string array descends left-to-right through nested objects. Intermediates may
|
|
2752
|
+
* be any object — records, class instances, or arrays indexed by string. Returns
|
|
2753
|
+
* `undefined` the moment a segment is missing or lands on a non-object, so the
|
|
2754
|
+
* lookup is total — even against a hostile getter or Proxy trap that throws on
|
|
2755
|
+
* read, contained via {@link attempt} so the throw never escapes.
|
|
2756
|
+
*
|
|
2757
|
+
* @param record - The source record
|
|
2758
|
+
* @param path - A property key, or a key path descending into nested objects
|
|
2759
|
+
* @returns The resolved value, or `undefined`
|
|
2760
|
+
*
|
|
2761
|
+
* @example
|
|
2762
|
+
* ```ts
|
|
2763
|
+
* resolveField({ user: { name: 'Ada' } }, ['user', 'name']) // 'Ada'
|
|
2764
|
+
* resolveField({ 'a.b': 1 }, 'a.b') // 1 (one key)
|
|
2765
|
+
* resolveField({ a: 1 }, ['a', 'b']) // undefined
|
|
2766
|
+
* ```
|
|
2767
|
+
*/
|
|
2768
|
+
export declare function resolveField(record: Readonly<Record<string, unknown>>, path: FieldPath): unknown;
|
|
2769
|
+
|
|
2770
|
+
/** Discriminated union for operations that can succeed or fail without throwing. */
|
|
2771
|
+
export declare type Result<T, E = Error> = Success<T> | Failure<E>;
|
|
2772
|
+
|
|
2773
|
+
/**
|
|
2774
|
+
* Classify a list of sample values against the {@link SchemaFormat}
|
|
2775
|
+
* vocabulary, requiring unanimity.
|
|
2776
|
+
*
|
|
2777
|
+
* @remarks
|
|
2778
|
+
* A format is returned ONLY IF every value is a string AND every one maps to
|
|
2779
|
+
* the SAME {@link stringToFormat} result (including all mapping to
|
|
2780
|
+
* `undefined`, which itself returns `undefined` here). A single disagreeing
|
|
2781
|
+
* value, a non-string value, or an empty list all yield `undefined` — the
|
|
2782
|
+
* multi-sample seam ({@link samplesToSchema} / {@link inferRecordSamples})
|
|
2783
|
+
* relies on this unanimity so a slot with mixed string shapes emits a bare
|
|
2784
|
+
* `{ type: 'string' }` rather than an `anyOf` of formats.
|
|
2785
|
+
*
|
|
2786
|
+
* @param values - The sample values to classify
|
|
2787
|
+
* @returns The unanimous {@link SchemaFormat}, or `undefined`
|
|
2788
|
+
*
|
|
2789
|
+
* @example
|
|
2790
|
+
* ```ts
|
|
2791
|
+
* samplesToFormat(['2024-01-01', '2024-02-02']) // 'date'
|
|
2792
|
+
* samplesToFormat(['2024-01-01', 'not a date']) // undefined
|
|
2793
|
+
* samplesToFormat([]) // undefined
|
|
2794
|
+
* ```
|
|
2795
|
+
*/
|
|
2796
|
+
export declare function samplesToFormat(values: readonly unknown[]): SchemaFormat | undefined;
|
|
2797
|
+
|
|
2798
|
+
/**
|
|
2799
|
+
* Infer a `JSONSchema` from a set of example values — the multi-example
|
|
2800
|
+
* counterpart of {@link valueToSchema} (e.g. inferring one schema from
|
|
2801
|
+
* several database rows).
|
|
2802
|
+
*
|
|
2803
|
+
* @remarks
|
|
2804
|
+
* An empty `samples` array infers the empty accept-anything schema `{}`.
|
|
2805
|
+
* When every sample is a plain record, properties/required are unified
|
|
2806
|
+
* per-key across all samples (see {@link inferRecordSamples}) — a key
|
|
2807
|
+
* required iff present and non-`undefined` in every sample. Otherwise the
|
|
2808
|
+
* slot is inferred via {@link inferSamples} (independent {@link valueToSchema}
|
|
2809
|
+
* per sample, unified with {@link unifySchemas} — the same de-duplication and
|
|
2810
|
+
* `anyOf` ordering {@link inferArray} applies to element schemas). `format`
|
|
2811
|
+
* and `enum` (both default `false`) opt a low-cardinality/unanimous-format
|
|
2812
|
+
* slot into the corresponding keyword — see {@link inferSamples} for the
|
|
2813
|
+
* precedence and the multi-sample format-disabling seam. `maxDepth` /
|
|
2814
|
+
* `maxProperties` are sanitized via {@link sanitizeBudget} the same way
|
|
2815
|
+
* {@link valueToSchema} sanitizes them — see there for why.
|
|
2816
|
+
*
|
|
2817
|
+
* @param samples - The example values to infer a schema from
|
|
2818
|
+
* @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` / `enum` bounds
|
|
2819
|
+
* @returns The inferred `JSONSchema`
|
|
2820
|
+
*
|
|
2821
|
+
* @example
|
|
2822
|
+
* ```ts
|
|
2823
|
+
* samplesToSchema([{ id: 1 }, { id: 2, name: 'Ada' }])
|
|
2824
|
+
* // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } },
|
|
2825
|
+
* // required: ['id'], additionalProperties: false }
|
|
2826
|
+
* samplesToSchema([]) // {}
|
|
2827
|
+
* ```
|
|
2828
|
+
*/
|
|
2829
|
+
export declare function samplesToSchema(samples: readonly unknown[], options?: ValueToSchemaOptions): JSONSchema;
|
|
2830
|
+
|
|
2831
|
+
/**
|
|
2832
|
+
* Sanitize a user-supplied inference budget (`maxDepth` / `maxProperties`) to
|
|
2833
|
+
* a finite non-negative integer, falling back to a default for anything else.
|
|
2834
|
+
*
|
|
2835
|
+
* @remarks
|
|
2836
|
+
* Guards {@link valueToSchema} / {@link samplesToSchema} against a hostile or
|
|
2837
|
+
* malformed budget: an unclamped `NaN` defeats every `depth <= 0` guard
|
|
2838
|
+
* (`NaN <= 0` is `false`, so recursion never halts), and a negative
|
|
2839
|
+
* `maxProperties` makes `slice(0, -1)` silently drop the LAST sorted key
|
|
2840
|
+
* instead of capping the list (a fractional value has a similarly undefined
|
|
2841
|
+
* `slice` bound). `Infinity` is rejected too — `Number.isInteger(Infinity)`
|
|
2842
|
+
* is `false` — since an unbounded budget is exactly the adversarial case the
|
|
2843
|
+
* caps exist to prevent. A valid finite non-negative integer passes through
|
|
2844
|
+
* unchanged.
|
|
2845
|
+
*
|
|
2846
|
+
* @param value - The candidate budget value
|
|
2847
|
+
* @param fallback - The default to use when `value` is not a finite
|
|
2848
|
+
* non-negative integer
|
|
2849
|
+
* @returns A finite non-negative integer budget
|
|
2850
|
+
*
|
|
2851
|
+
* @example
|
|
2852
|
+
* ```ts
|
|
2853
|
+
* sanitizeBudget(Number.NaN, INFER_DEPTH_LIMIT) // INFER_DEPTH_LIMIT
|
|
2854
|
+
* sanitizeBudget(-1, INFER_BREADTH_LIMIT) // INFER_BREADTH_LIMIT
|
|
2855
|
+
* sanitizeBudget(4, INFER_DEPTH_LIMIT) // 4
|
|
2856
|
+
* ```
|
|
2857
|
+
*/
|
|
2858
|
+
export declare function sanitizeBudget(value: number | undefined, fallback: number): number;
|
|
2859
|
+
|
|
2860
|
+
/**
|
|
2861
|
+
* The closed set of string formats {@link stringToFormat} recognizes.
|
|
2862
|
+
*
|
|
2863
|
+
* @remarks
|
|
2864
|
+
* Lowercase spec literals, matching the JSON Schema `format` vocabulary for
|
|
2865
|
+
* the subset the inferers detect: `'date-time'` / `'date'` / `'time'` are
|
|
2866
|
+
* ISO-8601 (validity-checked via `Date`, not pattern-only), `'uuid'` matches
|
|
2867
|
+
* RFC-4122 hex layout, `'email'` and `'uri'` are pragmatic (not full-spec)
|
|
2868
|
+
* shape checks. See {@link FORMAT_PATTERNS}.
|
|
2869
|
+
*/
|
|
2870
|
+
export declare type SchemaFormat = 'date-time' | 'date' | 'time' | 'uuid' | 'email' | 'uri';
|
|
2871
|
+
|
|
2872
|
+
/**
|
|
2873
|
+
* Wrap a non-object `JSONSchema` root in a single-property object schema, so
|
|
2874
|
+
* an inferred primitive/array/union schema can flow into {@link schemaToParameters}
|
|
2875
|
+
* as an MCP-compatible `inputSchema`.
|
|
2876
|
+
*
|
|
2877
|
+
* @remarks
|
|
2878
|
+
* Total and deterministic. `schema.type === 'object'` passes through
|
|
2879
|
+
* unchanged; every other root (a primitive/array `type`, an `anyOf`/`enum`-only
|
|
2880
|
+
* schema with no `type`, or the empty `{}`) is wrapped as a single required
|
|
2881
|
+
* `value` property: `{ type: 'object', properties: { value: schema },
|
|
2882
|
+
* required: ['value'], additionalProperties: false }`. Composition:
|
|
2883
|
+
* `schemaToParameters(schemaToObject(valueToSchema(payload)))`.
|
|
2884
|
+
*
|
|
2885
|
+
* @param schema - The schema to wrap
|
|
2886
|
+
* @returns `schema` unchanged when object-rooted, otherwise the wrapped object schema
|
|
2887
|
+
*
|
|
2888
|
+
* @example
|
|
2889
|
+
* ```ts
|
|
2890
|
+
* schemaToObject({ type: 'string' })
|
|
2891
|
+
* // { type: 'object', properties: { value: { type: 'string' } },
|
|
2892
|
+
* // required: ['value'], additionalProperties: false }
|
|
2893
|
+
* schemaToObject({ type: 'object', properties: {} }) // unchanged
|
|
2894
|
+
* ```
|
|
2895
|
+
*/
|
|
2896
|
+
export declare function schemaToObject(schema: JSONSchema): JSONSchema;
|
|
2897
|
+
|
|
2898
|
+
/**
|
|
2899
|
+
* Narrow a compiled {@link JSONSchema} down to the open `Readonly<Record<string, unknown>>` shape
|
|
2900
|
+
* tool definitions advertise as `parameters` — through the {@link isRecord} boundary guard, never
|
|
2901
|
+
* an assertion (AGENTS §14).
|
|
2902
|
+
*
|
|
2903
|
+
* @remarks
|
|
2904
|
+
* A `JSONSchema` is the closed contract-compiler fragment (it has no index signature), whereas a
|
|
2905
|
+
* tool advertises its `parameters` as an open record. The two are structurally compatible but not
|
|
2906
|
+
* assignable, so the schema crosses that boundary through `isRecord` — a compiled contract schema
|
|
2907
|
+
* is always a record, so the guard passes; the `undefined` fallback only satisfies the type's
|
|
2908
|
+
* optionality. This is the single sanctioned narrowing from a compiled contract schema to the open
|
|
2909
|
+
* tool-parameters record, so the crossing lives once rather than being copy-pasted per call site.
|
|
2910
|
+
*
|
|
2911
|
+
* @param schema - The compiled JSON Schema (a contract's `schema`)
|
|
2912
|
+
* @returns The schema as the open tool-parameters record, or `undefined` when it is not a record
|
|
2913
|
+
*
|
|
2914
|
+
* @example
|
|
2915
|
+
* ```ts
|
|
2916
|
+
* import { createContract, schemaToParameters } from '@src/core'
|
|
2917
|
+
*
|
|
2918
|
+
* const contract = createContract(shape)
|
|
2919
|
+
* const parameters = schemaToParameters(contract.schema) // the open record a tool advertises
|
|
2920
|
+
* ```
|
|
2921
|
+
*/
|
|
2922
|
+
export declare function schemaToParameters(schema: JSONSchema): Readonly<Record<string, unknown>> | undefined;
|
|
2923
|
+
|
|
2924
|
+
/**
|
|
2925
|
+
* Build a deterministic pseudo-random source seeded from a single number.
|
|
2926
|
+
*
|
|
2927
|
+
* @remarks
|
|
2928
|
+
* A mulberry32 generator — the same seed always yields the same sequence, so
|
|
2929
|
+
* generated seed data is reproducible across runs. Used as the default random
|
|
2930
|
+
* source for {@link compileGenerator}, seeded from the wall clock so casual
|
|
2931
|
+
* callers still get varied output without passing a source themselves.
|
|
2932
|
+
*
|
|
2933
|
+
* @param seed - The seed for the sequence
|
|
2934
|
+
* @returns A {@link RandomFunction} returning values in `[0, 1)`
|
|
2935
|
+
*
|
|
2936
|
+
* @example
|
|
2937
|
+
* ```ts
|
|
2938
|
+
* const random = seededRandom(42)
|
|
2939
|
+
* random() // always the same first value for seed 42
|
|
2940
|
+
* ```
|
|
2941
|
+
*/
|
|
2942
|
+
export declare function seededRandom(seed: number): RandomFunction;
|
|
2943
|
+
|
|
2944
|
+
/**
|
|
2945
|
+
* Build a guard that accepts `Set` instances whose every element satisfies
|
|
2946
|
+
* `elementGuard`.
|
|
2947
|
+
*
|
|
2948
|
+
* @example
|
|
2949
|
+
* ```ts
|
|
2950
|
+
* const isStringSet = setOf(isString)
|
|
2951
|
+
* isStringSet(new Set(['a', 'b'])) // true
|
|
2952
|
+
* isStringSet(new Set(['a', 1])) // false
|
|
2953
|
+
* ```
|
|
2954
|
+
*/
|
|
2955
|
+
export declare function setOf<T>(elementGuard: Guard<T>): Guard<ReadonlySet<T>>;
|
|
2956
|
+
|
|
2957
|
+
export declare function setOf(elementGuard: (value: unknown) => boolean): Guard<ReadonlySet<unknown>>;
|
|
2958
|
+
|
|
2959
|
+
/**
|
|
2960
|
+
* Project a {@link ContractShape} to the {@link FaultKind} it describes.
|
|
2961
|
+
*
|
|
2962
|
+
* @remarks
|
|
2963
|
+
* A structural mapping used by {@link compileReporter} to fill a `Fault`'s
|
|
2964
|
+
* `expected` field: most shapes map to their own `type` (`numberShape` maps to
|
|
2965
|
+
* `'integer'` when `integer: true`, else `'number'`); `optionalShape` /
|
|
2966
|
+
* `nullableShape` project through to their inner shape's kind, and `rawShape`
|
|
2967
|
+
* (an arbitrary embedded schema with no fixed kind) projects to `'json'`.
|
|
2968
|
+
*
|
|
2969
|
+
* @param shape - The shape to project
|
|
2970
|
+
* @returns The shape's {@link FaultKind}
|
|
2971
|
+
*
|
|
2972
|
+
* @example
|
|
2973
|
+
* ```ts
|
|
2974
|
+
* shapeToKind(stringShape()) // 'string'
|
|
2975
|
+
* shapeToKind(integerShape()) // 'integer'
|
|
2976
|
+
* shapeToKind(optionalShape(nullShape())) // 'null'
|
|
2977
|
+
* ```
|
|
2978
|
+
*/
|
|
2979
|
+
export declare function shapeToKind(shape: ContractShape): FaultKind;
|
|
2980
|
+
|
|
2981
|
+
/**
|
|
2982
|
+
* Build a guard that accepts strings satisfying optional length and pattern
|
|
2983
|
+
* refinements — `min` / `max` length and a `pattern`.
|
|
2984
|
+
*
|
|
2985
|
+
* @remarks
|
|
2986
|
+
* Composes {@link isString} with {@link boundsOf} on the string's `.length` and
|
|
2987
|
+
* an inline `pattern.test` (the same refinement {@link matchOf} performs). When all three options are absent it returns
|
|
2988
|
+
* the bare {@link isString} guard (the unconstrained fast path), so an
|
|
2989
|
+
* unrefined string leaf pays no wrapping cost. The single source of the string
|
|
2990
|
+
* refinement shared by the compiled guard and parser (compilers.ts).
|
|
2991
|
+
*
|
|
2992
|
+
* @example
|
|
2993
|
+
* ```ts
|
|
2994
|
+
* const isSlug = stringOf({ min: 1, max: 32, pattern: /^[a-z-]+$/ })
|
|
2995
|
+
* isSlug('hello-world') // true
|
|
2996
|
+
* isSlug('') // false — below min
|
|
2997
|
+
* isSlug('Hello') // false — pattern miss
|
|
2998
|
+
*
|
|
2999
|
+
* stringOf() // identical to isString
|
|
3000
|
+
* ```
|
|
3001
|
+
*/
|
|
3002
|
+
export declare function stringOf(options?: {
|
|
3003
|
+
min?: number;
|
|
3004
|
+
max?: number;
|
|
3005
|
+
pattern?: RegExp;
|
|
3006
|
+
}): Guard<string>;
|
|
3007
|
+
|
|
3008
|
+
/** A string shape with optional length and pattern constraints. */
|
|
3009
|
+
export declare interface StringShape {
|
|
3010
|
+
readonly type: 'string';
|
|
3011
|
+
readonly min?: number;
|
|
3012
|
+
readonly max?: number;
|
|
3013
|
+
readonly pattern?: RegExp;
|
|
3014
|
+
readonly description?: string;
|
|
3015
|
+
}
|
|
3016
|
+
|
|
3017
|
+
/**
|
|
3018
|
+
* Build a string {@link StringShape}.
|
|
3019
|
+
*
|
|
3020
|
+
* @param options - Optional length (`min` / `max`), `pattern`, and `description`
|
|
3021
|
+
* @returns A string shape
|
|
3022
|
+
*
|
|
3023
|
+
* @example
|
|
3024
|
+
* ```ts
|
|
3025
|
+
* const name = stringShape({ min: 1, max: 80, description: 'Display name' })
|
|
3026
|
+
* ```
|
|
3027
|
+
*/
|
|
3028
|
+
export declare function stringShape(options?: StringShapeOptions): StringShape;
|
|
3029
|
+
|
|
3030
|
+
/** Options for {@link StringShape} (via `stringShape`). */
|
|
3031
|
+
export declare interface StringShapeOptions {
|
|
3032
|
+
readonly min?: number;
|
|
3033
|
+
readonly max?: number;
|
|
3034
|
+
readonly pattern?: RegExp;
|
|
3035
|
+
readonly description?: string;
|
|
3036
|
+
}
|
|
3037
|
+
|
|
3038
|
+
/**
|
|
3039
|
+
* Classify a string against the {@link SchemaFormat} vocabulary.
|
|
3040
|
+
*
|
|
3041
|
+
* @remarks
|
|
3042
|
+
* Total, pure, and deterministic. Fixed precedence, most specific first:
|
|
3043
|
+
* `'uuid'`, `'date-time'`, `'date'`, `'time'`, `'email'`, `'uri'` — the first
|
|
3044
|
+
* match wins. The `date-time` / `date` / `time` branches require BOTH a
|
|
3045
|
+
* strict ISO-8601 shape match AND a real {@link isValidISOInstant} validity
|
|
3046
|
+
* check, so a shape-plausible but impossible date (`2020-13-45`) is rejected.
|
|
3047
|
+
* Returns `undefined` when no format matches (including the empty string).
|
|
3048
|
+
*
|
|
3049
|
+
* @param value - The string to classify
|
|
3050
|
+
* @returns The matched {@link SchemaFormat}, or `undefined`
|
|
3051
|
+
*
|
|
3052
|
+
* @example
|
|
3053
|
+
* ```ts
|
|
3054
|
+
* stringToFormat('550e8400-e29b-41d4-a716-446655440000') // 'uuid'
|
|
3055
|
+
* stringToFormat('2024-01-15') // 'date'
|
|
3056
|
+
* stringToFormat('2020-13-45') // undefined — invalid date
|
|
3057
|
+
* stringToFormat('ada@example.com') // 'email'
|
|
3058
|
+
* stringToFormat('10:30:00') // undefined — RFC 3339 time requires an offset
|
|
3059
|
+
* stringToFormat('10:30:00+02:00') // 'time'
|
|
3060
|
+
* ```
|
|
3061
|
+
*/
|
|
3062
|
+
export declare function stringToFormat(value: string): SchemaFormat | undefined;
|
|
3063
|
+
|
|
3064
|
+
/**
|
|
3065
|
+
* Discriminated success branch of a {@link Result}.
|
|
3066
|
+
*
|
|
3067
|
+
* @remarks
|
|
3068
|
+
* Used for operations that can succeed or fail without throwing.
|
|
3069
|
+
*/
|
|
3070
|
+
export declare interface Success<T> {
|
|
3071
|
+
readonly success: true;
|
|
3072
|
+
readonly value: T;
|
|
3073
|
+
}
|
|
3074
|
+
|
|
3075
|
+
/**
|
|
3076
|
+
* Build a guard that passes when the base passes AND the projection of the value
|
|
3077
|
+
* satisfies the target guard. Still narrows to `T` (the base type) — the target
|
|
3078
|
+
* check is a validity constraint on a derived view, not a type transformation.
|
|
3079
|
+
*
|
|
3080
|
+
* @remarks
|
|
3081
|
+
* `project` is a plain `(value: T) => U`. Per §14 the returned guard never
|
|
3082
|
+
* throws: a throw from `project` is contained and reported as a non-match.
|
|
3083
|
+
* `target` is itself a Guard (already §14-bound), so it stays outside the
|
|
3084
|
+
* contained region. (Unlike the reference implementation, there is no
|
|
3085
|
+
* "curried projector" branch — a projection that legitimately returns a function
|
|
3086
|
+
* would be double-invoked under that scheme. Compose explicitly if you need it.)
|
|
3087
|
+
*
|
|
3088
|
+
* @example
|
|
3089
|
+
* ```ts
|
|
3090
|
+
* const isBounded = transformOf(
|
|
3091
|
+
* isString,
|
|
3092
|
+
* (s) => s.trim().length,
|
|
3093
|
+
* whereOf(isNumber, (n) => n >= 1 && n <= 50),
|
|
3094
|
+
* )
|
|
3095
|
+
* isBounded('hello') // true
|
|
3096
|
+
* isBounded('') // false
|
|
3097
|
+
* ```
|
|
3098
|
+
*/
|
|
3099
|
+
export declare function transformOf<T, U>(base: Guard<T>, project: (value: T) => U, target: Guard<U>): Guard<T>;
|
|
3100
|
+
|
|
3101
|
+
export declare function transformOf<T>(base: Guard<T>, project: (value: T) => unknown, target: (value: unknown) => boolean): Guard<T>;
|
|
3102
|
+
|
|
3103
|
+
/** Map a tuple of element guards to a readonly tuple of their guarded types. */
|
|
3104
|
+
export declare type TupleFromGuards<Ts extends ReadonlyArray<Guard<unknown>>> = Readonly<{
|
|
3105
|
+
[K in keyof Ts]: GuardType<Ts[K]>;
|
|
3106
|
+
}>;
|
|
3107
|
+
|
|
3108
|
+
/**
|
|
3109
|
+
* Build a guard that accepts fixed-arity tuples, testing each index with the
|
|
3110
|
+
* corresponding guard.
|
|
3111
|
+
*
|
|
3112
|
+
* @example
|
|
3113
|
+
* ```ts
|
|
3114
|
+
* const isPair = tupleOf(isString, isNumber)
|
|
3115
|
+
* isPair(['hello', 42]) // true
|
|
3116
|
+
* isPair(['hello']) // false — wrong arity
|
|
3117
|
+
* ```
|
|
3118
|
+
*/
|
|
3119
|
+
export declare function tupleOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<TupleFromGuards<Gs>>;
|
|
3120
|
+
|
|
3121
|
+
export declare function tupleOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<readonly unknown[]>;
|
|
3122
|
+
|
|
3123
|
+
/**
|
|
3124
|
+
* Unify a list of inferred `JSONSchema` fragments into one schema.
|
|
3125
|
+
*
|
|
3126
|
+
* @remarks
|
|
3127
|
+
* De-duplicates by {@link canonicalStringify}, then applies the one
|
|
3128
|
+
* special-case subsumption inference performs: a bare `{ type: 'integer' }`
|
|
3129
|
+
* alongside a bare `{ type: 'number' }` collapses to just `{ type: 'number' }`
|
|
3130
|
+
* (an integer sample is also a valid `number` sample). A single surviving
|
|
3131
|
+
* distinct schema is returned directly; two or more are wrapped as
|
|
3132
|
+
* `{ anyOf: [...] }`, sorted by their canonical key for deterministic output.
|
|
3133
|
+
* An empty input list returns the empty accept-anything schema `{}`.
|
|
3134
|
+
*
|
|
3135
|
+
* @param schemas - The schemas to unify
|
|
3136
|
+
* @returns The unified schema
|
|
3137
|
+
*
|
|
3138
|
+
* @example
|
|
3139
|
+
* ```ts
|
|
3140
|
+
* unifySchemas([{ type: 'integer' }, { type: 'number' }]) // { type: 'number' }
|
|
3141
|
+
* unifySchemas([{ type: 'string' }, { type: 'boolean' }])
|
|
3142
|
+
* // { anyOf: [{ type: 'boolean' }, { type: 'string' }] }
|
|
3143
|
+
* ```
|
|
3144
|
+
*/
|
|
3145
|
+
export declare function unifySchemas(schemas: readonly JSONSchema[]): JSONSchema;
|
|
3146
|
+
|
|
3147
|
+
/**
|
|
3148
|
+
* Build a guard that accepts values matching at least one of the provided
|
|
3149
|
+
* guards — the variadic form of {@link orOf}.
|
|
3150
|
+
*
|
|
3151
|
+
* @example
|
|
3152
|
+
* ```ts
|
|
3153
|
+
* const isStringOrBoolean = unionOf(isString, isBoolean)
|
|
3154
|
+
* ```
|
|
3155
|
+
*/
|
|
3156
|
+
export declare function unionOf<const Gs extends ReadonlyArray<Guard<unknown>>>(...guards: Gs): Guard<GuardType<Gs[number]>>;
|
|
3157
|
+
|
|
3158
|
+
export declare function unionOf(...predicates: ReadonlyArray<(value: unknown) => boolean>): Guard<unknown>;
|
|
3159
|
+
|
|
3160
|
+
/**
|
|
3161
|
+
* A union shape — accepts a value matching any one variant (first match wins).
|
|
3162
|
+
*
|
|
3163
|
+
* @remarks
|
|
3164
|
+
* `mode` selects the emitted JSON Schema keyword: `'anyOf'` (default) or
|
|
3165
|
+
* `'oneOf'`. Runtime behavior is identical.
|
|
3166
|
+
*/
|
|
3167
|
+
export declare interface UnionShape<V extends readonly ContractShape[] = readonly ContractShape[]> {
|
|
3168
|
+
readonly type: 'union';
|
|
3169
|
+
readonly variants: V;
|
|
3170
|
+
readonly mode?: 'anyOf' | 'oneOf';
|
|
3171
|
+
readonly description?: string;
|
|
3172
|
+
}
|
|
3173
|
+
|
|
3174
|
+
/**
|
|
3175
|
+
* Build a {@link UnionShape} from a list of variant shapes (`anyOf` in JSON Schema).
|
|
3176
|
+
*
|
|
3177
|
+
* @param variants - The candidate shapes; the first match wins at runtime
|
|
3178
|
+
* @returns A union shape whose `Infer` is the union of the variants
|
|
3179
|
+
*
|
|
3180
|
+
* @example
|
|
3181
|
+
* ```ts
|
|
3182
|
+
* const id = unionShape(stringShape(), integerShape())
|
|
3183
|
+
* // Infer<typeof id> = string | number
|
|
3184
|
+
* ```
|
|
3185
|
+
*/
|
|
3186
|
+
export declare function unionShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
|
|
3187
|
+
|
|
3188
|
+
/** Convert a union type to an intersection type. */
|
|
3189
|
+
export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
|
|
3190
|
+
|
|
3191
|
+
/**
|
|
3192
|
+
* Validate that a {@link ContractShape} tree is well-formed — a pure recursive
|
|
3193
|
+
* prepass run before compilation.
|
|
3194
|
+
*
|
|
3195
|
+
* @remarks
|
|
3196
|
+
* Fail-fast, per AGENTS §12: a malformed shape is a programmer error, so this
|
|
3197
|
+
* throws a plain `Error` immediately rather than surfacing as a silently-wrong
|
|
3198
|
+
* guard, parser, schema, or generator later. Checks, recursively:
|
|
3199
|
+
*
|
|
3200
|
+
* - An {@link OptionalShape} is only legal as a direct object-property value —
|
|
3201
|
+
* `optionalShape` wrapping an array item, a union variant, another
|
|
3202
|
+
* optional/nullable's inner shape, `additionalProperties`, or the top-level
|
|
3203
|
+
* shape all throw. An object property IS the one legal placement: its value
|
|
3204
|
+
* is unwrapped to `.inner` before recursing, so `.inner` itself is validated
|
|
3205
|
+
* as a normal (non-optional-wrapping) shape.
|
|
3206
|
+
* - A {@link UnionShape} needs at least one variant; a {@link LiteralShape}
|
|
3207
|
+
* needs at least one value and rejects non-finite (`NaN` / `Infinity` /
|
|
3208
|
+
* `-Infinity`) number values.
|
|
3209
|
+
* - A bounded {@link StringShape} / {@link NumberShape} / {@link ArrayShape}
|
|
3210
|
+
* needs `min <= max` when both are set.
|
|
3211
|
+
* - An integer {@link NumberShape} (`integer: true`) needs a non-empty integer
|
|
3212
|
+
* range: `Math.ceil(min ?? -Infinity) <= Math.floor(max ?? Infinity)`.
|
|
3213
|
+
* - `null` / `json` / `raw` / `boolean` are always-valid leaves. Recursion
|
|
3214
|
+
* continues into array items, object properties (and `additionalProperties`
|
|
3215
|
+
* when it is a shape), union variants, and optional/nullable inner shapes.
|
|
3216
|
+
*
|
|
3217
|
+
* @param shape - The shape to validate
|
|
3218
|
+
* @throws {Error} When the shape is malformed
|
|
3219
|
+
*
|
|
3220
|
+
* @example
|
|
3221
|
+
* ```ts
|
|
3222
|
+
* validateShape(stringShape({ min: 1, max: 10 })) // does not throw
|
|
3223
|
+
* validateShape(stringShape({ min: 10, max: 1 })) // throws
|
|
3224
|
+
* ```
|
|
3225
|
+
*/
|
|
3226
|
+
export declare function validateShape(shape: ContractShape): void;
|
|
3227
|
+
|
|
3228
|
+
/**
|
|
3229
|
+
* Infer a `JSONSchema` for one unknown value — the reverse direction of
|
|
3230
|
+
* {@link compileSchema}.
|
|
3231
|
+
*
|
|
3232
|
+
* @remarks
|
|
3233
|
+
* Total: never throws, and is cycle/depth/breadth-bounded (see
|
|
3234
|
+
* {@link inferValue} / {@link inferArray} / {@link inferObject}). Nested
|
|
3235
|
+
* objects close to unknown keys (`additionalProperties: false`) by default;
|
|
3236
|
+
* pass `closed: false` to open them. `format` (default `false`) opts a
|
|
3237
|
+
* string/`Date` leaf into the `format` keyword. Structurally-equal inputs
|
|
3238
|
+
* infer byte-identical schemas (object keys and `anyOf` members are sorted).
|
|
3239
|
+
*
|
|
3240
|
+
* A non-object root — e.g. `valueToSchema('hi')` yielding `{ type: 'string'
|
|
3241
|
+
* }` — is structurally accepted by `schemaToParameters`, but MCP clients
|
|
3242
|
+
* expect an object-shaped `inputSchema`; wrap a non-object payload with
|
|
3243
|
+
* {@link schemaToObject} before advertising it as a tool's parameters.
|
|
3244
|
+
*
|
|
3245
|
+
* `maxDepth` / `maxProperties` are sanitized via {@link sanitizeBudget} to a
|
|
3246
|
+
* finite non-negative integer, falling back to {@link INFER_DEPTH_LIMIT} /
|
|
3247
|
+
* {@link INFER_BREADTH_LIMIT} for anything else (`NaN`, `Infinity`, negative,
|
|
3248
|
+
* fractional) — a hostile or malformed budget can never defeat the depth
|
|
3249
|
+
* guard or corrupt the sampled key/element list.
|
|
3250
|
+
*
|
|
3251
|
+
* @param value - The value to infer a schema from
|
|
3252
|
+
* @param options - Optional `maxDepth` / `maxProperties` / `closed` / `format` bounds
|
|
3253
|
+
* @returns The inferred `JSONSchema`
|
|
3254
|
+
*
|
|
3255
|
+
* @example
|
|
3256
|
+
* ```ts
|
|
3257
|
+
* valueToSchema({ id: 1, name: 'Ada', tags: ['a', 'b'] })
|
|
3258
|
+
* // { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' },
|
|
3259
|
+
* // tags: { type: 'array', items: { type: 'string' } } },
|
|
3260
|
+
* // required: ['id', 'name', 'tags'], additionalProperties: false }
|
|
3261
|
+
* ```
|
|
3262
|
+
*/
|
|
3263
|
+
export declare function valueToSchema(value: unknown, options?: ValueToSchemaOptions): JSONSchema;
|
|
3264
|
+
|
|
3265
|
+
/**
|
|
3266
|
+
* Options for {@link valueToSchema} / {@link samplesToSchema}.
|
|
3267
|
+
*
|
|
3268
|
+
* @remarks
|
|
3269
|
+
* The reverse direction of {@link compileSchema}: instead of emitting a
|
|
3270
|
+
* `JSONSchema` from a developer-authored `ContractShape`, these bounds tame
|
|
3271
|
+
* inference from an unknown runtime value (or a set of example values), which
|
|
3272
|
+
* — unlike a shape tree — may be arbitrarily deep, wide, or cyclic.
|
|
3273
|
+
*
|
|
3274
|
+
* @remarks
|
|
3275
|
+
* `format` (default `false`) emits a `format` keyword on a string leaf whose
|
|
3276
|
+
* value(s) unanimously match one {@link SchemaFormat} via {@link stringToFormat}
|
|
3277
|
+
* / {@link samplesToFormat}. `enum` (default `false`, multi-sample paths only)
|
|
3278
|
+
* emits an `enum` keyword for a low-cardinality, repeated primitive slot
|
|
3279
|
+
* instead of a bare `type`.
|
|
3280
|
+
*/
|
|
3281
|
+
export declare interface ValueToSchemaOptions {
|
|
3282
|
+
readonly maxDepth?: number;
|
|
3283
|
+
readonly maxProperties?: number;
|
|
3284
|
+
readonly closed?: boolean;
|
|
3285
|
+
readonly format?: boolean;
|
|
3286
|
+
readonly enum?: boolean;
|
|
3287
|
+
}
|
|
3288
|
+
|
|
3289
|
+
/**
|
|
3290
|
+
* Refine a base guard with an additional predicate that runs only when the base
|
|
3291
|
+
* passes.
|
|
3292
|
+
*
|
|
3293
|
+
* @remarks
|
|
3294
|
+
* The predicate receives a value already narrowed to `T`. When the predicate is
|
|
3295
|
+
* itself a type guard (`value is U`), the result narrows to `Guard<U>` — it
|
|
3296
|
+
* passes only when the value is genuinely a `U`, so the narrowing is sound. Per
|
|
3297
|
+
* §14 the returned guard never throws: if `predicate` throws, the throw is
|
|
3298
|
+
* contained and the guard reports a non-match.
|
|
3299
|
+
*
|
|
3300
|
+
* @example
|
|
3301
|
+
* ```ts
|
|
3302
|
+
* const isPositive = whereOf(isNumber, (n) => n > 0)
|
|
3303
|
+
* isPositive(5) // true
|
|
3304
|
+
* isPositive(-1) // false
|
|
3305
|
+
*
|
|
3306
|
+
* // A narrowing predicate refines the result type to Guard<5>
|
|
3307
|
+
* const isFive = whereOf(isNumber, (n): n is 5 => n === 5)
|
|
3308
|
+
* ```
|
|
3309
|
+
*/
|
|
3310
|
+
export declare function whereOf<T, U extends T>(base: Guard<T>, predicate: (value: T) => value is U): Guard<U>;
|
|
3311
|
+
|
|
3312
|
+
export declare function whereOf<T>(base: Guard<T>, predicate: (value: T) => boolean): Guard<T>;
|
|
3313
|
+
|
|
3314
|
+
/** An async function accepting zero arguments and returning a `Promise`. */
|
|
3315
|
+
export declare type ZeroArgAsyncFunction = () => Promise<unknown>;
|
|
3316
|
+
|
|
3317
|
+
/** A function accepting zero arguments and returning `unknown`. */
|
|
3318
|
+
export declare type ZeroArgFunction = () => unknown;
|
|
3319
|
+
|
|
3320
|
+
export { }
|