@final-hill/decorator-contracts 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,67 @@
1
- import type { FeatureDecoratorContext } from './types.mjs';
1
+ import type { ArmOptions } from './admissibility.mjs';
2
+ /**
3
+ * Rejects a call that did not receive a standard decorator context.
4
+ *
5
+ * Every standard context carries a string `kind`, and the second argument of a
6
+ * pre-standard invocation never does: for a member it is the property key, and a
7
+ * class decorator is called with the class alone, so there is no second argument
8
+ * at all. Testing that one field is therefore enough to tell the protocols apart,
9
+ * and it is deliberately the only test — a guard that demanded more of the
10
+ * context would reject a real one as the decorator-context proposal gains fields.
11
+ *
12
+ * Without the check every later assertion describes the wrong problem: a member
13
+ * decorator reports that the method it was applied to is not a method, and
14
+ * `@invariant` destructures `undefined`.
15
+ *
16
+ * The check runs before any other, in every decorator, because it is the one
17
+ * failure that makes the rest of the diagnostics meaningless.
18
+ *
19
+ * The assertion signature carries the narrowing, so callers get a typed context
20
+ * from a value they could not otherwise inspect. It narrows to the union rather
21
+ * than to a member context, because a class decorator is checked by the same
22
+ * guard.
23
+ */
24
+ export declare function assertDecoratorContext(contract: string, context: unknown): asserts context is DecoratorContext;
2
25
  /**
3
26
  * The gate every feature contract decorator shares.
4
27
  *
5
28
  * `@demands`, `@ensures`, and `@rescue` apply to exactly the same kind of member:
6
29
  * an instance feature of a `Contracted` subclass, whose name is not `_`-prefixed.
7
- * Each used to repeat the same four assertions and the same `addInitializer`
8
- * check, so a rule added to one was easy to miss in the others.
30
+ * The rule lives here rather than in each decorator so that a constraint added to
31
+ * one applies to all three, instead of being easy to miss in the others.
9
32
  *
10
33
  * The name of the contract is passed in so the messages stay specific.
34
+ *
35
+ * `context` is `unknown` because the protocol is diagnosed here rather than by
36
+ * the caller; the guard narrows it to a standard context.
37
+ */
38
+ export declare function assertFeatureContractTarget(contract: string, feature: unknown, context: unknown): void;
39
+ /**
40
+ * Rejects `awaitPredicate` on a feature whose boundary cannot await it.
41
+ *
42
+ * The option moves a precondition's verdict to a microtask, which is only sound
43
+ * where the feature's own result is already behind a promise: an `async` body is
44
+ * awaited before its exit checks run, so awaiting its entry checks moves nothing
45
+ * the caller could observe. The other three boundaries cannot absorb the wait.
46
+ *
47
+ * - A getter or setter is an accessor. Its caller reads or assigns synchronously,
48
+ * so there is no promise to attach a pending verdict to.
49
+ * - A generator hands the caller an iterator and runs nothing until it is
50
+ * resumed. Its contracts bracket a *step*, and awaiting one would make every
51
+ * `next()` asynchronous — a different protocol, not a slower check.
52
+ * - An async generator has the same per-step boundary.
53
+ *
54
+ * Each case is refused where it is written, with the reason, rather than accepted
55
+ * and then ignored by a lifecycle that cannot honour it. The element is the
56
+ * decorated member itself, so its kind is readable here; a class body that
57
+ * overrides an `async` feature with a synchronous one is caught separately, at the
58
+ * boundary, because the inherited declaration is not in scope at this point.
59
+ *
60
+ * @param contract - The contract name, for the message.
61
+ * @param element - The decorated member, whose kind decides.
62
+ * @param context - The member's decorator context.
63
+ * @param options - The declaration's options.
11
64
  */
12
- export declare function assertFeatureContractTarget(contract: string, feature: unknown, ctx: FeatureDecoratorContext): void;
65
+ export declare function assertAwaitableFeature(contract: string, element: unknown, context: {
66
+ kind: string;
67
+ }, options: ArmOptions | undefined): void;
@@ -2,21 +2,52 @@ import { Contracted } from "./Contracted.mjs";
2
2
  import { type ArmOptions } from './admissibility.mjs';
3
3
  import type { StandardSchemaV1 } from './standard-schema.mjs';
4
4
  import type { FeatureDecoratorContext } from './types.mjs';
5
+ /**
6
+ * The fields a precondition predicate is called with.
7
+ *
8
+ * `self` is the instance and `args` is the invocation's argument list.
9
+ *
10
+ * `This` and `Args` are inferred from the member the decorator is applied to, so
11
+ * a predicate that reads instance state needs no annotation:
12
+ * `({ self, args }) => self._x > 0`. The inference comes from the decorator's
13
+ * context type, which carries the class and the feature's signature; naming it
14
+ * explicitly is only necessary where the runtime subject differs from that
15
+ * signature.
16
+ *
17
+ * `self` is **not** `Readonly<This>`. `Readonly` maps over `keyof This`, which
18
+ * covers only public members, so `Readonly<Cart>` has no `_balance` when
19
+ * `_balance` is `protected` — the type would erase the fields contracts are
20
+ * written against, and `protected` state is the documented convention. Purity is
21
+ * enforced at runtime instead: every predicate receives a read-only view, so an
22
+ * assignment throws rather than silently corrupting the instance the next
23
+ * contract observes.
24
+ */
25
+ export interface DemandsSubject<This, Args extends any[] = any[]> {
26
+ readonly self: This;
27
+ readonly args: Args;
28
+ }
5
29
  /**
6
30
  * A precondition predicate.
7
31
  *
8
32
  * `args` is the argument list of the invocation, matching `EnsuresPredicate`,
9
- * so a predicate destructures it: `(_self, [x]) => x > 0`.
33
+ * so a predicate destructures it: `({ args: [x] }) => x > 0`.
10
34
  *
11
35
  * The type is generic over the argument tuple so the element types are inferred
12
- * from the predicate. Writing `(_self, x: number) => x > 0` does not compile:
13
- * the second parameter is the array, not the first argument, and a predicate
14
- * that compares against the array passes only through coercion, which is how
15
- * the previous documentation ended up describing contracts that never held.
36
+ * from the predicate. Writing `({ args }) => args > 0` does not compile: `args`
37
+ * is the array, not the first argument, and a predicate that compares against the
38
+ * array passes only through coercion.
39
+ *
40
+ * It takes one object rather than a positional list, so a contract that supplies
41
+ * a field the predicate does not read costs nothing where it is declared.
16
42
  */
17
- export type DemandsPredicate<This extends Contracted, Args extends any[] = any[]> = (self: This, args: Args) => boolean;
43
+ export type DemandsPredicate<This extends Contracted, Args extends any[] = any[]> = (subject: DemandsSubject<This, Args>) => boolean;
18
44
  /**
19
- * A precondiction arm: a predicate, or a schema the argument tuple must satisfy.
45
+ * A precondition arm: a predicate, or a schema the argument tuple must satisfy.
46
+ *
47
+ * A predicate may answer with a promise, but only when the declaration sets
48
+ * {@link ArmOptions.awaitPredicate} — the option is what makes the verdict
49
+ * awaited rather than coerced, and the overload on `DemandsDecorator` refuses the
50
+ * asynchronous form without it.
20
51
  *
21
52
  * A schema validates the **argument tuple**, which is the subject `@demands`
22
53
  * already describes, so a method with two parameters is written as
@@ -29,8 +60,22 @@ export type DemandsPredicate<This extends Contracted, Args extends any[] = any[]
29
60
  * `z.tuple([...])` whose input is `[number, number]`. The tuple shape is an
30
61
  * obligation on the declaration, checked at runtime by the schema itself.
31
62
  */
32
- export type DemandsArm<This extends Contracted, Args extends any[] = any[]> = DemandsPredicate<This, Args> | StandardSchemaV1<unknown, any>;
33
- export type DemandsDecorator = <This extends Contracted, Args extends any[], Feature = unknown>(arm: DemandsArm<This, Args>, options?: ArmOptions) => (value: Feature, context: FeatureDecoratorContext) => Feature | void;
63
+ export type DemandsArm<This extends Contracted, Args extends any[] = any[]> = DemandsPredicate<This, Args> | ((subject: DemandsSubject<This, Args>) => boolean | Promise<boolean>) | StandardSchemaV1<unknown, any>;
64
+ /**
65
+ * The `@demands` decorator.
66
+ *
67
+ * The two overloads are the opt-in. The first admits a synchronous verdict or a
68
+ * schema, so an accidentally `async` predicate is a compile error there; the
69
+ * second admits a promise and requires `awaitPredicate: true` to say so. Inference
70
+ * of `self` and `args` comes from the decorated member either way, and an options
71
+ * object built separately still matches the first overload.
72
+ */
73
+ export type DemandsDecorator = {
74
+ <This extends Contracted, Args extends any[]>(arm: DemandsPredicate<This, Args> | StandardSchemaV1<unknown, any>, options?: ArmOptions): (value: unknown, context: FeatureDecoratorContext<This, Args>) => void;
75
+ <This extends Contracted, Args extends any[]>(arm: DemandsArm<This, Args>, options: ArmOptions & {
76
+ awaitPredicate: true;
77
+ }): (value: unknown, context: FeatureDecoratorContext<This, Args>) => void;
78
+ };
34
79
  /** A registered precondition arm, with the options it was declared with. */
