@final-hill/decorator-contracts 1.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.
package/dist/assert.d.mts CHANGED
@@ -1,3 +1,6 @@
1
+ import { AssertionError, type ContractKind, type ContractViolation } from "./AssertionError.mjs";
2
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
3
+ import { type ArmFailures, type ViolationFactory } from './admissibility.mjs';
1
4
  /**
2
5
  * An assertion is an expression of a property that must be true at a particular
3
6
  * point of step of program execution. It consists of a boolean expression
@@ -18,3 +21,90 @@
18
21
  * ```
19
22
  */
20
23
  export declare function assert(condition: unknown, message?: string): asserts condition;
24
+ /**
25
+ * Asserts that a contract predicate returned a `boolean`.
26
+ *
27
+ * Contract predicates must return a boolean. Coercing the result would silently
28
+ * accept a non-boolean, which is how an accidentally asynchronous predicate
29
+ * passes: a `Promise` is always truthy. Treating a contract that never actually
30
+ * ran as satisfied is worse than failing, so a non-boolean result raises an
31
+ * `AssertionError` naming the contract, the feature, and the predicate index.
32
+ *
33
+ * @param result - The value returned by the predicate.
34
+ * @param contract - The name of the contract, e.g. `@demands`.
35
+ * @param label - Builds a human-readable description of the feature, e.g.
36
+ * `Foo.method`. A thunk so the name is resolved only for the message it appears
37
+ * in: a boolean verdict is the common case and never reads it.
38
+ * @param index - The zero-based index of the predicate in its composition list.
39
+ * @returns The predicate result, narrowed to `boolean`.
40
+ * @throws {AssertionError} If the predicate did not return a boolean.
41
+ */
42
+ export declare function assertContractResult(result: unknown, contract: string, label: () => string, index: number): boolean;
43
+ /**
44
+ * Builds a message for a failed contract and describes it structurally.
45
+ *
46
+ * Every contract reports the same way: which contract failed, on which feature,
47
+ * which arm(s) failed, and how each one is described. A caller can use the
48
+ * returned violation instead of parsing the message.
49
+ *
50
+ * @param contract - Which contract failed.
51
+ * @param className - The class the contract belongs to.
52
+ * @param feature - The feature the contract belongs to, absent for `@invariant`.
53
+ * @param arms - The full composition list, so indices are meaningful.
54
+ * @param failedIndices - The indices in `arms` that failed.
55
+ * @param summary - A per-contract description of what the failure means.
56
+ * @param issues - `issues` reported by failing schema arms, if any.
57
+ * @param describe - Renders one arm for the message.
58
+ * @returns The message and the structured violation.
59
+ */
60
+ export declare function describeViolation(contract: ContractKind, className: string, feature: string | undefined, arms: readonly unknown[], failedIndices: number[], summary: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, describe?: (arm: unknown) => string, thrown?: ReadonlyArray<{
61
+ index: number;
62
+ value: unknown;
63
+ }>): {
64
+ message: string;
65
+ violation: ContractViolation;
66
+ };
67
+ /**
68
+ * Builds the error for a contract whose arms were not satisfied.
69
+ *
70
+ * Every contract reports the same way — a message naming the feature and the
71
+ * arms that failed, plus the structured violation — so the identical
72
+ * `describeViolation` + `throw new AssertionError` tail is produced here instead
73
+ * of being written in each of `@invariant`, `@demands`, and `@ensures`.
74
+ *
75
+ * The composition rule stays with each contract, because it is not shared:
76
+ * `@demands` is OR-composed (a subtype may weaken a precondition) while
77
+ * `@invariant` and `@ensures` are AND-composed.
78
+ */
79
+ export declare function violationError(contract: ContractKind, className: string, feature: string | undefined, arms: readonly unknown[], failedIndices: number[], summary: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>, describe?: (arm: unknown) => string, thrown?: ReadonlyArray<{
80
+ index: number;
81
+ value: unknown;
82
+ }>): AssertionError;
83
+ /**
84
+ * Builds the value a contract raises when every arm has failed.
85
+ *
86
+ * A thrown arm is a failed arm, so when every arm failed and at least one of them
87
+ * threw, that value is what the caller receives. A typed error survives the
88
+ * composition it could not otherwise reach, and a predicate bug still surfaces as
89
+ * the bug it is rather than as an `AssertionError` describing a contract.
90
+ *
91
+ * The **first arm that threw** wins, matching the rule that the first arm
92
+ * evaluated decides a normalized value. Arm order is the composition list's, which
93
+ * for one class is reverse source order because decorators evaluate bottom-up, and
94
+ * which places inherited arms before a subclass's own.
95
+ *
96
+ * When no arm threw, the failure is a verdict rather than a fault and an
97
+ * `AssertionError` carrying the full violation is raised as usual.
98
+ *
99
+ * A declared {@link ViolationFactory} supersedes both rules, because it is the
100
+ * caller's explicit choice of error type and it receives the violation — including
101
+ * `thrownIndices` — so nothing is lost by preferring it. It runs only here, after
102
+ * every arm has been evaluated, which is the one point where the failure is final.
103
+ *
104
+ * @param factory - The contract's declared factory, if any arm declared one.
105
+ * @internal
106
+ * Exported only because the three contract modules live in their own files and
107
+ * import it. It takes an `ArmFailures`, which is not part of the published surface,
108
+ * so a consumer cannot call it without reaching into the library's internals.
109
+ */
110
+ export declare function violationFailure(contract: ContractKind, className: string, feature: string | undefined, arms: readonly unknown[], failures: ArmFailures, summary: string, describe?: (arm: unknown) => string, factory?: ViolationFactory): unknown;
@@ -0,0 +1,67 @@
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;
25
+ /**
26
+ * The gate every feature contract decorator shares.
27
+ *
28
+ * `@demands`, `@ensures`, and `@rescue` apply to exactly the same kind of member:
29
+ * an instance feature of a `Contracted` subclass, whose name is not `_`-prefixed.
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.
32
+ *
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.
64
+ */
65
+ export declare function assertAwaitableFeature(contract: string, element: unknown, context: {
66
+ kind: string;
67
+ }, options: ArmOptions | undefined): void;
@@ -1,6 +1,132 @@
1
1
  import { Contracted } from "./Contracted.mjs";
