@final-hill/decorator-contracts 2.0.0 → 3.1.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 +1 @@
1
- {"version":3,"file":"index.mjs","mappings":"AAGCA,OAAeC,WAAaD,OAAOE,IAAI,mBC0CjC,MAAMC,UAAuBC,MAOvBC,KAAO,iBAGPC,UAET,WAAAC,CAAYC,EAAkBF,GAC1BG,MAAMD,GACNE,KAAKJ,UAAYA,CACrB,ECvBJ,MAAMK,EAAgB,IAAIC,QCYbC,EAAYC,GACN,iBAARA,GAA4B,OAARA,GAAgB,cAAeA,EAQjDC,EAAeD,IACxB,GAAID,EAASC,GAAM,CACf,MAAM,OAAEE,EAAM,QAAEC,GAAYH,EAAI,aAEhC,MAAO,4BAA4BI,OAAOF,gBAAqBE,OAAOD,KAC1E,CAEA,OAAOC,OAAOJ,IAULK,EAAqB,CAACL,EAAcM,EAAkBC,KAC/D,GAAKA,GAASC,YAAaT,EAASC,GAEpC,MAAM,IAAIS,UAAU,GAAGH,iFAadI,EAAc,CACvBV,EACAW,EACAL,EACAM,EACAC,EACAN,IACgBR,EAASC,GACvBc,EAAed,EAAKW,EAASI,SAAUT,EAAUM,EAAOC,EAAON,GAC/DS,EACEhB,EACAW,EAASM,YACTX,EACAM,EACAC,GAeFG,EAAoB,CACtBC,EACAC,EACAZ,EACAM,EACAC,KAMA,MAAOM,KAAaC,GAAQF,EAK5B,MAAO,CAAEG,GAAIC,EAAqBL,EAJA,iBAAbE,GAAsC,OAAbA,EDrFtB,CAAmBI,IAC3C,MAAMC,EAAS3B,EAAc4B,IAAIF,GAEjC,GAAIC,EAAQ,OAAOA,EAEnB,MAAME,EAAO,IAAIC,MAAMJ,EAAQ,CAC3B,GAAAK,CAAIC,EAASC,GACT,MAAM,IAAIrB,UACN,wCAAwCL,OAAO0B,mGAGvD,EACA,cAAAC,CAAeF,EAASC,GACpB,MAAM,IAAIrB,UACN,wCAAwCL,OAA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IAAsBA,EAAKpD,WAAW,KAC7C,MAAM,IAAI3F,UAAU,2BAA2BL,OAAOoJ,oFAE1D,OAAOS,EAAa,SAAU1I,EAAQiI,EAAM,GAAI,IAAMV,QAAQ/G,eAAeR,EAAQiI,GACzF,GAGG,MAAMrE,EACTe,OAAQhH,OAAOC,UAmBL+G,6BAA+B,EAGlCA,OAAQd,IAAwB,EAEvC,UAAO,IAGOlE,GACV,MAAMkL,EAAYxM,KAAayM,sBAE9BzM,KAAayM,sBAAwBD,EAAW,EAEjD,IACI,MAAMjL,EAAW,IAAIvB,QAAQsB,GAG7B,OAFA+D,EAAiBrF,KAAMuB,GAEhB,IAAIQ,MAAuBR,EAAU2K,EAChD,C,QAIKlM,KAAayM,sBAAwBD,CAC1C,CACJ,CAEA,WAAA3M,IAAe6M,GACX,MAAMpH,EAAQtF,KAAKH,YAEnB,GAAIyF,EAAMmH,uBAAyB,EAC/B,MAAM,IAAI5L,UAAU,0DAIxByE,EAAMmH,uBACV,S","sources":["webpack://@final-hill/decorator-contracts/./src/types.mts","webpack://@final-hill/decorator-contracts/./src/AssertionError.mts","webpack://@final-hill/decorator-contracts/./src/read-only.mts","webpack://@final-hill/decorator-contracts/./src/admissibility.mts","webpack://@final-hill/decorator-contracts/./src/assert.mts","webpack://@final-hill/decorator-contracts/./src/iff.mts","webpack://@final-hill/decorator-contracts/./src/implies.mts","webpack://@final-hill/decorator-contracts/./src/invariant.mts","webpack://@final-hill/decorator-contracts/./src/decorator.mts","webpack://@final-hill/decorator-contracts/./src/demands.mts","webpack://@final-hill/decorator-contracts/./src/ensures.mts","webpack://@final-hill/decorator-contracts/./src/rescue.mts","webpack://@final-hill/decorator-contracts/./src/Contracted.mts"],"sourcesContent":["// Polyfill Symbol.metadata if not present\n// ref: https://github.com/microsoft/TypeScript/issues/53461#issuecomment-1736996954\n// ref: https://github.com/tc39/proposal-decorator-metadata\n(Symbol as any).metadata ??= Symbol.for(\"Symbol.metadata\");\n\n// Extend the global SymbolConstructor type to include metadata\ndeclare global {\n interface SymbolConstructor {\n readonly metadata: symbol;\n }\n}\n\nexport type Constructor<T> = new (...args: any[]) => T\n\nexport type FeatureDecoratorContext = Exclude<ClassMemberDecoratorContext, ClassAccessorDecoratorContext>;","import type { StandardSchemaV1 } from './standard-schema.mjs';\n\n/**\n * The contract kinds that can raise an {@link AssertionError}.\n */\nexport type ContractKind = '@invariant' | '@demands' | '@ensures';\n\n/**\n * Structured description of a failed contract.\n *\n * Attached to {@link AssertionError} so that callers — including integration\n * layers such as a schema adapter — can react to a specific violation without\n * parsing the message.\n */\nexport interface ContractViolation {\n /** Which contract failed. */\n contract: ContractKind;\n /** The class the contract belongs to. */\n className: string;\n /** The feature the contract belongs to, absent for `@invariant`. */\n feature?: string;\n /**\n * The indices, within the contract's composition list, that failed.\n *\n * `@demands` is OR-composed, so a failure lists every arm; `@ensures` and\n * `@invariant` are AND-composed, so a failure lists the one that broke.\n */\n failedIndices: number[];\n /** The source text of the failing arms, aligned with `failedIndices`. */\n predicates: string[];\n /**\n * The `issues` reported by failing schema arms, in the order they were\n * raised. Absent when the failure came only from predicate arms, so a caller\n * can distinguish \"a schema rejected this\" from \"a predicate returned\n * false\".\n */\n issues?: ReadonlyArray<StandardSchemaV1.Issue>;\n}\n\n/**\n * An `AssertionError` represents a failed assertion with an associated message.\n *\n * When the failure came from a contract, {@link AssertionError.violation}\n * describes it structurally.\n */\nexport class AssertionError extends Error {\n /**\n * Set explicitly rather than relying on the class name.\n *\n * Bundlers rename classes, so the published build would otherwise expose a\n * mangled name such as `t` to consumers.\n */\n override name = 'AssertionError';\n\n /** Structured description of the failure, when it came from a contract. */\n readonly violation?: ContractViolation;\n\n constructor(message?: string, violation?: ContractViolation) {\n super(message);\n this.violation = violation;\n }\n}\n","/**\n * Read-only views of an instance, handed to contract predicates.\n *\n * https://github.com/final-hill/decorator-contracts/issues/191\n *\n * A predicate answers a question; it must not change the state it is asked about.\n * Side effects in a predicate are corrupting rather than merely impure: the\n * predicate runs between the entry and exit `@invariant`, so a write there can\n * hide a violation the invariant would otherwise have reported.\n *\n * `rescue` is deliberately excluded. Restoring corrupted state is its purpose, so\n * it receives the raw target.\n *\n * ### Why a proxy rather than `Object.freeze`\n *\n * Freezing is permanent. A predicate that froze the instance would leave the\n * feature body unable to change it, so every feature on that instance would break:\n *\n * ```text\n * deposit FAILED: TypeError - Cannot assign to read only property '_balance'\n * ```\n *\n * A proxy is scoped to the predicate call, so the body still receives the raw\n * target and mutates normally.\n *\n * ### What is and is not blocked\n *\n * Assignment, deletion, and `defineProperty` on the instance are refused. A\n * mutation *through* a nested value (`self._items.push(x)`) still reaches the\n * shared object, because the proxy only intercepts the instance's own surface.\n * Closing that would require deep-wrapping every value returned from a read,\n * which changes identity for legitimate comparisons such as\n * `old.child === self.child`. The guarantee is therefore \"a predicate cannot\n * assign to the instance\", which is the case that actually corrupts contract\n * evaluation.\n */\n\nconst readOnlyViews = new WeakMap<object, object>();\n\n/**\n * Returns a cached read-only view of `target`.\n *\n * Cached because the same instance is evaluated by several contracts within one\n * lifecycle, and creating a fresh proxy each time would make `self` a different\n * object for each predicate — enough to break a predicate that compares `self`\n * across two contracts.\n */\nexport const readOnlyView = <T extends object>(target: T): T => {\n const cached = readOnlyViews.get(target);\n\n if (cached) return cached as T;\n\n const view = new Proxy(target, {\n set(_target, property) {\n throw new TypeError(\n `A contract predicate may not assign '${String(property)}'. `\n + 'Contract predicates answer a question; they must not change the state they are asked about.',\n );\n },\n deleteProperty(_target, property) {\n throw new TypeError(\n `A contract predicate may not delete '${String(property)}'. `\n + 'Contract predicates answer a question; they must not change the state they are asked about.',\n );\n },\n defineProperty() {\n throw new TypeError(\n 'A contract predicate may not define properties. '\n + 'Contract predicates answer a question; they must not change the state they are asked about.',\n );\n },\n });\n\n readOnlyViews.set(target, view);\n\n return view;\n}\n","import { assertContractResult } from './assert.mjs';\nimport { readOnlyView } from './read-only.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\n\n/**\n * The result of checking a subject against one contract arm.\n *\n * Predicates and schemas are adapted to this shape so that the composition rule\n * in each contract — OR for `@demands`, AND for `@invariant` and `@ensures` — is\n * written once rather than twice.\n */\nexport type Admissibility = { ok: boolean; value?: unknown; issues?: ReadonlyArray<StandardSchemaV1.Issue> };\n\n/** Options a decorator accepts alongside an arm. */\nexport interface ArmOptions {\n /**\n * Replace the subject with the schema's `Output`.\n *\n * Off by default. `validate` may transform what it returns, and applying that\n * transformation changes what the feature body receives and what later\n * contracts observe, so it is an explicit choice rather than a side effect of\n * validation. Only a schema can normalize.\n */\n normalize?: boolean;\n}\n\n/**\n * The two subjects a contract arm can observe.\n *\n * A predicate and a schema look at different things even within one contract: an\n * `@ensures` predicate needs the invocation and the historical instance, while a\n * schema in the same position validates the result. Passing both explicitly keeps\n * that difference visible at each call site instead of hiding it behind a\n * convention.\n */\nexport interface ArmSubjects {\n /** The arguments a predicate is called with. */\n predicate: () => any[];\n /** The value a schema arm validates. */\n schema: () => unknown;\n}\n\n/**\n * True when a value is a `StandardSchemaV1` rather than a predicate.\n *\n * The check is structural: any object exposing a `~standard` property is treated\n * as a schema, which is what makes the protocol provider-agnostic. A predicate is\n * callable and has no such property.\n */\nexport const isSchema = (arm: unknown): arm is StandardSchemaV1 =>\n typeof arm === 'object' && arm !== null && '~standard' in arm;\n\n/**\n * Describes an arm for a failure message.\n *\n * Schemas are identified by vendor because their `String()` form is opaque and\n * the caller needs to know which provider produced the arm.\n */\nexport const describeArm = (arm: unknown): string => {\n if (isSchema(arm)) {\n const { vendor, version } = arm['~standard'];\n\n return `Standard Schema (vendor: ${String(vendor)}, version: ${String(version)})`;\n }\n\n return String(arm);\n}\n\n/**\n * Rejects `normalize` on an arm that cannot honour it.\n *\n * Called at decoration time so an impossible declaration fails where it is\n * written rather than on the first invocation. A predicate reports a verdict, not\n * a replacement value.\n */\nexport const assertNormalizable = (arm: unknown, contract: string, options: ArmOptions | undefined): void => {\n if (!options?.normalize || isSchema(arm)) return;\n\n throw new TypeError(`${contract} cannot normalize: only a Standard Schema arm produces a replacement value.`);\n}\n\n/**\n * Checks one arm against the subject that belongs to it.\n *\n * @param arm - A predicate or a `StandardSchemaV1` value.\n * @param subjects - What the arm observes, chosen by the calling contract.\n * @param contract - The contract name, for the diagnostic.\n * @param label - The feature, for the diagnostic.\n * @param index - The arm's position in its composition list.\n * @param options - Declaration options for this arm.\n */\nexport const evaluateArm = (\n arm: unknown,\n subjects: ArmSubjects,\n contract: string,\n label: string,\n index: number,\n options?: ArmOptions,\n): Admissibility => isSchema(arm)\n ? evaluateSchema(arm, subjects.schema(), contract, label, index, options)\n : evaluatePredicate(\n arm as (...args: any[]) => unknown,\n subjects.predicate(),\n contract,\n label,\n index,\n );\n\n/**\n * Applies a predicate arm, reusing the strict-boolean rule from #283.\n *\n * Reusing `assertContractResult` keeps the diagnostic identical whether the\n * predicate was declared on its own or alongside a schema.\n *\n * The instance is passed as a read-only view. A predicate answers a question, so\n * it must not be able to change the state it is asked about — see `read-only.mts`\n * for why this is a scoped proxy rather than `Object.freeze`. The view is applied\n * here rather than by the caller so that a predicate can never be invoked with\n * the raw target by mistake.\n */\nconst evaluatePredicate = (\n predicate: (...args: any[]) => unknown,\n args: any[],\n contract: string,\n label: string,\n index: number,\n): Admissibility => {\n // Only the instance is guarded, and it is always the first argument:\n // `(self)`, `(self, args)`, or `(self, args, old)`. The argument tuple and the\n // `old` snapshot are data the predicate is expected to inspect and mutate\n // freely — `old` is a detached copy, so writing to it corrupts nothing.\n const [instance, ...rest] = args,\n guarded = typeof instance === 'object' && instance !== null\n ? readOnlyView(instance)\n : instance;\n\n return { ok: assertContractResult(predicate(guarded, ...rest), contract, label, index) };\n};\n\n/**\n * Applies a schema arm by calling its `validate`.\n *\n * A `validate` that returns a Promise is refused. Contract evaluation is\n * synchronous, so an asynchronous schema has decided nothing at the point where\n * the verdict is needed; treating it as satisfied would be worse than failing,\n * and awaiting would move the feature's boundary.\n */\nconst evaluateSchema = (\n schema: StandardSchemaV1,\n subject: unknown,\n contract: string,\n label: string,\n index: number,\n options: ArmOptions | undefined,\n): Admissibility => {\n const result = schema['~standard'].validate(subject) as any;\n\n if (typeof result?.then === 'function')\n throw new TypeError(\n `${contract} schema #${index + 1} for ${label} returned a Promise; `\n + 'contract evaluation is synchronous, so use a synchronous schema.',\n );\n\n if (result.issues)\n return { ok: false, issues: result.issues as ReadonlyArray<StandardSchemaV1.Issue> };\n\n return options?.normalize ? { ok: true, value: result.value } : { ok: true };\n}\n\n/**\n * Renders schema `issues` for a message.\n *\n * A path is reported as a dotted trail of keys, matching how the providers\n * describe a nested failure themselves.\n */\nexport const describeIssues = (issues: ReadonlyArray<StandardSchemaV1.Issue>): string =>\n issues\n .map(issue => {\n const path = (issue.path ?? [])\n .map(segment => typeof segment === 'object' && segment !== null ? segment.key : segment)\n .join('.');\n\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join('; ');\n","import { AssertionError, type ContractKind, type ContractViolation } from \"./AssertionError.mjs\";\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\nimport { isSchema } from './admissibility.mjs';\n\n/**\n * An assertion is an expression of a property that must be true at a particular\n * point of step of program execution. It consists of a boolean expression\n * and a message. This function tests the provided condition. If the condition\n * is false an AssertionError is raised with an optional message.\n * If the provided condition is true then the function returns without raising an error\n *\n * @param condition - The condition to test. If it is false an error is raised.\n * @param message - The message to display if the condition is false. If not provided a default message is used.\n * @throws {AssertionError} If the condition is false an AssertionError is raised.\n *\n * @example\n * ```ts\n * import assert from \"assert.mjs\";\n *\n * let x = 15;\n * assert(x > 5, `Expected: x > 5. Actual: x = ${x}`);\n * ```\n */\n\nexport function assert(condition: unknown, message: string = 'Assertion Error'): asserts condition {\n if (Boolean(condition) == false)\n throw new AssertionError(message);\n}\n\nconst describeContractResult = (value: unknown): string => {\n if (typeof value === 'object' && value !== null && typeof (value as any).then === 'function')\n return 'a Promise (contract predicates must be synchronous)';\n if (typeof value === 'string') return `the string ${JSON.stringify(value)}`;\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n if (typeof value === 'object') return `an object (${Object.prototype.toString.call(value)})`;\n\n return `a ${typeof value} (${String(value)})`;\n}\n\n/**\n * Asserts that a contract predicate returned a `boolean`.\n *\n * Contract predicates must return a boolean. Coercing the result would silently\n * accept a non-boolean, which is how an accidentally asynchronous predicate\n * passes: a `Promise` is always truthy. Treating a contract that never actually\n * ran as satisfied is worse than failing, so a non-boolean result raises an\n * `AssertionError` naming the contract, the feature, and the predicate index.\n *\n * @param result - The value returned by the predicate.\n * @param contract - The name of the contract, e.g. `@demands`.\n * @param label - A human-readable description of the feature, e.g. `Foo.method`.\n * @param index - The zero-based index of the predicate in its composition list.\n * @returns The predicate result, narrowed to `boolean`.\n * @throws {AssertionError} If the predicate did not return a boolean.\n */\nexport function assertContractResult(\n result: unknown,\n contract: string,\n label: string,\n index: number,\n): boolean {\n assert(\n typeof result === 'boolean',\n `${contract} predicate #${index + 1} for ${label} returned ${describeContractResult(result)}; contract predicates must return a boolean`\n );\n\n return result;\n}\n\nconst pluralise = (count: number, total: number, singular: string, plural: string): string =>\n `${count} of ${total} ${total === 1 ? singular : plural}`;\n\n/**\n * Renders one schema issue, including its path when the provider supplied one.\n *\n * A path is shown as a dotted trail of keys, which is how the providers describe\n * a nested failure themselves.\n */\nconst describeIssue = (issue: StandardSchemaV1.Issue): string => {\n const path = (issue.path ?? [])\n .map(segment => typeof segment === 'object' && segment !== null ? segment.key : segment)\n .join('.');\n\n return path ? `${path}: ${issue.message}` : issue.message;\n}\n\n/**\n * Builds a message for a failed contract and describes it structurally.\n *\n * Every contract reports the same way: which contract failed, on which feature,\n * which arm(s) failed, and how each one is described. A caller can use the\n * returned violation instead of parsing the message.\n *\n * @param contract - Which contract failed.\n * @param className - The class the contract belongs to.\n * @param feature - The feature the contract belongs to, absent for `@invariant`.\n * @param arms - The full composition list, so indices are meaningful.\n * @param failedIndices - The indices in `arms` that failed.\n * @param summary - A per-contract description of what the failure means.\n * @param issues - `issues` reported by failing schema arms, if any.\n * @param describe - Renders one arm for the message.\n * @returns The message and the structured violation.\n */\nexport function describeViolation(\n contract: ContractKind,\n className: string,\n feature: string | undefined,\n arms: readonly unknown[],\n failedIndices: number[],\n summary: string,\n issues?: ReadonlyArray<StandardSchemaV1.Issue>,\n describe: (arm: unknown) => string = String,\n): { message: string, violation: ContractViolation } {\n const violation: ContractViolation = {\n contract,\n className,\n feature,\n failedIndices,\n predicates: failedIndices.map(index => describe(arms[index])),\n ...(issues && issues.length > 0 ? { issues } : {}),\n };\n\n const where = feature === undefined ? className : `${className}.${feature}`,\n // Predicates and schemas are both arms of the same composition, so the\n // message names whichever the failing one actually is. Calling a schema a\n // predicate would be wrong; calling a predicate an arm would be vaguer\n // than the caller needs.\n noun = (arm: unknown) => isSchema(arm) ? 'schema' : 'predicate',\n nounPlural = (arm: unknown) => isSchema(arm) ? 'schemas' : 'predicates',\n detail = violation.predicates\n .map((source, position) => {\n const arm = arms[failedIndices[position]];\n\n return `${noun(arm)} #${failedIndices[position] + 1}: ${source}`;\n })\n .join('; '),\n count = pluralise(failedIndices.length, arms.length, noun(arms[0]), nounPlural(arms[0]));\n\n // Schema arms report `issues` rather than a true/false verdict, so the\n // provider's own explanation is carried into the message. A caller reading\n // only the message still learns which field was rejected and why.\n const reported = issues && issues.length > 0\n ? ` Reported: ${issues.map(issue => describeIssue(issue)).join('; ')}.`\n : '';\n\n return {\n message: `${contract} failed for ${where} (${count} unsatisfied: ${detail}).${reported} ${summary}`,\n violation,\n };\n}\n\n/**\n * Builds the error for a contract whose arms were not satisfied.\n *\n * Every contract reports the same way — a message naming the feature and the\n * arms that failed, plus the structured violation — so the identical\n * `describeViolation` + `throw new AssertionError` tail is produced here instead\n * of being written in each of `@invariant`, `@demands`, and `@ensures`.\n *\n * The composition rule stays with each contract, because it is not shared:\n * `@demands` is OR-composed (a subtype may weaken a precondition) while\n * `@invariant` and `@ensures` are AND-composed.\n */\nexport function violationError(\n contract: ContractKind,\n className: string,\n feature: string | undefined,\n arms: readonly unknown[],\n failedIndices: number[],\n summary: string,\n issues?: ReadonlyArray<StandardSchemaV1.Issue>,\n describe: (arm: unknown) => string = String,\n): AssertionError {\n const { message, violation } = describeViolation(\n contract, className, feature, arms, failedIndices, summary, issues, describe);\n\n return new AssertionError(message, violation);\n}\n","/**\n * Biconditional.\n * p ↔ q.\n * \"P if and only if Q\".\n * An example of usage is the encoding of \"You can ride the train if and only if you have a ticket\"\n * This is logically equivalent to: implies(p,q) && implies(q,p)\n *\n * @param p - The first boolean value (the antecedent).\n * @param q - The second boolean value (the consequent).\n * @returns - The result (biconditional) of p and q, always a `boolean`.\n *\n * A non-boolean operand is coerced rather than rejected, because this is a\n * general-purpose logical helper. Inside a contract the coercion is redundant:\n * `@demands` and the other contracts already require a literal `true` or `false`\n * and will report a non-boolean result by name.\n *\n * @example\n * ```ts\n * import { iff } from '@final-hill/decorator-contracts';\n *\n * // You can ride the train if and only if you have a ticket\n * iff(person.hasTicket, person.ridesTrain)\n * ```\n */\n\nexport function iff(p: boolean, q: boolean): boolean {\n // Coerced rather than returned directly. `(p && q) || (!p && !q)` is\n // logically correct but returns an *operand* rather than a boolean, so a\n // truthy non-boolean operand (`iff(true, someObject)`) would leak through a\n // signature that promises `boolean`. The leak only appears when the\n // non-boolean sits on the returned side of the short-circuit, which is why it\n // is easy to miss in testing.\n return Boolean((p && q) || (!p && !q));\n}\n","/**\n * Material Implication.\n * `p → q`\n * Also referred to as `if-then`.\n * An example of usage is the encoding of \"sunny weather is a precondition of visiting the beach\"\n * This is logically equivalent to: !p || q\n *\n * @param p - The first boolean value (the antecedent).\n * @param q - The second boolean value (the consequent).\n * @returns - The result (material implication) of p and q, always a `boolean`.\n *\n * A non-boolean consequent is coerced rather than rejected, for the same reason\n * as {@link iff}.\n *\n * @example\n * ```ts\n * import { implies } from '@final-hill/decorator-contracts';\n *\n * // Sunny weather is a precondition of visiting the beach\n * implies(weather.isSunny, person.visitsBeach)\n * ```\n */\n\nexport function implies(p: boolean, q: boolean): boolean {\n // Coerced for the same reason as `iff`: `!p || q` returns the operand `q`\n // when `p` is falsy, so a truthy non-boolean would escape a `boolean` return.\n return !p || Boolean(q);\n}\n","import { assert, violationError } from './assert.mjs';\nimport { checkedMode, Contracted } from './Contracted.mjs';\nimport { describeArm, evaluateArm, type ArmOptions } from './admissibility.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\n\n/**\n * An invariant predicate: a property the instance always satisfies.\n */\nexport type InvariantPredicate<Class extends typeof Contracted> = (self: InstanceType<Class>) => boolean;\n\n/**\n * An invariant arm: a predicate, or a schema the instance must satisfy.\n *\n * A schema in this position validates the **instance**, which is the subject\n * `@invariant` already describes.\n */\nexport type InvariantArm<Class extends typeof Contracted> =\n InvariantPredicate<Class> | StandardSchemaV1<unknown, any>;\n\nexport type InvariantDecorator = <Class extends typeof Contracted>(\n arm: InvariantArm<Class>,\n options?: ArmOptions,\n) => (\n value: Class,\n context: ClassDecoratorContext<Class>\n) => Class | void;\n\n/**\n * A registered invariant arm.\n *\n * The options travel with the arm because `normalize` is a property of the\n * declaration rather than of an individual evaluation.\n */\nexport interface RegisteredInvariant {\n arm: InvariantArm<typeof Contracted>;\n options?: ArmOptions;\n}\n\nexport function assertInvariants<C extends typeof Contracted, T extends InstanceType<C>>(Class: C, instance: T) {\n if (!Contracted[checkedMode]) return;\n\n const registered = (Class[Symbol.metadata]?.['invariants'] ?? []) as unknown as RegisteredInvariant[],\n failed: number[] = [],\n issues: StandardSchemaV1.Issue[] = [];\n\n // AND-composed: every arm must hold for the instance to be valid. Invariants\n // are covariant, so a subtype may strengthen the obligation but never weaken\n // it, which is why one failing arm is enough to reject.\n for (const [index, entry] of registered.entries()) {\n const result = evaluateArm(\n entry.arm,\n { predicate: () => [instance], schema: () => instance },\n '@invariant',\n Class.name,\n index,\n entry.options,\n );\n\n if (result.ok) continue;\n\n failed.push(index);\n\n if (result.issues) issues.push(...result.issues);\n }\n\n if (failed.length === 0) return;\n\n throw violationError(\n '@invariant',\n Class.name,\n undefined,\n registered.map(entry => entry.arm),\n failed,\n 'The instance left the invariant unsatisfied.',\n issues,\n describeArm,\n );\n}\n\nexport const invariant: InvariantDecorator = (arm, options) => (OriginalClass, { kind, metadata }) => {\n assert(kind === 'class', '@invariant decorator can only be applied to classes');\n assert(OriginalClass.prototype instanceof Contracted, '@invariant decorator can only be applied to classes that extend Contracted');\n\n const existing = (metadata.invariants ?? []) as unknown as RegisteredInvariant[];\n\n metadata.invariants = [...existing, { arm, options }];\n};\n","import { assert } from './assert.mjs';\nimport { Contracted } from './Contracted.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * The gate every feature contract decorator shares.\n *\n * `@demands`, `@ensures`, and `@rescue` apply to exactly the same kind of member:\n * an instance feature of a `Contracted` subclass, whose name is not `_`-prefixed.\n * Each used to repeat the same four assertions and the same `addInitializer`\n * check, so a rule added to one was easy to miss in the others.\n *\n * The name of the contract is passed in so the messages stay specific.\n */\nexport function assertFeatureContractTarget(contract: string, feature: unknown, ctx: FeatureDecoratorContext): void {\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), `${contract} decorator can only be applied to methods, getters, or setters`);\n assert(ctx.static === false, `${contract} decorator cannot be applied to static features`);\n assert(ctx.private === false, `${contract} decorator cannot be applied to private features`);\n assert(!String(ctx.name).startsWith('_'), `${contract} decorator cannot be applied to private/protected features`);\n\n // Registration happens at decoration time rather than in `addInitializer`,\n // which runs once per instance: doing it there appended the same predicate on\n // every instantiation, which was unbounded metadata growth and a linearly\n // growing predicate list to evaluate on each call.\n ctx.addInitializer(function () {\n assert(this instanceof Contracted, `${contract} decorator can only be applied to classes that extend Contracted`);\n });\n}\n","import { violationError } from './assert.mjs';\nimport { checkedMode, Contracted } from \"./Contracted.mjs\";\nimport { assertFeatureContractTarget } from './decorator.mjs';\nimport { assertNormalizable, describeArm, evaluateArm, type ArmOptions } from './admissibility.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * A precondition predicate.\n *\n * `args` is the argument list of the invocation, matching `EnsuresPredicate`,\n * so a predicate destructures it: `(_self, [x]) => x > 0`.\n *\n * The type is generic over the argument tuple so the element types are inferred\n * from the predicate. Writing `(_self, x: number) => x > 0` does not compile:\n * the second parameter is the array, not the first argument, and a predicate\n * that compares against the array passes only through coercion, which is how\n * the previous documentation ended up describing contracts that never held.\n */\nexport type DemandsPredicate<This extends Contracted, Args extends any[] = any[]> =\n (self: This, args: Args) => boolean;\n\n/**\n * A precondiction arm: a predicate, or a schema the argument tuple must satisfy.\n *\n * A schema validates the **argument tuple**, which is the subject `@demands`\n * already describes, so a method with two parameters is written as\n * `z.tuple([A, B])`. Keeping one subject for both kinds of arm is what lets the\n * composition rule below be the same for both.\n *\n * The schema's `Input` is left unpinned (`unknown`) rather than constrained to\n * `any[]`, because every real provider declares a concrete input type and\n * `StandardSchemaV1` is invariant in it: pinning it here would reject a\n * `z.tuple([...])` whose input is `[number, number]`. The tuple shape is an\n * obligation on the declaration, checked at runtime by the schema itself.\n */\nexport type DemandsArm<This extends Contracted, Args extends any[] = any[]> =\n DemandsPredicate<This, Args> | StandardSchemaV1<unknown, any>;\n\nexport type DemandsDecorator = <This extends Contracted, Args extends any[], Feature = unknown>(\n arm: DemandsArm<This, Args>,\n options?: ArmOptions,\n) => (\n value: Feature,\n context: FeatureDecoratorContext\n) => Feature | void;\n\n/** A registered precondition arm, with the options it was declared with. */\nexport interface RegisteredDemands {\n arm: DemandsArm<Contracted>;\n options?: ArmOptions;\n}\n\nexport const demands: DemandsDecorator = (arm, options) => (feature, ctx) => {\n assertFeatureContractTarget('@demands', feature, ctx);\n assertNormalizable(arm, '@demands', options);\n\n const ds = [\n ...(ctx.metadata as any)?.demands?.[ctx.name] ?? [],\n { arm, options }\n ]\n\n ctx.metadata.demands = {\n ...(ctx.metadata?.demands ?? {}),\n [ctx.name]: ds\n };\n}\n\n/**\n * Evaluates the precondition for an invocation.\n *\n * The arms are OR-composed, which is the contravariance rule: a subtype may\n * weaken a precondition, so satisfying any inherited arm is enough. A schema arm\n * composes exactly like a predicate arm.\n *\n * When an arm asks for normalization, the value it produced replaces the\n * arguments, and because OR-composition short-circuits, the **first passing arm**\n * decides what that value is. That is deterministic and matches evaluation order.\n *\n * @returns The arguments to use, which are the originals unless an arm\n * normalized them.\n */\nexport function assertDemands(\n instance: Contracted,\n propertyKey: PropertyKey,\n args: any[],\n): any[] {\n if (!Contracted[checkedMode]) return args;\n\n const Class = instance.constructor as typeof Contracted,\n ds = (Class[Symbol.metadata]?.demands?.[propertyKey] ?? []) as unknown as RegisteredDemands[];\n\n if (ds.length === 0) return args;\n\n const label = `${instance.constructor.name}.${String(propertyKey)}`,\n failed: number[] = [],\n issues: StandardSchemaV1.Issue[] = [];\n\n for (const [index, { arm, options }] of ds.entries()) {\n const result = evaluateArm(\n arm,\n { predicate: () => [instance, args], schema: () => args },\n '@demands',\n label,\n index,\n options,\n );\n\n if (!result.ok) {\n failed.push(index);\n\n if (result.issues) issues.push(...result.issues);\n\n continue;\n }\n\n // Any satisfied arm fulfils the obligation.\n return result.value === undefined ? args : result.value as any[];\n }\n\n // Every arm failed. All of them are reported, because OR-composition means\n // any of them could have permitted the call.\n throw violationError(\n '@demands',\n instance.constructor.name,\n String(propertyKey),\n ds.map(entry => entry.arm),\n failed,\n 'A precondition was not satisfied, so the feature was not entered.',\n issues,\n describeArm,\n );\n}\n","import { violationError } from './assert.mjs';\nimport { checkedMode, Contracted } from './Contracted.mjs';\nimport { assertFeatureContractTarget } from './decorator.mjs';\nimport { assertNormalizable, describeArm, evaluateArm, type ArmOptions } from './admissibility.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * A postcondition predicate.\n *\n * `args` is the argument list of the invocation and `old` is the snapshot of\n * the instance from before the feature ran, so a predicate reads\n * `(self, [x], old) => ...`. See `DemandsPredicate` for why the tuple is generic.\n */\nexport type EnsuresPredicate<This extends Contracted, Args extends any[] = any[]> =\n (self: This, args: Args, old: This) => boolean;\n\n/**\n * A postcondition arm: a predicate, or a schema the feature's **result** must\n * satisfy.\n *\n * A schema validates the result, which is the value the caller receives. This is\n * the covariant position: a subtype may promise a narrower result, so the arms\n * are AND-composed.\n */\nexport type EnsuresArm<This extends Contracted, Args extends any[] = any[]> =\n EnsuresPredicate<This, Args> | StandardSchemaV1<unknown, any>;\n\nexport type EnsuresDecorator = <\n This extends Contracted,\n Args extends any[]\n>(\n arm: EnsuresArm<This, Args>,\n options?: ArmOptions,\n) => (\n value: unknown,\n context: FeatureDecoratorContext\n) => void;\n\n/** A registered postcondition arm, with the options it was declared with. */\nexport interface RegisteredEnsures {\n arm: EnsuresArm<Contracted>;\n options?: ArmOptions;\n}\n\nexport const ensures: EnsuresDecorator = (arm, options) => (feature, ctx) => {\n assertFeatureContractTarget('@ensures', feature, ctx);\n assertNormalizable(arm, '@ensures', options);\n\n const es = [\n ...(ctx.metadata as any)?.ensures?.[ctx.name] ?? [],\n { arm, options }\n ]\n\n // AND-composition means every arm must hold, so two arms that both replace\n // the result would disagree about what the caller receives. There is no\n // correct winner, so the declaration is rejected where it is written.\n const normalizers = (es as unknown as RegisteredEnsures[]).filter(entry => entry.options?.normalize);\n\n if (normalizers.length > 1)\n throw new TypeError(\n `@ensures for ${String(ctx.name)} declares ${normalizers.length} normalizing arms; `\n + 'at most one arm may normalize the result, because they would disagree about what the caller receives.',\n );\n\n ctx.metadata.ensures = {\n ...(ctx.metadata?.ensures ?? {}),\n [ctx.name]: es\n };\n}\n\n/**\n * Evaluates the postcondition for an invocation.\n *\n * The arms are AND-composed, which is the covariance rule: a subtype may\n * strengthen a postcondition, so every inherited arm has to keep holding.\n *\n * @param result - The value the caller receives. A schema arm validates it.\n * @returns The result to hand the caller, which is the original unless an arm\n * normalized it.\n */\nexport function assertEnsures(\n instance: Contracted,\n old: Contracted,\n propertyKey: PropertyKey,\n args: any[],\n result: unknown,\n): unknown {\n if (!Contracted[checkedMode]) return result;\n\n const Class = instance.constructor as typeof Contracted,\n es = (Class[Symbol.metadata]?.ensures?.[propertyKey] ?? []) as unknown as RegisteredEnsures[];\n\n if (es.length === 0) return result;\n\n const label = `${instance.constructor.name}.${String(propertyKey)}`,\n failed: number[] = [],\n issues: StandardSchemaV1.Issue[] = [];\n\n let normalized = result;\n\n // ALL arms must hold for the obligation to be fulfilled.\n for (const [index, entry] of es.entries()) {\n const outcome = evaluateArm(\n entry.arm,\n // A predicate sees the invocation and the historical instance; a\n // schema validates the result. Both are supplied so the adapter can\n // pick the one that belongs to the arm.\n {\n predicate: () => [instance, args, old],\n schema: () => result,\n },\n '@ensures',\n label,\n index,\n entry.options,\n );\n\n if (!outcome.ok) {\n failed.push(index);\n\n if (outcome.issues) issues.push(...outcome.issues);\n\n continue;\n }\n\n if (outcome.value !== undefined) normalized = outcome.value;\n }\n\n if (failed.length === 0) return normalized;\n\n throw violationError(\n '@ensures',\n instance.constructor.name,\n String(propertyKey),\n es.map(entry => entry.arm),\n failed,\n 'A postcondition was not satisfied after the feature ran.',\n issues,\n describeArm,\n );\n}\n","import { assert } from './assert.mjs';\nimport { checkedMode, Contracted } from './Contracted.mjs';\nimport { assertFeatureContractTarget } from './decorator.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * A handler for `@rescue`.\n *\n * `retry` is an ordinary function, called as `retry(...)`, so it has no\n * meaningful `this`. Declaring `this: This` on it made every consumer-written\n * handler fail to type-check, because the `this` context of a bare call is\n * `void`.\n */\nexport type RescueHandler<This extends Contracted> =\n (self: This, error: unknown, args: any[], retry: (...args: any[]) => any) => void\n\nexport interface RescueOptions {\n /**\n * The maximum number of times `retry` may restart the lifecycle for a single\n * invocation. Defaults to `Infinity`, which allows a `@rescue` to implement\n * N-Version programming with any number of alternative strategies.\n *\n * Set this when a rescue handler always retries, to bound recursion.\n */\n maxRetries?: number;\n}\n\nexport interface RescueDeclaration<This extends Contracted> {\n handler: RescueHandler<This>;\n maxRetries?: number;\n}\n\n/**\n * Declares a rescue handler for a feature.\n *\n * `retry` is explicit: it passes only the arguments it is given and never\n * replays the original arguments. Forward the `args` parameter to retry with\n * the same arguments (`retry(...args)`); calling `retry()` retries with none.\n *\n * Options are declaration level because they describe the feature rather than an\n * individual failure. `maxRetries` bounds how many times `retry` may restart the\n * lifecycle for one invocation; it defaults to unbounded.\n */\nexport type RescueDecorator = <This extends Contracted>(\n handler: RescueHandler<This>,\n options?: RescueOptions,\n) => (\n value: unknown,\n context: FeatureDecoratorContext\n) => void;\n\nexport const rescue: RescueDecorator = (handler, options) => (feature, ctx) => {\n assertFeatureContractTarget('@rescue', feature, ctx);\n assert(options?.maxRetries === undefined || options.maxRetries >= 0, 'maxRetries must not be negative');\n\n // Register at decoration time. `addInitializer` runs once per instance, so\n // registering there rewrote the same declaration on every instantiation.\n ctx.metadata.rescue = {\n ...(ctx.metadata?.rescue ?? {}),\n [ctx.name]: { handler, maxRetries: options?.maxRetries }\n }\n\n ctx.addInitializer(function () {\n assert(this instanceof Contracted, '@rescue decorator can only be applied to classes that extend Contracted');\n })\n}\n\n/**\n * Resolves the `@rescue` declaration for `propertyKey`, walking the prototype\n * chain so that a declaration on an ancestor feature is inherited.\n */\nexport function getRescueDeclaration(instance: Contracted, propertyKey: PropertyKey): RescueDeclaration<Contracted> | undefined {\n let proto: any = instance.constructor;\n while (proto && proto !== Function.prototype) {\n const declaration = proto[Symbol.metadata]?.rescue?.[propertyKey] as RescueDeclaration<Contracted> | undefined;\n\n if (declaration) return declaration;\n proto = Object.getPrototypeOf(proto);\n }\n\n return undefined;\n}\n\n/**\n * Applies the `@rescue` handler declared for `propertyKey`, if any.\n *\n * When the handler calls `retry`, the arguments passed to `retry` are returned\n * so that the caller can restart the contract lifecycle with them. This keeps\n * the lifecycle in one place (see `runLifecycle` in `Contracted.mts`) and\n * ensures a retried invocation is subject to `@invariant`, `@demands`, and\n * `@ensures` like any other invocation.\n *\n * `retry` may be called at most once per rescue execution. Because the lifecycle\n * re-enters `@rescue` when a retried invocation fails, a handler is executed\n * once per attempt, which is what N-Version programming requires.\n *\n * @returns The arguments to retry with.\n * @throws The original error if the handler does not call `retry`, or whatever\n * the handler throws.\n */\nexport const applyRescueHandler = (instance: Contracted, propertyKey: PropertyKey, error: unknown, args: any): any[] => {\n if (!Contracted[checkedMode]) throw error;\n\n const declaration = getRescueDeclaration(instance, propertyKey);\n\n if (!declaration) throw error;\n\n let hasRetried = false;\n let retryArgs: any[] = [];\n\n declaration.handler.call(instance, instance, error, args, (...args: any[]) => {\n assert(!hasRetried, 'retry can only be called once per rescue execution');\n hasRetried = true;\n retryArgs = args;\n })\n if (!hasRetried)\n throw error;\n\n return retryArgs;\n}\n","import { AssertionError } from './AssertionError.mjs';\nimport { assertInvariants, InvariantPredicate } from './invariant.mjs';\nimport { assertDemands, DemandsPredicate } from './demands.mjs';\nimport { assertEnsures, EnsuresPredicate } from './ensures.mjs';\nimport { applyRescueHandler as applyRescueHandler, getRescueDeclaration, RescueDeclaration } from './rescue.mjs';\n\n// Symbol to store checked mode state\nexport const checkedMode = Symbol.for('Contracted.checkedMode');\n\n/**\n * Type of value that `cloneState` copies rather than shares.\n *\n * The list is deliberately closed: arrays, dates, maps, sets, and plain objects\n * are cloned because they are the containers contracts routinely compare. Every\n * other object — class instances, functions, regular expressions, buffers — is\n * shared by reference. See the `@ensures` documentation for the rationale.\n */\nconst isPlainObject = (value: object): boolean => {\n const proto = Object.getPrototypeOf(value);\n\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Copies a value for use in an `old` snapshot.\n *\n * Plain data containers are cloned recursively so that mutations performed by\n * the feature body are not visible through `old`. Anything else is returned by\n * reference, which preserves identity and avoids attempting to clone values that\n * cannot be cloned meaningfully (functions, class instances, buffers).\n *\n * Own property descriptors are copied rather than values, so accessors are not\n * invoked while snapshotting. An accessor on `old` therefore reads the\n * historical state through `this`, which is what a postcondition expects.\n */\nconst cloneState = (value: any, seen: WeakMap<object, any>): any => {\n if (typeof value !== 'object' || value === null) return value;\n\n const already = seen.get(value);\n if (already !== undefined) return already;\n\n if (value instanceof Date) return new Date(value.getTime());\n\n if (Array.isArray(value)) {\n const copy: any[] = [];\n seen.set(value, copy);\n for (const item of value) copy.push(cloneState(item, seen));\n\n return copy;\n }\n\n if (value instanceof Map) {\n const copy = new Map<any, any>();\n seen.set(value, copy);\n for (const [k, v] of value) copy.set(cloneState(k, seen), cloneState(v, seen));\n\n return copy;\n }\n\n if (value instanceof Set) {\n const copy = new Set<any>();\n seen.set(value, copy);\n for (const item of value) copy.add(cloneState(item, seen));\n\n return copy;\n }\n\n if (!isPlainObject(value)) return value;\n\n const copy = Object.create(Object.getPrototypeOf(value));\n seen.set(value, copy);\n\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key)!;\n Reflect.defineProperty(copy, key, 'value' in descriptor\n ? { ...descriptor, value: cloneState(descriptor.value, seen) }\n : descriptor);\n }\n\n return copy;\n}\n\n/**\n * Builds the `old` instance passed to `@ensures`.\n *\n * The result inherits from `target`, so prototype members (including getters and\n * methods) remain reachable, while own state is a copy taken at this moment.\n * Getters defined on the prototype therefore read the historical own state\n * through `this`.\n */\nconst populateOld = (target: Contracted) => {\n if (!Contracted[checkedMode]) return;\n\n const old = Object.create(target),\n seen = new WeakMap<object, any>();\n\n for (const key of Reflect.ownKeys(target)) {\n const descriptor = Object.getOwnPropertyDescriptor(target, key)!;\n Reflect.defineProperty(old, key, 'value' in descriptor\n ? { ...descriptor, value: cloneState(descriptor.value, seen) }\n : descriptor);\n }\n\n return old;\n}\n\n/**\n * How a feature's body hands its result back to the caller.\n *\n * A Hoare triple `{ P } C { Q }` only means something if `Q` is evaluated after\n * `C` has finished. \"Finished\" is not the same event for every kind of feature:\n * an `async` body finishes when its promise settles, and a generator finishes a\n * *segment* every time it yields. The kind decides where the exit boundary\n * therefore sits.\n */\ntype FeatureKind = 'sync' | 'async' | 'generator' | 'async-generator';\n\n/**\n * Classifies a feature body by how it delivers its results.\n *\n * `Reflect.apply` on an `async` function returns its promise immediately, and on\n * a generator it returns an iterator, so the only reliable signal is the\n * function's constructor, which is stable across bundling and minification\n * (unlike `Function.prototype.name`).\n */\nconst featureKindOf = (fn: (...args: any[]) => unknown): FeatureKind => {\n switch (fn.constructor.name) {\n case 'AsyncFunction': return 'async';\n case 'GeneratorFunction': return 'generator';\n case 'AsyncGeneratorFunction': return 'async-generator';\n default: return 'sync';\n }\n};\n\n// Caches the contract wrapper per instance and feature so that `f.m === f.m`.\nconst wrapperCache = new WeakMap<object, Map<PropertyKey, (...args: any[]) => any>>();\n\n// Utility to walk up the prototype chain to find a property descriptor\nfunction getPropertyDescriptor(obj: object, prop: PropertyKey): PropertyDescriptor | undefined {\n let proto = obj;\n while (proto && proto !== Object.prototype) {\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\n if (desc) return desc;\n proto = Object.getPrototypeOf(proto);\n }\n return undefined;\n}\n\n/**\n * The kind of public feature whose boundary is being evaluated.\n *\n * `@ensures` and `@rescue` treat a getter differently from every other feature,\n * and the rule was written out four times: once in the synchronous lifecycle and\n * once in the asynchronous one, for each contract. Naming it here keeps the two\n * lifecycles from drifting apart on the one thing they must agree about.\n */\ntype DescriptorType = 'get' | 'set' | 'func' | 'delete';\n\n/**\n * The arguments an `@ensures` predicate observes.\n *\n * A getter delivers its result as the value the caller receives, so that is what\n * its postcondition describes. Every other feature is described by the arguments\n * it was invoked with.\n */\nconst ensuresArgs = (descriptorType: DescriptorType, result: unknown, args: any[]): any[] =>\n descriptorType === 'get' ? [result] : args;\n\n/**\n * The arguments an `@rescue` retry restarts the lifecycle with.\n *\n * A getter has no arguments to replay, so a retry runs it from scratch.\n */\nconst rescueArguments = (descriptorType: DescriptorType, args: any[]): any[] =>\n descriptorType === 'get' ? [] : args;\n\n/**\n * Decides what a failed invocation does next.\n *\n * Every lifecycle needs the same three decisions at its `@rescue` boundary:\n * whether another retry is permitted, what the handler asked for, and whether\n * the invariant has to be re-checked before the error reaches the caller.\n * Extracted because the sync and async lifecycles had this block verbatim twice.\n *\n * The sync and async lifecycles are separate functions on purpose: a lifecycle\n * that awaited unconditionally would make every synchronous feature return a\n * promise, which is not a refactor but a change to every caller. What is shared\n * is the decision, not the boundary.\n *\n * @returns The arguments to retry with, or the error is rethrown.\n */\nfunction attemptRescue(\n Class: typeof Contracted,\n target: Contracted,\n prop: PropertyKey,\n error: unknown,\n retries: number,\n args: any[],\n): any[] {\n const maxRetries = getRescueDeclaration(target, prop)?.maxRetries ?? Infinity;\n\n if (retries >= maxRetries) {\n assertInvariants(Class, target);\n throw error;\n }\n\n try {\n return applyRescueHandler(target, prop, error, args);\n } catch (rescuedError) {\n assertInvariants(Class, target);\n throw rescuedError;\n }\n}\n\n/**\n * Runs the assertion lifecycle for a single public invocation.\n *\n * The contracts describe the observable boundary of a feature, in the sense of\n * a Hoare triple `{ P } C { Q }`: `@demands` is `P`, `@ensures` is `Q`, and the\n * feature body is `C`. Nothing inside `C` is constrained — a body may mutate its\n * own state, including public properties, and may call its own features without\n * re-entering the contracts. Correctness is the obligation that `P` and `Q` hold\n * at the boundary, with the invariant additionally holding on entry and exit.\n *\n * Order: `@invariant` -> `@demands` -> body -> `@ensures` -> `@invariant`\n * (see `docs/happy-path.png`).\n *\n * A `@rescue` may call `retry`, which restarts the lifecycle from `@invariant`\n * with the supplied arguments, so a retried invocation is subject to\n * `@demands` and `@ensures` like any other invocation\n * (see `docs/order-of-assertions.png`).\n *\n * A retried invocation that fails re-enters `@rescue`, so the handler runs once\n * per attempt. This is what N-Version programming requires: a handler can\n * select the next alternative each time it is executed. Retries are bounded by\n * the optional `maxRetries` option on the `@rescue` declaration.\n *\n * The exit boundary sits wherever the body's result becomes observable, so a\n * synchronous and an asynchronous body are run by separate functions below and\n * dispatched by `runLifecycle`.\n *\n * @param invokeArgs - The arguments for this invocation. `retry` replaces them.\n * @param invoke - Performs the feature body with the supplied arguments.\n */\nfunction runSyncLifecycle(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n): any {\n const Class = target.constructor as typeof Contracted,\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\n hasEnsures = es.length > 0;\n\n let args = invokeArgs,\n retries = 0;\n\n for (; ;) {\n const old = hasEnsures ? populateOld(target) : undefined;\n\n assertInvariants(Class, target);\n args = assertDemands(target, prop, args);\n\n let result: any\n try {\n result = invoke(args);\n\n assertNotThenable(result, target, prop);\n\n if (hasEnsures)\n result = assertEnsures(target, old, prop, ensuresArgs(descriptorType, result, args), result);\n } catch (error) {\n args = attemptRescue(Class, target, prop, error, retries,\n rescueArguments(descriptorType, args));\n retries++;\n continue;\n }\n\n assertInvariants(Class, target);\n return result;\n }\n}\n\n/**\n * Runs the contract lifecycle whose exit boundary is a promise settlement.\n *\n * An `async` body returns its promise from `Reflect.apply` before a single line\n * of it has run, so evaluating `@ensures` there would test a body that has not\n * executed. The exit boundary must therefore *follow* the value: the lifecycle\n * waits for the promise to settle and then runs `@ensures` and the exit\n * `@invariant` against the settled state.\n *\n * Two consequences shape the code below.\n *\n * The first is failure surface. A contract that is violated on entry is a\n * synchronous throw in `runSyncLifecycle`, but that would be a lie here: an\n * `async` function never throws synchronously, so a caller that adds a\n * precondition must not change how a failure is observed. Entry violations are\n * therefore delivered as a rejection, exactly as the undecorated body's own\n * throws are. Substituting a contracted implementation for a plain one is\n * transparent to the caller, which is the substitutability Liskov requires and\n * which the type system already enforces in both directions (`() => T` and\n * `() => Promise<T>` are mutually non-assignable, so neither is a subtype of the\n * other and no conversion is implied).\n *\n * The second is that `@rescue` must observe rejections, not just synchronous\n * throws. A rescue that retries restarts the lifecycle, so a retried attempt is\n * subject to every contract like any other invocation.\n */\nasync function runAsyncLifecycle(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n): Promise<any> {\n const Class = target.constructor as typeof Contracted,\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\n hasEnsures = es.length > 0;\n\n let args = invokeArgs,\n retries = 0;\n\n for (; ;) {\n const old = hasEnsures ? populateOld(target) : undefined;\n\n assertInvariants(Class, target);\n args = assertDemands(target, prop, args);\n\n let result: any;\n try {\n result = await invoke(args);\n if (hasEnsures)\n result = assertEnsures(target, old, prop, ensuresArgs(descriptorType, result, args), result);\n } catch (error) {\n args = attemptRescue(Class, target, prop, error, retries,\n rescueArguments(descriptorType, args));\n retries++;\n continue;\n }\n\n assertInvariants(Class, target);\n return result;\n }\n}\n\n/**\n * Runs the contract lifecycle whose boundary is a generator's iterator.\n *\n * A generator does not have one exit boundary: it has a boundary per *step*.\n * Calling `obj.gen(...)` starts the body but its first line has not run, and each\n * `next()` runs the body until the following `yield`. A yield is therefore the\n * observable delivery of a traversal, which is what `@ensures` describes, and the\n * contracts bracket it accordingly:\n *\n * ```\n * call -> @invariant, @demands (the call arguments are `P`)\n * next() -> body to the next yield\n * -> @ensures, @invariant (the yielded value and the new state are `Q`)\n * ```\n *\n * This is the same sandwich the diagram shows for an ordinary feature\n * (`docs/order-of-assertions.png`), applied once per step. The exit `@invariant`\n * is what closes the window between yields: a suspended generator's instance is\n * publicly reachable, so another feature can be called on it, and that call's\n * entry check is the guarantee that it never observes an invalid object.\n *\n * Checking the invariant *before* handing over a value is not possible — the\n * segment is not finished at the `yield` — so resuming is where the previous\n * step's exit check happens. The terminal step resumes into the same point and\n * then reports `done`, so completion is covered without extra machinery.\n *\n * `@demands` describes the call, so it runs once. A later step may also be\n * *given* a value through `next(value)`, which arrives as the value of the\n * preceding `yield` expression and is entirely outside the arguments of the\n * call. That input is checked when it is present and skipped when it is not,\n * because `for...of` iterates with `next()` and would otherwise re-enter the\n * precondition with `undefined` and fail it.\n *\n * `@rescue` is the outer scope, as it is for an `async` feature: it covers a\n * throw that escapes a step, and `retry` restarts the traversal. Rescuing a\n * single step would require resuming a generator that has already been consumed,\n * which the language cannot express.\n */\nfunction runGeneratorLifecycle(\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n kind: 'generator' | 'async-generator',\n): any {\n const Class = target.constructor as typeof Contracted,\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\n hasEnsures = es.length > 0;\n\n /*\n * A generator has a boundary per *step*, not one per call. Calling the\n * feature runs nothing, and each `next()` runs the body from where it was\n * suspended up to the following `yield`. When `next()` returns, the segment\n * has finished and the instance holds the state it will be observed with, so\n * the exit contracts run there, before the caller is given the value:\n *\n * call -> @invariant, @demands the call arguments are `P`\n * next() -> @invariant entry of the step\n * segment -> body to the next yield\n * next() -> @ensures, @invariant the yielded value and state\n *\n * This is the sandwich in `docs/order-of-assertions.png` applied once per\n * step, and it gives the invariant the same guarantee it has elsewhere: no\n * public interaction leaves the object invalid. That matters more here than\n * anywhere else, because a suspended generator's instance is publicly\n * reachable and another feature can be called on it between yields. Checking\n * only at completion would leave the object knowingly invalid for the whole\n * traversal, and would never check at all if the iterator were abandoned.\n */\n\n // The iterator in play. A `@rescue` that retries replaces it.\n let iterator: any,\n args = invokeArgs,\n retries = 0,\n // The invariant has not been evaluated since the traversal began.\n needsEntry = true,\n // The error a `@rescue` handled by retrying, raised if the retried\n // traversal then completes without producing a value.\n retriedError: unknown;\n\n /**\n * Runs the entry contracts for a step.\n *\n * `@demands` describes the call, so it runs once, on the first step. A later\n * step may be *given* a value through `next(value)`, which becomes the value\n * of the preceding `yield` expression and is not an argument of the call;\n * that input is checked as a precondition when it is present. `for...of`\n * iterates with `next()` and injects nothing, so it never re-enters the\n * precondition with `undefined`.\n */\n const enter = (stepArgs: any[]): any[] => {\n assertInvariants(Class, target);\n\n if (needsEntry) {\n needsEntry = false;\n\n return assertDemands(target, prop, args);\n }\n\n // A value injected with `next(value)` is an input to the step, so it is\n // the subject a precondition describes. `for...of` injects nothing, so\n // it never re-enters the precondition with `undefined`.\n return stepArgs.length > 0 ? assertDemands(target, prop, stepArgs) : stepArgs;\n };\n\n /**\n * Runs the exit contracts for a step that produced a value.\n */\n const exit = (value: any, old: Contracted | undefined) => {\n if (hasEnsures) assertEnsures(target, old!, prop, [value], value);\n\n assertInvariants(Class, target);\n\n // A value was delivered, so the retry that recovered the traversal has\n // been observed and the error it handled no longer needs reporting.\n retriedError = undefined;\n };\n\n /**\n * Raises the error a retry was recovering from, when the retried traversal\n * completes without a value. Nothing observed that value, so the caller who\n * triggered the rescue is told why rather than being handed `undefined`.\n */\n const reportRetried = () => {\n assertInvariants(Class, target);\n\n if (retriedError === undefined) return;\n\n const error = retriedError;\n\n retriedError = undefined;\n\n throw error;\n };\n\n /**\n * Rebuilds the traversal after a `@rescue` retried.\n *\n * A generator that has already been consumed cannot be resumed from the\n * beginning, so a retry restarts it: `retry` reruns the body, exactly as the\n * loop back to `@invariant` in `docs/order-of-assertions.png` says it does.\n */\n const prepareRetry = (error: unknown) => {\n args = attemptRescue(Class, target, prop, error, retries, args);\n retries++;\n iterator = invoke(args);\n needsEntry = true;\n retriedError = error;\n };\n\n /**\n * Drives one step of a synchronous generator.\n */\n const drive = (advance: (iterator: any, stepArgs: any[]) => any, stepArgs: any[]): any => {\n for (; ;) {\n try {\n // A normalizing schema on an injected value replaces the\n // arguments for this step, so the value the body receives is the\n // one the schema produced.\n stepArgs = enter(stepArgs);\n\n // `old` describes the state the segment is about to change, so\n // it is taken before the body advances.\n const old = hasEnsures ? populateOld(target) : undefined,\n result = advance(iterator, stepArgs);\n\n if (result.done) {\n reportRetried();\n\n return result;\n }\n\n exit(result.value, old);\n\n return result;\n } catch (error) {\n prepareRetry(error);\n }\n }\n };\n\n /**\n * Drives one step of an asynchronous generator, awaiting its segment.\n */\n const driveAsync = async (advance: (iterator: any, stepArgs: any[]) => Promise<any>, stepArgs: any[]): Promise<any> => {\n for (; ;) {\n try {\n stepArgs = enter(stepArgs);\n\n const old = hasEnsures ? populateOld(target) : undefined,\n result = await advance(iterator, stepArgs);\n\n if (result.done) {\n reportRetried();\n\n return result;\n }\n\n exit(result.value, old);\n\n return result;\n } catch (error) {\n prepareRetry(error);\n }\n }\n };\n\n // The call's entry contracts run when the feature is called, matching the\n // arrow out of `obj.feature(...)` in the diagram. The body itself does not\n // start until the iterator is resumed.\n assertInvariants(Class, target);\n args = assertDemands(target, prop, args);\n needsEntry = false;\n iterator = invoke(args);\n\n const wrapper: any = {};\n\n if (kind === 'generator') {\n // `arguments.length` distinguishes `next()` from `next(undefined)`, which\n // the engine treats differently: only an explicit value is injected.\n wrapper.next = function (...stepArgs: any[]) {\n return drive((current, args) => current.next(args[0]), stepArgs);\n };\n wrapper.return = function (...returnArgs: any[]) {\n return drive((current, args) => current.return(returnArgs[0] ?? args[0]), []);\n };\n wrapper.throw = function (...errorArgs: any[]) {\n return drive((current, args) => current.throw(errorArgs[0] ?? args[0]), []);\n };\n wrapper[Symbol.iterator] = function () { return this; };\n }\n else {\n wrapper.next = function (...stepArgs: any[]) {\n return driveAsync((current, args) => current.next(args[0]), stepArgs);\n };\n wrapper.return = function (...returnArgs: any[]) {\n return driveAsync((current, args) => current.return(returnArgs[0] ?? args[0]), []);\n };\n wrapper.throw = function (...errorArgs: any[]) {\n return driveAsync((current, args) => current.throw(errorArgs[0] ?? args[0]), []);\n };\n wrapper[Symbol.asyncIterator] = function () { return this; };\n }\n\n return wrapper;\n}\n\n/**\n * Selects the lifecycle boundary for a feature body.\n *\n * An `async` body is awaited through `runAsyncLifecycle` and a generator is\n * wrapped by `runGeneratorLifecycle`; anything else is evaluated synchronously.\n * This is decided from the function itself rather than from whether the result\n * *looks* like a promise, so a synchronous feature that happens to return a\n * thenable is still checked synchronously — the contract describes the feature as\n * written, and such a feature's postcondition cannot hold anyway because its body\n * has not finished. `@demands` therefore fails it with a message naming the\n * feature.\n */\nfunction runLifecycle(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n kind: FeatureKind = 'sync',\n): any {\n if (kind === 'async')\n return runAsyncLifecycle(descriptorType, target, prop, invokeArgs, invoke);\n\n if (kind === 'generator' || kind === 'async-generator')\n return runGeneratorLifecycle(target, prop, invokeArgs, invoke, kind);\n\n return runSyncLifecycle(descriptorType, target, prop, invokeArgs, invoke);\n}\n\n/**\n * Rejects a thenable returned by a feature that is not declared `async`.\n *\n * A synchronous feature's contracts are evaluated when its body returns, so a\n * body that defers its work through a promise is checked before it has done\n * anything. `@ensures` would then describe a state the feature has not reached\n * yet, and the caller would receive a promise whose outcome no contract ever\n * observed.\n *\n * The alternative — awaiting any thenable — was rejected because it would make\n * `async` optional while silently changing when failure is reported: a plain\n * function cannot return a settled value for a rejection to accompany, so the\n * feature would have to become `async` for its errors to be observable anyway.\n * Failing closed keeps the declaration and the boundary in agreement, and the\n * message says what to do.\n */\nconst assertNotThenable = (result: unknown, target: Contracted, prop: PropertyKey): void => {\n if (result === null || typeof result !== 'object' && typeof result !== 'function') return;\n\n if (typeof (result as any).then !== 'function') return;\n\n throw new AssertionError(\n `${target.constructor.name}.${String(prop)} returned a promise but is not declared 'async', `\n + \"so its contracts were evaluated before its body finished. Declare the feature 'async'.\",\n );\n}\n\nconst proxyHandler: ProxyHandler<Contracted> = {\n get(target, prop, receiver) {\n if (!Contracted[checkedMode]) return Reflect.get(target, prop, receiver);\n\n const descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop);\n\n if (typeof descriptor?.value === 'function') {\n let cache = wrapperCache.get(target);\n\n if (!cache) {\n cache = new Map();\n wrapperCache.set(target, cache);\n }\n\n const cached = cache.get(prop);\n\n if (cached) return cached;\n\n const kind = featureKindOf(descriptor.value);\n\n // The descriptor is resolved from the instance's prototype chain,\n // which is fixed for the lifetime of the instance, so the wrapper\n // can be reused for that feature.\n //\n // The body receives the raw target as `this`. A feature body is `C`\n // in `{ P } C { Q }`: what it does internally is unconstrained, so\n // internal accesses must not re-enter the traps.\n const wrapper = function (this: Contracted, ...methodArgs: any[]) {\n return runLifecycle('func', target, prop, methodArgs,\n (args) => Reflect.apply(descriptor.value!, target, args), kind);\n };\n\n cache.set(prop, wrapper);\n\n return wrapper;\n }\n else if (typeof descriptor?.get === 'function')\n return runLifecycle('get', target, prop, [],\n () => descriptor.get!.call(target), featureKindOf(descriptor.get!));\n else\n return Reflect.get(target, prop, receiver);\n },\n set(target, prop, value, receiver) {\n if (!Contracted[checkedMode]) return Reflect.set(target, prop, value, receiver);\n\n const descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop)\n\n // Encapsulation governs the external surface only. It exists so a caller\n // cannot mutate state without a postcondition to catch it; inside a body,\n // `@ensures` and `@invariant` provide that guarantee instead.\n if (!(descriptor && typeof descriptor.set === 'function'))\n if (typeof prop === 'string' && !prop.startsWith('_'))\n throw new TypeError(`Cannot assign to property '${String(prop)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);\n\n const setter = typeof descriptor?.set === 'function' ? descriptor.set : undefined;\n\n runLifecycle('set', target, prop, [value],\n (args) => setter\n ? (setter.call(target, args[0]), true)\n : Reflect.set(target, prop, args[0], receiver));\n\n // A `set` trap must report success or the assignment throws in strict\n // mode. Accessors do not return a meaningful value, so success is\n // implicit once the lifecycle completes.\n return true;\n },\n deleteProperty(target, prop) {\n if (!Contracted[checkedMode]) return Reflect.deleteProperty(target, prop);\n\n // Deletion follows the same rule as assignment: it is an external\n // mutation, so it is subject to encapsulation and to the lifecycle.\n // Only `_`-prefixed properties, the ones a caller is allowed to mutate\n // in the first place, may also be removed.\n if (typeof prop === 'string' && !prop.startsWith('_'))\n throw new TypeError(`Cannot delete property '${String(prop)}' from Contracted instances: only properties starting with '_' can be deleted.`);\n\n return runLifecycle('delete', target, prop, [], () => Reflect.deleteProperty(target, prop));\n },\n};\n\nexport class Contracted {\n static [Symbol.metadata]: {\n invariants: InvariantPredicate<typeof Contracted>[];\n demands: Record<PropertyKey, DemandsPredicate<Contracted>[]>;\n ensures: Record<PropertyKey, EnsuresPredicate<Contracted>[]>;\n rescue: Record<PropertyKey, RescueDeclaration<Contracted>>;\n };\n\n /**\n * Grants permission for exactly one `Contracted` constructor call.\n *\n * A boolean would leave the gate open for the whole duration of the\n * constructor, so a class that called `new Foo()` inside its own\n * constructor — directly or through a superclass — would obtain a raw,\n * unproxied instance and defeat every contract.\n *\n * `Contracted`'s constructor runs exactly once per construction, so a\n * single-use token is enough. Classes that do not declare their own\n * constructor call it implicitly; classes that do must call `super()` once.\n */\n protected static _allowedConstructions = 0;\n\n // Symbol-based checked mode state\n public static [checkedMode]: boolean = true;\n\n static new<\n C extends typeof Contracted,\n Args extends ConstructorParameters<C>,\n >(this: C, ...args: Args): InstanceType<C> {\n const previous = (this as any)._allowedConstructions;\n\n (this as any)._allowedConstructions = previous + 1;\n\n try {\n const instance = new this(...args) as InstanceType<C>;\n assertInvariants(this, instance);\n\n return new Proxy<InstanceType<C>>(instance, proxyHandler);\n } finally {\n // Restore rather than decrement: the constructor consumes the token,\n // so decrementing here would double-count. Restoring also clears it\n // if the constructor threw for any reason.\n (this as any)._allowedConstructions = previous;\n }\n }\n\n constructor(..._args: any[]) {\n const Class = this.constructor as typeof Contracted;\n\n if (Class._allowedConstructions <= 0)\n throw new TypeError(\"Use the static 'new' method to instantiate this class.\");\n\n // Consume the token so a nested `new` inside a constructor cannot\n // borrow the outer construction's permission.\n Class._allowedConstructions--;\n }\n}"],"names":["Symbol","metadata","for","AssertionError","Error","name","violation","constructor","message","super","this","readOnlyViews","WeakMap","isSchema","arm","describeArm","vendor","version","String","assertNormalizable","contract","options","normalize","TypeError","evaluateArm","subjects","label","index","evaluateSchema","schema","evaluatePredicate","predicate","args","instance","rest","ok","assertContractResult","target","cached","get","view","Proxy","set","_target","property","deleteProperty","defineProperty","readOnlyView","subject","result","validate","then","issues","value","assert","condition","Boolean","describeContractResult","JSON","stringify","undefined","Object","prototype","toString","call","describeViolation","className","feature","arms","failedIndices","summary","describe","predicates","map","length","where","noun","detail","source","position","join","count","total","singular","plural","issue","path","segment","key","describeIssue","violationError","iff","p","q","implies","assertInvariants","Class","Contracted","checkedMode","registered","failed","entry","entries","push","invariant","OriginalClass","kind","existing","invariants","assertFeatureContractTarget","ctx","includes","static","private","startsWith","addInitializer","demands","ds","assertDemands","propertyKey","ensures","es","normalizers","filter","assertEnsures","old","normalized","outcome","rescue","handler","maxRetries","getRescueDeclaration","proto","Function","declaration","getPrototypeOf","applyRescueHandler","error","hasRetried","retryArgs","cloneState","seen","already","Date","getTime","Array","isArray","copy","item","Map","k","v","Set","add","isPlainObject","create","Reflect","ownKeys","descriptor","getOwnPropertyDescriptor","populateOld","featureKindOf","fn","wrapperCache","getPropertyDescriptor","obj","prop","desc","ensuresArgs","descriptorType","rescueArguments","attemptRescue","retries","Infinity","rescuedError","runLifecycle","invokeArgs","invoke","async","hasEnsures","runAsyncLifecycle","iterator","retriedError","needsEntry","enter","stepArgs","exit","reportRetried","prepareRetry","drive","advance","done","driveAsync","wrapper","next","current","return","returnArgs","throw","errorArgs","asyncIterator","runGeneratorLifecycle","assertNotThenable","runSyncLifecycle","proxyHandler","receiver","cache","methodArgs","apply","setter","previous","_allowedConstructions","_args"],"sourceRoot":""}
1
+ {"version":3,"file":"index.mjs","mappings":"AAGCA,OAAeC,WAAaD,OAAOE,IAAI,mBCqEjC,MAAMC,UAAuBC,MAOvBC,KAAO,iBAGPC,UAET,WAAAC,CAAYC,EAAkBF,GAC1BG,MAAMD,GACNE,KAAKJ,UAAYA,CACrB,EClDJ,MAAMK,EAAgB,IAAIC,QAUbC,EAAkCC,IAC3C,MAAMC,EAASJ,EAAcK,IAAIF,GAEjC,GAAIC,EAAQ,OAAOA,EAEnB,MAAME,EAAO,IAAIC,MAAMJ,EAAQ,CAC3B,GAAAK,CAAIC,EAASC,GACT,MAAM,IAAIC,UACN,wCAAwCC,OAAOF,mGAGvD,EACA,cAAAG,CAAeJ,EAASC,GACpB,MAAM,IAAIC,UACN,wCAA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N,sHACV,GAAGuN,GAAOvN,mJAGxB,CA6BI6N,CAAkB7N,EAAOiC,GAEzB,IAAK,MAAM1F,KAAW0F,EAAU,CAC5B,MAAMkE,EAAasH,GAAazN,EAAM9D,UAAWK,GAEjD,GAA+B,mBAApB4J,GAAYlO,IACnB,MAAM,IAAIM,UACN,4BAA4BgE,gCAAsCgR,GAAOvN,wGAGrF,CAEA/D,OAAOvD,eAAesH,EAAM9D,UAAWoR,GAAS,CAC5CnS,MAAOwS,GAAc1L,GAGrB9C,YAAY,EACZoH,UAAU,EACVnH,cAAc,IAGlBoO,GAAUnO,IAAIW,W","sources":["webpack://@final-hill/decorator-contracts/./src/types.mts","webpack://@final-hill/decorator-contracts/./src/AssertionError.mts","webpack://@final-hill/decorator-contracts/./src/read-only.mts","webpack://@final-hill/decorator-contracts/./src/admissibility.mts","webpack://@final-hill/decorator-contracts/./src/assert.mts","webpack://@final-hill/decorator-contracts/./src/iff.mts","webpack://@final-hill/decorator-contracts/./src/implies.mts","webpack://@final-hill/decorator-contracts/./src/name.mts","webpack://@final-hill/decorator-contracts/./src/inspect.mts","webpack://@final-hill/decorator-contracts/./src/feature-kind.mts","webpack://@final-hill/decorator-contracts/./src/decorator.mts","webpack://@final-hill/decorator-contracts/./src/invariant.mts","webpack://@final-hill/decorator-contracts/./src/demands.mts","webpack://@final-hill/decorator-contracts/./src/ensures.mts","webpack://@final-hill/decorator-contracts/./src/rescue.mts","webpack://@final-hill/decorator-contracts/./src/Contracted.mts","webpack://@final-hill/decorator-contracts/./src/metadata.mts","webpack://@final-hill/decorator-contracts/./src/serialization.mts"],"sourcesContent":["// Polyfill Symbol.metadata if not present\n// ref: https://github.com/microsoft/TypeScript/issues/53461#issuecomment-1736996954\n// ref: https://github.com/tc39/proposal-decorator-metadata\n(Symbol as any).metadata ??= Symbol.for(\"Symbol.metadata\");\n\n// Extend the global SymbolConstructor type to include metadata\ndeclare global {\n interface SymbolConstructor {\n readonly metadata: symbol;\n }\n}\n\nexport type Constructor<T> = new (...args: any[]) => T\n\n/**\n * The context a feature contract decorator is applied with.\n *\n * The type parameters are what make a contract predicate inferable. A standard\n * member decorator's context carries the class it is declared on (`This`) and the\n * decorated member's own signature, so stating them here connects the decorator's\n * argument to the member it is applied to. Leaving them out — as the\n * unparameterized `ClassMemberDecoratorContext` does — gives the compiler nothing\n * to infer from, and `self` degrades to the constraint.\n *\n * `Result` is deliberately **not** a parameter here. A method's context carries a\n * call signature (`() => number`) while a getter's carries the property type\n * (`number`), and both would be inference sites for one `Result`, so the compiler\n * resolves it to their intersection — `number & (() => number)`. An `@ensures`\n * predicate therefore keeps `result` at `unknown` and names it with an explicit\n * annotation when it needs more, which is what `EnsuresSubject`'s third parameter\n * is for.\n *\n * `ClassAccessorDecoratorContext` is excluded because the library does not support\n * the `accessor` keyword.\n */\nexport type FeatureDecoratorContext<This, Args extends any[] = any[]> =\n | ClassMethodDecoratorContext<This, (this: This, ...args: Args) => unknown>\n | ClassGetterDecoratorContext<This, unknown>\n | ClassSetterDecoratorContext<This, unknown>","import type { StandardSchemaV1 } from './standard-schema.mjs';\n\n/**\n * The contract kinds that can raise an {@link AssertionError}.\n */\nexport type ContractKind = '@invariant' | '@demands' | '@ensures';\n\n/**\n * Structured description of a failed contract.\n *\n * Attached to {@link AssertionError} so that callers — including integration\n * layers such as a schema adapter — can react to a specific violation without\n * parsing the message.\n */\nexport interface ContractViolation {\n /** Which contract failed. */\n contract: ContractKind;\n /**\n * The class the contract belongs to.\n *\n * This is the class's declared `contractName` when it has one, and the\n * constructor's name otherwise — which is the build's output rather than the\n * author's declaration, and degrades under minification. Declare a name for a\n * `className` that survives a production build.\n */\n className: string;\n /** The feature the contract belongs to, absent for `@invariant`. */\n feature?: string;\n /**\n * The indices, within the contract's composition list, that failed.\n *\n * `@demands` is OR-composed, so a failure lists every arm; `@ensures` and\n * `@invariant` are AND-composed, so a failure lists the one that broke.\n */\n failedIndices: number[];\n /**\n * The indices of the arms that failed by throwing, in evaluation order.\n *\n * Absent when every failing arm reported a verdict. An arm that throws is a\n * failed arm, so it also appears in {@link ContractViolation.failedIndices};\n * this field separates the arms that threw from the arms that returned\n * `false`, which is how a deliberate throw is told apart from a predicate bug.\n */\n thrownIndices?: number[];\n /**\n * Descriptions of the values thrown by the failing arms, aligned with\n * `thrownIndices`.\n *\n * These are strings rather than the values themselves. The rest of this record\n * is plain data, and a violation is logged, retained, and serialised; holding a\n * reference to the consumer's error would keep it alive and could make the\n * record unserialisable. The value the contract re-raised is the error the\n * caller caught, which is where they read it.\n */\n thrown?: string[];\n /** The source text of the failing arms, aligned with `failedIndices`. */\n predicates: string[];\n /**\n * The `issues` reported by failing schema arms, in the order they were\n * raised. Absent when the failure came only from predicate arms, so a caller\n * can distinguish \"a schema rejected this\" from \"a predicate returned\n * false\".\n */\n issues?: ReadonlyArray<StandardSchemaV1.Issue>;\n}\n\n/**\n * An `AssertionError` represents a failed assertion with an associated message.\n *\n * When the failure came from a contract, {@link AssertionError.violation}\n * describes it structurally.\n */\nexport class AssertionError extends Error {\n /**\n * Set explicitly rather than relying on the class name.\n *\n * Bundlers rename classes, so the published build would otherwise expose a\n * mangled name such as `t` to consumers.\n */\n override name = 'AssertionError';\n\n /** Structured description of the failure, when it came from a contract. */\n readonly violation?: ContractViolation;\n\n constructor(message?: string, violation?: ContractViolation) {\n super(message);\n this.violation = violation;\n }\n}\n","/**\n * Read-only views of an instance, handed to contract predicates.\n *\n * https://github.com/final-hill/decorator-contracts/issues/191\n *\n * A predicate answers a question; it must not change the state it is asked about.\n * Side effects in a predicate are corrupting rather than merely impure: the\n * predicate runs between the entry and exit `@invariant`, so a write there can\n * hide a violation the invariant would otherwise have reported.\n *\n * `rescue` is deliberately excluded. Restoring corrupted state is its purpose, so\n * it receives the raw target.\n *\n * ### Why a proxy rather than `Object.freeze`\n *\n * Freezing is permanent. A predicate that froze the instance would leave the\n * feature body unable to change it, so every feature on that instance would break:\n *\n * ```text\n * deposit FAILED: TypeError - Cannot assign to read only property '_balance'\n * ```\n *\n * A proxy is scoped to the predicate call, so the body still receives the raw\n * target and mutates normally.\n *\n * ### What is and is not blocked\n *\n * Assignment, deletion, and `defineProperty` on the instance are refused. A\n * mutation *through* a nested value (`self._items.push(x)`) still reaches the\n * shared object, because the proxy only intercepts the instance's own surface.\n * Closing that would require deep-wrapping every value returned from a read,\n * which changes identity for legitimate comparisons such as\n * `old.child === self.child`. The guarantee is therefore \"a predicate cannot\n * assign to the instance\", which is the case that actually corrupts contract\n * evaluation.\n */\n\nconst readOnlyViews = new WeakMap<object, object>();\n\n/**\n * Returns a cached read-only view of `target`.\n *\n * Cached because the same instance is evaluated by several contracts within one\n * lifecycle, and creating a fresh proxy each time would make `self` a different\n * object for each predicate — enough to break a predicate that compares `self`\n * across two contracts.\n */\nexport const readOnlyView = <T extends object>(target: T): T => {\n const cached = readOnlyViews.get(target);\n\n if (cached) return cached as T;\n\n const view = new Proxy(target, {\n set(_target, property) {\n throw new TypeError(\n `A contract predicate may not assign '${String(property)}'. `\n + 'Contract predicates answer a question; they must not change the state they are asked about.',\n );\n },\n deleteProperty(_target, property) {\n throw new TypeError(\n `A contract predicate may not delete '${String(property)}'. `\n + 'Contract predicates answer a question; they must not change the state they are asked about.',\n );\n },\n defineProperty() {\n throw new TypeError(\n 'A contract predicate may not define properties. '\n + 'Contract predicates answer a question; they must not change the state they are asked about.',\n );\n },\n });\n\n readOnlyViews.set(target, view);\n\n return view;\n}\n","import { assertContractResult } from './assert.mjs';\nimport type { ContractViolation } from './AssertionError.mjs';\nimport { readOnlyView } from './read-only.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\n\n/**\n * Converts a failed contract into the error its caller receives.\n *\n * It is called once, after **every** arm has failed, with the structured\n * violation. That position is the whole reason the option exists: a predicate\n * must not throw, because an arm that throws is one opinion that the call should\n * not proceed rather than an abort of the composition, so a typed error cannot be\n * raised from inside one. A factory runs where the decision is already made.\n *\n * The return value must be an object. The violation and the `AssertionError` that\n * describes every unsatisfied arm are attached to it, so an error that could carry\n * neither would silently lose the contract details.\n */\nexport type ViolationFactory = (violation: ContractViolation) => object;\n\n/**\n * The result of checking a subject against one contract arm.\n *\n * Predicates and schemas are adapted to this shape so that the composition rule\n * in each contract — OR for `@demands`, AND for `@invariant` and `@ensures` — is\n * written once rather than twice.\n *\n * An arm that threw reports `ok: false` with the thrown value preserved in\n * `thrown`. Composition continues past it: an `@demands` arm that throws is one\n * opinion that the call should not proceed, and a later arm may still permit it.\n * Keeping the value instead of letting it propagate is what makes an arm's own\n * error reachable without making the composition rule unreachable.\n */\nexport type Admissibility = {\n ok: boolean;\n value?: unknown;\n thrown?: unknown;\n issues?: ReadonlyArray<StandardSchemaV1.Issue>\n};\n\n/** Options a decorator accepts alongside an arm. */\nexport interface ArmOptions {\n /**\n * Replace the subject with the schema's `Output`.\n *\n * Off by default. `validate` may transform what it returns, and applying that\n * transformation changes what the feature body receives and what later\n * contracts observe, so it is an explicit choice rather than a side effect of\n * validation. Only a schema can normalize.\n */\n normalize?: boolean;\n\n /**\n * Build the error raised when the arm's contract fails.\n *\n * Receives the full `ContractViolation`, because that record is the only\n * machine-readable part of a failure: an error boundary or a metadata-driven\n * test needs `failedIndices`, `thrownIndices`, and the schema `issues`, and a\n * bare constructor would discard them.\n *\n * Scope is **per contract, not per arm.** When several arms declare a factory,\n * the one belonging to the **first arm evaluated** decides, matching the rule\n * that the first arm decides a normalized value. Arms evaluate in the contract's\n * composition order — reverse source order within a class, inherited arms\n * first — so the factory that wins is the one whose declaration is read first by\n * the runtime.\n *\n * The returned error carries the violation as `violation` and the\n * `AssertionError` describing every unsatisfied arm as `cause`, both\n * non-enumerable. A factory that returns a non-object is refused when it runs,\n * since neither field could be attached to it; what it produces depends on the\n * violation, so there is nothing to check at decoration time. The guard admits\n * anything `typeof` reports as an object, so an array passes and carries both\n * fields — it is the author's choice whether an error boundary can branch on it.\n *\n * A `@rescue` that retries calls the factory once per failed attempt, because\n * each attempt is a separate failure with its own violation.\n */\n onViolation?: ViolationFactory;\n\n /**\n * Suppress the warning a subclass `@demands` arm raises for narrowing.\n *\n * `@demands` is OR-composed, so an arm added below an inherited one cannot\n * narrow the precondition — satisfying any inherited arm still permits the\n * call. That is easy to misread as a restriction, so declaring an arm on a\n * feature that already has inherited arms warns.\n *\n * The arm is a legal weakening, so the warning is a diagnostic and not a\n * refusal. Set this when the weakening is what was meant.\n *\n * Only `@demands` reports it. `@ensures` and `@invariant` are AND-composed, so\n * a subclass arm strengthens the obligation rather than appearing to restrict\n * it, and those decorators **refuse** the option rather than accepting one that\n * could never do anything.\n */\n allowWeakening?: boolean;\n\n /**\n * Allow the predicate to answer with a promise, which the lifecycle awaits\n * before it decides the arm.\n *\n * Off by default, and off is load-bearing: a `Promise` is always truthy, so\n * coercing a verdict that has not settled yet would treat a contract that has\n * not been checked as satisfied. Accepting one only where the feature's own\n * boundary is a promise keeps that rule intact — the check moves to the same\n * microtask the exit checks already occupy.\n *\n * Only an `async` method qualifies. A synchronous feature has evaluated its\n * contracts by the time a promise could settle; a generator hands the caller an\n * iterator rather than a promise; and `@invariant` runs on every accessor read\n * and write, where nothing can be awaited. Each of those refuses the option\n * where it is written, and a schema arm refuses it too because `validate` is\n * synchronous.\n *\n * A rejected predicate is a failed arm, exactly as a throwing predicate is: the\n * rejection is recorded and composition continues, so a sibling `@demands` arm\n * can still permit the call. Only a value that resolves to `true` or `false`\n * decides anything.\n *\n * The cost is a window: the instance stays reachable across one more await\n * boundary between the precondition and the body, so a concurrent caller can\n * observe it in the state the precondition just approved.\n */\n awaitPredicate?: boolean;\n}\n\n/**\n * The object a predicate is called with.\n *\n * A predicate takes one argument rather than a positional list, so a contract\n * that supplies a field the predicate does not need costs nothing at the call\n * site: the predicate destructures the fields it reads. Each contract publishes\n * a precise version of this shape — `DemandsSubject`, `EnsuresSubject`,\n * `InvariantSubject`, `RescueSubject` — and this is the part the runtime has in\n * common.\n */\nexport interface PredicateSubject {\n /** The instance, replaced with a read-only view before the call. */\n readonly self: unknown;\n readonly [field: string]: unknown;\n}\n\n/**\n * The two subjects a contract arm can observe.\n *\n * A predicate and a schema look at different things even within one contract: an\n * `@ensures` predicate needs the invocation and the historical instance, while a\n * schema in the same position validates the result. Passing both explicitly keeps\n * that difference visible at each call site instead of hiding it behind a\n * convention.\n */\nexport interface ArmSubjects {\n /** The fields a predicate is called with. */\n predicate: () => PredicateSubject;\n /** The value a schema arm validates. */\n schema: () => unknown;\n}\n\n/**\n * True when a value is a `StandardSchemaV1` rather than a predicate.\n *\n * The check is structural: any object exposing a `~standard` property is treated\n * as a schema, which is what makes the protocol provider-agnostic. A predicate is\n * callable and has no such property.\n */\nexport const isSchema = (arm: unknown): arm is StandardSchemaV1 =>\n typeof arm === 'object' && arm !== null && '~standard' in arm;\n\n/**\n * Describes an arm for a failure message.\n *\n * Schemas are identified by vendor because their `String()` form is opaque and\n * the caller needs to know which provider produced the arm.\n */\nexport const describeArm = (arm: unknown): string => {\n if (isSchema(arm)) {\n const { vendor, version } = arm['~standard'];\n\n return `Standard Schema (vendor: ${String(vendor)}, version: ${String(version)})`;\n }\n\n return String(arm);\n}\n\n/**\n * Rejects `normalize` on an arm that cannot honour it.\n *\n * Called at decoration time so an impossible declaration fails where it is\n * written rather than on the first invocation. A predicate reports a verdict, not\n * a replacement value.\n */\nexport const assertNormalizable = (arm: unknown, contract: string, options: ArmOptions | undefined): void => {\n if (!options?.normalize || isSchema(arm)) return;\n\n throw new TypeError(`${contract} cannot normalize: only a Standard Schema arm produces a replacement value.`);\n}\n\n/**\n * Rejects `normalize` on a contract that has nothing to replace.\n *\n * `@invariant` describes the instance, and an invariant predicate or schema answers\n * a question about it; neither produces a value the runtime could substitute. The\n * option was previously accepted here and silently ignored, which reads as a\n * declared intention that is not in force. Rejecting it where it is written keeps\n * the declaration and the behaviour in agreement.\n */\nexport const assertNotNormalizable = (contract: string, options: ArmOptions | undefined): void => {\n if (!options?.normalize) return;\n\n throw new TypeError(`${contract} cannot normalize: its subject is the instance, which no arm can replace.`);\n}\n\n/**\n * Rejects `awaitPredicate` on an arm that cannot answer with a promise.\n *\n * A schema's `validate` that returns a promise is refused when it runs, because\n * contract evaluation is synchronous at that point. Accepting the option on a\n * schema arm would therefore declare that waiting is in force when it is not, so\n * the mistake is refused where it is written rather than on the first call.\n */\nexport const assertAwaitableArm = (arm: unknown, contract: string, options: ArmOptions | undefined): void => {\n if (!options?.awaitPredicate || !isSchema(arm)) return;\n\n throw new TypeError(\n `${contract} cannot declare awaitPredicate on a schema arm: \\`validate\\` is evaluated synchronously, so `\n + 'there is no verdict to await.',\n );\n}\n\n/**\n * Rejects `awaitPredicate` on a contract whose boundaries nothing can await.\n *\n * `@invariant` is evaluated on entry and exit of every feature, on both halves of\n * an accessor, and once after construction. An accessor read has no promise for a\n * caller to await, so the option could only be honoured where it is not needed and\n * silently skipped where it is — an invisible semantic hole in the one contract\n * that is supposed to hold always. Refusing it keeps the declaration and the\n * behaviour in agreement, following `normalize` and `onViolation`.\n */\nexport const assertNotAwaitable = (contract: string, options: ArmOptions | undefined): void => {\n if (!options?.awaitPredicate) return;\n\n throw new TypeError(\n `${contract} cannot declare awaitPredicate: an invariant is evaluated after construction and on every `\n + 'accessor read and write, where there is no promise a caller could await. Declare the option on the arm '\n + 'of an `async` feature instead.',\n );\n}\n\n/**\n * Rejects a factory that is not callable.\n *\n * The return value is checked when the factory runs, because what it produces\n * depends on the violation it is given. What can be checked here is that the\n * declaration names a function at all, which catches the mistake where it is\n * written rather than on the first failed call.\n */\nexport const assertViolationFactory = (contract: string, options: ArmOptions | undefined): void => {\n if (options?.onViolation === undefined || typeof options.onViolation === 'function') return;\n\n throw new TypeError(`${contract} onViolation must be a function that returns an error object.`);\n}\n\n/**\n * Rejects a factory on a contract whose failure cannot carry one.\n *\n * `@invariant` is checked on entry, on exit, and once per construction, and its\n * failure is what tells the lifecycle that the instance is in a state a `@rescue`\n * handler must repair: `isInvariantFailure` in `Contracted.mts` recognises it as an\n * `AssertionError` whose `violation.contract` is `'@invariant'`. An error built by\n * a factory has neither, so a failure it raised would be re-tested, the factory\n * called a second time, and the first error replaced by the second. The repair\n * protocol would then act on an error the handler never saw.\n *\n * `@invariant` also has its own route to a typed error for a failure a feature\n * raises: the entry and exit checks run inside the rescuable scope, so a `@rescue`\n * handler observes the failure and can translate it. The check in `Contracted.new`\n * is outside every handler — the constructor has returned and no feature is in\n * play — so a class whose initial state violates an invariant reports an untyped\n * `AssertionError`. `@demands` has no route at all, because a rejected precondition\n * never enters a body, which is why the factory exists for it.\n */\nexport const assertNotViolationFactory = (contract: string, options: ArmOptions | undefined): void => {\n // Tested against `undefined` rather than for truthiness, so the same declarations\n // `assertViolationFactory` refuses are refused here too: `false`, `0`, `''`, and\n // `null` are not factories on either contract.\n if (options?.onViolation === undefined) return;\n\n throw new TypeError(\n `${contract} cannot declare onViolation: its failure is what signals an unrecoverable instance, `\n + 'so it must stay an AssertionError. Translate it with a `@rescue` handler instead (which does not '\n + 'cover the check in `Contracted.new`).',\n );\n}\n\n/**\n * Picks the factory that decides a contract's error.\n *\n * Scope is per contract rather than per arm, so the arms have to agree on which\n * declaration is authoritative. The **first arm evaluated** wins, matching the rule\n * that the first passing arm decides a normalized value: an arm earlier in the\n * composition is the one whose declaration the contract reads first, and an arm\n * that declares no factory defers to the next.\n *\n * @param entries - The contract's registered arms, in evaluation order.\n */\nexport const selectViolationFactory = (\n entries: ReadonlyArray<{ options?: ArmOptions }>,\n): ViolationFactory | undefined => {\n for (const { options } of entries)\n if (options?.onViolation) return options.onViolation;\n\n return undefined;\n}\n\n/**\n * Rejects `allowWeakening` on a contract that never reports a weakening.\n *\n * The option suppresses a diagnostic about OR-composition, which only a\n * precondition has. On an AND-composed contract it would be a declaration record\n * that says something the runtime has no use for, discoverable only by reading the\n * source, so it is refused at the point it is written rather than silently ignored.\n *\n * This follows the rule the other options already follow: `normalize` is refused\n * where nothing can be replaced and `onViolation` where the failure must stay an\n * `AssertionError`. An option that cannot act is a mistake about which contract\n * the declaration belongs to.\n *\n * The test is for what the option would **do**, not for its presence, so\n * `allowWeakening: false` is accepted: it asks for nothing, exactly as\n * `normalize: false` is accepted on `@invariant`.\n *\n * @param contract - The contract name, for the message.\n * @param options - The declaration's options.\n * @internal\n * Exported only because the AND-composed contract modules live in their own\n * files and import it.\n */\nexport const assertNotWeakenable = (contract: string, options: ArmOptions | undefined): void => {\n if (!options?.allowWeakening) return;\n\n throw new TypeError(\n `${contract} cannot declare allowWeakening: only a precondition can be weakened, because only `\n + '`@demands` is OR-composed. A subclass arm on an AND-composed contract strengthens the obligation '\n + 'and takes effect, so there is no warning to suppress.',\n );\n}\n\n/**\n * The inherited precondition arms a class's new arm composes with.\n *\n * Read from the **metadata object's prototype**, not from\n * `metadata.demands[feature]`. At the moment a decorator runs, that property still\n * holds only what was inherited — the merged list is written afterwards — so both\n * reads agree today. The prototype is used because it is the record the compiler\n * gives each class for exactly this purpose — `Object.create(base[Symbol.metadata]\n * ?? null)` — and it keeps working if a decorator ever runs after another one has\n * already written the merged list.\n *\n * A class with no metadata of its own has a prototype of `null` and reports no\n * inherited arms, which is correct: there is nothing to have weakened.\n *\n * @param metadata - The decorating class's metadata object.\n * @param feature - The feature's name.\n * @internal\n * Exported only because `demands.mts` lives in its own file and imports it. The\n * prototype walk relies on the compiler's metadata emission, which no consumer\n * should build on.\n */\nexport const inheritedArms = (metadata: object | undefined, feature: unknown): readonly unknown[] => {\n const inherited = Object.getPrototypeOf(metadata ?? {}) as\n { demands?: Record<PropertyKey, readonly unknown[]> } | null;\n\n return (inherited?.demands as Record<PropertyKey, readonly unknown[]> | undefined)?.[feature as PropertyKey] ?? [];\n}\n\n/**\n * The features a metadata object has already been warned about.\n *\n * The diagnostic is a property of the feature, and a feature may carry several\n * arms. Each decorator runs independently, so without this a subclass declaring\n * two `@demands` arms on one method prints the same warning twice, which teaches\n * the reader to ignore it. Keyed on the metadata object because that is the object\n * the decorators share, and on the feature within it because one class may have\n * several features, each deserving its own report. A `WeakMap` so it holds nothing\n * alive.\n */\nconst reportedFeatures = new WeakMap<object, Set<unknown>>();\n\n/**\n * Whether this class has already been warned about this feature, marking it if not.\n *\n * Call before reporting, not after: the pair is recorded on the first call, so a\n * class whose arms are evaluated again is not reported again.\n *\n * @param metadata - The decorating class's metadata object.\n * @param feature - The feature's name.\n * @returns Whether a report has already been made for this pair.\n * @internal\n * Exported only because `demands.mts` lives in its own file and imports it.\n */\nexport const alreadyReported = (metadata: object, feature: unknown): boolean => {\n const features = reportedFeatures.get(metadata);\n\n if (features?.has(feature)) return true;\n\n if (features) features.add(feature);\n else reportedFeatures.set(metadata, new Set([feature]));\n\n return false;\n}\n\n/**\n * Describes an inherited precondition that a new arm cannot narrow.\n *\n * A subclass declaring `@demands` reads as a restriction — \"the feature now\n * requires this as well\" — and it is not one. `@demands` is OR-composed, because a\n * subtype may accept wider input but never narrower, so satisfying any inherited\n * arm still permits the call and the new arm decides nothing on its own. The\n * author believes the feature is stricter than it is.\n *\n * Returns `undefined` when the arm is a genuine weakening (nothing inherited to be\n * weaker than) or when the diagnostic is switched off. It **warns** rather than\n * throws by default: a declared arm is always a legal weakening, and the defect is\n * the author's model of it, so refusing the class would break legitimate code. The\n * return value is the message so a stricter policy, or a test, can act on it.\n *\n * `@ensures` and `@invariant` are unaffected: they are AND-composed, so a subclass\n * arm genuinely strengthens the obligation and there is nothing to report. They\n * refuse `allowWeakening` outright; see {@link assertNotWeakenable}.\n *\n * @param contract - The contract name, for the message.\n * @param label - The feature, for the message.\n * @param inherited - The inherited arms this class's arm composes with.\n * @param options - The declaration's options, which may switch the diagnostic off.\n * @internal\n * Exported only because `demands.mts` lives in its own file and imports it. A\n * consumer who wants the warning suppressed sets `allowWeakening`; the message\n * text is not part of the surface.\n */\nexport const reportWeakeningArm = (\n contract: string,\n label: string,\n inherited: readonly unknown[],\n options: ArmOptions | undefined,\n): string | undefined => {\n if (inherited.length === 0 || options?.allowWeakening) return undefined;\n\n const message =\n `${contract} on ${label} adds an arm to a precondition that already has ${inherited.length} inherited `\n + 'arm(s). `@demands` is OR-composed, so this arm cannot narrow what the base permits: satisfying any '\n + 'inherited arm still allows the call. Move the restriction to the base feature, or declare the arm '\n + 'with `allowWeakening` if a genuine weakening is what was meant.';\n\n console.warn(message);\n\n return message;\n}\n\n/**\n * Whether every arm is a schema, so no predicate will be shown the subject.\n *\n * A schema arm is handed the value it validates, never the predicate subject. When\n * *every* arm of a contract is a schema, the fields that exist only for a predicate\n * — `self`, `old`, `oldArgs` — cannot be observed by anything, so the work of\n * producing them is unobservable too. That is a property of the declaration rather\n * than an inference about code, which is what makes it safe to act on.\n *\n * An empty list answers `false`: a contract with no arms evaluates nothing, so there\n * is no snapshot to skip and no reason to claim otherwise.\n *\n * @param arms - The contract's registered arms, in evaluation order.\n */\nexport const observesNoSubject = (arms: readonly { arm: unknown }[]): boolean =>\n arms.length > 0 && arms.every(entry => isSchema(entry.arm));\n\n/**\n * Checks one arm against the subject that belongs to it.\n *\n * @param arm - A predicate or a `StandardSchemaV1` value.\n * @param subjects - What the arm observes, chosen by the calling contract.\n * @param contract - The contract name, for the diagnostic.\n * @param label - Builds the feature's name **for a diagnostic**. A thunk because\n * the name is a declaration read and a string concatenation that a satisfied\n * arm never shows to anyone; see `classNameOf`.\n * @param index - The arm's position in its composition list.\n * @param options - Declaration options for this arm.\n */\nexport const evaluateArm = (\n arm: unknown,\n subjects: ArmSubjects,\n contract: string,\n label: () => string,\n index: number,\n options?: ArmOptions,\n): Admissibility => isSchema(arm)\n ? evaluateSchema(arm, subjects.schema(), contract, label, index, options)\n : evaluatePredicate(\n arm as (...args: any[]) => unknown,\n subjects.predicate(),\n contract,\n label,\n index,\n options,\n );\n\n/**\n * Checks one arm, awaiting a predicate that was declared awaitable.\n *\n * The only difference from {@link evaluateArm} is that a predicate declared\n * awaitable has its verdict awaited. Every other arm is decided synchronously, so\n * a predicate that returns a promise without the option is still refused by the\n * strict-boolean rule rather than quietly awaited — on an `async` feature as much\n * as anywhere else.\n *\n * Awaiting decides when the verdict arrives, not what it means: a rejection is a\n * failed arm with the reason in `thrown`, and a resolution that is not a boolean\n * is still a defect rather than a decision.\n */\nexport const evaluateArmAsync = async (\n arm: unknown,\n subjects: ArmSubjects,\n contract: string,\n label: () => string,\n index: number,\n options?: ArmOptions,\n): Promise<Admissibility> => {\n if (isSchema(arm))\n return evaluateSchema(arm, subjects.schema(), contract, label, index, options);\n\n const predicate = arm as (...args: any[]) => unknown,\n subject = subjects.predicate();\n\n return options?.awaitPredicate\n ? awaitPredicate(predicate, subject, contract, label, index)\n : evaluatePredicate(predicate, subject, contract, label, index, options);\n};\n\n/**\n * Applies a predicate arm whose verdict may be a promise.\n *\n * The read-only view and the guarded call are shared with {@link evaluatePredicate}\n * through {@link invokePredicate}; only the settlement differs. A rejection is\n * caught here for the same reason a synchronous throw is caught there: an arm that\n * could not answer has not *permitted* anything, and propagating would make a\n * legal sibling arm unreachable.\n */\nconst awaitPredicate = async (\n predicate: (...args: any[]) => unknown,\n subject: PredicateSubject,\n contract: string,\n label: () => string,\n index: number,\n): Promise<Admissibility> => {\n let verdict: unknown;\n\n try {\n verdict = await invokePredicate(predicate, subject);\n } catch (thrown) {\n return { ok: false, thrown };\n }\n\n return { ok: assertContractResult(verdict, contract, label, index) };\n}\n\n/**\n * Calls a predicate with the guarded subject.\n *\n * The synchronously evaluated arm and the awaited one must observe the same\n * thing — the read-only view of `self`, and every other field untouched — so the\n * call is made in one place. Two copies would be free to disagree about which\n * fields are guarded.\n */\nconst invokePredicate = (predicate: (...args: any[]) => unknown, subject: PredicateSubject): unknown => {\n // Only `self` is guarded, and the guard is a property of the field rather\n // than of its position. Every other field describes the invocation rather\n // than the instance: `args` and `result` are readable data shared with the\n // caller, `old` is a detached copy taken by `populateOld`, and `error` and\n // `retry` belong to `@rescue`, which is exempt from the view because\n // restoring corrupted state is its purpose.\n //\n // The guarded subject is built with one spread and an override rather than by\n // destructuring `self` out and spreading the remainder: the two produce the same\n // object, and the rest half of a destructuring pattern re-enumerates every key\n // into a second object for no gain.\n return predicate(typeof subject.self === 'object' && subject.self !== null\n ? { ...subject, self: readOnlyView(subject.self) }\n : subject);\n}\n\n/**\n * Applies a predicate arm, reusing the strict-boolean rule from #283.\n *\n * Reusing `assertContractResult` keeps the diagnostic identical whether the\n * predicate was declared on its own or alongside a schema.\n *\n * The instance is passed as a read-only view through {@link invokePredicate}. A\n * predicate answers a question, so it must not be able to change the state it is\n * asked about — see `read-only.mts` for why this is a scoped proxy rather than\n * `Object.freeze`. The view is applied at the call rather than by the caller so\n * that a predicate can never be invoked with the raw target by mistake.\n */\nconst evaluatePredicate = (\n predicate: (...args: any[]) => unknown,\n subject: PredicateSubject,\n contract: string,\n label: () => string,\n index: number,\n options: ArmOptions | undefined,\n): Admissibility => {\n // A predicate that throws has answered \"no\": the call it guards must not be\n // denied on its say-so when a sibling arm permits it. The value is carried in\n // `thrown` rather than propagated, so the contract can decide whether it still\n // matters once every arm has been evaluated.\n let verdict: unknown;\n\n try {\n verdict = invokePredicate(predicate, subject);\n } catch (thrown) {\n return { ok: false, thrown };\n }\n\n // The arm may declare `awaitPredicate` on a feature that is not `async`: a\n // subclass can override an async feature with a synchronous one while the\n // metadata record still carries the inherited arm. Nothing at this boundary can\n // wait, so the verdict is named for what it is rather than reported as a\n // predicate that forgot to return a boolean.\n if (options?.awaitPredicate && typeof (verdict as { then?: unknown } | null)?.then === 'function')\n throw new TypeError(\n `${contract} predicate #${index + 1} for ${label()} declared awaitPredicate but returned a Promise, `\n + 'and the feature it guards is not `async`, so nothing can await it. Declare the feature `async`, '\n + 'or drop the option.',\n );\n\n // The verdict is validated outside the guard, because a non-boolean return is a\n // defect in the predicate rather than a decision about the call: a Promise is\n // truthy, so treating it as a failed arm would let a sibling excuse a contract\n // that never ran. That is the rule `assertContractResult` exists to enforce, and\n // it stays fatal.\n return { ok: assertContractResult(verdict, contract, label, index) };\n};\n\n/**\n * Applies a schema arm by calling its `validate`.\n *\n * A `validate` that returns a Promise is refused. Contract evaluation is\n * synchronous, so an asynchronous schema has decided nothing at the point where\n * the verdict is needed; treating it as satisfied would be worse than failing,\n * and awaiting would move the feature's boundary.\n */\nconst evaluateSchema = (\n schema: StandardSchemaV1,\n subject: unknown,\n contract: string,\n label: () => string,\n index: number,\n options: ArmOptions | undefined,\n): Admissibility => {\n const result = schema['~standard'].validate(subject) as any;\n\n if (typeof result?.then === 'function')\n throw new TypeError(\n `${contract} schema #${index + 1} for ${label()} returned a Promise; `\n + 'contract evaluation is synchronous, so use a synchronous schema.',\n );\n\n if (result.issues)\n return { ok: false, issues: result.issues as ReadonlyArray<StandardSchemaV1.Issue> };\n\n return options?.normalize ? { ok: true, value: result.value } : { ok: true };\n}\n\n/**\n * The arms that rejected a call, gathered across a composition loop.\n *\n * The three contracts differ in their composition rule but not in what they\n * record about a rejected arm: its index, any issues a schema reported, and the\n * value a throwing predicate raised. Collecting it in one place keeps the loops\n * about their rule rather than about bookkeeping.\n */\nexport interface ArmFailures {\n failed: number[];\n thrown: { index: number, value: unknown }[];\n issues: StandardSchemaV1.Issue[];\n}\n\n/** Starts an empty record for a composition pass. */\nexport const armFailures = (): ArmFailures => ({ failed: [], thrown: [], issues: [] });\n\n/**\n * Records one rejected arm.\n *\n * A throwing arm also lands in `failed`: it rejected the call, and the\n * distinction the caller needs is `thrown`, not whether the arm was counted.\n */\nexport const recordFailure = (failures: ArmFailures, index: number, result: Admissibility): void => {\n failures.failed.push(index);\n\n if (result.issues) failures.issues.push(...result.issues);\n if ('thrown' in result) failures.thrown.push({ index, value: result.thrown });\n};\n\n/**\n * A failure record that is allocated only once an arm rejects.\n *\n * A satisfied composition is the common case, and it would otherwise allocate three\n * arrays it never reads. The log hands back the same interface as {@link ArmFailures},\n * so the composition loops keep their rule rather than their bookkeeping, and\n * `entries` stays `undefined` until something fails — which is the whole test a loop\n * needs at the end.\n *\n * The methods live on the prototype rather than in a closure per call, because a\n * closure pair allocated on every invocation costs more than the three arrays it is\n * there to avoid.\n */\nexport class FailureLog {\n #entries: ArmFailures | undefined;\n\n /** Records a rejected arm, allocating the record on the first one. */\n record(index: number, result: Admissibility): void {\n recordFailure(this.#entries ??= armFailures(), index, result);\n }\n\n /** The record, or `undefined` when no arm has rejected. */\n get entries(): ArmFailures | undefined { return this.#entries; }\n}\n\n/** Starts a failure log that allocates its record only when something fails. */\nexport const failureLog = (): FailureLog => new FailureLog();\n\n/**\n * Renders schema `issues` for a message.\n *\n * A path is reported as a dotted trail of keys, matching how the providers\n * describe a nested failure themselves.\n */\nexport const describeIssues = (issues: ReadonlyArray<StandardSchemaV1.Issue>): string =>\n issues\n .map(issue => {\n const path = (issue.path ?? [])\n .map(segment => typeof segment === 'object' && segment !== null ? segment.key : segment)\n .join('.');\n\n return path ? `${path}: ${issue.message}` : issue.message;\n })\n .join('; ');\n","import { AssertionError, type ContractKind, type ContractViolation } from \"./AssertionError.mjs\";\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\nimport { isSchema, type ArmFailures, type ViolationFactory } from './admissibility.mjs';\n\n/**\n * An assertion is an expression of a property that must be true at a particular\n * point of step of program execution. It consists of a boolean expression\n * and a message. This function tests the provided condition. If the condition\n * is false an AssertionError is raised with an optional message.\n * If the provided condition is true then the function returns without raising an error\n *\n * @param condition - The condition to test. If it is false an error is raised.\n * @param message - The message to display if the condition is false. If not provided a default message is used.\n * @throws {AssertionError} If the condition is false an AssertionError is raised.\n *\n * @example\n * ```ts\n * import assert from \"assert.mjs\";\n *\n * let x = 15;\n * assert(x > 5, `Expected: x > 5. Actual: x = ${x}`);\n * ```\n */\n\nexport function assert(condition: unknown, message: string = 'Assertion Error'): asserts condition {\n if (Boolean(condition) == false)\n throw new AssertionError(message);\n}\n\nconst describeContractResult = (value: unknown): string => {\n if (typeof value === 'object' && value !== null && typeof (value as any).then === 'function')\n return 'a Promise (contract predicates must be synchronous)';\n if (typeof value === 'string') return `the string ${JSON.stringify(value)}`;\n if (value === undefined) return 'undefined';\n if (value === null) return 'null';\n if (typeof value === 'object') return `an object (${Object.prototype.toString.call(value)})`;\n\n return `a ${typeof value} (${String(value)})`;\n}\n\n/**\n * Asserts that a contract predicate returned a `boolean`.\n *\n * Contract predicates must return a boolean. Coercing the result would silently\n * accept a non-boolean, which is how an accidentally asynchronous predicate\n * passes: a `Promise` is always truthy. Treating a contract that never actually\n * ran as satisfied is worse than failing, so a non-boolean result raises an\n * `AssertionError` naming the contract, the feature, and the predicate index.\n *\n * @param result - The value returned by the predicate.\n * @param contract - The name of the contract, e.g. `@demands`.\n * @param label - Builds a human-readable description of the feature, e.g.\n * `Foo.method`. A thunk so the name is resolved only for the message it appears\n * in: a boolean verdict is the common case and never reads it.\n * @param index - The zero-based index of the predicate in its composition list.\n * @returns The predicate result, narrowed to `boolean`.\n * @throws {AssertionError} If the predicate did not return a boolean.\n */\nexport function assertContractResult(\n result: unknown,\n contract: string,\n label: () => string,\n index: number,\n): boolean {\n // A boolean is the case this function exists to pass through, so the message is\n // built only when it is about to be thrown. Naming the feature is a declaration\n // read and a concatenation, which a passing verdict pays for nothing.\n if (typeof result === 'boolean') return result;\n\n throw new AssertionError(\n `${contract} predicate #${index + 1} for ${label()} returned `\n + `${describeContractResult(result)}; contract predicates must return a boolean`\n );\n}\n\nconst pluralise = (count: number, total: number, singular: string, plural: string): string =>\n `${count} of ${total} ${total === 1 ? singular : plural}`;\n\n/**\n * Describes a value an arm threw, for the violation record.\n *\n * The record holds a description rather than the value, so that a violation stays\n * plain data and cannot keep the consumer's error alive or make itself\n * unserialisable (see {@link ContractViolation.thrown}). An object is named by its\n * constructor and message, which is what a reader needs to tell a deliberate\n * `Denied` from a `TypeError` raised by a bug.\n */\nconst describeThrown = (value: unknown): string => {\n if (typeof value === 'object' && value !== null) {\n const named = value as { name?: unknown, message?: unknown },\n name = typeof named.name === 'string' ? named.name : value.constructor?.name ?? 'Object',\n message = typeof named.message === 'string' ? named.message : '';\n\n return message ? `${name}: ${message}` : name;\n }\n\n return String(value);\n};\n\n/**\n * Renders the failing arms for a message.\n *\n * Predicates and schemas are both arms of the same composition, so each is named\n * as whichever it actually is. Calling a schema a predicate would be wrong;\n * calling a predicate an arm would be vaguer than the caller needs. An arm that\n * threw is marked, so a reader can tell a thrown value from a `false` verdict\n * without unpacking the violation.\n */\nconst describeArms = (\n arms: readonly unknown[],\n failedIndices: number[],\n predicates: string[],\n thrownIndices: ReadonlySet<number>,\n): string => predicates\n .map((source, position) => {\n const index = failedIndices[position],\n noun = isSchema(arms[index]) ? 'schema' : 'predicate',\n how = thrownIndices.has(index) ? ' threw' : '';\n\n return `${noun} #${index + 1}${how}: ${source}`;\n })\n .join('; ');\n\n/**\n * Renders one schema issue, including its path when the provider supplied one.\n *\n * A path is shown as a dotted trail of keys, which is how the providers describe\n * a nested failure themselves.\n */\nconst describeIssue = (issue: StandardSchemaV1.Issue): string => {\n const path = (issue.path ?? [])\n .map(segment => typeof segment === 'object' && segment !== null ? segment.key : segment)\n .join('.');\n\n return path ? `${path}: ${issue.message}` : issue.message;\n}\n\n/**\n * Builds a message for a failed contract and describes it structurally.\n *\n * Every contract reports the same way: which contract failed, on which feature,\n * which arm(s) failed, and how each one is described. A caller can use the\n * returned violation instead of parsing the message.\n *\n * @param contract - Which contract failed.\n * @param className - The class the contract belongs to.\n * @param feature - The feature the contract belongs to, absent for `@invariant`.\n * @param arms - The full composition list, so indices are meaningful.\n * @param failedIndices - The indices in `arms` that failed.\n * @param summary - A per-contract description of what the failure means.\n * @param issues - `issues` reported by failing schema arms, if any.\n * @param describe - Renders one arm for the message.\n * @returns The message and the structured violation.\n */\nexport function describeViolation(\n contract: ContractKind,\n className: string,\n feature: string | undefined,\n arms: readonly unknown[],\n failedIndices: number[],\n summary: string,\n issues?: ReadonlyArray<StandardSchemaV1.Issue>,\n describe: (arm: unknown) => string = String,\n thrown?: ReadonlyArray<{ index: number, value: unknown }>,\n): { message: string, violation: ContractViolation } {\n const thrownIndices = thrown?.map(entry => entry.index),\n thrownDescriptions = thrown?.map(entry => describeThrown(entry.value));\n\n const violation: ContractViolation = {\n contract,\n className,\n feature,\n failedIndices,\n predicates: failedIndices.map(index => describe(arms[index])),\n ...(thrownIndices && thrownIndices.length > 0\n ? { thrownIndices, thrown: thrownDescriptions }\n : {}),\n ...(issues && issues.length > 0 ? { issues } : {}),\n };\n\n return { message: describeMessage(contract, violation, arms, summary, issues), violation };\n}\n\n/**\n * Assembles the human-readable half of a contract failure.\n *\n * The structured `violation` carries the same facts for a caller that will branch\n * on them; this string exists for the reader who only ever sees the message, so it\n * names the feature, the unsatisfied arms, anything the failing schemas reported,\n * and what the failure means for the contract.\n */\nconst describeMessage = (\n contract: ContractKind,\n violation: ContractViolation,\n arms: readonly unknown[],\n summary: string,\n issues: ReadonlyArray<StandardSchemaV1.Issue> | undefined,\n): string => {\n const where = violation.feature === undefined\n ? violation.className\n : `${violation.className}.${violation.feature}`,\n threw: ReadonlySet<number> = new Set(violation.thrownIndices ?? []),\n detail = describeArms(arms, violation.failedIndices, violation.predicates, threw),\n noun = (arm: unknown) => isSchema(arm) ? 'schema' : 'predicate',\n nounPlural = (arm: unknown) => isSchema(arm) ? 'schemas' : 'predicates',\n count = pluralise(violation.failedIndices.length, arms.length, noun(arms[0]), nounPlural(arms[0])),\n // Schema arms report `issues` rather than a true/false verdict, so the\n // provider's own explanation is carried into the message. A caller reading\n // only the message still learns which field was rejected and why.\n reported = issues && issues.length > 0\n ? ` Reported: ${issues.map(issue => describeIssue(issue)).join('; ')}.`\n : '';\n\n return `${contract} failed for ${where} (${count} unsatisfied: ${detail}).${reported} ${summary}`;\n};\n\n/**\n * Builds the error for a contract whose arms were not satisfied.\n *\n * Every contract reports the same way — a message naming the feature and the\n * arms that failed, plus the structured violation — so the identical\n * `describeViolation` + `throw new AssertionError` tail is produced here instead\n * of being written in each of `@invariant`, `@demands`, and `@ensures`.\n *\n * The composition rule stays with each contract, because it is not shared:\n * `@demands` is OR-composed (a subtype may weaken a precondition) while\n * `@invariant` and `@ensures` are AND-composed.\n */\nexport function violationError(\n contract: ContractKind,\n className: string,\n feature: string | undefined,\n arms: readonly unknown[],\n failedIndices: number[],\n summary: string,\n issues?: ReadonlyArray<StandardSchemaV1.Issue>,\n describe: (arm: unknown) => string = String,\n thrown?: ReadonlyArray<{ index: number, value: unknown }>,\n): AssertionError {\n const { message, violation } = describeViolation(\n contract, className, feature, arms, failedIndices, summary, issues, describe, thrown);\n\n return new AssertionError(message, violation);\n}\n\n/**\n * The errors this module has already annotated.\n *\n * Kept so a reused error instance can be recognised as ours and updated, while an\n * error carrying a `cause` of its own is never overwritten. A `WeakMap`-style\n * record is used because the error belongs to the consumer: this must not keep it\n * alive.\n */\nconst annotated = new WeakSet<object>();\n\n/**\n * Records a contract failure on an error the contract did not create.\n *\n * A predicate's error is the consumer's object. Three things follow, and all are\n * about not damaging it:\n *\n * - **The record is only added to an extensible object.** A frozen or non-extensible\n * error cannot accept it, and a refusal is silent: the caller still receives the\n * error they were waiting for, which is the outcome that matters.\n * - **A `cause` the consumer set is never overwritten.** An error constructed with\n * its own `cause` uses it to record what actually went wrong underneath;\n * replacing it with the contract's diagnostic would destroy the information\n * `cause` exists to carry. A record this module wrote earlier *is* replaced, so\n * that a reused error reports the contract that raised it now rather than the\n * first one it was thrown from.\n * - **`defineProperty` is used rather than assignment**, so the record is\n * non-enumerable. A domain error that serialises its own properties for logging\n * must not suddenly gain a contract record it never asked for.\n * - **A violation the factory supplied is kept.** The factory is handed the record,\n * so it may carry a narrowed or extended one. What counts as supplying one is a\n * **value**, not an own property: an optional parameter property on the error class\n * holds `undefined` until it is assigned, and treating that as a deliberate\n * omission would strip the error of the record the factory exists to deliver.\n */\nconst annotate = (\n raised: object,\n violation: ContractViolation,\n cause: AssertionError,\n fromFactory = false,\n): void => {\n if (!Object.isExtensible(raised)) return;\n\n const mine = annotated.has(raised),\n supplied = (key: 'violation' | 'cause'): boolean => {\n if (mine || !Object.hasOwn(raised, key)) return false;\n\n return !(fromFactory && key === 'violation' && (raised as { violation?: unknown }).violation === undefined);\n };\n\n for (const [key, value] of [['violation', violation], ['cause', cause]] as const)\n if (!supplied(key))\n Object.defineProperty(raised, key, {\n value,\n enumerable: false,\n configurable: true,\n });\n\n annotated.add(raised);\n};\n\n/**\n * Builds the value a declared factory raises.\n *\n * Split from {@link violationFailure} because what it decides is independent of\n * which contract failed: the factory is the caller's own choice of error type, and\n * the only thing this library adds to what it returns is the record it was given.\n *\n * A returned primitive has nowhere to hold either attachment, so it is refused here\n * rather than silently degrading the report — the caller would otherwise receive a\n * value they cannot inspect. Anything `typeof` calls an object is accepted, so an\n * array passes and carries both fields; narrowing further would reject a\n * consumer's own error-like object for no gain, since the fields are attached\n * whether or not it extends `Error`.\n *\n * @param label - The contract, feature, and class, for the diagnostic.\n * @param error - The `AssertionError` describing every unsatisfied arm.\n */\nconst factoryFailure = (\n label: string,\n violation: ContractViolation,\n error: AssertionError,\n factory: ViolationFactory,\n): unknown => {\n const raised = factory(violation);\n\n if (typeof raised !== 'object' || raised === null)\n throw new TypeError(\n `${label} returned ${typeof raised}; it must return an object so the violation can be attached.`,\n // The defect replaces the contract failure at the caller, so the\n // failure travels as `cause`: what the factory was asked to report is\n // still readable.\n { cause: error },\n );\n\n // The violation and the describing `AssertionError` are attached by the same\n // defensive rules a re-raised predicate error gets, so a factory error that\n // carries its own `cause` keeps it. A violation the factory supplied itself\n // also wins, because the factory was given the record and may have narrowed or\n // extended it.\n annotate(raised, violation, error, true);\n\n return raised;\n};\n\n/**\n * Builds the value a contract raises when every arm has failed.\n *\n * A thrown arm is a failed arm, so when every arm failed and at least one of them\n * threw, that value is what the caller receives. A typed error survives the\n * composition it could not otherwise reach, and a predicate bug still surfaces as\n * the bug it is rather than as an `AssertionError` describing a contract.\n *\n * The **first arm that threw** wins, matching the rule that the first arm\n * evaluated decides a normalized value. Arm order is the composition list's, which\n * for one class is reverse source order because decorators evaluate bottom-up, and\n * which places inherited arms before a subclass's own.\n *\n * When no arm threw, the failure is a verdict rather than a fault and an\n * `AssertionError` carrying the full violation is raised as usual.\n *\n * A declared {@link ViolationFactory} supersedes both rules, because it is the\n * caller's explicit choice of error type and it receives the violation — including\n * `thrownIndices` — so nothing is lost by preferring it. It runs only here, after\n * every arm has been evaluated, which is the one point where the failure is final.\n *\n * @param factory - The contract's declared factory, if any arm declared one.\n * @internal\n * Exported only because the three contract modules live in their own files and\n * import it. It takes an `ArmFailures`, which is not part of the published surface,\n * so a consumer cannot call it without reaching into the library's internals.\n */\nexport function violationFailure(\n contract: ContractKind,\n className: string,\n feature: string | undefined,\n arms: readonly unknown[],\n failures: ArmFailures,\n summary: string,\n describe: (arm: unknown) => string = String,\n factory?: ViolationFactory,\n): unknown {\n const error = violationError(\n contract, className, feature, arms, failures.failed, summary,\n failures.issues, describe, failures.thrown),\n violation = error.violation as ContractViolation;\n\n if (factory)\n return factoryFailure(\n `${contract} onViolation for ${feature === undefined ? className : `${className}.${feature}`}`,\n violation, error, factory,\n );\n\n if (failures.thrown.length === 0) return error;\n\n const raised = failures.thrown[0].value;\n\n // A thrown primitive has nowhere to carry the payload, and replacing it with a\n // wrapper would change the value the contract chose to raise.\n if (typeof raised === 'object' && raised !== null)\n annotate(raised, violation, error);\n\n return raised;\n}\n","/**\n * Biconditional.\n * p ↔ q.\n * \"P if and only if Q\".\n * An example of usage is the encoding of \"You can ride the train if and only if you have a ticket\"\n * This is logically equivalent to: implies(p,q) && implies(q,p)\n *\n * @param p - The first boolean value (the antecedent).\n * @param q - The second boolean value (the consequent).\n * @returns - The result (biconditional) of p and q, always a `boolean`.\n *\n * A non-boolean operand is coerced rather than rejected, because the parameters are\n * already `boolean`: a typed non-boolean operand does not compile. The coercion\n * therefore decides only what a value that reached the helper through `any` or\n * untyped JavaScript means, and there it is the ordinary JavaScript rule — a truthy\n * operand answers `true` rather than being named.\n *\n * A contract names a non-boolean *result*, but it cannot see inside the helper to\n * name an operand. State a contract through this helper only when both operands are\n * already booleans, or write the comparison directly instead.\n *\n * @example\n * ```ts\n * import { iff } from '@final-hill/decorator-contracts';\n *\n * // You can ride the train if and only if you have a ticket\n * iff(person.hasTicket, person.ridesTrain)\n * ```\n */\n\nexport function iff(p: boolean, q: boolean): boolean {\n // Coerced rather than returned directly. `(p && q) || (!p && !q)` is\n // logically correct but returns an *operand* rather than a boolean, so a\n // truthy non-boolean operand (`iff(true, someObject)`) would leak through a\n // signature that promises `boolean`. The leak only appears when the\n // non-boolean sits on the returned side of the short-circuit, which is why it\n // is easy to miss in testing.\n return Boolean((p && q) || (!p && !q));\n}\n","/**\n * Material Implication.\n * `p → q`\n * Also referred to as `if-then`.\n * An example of usage is the encoding of \"sunny weather is a precondition of visiting the beach\"\n * This is logically equivalent to: !p || q\n *\n * @param p - The first boolean value (the antecedent).\n * @param q - The second boolean value (the consequent).\n * @returns - The result (material implication) of p and q, always a `boolean`.\n *\n * A non-boolean consequent is coerced rather than rejected, because the parameters\n * are already `boolean`: a typed non-boolean operand does not compile. The coercion\n * therefore decides only what a value that reached the helper through `any` or\n * untyped JavaScript means, and there it is the ordinary JavaScript rule — a truthy\n * operand answers `true` rather than being named.\n *\n * A contract names a non-boolean *result*, but it cannot see inside the helper to\n * name an operand. State a contract through this helper only when both operands are\n * already booleans, or write the comparison directly instead.\n *\n * @example\n * ```ts\n * import { implies } from '@final-hill/decorator-contracts';\n *\n * // Sunny weather is a precondition of visiting the beach\n * implies(weather.isSunny, person.visitsBeach)\n * ```\n */\n\nexport function implies(p: boolean, q: boolean): boolean {\n // Coerced for the same reason as `iff`: `!p || q` returns the operand `q`\n // when `p` is falsy, so a truthy non-boolean would escape a `boolean` return.\n return !p || Boolean(q);\n}\n","/**\n * The name a class reports in a contract violation, and how it is resolved.\n *\n * `Class.name` is whatever the consumer's build emitted. The standard decorator\n * lowering wraps a decorated class in an immediately invoked arrow that returns a\n * **class expression**, which a compressor is free to leave anonymous, so the\n * reported name degrades with the build: correct when the bundle is unminified, a\n * short identifier when it is not, and empty when the compressor dropped the name\n * outright.\n *\n * There is no earlier moment with a better name. The class object is created once,\n * and the name a class decorator observes is the same name the violation would\n * report later, so capturing it at decoration time cannot improve it. Only a\n * declaration by the consumer is independent of the build.\n *\n * Declaring one makes the name stable no matter how the bundle is minified, which\n * is what a production `className`, message, or `onViolation` factory needs:\n *\n * ```typescript\n * import { Contracted, contractName } from '@final-hill/decorator-contracts';\n *\n * class Cart extends Contracted {\n * static [contractName] = 'Cart';\n * }\n * ```\n *\n * A name is declared rather than inherited. `checkedMode` and `encapsulationMode`\n * inherit because they answer how a class *behaves*, and a subclass that says\n * nothing about behaviour should behave like its base. A name answers who the class\n * *is*, so an inherited one would label every subclass's violations with the base's\n * name.\n *\n * Set it **through the class**: it is read from the constructor, so a write to an\n * instance has no effect. Unlike the enforcement switches there is nothing to\n * refuse — a name that does not take effect removes no guarantee.\n *\n * Nothing here imports `Contracted`, so every contract module and the proxy can use\n * it without an import cycle.\n */\nexport const contractName = Symbol.for('Contracted.contractName');\n\n/**\n * The name to report for `Class` in a contract violation.\n *\n * An own {@link contractName} declaration wins, so a class that declares one is\n * named stably whatever the build did to its class name. Otherwise `Class.name` is\n * reported, which is what the consumer's build emitted.\n *\n * **Own, not inherited**, for the reason {@link contractName} gives. The fallback\n * is also what makes ownership meaningful: a subclass that declares no name reports\n * itself rather than the base whose name it inherited.\n *\n * The declared value is used only when it is a non-empty string, so a declaration\n * that resolves to `undefined` or `''` falls back to `Class.name` rather than\n * producing an empty label. An empty name would render as\n * `@demands failed for .withdraw`, which is the failure this symbol exists to\n * prevent and must not be reachable through a mistyped declaration.\n *\n * A declaration that throws is not a name either. The lookup is wrapped for that\n * reason: a contract failure is the outcome the caller is waiting for, and a\n * declaration is read on the way to reporting it, so a throwing accessor must not\n * replace the failure with its own error. The constructor name is what is left.\n *\n * @param Class - The class to name, passed as the constructor itself (`Cart`).\n * `instance.constructor` is the same object and may be passed instead, but a\n * caller that already holds the class needs no instance to name it.\n * @internal\n * Exported only because the contract modules and the proxy live in their own files\n * and import it. Read {@link contractName} instead; it is the published surface.\n */\nexport const classNameOf = (Class: unknown): string => {\n if (typeof Class !== 'function') return '';\n\n try {\n const declared = Object.hasOwn(Class, contractName)\n ? (Class as { [contractName]?: unknown })[contractName]\n : undefined;\n\n if (typeof declared === 'string' && declared.length > 0) return declared;\n } catch {\n // Fall through to the constructor name; see the docblock.\n }\n\n return (Class as { name: string }).name;\n};\n","/*\n * How a contracted instance describes itself to a debugger.\n *\n * https://github.com/final-hill/decorator-contracts/issues/341\n *\n * Without this, `util.inspect` falls back to the proxy's own rendering, which shows\n * the wrapper rather than the instance:\n *\n * ```text\n * Proxy(Account { _balance: 5, _orgId: 'o' })\n * ```\n *\n * The state is readable there but it is labelled as a proxy, so a reader cannot\n * tell a contracted instance from an accidental one, and a nested instance renders\n * the same way again. `util.inspect` honours a `nodejs.util.inspect.custom` method\n * instead, so one is provided here.\n *\n * ### Why this reads descriptors rather than properties\n *\n * Two facts decide the implementation, and both were measured.\n *\n * `inspect` looks the method up **through the proxy**, so it is the runtime's\n * wrapped feature that is invoked. Node calls that function itself, however,\n * rather than reading the property a second time — a direct\n * `instance[inspectKey]()` runs the contract lifecycle twice, while\n * `inspect(instance)` runs it zero times.\n *\n * A method that therefore read `this._balance` would run a getter through the\n * proxy when one exists, and `inspect` would then throw for exactly the instance a\n * reader is trying to look at. Reading own property **descriptors** instead is\n * outside every trap, which is what a diagnostic surface needs: it reports the\n * state the object holds and cannot fail because a contract does.\n *\n * ### What is shown\n *\n * The class name and the instance's own state, including the `_`-prefixed fields\n * the library's convention marks private. That is the intent here: `inspect` is the\n * surface a developer uses to see what an object actually holds, and hiding the\n * state would make it useless for the one purpose it has. It is not a serialization\n * format — see `serialization.mts` for why that is a separate, opt-in decision.\n */\n\nimport { classNameOf } from './name.mjs';\n\n/**\n * The key `util.inspect` looks a custom method up under.\n *\n * This is not a name of this library's choosing: `util.inspect` asks the object for\n * one specific symbol, and `Symbol.for('nodejs.util.inspect.custom')` resolves to\n * it. A symbol made with `Symbol(…)` would be a key nothing looks up, so the method\n * would be inherited by every class and never called.\n *\n * `Symbol.for` rather than importing `node:util` because the registry is shared: a\n * consumer overriding the rendering, and a second copy of this library, both resolve\n * to the same key. Importing the symbol would also make `node:util` a dependency of\n * the module graph, which this library otherwise does not have.\n *\n * Module-private: only the installation site needs it, and a consumer that wants to\n * override the rendering derives the same key from `Symbol.for`.\n */\nconst inspectKey = Symbol.for('nodejs.util.inspect.custom');\n\n/**\n * What Node renders in place of a value it has been asked not to descend into.\n *\n * Matches the text `util.inspect` produces itself once the depth budget is spent,\n * so a nested instance is abbreviated the same way a nested plain object is.\n */\nconst NOT_DESCENDED = '[Object]';\n\n/**\n * The instances on the current descent.\n *\n * A reference back to an ancestor would recurse without end, and the ancestry\n * cannot be carried in `options`: Node builds a fresh options object for every\n * level and drops any key it does not know, which was verified. Tracking it here\n * is what keeps a self-referential instance from overflowing the stack.\n *\n * The cost of a module-wide record is that a nested custom inspector which inspects\n * an ancestor sees it still registered and is reported as `[Circular]` even though\n * it is not one. That shape recurses without end under `util.inspect` itself, so a\n * marker is the safer answer; it is recorded here rather than presented as parity.\n */\nconst rendering = new Set<object>();\n\n/**\n * The own state of `instance`, as the constructor holds it.\n *\n * `Object.getOwnPropertyDescriptors` neither invokes an accessor nor passes through\n * a trap, so this reports what the object holds without running a contract. An\n * accessor is skipped because it holds no state: reading it is exactly the\n * contract-running operation this file exists to avoid, and its value is already\n * visible through the field it reads.\n *\n * @param instance - The instance being described.\n * @returns A key/value list of the own data properties.\n */\nconst ownState = (instance: object): Array<[string, unknown]> =>\n Object.entries(Object.getOwnPropertyDescriptors(instance))\n .filter(([, descriptor]) => 'value' in descriptor)\n .map(([key, descriptor]) => [key, descriptor.value]);\n\n/**\n * Renders an instance for `util.inspect`.\n *\n * The name is the class's declared one when it has one, and the constructor's\n * otherwise — the same rule every violation message follows, so a class that named\n * itself is named the same way in a debugger as in a failure. The state is read\n * from own descriptors, so no contract runs and no accessor can throw.\n *\n * @param depth - How many levels of nesting `util.inspect` will show; `null` means\n * unlimited.\n * @param options - The options in force for this inspection.\n * @param inspect - Renders a value with those options, used to recurse.\n * @returns The class name with the instance's own state.\n * @internal\n * Installed on `Contracted.prototype` by `installInspect`; exported so a test can\n * call it directly with the arguments `util.inspect` would pass.\n */\nexport const inspectInstance = function (\n this: object,\n depth: number | null,\n options: object,\n inspect: (value: unknown, options: object) => string,\n): string {\n // `null` is the unlimited depth `util.inspect` uses by default.\n const remaining = depth === null ? Infinity : depth;\n\n // Node abbreviates a value it has no budget left to descend into, and it counts\n // the instance itself as shown at `depth: 0`, so only a spent budget is\n // abbreviated. Treating `0` as spent would report the instance the caller asked\n // about as `[Object]`.\n if (remaining < 0) return NOT_DESCENDED;\n\n // A reference back to an instance already on this descent would recurse without\n // end; see `rendering`.\n if (rendering.has(this)) return '[Circular]';\n\n rendering.add(this);\n\n try {\n // `getPrototypeOf` is not trapped, so this is the class the consumer\n // declared rather than the proxy's wrapper for it.\n const name = classNameOf(Object.getPrototypeOf(this)?.constructor),\n rendered = ownState(this).map(([key, value]) =>\n `${key}: ${inspect(value, { ...options, depth: remaining - 1 })}`);\n\n return rendered.length === 0 ? `${name} {}` : `${name} { ${rendered.join(', ')} }`;\n } finally {\n rendering.delete(this);\n }\n};\n\n/**\n * Installs the rendering on a class prototype.\n *\n * On the prototype rather than on each instance, so a class pays nothing per\n * instance and a subclass may override it by declaring its own method under the same\n * key.\n *\n * Defined rather than assigned so the property is fixed in place: a caller cannot\n * swap the rendering without the class knowing. `enumerable: false` states the\n * intent — `for...in` never enumerates a symbol key either way, so it changes what a\n * loop sees by nothing, but it is the flag a prototype method would carry.\n *\n * Here rather than in `Contracted.mts` so the key stays module-private: the\n * installation is the only thing that needs it, and every other consumer derives it\n * from `Symbol.for`.\n *\n * @param prototype - The prototype to install on.\n * @internal\n */\nexport const installInspect = (prototype: object): void => {\n Object.defineProperty(prototype, inspectKey, {\n value: inspectInstance,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n};\n","/**\n * Classifies a feature body by how it delivers its results.\n *\n * A Hoare triple `{ P } C { Q }` only means something if `Q` is evaluated after\n * `C` has finished. \"Finished\" is not the same event for every kind of feature:\n * an `async` body finishes when its promise settles, and a generator finishes a\n * *segment* every time it yields. The kind decides where the exit boundary\n * therefore sits.\n *\n * The classifier lives in its own module because two layers need it and neither\n * should learn the other's vocabulary: the lifecycle dispatches on it, and a\n * decorator refuses a declaration whose boundary cannot honour it. Importing it\n * from `Contracted.mts` would make every decorator depend on the proxy for one\n * `switch`.\n */\nexport type FeatureKind = 'sync' | 'async' | 'generator' | 'async-generator';\n\n/**\n * Reads a feature's kind from its function object.\n *\n * `Reflect.apply` on an `async` function returns its promise immediately, and on\n * a generator it returns an iterator, so the only reliable signal is the\n * function's constructor, which is stable across bundling and minification\n * (unlike `Function.prototype.name`).\n */\nexport const featureKindOf = (fn: (...args: any[]) => unknown): FeatureKind => {\n switch (fn.constructor.name) {\n case 'AsyncFunction': return 'async';\n case 'GeneratorFunction': return 'generator';\n case 'AsyncGeneratorFunction': return 'async-generator';\n default: return 'sync';\n }\n};\n","import { assert } from './assert.mjs';\nimport { Contracted } from './Contracted.mjs';\nimport { featureKindOf } from './feature-kind.mjs';\nimport type { ArmOptions } from './admissibility.mjs';\n\n/**\n * Rejects a call that did not receive a standard decorator context.\n *\n * Every standard context carries a string `kind`, and the second argument of a\n * pre-standard invocation never does: for a member it is the property key, and a\n * class decorator is called with the class alone, so there is no second argument\n * at all. Testing that one field is therefore enough to tell the protocols apart,\n * and it is deliberately the only test — a guard that demanded more of the\n * context would reject a real one as the decorator-context proposal gains fields.\n *\n * Without the check every later assertion describes the wrong problem: a member\n * decorator reports that the method it was applied to is not a method, and\n * `@invariant` destructures `undefined`.\n *\n * The check runs before any other, in every decorator, because it is the one\n * failure that makes the rest of the diagnostics meaningless.\n *\n * The assertion signature carries the narrowing, so callers get a typed context\n * from a value they could not otherwise inspect. It narrows to the union rather\n * than to a member context, because a class decorator is checked by the same\n * guard.\n */\nexport function assertDecoratorContext(\n contract: string,\n context: unknown,\n): asserts context is DecoratorContext {\n const kind = (context as { kind?: unknown } | undefined)?.kind;\n\n assert(\n typeof kind === 'string',\n `${contract} was invoked without a standard decorator context, so it received no 'kind'. `\n + \"This happens when the compiler emits the pre-standard protocol, which `experimentalDecorators` selects. \"\n + 'This library requires the TC39 protocol, so disable `experimentalDecorators` (and `emitDecoratorMetadata`), '\n + 'and make sure the build lowers decorator syntax rather than passing it through.',\n );\n}\n\n/**\n * The gate every feature contract decorator shares.\n *\n * `@demands`, `@ensures`, and `@rescue` apply to exactly the same kind of member:\n * an instance feature of a `Contracted` subclass, whose name is not `_`-prefixed.\n * The rule lives here rather than in each decorator so that a constraint added to\n * one applies to all three, instead of being easy to miss in the others.\n *\n * The name is the only visibility the runtime can see, and it is deliberately the\n * only one checked. A `protected` or `private` keyword member is an ordinary public\n * property in the emitted JavaScript, and a standard context reports `private: false`\n * for it; `context.private` is true only for a native `#private` member. The `_`\n * convention is therefore what carries the guarantee, not the modifier: a contract on\n * a non-public keyword member is accepted here, and the documentation says why.\n *\n * The name of the contract is passed in so the messages stay specific.\n *\n * `context` is `unknown` because the protocol is diagnosed here rather than by\n * the caller; the guard narrows it to a standard context.\n */\nexport function assertFeatureContractTarget(contract: string, feature: unknown, context: unknown): void {\n assertDecoratorContext(contract, context);\n\n assert(\n context.kind === 'method' || context.kind === 'getter' || context.kind === 'setter',\n `${contract} decorator can only be applied to methods, getters, or setters`,\n );\n\n assert(context.static === false, `${contract} decorator cannot be applied to static features`);\n assert(context.private === false, `${contract} decorator cannot be applied to private features`);\n assert(!String(context.name).startsWith('_'), `${contract} decorator cannot be applied to a '_'-prefixed feature`);\n\n // Registration happens at decoration time rather than in `addInitializer`,\n // which runs once per instance: doing it there appended the same predicate on\n // every instantiation, which was unbounded metadata growth and a linearly\n // growing predicate list to evaluate on each call.\n context.addInitializer(function () {\n assert(this instanceof Contracted, `${contract} decorator can only be applied to classes that extend Contracted`);\n });\n}\n\n/**\n * Rejects `awaitPredicate` on a feature whose boundary cannot await it.\n *\n * The option moves a precondition's verdict to a microtask, which is only sound\n * where the feature's own result is already behind a promise: an `async` body is\n * awaited before its exit checks run, so awaiting its entry checks moves nothing\n * the caller could observe. The other three boundaries cannot absorb the wait.\n *\n * - A getter or setter is an accessor. Its caller reads or assigns synchronously,\n * so there is no promise to attach a pending verdict to.\n * - A generator hands the caller an iterator and runs nothing until it is\n * resumed. Its contracts bracket a *step*, and awaiting one would make every\n * `next()` asynchronous — a different protocol, not a slower check.\n * - An async generator has the same per-step boundary.\n *\n * Each case is refused where it is written, with the reason, rather than accepted\n * and then ignored by a lifecycle that cannot honour it. The element is the\n * decorated member itself, so its kind is readable here; a class body that\n * overrides an `async` feature with a synchronous one is caught separately, at the\n * boundary, because the inherited declaration is not in scope at this point.\n *\n * @param contract - The contract name, for the message.\n * @param element - The decorated member, whose kind decides.\n * @param context - The member's decorator context.\n * @param options - The declaration's options.\n */\nexport function assertAwaitableFeature(\n contract: string,\n element: unknown,\n context: { kind: string },\n options: ArmOptions | undefined,\n): void {\n if (!options?.awaitPredicate) return;\n\n if (context.kind !== 'method')\n throw new TypeError(\n `${contract} cannot declare awaitPredicate on ${context.kind === 'getter' ? 'a getter' : 'a setter'}: `\n + 'an accessor is read or assigned synchronously, so there is no promise a pending verdict could join.',\n );\n\n const kind = featureKindOf(element as (...args: any[]) => unknown);\n\n if (kind === 'async') return;\n\n const reason = kind === 'generator' || kind === 'async-generator'\n ? 'a generator has one contract boundary per step, and awaiting a step would make every `next()` asynchronous rather than merely slower'\n : 'a synchronous feature has evaluated its contracts by the time the verdict could settle';\n\n throw new TypeError(\n `${contract} cannot declare awaitPredicate on this feature: ${reason}. `\n + 'The option is available on an `async` method only.',\n );\n}\n","import { assert, violationFailure } from './assert.mjs';\nimport { contractsEnabled, Contracted } from './Contracted.mjs';\nimport { classNameOf } from './name.mjs';\nimport { assertDecoratorContext } from './decorator.mjs';\nimport { failureLog, assertNotAwaitable, assertNotNormalizable, assertNotViolationFactory, assertNotWeakenable, describeArm, evaluateArm, type ArmOptions } from './admissibility.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\n\n/**\n * The fields an invariant predicate is called with.\n *\n * An invariant describes the whole instance, so `self` is the only field. See\n * `DemandsSubject` for why it is not `Readonly<This>`, which would hide the\n * `protected` state an invariant is written against.\n *\n * A predicate rarely needs to name this type. The decorator receives the class,\n * so `This` is inferred and `@invariant(({ self }) => ...)` reads instance state\n * without an annotation. It is exported for code that builds an arm separately\n * from the decorator that registers it.\n */\nexport interface InvariantSubject<This> {\n readonly self: This;\n}\n\n/**\n * An invariant predicate: a property the instance always satisfies.\n *\n * It takes one object rather than a positional list, so every contract in the\n * library presents the same shape to the predicate it calls.\n */\nexport type InvariantPredicate<Class extends typeof Contracted> =\n (subject: InvariantSubject<InstanceType<Class>>) => boolean;\n\n/**\n * An invariant arm: a predicate, or a schema the instance must satisfy.\n *\n * A schema in this position validates the **instance**, which is the subject\n * `@invariant` already describes.\n */\nexport type InvariantArm<Class extends typeof Contracted> =\n InvariantPredicate<Class> | StandardSchemaV1<unknown, any>;\n\nexport type InvariantDecorator = <Class extends typeof Contracted>(\n arm: InvariantArm<Class>,\n options?: ArmOptions,\n) => (\n value: Class,\n context: ClassDecoratorContext<Class>\n) => Class | void;\n\n/**\n * A registered invariant arm.\n *\n * The options travel with the arm because `normalize` is a property of the\n * declaration rather than of an individual evaluation.\n */\nexport interface RegisteredInvariant {\n arm: InvariantArm<typeof Contracted>;\n options?: ArmOptions;\n}\n\nexport function assertInvariants<C extends typeof Contracted, T extends InstanceType<C>>(\n Class: C,\n instance: T,\n enabled: boolean = contractsEnabled(Class),\n) {\n if (!enabled) return;\n\n const registered = (Class[Symbol.metadata]?.['invariants'] ?? []) as unknown as RegisteredInvariant[];\n\n // A class with no invariant arms is the common case, and this runs on entry and\n // exit of every feature. The name is only needed to label an arm, so it is\n // resolved after the loop has decided one failed rather than on every call: a\n // declaration may be an accessor, and reading it twice per invocation to name a\n // failure that did not happen is cost the caller pays for nothing.\n if (registered.length === 0) return;\n\n const className = () => classNameOf(Class),\n failures = failureLog();\n\n // AND-composed: every arm must hold for the instance to be valid. Invariants\n // are covariant, so a subtype may strengthen the obligation but never weaken\n // it, which is why one failing arm is enough to reject.\n for (const [index, entry] of registered.entries()) {\n const result = evaluateArm(\n entry.arm,\n { predicate: () => ({ self: instance }), schema: () => instance },\n '@invariant',\n className,\n index,\n entry.options,\n );\n\n if (result.ok) continue;\n\n // Every arm is evaluated even after one rejects, because a report naming\n // only the first broken invariant hides the others the instance violates\n // at the same moment.\n failures.record(index, result);\n }\n\n if (failures.entries === undefined) return;\n\n throw violationFailure(\n '@invariant',\n className(),\n undefined,\n registered.map(entry => entry.arm),\n failures.entries,\n 'The instance left the invariant unsatisfied.',\n describeArm,\n );\n}\n\nexport const invariant: InvariantDecorator = (arm, options) => (OriginalClass, context) => {\n assertDecoratorContext('@invariant', context);\n assertNotAwaitable('@invariant', options);\n assertNotNormalizable('@invariant', options);\n assertNotViolationFactory('@invariant', options);\n assertNotWeakenable('@invariant', options);\n\n const { metadata } = context;\n\n assert(context.kind === 'class', '@invariant decorator can only be applied to classes');\n assert(OriginalClass.prototype instanceof Contracted, '@invariant decorator can only be applied to classes that extend Contracted');\n\n const existing = (metadata.invariants ?? []) as unknown as RegisteredInvariant[];\n\n metadata.invariants = [...existing, { arm, options }];\n};\n","import { violationFailure } from './assert.mjs';\nimport { contractsEnabled, Contracted } from \"./Contracted.mjs\";\nimport { classNameOf } from './name.mjs';\nimport { assertAwaitableFeature, assertFeatureContractTarget } from './decorator.mjs';\nimport {\n alreadyReported, failureLog, assertAwaitableArm, assertNormalizable, assertViolationFactory, describeArm,\n evaluateArm, evaluateArmAsync, inheritedArms, reportWeakeningArm, selectViolationFactory,\n type ArmFailures, type ArmOptions, type ArmSubjects,\n} from './admissibility.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * The fields a precondition predicate is called with.\n *\n * `self` is the instance and `args` is the invocation's argument list.\n *\n * `This` and `Args` are inferred from the member the decorator is applied to, so\n * a predicate that reads instance state needs no annotation:\n * `({ self, args }) => self._x > 0`. The inference comes from the decorator's\n * context type, which carries the class and the feature's signature; naming it\n * explicitly is only necessary where the runtime subject differs from that\n * signature.\n *\n * `self` is **not** `Readonly<This>`. `Readonly` maps over `keyof This`, which\n * covers only public members, so `Readonly<Cart>` has no `_balance` when\n * `_balance` is `protected` — the type would erase the fields contracts are\n * written against, and `protected` state is the documented convention. Purity is\n * enforced at runtime instead: every predicate receives a read-only view, so an\n * assignment throws rather than silently corrupting the instance the next\n * contract observes.\n */\nexport interface DemandsSubject<This, Args extends any[] = any[]> {\n readonly self: This;\n readonly args: Args;\n}\n\n/**\n * A precondition predicate.\n *\n * `args` is the argument list of the invocation, matching `EnsuresPredicate`,\n * so a predicate destructures it: `({ args: [x] }) => x > 0`.\n *\n * The type is generic over the argument tuple so the element types are inferred\n * from the predicate. Writing `({ args }) => args > 0` does not compile: `args`\n * is the array, not the first argument, and a predicate that compares against the\n * array passes only through coercion.\n *\n * It takes one object rather than a positional list, so a contract that supplies\n * a field the predicate does not read costs nothing where it is declared.\n */\nexport type DemandsPredicate<This extends Contracted, Args extends any[] = any[]> =\n (subject: DemandsSubject<This, Args>) => boolean;\n\n/**\n * A precondition arm: a predicate, or a schema the argument tuple must satisfy.\n *\n * A predicate may answer with a promise, but only when the declaration sets\n * {@link ArmOptions.awaitPredicate} — the option is what makes the verdict\n * awaited rather than coerced, and the overload on `DemandsDecorator` refuses the\n * asynchronous form without it.\n *\n * A schema validates the **argument tuple**, which is the subject `@demands`\n * already describes, so a method with two parameters is written as\n * `z.tuple([A, B])`. Keeping one subject for both kinds of arm is what lets the\n * composition rule below be the same for both.\n *\n * The schema's `Input` is left unpinned (`unknown`) rather than constrained to\n * `any[]`, because every real provider declares a concrete input type and\n * `StandardSchemaV1` is invariant in it: pinning it here would reject a\n * `z.tuple([...])` whose input is `[number, number]`. The tuple shape is an\n * obligation on the declaration, checked at runtime by the schema itself.\n */\nexport type DemandsArm<This extends Contracted, Args extends any[] = any[]> =\n DemandsPredicate<This, Args>\n | ((subject: DemandsSubject<This, Args>) => boolean | Promise<boolean>)\n | StandardSchemaV1<unknown, any>;\n\n/**\n * The `@demands` decorator.\n *\n * The two overloads are the opt-in. The first admits a synchronous verdict or a\n * schema, so an accidentally `async` predicate is a compile error there; the\n * second admits a promise and requires `awaitPredicate: true` to say so. Inference\n * of `self` and `args` comes from the decorated member either way, and an options\n * object built separately still matches the first overload.\n */\nexport type DemandsDecorator = {\n <This extends Contracted, Args extends any[]>(\n arm: DemandsPredicate<This, Args> | StandardSchemaV1<unknown, any>,\n options?: ArmOptions,\n ): (\n value: unknown,\n context: FeatureDecoratorContext<This, Args>\n ) => void;\n <This extends Contracted, Args extends any[]>(\n arm: DemandsArm<This, Args>,\n options: ArmOptions & { awaitPredicate: true },\n ): (\n value: unknown,\n context: FeatureDecoratorContext<This, Args>\n ) => void;\n};\n\n/** No arm is declared for a feature, so none is evaluated. */\nconst NO_ARMS: readonly RegisteredDemands[] = Object.freeze([]);\n\n/** A registered precondition arm, with the options it was declared with. */\nexport interface RegisteredDemands {\n arm: DemandsArm<Contracted>;\n options?: ArmOptions;\n}\n\nexport const demands: DemandsDecorator = (arm, options) => (feature, ctx) => {\n assertFeatureContractTarget('@demands', feature, ctx);\n assertAwaitableFeature('@demands', feature, ctx, options);\n assertAwaitableArm(arm, '@demands', options);\n assertNormalizable(arm, '@demands', options);\n assertViolationFactory('@demands', options);\n\n // A subclass arm reads as a restriction and is not one: OR-composition keeps\n // every inherited arm, so satisfying any of them still permits the call. The\n // diagnostic names that where the arm is written, which is the only point the\n // author is looking at it.\n //\n // Reported once per feature: a class may carry several arms on one method, and\n // each decorator runs independently, so an unconditional report would print the\n // same message for each of them.\n //\n // The feature is `ctx.name`; the decorator's `value` parameter is the element,\n // so using it here would look the arms up under a function's source text. A\n // member decorator's context carries no class name — the class is not in scope\n // — so the label names the feature alone rather than inventing a class.\n if (!alreadyReported(ctx.metadata, ctx.name))\n reportWeakeningArm(\n '@demands',\n String(ctx.name),\n inheritedArms(ctx.metadata, ctx.name),\n options,\n );\n\n // The cast is the protocol's, not this contract's: `ctx.metadata` is\n // `DecoratorMetadataObject`, an open `Record<PropertyKey, unknown>`, so the\n // key this decorator writes has no static type until it is asserted. The\n // record's shape is asserted once here and read back through\n // `Contracted[Symbol.metadata]`, which is typed.\n const ds = [\n ...(ctx.metadata as any)?.demands?.[ctx.name] ?? [],\n { arm, options }\n ]\n\n ctx.metadata.demands = {\n ...(ctx.metadata?.demands ?? {}),\n [ctx.name]: ds\n };\n}\n\n/** What a precondition arm observes: the instance and the invocation's arguments. */\nconst demandsSubjects = (instance: Contracted, args: any[]): ArmSubjects => ({\n predicate: () => ({ self: instance, args }),\n schema: () => args,\n});\n\n/**\n * Raises the failure for a precondition no arm satisfied.\n *\n * All arms are reported, because OR-composition means any of them could have\n * permitted the call. A declared factory decides the error; failing that, a thrown\n * value is raised in place of the `AssertionError`, so a typed error survives.\n */\nfunction raiseDemandsFailure(\n ds: readonly RegisteredDemands[],\n className: string,\n propertyKey: PropertyKey,\n failures: ArmFailures,\n): never {\n throw violationFailure(\n '@demands',\n className,\n String(propertyKey),\n ds.map(entry => entry.arm),\n failures,\n 'A precondition was not satisfied, so the feature was not entered.',\n describeArm,\n selectViolationFactory(ds),\n );\n}\n\n/**\n * Evaluates the precondition for an invocation.\n *\n * The arms are OR-composed, which is the contravariance rule: a subtype may\n * weaken a precondition, so satisfying any inherited arm is enough. A schema arm\n * composes exactly like a predicate arm.\n *\n * When an arm asks for normalization, the value it produced replaces the\n * arguments, and because OR-composition short-circuits, the **first passing arm**\n * decides what that value is. That is deterministic and matches evaluation order.\n *\n * @param enabled - Whether the contracts are evaluated for this class. The lifecycle\n * has already resolved the switch, so it passes its verdict rather than making this\n * function walk the class chain a second time; a caller that reaches this function\n * on its own omits it and the switch is resolved here.\n * @returns The arguments to use, which are the originals unless an arm\n * normalized them.\n */\nexport function assertDemands(\n instance: Contracted,\n propertyKey: PropertyKey,\n args: any[],\n enabled: boolean = contractsEnabled(instance.constructor),\n): any[] {\n if (!enabled) return args;\n\n const Class = instance.constructor as typeof Contracted,\n ds = Class[Symbol.metadata]?.demands?.[propertyKey] ?? NO_ARMS;\n\n if (ds.length === 0) return args;\n\n const label = () => `${classNameOf(Class)}.${String(propertyKey)}`,\n failures = failureLog();\n\n for (let index = 0; index < ds.length; index++) {\n const { arm, options } = ds[index],\n result = evaluateArm(arm, demandsSubjects(instance, args), '@demands', label, index, options);\n\n // A later arm may still permit the call, so a rejected arm is recorded\n // rather than returned from. Propagating a throw here would make a legal\n // weakening arm unreachable.\n if (!result.ok) {\n failures.record(index, result);\n\n continue;\n }\n\n // Any satisfied arm fulfils the obligation.\n return result.value === undefined ? args : result.value as any[];\n }\n\n raiseDemandsFailure(ds, classNameOf(Class), propertyKey, failures.entries!);\n}\n\n/**\n * Whether any registered arm declared `awaitPredicate`.\n *\n * The asynchronous lifecycle asks this before choosing the awaited composition, so\n * a feature whose arms are all synchronous pays nothing for the capability: the\n * awaited form returns a promise from every call, which is one extra microtask the\n * caller would wait on for a verdict that was already decided synchronously.\n *\n * @param instance - The instance whose class holds the record.\n * @param propertyKey - The feature being invoked.\n * @internal\n * Exported only so the lifecycle in `Contracted.mts` can import it; `index.mts`\n * does not re-export it.\n */\nexport function demandsAwaitable(instance: Contracted, propertyKey: PropertyKey): boolean {\n const Class = instance.constructor as typeof Contracted;\n\n return (Class[Symbol.metadata]?.demands?.[propertyKey] ?? NO_ARMS).some(entry => entry.options?.awaitPredicate);\n}\n\n/**\n * Evaluates the precondition for an invocation whose arms may answer with a promise.\n *\n * OR-composition decides the arms here too: a subtype may weaken a precondition,\n * so satisfying any arm is enough. Only the settlement differs, and it is stated\n * separately from {@link assertDemands} because the two boundaries differ: this\n * one hands back a promise, and a synchronous feature's precondition must be\n * decided before its body starts rather than in a microtask afterwards.\n *\n * A rejected predicate is a failed arm, exactly as a throwing one is, so a sibling\n * arm may still permit the call and the rejection is raised only if every arm\n * fails.\n */\nexport async function assertDemandsAsync(\n instance: Contracted,\n propertyKey: PropertyKey,\n args: any[],\n enabled: boolean = contractsEnabled(instance.constructor),\n): Promise<any[]> {\n if (!enabled) return args;\n\n const Class = instance.constructor as typeof Contracted,\n ds = Class[Symbol.metadata]?.demands?.[propertyKey] ?? NO_ARMS;\n\n if (ds.length === 0) return args;\n\n const label = () => `${classNameOf(Class)}.${String(propertyKey)}`,\n failures = failureLog();\n\n for (let index = 0; index < ds.length; index++) {\n const { arm, options } = ds[index],\n result = await evaluateArmAsync(arm, demandsSubjects(instance, args), '@demands', label, index, options);\n\n if (!result.ok) {\n failures.record(index, result);\n\n continue;\n }\n\n return result.value === undefined ? args : result.value as any[];\n }\n\n raiseDemandsFailure(ds, classNameOf(Class), propertyKey, failures.entries!);\n}\n","import { violationFailure } from './assert.mjs';\nimport { contractsEnabled, Contracted } from './Contracted.mjs';\nimport { classNameOf } from './name.mjs';\nimport { assertAwaitableFeature, assertFeatureContractTarget } from './decorator.mjs';\nimport {\n failureLog, assertAwaitableArm, assertNormalizable, assertNotWeakenable, assertViolationFactory, describeArm,\n evaluateArm, evaluateArmAsync, selectViolationFactory, type ArmFailures,\n type Admissibility, type ArmOptions, type ArmSubjects, type FailureLog,\n} from './admissibility.mjs';\nimport type { StandardSchemaV1 } from './standard-schema.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * The fields a postcondition predicate is called with.\n *\n * `old` is the snapshot of the instance from before the feature ran. It is not\n * `Readonly`, and is deliberately not the same object as `self`: it is a detached\n * copy, so a predicate writing to it corrupts nothing.\n *\n * `oldArgs` is the snapshot of the **call's arguments** from before the body ran,\n * taken on the same terms as `old`. It is what lets a predicate state a property\n * over an object it was *given*, rather than only over the instance whose feature\n * it is: `oldArgs[0].onHold` is the argument's state before the call, while\n * `args[0].onHold` is its state now.\n *\n * `oldArgs` mirrors the arguments the caller supplied, which is why a getter has\n * none: `args` describes a getter's *result*, and a result has no pre-state. A\n * generator is the same case from the other end — `args` describes the value the\n * step yielded — so it has none either. Every other feature pairs them:\n * `oldArgs[i]` is the pre-state of `args[i]`.\n *\n * The field is typed `Args` because that is the only tuple the subject carries.\n * A generator's `oldArgs` is therefore empty where its annotation says otherwise,\n * which is why a generator's `@ensures` is annotated for its `args` alone.\n *\n * `result` is the value the feature body produced, which is what the caller\n * receives unless a schema arm normalizes it. Every arm is given the **same**\n * unnormalized value, because `@ensures` is AND-composed: \"every arm must hold\" is\n * only a statement about one thing if every arm observes one thing. A normalizing\n * schema also validates this value and replaces it afterwards, so a predicate and\n * a schema in the same composition always agree about what they were shown.\n *\n * See `DemandsSubject` for why `self` is not `Readonly<This>` and for the\n * inference that makes an annotation unnecessary.\n *\n * `Result` defaults to `unknown`. A method's context type carries a call\n * signature while a getter's carries the property type, so both would be\n * inference sites for one parameter and the compiler would resolve it to their\n * intersection. A predicate that reads a member of `result` therefore names it —\n * `EnsuresSubject<Cart, [number], number>` — and `unknown` rather than `any` makes\n * forgetting that a compile error rather than a silent `undefined`.\n */\nexport interface EnsuresSubject<This, Args extends any[] = any[], Result = unknown> {\n readonly self: This;\n readonly args: Args;\n readonly old: This;\n readonly oldArgs: Args;\n readonly result: Result;\n}\n\n/**\n * A postcondition predicate.\n *\n * It takes one object rather than a positional list, so a contract that supplies\n * fields the predicate does not read costs nothing where it is declared.\n */\nexport type EnsuresPredicate<\n This extends Contracted,\n Args extends any[] = any[],\n Result = unknown,\n> = (subject: EnsuresSubject<This, Args, Result>) => boolean;\n\n/**\n * A postcondition arm: a predicate, or a schema the feature's **result** must\n * satisfy.\n *\n * A schema validates the result, which is the value the caller receives. This is\n * the covariant position: a subtype may promise a narrower result, so the arms\n * are AND-composed.\n *\n * A predicate may answer with a promise only when the declaration sets\n * {@link ArmOptions.awaitPredicate}; the overload on `EnsuresDecorator` is what\n * refuses the asynchronous form without it.\n */\nexport type EnsuresArm<\n This extends Contracted,\n Args extends any[] = any[],\n Result = unknown,\n> =\n EnsuresPredicate<This, Args, Result>\n | ((subject: EnsuresSubject<This, Args, Result>) => boolean | Promise<boolean>)\n | StandardSchemaV1<unknown, any>;\n\n/**\n * The `@ensures` decorator.\n *\n * The two overloads are the opt-in, as on `@demands`: a promise is admitted only\n * by the second, which requires `awaitPredicate: true`, while the first keeps the\n * synchronous verdict or a schema and accepts an options object built separately.\n */\nexport type EnsuresDecorator = {\n <\n This extends Contracted,\n Args extends any[],\n Result = unknown,\n >(\n arm: EnsuresPredicate<This, Args, Result> | StandardSchemaV1<unknown, any>,\n options?: ArmOptions,\n ): (\n value: unknown,\n context: FeatureDecoratorContext<This, Args>\n ) => void;\n <\n This extends Contracted,\n Args extends any[],\n Result = unknown,\n >(\n arm: EnsuresArm<This, Args, Result>,\n options: ArmOptions & { awaitPredicate: true },\n ): (\n value: unknown,\n context: FeatureDecoratorContext<This, Args>\n ) => void;\n};\n\n/** A registered postcondition arm, with the options it was declared with. */\n/** No arms are declared for a feature, so none are evaluated. */\nconst NO_ARMS: readonly RegisteredEnsures[] = Object.freeze([]);\n\nexport interface RegisteredEnsures {\n arm: EnsuresArm<Contracted>;\n options?: ArmOptions;\n}\n\nexport const ensures: EnsuresDecorator = (arm, options) => (feature, ctx) => {\n assertFeatureContractTarget('@ensures', feature, ctx);\n assertAwaitableFeature('@ensures', feature, ctx, options);\n assertAwaitableArm(arm, '@ensures', options);\n assertNormalizable(arm, '@ensures', options);\n assertViolationFactory('@ensures', options);\n assertNotWeakenable('@ensures', options);\n\n // See `@demands` for why the metadata record needs an assertion here.\n const es = [\n ...(ctx.metadata as any)?.ensures?.[ctx.name] ?? [],\n { arm, options }\n ]\n\n // AND-composition means every arm must hold, so two arms that both replace\n // the result would disagree about what the caller receives. There is no\n // correct winner, so the declaration is rejected where it is written.\n const normalizers = (es as unknown as RegisteredEnsures[]).filter(entry => entry.options?.normalize);\n\n if (normalizers.length > 1)\n throw new TypeError(\n `@ensures for ${String(ctx.name)} declares ${normalizers.length} normalizing arms; `\n + 'at most one arm may normalize the result, because they would disagree about what the caller receives.',\n );\n\n ctx.metadata.ensures = {\n ...(ctx.metadata?.ensures ?? {}),\n [ctx.name]: es\n };\n}\n\n/**\n * What a postcondition arm observes.\n *\n * A predicate sees the invocation, the historical instance, the invocation's\n * historical arguments, and the result; a schema validates the result. Every arm is\n * given the same `result`, including a normalizing schema arm, which validates it\n * before replacing it. Supplying the raw value to all of them is what makes\n * AND-composition a claim about one thing rather than several.\n *\n * `oldArgs` arrives on the subject rather than as a parameter because the subject is\n * where a predicate reads it, and because this function is published: a caller that\n * builds a subject already supplies it, and its signature stays as it was.\n */\nconst ensuresSubjects = (\n instance: Contracted,\n args: any[],\n old: Contracted,\n oldArgs: any[],\n result: unknown,\n): ArmSubjects => ({\n predicate: () => ({ self: instance, args, old, oldArgs, result }),\n schema: () => result,\n});\n\n/**\n * Raises the failure for a postcondition the arms did not all satisfy.\n *\n * A declared factory decides the error; failing that, a thrown value is raised in\n * place of the `AssertionError`, so a typed error survives.\n */\nfunction raiseEnsuresFailure(\n es: readonly RegisteredEnsures[],\n className: string,\n propertyKey: PropertyKey,\n failures: ArmFailures,\n): never {\n throw violationFailure(\n '@ensures',\n className,\n String(propertyKey),\n es.map(entry => entry.arm),\n failures,\n 'A postcondition was not satisfied after the feature ran.',\n describeArm,\n selectViolationFactory(es),\n );\n}\n\n/**\n * Folds one arm's outcome into the composition's running result.\n *\n * A rejected arm is recorded and the running value passes through unchanged; a\n * passing arm replaces it only when it normalized one, which is how a schema arm's\n * `Output` reaches the caller. The rule is the same whether the verdict was\n * synchronous or awaited, so it is stated once for both loops.\n */\nconst foldOutcome = (\n failures: FailureLog,\n index: number,\n outcome: Admissibility,\n normalized: unknown,\n): unknown => {\n if (!outcome.ok) {\n failures.record(index, outcome);\n\n return normalized;\n }\n\n return outcome.value === undefined ? normalized : outcome.value;\n}\n\n/**\n * Evaluates the postcondition for an invocation.\n *\n * The arms are AND-composed, which is the covariance rule: a subtype may\n * strengthen a postcondition, so every inherited arm has to keep holding.\n *\n * @param result - The value the caller receives. A schema arm validates it.\n * @param oldArgs - The pre-state of the arguments the body received. Optional and\n * trailing so the signature stays additive: a caller that predates the field\n * omits it, and the subject reports an empty list.\n * @returns The result to hand the caller, which is the original unless an arm\n * normalized it.\n */\nexport function assertEnsures(\n instance: Contracted,\n old: Contracted,\n propertyKey: PropertyKey,\n args: any[],\n result: unknown,\n oldArgs: any[] = [],\n enabled: boolean = contractsEnabled(instance.constructor),\n): unknown {\n if (!enabled) return result;\n\n const Class = instance.constructor as typeof Contracted,\n es = Class[Symbol.metadata]?.ensures?.[propertyKey] ?? NO_ARMS;\n\n if (es.length === 0) return result;\n\n const label = () => `${classNameOf(Class)}.${String(propertyKey)}`;\n\n const failures = failureLog();\n\n let normalized = result;\n\n // ALL arms must hold for the obligation to be fulfilled.\n for (let index = 0; index < es.length; index++) {\n const entry = es[index];\n\n normalized = foldOutcome(failures, index, evaluateArm(\n entry.arm,\n ensuresSubjects(instance, args, old, oldArgs, result),\n '@ensures',\n label,\n index,\n entry.options,\n ), normalized);\n }\n\n if (failures.entries === undefined) return normalized;\n\n raiseEnsuresFailure(es, classNameOf(Class), propertyKey, failures.entries);\n}\n\n/**\n * Whether any registered arm declared `awaitPredicate`.\n *\n * The asynchronous lifecycle asks this before choosing the awaited composition, so\n * a feature whose arms are all synchronous pays nothing for the capability: the\n * awaited form returns a promise from every call, which is one extra microtask the\n * caller would wait on for a verdict that was already decided synchronously.\n *\n * @param instance - The instance whose class holds the record.\n * @param propertyKey - The feature being invoked.\n * @internal\n * Exported only so the lifecycle in `Contracted.mts` can import it; `index.mts`\n * does not re-export it.\n */\nexport function ensuresAwaitable(instance: Contracted, propertyKey: PropertyKey): boolean {\n const Class = instance.constructor as typeof Contracted;\n\n return (Class[Symbol.metadata]?.ensures?.[propertyKey] ?? NO_ARMS).some(entry => entry.options?.awaitPredicate);\n}\n\n/**\n * Evaluates the postcondition for an invocation whose arms may answer with a promise.\n *\n * AND-composition decides the arms here too: a subtype may strengthen a\n * postcondition, so every arm has to hold. Only the settlement differs. A\n * rejected predicate is a failed arm, exactly as a throwing one is, and the\n * rejection is raised only when every arm has been evaluated and at least one\n * failed.\n *\n * @param result - The value the caller receives. A schema arm validates it.\n * @param oldArgs - The pre-state of the arguments the body received. Optional and\n * trailing so the signature stays additive: a caller that predates the field\n * omits it, and the subject reports an empty list.\n * @returns The result to hand the caller, which is the original unless an arm\n * normalized it.\n */\nexport async function assertEnsuresAsync(\n instance: Contracted,\n old: Contracted,\n propertyKey: PropertyKey,\n args: any[],\n result: unknown,\n oldArgs: any[] = [],\n enabled: boolean = contractsEnabled(instance.constructor),\n): Promise<unknown> {\n if (!enabled) return result;\n\n const Class = instance.constructor as typeof Contracted,\n es = Class[Symbol.metadata]?.ensures?.[propertyKey] ?? NO_ARMS;\n\n if (es.length === 0) return result;\n\n const label = () => `${classNameOf(Class)}.${String(propertyKey)}`,\n failures = failureLog();\n\n let normalized = result;\n\n for (let index = 0; index < es.length; index++) {\n const entry = es[index];\n\n normalized = foldOutcome(failures, index, await evaluateArmAsync(\n entry.arm,\n ensuresSubjects(instance, args, old, oldArgs, result),\n '@ensures',\n label,\n index,\n entry.options,\n ), normalized);\n }\n\n if (failures.entries === undefined) return normalized;\n\n raiseEnsuresFailure(es, classNameOf(Class), propertyKey, failures.entries);\n}\n","import { assert } from './assert.mjs';\nimport { contractsEnabled, Contracted } from './Contracted.mjs';\nimport { assertDecoratorContext, assertFeatureContractTarget } from './decorator.mjs';\nimport type { FeatureDecoratorContext } from './types.mjs';\n\n/**\n * The fields a rescue handler is called with.\n *\n * `self` is the **raw** instance. Restoring corrupted state is what a handler is\n * for, so unlike a predicate it must be able to assign — `read-only.mts` excludes\n * `@rescue` for that reason.\n *\n * `retry` is an ordinary function field, called as `retry(...)`. It is not a\n * method of the subject, so lifting it off (`subject.retry(...)`) is unnecessary\n * and would give it a `this` it does not want. The handler itself carries no\n * `this: This` annotation for the same reason: the `this` context of a bare call\n * is `void`, so a declared `this` makes every consumer-written handler fail to\n * type-check. The subject carries the instance instead.\n *\n * `feature` names the feature whose invocation failed. A per-feature declaration\n * already knows it, because the handler was written next to that feature; a\n * class-level declaration serves every feature, so without this field a handler\n * that translates or logs per feature has nothing to key on. The value is the\n * property key the lifecycle was running for, so a `delete` reports the deleted\n * property and an accessor reports the accessor's name.\n */\nexport interface RescueSubject<This> {\n readonly self: This;\n readonly error: unknown;\n readonly args: any[];\n readonly retry: (...args: any[]) => any;\n readonly feature: PropertyKey;\n}\n\n/**\n * A handler for `@rescue`.\n *\n * It takes one object rather than a positional list, matching the other\n * contracts. See {@link RescueSubject} for the fields and for why `retry` is a\n * bare callable.\n */\nexport type RescueHandler<This extends Contracted> =\n (subject: RescueSubject<This>) => void\n\nexport interface RescueOptions {\n /**\n * The maximum number of times `retry` may restart the lifecycle for a single\n * invocation. Defaults to `Infinity`, which allows a `@rescue` to implement\n * N-Version programming with any number of alternative strategies.\n *\n * Set this when a rescue handler always retries, to bound recursion.\n */\n maxRetries?: number;\n}\n\nexport interface RescueDeclaration<This extends Contracted> {\n handler: RescueHandler<This>;\n maxRetries?: number;\n}\n\n/**\n * Declares a rescue handler for a feature, or for every feature of a class.\n *\n * `retry` is explicit: it passes only the arguments it is given and never\n * replays the original arguments. Forward the `args` field to retry with the\n * same arguments (`retry(...args)`); calling `retry()` retries with none.\n *\n * Options are declaration level because they describe the feature rather than an\n * individual failure. `maxRetries` bounds how many times `retry` may restart the\n * lifecycle for one invocation; it defaults to unbounded, and it is counted per\n * invocation of the feature the handler served rather than across the class.\n *\n * On a class the declaration applies to every feature that declares none of its\n * own. Precedence is feature-level first, then the nearest class-level\n * declaration walking up the constructor chain, so a subclass may override a\n * class-level handler its base declared without restating it per feature.\n *\n * The returned decorator takes one call signature whose context is the **union**\n * of the two positions, rather than two overloads. An overload pair cannot be\n * selected for a decorator expression: TypeScript resolves the class position\n * against the first signature and does not fall through, so a member-first pair\n * is rejected on a class and a class-first pair is rejected on a member. A union\n * is accepted in both positions and needs no ordering.\n *\n * `This` reaches both positions, and each supplies it differently: the member\n * context carries it through the decorated element's own signature, and the\n * class context through the constructor being decorated. Only the class context\n * is named by this type; the member context is left to `FeatureDecoratorContext`,\n * which already threads the instance through its three kind variants.\n *\n * The decorated element itself is typed `unknown` in both positions. Its type is\n * the feature's signature, which no handler reads, and naming it would make it a\n * second inference site for `This` — `typeof A` where the handler said `A` — and\n * a decorator expression has no way to unify the two.\n */\nexport type RescueDecorator = <This extends Contracted>(\n handler: RescueHandler<This>,\n options?: RescueOptions,\n) => <Args extends any[]>(\n value: unknown,\n context: FeatureDecoratorContext<This, Args>\n | ClassDecoratorContext<abstract new (...args: any[]) => This>,\n) => void;\n\nexport const rescue: RescueDecorator = (handler, options) => (element: unknown, ctx: unknown) => {\n assertDecoratorContext('@rescue', ctx);\n\n if (ctx.kind === 'class') {\n const Class = element as typeof Contracted;\n\n // A class decorator receives no instance, so there is no `this` to test in\n // `addInitializer`; the prototype chain is what says whether a subclass of\n // `Contracted` is being declared.\n assert(Class.prototype instanceof Contracted, '@rescue decorator can only be applied to classes that extend Contracted');\n assert(options?.maxRetries === undefined || options.maxRetries >= 0, 'maxRetries must not be negative');\n\n // A class decorator runs once for the class rather than once per member, so\n // it stores under its own key. `ctx.name` is the class name, which a feature\n // could also be called, so sharing the feature map would make the two forms\n // collide.\n ctx.metadata.classRescue = { handler, maxRetries: options?.maxRetries };\n\n return;\n }\n\n // The placement gate runs first, so a misplaced declaration reports that rather\n // than an option the placement made meaningless.\n assertFeatureContractTarget('@rescue', element, ctx);\n assert(options?.maxRetries === undefined || options.maxRetries >= 0, 'maxRetries must not be negative');\n\n // Register at decoration time. `addInitializer` runs once per instance, so\n // registering there rewrote the same declaration on every instantiation.\n ctx.metadata.rescue = {\n ...(ctx.metadata?.rescue ?? {}),\n [ctx.name]: { handler, maxRetries: options?.maxRetries }\n }\n\n ctx.addInitializer(function () {\n assert(this instanceof Contracted, '@rescue decorator can only be applied to classes that extend Contracted');\n })\n}\n\n/**\n * The `@rescue` declaration a metadata record holds for `feature`.\n *\n * A feature-level declaration wins over a class-level one, which is what lets a\n * class serve a uniform handler and still let one feature state its own. A\n * feature's own entry is an own property of the map, copied into a subclass's\n * record by the spread a decorator performs; a class-level declaration is one\n * property, reached through the metadata prototype chain when this class did not\n * declare its own.\n *\n * A `_`-prefixed feature takes neither form: the decorator refuses one wherever it\n * is written, because `@rescue` is the only contract a handler applies, and a\n * lifecycle that starts for a `_` name would otherwise inherit a class-level\n * handler for it. Leaving the name out of both answers keeps the two forms\n * consistent, so a consumer never has a feature they can cover but not override.\n *\n * @internal\n * Exported because `metadata.mts` reports the same effective declaration this\n * module applies, so both have to answer the question one way. It is not\n * re-exported from the package entry: it returns the live declaration, and a\n * consumer has to read a copy through `getContractMetadata`.\n */\nexport const rescueDeclarationOf = (\n metadata: {\n rescue?: Readonly<Record<PropertyKey, RescueDeclaration<Contracted>>>,\n classRescue?: RescueDeclaration<Contracted>,\n } | undefined,\n feature: PropertyKey,\n): RescueDeclaration<Contracted> | undefined =>\n String(feature).startsWith('_')\n ? undefined\n : metadata?.rescue?.[feature] ?? metadata?.classRescue;\n\n/**\n * Resolves the `@rescue` declaration for `propertyKey`, walking the constructor\n * chain so that a declaration on an ancestor is inherited.\n *\n * The walk covers the case where a class inherited its base's metadata record by\n * `Symbol.metadata` lookup rather than owning one, so the record it sees is the\n * one its ancestor wrote; the first class whose record resolves a declaration\n * supplies it.\n */\nexport function getRescueDeclaration(instance: Contracted, propertyKey: PropertyKey): RescueDeclaration<Contracted> | undefined {\n for (let proto: any = instance.constructor; proto && proto !== Function.prototype; proto = Object.getPrototypeOf(proto)) {\n const metadata = proto[Symbol.metadata] as Parameters<typeof rescueDeclarationOf>[0];\n\n if (!metadata) continue;\n\n const declaration = rescueDeclarationOf(metadata, propertyKey);\n\n if (declaration) return declaration;\n }\n\n return undefined;\n}\n\n/**\n * Applies the `@rescue` handler declared for `propertyKey`, if any.\n *\n * When the handler calls `retry`, the arguments passed to `retry` are returned\n * so that the caller can restart the contract lifecycle with them. This keeps\n * the lifecycle in one place (see `runLifecycle` in `Contracted.mts`) and\n * ensures a retried invocation is subject to `@invariant`, `@demands`, and\n * `@ensures` like any other invocation.\n *\n * `retry` may be called at most once per rescue execution. Because the lifecycle\n * re-enters `@rescue` when a retried invocation fails, a handler is executed\n * once per attempt, which is what N-Version programming requires.\n *\n * @returns The arguments to retry with.\n * @throws The original error if the handler does not call `retry`, or whatever\n * the handler throws.\n */\nexport const applyRescueHandler = (instance: Contracted, propertyKey: PropertyKey, error: unknown, args: any): any[] => {\n if (!contractsEnabled(instance.constructor)) throw error;\n\n const declaration = getRescueDeclaration(instance, propertyKey);\n\n if (!declaration) throw error;\n\n let hasRetried = false;\n let retryArgs: any[] = [];\n\n // `this` stays bound to the instance so a handler written with a `function`\n // expression keeps working; the instance is also supplied as `self`.\n declaration.handler.call(instance, {\n self: instance,\n error,\n args,\n retry: (...retryArguments: any[]) => {\n assert(!hasRetried, 'retry can only be called once per rescue execution');\n hasRetried = true;\n retryArgs = retryArguments;\n },\n feature: propertyKey,\n });\n if (!hasRetried)\n throw error;\n\n return retryArgs;\n}\n","import { AssertionError } from './AssertionError.mjs';\nimport { observesNoSubject } from './admissibility.mjs';\nimport { installInspect } from './inspect.mjs';\nimport { assertInvariants } from './invariant.mjs';\nimport { assertDemands, assertDemandsAsync, demandsAwaitable } from './demands.mjs';\nimport { assertEnsures, assertEnsuresAsync, ensuresAwaitable, type RegisteredEnsures } from './ensures.mjs';\nimport { classNameOf } from './name.mjs';\nimport { featureKindOf, type FeatureKind } from './feature-kind.mjs';\nimport { applyRescueHandler as applyRescueHandler, getRescueDeclaration } from './rescue.mjs';\nimport type { ContractMetadata } from './metadata.mjs';\n\n// Symbol to store checked mode state\nexport const checkedMode = Symbol.for('Contracted.checkedMode');\n\n/**\n * The switch for encapsulation, independent of {@link checkedMode}.\n *\n * Encapsulation is the `set`, `defineProperty`, and `deleteProperty` traps: the\n * rule that an external caller may not mutate state without a postcondition to\n * catch it. Contracts are whether `@invariant`, `@demands`, `@ensures`, and\n * `@rescue` are evaluated at all.\n *\n * They are separate because they answer different questions. A test double or a\n * plain data holder wants the contract checks off while still refusing an\n * assignment to a field it never declared. A class that is deliberately\n * configured with its state exposed wants the reverse. A single switch cannot\n * express either, because it would have to answer both at once.\n *\n * A class opts out by assigning a static, exactly as with {@link checkedMode}, and\n * the nearest declaration on the class chain wins.\n */\nexport const encapsulationMode = Symbol.for('Contracted.encapsulationMode');\n\n/**\n * Reads one enforcement switch from the class chain.\n *\n * The nearest **own** declaration wins, which is why the walk tests ownership\n * rather than the value: `Class[symbol]` would read an inherited declaration but\n * cannot tell it apart from one this class made, and a class that declares\n * nothing must fall through to the default rather than inherit from a sibling.\n *\n * The walk stops at `Function.prototype`, which is where a constructor chain ends.\n * A key that is not a constructor — a plain object, `undefined` — yields the\n * default rather than throwing, so a caller that has no `constructor` to offer\n * still gets a defined answer.\n *\n * Not memoised: the switch is assignable at runtime, and a cache would have to be\n * invalidated on every write, which is what a cache of a mutable switch gets\n * wrong.\n */\nconst switchOn = (Class: unknown, symbol: symbol): boolean => {\n for (let C: any = Class; typeof C === 'function' && C !== Function.prototype; C = Object.getPrototypeOf(C))\n if (Object.hasOwn(C, symbol)) return Boolean(C[symbol]);\n\n return true;\n};\n\n/**\n * Whether the contracts of `Class` are evaluated.\n *\n * @internal\n * Exported only because the four contract modules live in their own files and\n * import it. It takes a constructor rather than an instance because the caller\n * often has one without the other, and it is not part of the published surface.\n */\nexport const contractsEnabled = (Class: unknown): boolean => switchOn(Class, checkedMode);\n\n/**\n * Whether an external mutation of an instance of `Class` is trapped.\n *\n * The counterpart of {@link contractsEnabled} for the other switch, stated\n * separately so a trap that reads only this one does not walk the class chain twice\n * and allocate an object it immediately discards.\n */\nconst encapsulationEnabled = (Class: unknown): boolean => switchOn(Class, encapsulationMode);\n\n/**\n * Whether `prop` names one of the enforcement switches.\n *\n * Set through the class, never through an instance. An instance write would land\n * on the raw target where no trap could refuse it, and a switch a caller can set\n * is a guarantee a caller can remove.\n */\nconst isSwitch = (prop: PropertyKey): boolean => prop === checkedMode || prop === encapsulationMode;\n\n/**\n * Type of value that `cloneState` copies rather than shares.\n *\n * The list is deliberately closed: arrays, dates, maps, sets, and plain objects\n * are cloned because they are the containers contracts routinely compare. Every\n * other object — class instances, functions, regular expressions, buffers — is\n * shared by reference. See the `@ensures` documentation for the rationale.\n */\nconst isPlainObject = (value: object): boolean => {\n const proto = Object.getPrototypeOf(value);\n\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Copies a value for use in an `old` snapshot.\n *\n * Plain data containers are cloned recursively so that mutations performed by\n * the feature body are not visible through `old`. Anything else is returned by\n * reference, which preserves identity and avoids attempting to clone values that\n * cannot be cloned meaningfully (functions, class instances, buffers).\n *\n * Own property descriptors are copied rather than values, so accessors are not\n * invoked while snapshotting. An accessor on `old` therefore reads the\n * historical state through `this`, which is what a postcondition expects.\n */\nconst cloneState = (value: any, seen: WeakMap<object, any>): any => {\n if (typeof value !== 'object' || value === null) return value;\n\n const already = seen.get(value);\n if (already !== undefined) return already;\n\n if (value instanceof Date) return new Date(value.getTime());\n\n const container = cloneContainer(value, seen);\n if (container !== undefined) return container;\n\n if (!isPlainObject(value)) return value;\n\n const copy = Object.create(Object.getPrototypeOf(value));\n seen.set(value, copy);\n copyDescriptors(value, copy, seen);\n\n return copy;\n}\n\n/**\n * Clones one of the container types a contract routinely compares.\n *\n * Returns `undefined` when `value` is none of them, which is how `cloneState` falls\n * through to the plain-object path. Each container registers its copy in `seen`\n * before recursing, so a cycle in the data terminates.\n */\nconst cloneContainer = (value: any, seen: WeakMap<object, any>): any => {\n if (Array.isArray(value)) {\n const copy: any[] = [];\n seen.set(value, copy);\n for (const item of value) copy.push(cloneState(item, seen));\n\n return copy;\n }\n\n if (value instanceof Map) {\n const copy = new Map<any, any>();\n seen.set(value, copy);\n for (const [k, v] of value) copy.set(cloneState(k, seen), cloneState(v, seen));\n\n return copy;\n }\n\n if (value instanceof Set) {\n const copy = new Set<any>();\n seen.set(value, copy);\n for (const item of value) copy.add(cloneState(item, seen));\n\n return copy;\n }\n\n return undefined;\n}\n\n/**\n * Copies `source`'s own property descriptors onto `copy`, cloning each value.\n *\n * Descriptors are copied rather than values, so an accessor is never invoked while\n * a snapshot is taken: a getter on the copy reads the historical own state through\n * `this`. `seen` carries the identity map, so a value reached twice is one copy.\n *\n * The instance snapshot, the plain-object clone, and a contracted argument's copy\n * are the same operation on different sources, which is why it is stated once here.\n */\nconst copyDescriptors = (\n source: object,\n copy: object,\n seen: WeakMap<object, any>,\n): void => {\n for (const key of Reflect.ownKeys(source)) {\n const descriptor = Object.getOwnPropertyDescriptor(source, key)!;\n const cloned = 'value' in descriptor\n ? { ...descriptor, value: cloneState(descriptor.value, seen) }\n : descriptor;\n\n defineOrAssign(copy, key, cloned);\n }\n}\n\n/**\n * Defines one copied property, assigning instead when the descriptor is ordinary.\n *\n * A class field is a writable, enumerable, configurable data property, so most of an\n * instance is described by that case and defining costs an order of magnitude more\n * than writing the same value. Anything else — an accessor, or a read-only or\n * non-configurable property — is defined from its descriptor, so a copy reproduces\n * the instance's property attributes rather than flattening them into writable data.\n */\nconst defineOrAssign = (copy: object, key: PropertyKey, descriptor: PropertyDescriptor): void => {\n if ('value' in descriptor && descriptor.writable && descriptor.enumerable && descriptor.configurable)\n (copy as Record<PropertyKey, unknown>)[key] = descriptor.value;\n else\n Reflect.defineProperty(copy, key, descriptor);\n}\n\n/**\n * The own state of an instance as it is at one moment, with its values already\n * cloned.\n *\n * The values are cloned at capture time rather than when the object is built. A\n * snapshot describes the state the body is about to change, so reading the live\n * target later would observe the change instead; deferring the read is not an\n * available optimisation, only deferring the construction is.\n */\ninterface CapturedState {\n /** The instance whose prototype the snapshot inherits. */\n readonly target: object;\n /** Each own key with the descriptor it is defined by, its value already cloned. */\n readonly entries: [PropertyKey, PropertyDescriptor][];\n}\n\n/**\n * Captures the own state of `target` as it is now.\n *\n * `Reflect.ownKeys` is what also enumerates symbol keys, which a snapshot copies\n * because a symbol field is ordinary state.\n */\nconst captureState = (target: object, seen: WeakMap<object, any>): CapturedState => {\n const entries: [PropertyKey, PropertyDescriptor][] = [];\n\n for (const key of Reflect.ownKeys(target)) {\n const descriptor = Object.getOwnPropertyDescriptor(target, key)!;\n\n entries.push([key, 'value' in descriptor\n ? { ...descriptor, value: cloneState(descriptor.value, seen) }\n : descriptor]);\n }\n\n return { target, entries };\n}\n\n/**\n * Builds the snapshot object from previously captured state.\n *\n * The object inherits from the instance, so prototype members — including getters —\n * remain reachable and a getter reads the historical own state through `this`.\n */\nconst buildState = ({ target, entries }: CapturedState): object => {\n const copy: Record<PropertyKey, unknown> = Object.create(target);\n\n for (const [key, descriptor] of entries) defineOrAssign(copy, key, descriptor);\n\n return copy;\n}\n\n/**\n * Builds the `old` instance passed to `@ensures`.\n *\n * The result inherits from `target`, so prototype members (including getters and\n * methods) remain reachable, while own state is a copy taken at this moment.\n * Getters defined on the prototype therefore read the historical own state\n * through `this`.\n *\n * @param enabled - Whether the contracts are evaluated for this class, already\n * resolved by the lifecycle. `undefined` when they are not, which is the value\n * the call site's `needsSnapshot` guard already implies.\n */\nconst populateOld = (target: Contracted, enabled: boolean): Contracted | undefined => {\n if (!enabled) return undefined;\n\n return buildState(captureState(target, new WeakMap<object, any>())) as Contracted;\n}\n\n/**\n * Copies one call argument for the `oldArgs` snapshot.\n *\n * A contracted argument is copied the way `populateOld` copies the instance: a new\n * object sharing the argument's prototype, with its own descriptors cloned. The\n * descriptors are read from the target below the proxy, so no lifecycle runs and an\n * argument that is already invalid does not throw while it is being described. A\n * prototype getter on the copy therefore reads the historical own state through\n * `this`, exactly as it does on `old`.\n *\n * Every other value takes the `cloneState` policy, so an argument and a field are\n * described by the same rule. The boundary is consequently the same as `old`'s: the\n * instance at the top of the value is snapshotted, while a contracted instance\n * reached through a plain container is shared by reference.\n */\nconst snapshotArgument = (value: any, seen: WeakMap<object, any>): any => {\n if (typeof value !== 'object' || value === null) return value;\n\n const already = seen.get(value);\n if (already !== undefined) return already;\n\n if (!(value instanceof Contracted)) return cloneState(value, seen);\n\n const copy = Object.create(Object.getPrototypeOf(value));\n seen.set(value, copy);\n copyDescriptors(value, copy, seen);\n\n return copy;\n}\n\n/**\n * Snapshots a call's arguments for the `oldArgs` field of the `@ensures` subject.\n *\n * The arguments are the ones the body receives, so a `@demands` arm that normalized\n * them has already run: a postcondition compares the body's result against the\n * arguments the body was actually given. One `seen` map spans the list, so an object\n * reached twice is one copy in the snapshot, as it was one object to the caller.\n *\n * A value that cannot be described fails here rather than part-way through the\n * contracts. The error names the feature and the argument's position, because the\n * alternative is a foreign error from a `Proxy` trap with nothing to say about which\n * argument caused it.\n */\nconst snapshotArguments = (args: any[], prop: PropertyKey): any[] => {\n const seen = new WeakMap<object, any>();\n\n return args.map((arg, index) => {\n try {\n return snapshotArgument(arg, seen);\n } catch (error) {\n throw new TypeError(\n `@ensures on '${String(prop)}' cannot snapshot argument ${index}: `\n + `a postcondition that describes an argument's pre-state needs every argument to be readable.`,\n { cause: error },\n );\n }\n });\n}\n\n/**\n * Takes the `oldArgs` snapshot for an invocation, or `undefined` when no arm needs it.\n *\n * `hasEnsures` decides whether the work is worth doing at all: with no postcondition\n * there is nothing that could read the snapshot, so the copy is skipped. It is also\n * what makes the snapshot follow the checks-mode switch, because `hasEnsures` is the\n * same condition the postcondition itself runs under.\n */\nconst preStateOfArguments = (\n hasEnsures: boolean,\n args: any[],\n prop: PropertyKey,\n): any[] | undefined =>\n hasEnsures ? snapshotArguments(args, prop) : undefined;\n\n/**\n * Caches the contract wrapper per instance and feature, so `f.m === f.m`.\n *\n * The cache is keyed on the property and resolves the descriptor once, so it\n * assumes the function a property resolves to does not change while the instance\n * lives. Replacing the member on the class prototype is outside both traps and\n * leaves the cache bound to the function it first saw; the prototype an instance\n * resolves through is therefore part of what the cache depends on, which is why the\n * `setPrototypeOf` trap refuses to change it while encapsulation is on.\n */\nconst wrapperCache = new WeakMap<object, Map<PropertyKey, (...args: any[]) => any>>();\n\n/**\n * Stores a wrapper in the instance's cache and returns it.\n *\n * The map is created on first use rather than at construction, because an instance\n * that never has a function read would otherwise carry one for its whole lifetime.\n * Returning the wrapper from here is what lets a caller write the store and the\n * answer as one expression.\n */\nconst cacheWrapper = (\n target: object,\n prop: PropertyKey,\n wrapper: (...args: any[]) => any,\n): (...args: any[]) => any => {\n let cache = wrapperCache.get(target);\n\n if (!cache) {\n cache = new Map();\n wrapperCache.set(target, cache);\n }\n\n cache.set(prop, wrapper);\n\n return wrapper;\n}\n\n// Utility to walk up the prototype chain to find a property descriptor\nfunction getPropertyDescriptor(obj: object, prop: PropertyKey): PropertyDescriptor | undefined {\n let proto = obj;\n while (proto && proto !== Object.prototype) {\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\n if (desc) return desc;\n proto = Object.getPrototypeOf(proto);\n }\n return undefined;\n}\n\n/**\n * The kind of public feature whose boundary is being evaluated.\n *\n * `@ensures` and `@rescue` treat a getter differently from every other feature,\n * and the rule was written out four times: once in the synchronous lifecycle and\n * once in the asynchronous one, for each contract. Naming it here keeps the two\n * lifecycles from drifting apart on the one thing they must agree about.\n */\ntype DescriptorType = 'get' | 'set' | 'func' | 'delete';\n\n/**\n * The arguments an `@ensures` predicate observes.\n *\n * A getter delivers its result as the value the caller receives, so that is what\n * its postcondition describes. Every other feature is described by the arguments\n * it was invoked with.\n */\nconst ensuresArgs = (descriptorType: DescriptorType, result: unknown, args: any[]): any[] =>\n descriptorType === 'get' ? [result] : args;\n\n/**\n * The arguments an `@rescue` retry restarts the lifecycle with.\n *\n * A getter has no arguments to replay, so a retry runs it from scratch.\n */\nconst rescueArguments = (descriptorType: DescriptorType, args: any[]): any[] =>\n descriptorType === 'get' ? [] : args;\n\n/**\n * True when a feature delivers a value to its caller, so that returning a promise\n * instead of a result is a declaration mistake.\n *\n * A write and a deletion have no result the caller receives: the lifecycle carries\n * the assigned value or a boolean verdict. Storing a promise in a field is\n * ordinary — a body may keep one for a later `await` — so the async rule must not\n * reach these paths, or an assignment is reported as a missing `async` keyword\n * naming a property instead of a feature.\n */\nconst deliversValue = (descriptorType: DescriptorType): boolean =>\n descriptorType === 'func' || descriptorType === 'get';\n\n/**\n * True when an error is a contract failure raised by `@invariant`.\n *\n * Used to tell \"the instance is broken\" apart from \"something else failed and the\n * instance may also be broken\". The two are handled differently: a broken instance\n * is the state a handler must repair, so it is never re-tested before the handler\n * runs, and a second failure is not invented on top of the first.\n */\nconst isInvariantFailure = (error: unknown): boolean =>\n error instanceof AssertionError && error.violation?.contract === '@invariant';\n\n/**\n * Raises an invariant failure in place of the error that revealed it.\n *\n * A body or postcondition error can leave the instance in a state the invariant\n * rejects. That failure supersedes the original, because it is the state the caller\n * has to repair, but the original is what explains how the instance got there, so it\n * travels as `cause`.\n */\nconst supersede = (invariantError: unknown, original: unknown): unknown => {\n if (invariantError instanceof AssertionError\n && typeof original === 'object' && original !== null\n && !Object.hasOwn(invariantError, 'cause'))\n Object.defineProperty(invariantError, 'cause', {\n value: original,\n enumerable: false,\n configurable: true,\n });\n\n return invariantError;\n};\n\n/**\n * Raises an invariant failure in place of the error that revealed it.\n *\n * A body or postcondition error can leave the instance in a state the invariant\n * rejects. That failure supersedes the original, because it is the state the caller\n * has to repair, but the original is what explains how the instance got there, so it\n * travels as `cause`. When the instance is still valid the original error stands.\n */\nconst surfaceInvariantFailure = (\n Class: typeof Contracted,\n target: Contracted,\n error: unknown,\n enabled: boolean,\n): unknown => {\n if (isInvariantFailure(error)) return error;\n\n try {\n assertInvariants(Class, target, enabled);\n } catch (invariantError) {\n return supersede(invariantError, error);\n }\n\n return error;\n};\n\n/**\n * Decides what a failed invocation does next.\n *\n * Every lifecycle needs the same three decisions at its `@rescue` boundary:\n * whether another retry is permitted, what the handler asked for, and what happens\n * to an instance the failure left invalid. Extracted because the sync and async\n * lifecycles had this block verbatim twice.\n *\n * The sync and async lifecycles are separate functions on purpose: a lifecycle\n * that awaited unconditionally would make every synchronous feature return a\n * promise, which is not a refactor but a change to every caller. What is shared\n * is the decision, not the boundary.\n *\n * @returns The arguments to retry with, or the error is rethrown.\n */\nfunction attemptRescue(\n Class: typeof Contracted,\n target: Contracted,\n prop: PropertyKey,\n error: unknown,\n retries: number,\n args: any[],\n enabled: boolean,\n): any[] {\n const declaration = getRescueDeclaration(target, prop),\n maxRetries = declaration?.maxRetries ?? Infinity;\n\n if (!declaration || retries >= maxRetries) {\n // The error is on its way to the caller, so the invariant is checked one last\n // time: an invalid instance is the state the caller has to repair, and that\n // failure supersedes the error which revealed it.\n //\n // A handler is not given this check, because it is the thing that repairs the\n // state: re-testing first would report the failure it was called to fix. The\n // consequence is that a handler observes the error that failed — the body's\n // own error when the body threw — while the caller may receive the superseding\n // invariant failure. A class-level `@rescue` serves features that fail in\n // different ways, so that asymmetry is visible there; the handler's subject\n // carries the failing feature's name, which is what it dispatches on.\n throw surfaceInvariantFailure(Class, target, error, enabled);\n }\n\n try {\n return applyRescueHandler(target, prop, error, args);\n } catch (rescuedError) {\n // The handler ran and either threw its own error or returned without asking\n // for a retry. Its repair is over by this point, so an instance it left\n // invalid is reported rather than passed over, and the original is carried as\n // `cause`. Routing through the same helper keeps the caller's error identical\n // whichever path produced it.\n throw surfaceInvariantFailure(Class, target, rescuedError, enabled);\n }\n}\n\n/**\n * Runs the entry invariant for one invocation, giving a `@rescue` one chance to\n * repair it.\n *\n * This is the one boundary a retry cannot restart: nothing has run yet, so the\n * handler's repair is the only thing the next check can observe. A second attempt\n * after a repair that did not satisfy the invariant would fail identically, so the\n * failure is surfaced rather than spent against the retry budget.\n *\n * The exit side needs no equivalent: a retried body can genuinely change the state it\n * returns to, which is why `retry` is unbounded there by default.\n *\n * @param state - The call's argument list and retry count, which the handler may\n * replace and which the repair consumes.\n * @throws Whatever the invariant raises once the repair attempt is spent.\n */\nfunction enterWithRepair(\n Class: typeof Contracted,\n target: Contracted,\n prop: PropertyKey,\n state: { args: any[], retries: number },\n enabled: boolean,\n): void {\n for (let repairs = 0; ;) {\n try {\n assertInvariants(Class, target, enabled);\n\n return;\n } catch (error) {\n if (repairs++ > 0) throw error;\n\n state.args = attemptRescue(Class, target, prop, error, state.retries, state.args, enabled);\n state.retries++;\n }\n }\n}\n\n/**\n * Runs the assertion lifecycle for a single public invocation.\n *\n * The contracts describe the observable boundary of a feature, in the sense of\n * a Hoare triple `{ P } C { Q }`: `@demands` is `P`, `@ensures` is `Q`, and the\n * feature body is `C`. Nothing inside `C` is constrained — a body may mutate its\n * own state, including public properties, and may call its own features without\n * re-entering the contracts. Correctness is the obligation that `P` and `Q` hold\n * at the boundary, with the invariant additionally holding on entry and exit.\n *\n * Order: `@invariant` -> `@demands` -> body -> `@ensures` -> `@invariant`\n * (see `docs/happy-path.png`).\n *\n * A `@rescue` may call `retry`, which restarts the lifecycle from `@invariant`\n * with the supplied arguments, so a retried invocation is subject to\n * `@demands` and `@ensures` like any other invocation\n * (see `docs/order-of-assertions.png`).\n *\n * A retried invocation that fails re-enters `@rescue`, so the handler runs once\n * per attempt. This is what N-Version programming requires: a handler can\n * select the next alternative each time it is executed. Retries are bounded by\n * the optional `maxRetries` option on the `@rescue` declaration.\n *\n * The exit boundary sits wherever the body's result becomes observable, so a\n * synchronous and an asynchronous body are run by separate functions below and\n * dispatched by `runLifecycle`.\n *\n * @param invokeArgs - The arguments for this invocation. `retry` replaces them.\n * @param invoke - Performs the feature body with the supplied arguments.\n */\nfunction runSyncLifecycle(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n enabled: boolean,\n): any {\n const Class = target.constructor as typeof Contracted,\n es = (Class[Symbol.metadata]?.ensures?.[prop] ?? []) as readonly RegisteredEnsures[],\n hasEnsures = es.length > 0;\n\n let args = invokeArgs,\n retries = 0;\n\n for (; ;) {\n const old = needsSnapshot(es) ? populateOld(target, enabled) : undefined;\n\n // The entry invariant may be repaired once by a `@rescue`; see `enterWithRepair`.\n // It is inside the lifecycle so that a broken instance is not unrecoverable:\n // every accessor throws on exit, so a handler could not otherwise reach the\n // state it would fix.\n const state = { args, retries };\n\n enterWithRepair(Class, target, prop, state, enabled);\n args = state.args;\n retries = state.retries;\n\n // `@demands` sits outside every `try`. A precondition rejects a call that has\n // not begun, so there is no body to resume, and a handler that retried with\n // an argument the precondition also rejects would recurse without end. A\n // failed precondition therefore reaches the caller directly.\n args = assertDemands(target, prop, args, enabled);\n\n // The pre-state of the arguments the body is about to receive. Taken after\n // `@demands` so a normalizing arm is reflected, and before the body so a\n // mutation it makes is not visible through `oldArgs`. A retry loops back here\n // and takes a fresh snapshot, so an attempt is described by its own arguments.\n const oldArgs = preStateOfArguments(needsSnapshot(es), args, prop);\n\n let result: any;\n try {\n result = invoke(args);\n\n if (deliversValue(descriptorType))\n assertNotThenable(result, target, prop);\n\n // `old` is absent only when no arm can observe it, which is the one case\n // `assertEnsures` does not need it in: it evaluates a predicate arm only,\n // and there is none.\n if (hasEnsures)\n result = assertEnsures(\n target, old!, prop, ensuresArgs(descriptorType, result, args), result, oldArgs, enabled);\n\n assertInvariants(Class, target, enabled);\n } catch (error) {\n args = attemptRescue(Class, target, prop, error, retries,\n rescueArguments(descriptorType, args), enabled);\n retries++;\n continue;\n }\n\n return result;\n }\n}\n\n/**\n * Runs the exit half of an `async` feature: its postcondition, then the invariant.\n *\n * The two are one unit because both belong to the moment the body's value becomes\n * observable, and separating them would let a caller check the postcondition and\n * forget the invariant.\n *\n * It is deliberately not `async`. A promise is returned only when an arm declared\n * `awaitPredicate`, so a feature whose arms all answer synchronously keeps both\n * checks in the tick the body settled in. Awaiting unconditionally would schedule\n * the exit `@invariant` a microtask later for every `@ensures`, and a concurrent\n * caller resuming into that tick could observe state the check has not approved.\n *\n * @returns The value to hand the caller, or a promise for it when an arm must be\n * awaited.\n */\nfunction runExit(\n Class: typeof Contracted,\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n args: any[],\n result: unknown,\n old: Contracted | undefined,\n oldArgs: any[] | undefined,\n hasEnsures: boolean,\n awaitEnsures: boolean,\n enabled: boolean,\n): unknown {\n if (!hasEnsures) {\n assertInvariants(Class, target, enabled);\n\n return result;\n }\n\n const subject = ensuresArgs(descriptorType, result, args);\n\n if (!awaitEnsures) {\n const checked = assertEnsures(\n target, old!, prop, subject, result, oldArgs, enabled);\n\n assertInvariants(Class, target, enabled);\n\n return checked;\n }\n\n return runAwaitedPostcondition(Class, target, assertEnsuresAsync(\n target, old!, prop, subject, result, oldArgs, enabled), enabled);\n}\n\n/**\n * Waits for a pending postcondition and then checks the exit invariant.\n *\n * The invariant runs after the settlement because that is the only point at which\n * the feature's value and the state the body reached are both final.\n */\nasync function runAwaitedPostcondition(\n Class: typeof Contracted,\n target: Contracted,\n pending: Promise<unknown>,\n enabled: boolean,\n): Promise<unknown> {\n const settled = await pending;\n\n assertInvariants(Class, target, enabled);\n\n return settled;\n}\n\n/**\n * Runs the contract lifecycle whose exit boundary is a promise settlement.\n *\n * An `async` body returns its promise from `Reflect.apply` before a single line\n * of it has run, so evaluating `@ensures` there would test a body that has not\n * executed. The exit boundary must therefore *follow* the value: the lifecycle\n * waits for the promise to settle and then runs `@ensures` and the exit\n * `@invariant` against the settled state.\n *\n * Two consequences shape this loop.\n *\n * The first is failure surface. A contract that is violated on entry is a\n * synchronous throw in `runSyncLifecycle`, but that would be a lie here: an\n * `async` function never throws synchronously, so a caller that adds a\n * precondition must not change how a failure is observed. Entry violations are\n * therefore delivered as a rejection, exactly as the undecorated body's own\n * throws are. Substituting a contracted implementation for a plain one is\n * transparent to the caller, which is the substitutability Liskov requires and\n * which the type system already enforces in both directions (`() => T` and\n * `() => Promise<T>` are mutually non-assignable, so neither is a subtype of the\n * other and no conversion is implied).\n *\n * The second is that `@rescue` must observe rejections, not just synchronous\n * throws. A rescue that retries restarts the lifecycle, so a retried attempt is\n * subject to every contract like any other invocation.\n */\nasync function runAsyncLifecycle(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n enabled: boolean,\n): Promise<any> {\n const Class = target.constructor as typeof Contracted,\n es = (Class[Symbol.metadata]?.ensures?.[prop] ?? []) as readonly RegisteredEnsures[],\n hasEnsures = es.length > 0,\n // Resolved once: the metadata record is fixed for the class, so whether an\n // arm asked to be awaited cannot change during a call. Each reports false\n // for a feature with no arms, so neither needs a separate check.\n awaitDemands = demandsAwaitable(target, prop),\n awaitEnsures = ensuresAwaitable(target, prop);\n\n let args = invokeArgs,\n retries = 0;\n\n for (; ;) {\n const old = needsSnapshot(es) ? populateOld(target, enabled) : undefined;\n\n // The same entry boundary as the synchronous lifecycle. Because this function\n // is `async`, an entry failure is delivered as a rejection rather than a\n // synchronous throw, which keeps the failure surface identical to the\n // undecorated body's.\n const state = { args, retries };\n\n enterWithRepair(Class, target, prop, state, enabled);\n args = state.args;\n retries = state.retries;\n\n // Outside the rescuable scope, for the reason given in the synchronous\n // lifecycle: a rejected precondition has no body to resume, and a retry\n // whose argument it also rejects would recurse without end.\n //\n // The awaited composition is chosen only when an arm declared\n // `awaitPredicate`; otherwise the synchronous one decides the precondition\n // without handing the caller a promise to wait on for a verdict that is\n // already settled.\n args = awaitDemands\n ? await assertDemandsAsync(target, prop, args, enabled)\n : assertDemands(target, prop, args, enabled);\n\n // Taken after `@demands` and before the body, exactly as in the synchronous\n // lifecycle, so it describes the arguments this attempt's body receives.\n const oldArgs = preStateOfArguments(needsSnapshot(es), args, prop);\n\n let result: any;\n try {\n result = await invoke(args);\n\n // The postcondition and the exit invariant form one boundary, and the\n // invariant must not be skipped when a postcondition has to be awaited,\n // so the two are run together rather than inline here. `awaitEnsures`\n // alone decides the wait: it is false when there is no postcondition to\n // check as well as when none of its arms asked to be awaited.\n const exit = runExit(\n Class, descriptorType, target, prop, args, result, old, oldArgs,\n hasEnsures, awaitEnsures, enabled);\n\n result = awaitEnsures ? await exit : exit;\n } catch (error) {\n args = attemptRescue(Class, target, prop, error, retries,\n rescueArguments(descriptorType, args), enabled);\n retries++;\n continue;\n }\n\n return result;\n }\n}\n\n/**\n * Runs the contract lifecycle whose boundary is a generator's iterator.\n *\n * A generator does not have one exit boundary: it has a boundary per *step*.\n * Calling `obj.gen(...)` starts the body but its first line has not run, and each\n * `next()` runs the body until the following `yield`. A yield is therefore the\n * observable delivery of a traversal, which is what `@ensures` describes, and the\n * contracts bracket it accordingly:\n *\n * ```\n * call -> @invariant, @demands (the call arguments are `P`)\n * next() -> body to the next yield\n * -> @ensures, @invariant (the yielded value and the new state are `Q`)\n * ```\n *\n * This is the same sandwich the diagram shows for an ordinary feature\n * (`docs/order-of-assertions.png`), applied once per step. The exit `@invariant`\n * is what closes the window between yields: a suspended generator's instance is\n * publicly reachable, so another feature can be called on it, and that call's\n * entry check is the guarantee that it never observes an invalid object.\n *\n * Checking the invariant *before* handing over a value is not possible — the\n * segment is not finished at the `yield` — so resuming is where the previous\n * step's exit check happens. The terminal step resumes into the same point and\n * then reports `done`, so completion is covered without extra machinery.\n *\n * `@demands` describes the call, so it runs once. A later step may also be\n * *given* a value through `next(value)`, which arrives as the value of the\n * preceding `yield` expression and is entirely outside the arguments of the\n * call. That input is checked when it is present and skipped when it is not,\n * because `for...of` iterates with `next()` and would otherwise re-enter the\n * precondition with `undefined` and fail it.\n *\n * `@rescue` is the outer scope, as it is for an `async` feature: it covers a\n * throw that escapes a step, and `retry` restarts the traversal. Rescuing a\n * single step would require resuming a generator that has already been consumed,\n * which the language cannot express.\n */\nfunction runGeneratorLifecycle(\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n kind: 'generator' | 'async-generator',\n enabled: boolean,\n): any {\n const Class = target.constructor as typeof Contracted,\n es = (Class[Symbol.metadata]?.ensures?.[prop] ?? []) as readonly RegisteredEnsures[],\n hasEnsures = es.length > 0;\n\n /*\n * A generator has a boundary per *step*, not one per call. Calling the\n * feature runs nothing, and each `next()` runs the body from where it was\n * suspended up to the following `yield`. When `next()` returns, the segment\n * has finished and the instance holds the state it will be observed with, so\n * the exit contracts run there, before the caller is given the value:\n *\n * call -> @invariant, @demands the call arguments are `P`\n * next() -> @invariant entry of the step\n * segment -> body to the next yield\n * next() -> @ensures, @invariant the yielded value and state\n *\n * This is the sandwich in `docs/order-of-assertions.png` applied once per\n * step, and it gives the invariant the same guarantee it has elsewhere: no\n * public interaction leaves the object invalid. That matters more here than\n * anywhere else, because a suspended generator's instance is publicly\n * reachable and another feature can be called on it between yields. Checking\n * only at completion would leave the object knowingly invalid for the whole\n * traversal, and would never check at all if the iterator were abandoned.\n */\n\n // The iterator in play. A `@rescue` that retries replaces it.\n let iterator: any,\n args = invokeArgs,\n retries = 0,\n // The invariant has not been evaluated since the traversal began.\n needsEntry = true,\n // The error a `@rescue` handled by retrying, raised if the retried\n // traversal then completes without producing a value.\n retriedError: unknown;\n\n /**\n * Runs the entry contracts for a step.\n *\n * `@demands` describes the call, so it runs once, on the first step. A later\n * step may be *given* a value through `next(value)`, which becomes the value\n * of the preceding `yield` expression and is not an argument of the call;\n * that input is checked as a precondition when it is present. `for...of`\n * iterates with `next()` and injects nothing, so it never re-enters the\n * precondition with `undefined`.\n */\n const enter = (stepArgs: any[]): any[] => {\n assertInvariants(Class, target, enabled);\n\n if (needsEntry) {\n needsEntry = false;\n\n return assertDemands(target, prop, args);\n }\n\n // A value injected with `next(value)` is an input to the step, so it is\n // the subject a precondition describes. `for...of` injects nothing, so\n // it never re-enters the precondition with `undefined`.\n return stepArgs.length > 0 ? assertDemands(target, prop, stepArgs) : stepArgs;\n };\n\n /**\n * Runs the exit contracts for a step that produced a value.\n *\n * A generator's `@ensures` describes the value the step yielded, so there is no\n * argument whose pre-state it could compare: `oldArgs` is empty, on the same\n * grounds as a getter's. The step's pre-state is already `old`.\n */\n const exit = (value: any, old: Contracted | undefined) => {\n if (hasEnsures) assertEnsures(target, old!, prop, [value], value, [], enabled);\n\n assertInvariants(Class, target, enabled);\n\n // A value was delivered, so the retry that recovered the traversal has\n // been observed and the error it handled no longer needs reporting.\n retriedError = undefined;\n };\n\n /**\n * Raises the error a retry was recovering from, when the retried traversal\n * completes without a value. Nothing observed that value, so the caller who\n * triggered the rescue is told why rather than being handed `undefined`.\n */\n const reportRetried = () => {\n assertInvariants(Class, target, enabled);\n\n if (retriedError === undefined) return;\n\n const error = retriedError;\n\n retriedError = undefined;\n\n throw error;\n };\n\n /**\n * Rebuilds the traversal after a `@rescue` retried.\n *\n * A generator that has already been consumed cannot be resumed from the\n * beginning, so a retry restarts it: `retry` reruns the body, exactly as the\n * loop back to `@invariant` in `docs/order-of-assertions.png` says it does.\n */\n const prepareRetry = (error: unknown) => {\n args = attemptRescue(Class, target, prop, error, retries, args, enabled);\n retries++;\n iterator = invoke(args);\n needsEntry = true;\n retriedError = error;\n };\n\n /**\n * Drives one step of a synchronous generator.\n */\n const drive = (advance: (iterator: any, stepArgs: any[]) => any, stepArgs: any[]): any => {\n for (; ;) {\n try {\n // A normalizing schema on an injected value replaces the\n // arguments for this step, so the value the body receives is the\n // one the schema produced.\n stepArgs = enter(stepArgs);\n\n // `old` describes the state the segment is about to change, so\n // it is taken before the body advances.\n const old = needsSnapshot(es) ? populateOld(target, enabled) : undefined,\n result = advance(iterator, stepArgs);\n\n if (result.done) {\n reportRetried();\n\n return result;\n }\n\n exit(result.value, old);\n\n return result;\n } catch (error) {\n prepareRetry(error);\n }\n }\n };\n\n /**\n * Drives one step of an asynchronous generator, awaiting its segment.\n */\n const driveAsync = async (advance: (iterator: any, stepArgs: any[]) => Promise<any>, stepArgs: any[]): Promise<any> => {\n for (; ;) {\n try {\n stepArgs = enter(stepArgs);\n\n const old = needsSnapshot(es) ? populateOld(target, enabled) : undefined,\n result = await advance(iterator, stepArgs);\n\n if (result.done) {\n reportRetried();\n\n return result;\n }\n\n exit(result.value, old);\n\n return result;\n } catch (error) {\n prepareRetry(error);\n }\n }\n };\n\n // The call's entry contracts run when the feature is called, matching the\n // arrow out of `obj.feature(...)` in the diagram. The body itself does not\n // start until the iterator is resumed, so this is the same entry boundary as an\n // ordinary feature and goes through the same helper.\n //\n // `@demands` stays outside, for the reason given in the synchronous lifecycle: a\n // rejected precondition has no traversal to resume, and a retry that violated it\n // again would recurse without end.\n const entry = { args, retries };\n\n enterWithRepair(Class, target, prop, entry, enabled);\n args = entry.args;\n retries = entry.retries;\n\n args = assertDemands(target, prop, args);\n needsEntry = false;\n iterator = invoke(args);\n\n const wrapper: any = {};\n\n if (kind === 'generator') {\n // `arguments.length` distinguishes `next()` from `next(undefined)`, which\n // the engine treats differently: only an explicit value is injected.\n wrapper.next = function (...stepArgs: any[]) {\n return drive((current, args) => current.next(args[0]), stepArgs);\n };\n wrapper.return = function (...returnArgs: any[]) {\n return drive((current, args) => current.return(returnArgs[0] ?? args[0]), []);\n };\n wrapper.throw = function (...errorArgs: any[]) {\n return drive((current, args) => current.throw(errorArgs[0] ?? args[0]), []);\n };\n wrapper[Symbol.iterator] = function () { return this; };\n }\n else {\n wrapper.next = function (...stepArgs: any[]) {\n return driveAsync((current, args) => current.next(args[0]), stepArgs);\n };\n wrapper.return = function (...returnArgs: any[]) {\n return driveAsync((current, args) => current.return(returnArgs[0] ?? args[0]), []);\n };\n wrapper.throw = function (...errorArgs: any[]) {\n return driveAsync((current, args) => current.throw(errorArgs[0] ?? args[0]), []);\n };\n wrapper[Symbol.asyncIterator] = function () { return this; };\n }\n\n return wrapper;\n}\n\n/**\n * Selects the lifecycle boundary for a feature body.\n *\n * An `async` body is awaited through `runAsyncLifecycle` and a generator is\n * wrapped by `runGeneratorLifecycle`; anything else is evaluated synchronously.\n * This is decided from the function itself rather than from whether the result\n * *looks* like a promise, so a synchronous feature that happens to return a\n * thenable is still checked synchronously — the contract describes the feature as\n * written, and such a feature's postcondition cannot hold anyway because its body\n * has not finished. `@demands` therefore fails it with a message naming the\n * feature.\n */\nfunction runLifecycle(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n enabled: boolean,\n kind: FeatureKind = 'sync',\n): any {\n if (kind === 'async')\n return runAsyncLifecycle(descriptorType, target, prop, invokeArgs, invoke, enabled);\n\n if (kind === 'generator' || kind === 'async-generator')\n return runGeneratorLifecycle(target, prop, invokeArgs, invoke, kind, enabled);\n\n return runSyncLifecycle(descriptorType, target, prop, invokeArgs, invoke, enabled);\n}\n\n/**\n * The kind of each getter, keyed by the getter function.\n *\n * A getter is not cached as a wrapper the way a method is: the value depends on the\n * instance's state, so a read has to run its lifecycle every time. The *kind* does\n * not depend on either, and reading it classifies a function's constructor on every\n * read, so it is remembered per function. A `WeakMap` so a replaced accessor holds\n * nothing alive.\n */\nconst getterKinds = new WeakMap<(...args: any[]) => unknown, FeatureKind>();\n\n/** The argument list of an accessor read, which never has any. */\nconst NO_READ_ARGS: any[] = [];\n\n/**\n * Whether an invocation of a feature with these arms needs a pre-state snapshot.\n *\n * Two circumstances say it does not. A feature with no postcondition has nothing that\n * could read one, and a composition made only of schemas cannot observe the predicate\n * subject at all — see `observesNoSubject`. Both are properties of the declaration, so\n * neither depends on guessing what a predicate reads.\n */\nconst needsSnapshot = (es: readonly RegisteredEnsures[]): boolean =>\n es.length > 0 && !observesNoSubject(es);\n\n/**\n * Classifies a getter, remembering the answer for that function.\n *\n * The kind is a property of the function object, and the instance cannot change\n * which function its prototype holds while encapsulation is on, so the classification\n * is stable for as long as the getter is.\n */\nconst getterKindOf = (getter: (...args: any[]) => unknown): FeatureKind => {\n const known = getterKinds.get(getter);\n\n if (known !== undefined) return known;\n\n const kind = featureKindOf(getter);\n\n getterKinds.set(getter, kind);\n\n return kind;\n}\n\n/**\n * Performs one feature invocation, bracketed by its contracts when they are on.\n *\n * The switch is resolved here, once, and it decides whether the lifecycle runs at\n * all. Every contract module guards itself as well, because each is published and\n * may be called on its own, but a feature invocation reaches the lifecycle through\n * this one decision rather than through each of them.\n *\n * The body is performed on the **raw target** whether the contracts run or not.\n * `invoke` is what binds `this`, so skipping the lifecycle here cannot change the\n * receiver a body sees: a body is `C` in `{ P } C { Q }`, and its own writes must\n * land on the instance rather than re-enter the traps as though they came from a\n * caller.\n *\n * @param invoke - Performs the body with an argument list, on the raw target.\n */\nfunction invokeFeature(\n descriptorType: DescriptorType,\n target: Contracted,\n prop: PropertyKey,\n invokeArgs: any[],\n invoke: (args: any[]) => any,\n kind: FeatureKind,\n): any {\n const enabled = contractsEnabled(target.constructor);\n\n // The body runs on the raw target whether the contracts run or not: `invoke` is\n // what binds `this`, so skipping the lifecycle cannot change the receiver a body\n // sees.\n if (!enabled) return invoke(invokeArgs);\n\n return runLifecycle(descriptorType, target, prop, invokeArgs, invoke, enabled, kind);\n}\n\n/**\n * Wraps a method so each invocation is bracketed by its contracts.\n *\n * One wrapper serves both switch positions, and it resolves the switch per\n * invocation rather than capturing it at read time. The switch is assignable on the\n * class at any moment, so a wrapper that remembered the position would keep\n * enforcing after a caller had turned the checks off — or stop enforcing after it\n * had turned them back on.\n *\n * The body receives the raw target as `this`, so an internal access never re-enters\n * a trap. The descriptor is resolved once, from the instance's prototype chain,\n * which is fixed for the lifetime of the instance; the `setPrototypeOf` trap is what\n * keeps that assumption true.\n *\n * @internal\n * Shared by the proxy's `get` trap and its checks-off path so the two cannot drift.\n */\nfunction methodWrapper(\n target: Contracted,\n prop: PropertyKey,\n method: (...args: any[]) => any,\n): (...args: any[]) => any {\n const kind = featureKindOf(method);\n\n return function (this: Contracted, ...methodArgs: any[]) {\n return invokeFeature('func', target, prop, methodArgs,\n (args) => Reflect.apply(method, target, args), kind);\n };\n}\n\n/**\n * Rejects a thenable returned by a feature that is not declared `async`.\n *\n * A synchronous feature's contracts are evaluated when its body returns, so a\n * body that defers its work through a promise is checked before it has done\n * anything. `@ensures` would then describe a state the feature has not reached\n * yet, and the caller would receive a promise whose outcome no contract ever\n * observed.\n *\n * The alternative — awaiting any thenable — was rejected because it would make\n * `async` optional while silently changing when failure is reported: a plain\n * function cannot return a settled value for a rejection to accompany, so the\n * feature would have to become `async` for its errors to be observable anyway.\n * Failing closed keeps the declaration and the boundary in agreement, and the\n * message says what to do.\n */\nconst assertNotThenable = (result: unknown, target: Contracted, prop: PropertyKey): void => {\n if (result === null || typeof result !== 'object' && typeof result !== 'function') return;\n\n if (typeof (result as any).then !== 'function') return;\n\n throw new AssertionError(\n `${classNameOf(target.constructor)}.${String(prop)} returned a promise but is not declared 'async', `\n + \"so its contracts were evaluated before its body finished. Declare the feature 'async'.\",\n );\n}\n\n/**\n * Performs the assignment a `set` trap authorised.\n *\n * `Reflect.set` is called without a receiver on purpose. Passing the proxy would\n * route the write back through the `defineProperty` trap, which refuses an\n * external definition of a public property. The name is already authorised by the\n * caller, so writing the target directly performs exactly that mutation.\n *\n * @returns Whether the target accepted the write. A setter's assignment is\n * reported as accepted, because the setter ran.\n */\nconst performSet = (\n target: Contracted,\n prop: PropertyKey,\n value: unknown,\n setter: ((value: unknown) => void) | undefined,\n): boolean => {\n if (setter) {\n setter.call(target, value);\n\n return true;\n }\n\n // A target that cannot accept the write, because `Object.freeze` or\n // `Object.preventExtensions` was applied, reports `false`, which strict mode\n // turns into a `TypeError`.\n return Reflect.set(target, prop, value);\n};\n\n/**\n * Refuses an instance-level write to an enforcement switch.\n *\n * The switches are static, so a write here could only land on the raw target,\n * out of reach of every trap. A switch a caller can set is a guarantee a caller\n * can remove, so the attempt is refused wherever it happens — including when both\n * switches are off, because that is exactly the state a caller would want to\n * escape from.\n */\nconst refuseSwitchWrite = (prop: PropertyKey): void => {\n if (!isSwitch(prop)) return;\n\n throw new TypeError(\n `Cannot set '${String(prop)}' on a Contracted instance: enforcement is switched on the class, `\n + `not on an instance. Assign '${String(prop)}' on the class itself.`,\n );\n};\n\n/**\n * Returns the cached wrapper for a feature, creating it on the first read.\n *\n * A wrapper is reusable because it is bound to the instance and the property, and the\n * function it dispatches to is resolved from a prototype chain the instance cannot\n * change while encapsulation is on. Caching is also what keeps `instance.feature` a\n * stable reference, so a detached method call keeps working.\n */\nconst wrapperFor = (\n target: Contracted,\n prop: PropertyKey,\n method: (...args: any[]) => any,\n): (...args: any[]) => any =>\n wrapperCache.get(target)?.get(prop) ?? cacheWrapper(target, prop, methodWrapper(target, prop, method));\n\n/**\n * Resolves one member read for the `get` trap.\n *\n * JavaScript resolves an own property before the prototype chain, and the trap has\n * to do the same: an own property is what a field initializer or a body wrote, and it\n * shadows the prototype member of the same name. A chain walk alone cannot see it.\n * Reading the own descriptor first is also the cheaper order, because own state is\n * read far more often than a prototype feature and a miss cannot happen.\n *\n * An own property is **state**, never a declared feature: a decorator refuses a\n * private name, so every contracted member's descriptor stays on the prototype. The\n * read is therefore an ordinary `Reflect.get`, with no wrapper. Wrapping a\n * function-valued own property would break the `get` invariant on a frozen instance\n * (the trap must return the property's actual value), would run the lifecycle for a\n * callback that is not a feature, and would report a replaced callback through the\n * wrapper cached against the property name.\n *\n * `constructor` is read the same way, for its own reason: it is the class's\n * **identity**, not a feature. A decorator cannot target it — a class body's\n * `constructor` is the constructor itself, which `assertFeatureContractTarget`\n * refuses — so there is no contract to bracket and no feature for a wrapper to\n * dispatch to. Returning the class is what keeps `instance.constructor === Class`\n * and `instance.constructor.name` true for code that inspects an instance from\n * outside; a wrapper is an anonymous function that is neither.\n *\n * `Reflect.get` on the raw target rather than a read of the prototype keeps the\n * language's own rule: an own `constructor` a body installed shadows the inherited\n * one, exactly as it would on a plain object.\n *\n * @param own - The target's own descriptor, if it has one.\n */\nconst readMember = (\n target: Contracted,\n prop: PropertyKey,\n receiver: unknown,\n own: PropertyDescriptor | undefined,\n): any => {\n if (prop === 'constructor' || own) return Reflect.get(target, prop, receiver);\n\n const descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop);\n\n if (typeof descriptor?.value === 'function')\n return wrapperFor(target, prop, descriptor.value);\n\n if (typeof descriptor?.get === 'function')\n return invokeFeature('get', target, prop, NO_READ_ARGS,\n () => descriptor.get!.call(target), getterKindOf(descriptor.get!));\n\n return Reflect.get(target, prop, receiver);\n}\n\nconst proxyHandler: ProxyHandler<Contracted> = {\n get(target, prop, receiver) {\n return readMember(target, prop, receiver,\n Object.getOwnPropertyDescriptor(target, prop));\n },\n set(target, prop, value) {\n refuseSwitchWrite(prop);\n\n const encapsulation = encapsulationEnabled(target.constructor),\n descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop),\n setter = typeof descriptor?.set === 'function' ? descriptor.set : undefined;\n\n // Encapsulation is the name check below: it exists so a caller cannot\n // mutate state without a postcondition to catch it. It governs the external\n // surface only — inside a body, `@ensures` and `@invariant` provide that\n // guarantee instead.\n //\n // The switch removes this verdict, not the lifecycle. A permitted write is\n // still a feature invocation, so it is bracketed like any other and a\n // setter's postcondition describes it. Skipping the lifecycle here would\n // make the two switches dependent after all: turning encapsulation off\n // would silently stop the contracts running on every write.\n if (encapsulation && !setter && typeof prop === 'string' && !prop.startsWith('_'))\n throw new TypeError(`Cannot assign to property '${String(prop)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);\n\n // Only the contracts describe a feature; the write itself is a property of\n // the trap. With the contracts off the assignment runs directly, so the\n // contracts switch is not resolved on this path.\n if (!contractsEnabled(target.constructor)) return performSet(target, prop, value, setter);\n\n // A setter's lifecycle result is the assigned value, which is what a\n // postcondition describes. Whether the write was accepted is a property of\n // the trap rather than of the feature, so it is tracked separately instead\n // of being inferred from that value — `false` is both a legitimate value to\n // assign and the failure `Reflect.set` reports.\n let accepted = true;\n\n runLifecycle('set', target, prop, [value],\n (args) => {\n accepted = performSet(target, prop, args[0], setter);\n\n return args[0];\n }, true);\n\n return accepted;\n },\n defineProperty(target, prop, descriptor) {\n refuseSwitchWrite(prop);\n\n if (!encapsulationEnabled(target.constructor))\n return Reflect.defineProperty(target, prop, descriptor);\n\n // Defining a property is an external mutation, so it follows the same\n // rule as assignment. Redefining a public field escapes the\n // postcondition that would have caught the change, and replacing a\n // contracted method routes callers around its `@demands` and\n // `@ensures`.\n //\n // Only `_`-prefixed names are permitted. A prototype setter does not\n // widen this: assignment invokes the setter, while defining an own\n // data property shadows the accessor.\n //\n // A descriptor carrying neither a value nor an accessor cannot change\n // or shadow state, so any name is permitted. `Object.freeze` and\n // `Object.seal` define such descriptors for each existing property,\n // and refusing them would make an instance impossible to freeze.\n const freezesOnly = !('value' in descriptor) && !('get' in descriptor) && !('set' in descriptor);\n\n if (!freezesOnly && typeof prop === 'string' && !prop.startsWith('_'))\n throw new TypeError(\n `Cannot define property '${String(prop)}' on Contracted instances: only properties starting with '_' can be defined.`\n + ' A feature body may change its own state, but an external caller must go through a method or a setter.',\n );\n\n return Reflect.defineProperty(target, prop, descriptor);\n },\n setPrototypeOf(target, prototype) {\n // Replacing the prototype is an external mutation of the instance, so\n // encapsulation governs whether it is permitted. It is not a feature call,\n // so no lifecycle would have run for it either way.\n if (!encapsulationEnabled(target.constructor))\n return Reflect.setPrototypeOf(target, prototype);\n\n // Replacing the prototype swaps which descriptors a feature resolves to.\n // The per-feature wrappers are cached against `prop` for the lifetime of\n // the instance and would then dispatch to the wrong function, and the\n // contract metadata is reached through the constructor, so the instance\n // would report one class's contracts while running another's methods.\n throw new TypeError(\n 'Cannot change the prototype of a Contracted instance: it would detach the instance from the features and contracts it was constructed with.',\n );\n },\n preventExtensions(target) {\n // Permitted for any property name: it changes no state and shadows no\n // accessor. The `set` trap reports the write failures that follow.\n return Reflect.preventExtensions(target);\n },\n deleteProperty(target, prop) {\n refuseSwitchWrite(prop);\n\n const encapsulation = encapsulationEnabled(target.constructor);\n\n // Deletion follows the same rule as assignment: it is an external mutation,\n // so it is subject to encapsulation and to the lifecycle. Only `_`-prefixed\n // properties, the ones a caller is allowed to mutate in the first place, may\n // also be removed.\n //\n // The switch removes this verdict, not the lifecycle, for the reason `set`\n // gives: a permitted deletion is still an external mutation of the instance,\n // so its `@invariant` still has to hold afterwards.\n if (encapsulation && typeof prop === 'string' && !prop.startsWith('_'))\n throw new TypeError(`Cannot delete property '${String(prop)}' from Contracted instances: only properties starting with '_' can be deleted.`);\n\n return invokeFeature('delete', target, prop, [], () => Reflect.deleteProperty(target, prop), 'sync');\n },\n};\n\nexport class Contracted {\n /**\n * The contracts declared on this class, keyed by the feature they belong to.\n *\n * `undefined` when the class declares none, because the metadata record is\n * created by the first decorator to run rather than by the class itself.\n *\n * Read it through {@link getContractMetadata} rather than indexing this symbol:\n * the accessor returns copies, so a consumer cannot corrupt the contracts a\n * class is checked against by mutating what it was handed.\n *\n * The shape is stable for the major version. Fields may be added, but an\n * existing field will not change meaning without one.\n */\n static [Symbol.metadata]: ContractMetadata | undefined;\n\n /**\n * Grants permission for exactly one `Contracted` constructor call.\n *\n * A boolean would leave the gate open for the whole duration of the\n * constructor, so a class that called `new Foo()` inside its own\n * constructor — directly or through a superclass — would obtain a raw,\n * unproxied instance and defeat every contract.\n *\n * `Contracted`'s constructor runs exactly once per construction, so a\n * single-use token is enough. Classes that do not declare their own\n * constructor call it implicitly; classes that do must call `super()` once.\n */\n protected static _allowedConstructions = 0;\n\n /**\n * Whether the contracts declared on this class are evaluated.\n *\n * Assign it on a class to opt that class — and any class extending it that\n * does not declare its own — out of `@invariant`, `@demands`, `@ensures`, and\n * `@rescue`, without affecting a sibling or the rest of the process:\n *\n * ```typescript\n * class DataHolder extends Contracted {\n * static [checkedMode] = false;\n * }\n * ```\n *\n * It is separate from {@link encapsulationMode} so a class can keep the write\n * protection while skipping the checks. Both default to `true`, and the\n * nearest declaration on the class chain decides.\n *\n * Set it **through the class**. An instance write would land on the raw target,\n * where no trap can refuse it.\n */\n public static [checkedMode]: boolean = true;\n\n /**\n * Whether an external write, definition, or deletion on this class's instances\n * is trapped.\n *\n * Assign it on a class exactly as {@link checkedMode}, with the same scope: the\n * class and the subclasses that do not declare their own. Disabling it makes\n * the instance behave like a plain object for mutation, while the contracts\n * still run when `checkedMode` is left on.\n */\n public static [encapsulationMode]: boolean = true;\n\n static new<\n C extends typeof Contracted,\n Args extends ConstructorParameters<C>,\n >(this: C, ...args: Args): InstanceType<C> {\n const previous = (this as any)._allowedConstructions;\n\n (this as any)._allowedConstructions = previous + 1;\n\n try {\n const instance = new this(...args) as InstanceType<C>;\n assertInvariants(this, instance);\n\n return new Proxy<InstanceType<C>>(instance, proxyHandler);\n } finally {\n // Restore rather than decrement: the constructor consumes the token,\n // so decrementing here would double-count. Restoring also clears it\n // if the constructor threw for any reason.\n (this as any)._allowedConstructions = previous;\n }\n }\n\n constructor(..._args: any[]) {\n const Class = this.constructor as typeof Contracted;\n\n if (Class._allowedConstructions <= 0)\n throw new TypeError(\"Use the static 'new' method to instantiate this class.\");\n\n // Consume the token so a nested `new` inside a constructor cannot\n // borrow the outer construction's permission.\n Class._allowedConstructions--;\n }\n}\n\n/**\n * Installs the `util.inspect` rendering on every contracted class.\n *\n * The surface itself lives in `inspect.mts`, which owns the key it is registered\n * under; this is the one place a library class is available to attach it to.\n */\ninstallInspect(Contracted.prototype);\n","import type { Contracted } from './Contracted.mjs';\nimport type { RegisteredDemands } from './demands.mjs';\nimport type { RegisteredEnsures } from './ensures.mjs';\nimport type { RegisteredInvariant } from './invariant.mjs';\nimport { rescueDeclarationOf, type RescueDeclaration } from './rescue.mjs';\n\n/**\n * The contracts a class declares, as {@link getContractMetadata} reports them.\n *\n * This is the shape stored on `Contracted[Symbol.metadata]`, but read through the\n * accessor rather than the symbol so that a consumer receives copies and cannot\n * corrupt the contracts a class is checked against.\n *\n * Every list is already the **effective** set: a subclass's record contains its\n * own declarations and the inherited ones, because each decorator registers by\n * spreading the record it inherited. A consumer therefore never has to walk the\n * prototype chain itself.\n */\nexport interface ContractMetadata {\n /**\n * The class-level invariant arms.\n *\n * Unlike the feature contracts these are not keyed by feature: an invariant\n * describes the whole instance, so every arm applies to every call.\n */\n invariants: readonly RegisteredInvariant[];\n\n /** Precondition arms, keyed by feature name. */\n demands: Readonly<Record<PropertyKey, readonly RegisteredDemands[]>>;\n\n /** Postcondition arms, keyed by feature name. */\n ensures: Readonly<Record<PropertyKey, readonly RegisteredEnsures[]>>;\n\n /**\n * The rescue declaration, keyed by feature name.\n *\n * A map rather than a list because a feature has one handler: a second\n * `@rescue` on the same feature replaces the first.\n */\n rescue: Readonly<Record<PropertyKey, RescueDeclaration<Contracted>>>;\n\n /**\n * The class-level rescue declaration, which applies to every feature that\n * declares none of its own.\n *\n * Separate from {@link rescue} because the two forms are keyed differently: a\n * feature declaration is stored under the feature's name, and a class\n * declaration exists once for the whole class. `undefined` when neither this\n * class nor an ancestor declared one.\n */\n classRescue: RescueDeclaration<Contracted> | undefined;\n}\n\n/**\n * The contracts that apply to one feature, in the order they are evaluated.\n *\n * Each list is the effective composition for the feature: inherited arms first,\n * then the class's own, and within one class in **reverse source order**, because\n * decorators evaluate bottom-up. That order is the one the contract runtime uses,\n * so an assertion built from this list describes what actually happens.\n */\nexport interface FeatureContracts {\n /** The feature's precondition arms, in evaluation order. */\n demands: readonly RegisteredDemands[];\n\n /** The feature's postcondition arms, in evaluation order. */\n ensures: readonly RegisteredEnsures[];\n\n /**\n * The feature's effective rescue declaration, absent when neither it nor its\n * class declares one.\n */\n rescue: RescueDeclaration<Contracted> | undefined;\n}\n\nconst NO_ARMS: readonly never[] = Object.freeze([]);\n\nconst EMPTY: ContractMetadata = Object.freeze({\n invariants: NO_ARMS as readonly RegisteredInvariant[],\n demands: Object.freeze({}),\n ensures: Object.freeze({}),\n rescue: Object.freeze({}),\n classRescue: undefined,\n});\n\n/**\n * Copies a registered arm so that its fields cannot be reassigned through the\n * accessor.\n *\n * The `arm` itself is **not** copied. It is a predicate or a schema the consumer\n * wrote, and its identity is what lets a consumer compare what they declared\n * against what the class reports, so the reference is preserved deliberately. Only\n * the record around it is copied, which is what stops a caller replacing the arm\n * the runtime evaluates.\n *\n * `options` is spread rather than shared for the same reason: it is a small\n * declaration record, and sharing it would leave `normalize` writable on the live\n * declaration even though the entry around it is a copy.\n */\nconst copyArm = <Entry extends { arm: unknown; options?: object }>(entry: Entry): Entry =>\n Object.freeze({\n ...entry,\n ...(entry.options ? { options: Object.freeze({ ...entry.options }) } : {}),\n }) as Entry;\n\n/**\n * Copies a rescue declaration.\n *\n * `handler` keeps its identity for the reason `copyArm` gives for `arm`; the\n * record around it is copied so `maxRetries` cannot be rewritten after the class\n * is defined.\n */\nconst copyRescue = <Declaration extends { handler: unknown }>(declaration: Declaration): Declaration =>\n Object.freeze({ ...declaration }) as Declaration;\n\n/**\n * Copies a record of rescue declarations.\n *\n * Each declaration is copied for the reason {@link copyRescue} gives, and the map\n * itself is copied so a feature cannot be given a handler the class never declared.\n */\nconst copyRescueMap = (\n source: Readonly<Record<PropertyKey, { handler: unknown }>> | undefined,\n): Readonly<Record<PropertyKey, never>> => {\n if (!source) return Object.freeze({});\n\n const copy: Record<PropertyKey, unknown> = {};\n\n for (const key of Reflect.ownKeys(source))\n copy[key] = copyRescue(source[key]);\n\n return Object.freeze(copy) as Readonly<Record<PropertyKey, never>>;\n};\n\n/**\n * Copies a record of per-feature entries.\n *\n * Both the array and each entry are copied. Freezing the array alone is shallow:\n * it refuses `push`, and leaves `entries[0].arm = …` writing through to the record\n * the runtime consults. A copied entry refuses that assignment while the `arm` it\n * carries is still the consumer's own function.\n */\nconst copyEntries = <Entry extends { arm: unknown; options?: object }>(\n source: Readonly<Record<PropertyKey, readonly Entry[]>> | undefined,\n): Readonly<Record<PropertyKey, readonly Entry[]>> => {\n if (!source) return Object.freeze({});\n\n const copy: Record<PropertyKey, readonly Entry[]> = {};\n\n for (const key of Reflect.ownKeys(source))\n copy[key] = Object.freeze((source[key] as readonly Entry[]).map(copyArm));\n\n return Object.freeze(copy);\n};\n\n/**\n * Reports the contracts declared on a class.\n *\n * Use this instead of reading `Contracted[Symbol.metadata]`. The symbol is a\n * supported read surface, but the record it holds is the one the runtime consults,\n * so a consumer who reaches it directly can edit the contracts their own class is\n * checked against. This returns copies.\n *\n * A class that declares nothing — including `Contracted` itself, and any subclass\n * that adds no decorator — has no record at all, and reports an empty one.\n *\n * @param Class - The class to inspect.\n * @returns The class's effective contracts. Stable across calls in the sense that\n * the declared arms do not change after the class is defined.\n */\nexport function getContractMetadata<Class extends typeof Contracted>(\n Class: Class,\n): ContractMetadata {\n const metadata = Class[Symbol.metadata] as ContractMetadata | undefined;\n\n if (!metadata) return EMPTY;\n\n return Object.freeze({\n invariants: Object.freeze((metadata.invariants ?? []).map(copyArm)),\n demands: copyEntries<RegisteredDemands>(metadata.demands),\n ensures: copyEntries<RegisteredEnsures>(metadata.ensures),\n rescue: copyRescueMap(metadata.rescue),\n classRescue: metadata.classRescue && copyRescue(metadata.classRescue),\n });\n}\n\n/**\n * Reports the contracts that apply to one feature, in the order they are evaluated.\n *\n * This is what an architectural test usually wants: \"every public verb declares a\n * precondition\" is a question about one feature, and the answer depends on the\n * inherited arms as well as the class's own. Because each decorator registers by\n * spreading the record it inherited, the effective list is already assembled — this\n * reads it without walking the prototype chain.\n *\n * @param Class - The class to inspect.\n * @param feature - The feature's name.\n * @returns The feature's arms in evaluation order, or empty lists when it declares\n * none. `rescue` is the declaration the runtime would actually apply: the\n * feature's own when it declares one, otherwise the class-level declaration.\n */\nexport function getFeatureContracts<Class extends typeof Contracted>(\n Class: Class,\n feature: PropertyKey,\n): FeatureContracts {\n const metadata = getContractMetadata(Class),\n rescue = rescueDeclarationOf(metadata, feature);\n\n return Object.freeze({\n demands: (metadata.demands[feature] ?? NO_ARMS) as readonly RegisteredDemands[],\n ensures: (metadata.ensures[feature] ?? NO_ARMS) as readonly RegisteredEnsures[],\n // Already a copy: `getContractMetadata` copied the map. Re-copied here so\n // that the object a caller mutates is not the one they received from the\n // other accessor.\n rescue: rescue && copyRescue(rescue),\n });\n}\n","/**\n * Opt-in JSON serialization for a contracted class.\n *\n * https://github.com/final-hill/decorator-contracts/issues/341\n *\n * A contracted instance serializes its own data properties, which are the\n * `_`-prefixed fields the library's convention marks private:\n *\n * ```text\n * JSON.stringify(instance) // {\"_balance\":5,\"_orgId\":\"o\"}\n * ```\n *\n * That is a leak, but the fix cannot be a default `toJSON`. Which fields are\n * \"public\" is a decision about the consumer's domain, and the `_` prefix is a\n * convention the library enforces for assignment rather than a declaration of what\n * may be published. A default would also change what `JSON.stringify` emits for\n * every existing class, which is the kind of silent break a library cannot make.\n *\n * So a class opts in, naming the getters it wants published:\n *\n * ```typescript\n * import { Contracted, serializable } from '@final-hill/decorator-contracts';\n *\n * @serializable('balance', 'orgId')\n * class Account extends Contracted {\n * protected _balance = 0;\n * protected _orgId = 'o';\n *\n * get balance() { return this._balance; }\n * get orgId() { return this._orgId; }\n * }\n *\n * JSON.stringify(Account.new()); // {\"balance\":0,\"orgId\":\"o\"}\n * ```\n *\n * Naming getters rather than fields is deliberate. A field name is storage; a\n * getter is the class's own statement of what is observable, and it is already the\n * only way an external caller reads state the encapsulation rule protects. The\n * published shape is therefore the shape a caller can already see, and it cannot\n * drift from the class's public surface without the class saying so.\n */\n\nimport { assertDecoratorContext } from './decorator.mjs';\nimport { Contracted } from './Contracted.mjs';\nimport { classNameOf } from './name.mjs';\n\n/** The property `JSON.stringify` looks for. */\nconst TO_JSON = 'toJSON';\n\n/**\n * The name a diagnostic reports for `Class`.\n *\n * The class's declared name when it has one, so a message names the class the way\n * every other diagnostic does.\n *\n * @param Class - The constructor the decorator was given.\n */\nconst nameOf = (Class: unknown): string => classNameOf(Class);\n\n/**\n * The classes this decorator has already been applied to.\n *\n * Recorded so a second application is reported as the duplicate declaration it is,\n * rather than as a conflict with a `toJSON` the author never wrote.\n */\nconst published = new WeakSet<object>();\n\n/**\n * Resolves a property descriptor from `start` up the prototype chain.\n *\n * Walks the chain because a subclass may publish a getter it inherited.\n *\n * @param start - The prototype to search from.\n * @param feature - The property name.\n */\nconst descriptorOf = (start: object, feature: string): PropertyDescriptor | undefined => {\n for (let proto: any = start; proto && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, feature);\n\n if (descriptor) return descriptor;\n }\n\n return undefined;\n};\n\n/**\n * Builds the `toJSON` method for a class that publishes `features`.\n *\n * A getter is read through its descriptor rather than through `this`. The body of a\n * feature runs against the raw target, so `this[feature]` would work here too — but\n * only by accident, and only while nothing changes that. Reaching the descriptor\n * says what is meant: read this getter, now, from the object being written, without\n * depending on how the proxy happens to hand the body its receiver.\n *\n * `toJSON` is itself a public feature, so the proxy brackets it and the entry and\n * exit `@invariant` hold around the whole serialization. A reader learns that the\n * object written is one the instance's invariant accepted.\n *\n * A getter that throws propagates. That is the getter's own behaviour, and\n * suppressing it would emit a partial object that looks complete.\n *\n * @param features - The getter names to publish, in the order they are emitted.\n * @returns The `toJSON` method.\n */\nconst serializeWith = (features: readonly string[]) =>\n function (this: Contracted): Record<string, unknown> {\n const result: Record<string, unknown> = {},\n // `getPrototypeOf` is not trapped, so this is the class the consumer\n // declared rather than the proxy's wrapper for it.\n start = Object.getPrototypeOf(this);\n\n for (const feature of features) {\n const descriptor = descriptorOf(start, feature);\n\n if (descriptor?.get) result[feature] = descriptor.get.call(this);\n }\n\n return result;\n };\n\n/**\n * Rejects a `@serializable` target that the decorator cannot honour.\n *\n * Four independent declarations are possible and each has its own remedy, so the\n * checks live together rather than interleaved with the installation. Collecting\n * them also keeps the decorator itself a short pipeline, which is what a reader\n * needs from a declaration site.\n *\n * @param Class - The value the decorator was applied to.\n * @param features - The getter names it was given.\n * @throws {TypeError} For the reason each check exists.\n */\nfunction assertPublishable(Class: unknown, features: readonly string[]): asserts Class is typeof Contracted {\n if (Class === null || typeof Class !== 'function' || !(Class.prototype instanceof Contracted))\n throw new TypeError('@serializable decorator can only be applied to classes that extend Contracted');\n\n if (features.length === 0)\n throw new TypeError(\n '@serializable was given no features, so it would publish an empty object for every instance. '\n + 'Name the getters to publish; a class that publishes nothing does not need the decorator.',\n );\n\n // An own `toJSON` is the class's own statement of its published shape, so the\n // decorator does not overwrite it. Reported rather than accepted, because the\n // two declarations cannot both be the shape the class publishes and the author\n // needs to know which one is in force. A second application of this decorator\n // lands in the same place, so it is named separately — it is a different\n // mistake and the remedy differs.\n if (!Object.hasOwn(Class.prototype, TO_JSON)) return;\n\n throw new TypeError(\n published.has(Class)\n ? `${nameOf(Class)} declares @serializable more than once, so two shapes were given for one class. Apply it once with the full list.`\n : `${nameOf(Class)} already declares its own 'toJSON', so the shape it publishes is that method's `\n + 'and not the one @serializable was given. Remove one of the two.',\n );\n};\n\n/**\n * Publishes the named getters through `JSON.stringify`.\n *\n * Every name is checked at decoration time, where the author is looking at the\n * declaration, rather than at serialization time where the diagnostic would arrive\n * in a logger.\n *\n * The method is installed on the class's **own** prototype, so a subclass that\n * declares its own `@serializable` publishes its own shape rather than the base's.\n * A subclass that declares nothing inherits the base's publication, which is the\n * substitution rule: the subclass *is* a `Base`, so the shape a `Base` publishes is\n * the shape it publishes. Contrast `contractName`, which is declared rather than\n * inherited because a name answers who a class is, while a serialized shape answers\n * what a class is.\n *\n * @param features - The getter names to publish, in the order they are emitted.\n * @returns A class decorator.\n * @throws {TypeError} If the target is not a `Contracted` class, if no feature is\n * named, if a named feature is not a getter, or if the class declares its\n * serialization twice.\n */\nexport const serializable = (...features: string[]) => (Class: unknown, context: DecoratorContext): void => {\n assertDecoratorContext('@serializable', context);\n\n if (context.kind !== 'class')\n throw new TypeError('@serializable decorator can only be applied to classes');\n\n assertPublishable(Class, features);\n\n for (const feature of features) {\n const descriptor = descriptorOf(Class.prototype, feature);\n\n if (typeof descriptor?.get !== 'function')\n throw new TypeError(\n `@serializable was given '${feature}', which is not a getter on ${nameOf(Class)}. `\n + 'Name the getters that describe the published shape; a field is storage rather than an observable.',\n );\n }\n\n Object.defineProperty(Class.prototype, TO_JSON, {\n value: serializeWith(features),\n // Non-enumerable and fixed, so the published shape is the decorator's\n // declaration and not something a caller can replace afterwards.\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n published.add(Class);\n};\n"],"names":["Symbol","metadata","for","AssertionError","Error","name","violation","constructor","message","super","this","readOnlyViews","WeakMap","readOnlyView","target","cached","get","view","Proxy","set","_target","property","TypeError","String","deleteProperty","defineProperty","isSchema","arm","describeArm","vendor","version","assertNormalizable","contract","options","normalize","assertAwaitableArm","awaitPredicate","assertViolationFactory","undefined","onViolation","selectViolationFactory","entries","assertNotWeakenable","allowWeakening","reportedFeatures","evaluateArm","subjects","label","index","evaluateSchema","schema","evaluatePredicate","predicate","evaluateArmAsync","async","subject","verdict","invokePredicate","thrown","ok","assertContractResult","self","then","result","validate","issues","value","FailureLog","record","failures","failed","push","recordFailure","failureLog","assert","condition","Boolean","describeContractResult","JSON","stringify","Object","prototype","toString","call","describeViolation","className","feature","arms","failedIndices","summary","describe","thrownIndices","map","entry","thrownDescriptions","named","describeThrown","predicates","length","describeMessage","where","threw","Set","detail","source","position","has","join","describeArms","count","total","singular","plural","nounPlural","issue","path","segment","key","describeIssue","violationError","annotated","WeakSet","annotate","raised","cause","fromFactory","isExtensible","mine","supplied","hasOwn","enumerable","configurable","add","violationFailure","factory","error","factoryFailure","iff","p","q","implies","contractName","classNameOf","Class","declared","inspectKey","rendering","featureKindOf","fn","assertDecoratorContext","context","kind","assertFeatureContractTarget","static","private","startsWith","addInitializer","Contracted","assertAwaitableFeature","element","assertInvariants","instance","enabled","contractsEnabled","registered","invariant","OriginalClass","assertNotAwaitable","assertNotNormalizable","assertNotViolationFactory","existing","invariants","NO_ARMS","freeze","demands","ctx","features","alreadyReported","inherited","console","warn","reportWeakeningArm","getPrototypeOf","inheritedArms","ds","demandsSubjects","args","raiseDemandsFailure","propertyKey","assertDemands","assertDemandsAsync","ensures","es","normalizers","filter","ensuresSubjects","old","oldArgs","raiseEnsuresFailure","foldOutcome","outcome","normalized","assertEnsures","rescue","handler","maxRetries","classRescue","rescueDeclarationOf","getRescueDeclaration","proto","Function","declaration","applyRescueHandler","hasRetried","retryArgs","retry","retryArguments","checkedMode","encapsulationMode","switchOn","symbol","C","encapsulationEnabled","cloneState","seen","already","Date","getTime","container","cloneContainer","isPlainObject","copy","create","copyDescriptors","Array","isArray","item","Map","k","v","Reflect","ownKeys","descriptor","getOwnPropertyDescriptor","cloned","defineOrAssign","writable","populateOld","buildState","captureState","preStateOfArguments","hasEnsures","prop","arg","snapshotArgument","snapshotArguments","wrapperCache","getPropertyDescriptor","obj","desc","ensuresArgs","descriptorType","rescueArguments","deliversValue","surfaceInvariantFailure","isInvariantFailure","invariantError","original","supersede","attemptRescue","retries","Infinity","rescuedError","enterWithRepair","state","repairs","runExit","awaitEnsures","checked","pending","settled","runAwaitedPostcondition","assertEnsuresAsync","runLifecycle","invokeArgs","invoke","awaitDemands","some","demandsAwaitable","ensuresAwaitable","needsSnapshot","exit","runAsyncLifecycle","iterator","retriedError","needsEntry","enter","stepArgs","reportRetried","prepareRetry","drive","advance","done","driveAsync","wrapper","next","current","return","returnArgs","throw","errorArgs","asyncIterator","runGeneratorLifecycle","assertNotThenable","runSyncLifecycle","getterKinds","NO_READ_ARGS","every","invokeFeature","performSet","setter","refuseSwitchWrite","isSwitch","readMember","receiver","own","method","cache","cacheWrapper","methodArgs","apply","methodWrapper","wrapperFor","getter","known","getterKindOf","proxyHandler","encapsulation","accepted","setPrototypeOf","preventExtensions","previous","_allowedConstructions","_args","depth","inspect","remaining","rendered","getOwnPropertyDescriptors","delete","EMPTY","copyArm","copyRescue","copyRescueMap","copyEntries","getContractMetadata","getFeatureContracts","TO_JSON","nameOf","published","descriptorOf","start","serializeWith","serializable","assertPublishable"],"sourceRoot":""}