35
80
  export interface RegisteredDemands {
36
81
  arm: DemandsArm<Contracted>;
@@ -48,7 +93,40 @@ export declare const demands: DemandsDecorator;
48
93
  * arguments, and because OR-composition short-circuits, the **first passing arm**
49
94
  * decides what that value is. That is deterministic and matches evaluation order.
50
95
  *
96
+ * @param enabled - Whether the contracts are evaluated for this class. The lifecycle
97
+ * has already resolved the switch, so it passes its verdict rather than making this
98
+ * function walk the class chain a second time; a caller that reaches this function
99
+ * on its own omits it and the switch is resolved here.
51
100
  * @returns The arguments to use, which are the originals unless an arm
52
101
  * normalized them.
53
102
  */
54
- export declare function assertDemands(instance: Contracted, propertyKey: PropertyKey, args: any[]): any[];
103
+ export declare function assertDemands(instance: Contracted, propertyKey: PropertyKey, args: any[], enabled?: boolean): any[];
104
+ /**
105
+ * Whether any registered arm declared `awaitPredicate`.
106
+ *
107
+ * The asynchronous lifecycle asks this before choosing the awaited composition, so
108
+ * a feature whose arms are all synchronous pays nothing for the capability: the
109
+ * awaited form returns a promise from every call, which is one extra microtask the
110
+ * caller would wait on for a verdict that was already decided synchronously.
111
+ *
112
+ * @param instance - The instance whose class holds the record.
113
+ * @param propertyKey - The feature being invoked.
114
+ * @internal
115
+ * Exported only so the lifecycle in `Contracted.mts` can import it; `index.mts`
116
+ * does not re-export it.
117
+ */
118
+ export declare function demandsAwaitable(instance: Contracted, propertyKey: PropertyKey): boolean;
119
+ /**
120
+ * Evaluates the precondition for an invocation whose arms may answer with a promise.
121
+ *
122
+ * OR-composition decides the arms here too: a subtype may weaken a precondition,
123
+ * so satisfying any arm is enough. Only the settlement differs, and it is stated
124
+ * separately from {@link assertDemands} because the two boundaries differ: this
125
+ * one hands back a promise, and a synchronous feature's precondition must be
126
+ * decided before its body starts rather than in a microtask afterwards.
127
+ *
128
+ * A rejected predicate is a failed arm, exactly as a throwing one is, so a sibling
129
+ * arm may still permit the call and the rejection is raised only if every arm
130
+ * fails.
131
+ */
132
+ export declare function assertDemandsAsync(instance: Contracted, propertyKey: PropertyKey, args: any[], enabled?: boolean): Promise<any[]>;
@@ -2,14 +2,60 @@ import { Contracted } from './Contracted.mjs';
2
2
  import { type ArmOptions } from './admissibility.mjs';
3
3
  import type { StandardSchemaV1 } from './standard-schema.mjs';
4
4
  import type { FeatureDecoratorContext } from './types.mjs';
5
+ /**
6
+ * The fields a postcondition predicate is called with.
7
+ *
8
+ * `old` is the snapshot of the instance from before the feature ran. It is not
9
+ * `Readonly`, and is deliberately not the same object as `self`: it is a detached
10
+ * copy, so a predicate writing to it corrupts nothing.
11
+ *
12
+ * `oldArgs` is the snapshot of the **call's arguments** from before the body ran,
13
+ * taken on the same terms as `old`. It is what lets a predicate state a property
14
+ * over an object it was *given*, rather than only over the instance whose feature
15
+ * it is: `oldArgs[0].onHold` is the argument's state before the call, while
16
+ * `args[0].onHold` is its state now.
17
+ *
18
+ * `oldArgs` mirrors the arguments the caller supplied, which is why a getter has
19
+ * none: `args` describes a getter's *result*, and a result has no pre-state. A
20
+ * generator is the same case from the other end — `args` describes the value the
21
+ * step yielded — so it has none either. Every other feature pairs them:
22
+ * `oldArgs[i]` is the pre-state of `args[i]`.
23
+ *
24
+ * The field is typed `Args` because that is the only tuple the subject carries.
25
+ * A generator's `oldArgs` is therefore empty where its annotation says otherwise,
26
+ * which is why a generator's `@ensures` is annotated for its `args` alone.
27
+ *
28
+ * `result` is the value the feature body produced, which is what the caller
29
+ * receives unless a schema arm normalizes it. Every arm is given the **same**
30
+ * unnormalized value, because `@ensures` is AND-composed: "every arm must hold" is
31
+ * only a statement about one thing if every arm observes one thing. A normalizing
32
+ * schema also validates this value and replaces it afterwards, so a predicate and
33
+ * a schema in the same composition always agree about what they were shown.
34
+ *
35
+ * See `DemandsSubject` for why `self` is not `Readonly<This>` and for the
36
+ * inference that makes an annotation unnecessary.
37
+ *
38
+ * `Result` defaults to `unknown`. A method's context type carries a call
39
+ * signature while a getter's carries the property type, so both would be
40
+ * inference sites for one parameter and the compiler would resolve it to their
41
+ * intersection. A predicate that reads a member of `result` therefore names it —
42
+ * `EnsuresSubject<Cart, [number], number>` — and `unknown` rather than `any` makes
43
+ * forgetting that a compile error rather than a silent `undefined`.
44
+ */
45
+ export interface EnsuresSubject<This, Args extends any[] = any[], Result = unknown> {
46
+ readonly self: This;
47
+ readonly args: Args;
48
+ readonly old: This;
49
+ readonly oldArgs: Args;
50
+ readonly result: Result;
51
+ }
5
52
  /**
6
53
  * A postcondition predicate.
7
54
  *
8
- * `args` is the argument list of the invocation and `old` is the snapshot of
9
- * the instance from before the feature ran, so a predicate reads
10
- * `(self, [x], old) => ...`. See `DemandsPredicate` for why the tuple is generic.
55
+ * It takes one object rather than a positional list, so a contract that supplies
56
+ * fields the predicate does not read costs nothing where it is declared.
11
57
  */
12
- export type EnsuresPredicate<This extends Contracted, Args extends any[] = any[]> = (self: This, args: Args, old: This) => boolean;
58
+ export type EnsuresPredicate<This extends Contracted, Args extends any[] = any[], Result = unknown> = (subject: EnsuresSubject<This, Args, Result>) => boolean;
13
59
  /**
14
60
  * A postcondition arm: a predicate, or a schema the feature's **result** must
15
61
  * satisfy.
@@ -17,10 +63,25 @@ export type EnsuresPredicate<This extends Contracted, Args extends any[] = any[]
17
63
  * A schema validates the result, which is the value the caller receives. This is
18
64
  * the covariant position: a subtype may promise a narrower result, so the arms
19
65
  * are AND-composed.
66
+ *
67
+ * A predicate may answer with a promise only when the declaration sets
68
+ * {@link ArmOptions.awaitPredicate}; the overload on `EnsuresDecorator` is what
69
+ * refuses the asynchronous form without it.
20
70
  */
21
- export type EnsuresArm<This extends Contracted, Args extends any[] = any[]> = EnsuresPredicate<This, Args> | StandardSchemaV1<unknown, any>;
22
- export type EnsuresDecorator = <This extends Contracted, Args extends any[]>(arm: EnsuresArm<This, Args>, options?: ArmOptions) => (value: unknown, context: FeatureDecoratorContext) => void;
23
- /** A registered postcondition arm, with the options it was declared with. */
71
+ export type EnsuresArm<This extends Contracted, Args extends any[] = any[], Result = unknown> = EnsuresPredicate<This, Args, Result> | ((subject: EnsuresSubject<This, Args, Result>) => boolean | Promise<boolean>) | StandardSchemaV1<unknown, any>;
72
+ /**
73
+ * The `@ensures` decorator.
74
+ *
75
+ * The two overloads are the opt-in, as on `@demands`: a promise is admitted only
76
+ * by the second, which requires `awaitPredicate: true`, while the first keeps the
77
+ * synchronous verdict or a schema and accepts an options object built separately.
78
+ */
79
+ export type EnsuresDecorator = {
80
+ <This extends Contracted, Args extends any[], Result = unknown>(arm: EnsuresPredicate<This, Args, Result> | StandardSchemaV1<unknown, any>, options?: ArmOptions): (value: unknown, context: FeatureDecoratorContext<This, Args>) => void;
81
+ <This extends Contracted, Args extends any[], Result = unknown>(arm: EnsuresArm<This, Args, Result>, options: ArmOptions & {
82
+ awaitPredicate: true;
83
+ }): (value: unknown, context: FeatureDecoratorContext<This, Args>) => void;
84
+ };
24
85
  export interface RegisteredEnsures {
25
86
  arm: EnsuresArm<Contracted>;
26
87
  options?: ArmOptions;
@@ -33,7 +94,42 @@ export declare const ensures: EnsuresDecorator;
33
94
  * strengthen a postcondition, so every inherited arm has to keep holding.
34
95
  *
35
96
  * @param result - The value the caller receives. A schema arm validates it.
97
+ * @param oldArgs - The pre-state of the arguments the body received. Optional and
98
+ * trailing so the signature stays additive: a caller that predates the field
99
+ * omits it, and the subject reports an empty list.
100
+ * @returns The result to hand the caller, which is the original unless an arm
101
+ * normalized it.
102
+ */
103
+ export declare function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any[], result: unknown, oldArgs?: any[], enabled?: boolean): unknown;
104
+ /**
105
+ * Whether any registered arm declared `awaitPredicate`.
106
+ *
107
+ * The asynchronous lifecycle asks this before choosing the awaited composition, so
108
+ * a feature whose arms are all synchronous pays nothing for the capability: the
109
+ * awaited form returns a promise from every call, which is one extra microtask the
110
+ * caller would wait on for a verdict that was already decided synchronously.
111
+ *
112
+ * @param instance - The instance whose class holds the record.
113
+ * @param propertyKey - The feature being invoked.
114
+ * @internal
115
+ * Exported only so the lifecycle in `Contracted.mts` can import it; `index.mts`
116
+ * does not re-export it.
117
+ */
118
+ export declare function ensuresAwaitable(instance: Contracted, propertyKey: PropertyKey): boolean;
119
+ /**
120
+ * Evaluates the postcondition for an invocation whose arms may answer with a promise.
121
+ *
122
+ * AND-composition decides the arms here too: a subtype may strengthen a
123
+ * postcondition, so every arm has to hold. Only the settlement differs. A
124
+ * rejected predicate is a failed arm, exactly as a throwing one is, and the
125
+ * rejection is raised only when every arm has been evaluated and at least one
126
+ * failed.
127
+ *
128
+ * @param result - The value the caller receives. A schema arm validates it.
129
+ * @param oldArgs - The pre-state of the arguments the body received. Optional and
130
+ * trailing so the signature stays additive: a caller that predates the field
131
+ * omits it, and the subject reports an empty list.
36
132
  * @returns The result to hand the caller, which is the original unless an arm
37
133
  * normalized it.
38
134
  */
39
- export declare function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any[], result: unknown): unknown;
135
+ export declare function assertEnsuresAsync(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any[], result: unknown, oldArgs?: any[], enabled?: boolean): Promise<unknown>;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Classifies a feature body by how it delivers its results.
3
+ *
4
+ * A Hoare triple `{ P } C { Q }` only means something if `Q` is evaluated after
5
+ * `C` has finished. "Finished" is not the same event for every kind of feature:
6
+ * an `async` body finishes when its promise settles, and a generator finishes a
7
+ * *segment* every time it yields. The kind decides where the exit boundary
8
+ * therefore sits.
9
+ *
10
+ * The classifier lives in its own module because two layers need it and neither
11
+ * should learn the other's vocabulary: the lifecycle dispatches on it, and a
12
+ * decorator refuses a declaration whose boundary cannot honour it. Importing it
13
+ * from `Contracted.mts` would make every decorator depend on the proxy for one
14
+ * `switch`.
15
+ */
16
+ export type FeatureKind = 'sync' | 'async' | 'generator' | 'async-generator';
17
+ /**
18
+ * Reads a feature's kind from its function object.
19
+ *
20
+ * `Reflect.apply` on an `async` function returns its promise immediately, and on
21
+ * a generator it returns an iterator, so the only reliable signal is the
22
+ * function's constructor, which is stable across bundling and minification
23
+ * (unlike `Function.prototype.name`).
24
+ */
25
+ export declare const featureKindOf: (fn: (...args: any[]) => unknown) => FeatureKind;
package/dist/iff.d.mts CHANGED
@@ -9,10 +9,15 @@
9
9
  * @param q - The second boolean value (the consequent).