2
+ import { type ArmOptions } from './admissibility.mjs';
3
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
2
4
  import type { FeatureDecoratorContext } from './types.mjs';
3
- export type DemandsPredicate<This extends Contracted> = (self: This, ...args: any[]) => boolean;
4
- export type DemandsDecorator = <This extends Contracted, Feature = unknown>(predicate: DemandsPredicate<This>) => (value: Feature, context: FeatureDecoratorContext) => Feature | void;
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
+ }
29
+ /**
30
+ * A precondition predicate.
31
+ *
32
+ * `args` is the argument list of the invocation, matching `EnsuresPredicate`,
33
+ * so a predicate destructures it: `({ args: [x] }) => x > 0`.
34
+ *
35
+ * The type is generic over the argument tuple so the element types are inferred
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.
42
+ */
43
+ export type DemandsPredicate<This extends Contracted, Args extends any[] = any[]> = (subject: DemandsSubject<This, Args>) => boolean;
44
+ /**
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.
51
+ *
52
+ * A schema validates the **argument tuple**, which is the subject `@demands`
53
+ * already describes, so a method with two parameters is written as
54
+ * `z.tuple([A, B])`. Keeping one subject for both kinds of arm is what lets the
55
+ * composition rule below be the same for both.
56
+ *
57
+ * The schema's `Input` is left unpinned (`unknown`) rather than constrained to
58
+ * `any[]`, because every real provider declares a concrete input type and
59
+ * `StandardSchemaV1` is invariant in it: pinning it here would reject a
60
+ * `z.tuple([...])` whose input is `[number, number]`. The tuple shape is an
61
+ * obligation on the declaration, checked at runtime by the schema itself.
62
+ */
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
+ };
79
+ /** A registered precondition arm, with the options it was declared with. */
80
+ export interface RegisteredDemands {
81
+ arm: DemandsArm<Contracted>;
82
+ options?: ArmOptions;
83
+ }
5
84
  export declare const demands: DemandsDecorator;
6
- export declare function assertDemands(instance: Contracted, propertyKey: PropertyKey, ...args: any[]): void;
85
+ /**
86
+ * Evaluates the precondition for an invocation.
87
+ *
88
+ * The arms are OR-composed, which is the contravariance rule: a subtype may
89
+ * weaken a precondition, so satisfying any inherited arm is enough. A schema arm
90
+ * composes exactly like a predicate arm.
91
+ *
92
+ * When an arm asks for normalization, the value it produced replaces the
93
+ * arguments, and because OR-composition short-circuits, the **first passing arm**
94
+ * decides what that value is. That is deterministic and matches evaluation order.
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.
100
+ * @returns The arguments to use, which are the originals unless an arm
101
+ * normalized them.
102
+ */
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[]>;
@@ -1,6 +1,135 @@
1
1
  import { Contracted } from './Contracted.mjs';
