@orkestrel/contract 0.0.3 → 0.0.5

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.
@@ -143,16 +143,32 @@ export declare function unionShape<V extends readonly ContractShape[]>(...varian
143
143
  * Build a {@link UnionShape} that emits `oneOf` (exactly one match) in JSON Schema.
144
144
  *
145
145
  * @remarks
146
- * Runtime behavior is identical to {@link unionShape} — only the emitted schema
147
- * keyword differs (`oneOf` vs `anyOf`).
146
+ * Unlike {@link unionShape} (`anyOf` — at least one variant matches),
147
+ * `oneOfShape`'s compiled guard and parser enforce EXACTLY one match:
148
+ *
149
+ * - **Guard**: accepts the value only when exactly one variant's guard
150
+ * accepts it. A value matching two-or-more variants — which would violate
151
+ * the emitted `oneOf` schema — is rejected, even though it would pass
152
+ * {@link unionShape}'s guard.
153
+ * - **Parser**: judged on the RAW input's guard matches only, with NO
154
+ * coercion fallback for an ambiguous input. When exactly one variant's
155
+ * guard accepts the raw value, that variant's parser runs. Zero matches or
156
+ * two-or-more matches both parse to `undefined` — a value ambiguous
157
+ * between variants has no well-defined coercion target.
158
+ *
159
+ * Prefer {@link unionShape} when a value may legitimately satisfy more than
160
+ * one variant (e.g. overlapping shapes) and any match is acceptable. Prefer
161
+ * `oneOfShape` when overlap between variants indicates malformed input that
162
+ * must be rejected.
148
163
  *
149
164
  * @param variants - The candidate shapes
150
165
  * @returns A union shape with `mode: 'oneOf'`
151
166
  *
152
167
  * @example
153
168
  * ```ts
154
- * const id = oneOfShape(stringShape(), integerShape())
155
- * // Infer<typeof id> = string | number
169
+ * const id = oneOfShape(numberShape(), integerShape())
170
+ * // 3 fails — matches both numberShape and integerShape
171
+ * // 3.5 passes — matches numberShape only
156
172
  * ```
157
173
  */
158
174
  export declare function oneOfShape<V extends readonly ContractShape[]>(...variants: V): UnionShape<V>;
@@ -278,6 +278,15 @@ export interface RawShape {
278
278
  * out until it aborts with TS2589. Bailing out lazily short-circuits that
279
279
  * fixed point (the untaken branch is never instantiated) while every narrow
280
280
  * shape and every partial union still flows through the exact chain below.
281
+ *
282
+ * The `ObjectShape` branch's `additionalProperties` guard (`[A] extends
283
+ * [boolean | ContractShape]`) is likewise wrapped in a tuple to stay
284
+ * non-distributive: a naked `A extends boolean | ContractShape` distributes
285
+ * over a union `A`, fanning a wide `additionalProperties` type into one
286
+ * {@link InferObject} instantiation per union member instead of one
287
+ * instantiation over the whole union — the same TS2589 risk under repeated
288
+ * nesting. {@link InferIndex} and {@link InferOpenIndex} apply the identical
289
+ * tuple guard to their own `A` parameter for the same reason.
281
290
  */
282
291
  export 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 {
283
292
  readonly type: 'literal';
@@ -285,7 +294,7 @@ export type Infer<S extends ContractShape> = [ContractShape] extends [S] ? unkno
285
294
  } ? V extends readonly (infer L)[] ? L : never : S extends {
286
295
  readonly type: 'array';
287
296
  readonly items: infer I;
288
- } ? 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 {
297
+ } ? 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 {
289
298
  readonly type: 'union';
290
299
  readonly variants: infer V;
291
300
  } ? V extends readonly ContractShape[] ? InferUnion<V> : never : S extends {
@@ -299,8 +308,19 @@ export type Infer<S extends ContractShape> = [ContractShape] extends [S] ? unkno
299
308
  * {@link Infer} of an object shape's `properties` — the required keys, plus the
300
309
  * `optional`-wrapped keys as optional members, plus the index-signature
301
310
  * contribution of `additionalProperties` (see {@link InferIndex}).
311
+ *
312
+ * @remarks
313
+ * The `[keyof P] extends [never]` split is hoisted to the front (rather than
314
+ * folded into the intersection's second operand) so a pure record shape
315
+ * (`P` empty) short-circuits straight to {@link InferIndex} without ever
316
+ * building the `Readonly<{} & {}>` intersection shell — the clean
317
+ * `Readonly<Record<string, V>>` {@link InferIndex} already returns. A closed
318
+ * empty object (`P` empty, `A` `false`/absent) still resolves through
319
+ * {@link InferIndex}'s own `[A] extends [false]` branch to
320
+ * `Readonly<Record<never, never>>`, preserving the empty-closed-object result.
321
+ * A shape with fixed properties always routes through {@link InferOpenIndex}.
302
322
  */
303
- export type InferObject<P extends Readonly<Record<string, ContractShape>>, A extends boolean | ContractShape = false> = Readonly<{
323
+ export 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<{
304
324
  [K in keyof P as P[K] extends {
305
325
  readonly type: 'optional';
306
326
  } ? never : K]: Infer<P[K]>;
@@ -311,7 +331,7 @@ export type InferObject<P extends Readonly<Record<string, ContractShape>>, A ext
311
331
  readonly type: 'optional';
312
332
  readonly inner: infer I;
313
333
  } ? I extends ContractShape ? Infer<I> : never : never;
314
- }> & ([keyof P] extends [never] ? InferIndex<A> : InferOpenIndex<A>);
334
+ }> & InferOpenIndex<A>;
315
335
  /**
316
336
  * The index-signature contribution of a pure record shape's `additionalProperties`
317
337
  * — the `recordShape` case, where `properties` is empty.
@@ -323,10 +343,16 @@ export type InferObject<P extends Readonly<Record<string, ContractShape>>, A ext
323
343
  * {@link ContractShape} (open, constrained) contributes an index signature
324
344
  * typed to that shape's own `Infer` — sound here because there are no fixed
325
345
  * properties for the index to collide with.
346
+ *
347
+ * @remarks
348
+ * The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay
349
+ * non-distributive, matching {@link Infer}'s own object-branch guard — see
350
+ * that type's remarks for why a naked `extends` here would fan a wide `A`
351
+ * into a union of `InferIndex` instantiations instead of one.
326
352
  */
327
353
  export type InferIndex<A extends boolean | ContractShape> = [A] extends [false] ? unknown : [A] extends [true] ? {
328
354
  readonly [k: string]: unknown;
329
- } : A extends ContractShape ? {
355
+ } : [A] extends [ContractShape] ? {
330
356
  readonly [k: string]: Infer<A>;
331
357
  } : unknown;
332
358
  /**
@@ -342,15 +368,21 @@ export type InferIndex<A extends boolean | ContractShape> = [A] extends [false]
342
368
  * `{ readonly [k: string]: unknown }`: the static type stops over-claiming the
343
369
  * extra-key type while the runtime guard still validates extras against `A`.
344
370
  * `false` / `true` behave exactly as {@link InferIndex}.
371
+ *
372
+ * @remarks
373
+ * The final `[A] extends [ContractShape]` guard is tuple-wrapped to stay
374
+ * non-distributive, matching {@link Infer}'s own object-branch guard and
375
+ * {@link InferIndex}'s tail — see {@link Infer}'s remarks for why a naked
376
+ * `extends` here would fan a wide `A` into a union of instantiations.
345
377
  */
346
378
  export type InferOpenIndex<A extends boolean | ContractShape> = [A] extends [false] ? unknown : [A] extends [true] ? {
347
379
  readonly [k: string]: unknown;
348
- } : A extends ContractShape ? {
380
+ } : [A] extends [ContractShape] ? {
349
381
  readonly [k: string]: unknown;
350
382
  } : unknown;
351
383
  /** {@link Infer} of a union shape's `variants` — the union of each variant's inferred type. */
352
384
  export type InferUnion<V extends readonly ContractShape[]> = V extends readonly (infer U)[] ? U extends ContractShape ? Infer<U> : never : never;
353
- /** {@link Infer} with all `readonly` modifiers stripped — for consumers writing the parsed value. */
385
+ /** {@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. */
354
386
  export type InferMutable<S extends ContractShape> = {
355
387
  -readonly [K in keyof Infer<S>]: Infer<S>[K];
356
388
  };
@@ -399,6 +431,51 @@ export interface ObjectShapeOptions<A extends boolean | ContractShape = boolean
399
431
  export interface RecordShapeOptions {
400
432
  readonly description?: string;
401
433
  }
434
+ /** The kind of value a {@link Fault} expected — the shape-projected counterpart of a `ContractShape`'s `type`. */
435
+ export type FaultKind = 'string' | 'number' | 'integer' | 'boolean' | 'null' | 'literal' | 'array' | 'object' | 'union' | 'json';
436
+ /** The refinement a {@link Fault} of reason `'constraint'` violates. */
437
+ export type FaultConstraint = 'min' | 'max' | 'pattern' | 'integer';
438
+ /**
439
+ * A single structured parse-failure diagnostic — one entry of an
440
+ * {@link ContractInterface.explain} report.
441
+ *
442
+ * @remarks
443
+ * A discriminated union on `reason`:
444
+ * - `'type'` — the value could not coerce to `expected` at all.
445
+ * - `'missing'` — a required object property was absent.
446
+ * - `'constraint'` — the value coerced to `expected` but violated one
447
+ * refinement (`min` / `max` / `pattern` / `integer`); `limit` carries the
448
+ * violated bound/pattern when applicable.
449
+ * - `'variant'` — an `anyOf`-mode union matched no variant; `variants` is the
450
+ * variant count, followed (in the report) by the closest variant's own faults.
451
+ * - `'oneOf'` — a `oneOf`-mode union matched zero or two-or-more variants;
452
+ * `matched` is the raw match count.
453
+ */
454
+ export type Fault = {
455
+ readonly reason: 'type';
456
+ readonly path: FieldPath;
457
+ readonly expected: FaultKind;
458
+ readonly received: string;
459
+ } | {
460
+ readonly reason: 'missing';
461
+ readonly path: FieldPath;
462
+ readonly expected: FaultKind;
463
+ } | {
464
+ readonly reason: 'constraint';
465
+ readonly path: FieldPath;
466
+ readonly expected: FaultKind;
467
+ readonly constraint: FaultConstraint;
468
+ readonly limit?: number | string;
469
+ readonly received: string;
470
+ } | {
471
+ readonly reason: 'variant';
472
+ readonly path: FieldPath;
473
+ readonly variants: number;
474
+ } | {
475
+ readonly reason: 'oneOf';
476
+ readonly path: FieldPath;
477
+ readonly matched: number;
478
+ };
402
479
  /** A deterministic random source returning a value in `[0, 1)`. */
403
480
  export type RandomFunction = () => number;
404
481
  /**
@@ -414,5 +491,18 @@ export interface ContractInterface<T> {
414
491
  readonly schema: JSONSchema;
415
492
  readonly is: Guard<T>;
416
493
  parse(value: unknown): T | undefined;
494
+ /**
495
+ * Report every structured parse fault a value has against this contract.
496
+ *
497
+ * @remarks
498
+ * An empty report means the value is valid. Soundness invariant:
499
+ * `explain(v).length === 0` if and only if `parse(v) !== undefined` — explain
500
+ * mirrors `parse`'s coercion, not the stricter `is`. Faults are listed in
501
+ * stable pre-order (declared key/index order).
502
+ *
503
+ * @param value - The value to check
504
+ * @returns The faults found, empty when the value parses successfully
505
+ */
506
+ explain(value: unknown): readonly Fault[];
417
507
  generate(random?: RandomFunction): T;
418
508
  }
@@ -27,16 +27,38 @@ export declare function isUndefined(value: unknown): value is undefined;
27
27
  * ```
28
28
  */
29
29
  export declare function isDefined<T>(value: T | null | undefined): value is T;
30
- /** Determine whether a value is a string. */
30
+ /** Determine whether a value is a string.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * isString('hi') // true
35
+ * isString(42) // false
36
+ * ```
37
+ */
31
38
  export declare function isString(value: unknown): value is string;
32
39
  /**
33
40
  * Determine whether a value is a number.
34
41
  *
35
42
  * @remarks
36
43
  * Includes `NaN` and `±Infinity` — use {@link isFiniteNumber} to exclude them.
44
+ *
45
+ * @example
46
+ * ```ts
47
+ * isNumber(42) // true
48
+ * isNumber(Number.NaN) // true — NaN is still a number
49
+ * isNumber('42') // false
50
+ * ```
37
51
  */
38
52
  export declare function isNumber(value: unknown): value is number;
39
- /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`). */
53
+ /** Determine whether a value is a finite number (excludes `NaN` and `±Infinity`).
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * isFiniteNumber(42) // true
58
+ * isFiniteNumber(Number.NaN) // false
59
+ * isFiniteNumber(Infinity) // false
60
+ * ```
61
+ */
40
62
  export declare function isFiniteNumber(value: unknown): value is number;
41
63
  /** Determine whether a value is a finite integer (excludes `NaN`, `±Infinity`, and fractional numbers).
42
64
  *
@@ -131,6 +153,31 @@ export declare function isNullableNumber(value: unknown): value is number | null
131
153
  * ```
132
154
  */
133
155
  export declare function isNullableBoolean(value: unknown): value is boolean | null;
156
+ /**
157
+ * Determine whether a value is an instance of a constructor, contained against
158
+ * a throwing `instanceof` check.
159
+ *
160
+ * @remarks
161
+ * The low-level total helper every `instanceof`-based guard in this file (and
162
+ * the `instanceOf` combinator) routes through. A bare `value instanceof X` is
163
+ * NOT total (AGENTS §14): it invokes `getPrototypeOf` on `value` — which a
164
+ * revoked `Proxy` or a `getPrototypeOf`-trap `Proxy` throws from — and, when
165
+ * `X[Symbol.hasInstance]` is user-defined, can throw from arbitrary code. This
166
+ * wraps the check in {@link attempt} (see ./helpers.js) so any such throw
167
+ * yields `false` instead of escaping.
168
+ *
169
+ * @param value - The value to test
170
+ * @param ctor - The constructor to test against
171
+ * @returns `true` when `value instanceof ctor`, `false` on a non-match or a
172
+ * contained throw
173
+ *
174
+ * @example
175
+ * ```ts
176
+ * isInstance(new Date(), Date) // true
177
+ * isInstance({}, Date) // false
178
+ * ```
179
+ */
180
+ export declare function isInstance<C>(value: unknown, ctor: C): value is InstanceType<C & AnyConstructor<object>>;
134
181
  /** Determine whether a value is a `Date`.
135
182
  *
136
183
  * @example
@@ -265,6 +312,14 @@ export declare function isObject(value: unknown): value is object;
265
312
  * instance's runs through the class's own prototype. The whole body runs
266
313
  * inside `attempt` (AGENTS §14) so a revoked `Proxy` or a hostile
267
314
  * `getPrototypeOf` trap cannot escape as a thrown error.
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * isRecord({ a: 1 }) // true
319
+ * isRecord(Object.create(null)) // true
320
+ * isRecord([]) // false
321
+ * isRecord(new Date()) // false
322
+ * ```
268
323
  */
269
324
  export declare function isRecord(value: unknown): value is Record<string, unknown>;
270
325
  /** Determine whether a value is a `Map`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orkestrel/contract",
3
- "version": "0.0.3",
3
+ "version": "0.0.5",
4
4
  "description": "Zero-dependency contract toolkit — type guards, combinators, parsers, and a shape DSL that compiles one contract shape into a guard, parser, JSON Schema, and generator. The foundation package of the @orkestrel line.",
5
5
  "keywords": [
6
6
  "contract",
@@ -64,7 +64,7 @@
64
64
  "prepublishOnly": "npm run format:check && npm run lint:check && npm run check && npm run build && npm test"
65
65
  },
66
66
  "devDependencies": {
67
- "@orkestrel/guide": "^0.0.1",
67
+ "@orkestrel/guide": "^0.0.3",
68
68
  "@types/node": "^26.1.1",
69
69
  "oxfmt": "^0.59.0",
70
70
  "oxlint": "^1.74.0",