10
10
  * @returns - The result (biconditional) of p and q, always a `boolean`.
11
11
  *
12
- * A non-boolean operand is coerced rather than rejected, because this is a
13
- * general-purpose logical helper. Inside a contract the coercion is redundant:
14
- * `@demands` and the other contracts already require a literal `true` or `false`
15
- * and will report a non-boolean result by name.
12
+ * A non-boolean operand is coerced rather than rejected, because the parameters are
13
+ * already `boolean`: a typed non-boolean operand does not compile. The coercion
14
+ * therefore decides only what a value that reached the helper through `any` or
15
+ * untyped JavaScript means, and there it is the ordinary JavaScript rule — a truthy
16
+ * operand answers `true` rather than being named.
17
+ *
18
+ * A contract names a non-boolean *result*, but it cannot see inside the helper to
19
+ * name an operand. State a contract through this helper only when both operands are
20
+ * already booleans, or write the comparison directly instead.
16
21
  *
17
22
  * @example
18
23
  * ```ts
@@ -9,8 +9,15 @@
9
9
  * @param q - The second boolean value (the consequent).
10
10
  * @returns - The result (material implication) of p and q, always a `boolean`.
11
11
  *
12
- * A non-boolean consequent is coerced rather than rejected, for the same reason
13
- * as {@link iff}.
12
+ * A non-boolean consequent is coerced rather than rejected, because the parameters
13
+ * are already `boolean`: a typed non-boolean operand does not compile. The coercion
14
+ * therefore decides only what a value that reached the helper through `any` or
15
+ * untyped JavaScript means, and there it is the ordinary JavaScript rule — a truthy
16
+ * operand answers `true` rather than being named.
17
+ *
18
+ * A contract names a non-boolean *result*, but it cannot see inside the helper to
19
+ * name an operand. State a contract through this helper only when both operands are
20
+ * already booleans, or write the comparison directly instead.
14
21
  *
15
22
  * @example
16
23
  * ```ts
package/dist/index.d.mts CHANGED
@@ -6,6 +6,13 @@ export * from './iff.mjs';
6
6
  export * from './implies.mjs';
7
7
  export * from './Contracted.mjs';
8
8
  export * from './invariant.mjs';