2
+ import { type ArmOptions } from './admissibility.mjs';
3
+ import type { StandardSchemaV1 } from './standard-schema.mjs';
2
4
  import type { FeatureDecoratorContext } from './types.mjs';
3
- export type EnsuresPredicate<This extends Contracted> = (self: This, args: any[], old: This) => boolean;
4
- export type EnsuresDecorator = <This extends Contracted>(predicate: EnsuresPredicate<This>) => (value: unknown, context: FeatureDecoratorContext) => void;
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
+ }
52
+ /**
53
+ * A postcondition predicate.
54
+ *
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.
57
+ */
58
+ export type EnsuresPredicate<This extends Contracted, Args extends any[] = any[], Result = unknown> = (subject: EnsuresSubject<This, Args, Result>) => boolean;
59
+ /**
60
+ * A postcondition arm: a predicate, or a schema the feature's **result** must
61
+ * satisfy.
62
+ *
63
+ * A schema validates the result, which is the value the caller receives. This is
64
+ * the covariant position: a subtype may promise a narrower result, so the arms
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.
70
+ */
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
+ };
85
+ export interface RegisteredEnsures {
86
+ arm: EnsuresArm<Contracted>;
87
+ options?: ArmOptions;
88
+ }
5
89
  export declare const ensures: EnsuresDecorator;
6
- export declare function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any): void;
90
+ /**
91
+ * Evaluates the postcondition for an invocation.
92
+ *
93
+ * The arms are AND-composed, which is the covariance rule: a subtype may
94
+ * strengthen a postcondition, so every inherited arm has to keep holding.
95
+ *
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.
132
+ * @returns The result to hand the caller, which is the original unless an arm
133
+ * normalized it.
134
+ */
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
@@ -7,7 +7,17 @@
7
7
  *
8
8
  * @param p - The first boolean value (the antecedent).
9
9
  * @param q - The second boolean value (the consequent).
10
- * @returns - The result (biconditional) of p and q.
10
+ * @returns - The result (biconditional) of p and q, always a `boolean`.
11
+ *
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.
11
21
  *
12
22
  * @example
13
23
  * ```ts
@@ -7,7 +7,17 @@
7
7
  *
8
8
  * @param p - The first boolean value (the antecedent).
9
9
  * @param q - The second boolean value (the consequent).
10
- * @returns - The result (material implication) of p and q.
10
+ * @returns - The result (material implication) of p and q, always a `boolean`.
11
+ *
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.
11
21
  *
12
22
  * @example
13
23
  * ```ts
package/dist/index.d.mts CHANGED
@@ -1,10 +1,18 @@
1
1
  export * from './types.mjs';
2
+ export * from './standard-schema.mjs';
2
3
  export * from "./AssertionError.mjs";
3
4
  export * from "./assert.mjs";
4
5
  export * from './iff.mjs';
5
6
  export * from './implies.mjs';
6
7
  export * from './Contracted.mjs';
7
8
  export * from './invariant.mjs';