9
- export * from './demands.mjs';
10
- export * from './ensures.mjs';
11
- export * from './rescue.mjs';
9
+ export { assertDemands, demands, } from './demands.mjs';
10
+ export type { DemandsArm, DemandsDecorator, DemandsPredicate, DemandsSubject, RegisteredDemands, } from './demands.mjs';
11
+ export { assertEnsures, ensures, } from './ensures.mjs';
12
+ export type { EnsuresArm, EnsuresDecorator, EnsuresPredicate, EnsuresSubject, RegisteredEnsures, } from './ensures.mjs';
13
+ export { applyRescueHandler, getRescueDeclaration, rescue, } from './rescue.mjs';
14
+ export type { RescueDecorator, RescueDeclaration, RescueHandler, RescueOptions, RescueSubject, } from './rescue.mjs';
15
+ export * from './metadata.mjs';
16
+ export { contractName } from './name.mjs';
17
+ export { serializable } from './serialization.mjs';
18
+ export type { ArmOptions, ViolationFactory } from './admissibility.mjs';
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- Symbol.metadata??=Symbol.for("Symbol.metadata");class t extends Error{name="AssertionError";violation;constructor(t,e){super(t),this.violation=e}}const e=new WeakMap,n=t=>"object"==typeof t&&null!==t&&"~standard"in t,r=t=>{if(n(t)){const{vendor:e,version:n}=t["~standard"];return`Standard Schema (vendor: ${String(e)}, version: ${String(n)})`}return String(t)},o=(t,e,r)=>{if(r?.normalize&&!n(t))throw new TypeError(`${e} cannot normalize: only a Standard Schema arm produces a replacement value.`)},a=(t,e,r,o,a,i)=>n(t)?c(t,e.schema(),r,o,a,i):s(t,e.predicate(),r,o,a),s=(t,n,r,o,a)=>{const[s,...c]=n;return{ok:l(t("object"==typeof s&&null!==s?(t=>{const n=e.get(t);if(n)return n;const r=new Proxy(t,{set(t,e){throw new TypeError(`A contract predicate may not assign '${String(e)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},deleteProperty(t,e){throw new TypeError(`A contract predicate may not delete '${String(e)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},defineProperty(){throw new TypeError("A contract predicate may not define properties. Contract predicates answer a question; they must not change the state they are asked about.")}});return e.set(t,r),r})(s):s,...c),r,o,a)}},c=(t,e,n,r,o,a)=>{const s=t["~standard"].validate(e);if("function"==typeof s?.then)throw new TypeError(`${n} schema #${o+1} for ${r} returned a Promise; contract evaluation is synchronous, so use a synchronous schema.`);return s.issues?{ok:!1,issues:s.issues}:a?.normalize?{ok:!0,value:s.value}:{ok:!0}};function i(e,n="Assertion Error"){if(0==Boolean(e))throw new t(n)}const u=t=>"object"==typeof t&&null!==t&&"function"==typeof t.then?"a Promise (contract predicates must be synchronous)":"string"==typeof t?`the string ${JSON.stringify(t)}`:void 0===t?"undefined":null===t?"null":"object"==typeof t?`an object (${Object.prototype.toString.call(t)})`:`a ${typeof t} (${String(t)})`;function l(t,e,n,r){return i("boolean"==typeof t,`${e} predicate #${r+1} for ${n} returned ${u(t)}; contract predicates must return a boolean`),t}function d(t,e,r,o,a,s,c,i=String){const u={contract:t,className:e,feature:r,failedIndices:a,predicates:a.map(t=>i(o[t])),...c&&c.length>0?{issues:c}:{}},l=void 0===r?e:`${e}.${r}`,d=t=>n(t)?"schema":"predicate",f=u.predicates.map((t,e)=>{const n=o[a[e]];return`${d(n)} #${a[e]+1}: ${t}`}).join("; ");var p,m,y,h,g;return{message:`${t} failed for ${l} (${m=a.length,y=o.length,h=d(o[0]),p=o[0],g=n(p)?"schemas":"predicates",`${m} of ${y} ${1===y?h:g}`} unsatisfied: ${f}).${c&&c.length>0?` Reported: ${c.map(t=>(t=>{const e=(t.path??[]).map(t=>"object"==typeof t&&null!==t?t.key:t).join(".");return e?`${e}: ${t.message}`:t.message})(t)).join("; ")}.`:""} ${s}`,violation:u}}function f(e,n,r,o,a,s,c,i=String){const{message:u,violation:l}=d(e,n,r,o,a,s,c,i);return new t(u,l)}function p(t,e){return Boolean(t&&e||!t&&!e)}function m(t,e){return!t||Boolean(e)}function y(t,e){if(!W[P])return;const n=t[Symbol.metadata]?.invariants??[],o=[],s=[];for(const[r,c]of n.entries()){const n=a(c.arm,{predicate:()=>[e],schema:()=>e},"@invariant",t.name,r,c.options);n.ok||(o.push(r),n.issues&&s.push(...n.issues))}if(0!==o.length)throw f("@invariant",t.name,void 0,n.map(t=>t.arm),o,"The instance left the invariant unsatisfied.",s,r)}const h=(t,e)=>(n,{kind:r,metadata:o})=>{i("class"===r,"@invariant decorator can only be applied to classes"),i(n.prototype instanceof W,"@invariant decorator can only be applied to classes that extend Contracted");const a=o.invariants??[];o.invariants=[...a,{arm:t,options:e}]};function g(t,e,n){i(["method","getter","setter"].includes(n.kind),`${t} decorator can only be applied to methods, getters, or setters`),i(!1===n.static,`${t} decorator cannot be applied to static features`),i(!1===n.private,`${t} decorator cannot be applied to private features`),i(!String(n.name).startsWith("_"),`${t} decorator cannot be applied to private/protected features`),n.addInitializer(function(){i(this instanceof W,`${t} decorator can only be applied to classes that extend Contracted`)})}const w=(t,e)=>(n,r)=>{g("@demands",0,r),o(t,"@demands",e);const a=[...r.metadata?.demands?.[r.name]??[],{arm:t,options:e}];r.metadata.demands={...r.metadata?.demands??{},[r.name]:a}};function b(t,e,n){if(!W[P])return n;const o=t.constructor,s=o[Symbol.metadata]?.demands?.[e]??[];if(0===s.length)return n;const c=`${t.constructor.name}.${String(e)}`,i=[],u=[];for(const[e,{arm:r,options:o}]of s.entries()){const s=a(r,{predicate:()=>[t,n],schema:()=>n},"@demands",c,e,o);if(s.ok)return void 0===s.value?n:s.value;i.push(e),s.issues&&u.push(...s.issues)}throw f("@demands",t.constructor.name,String(e),s.map(t=>t.arm),i,"A precondition was not satisfied, so the feature was not entered.",u,r)}const v=(t,e)=>(n,r)=>{g("@ensures",0,r),o(t,"@ensures",e);const a=[...r.metadata?.ensures?.[r.name]??[],{arm:t,options:e}],s=a.filter(t=>t.options?.normalize);if(s.length>1)throw new TypeError(`@ensures for ${String(r.name)} declares ${s.length} normalizing arms; at most one arm may normalize the result, because they would disagree about what the caller receives.`);r.metadata.ensures={...r.metadata?.ensures??{},[r.name]:a}};function $(t,e,n,o,s){if(!W[P])return s;const c=t.constructor,i=c[Symbol.metadata]?.ensures?.[n]??[];if(0===i.length)return s;const u=`${t.constructor.name}.${String(n)}`,l=[],d=[];let p=s;for(const[n,r]of i.entries()){const c=a(r.arm,{predicate:()=>[t,o,e],schema:()=>s},"@ensures",u,n,r.options);c.ok?void 0!==c.value&&(p=c.value):(l.push(n),c.issues&&d.push(...c.issues))}if(0===l.length)return p;throw f("@ensures",t.constructor.name,String(n),i.map(t=>t.arm),l,"A postcondition was not satisfied after the feature ran.",d,r)}const S=(t,e)=>(n,r)=>{g("@rescue",0,r),i(void 0===e?.maxRetries||e.maxRetries>=0,"maxRetries must not be negative"),r.metadata.rescue={...r.metadata?.rescue??{},[r.name]:{handler:t,maxRetries:e?.maxRetries}},r.addInitializer(function(){i(this instanceof W,"@rescue decorator can only be applied to classes that extend Contracted")})};function j(t,e){let n=t.constructor;for(;n&&n!==Function.prototype;){const t=n[Symbol.metadata]?.rescue?.[e];if(t)return t;n=Object.getPrototypeOf(n)}}const O=(t,e,n,r)=>{if(!W[P])throw n;const o=j(t,e);if(!o)throw n;let a=!1,s=[];if(o.handler.call(t,t,n,r,(...t)=>{i(!a,"retry can only be called once per rescue execution"),a=!0,s=t}),!a)throw n;return s},P=Symbol.for("Contracted.checkedMode"),x=(t,e)=>{if("object"!=typeof t||null===t)return t;const n=e.get(t);if(void 0!==n)return n;if(t instanceof Date)return new Date(t.getTime());if(Array.isArray(t)){const n=[];e.set(t,n);for(const r of t)n.push(x(r,e));return n}if(t instanceof Map){const n=new Map;e.set(t,n);for(const[r,o]of t)n.set(x(r,e),x(o,e));return n}if(t instanceof Set){const n=new Set;e.set(t,n);for(const r of t)n.add(x(r,e));return n}if(!(t=>{const e=Object.getPrototypeOf(t);return e===Object.prototype||null===e})(t))return t;const r=Object.create(Object.getPrototypeOf(t));e.set(t,r);for(const n of Reflect.ownKeys(t)){const o=Object.getOwnPropertyDescriptor(t,n);Reflect.defineProperty(r,n,"value"in o?{...o,value:x(o.value,e)}:o)}return r},R=t=>{if(!W[P])return;const e=Object.create(t),n=new WeakMap;for(const r of Reflect.ownKeys(t)){const o=Object.getOwnPropertyDescriptor(t,r);Reflect.defineProperty(e,r,"value"in o?{...o,value:x(o.value,n)}:o)}return e},k=t=>{switch(t.constructor.name){case"AsyncFunction":return"async";case"GeneratorFunction":return"generator";case"AsyncGeneratorFunction":return"async-generator";default:return"sync"}},C=new WeakMap;function E(t,e){let n=t;for(;n&&n!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(n,e);if(t)return t;n=Object.getPrototypeOf(n)}}const A=(t,e,n)=>"get"===t?[e]:n,T=(t,e)=>"get"===t?[]:e;function _(t,e,n,r,o,a){if(o>=(j(e,n)?.maxRetries??1/0))throw y(t,e),r;try{return O(e,n,r,a)}catch(n){throw y(t,e),n}}function z(t,e,n,r,o,a="sync"){return"async"===a?async function(t,e,n,r,o){const a=e.constructor,s=(a[Symbol.metadata]?.ensures?.[n]??[]).length>0;let c=r,i=0;for(;;){const r=s?R(e):void 0;let u;y(a,e),c=b(e,n,c);try{u=await o(c),s&&(u=$(e,r,n,A(t,u,c),u))}catch(r){c=_(a,e,n,r,i,T(t,c)),i++;continue}return y(a,e),u}}(t,e,n,r,o):"generator"===a||"async-generator"===a?function(t,e,n,r,o){const a=t.constructor,s=(a[Symbol.metadata]?.ensures?.[e]??[]).length>0;let c,i,u=n,l=0,d=!0;const f=n=>(y(a,t),d?(d=!1,b(t,e,u)):n.length>0?b(t,e,n):n),p=(n,r)=>{s&&$(t,r,e,[n],n),y(a,t),i=void 0},m=()=>{if(y(a,t),void 0===i)return;const e=i;throw i=void 0,e},h=n=>{u=_(a,t,e,n,l,u),l++,c=r(u),d=!0,i=n},g=(e,n)=>{for(;;)try{n=f(n);const r=s?R(t):void 0,o=e(c,n);return o.done?(m(),o):(p(o.value,r),o)}catch(t){h(t)}},w=async(e,n)=>{for(;;)try{n=f(n);const r=s?R(t):void 0,o=await e(c,n);return o.done?(m(),o):(p(o.value,r),o)}catch(t){h(t)}};y(a,t),u=b(t,e,u),d=!1,c=r(u);const v={};return"generator"===o?(v.next=function(...t){return g((t,e)=>t.next(e[0]),t)},v.return=function(...t){return g((e,n)=>e.return(t[0]??n[0]),[])},v.throw=function(...t){return g((e,n)=>e.throw(t[0]??n[0]),[])},v[Symbol.iterator]=function(){return this}):(v.next=function(...t){return w((t,e)=>t.next(e[0]),t)},v.return=function(...t){return w((e,n)=>e.return(t[0]??n[0]),[])},v.throw=function(...t){return w((e,n)=>e.throw(t[0]??n[0]),[])},v[Symbol.asyncIterator]=function(){return this}),v}(e,n,r,o,a):function(t,e,n,r,o){const a=e.constructor,s=(a[Symbol.metadata]?.ensures?.[n]??[]).length>0;let c=r,i=0;for(;;){const r=s?R(e):void 0;let u;y(a,e),c=b(e,n,c);try{u=o(c),M(u,e,n),s&&(u=$(e,r,n,A(t,u,c),u))}catch(r){c=_(a,e,n,r,i,T(t,c)),i++;continue}return y(a,e),u}}(t,e,n,r,o)}const M=(e,n,r)=>{if(null!==e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then)throw new t(`${n.constructor.name}.${String(r)} returned a promise but is not declared 'async', so its contracts were evaluated before its body finished. Declare the feature 'async'.`)},D={get(t,e,n){if(!W[P])return Reflect.get(t,e,n);const r=E(Object.getPrototypeOf(t),e);if("function"==typeof r?.value){let n=C.get(t);n||(n=new Map,C.set(t,n));const o=n.get(e);if(o)return o;const a=k(r.value),s=function(...n){return z("func",t,e,n,e=>Reflect.apply(r.value,t,e),a)};return n.set(e,s),s}return"function"==typeof r?.get?z("get",t,e,[],()=>r.get.call(t),k(r.get)):Reflect.get(t,e,n)},set(t,e,n,r){if(!W[P])return Reflect.set(t,e,n,r);const o=E(Object.getPrototypeOf(t),e);if(!(o&&"function"==typeof o.set||"string"!=typeof e||e.startsWith("_")))throw new TypeError(`Cannot assign to property '${String(e)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);const a="function"==typeof o?.set?o.set:void 0;return z("set",t,e,[n],n=>a?(a.call(t,n[0]),!0):Reflect.set(t,e,n[0],r)),!0},deleteProperty(t,e){if(!W[P])return Reflect.deleteProperty(t,e);if("string"==typeof e&&!e.startsWith("_"))throw new TypeError(`Cannot delete property '${String(e)}' from Contracted instances: only properties starting with '_' can be deleted.`);return z("delete",t,e,[],()=>Reflect.deleteProperty(t,e))}};class W{static[Symbol.metadata];static _allowedConstructions=0;static[P]=!0;static new(...t){const e=this._allowedConstructions;this._allowedConstructions=e+1;try{const e=new this(...t);return y(this,e),new Proxy(e,D)}finally{this._allowedConstructions=e}}constructor(...t){const e=this.constructor;if(e._allowedConstructions<=0)throw new TypeError("Use the static 'new' method to instantiate this class.");e._allowedConstructions--}}export{t as AssertionError,W as Contracted,O as applyRescueHandler,i as assert,l as assertContractResult,b as assertDemands,$ as assertEnsures,y as assertInvariants,P as checkedMode,w as demands,d as describeViolation,v as ensures,j as getRescueDeclaration,p as iff,m as implies,h as invariant,S as rescue,f as violationError};
1
+ Symbol.metadata??=Symbol.for("Symbol.metadata");class e extends Error{name="AssertionError";violation;constructor(e,t){super(e),this.violation=t}}const t=new WeakMap,n=e=>{const n=t.get(e);if(n)return n;const r=new Proxy(e,{set(e,t){throw new TypeError(`A contract predicate may not assign '${String(t)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},deleteProperty(e,t){throw new TypeError(`A contract predicate may not delete '${String(t)}'. Contract predicates answer a question; they must not change the state they are asked about.`)},defineProperty(){throw new TypeError("A contract predicate may not define properties. Contract predicates answer a question; they must not change the state they are asked about.")}});return t.set(e,r),r},r=e=>"object"==typeof e&&null!==e&&"~standard"in e,o=e=>{if(r(e)){const{vendor:t,version:n}=e["~standard"];return`Standard Schema (vendor: ${String(t)}, version: ${String(n)})`}return String(e)},a=(e,t,n)=>{if(n?.normalize&&!r(e))throw new TypeError(`${t} cannot normalize: only a Standard Schema arm produces a replacement value.`)},s=(e,t,n)=>{if(n?.awaitPredicate&&r(e))throw new TypeError(`${t} cannot declare awaitPredicate on a schema arm: \`validate\` is evaluated synchronously, so there is no verdict to await.`)},i=(e,t)=>{if(void 0!==t?.onViolation&&"function"!=typeof t.onViolation)throw new TypeError(`${e} onViolation must be a function that returns an error object.`)},c=e=>{for(const{options:t}of e)if(t?.onViolation)return t.onViolation},u=(e,t)=>{if(t?.allowWeakening)throw new TypeError(`${e} cannot declare allowWeakening: only a precondition can be weakened, because only \`@demands\` is OR-composed. A subclass arm on an AND-composed contract strengthens the obligation and takes effect, so there is no warning to suppress.`)},l=new WeakMap,d=(e,t,n,o,a,s)=>r(e)?m(e,t.schema(),n,o,a,s):y(e,t.predicate(),n,o,a,s),f=async(e,t,n,o,a,s)=>{if(r(e))return m(e,t.schema(),n,o,a,s);const i=e,c=t.predicate();return s?.awaitPredicate?h(i,c,n,o,a):y(i,c,n,o,a,s)},h=async(e,t,n,r,o)=>{let a;try{a=await p(e,t)}catch(e){return{ok:!1,thrown:e}}return{ok:$(a,n,r,o)}},p=(e,t)=>e("object"==typeof t.self&&null!==t.self?{...t,self:n(t.self)}:t),y=(e,t,n,r,o,a)=>{let s;try{s=p(e,t)}catch(e){return{ok:!1,thrown:e}}if(a?.awaitPredicate&&"function"==typeof s?.then)throw new TypeError(`${n} predicate #${o+1} for ${r()} declared awaitPredicate but returned a Promise, and the feature it guards is not \`async\`, so nothing can await it. Declare the feature \`async\`, or drop the option.`);return{ok:$(s,n,r,o)}},m=(e,t,n,r,o,a)=>{const s=e["~standard"].validate(t);if("function"==typeof s?.then)throw new TypeError(`${n} schema #${o+1} for ${r()} returned a Promise; contract evaluation is synchronous, so use a synchronous schema.`);return s.issues?{ok:!1,issues:s.issues}:a?.normalize?{ok:!0,value:s.value}:{ok:!0}};class w{#e;record(e,t){((e,t,n)=>{e.failed.push(t),n.issues&&e.issues.push(...n.issues),"thrown"in n&&e.thrown.push({index:t,value:n.thrown})})(this.#e??={failed:[],thrown:[],issues:[]},e,t)}get entries(){return this.#e}}const g=()=>new w;function b(t,n="Assertion Error"){if(0==Boolean(t))throw new e(n)}const v=e=>"object"==typeof e&&null!==e&&"function"==typeof e.then?"a Promise (contract predicates must be synchronous)":"string"==typeof e?`the string ${JSON.stringify(e)}`:void 0===e?"undefined":null===e?"null":"object"==typeof e?`an object (${Object.prototype.toString.call(e)})`:`a ${typeof e} (${String(e)})`;function $(t,n,r,o){if("boolean"==typeof t)return t;throw new e(`${n} predicate #${o+1} for ${r()} returned ${v(t)}; contract predicates must return a boolean`)}function O(e,t,n,r,o,a,s,i=String,c){const u=c?.map(e=>e.index),l=c?.map(e=>(e=>{if("object"==typeof e&&null!==e){const t=e,n="string"==typeof t.name?t.name:e.constructor?.name??"Object",r="string"==typeof t.message?t.message:"";return r?`${n}: ${r}`:n}return String(e)})(e.value)),d={contract:e,className:t,feature:n,failedIndices:o,predicates:o.map(e=>i(r[e])),...u&&u.length>0?{thrownIndices:u,thrown:l}:{},...s&&s.length>0?{issues:s}:{}};return{message:j(e,d,r,a,s),violation:d}}const j=(e,t,n,o,a)=>{const s=void 0===t.feature?t.className:`${t.className}.${t.feature}`,i=new Set(t.thrownIndices??[]),c=((e,t,n,o)=>n.map((n,a)=>{const s=t[a];return`${r(e[s])?"schema":"predicate"} #${s+1}${o.has(s)?" threw":""}: ${n}`}).join("; "))(n,t.failedIndices,t.predicates,i);var u,l,d,f,h;return`${e} failed for ${s} (${l=t.failedIndices.length,d=n.length,u=n[0],f=r(u)?"schema":"predicate",h=(e=>r(e)?"schemas":"predicates")(n[0]),`${l} of ${d} ${1===d?f:h}`} unsatisfied: ${c}).${a&&a.length>0?` Reported: ${a.map(e=>(e=>{const t=(e.path??[]).map(e=>"object"==typeof e&&null!==e?e.key:e).join(".");return t?`${t}: ${e.message}`:e.message})(e)).join("; ")}.`:""} ${o}`};function S(t,n,r,o,a,s,i,c=String,u){const{message:l,violation:d}=O(t,n,r,o,a,s,i,c,u);return new e(l,d)}const P=new WeakSet,k=(e,t,n,r=!1)=>{if(!Object.isExtensible(e))return;const o=P.has(e),a=t=>!(o||!Object.hasOwn(e,t)||r&&"violation"===t&&void 0===e.violation);for(const[r,o]of[["violation",t],["cause",n]])a(r)||Object.defineProperty(e,r,{value:o,enumerable:!1,configurable:!0});P.add(e)};function x(e,t,n,r,o,a,s=String,i){const c=S(e,t,n,r,o.failed,a,o.issues,s,o.thrown),u=c.violation;if(i)return((e,t,n,r)=>{const o=r(t);if("object"!=typeof o||null===o)throw new TypeError(`${e} returned ${typeof o}; it must return an object so the violation can be attached.`,{cause:n});return k(o,t,n,!0),o})(`${e} onViolation for ${void 0===n?t:`${t}.${n}`}`,u,c,i);if(0===o.thrown.length)return c;const l=o.thrown[0].value;return"object"==typeof l&&null!==l&&k(l,u,c),l}function z(e,t){return Boolean(e&&t||!e&&!t)}function E(e,t){return!e||Boolean(t)}const R=Symbol.for("Contracted.contractName"),T=e=>{if("function"!=typeof e)return"";try{const t=Object.hasOwn(e,R)?e[R]:void 0;if("string"==typeof t&&t.length>0)return t}catch{}return e.name},C=Symbol.for("nodejs.util.inspect.custom"),A=new Set,W=e=>{switch(e.constructor.name){case"AsyncFunction":return"async";case"GeneratorFunction":return"generator";case"AsyncGeneratorFunction":return"async-generator";default:return"sync"}};function D(e,t){const n=t?.kind;b("string"==typeof n,`${e} was invoked without a standard decorator context, so it received no 'kind'. This happens when the compiler emits the pre-standard protocol, which \`experimentalDecorators\` selects. This library requires the TC39 protocol, so disable \`experimentalDecorators\` (and \`emitDecoratorMetadata\`), and make sure the build lowers decorator syntax rather than passing it through.`)}function _(e,t,n){D(e,n),b("method"===n.kind||"getter"===n.kind||"setter"===n.kind,`${e} decorator can only be applied to methods, getters, or setters`),b(!1===n.static,`${e} decorator cannot be applied to static features`),b(!1===n.private,`${e} decorator cannot be applied to private features`),b(!String(n.name).startsWith("_"),`${e} decorator cannot be applied to private/protected features`),n.addInitializer(function(){b(this instanceof Ce,`${e} decorator can only be applied to classes that extend Contracted`)})}function M(e,t,n,r){if(!r?.awaitPredicate)return;if("method"!==n.kind)throw new TypeError(`${e} cannot declare awaitPredicate on ${"getter"===n.kind?"a getter":"a setter"}: an accessor is read or assigned synchronously, so there is no promise a pending verdict could join.`);const o=W(t);if("async"!==o)throw new TypeError(`${e} cannot declare awaitPredicate on this feature: ${"generator"===o||"async-generator"===o?"a generator has one contract boundary per step, and awaiting a step would make every `next()` asynchronous rather than merely slower":"a synchronous feature has evaluated its contracts by the time the verdict could settle"}. The option is available on an \`async\` method only.`)}function N(e,t,n=ae(e)){if(!n)return;const r=e[Symbol.metadata]?.invariants??[];if(0===r.length)return;const a=()=>T(e),s=g();for(const[e,n]of r.entries()){const r=d(n.arm,{predicate:()=>({self:t}),schema:()=>t},"@invariant",a,e,n.options);r.ok||s.record(e,r)}if(void 0!==s.entries)throw x("@invariant",a(),void 0,r.map(e=>e.arm),s.entries,"The instance left the invariant unsatisfied.",o)}const I=(e,t)=>(n,r)=>{D("@invariant",r),((e,t)=>{if(t?.awaitPredicate)throw new TypeError("@invariant cannot declare awaitPredicate: an invariant is evaluated after construction and on every accessor read and write, where there is no promise a caller could await. Declare the option on the arm of an `async` feature instead.")})(0,t),((e,t)=>{if(t?.normalize)throw new TypeError("@invariant cannot normalize: its subject is the instance, which no arm can replace.")})(0,t),((e,t)=>{if(void 0!==t?.onViolation)throw new TypeError("@invariant cannot declare onViolation: its failure is what signals an unrecoverable instance, so it must stay an AssertionError. Translate it with a `@rescue` handler instead (which does not cover the check in `Contracted.new`).")})(0,t),u("@invariant",t);const{metadata:o}=r;b("class"===r.kind,"@invariant decorator can only be applied to classes"),b(n.prototype instanceof Ce,"@invariant decorator can only be applied to classes that extend Contracted");const a=o.invariants??[];o.invariants=[...a,{arm:e,options:t}]},V=Object.freeze([]),F=(e,t)=>(n,r)=>{_("@demands",0,r),M("@demands",n,r,t),s(e,"@demands",t),a(e,"@demands",t),i("@demands",t),((e,t)=>{const n=l.get(e);return!!n?.has(t)||(n?n.add(t):l.set(e,new Set([t])),!1)})(r.metadata,r.name)||((e,t,n,r)=>{if(0===n.length||r?.allowWeakening)return;const o=`@demands on ${t} adds an arm to a precondition that already has ${n.length} inherited arm(s). \`@demands\` is OR-composed, so this arm cannot narrow what the base permits: satisfying any inherited arm still allows the call. Move the restriction to the base feature, or declare the arm with \`allowWeakening\` if a genuine weakening is what was meant.`;console.warn(o)})(0,String(r.name),((e,t)=>{const n=Object.getPrototypeOf(e??{});return n?.demands?.[t]??[]})(r.metadata,r.name),t);const o=[...r.metadata?.demands?.[r.name]??[],{arm:e,options:t}];r.metadata.demands={...r.metadata?.demands??{},[r.name]:o}},q=(e,t)=>({predicate:()=>({self:e,args:t}),schema:()=>t});function B(e,t,n,r){throw x("@demands",t,String(n),e.map(e=>e.arm),r,"A precondition was not satisfied, so the feature was not entered.",o,c(e))}function K(e,t,n,r=ae(e.constructor)){if(!r)return n;const o=e.constructor,a=o[Symbol.metadata]?.demands?.[t]??V;if(0===a.length)return n;const s=()=>`${T(o)}.${String(t)}`,i=g();for(let t=0;t<a.length;t++){const{arm:r,options:o}=a[t],c=d(r,q(e,n),"@demands",s,t,o);if(c.ok)return void 0===c.value?n:c.value;i.record(t,c)}B(a,T(o),t,i.entries)}async function J(e,t,n,r=ae(e.constructor)){if(!r)return n;const o=e.constructor,a=o[Symbol.metadata]?.demands?.[t]??V;if(0===a.length)return n;const s=()=>`${T(o)}.${String(t)}`,i=g();for(let t=0;t<a.length;t++){const{arm:r,options:o}=a[t],c=await f(r,q(e,n),"@demands",s,t,o);if(c.ok)return void 0===c.value?n:c.value;i.record(t,c)}B(a,T(o),t,i.entries)}const G=Object.freeze([]),U=(e,t)=>(n,r)=>{_("@ensures",0,r),M("@ensures",n,r,t),s(e,"@ensures",t),a(e,"@ensures",t),i("@ensures",t),u("@ensures",t);const o=[...r.metadata?.ensures?.[r.name]??[],{arm:e,options:t}],c=o.filter(e=>e.options?.normalize);if(c.length>1)throw new TypeError(`@ensures for ${String(r.name)} declares ${c.length} normalizing arms; at most one arm may normalize the result, because they would disagree about what the caller receives.`);r.metadata.ensures={...r.metadata?.ensures??{},[r.name]:o}},H=(e,t,n,r,o)=>({predicate:()=>({self:e,args:t,old:n,oldArgs:r,result:o}),schema:()=>o});function L(e,t,n,r){throw x("@ensures",t,String(n),e.map(e=>e.arm),r,"A postcondition was not satisfied after the feature ran.",o,c(e))}const Q=(e,t,n,r)=>n.ok?void 0===n.value?r:n.value:(e.record(t,n),r);function X(e,t,n,r,o,a=[],s=ae(e.constructor)){if(!s)return o;const i=e.constructor,c=i[Symbol.metadata]?.ensures?.[n]??G;if(0===c.length)return o;const u=()=>`${T(i)}.${String(n)}`,l=g();let f=o;for(let n=0;n<c.length;n++){const s=c[n];f=Q(l,n,d(s.arm,H(e,r,t,a,o),"@ensures",u,n,s.options),f)}if(void 0===l.entries)return f;L(c,T(i),n,l.entries)}const Y=(e,t)=>(n,r)=>{if(D("@rescue",r),"class"===r.kind)return b(n.prototype instanceof Ce,"@rescue decorator can only be applied to classes that extend Contracted"),b(void 0===t?.maxRetries||t.maxRetries>=0,"maxRetries must not be negative"),void(r.metadata.classRescue={handler:e,maxRetries:t?.maxRetries});_("@rescue",0,r),b(void 0===t?.maxRetries||t.maxRetries>=0,"maxRetries must not be negative"),r.metadata.rescue={...r.metadata?.rescue??{},[r.name]:{handler:e,maxRetries:t?.maxRetries}},r.addInitializer(function(){b(this instanceof Ce,"@rescue decorator can only be applied to classes that extend Contracted")})},Z=(e,t)=>String(t).startsWith("_")?void 0:e?.rescue?.[t]??e?.classRescue;function ee(e,t){for(let n=e.constructor;n&&n!==Function.prototype;n=Object.getPrototypeOf(n)){const e=n[Symbol.metadata];if(!e)continue;const r=Z(e,t);if(r)return r}}const te=(e,t,n,r)=>{if(!ae(e.constructor))throw n;const o=ee(e,t);if(!o)throw n;let a=!1,s=[];if(o.handler.call(e,{self:e,error:n,args:r,retry:(...e)=>{b(!a,"retry can only be called once per rescue execution"),a=!0,s=e},feature:t}),!a)throw n;return s},ne=Symbol.for("Contracted.checkedMode"),re=Symbol.for("Contracted.encapsulationMode"),oe=(e,t)=>{for(let n=e;"function"==typeof n&&n!==Function.prototype;n=Object.getPrototypeOf(n))if(Object.hasOwn(n,t))return Boolean(n[t]);return!0},ae=e=>oe(e,ne),se=e=>oe(e,re),ie=(e,t)=>{if("object"!=typeof e||null===e)return e;const n=t.get(e);if(void 0!==n)return n;if(e instanceof Date)return new Date(e.getTime());const r=ce(e,t);if(void 0!==r)return r;if(!(e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t})(e))return e;const o=Object.create(Object.getPrototypeOf(e));return t.set(e,o),ue(e,o,t),o},ce=(e,t)=>{if(Array.isArray(e)){const n=[];t.set(e,n);for(const r of e)n.push(ie(r,t));return n}if(e instanceof Map){const n=new Map;t.set(e,n);for(const[r,o]of e)n.set(ie(r,t),ie(o,t));return n}if(e instanceof Set){const n=new Set;t.set(e,n);for(const r of e)n.add(ie(r,t));return n}},ue=(e,t,n)=>{for(const r of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,r),a="value"in o?{...o,value:ie(o.value,n)}:o;le(t,r,a)}},le=(e,t,n)=>{"value"in n&&n.writable&&n.enumerable&&n.configurable?e[t]=n.value:Reflect.defineProperty(e,t,n)},de=(e,t)=>{if(t)return(({target:e,entries:t})=>{const n=Object.create(e);for(const[e,r]of t)le(n,e,r);return n})(((e,t)=>{const n=[];for(const r of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,r);n.push([r,"value"in o?{...o,value:ie(o.value,t)}:o])}return{target:e,entries:n}})(e,new WeakMap))},fe=(e,t,n)=>e?((e,t)=>{const n=new WeakMap;return e.map((e,r)=>{try{return((e,t)=>{if("object"!=typeof e||null===e)return e;const n=t.get(e);if(void 0!==n)return n;if(!(e instanceof Ce))return ie(e,t);const r=Object.create(Object.getPrototypeOf(e));return t.set(e,r),ue(e,r,t),r})(e,n)}catch(e){throw new TypeError(`@ensures on '${String(t)}' cannot snapshot argument ${r}: a postcondition that describes an argument's pre-state needs every argument to be readable.`,{cause:e})}})})(t,n):void 0,he=new WeakMap;function pe(e,t){let n=e;for(;n&&n!==Object.prototype;){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Object.getPrototypeOf(n)}}const ye=(e,t,n)=>"get"===e?[t]:n,me=(e,t)=>"get"===e?[]:t,we=e=>"func"===e||"get"===e,ge=(t,n,r,o)=>{if((t=>t instanceof e&&"@invariant"===t.violation?.contract)(r))return r;try{N(t,n,o)}catch(t){return((t,n)=>(t instanceof e&&"object"==typeof n&&null!==n&&!Object.hasOwn(t,"cause")&&Object.defineProperty(t,"cause",{value:n,enumerable:!1,configurable:!0}),t))(t,r)}return r};function be(e,t,n,r,o,a,s){const i=ee(t,n);if(!i||o>=(i?.maxRetries??1/0))throw ge(e,t,r,s);try{return te(t,n,r,a)}catch(n){throw ge(e,t,n,s)}}function ve(e,t,n,r,o){for(let a=0;;)try{return void N(e,t,o)}catch(s){if(a++>0)throw s;r.args=be(e,t,n,s,r.retries,r.args,o),r.retries++}}function $e(e,t,n,r,o,a,s,i,c,u,l){if(!c)return N(e,n,l),a;const d=ye(t,a,o);if(!u){const t=X(n,s,r,d,a,i,l);return N(e,n,l),t}return async function(e,t,n,r){const o=await n;return N(e,t,r),o}(e,n,async function(e,t,n,r,o,a=[],s=ae(e.constructor)){if(!s)return o;const i=e.constructor,c=i[Symbol.metadata]?.ensures?.[n]??G;if(0===c.length)return o;const u=()=>`${T(i)}.${String(n)}`,l=g();let d=o;for(let n=0;n<c.length;n++){const s=c[n];d=Q(l,n,await f(s.arm,H(e,r,t,a,o),"@ensures",u,n,s.options),d)}if(void 0===l.entries)return d;L(c,T(i),n,l.entries)}(n,s,r,d,a,i,l),l)}function Oe(e,t,n,r,o,a,s="sync"){return"async"===s?async function(e,t,n,r,o,a){const s=t.constructor,i=s[Symbol.metadata]?.ensures?.[n]??[],c=i.length>0,u=function(e,t){const n=e.constructor;return(n[Symbol.metadata]?.demands?.[t]??V).some(e=>e.options?.awaitPredicate)}(t,n),l=function(e,t){const n=e.constructor;return(n[Symbol.metadata]?.ensures?.[t]??G).some(e=>e.options?.awaitPredicate)}(t,n);let d=r,f=0;for(;;){const r=Pe(i)?de(t,a):void 0,h={args:d,retries:f};ve(s,t,n,h,a),d=h.args,f=h.retries,d=u?await J(t,n,d,a):K(t,n,d,a);const p=fe(Pe(i),d,n);let y;try{y=await o(d);const i=$e(s,e,t,n,d,y,r,p,c,l,a);y=l?await i:i}catch(r){d=be(s,t,n,r,f,me(e,d),a),f++;continue}return y}}(e,t,n,r,o,a):"generator"===s||"async-generator"===s?function(e,t,n,r,o,a){const s=e.constructor,i=s[Symbol.metadata]?.ensures?.[t]??[],c=i.length>0;let u,l,d=n,f=0,h=!0;const p=n=>(N(s,e,a),h?(h=!1,K(e,t,d)):n.length>0?K(e,t,n):n),y=(n,r)=>{c&&X(e,r,t,[n],n,[],a),N(s,e,a),l=void 0},m=()=>{if(N(s,e,a),void 0===l)return;const t=l;throw l=void 0,t},w=n=>{d=be(s,e,t,n,f,d,a),f++,u=r(d),h=!0,l=n},g=(t,n)=>{for(;;)try{n=p(n);const r=Pe(i)?de(e,a):void 0,o=t(u,n);return o.done?(m(),o):(y(o.value,r),o)}catch(e){w(e)}},b=async(t,n)=>{for(;;)try{n=p(n);const r=Pe(i)?de(e,a):void 0,o=await t(u,n);return o.done?(m(),o):(y(o.value,r),o)}catch(e){w(e)}},v={args:d,retries:f};ve(s,e,t,v,a),d=v.args,f=v.retries,d=K(e,t,d),h=!1,u=r(d);const $={};return"generator"===o?($.next=function(...e){return g((e,t)=>e.next(t[0]),e)},$.return=function(...e){return g((t,n)=>t.return(e[0]??n[0]),[])},$.throw=function(...e){return g((t,n)=>t.throw(e[0]??n[0]),[])},$[Symbol.iterator]=function(){return this}):($.next=function(...e){return b((e,t)=>e.next(t[0]),e)},$.return=function(...e){return b((t,n)=>t.return(e[0]??n[0]),[])},$.throw=function(...e){return b((t,n)=>t.throw(e[0]??n[0]),[])},$[Symbol.asyncIterator]=function(){return this}),$}(t,n,r,o,s,a):function(e,t,n,r,o,a){const s=t.constructor,i=s[Symbol.metadata]?.ensures?.[n]??[],c=i.length>0;let u=r,l=0;for(;;){const r=Pe(i)?de(t,a):void 0,d={args:u,retries:l};ve(s,t,n,d,a),u=d.args,l=d.retries,u=K(t,n,u,a);const f=fe(Pe(i),u,n);let h;try{h=o(u),we(e)&&xe(h,t,n),c&&(h=X(t,r,n,ye(e,h,u),h,f,a)),N(s,t,a)}catch(r){u=be(s,t,n,r,l,me(e,u),a),l++;continue}return h}}(e,t,n,r,o,a)}const je=new WeakMap,Se=[],Pe=e=>{return e.length>0&&!((t=e).length>0&&t.every(e=>r(e.arm)));var t};function ke(e,t,n,r,o,a){const s=ae(t.constructor);return s?Oe(e,t,n,r,o,s,a):o(r)}const xe=(t,n,r)=>{if(null!==t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof t.then)throw new e(`${T(n.constructor)}.${String(r)} returned a promise but is not declared 'async', so its contracts were evaluated before its body finished. Declare the feature 'async'.`)},ze=(e,t,n,r)=>r?(r.call(e,n),!0):Reflect.set(e,t,n),Ee=e=>{if((e=>e===ne||e===re)(e))throw new TypeError(`Cannot set '${String(e)}' on a Contracted instance: enforcement is switched on the class, not on an instance. Assign '${String(e)}' on the class itself.`)},Re=(e,t,n,r)=>{if(r)return Reflect.get(e,t,n);const o=pe(Object.getPrototypeOf(e),t);return"function"==typeof o?.value?((e,t,n)=>he.get(e)?.get(t)??((e,t,n)=>{let r=he.get(e);return r||(r=new Map,he.set(e,r)),r.set(t,n),n})(e,t,function(e,t,n){const r=W(n);return function(...o){return ke("func",e,t,o,t=>Reflect.apply(n,e,t),r)}}(e,t,n)))(e,t,o.value):"function"==typeof o?.get?ke("get",e,t,Se,()=>o.get.call(e),(e=>{const t=je.get(e);if(void 0!==t)return t;const n=W(e);return je.set(e,n),n})(o.get)):Reflect.get(e,t,n)},Te={get:(e,t,n)=>Re(e,t,n,Object.getOwnPropertyDescriptor(e,t)),set(e,t,n){Ee(t);const r=se(e.constructor),o=pe(Object.getPrototypeOf(e),t),a="function"==typeof o?.set?o.set:void 0;if(r&&!a&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot assign to property '${String(t)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);if(!ae(e.constructor))return ze(e,t,n,a);let s=!0;return Oe("set",e,t,[n],n=>(s=ze(e,t,n[0],a),n[0]),!0),s},defineProperty(e,t,n){if(Ee(t),!se(e.constructor))return Reflect.defineProperty(e,t,n);if(("value"in n||"get"in n||"set"in n)&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot define property '${String(t)}' on Contracted instances: only properties starting with '_' can be defined. A feature body may change its own state, but an external caller must go through a method or a setter.`);return Reflect.defineProperty(e,t,n)},setPrototypeOf(e,t){if(!se(e.constructor))return Reflect.setPrototypeOf(e,t);throw new TypeError("Cannot change the prototype of a Contracted instance: it would detach the instance from the features and contracts it was constructed with.")},preventExtensions:e=>Reflect.preventExtensions(e),deleteProperty(e,t){if(Ee(t),se(e.constructor)&&"string"==typeof t&&!t.startsWith("_"))throw new TypeError(`Cannot delete property '${String(t)}' from Contracted instances: only properties starting with '_' can be deleted.`);return ke("delete",e,t,[],()=>Reflect.deleteProperty(e,t),"sync")}};class Ce{static[Symbol.metadata];static _allowedConstructions=0;static[ne]=!0;static[re]=!0;static new(...e){const t=this._allowedConstructions;this._allowedConstructions=t+1;try{const t=new this(...e);return N(this,t),new Proxy(t,Te)}finally{this._allowedConstructions=t}}constructor(...e){const t=this.constructor;if(t._allowedConstructions<=0)throw new TypeError("Use the static 'new' method to instantiate this class.");t._allowedConstructions--}}var Ae;Ae=Ce.prototype,Object.defineProperty(Ae,C,{value:function(e,t,n){const r=null===e?1/0:e;if(r<0)return"[Object]";if(A.has(this))return"[Circular]";A.add(this);try{const e=T(Object.getPrototypeOf(this)?.constructor),o=Object.entries(Object.getOwnPropertyDescriptors(this)).filter(([,e])=>"value"in e).map(([e,t])=>[e,t.value]).map(([e,o])=>`${e}: ${n(o,{...t,depth:r-1})}`);return 0===o.length?`${e} {}`:`${e} { ${o.join(", ")} }`}finally{A.delete(this)}},enumerable:!1,writable:!0,configurable:!0});const We=Object.freeze([]),De=Object.freeze({invariants:We,demands:Object.freeze({}),ensures:Object.freeze({}),rescue:Object.freeze({}),classRescue:void 0}),_e=e=>Object.freeze({...e,...e.options?{options:Object.freeze({...e.options})}:{}}),Me=e=>Object.freeze({...e}),Ne=e=>{if(!e)return Object.freeze({});const t={};for(const n of Reflect.ownKeys(e))t[n]=Me(e[n]);return Object.freeze(t)},Ie=e=>{if(!e)return Object.freeze({});const t={};for(const n of Reflect.ownKeys(e))t[n]=Object.freeze(e[n].map(_e));return Object.freeze(t)};function Ve(e){const t=e[Symbol.metadata];return t?Object.freeze({invariants:Object.freeze((t.invariants??[]).map(_e)),demands:Ie(t.demands),ensures:Ie(t.ensures),rescue:Ne(t.rescue),classRescue:t.classRescue&&Me(t.classRescue)}):De}function Fe(e,t){const n=Ve(e),r=Z(n,t);return Object.freeze({demands:n.demands[t]??We,ensures:n.ensures[t]??We,rescue:r&&Me(r)})}const qe="toJSON",Be=e=>T(e),Ke=new WeakSet,Je=(e,t)=>{for(let n=e;n&&n!==Object.prototype;n=Object.getPrototypeOf(n)){const e=Object.getOwnPropertyDescriptor(n,t);if(e)return e}},Ge=e=>function(){const t={},n=Object.getPrototypeOf(this);for(const r of e){const e=Je(n,r);e?.get&&(t[r]=e.get.call(this))}return t},Ue=(...e)=>(t,n)=>{if(D("@serializable",n),"class"!==n.kind)throw new TypeError("@serializable decorator can only be applied to classes");!function(e,t){if(null===e||"function"!=typeof e||!(e.prototype instanceof Ce))throw new TypeError("@serializable decorator can only be applied to classes that extend Contracted");if(0===t.length)throw new TypeError("@serializable was given no features, so it would publish an empty object for every instance. Name the getters to publish; a class that publishes nothing does not need the decorator.");if(Object.hasOwn(e.prototype,qe))throw new TypeError(Ke.has(e)?`${Be(e)} declares @serializable more than once, so two shapes were given for one class. Apply it once with the full list.`:`${Be(e)} already declares its own 'toJSON', so the shape it publishes is that method's and not the one @serializable was given. Remove one of the two.`)}(t,e);for(const n of e){const e=Je(t.prototype,n);if("function"!=typeof e?.get)throw new TypeError(`@serializable was given '${n}', which is not a getter on ${Be(t)}. Name the getters that describe the published shape; a field is storage rather than an observable.`)}Object.defineProperty(t.prototype,qe,{value:Ge(e),enumerable:!1,writable:!1,configurable:!1}),Ke.add(t)};export{e as AssertionError,Ce as Contracted,te as applyRescueHandler,b as assert,$ as assertContractResult,K as assertDemands,X as assertEnsures,N as assertInvariants,ne as checkedMode,R as contractName,ae as contractsEnabled,F as demands,O as describeViolation,re as encapsulationMode,U as ensures,Ve as getContractMetadata,Fe as getFeatureContracts,ee as getRescueDeclaration,z as iff,E as implies,I as invariant,Y as rescue,Ue as serializable,S as violationError,x as violationFailure};
2
2
  //# sourceMappingURL=index.mjs.map