8
- export * from './demands.mjs';
9
- export * from './ensures.mjs';
10
- 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{}function e(e,r="Assertion Error"){if(0==Boolean(e))throw new t(r)}function r(t,e){return t&&e||!t&&!e}function n(t,e){return!t||e}function a(t,r){if(!h[u])return;h[u]=!1;const n=t[Symbol.metadata]?.invariants??[];try{for(const a of n)e(a(r),`Invariant violated in class ${t.name}: ${a.toString()}`)}finally{h[u]=!0}}const o=t=>(r,{kind:n,metadata:a})=>{e("class"===n,"@invariant decorator can only be applied to classes"),e(r.prototype instanceof h,"@invariant decorator can only be applied to classes that extend Contracted");const o=a.invariants??[];a.invariants=[...o,t]},s=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@demands decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@demands decorator cannot be applied to static features"),e(!1===n.private,"@demands decorator cannot be applied to private/protected features"),e(!String(n.name).startsWith("_"),"@demands decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@demands decorator can only be applied to classes that extend Contracted");const r=[...n.metadata?.demands?.[n.name]??[],t];n.metadata.demands={...n.metadata?.demands??{},[n.name]:r}}))};function c(t,r,...n){if(!h[u])return;h[u]=!1;const a=t.constructor,o=a[Symbol.metadata]?.demands?.[r]??[];try{if(0===o.length)return;for(const e of o)if(e(t,...n))return;e(!1,`No demands were satisfied for ${t.constructor.name}.${String(r)}`)}finally{h[u]=!0}}const i=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@ensures decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@ensures decorator cannot be applied to static features"),e(!1===n.private,"@ensures decorator cannot be applied to private features"),e(!String(n.name).startsWith("_"),"@ensures decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@ensures decorator can only be applied to classes that extend Contracted");const r=[...n.metadata?.ensures?.[n.name]??[],t];n.metadata.ensures={...n.metadata?.ensures??{},[n.name]:r}}))};function d(t,r,n,a){if(!h[u])return;h[u]=!1;const o=t.constructor,s=o[Symbol.metadata]?.ensures?.[n]??[];try{if(0===s.length)return;for(const o of s)o(t,a,r)||e(!1,`No ensurances were satisfied for ${t.constructor.name}.${String(n)}`)}finally{h[u]=!0}}const l=t=>(r,n)=>{e(["method","getter","setter"].includes(n.kind),"@rescue decorator can only be applied to methods, getters, or setters"),e(!1===n.static,"@rescue decorator cannot be applied to static features"),e(!1===n.private,"@rescue decorator cannot be applied to private features"),e(!String(n.name).startsWith("_"),"@rescue decorator cannot be applied to private/protected features"),n.addInitializer((function(){e(this instanceof h,"@rescue decorator can only be applied to classes that extend Contracted"),n.metadata.rescue={...n.metadata?.rescue??{},[n.name]:t}}))},f=(t,r,n,a,o)=>{if(!h[u])return a;const s=r.constructor,c=Object.getOwnPropertyDescriptor(s.prototype,n),i=s[Symbol.metadata]?.rescue?.[n];if(!i)throw a;let d,l=!1;h[u]=!1;try{if(i.call(r,r,a,o,((...a)=>{e(!l,"retry can only be called once"),l=!0,h[u]=!0,"get"==t?d=Reflect.get(r,n,r):"set"==t?d=Reflect.set(r,n,a[0],r):"func"==t&&(d=Reflect.apply(c.value,r,a))})),!l)throw a}finally{h[u]=!0}return d},u=Symbol.for("Contracted.checkedMode"),p=t=>{if(!h[u])return;h[u]=!1;const e=Object.create(t);for(const r in t)Reflect.set(e,r,Reflect.get(t,r));return h[u]=!0,e};function y(t,e){let r=t;for(;r&&r!==Object.prototype;){const t=Object.getOwnPropertyDescriptor(r,e);if(t)return t;r=Object.getPrototypeOf(r)}}const m={get(t,e,r){if(!h[u])return Reflect.get(t,e,r);const n=t.constructor,o=y(Object.getPrototypeOf(t),e),s=(n[Symbol.metadata]?.ensures?.[e]??[]).length>0,i=s?p(t):void 0;if("function"==typeof o?.value)return function(...r){let l;a(n,t),c(t,e,r);try{l=Reflect.apply(o.value,t,r),s&&d(t,i,e,r)}catch(n){l=f("func",t,e,n,r)}finally{a(n,t)}return l};if("function"==typeof o?.get){let o;a(n,t),c(t,e,[]);try{o=Reflect.get(t,e,r),s&&d(t,i,e,[o])}catch(r){o=f("get",t,e,r,[])}finally{a(n,t)}return o}return Reflect.get(t,e,r)},set(t,e,r,n){if(!h[u])return Reflect.set(t,e,r,n);const o=y(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 s=t.constructor,i=(s[Symbol.metadata]?.ensures?.[e]??[]).length>0,l=i?p(t):void 0;let m;a(s,t),c(t,e,[r]);try{m=Reflect.set(t,e,r,n),i&&d(t,l,e,[r])}catch(n){m=f("set",t,e,n,[r])}finally{a(s,t)}return m},deleteProperty(t,e){throw new TypeError(`Cannot delete property '${String(e)}' from Contracted instances.`)}};class h{static[Symbol.metadata];static _allowConstruction=!1;static[u]=!0;static new(...t){this._allowConstruction=!0;try{const e=new this(...t);return a(this,e),new Proxy(e,m)}finally{this._allowConstruction=!1}}constructor(...t){if(!this.constructor._allowConstruction)throw new TypeError("Use the static 'new' method to instantiate this class.")}}export{t as AssertionError,h as Contracted,f as applyRescueHandler,e as assert,c as assertDemands,d as assertEnsures,a as assertInvariants,u as checkedMode,s as demands,i as ensures,r as iff,n as implies,o as invariant,l as rescue};
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