@final-hill/decorator-contracts 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +488 -9
- package/dist/AssertionError.d.mts +50 -1
- package/dist/Contracted.d.mts +15 -3
- package/dist/admissibility.d.mts +81 -0
- package/dist/assert.d.mts +53 -0
- package/dist/decorator.d.mts +12 -0
- package/dist/demands.d.mts +51 -3
- package/dist/ensures.d.mts +36 -3
- package/dist/iff.d.mts +6 -1
- package/dist/implies.d.mts +4 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/invariant.d.mts +23 -1
- package/dist/read-only.d.mts +45 -0
- package/dist/rescue.d.mts +58 -3
- package/dist/standard-schema.d.mts +46 -0
- package/package.json +33 -21
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","mappings":"AAGCA,OAAeC,WAAaD,OAAOE,IAAI,mBCAjC,MAAMC,UAAuBC,OCmB7B,SAASC,EAAOC,EAAoBC,EAAkB,mBACzD,GAA0B,GAAtBC,QAAQF,GACR,MAAM,IAAIH,EAAeI,EACjC,CCLO,SAASE,EAAIC,EAAYC,GAC5B,OAAQD,GAAKC,IAAQD,IAAMC,CAC/B,CCFO,SAASC,EAAQF,EAAYC,GAChC,OAAQD,GAAKC,CACjB,CCVO,SAASE,EAAyEC,EAAUC,GAC/F,IAAKC,EAAWC,GAAc,OAE9BD,EAAWC,IAAe,EAE1B,MAAMC,EAAcJ,EAAMd,OAAOC,WAAwB,YAAK,GAE9D,IACI,IAAK,MAAMkB,KAAOD,EACdb,EACIc,EAAIJ,GACJ,+BAA+BD,EAAMM,SAASD,EAAIE,aAE9D,C,QACIL,EAAWC,IAAe,CAC9B,CACJ,CAEO,MAAMK,EAAiCC,GAAc,CAACC,GAAiBC,OAAMxB,eAChFI,EAAgB,UAAToB,EAAkB,uDACzBp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C,EAAOsD,GACxB7B,EAAc6B,EAAQK,EAAM,CAACP,IAE7B,IACIP,EAASG,QAAQE,IAAII,EAAQK,EAAMP,EAAOY,GACtCC,GAAYhC,EAAcqB,EAAQpB,EAAKyB,EAAM,CAACP,GACtD,CAAE,MAAOZ,GACLK,EAASP,EAAmB,MAAOgB,EAAQK,EAA0BnB,EAAO,CAACY,GACjF,C,QACIrD,EAAiBC,EAAOsD,EAC5B,CAEA,OAAOT,CACX,EACA,cAAAwB,CAAef,EAAQK,GACnB,MAAM,IAAIS,UAAU,2BAA2BhD,OAAOuC,iCAC1D,GAGG,MAAMzD,EACTgB,OAAQhC,OAAOC,UAQL+B,2BAA4B,EAG/BA,OAAQf,IAAwB,EAEvC,UAAO,IAGOwB,GACTJ,KAAa+C,oBAAqB,EACnC,IACI,MAAMrE,EAAW,IAAIsB,QAAQI,GAG7B,OAFA5B,EAAiBwB,KAAMtB,GAEhB,IAAIsE,MAAuBtE,EAAU8D,EAChD,C,QACKxC,KAAa+C,oBAAqB,CACvC,CACJ,CAEA,WAAA1C,IAAe4C,GAEX,IADcjD,KAAKK,YACR0C,mBACP,MAAM,IAAIF,UAAU,yDAC5B,S","sources":["webpack://@final-hill/decorator-contracts/./src/types.mts","webpack://@final-hill/decorator-contracts/./src/AssertionError.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/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\r\n// ref: https://github.com/microsoft/TypeScript/issues/53461#issuecomment-1736996954\r\n// ref: https://github.com/tc39/proposal-decorator-metadata\r\n(Symbol as any).metadata ??= Symbol.for(\"Symbol.metadata\");\r\n\r\n// Extend the global SymbolConstructor type to include metadata\r\ndeclare global {\r\n interface SymbolConstructor {\r\n readonly metadata: symbol;\r\n }\r\n}\r\n\r\nexport type Constructor<T> = new (...args: any[]) => T\r\n\r\nexport type FeatureDecoratorContext = Exclude<ClassMemberDecoratorContext, ClassAccessorDecoratorContext>;","/**\r\n * An AssertionError represents a failed assertion with an associated message\r\n */\r\nexport class AssertionError extends Error { }\r\n","import { AssertionError } from \"./AssertionError.mjs\";\r\n\r\n/**\r\n * An assertion is an expression of a property that must be true at a particular\r\n * point of step of program execution. It consists of a boolean expression\r\n * and a message. This function tests the provided condition. If the condition\r\n * is false an AssertionError is raised with an optional message.\r\n * If the provided condition is true then the function returns without raising an error\r\n *\r\n * @param condition - The condition to test. If it is false an error is raised.\r\n * @param message - The message to display if the condition is false. If not provided a default message is used.\r\n * @throws {AssertionError} If the condition is false an AssertionError is raised.\r\n *\r\n * @example\r\n * ```ts\r\n * import assert from \"assert.mjs\";\r\n *\r\n * let x = 15;\r\n * assert(x > 5, `Expected: x > 5. Actual: x = ${x}`);\r\n * ```\r\n */\r\n\r\nexport function assert(condition: unknown, message: string = 'Assertion Error'): asserts condition {\r\n if (Boolean(condition) == false)\r\n throw new AssertionError(message);\r\n}\r\n","/**\r\n * Biconditional.\r\n * p ↔ q.\r\n * \"P if and only if Q\".\r\n * An example of usage is the encoding of \"You can ride the train if and only if you have a ticket\"\r\n * This is logically equivalent to: implies(p,q) && implies(q,p)\r\n *\r\n * @param p - The first boolean value (the antecedent).\r\n * @param q - The second boolean value (the consequent).\r\n * @returns - The result (biconditional) of p and q.\r\n *\r\n * @example\r\n * ```ts\r\n * import { iff } from '@final-hill/decorator-contracts';\r\n *\r\n * // You can ride the train if and only if you have a ticket\r\n * iff(person.hasTicket, person.ridesTrain)\r\n * ```\r\n */\r\n\r\nexport function iff(p: boolean, q: boolean): boolean {\r\n return (p && q) || (!p && !q);\r\n}\r\n","/**\r\n * Material Implication.\r\n * `p → q`\r\n * Also referred to as `if-then`.\r\n * An example of usage is the encoding of \"sunny weather is a precondition of visiting the beach\"\r\n * This is logically equivalent to: !p || q\r\n *\r\n * @param p - The first boolean value (the antecedent).\r\n * @param q - The second boolean value (the consequent).\r\n * @returns - The result (material implication) of p and q.\r\n *\r\n * @example\r\n * ```ts\r\n * import { implies } from '@final-hill/decorator-contracts';\r\n *\r\n * // Sunny weather is a precondition of visiting the beach\r\n * implies(weather.isSunny, person.visitsBeach)\r\n * ```\r\n */\r\n\r\nexport function implies(p: boolean, q: boolean): boolean {\r\n return !p || q;\r\n}\r\n","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from './Contracted.mjs';\r\n\r\nexport type InvariantPredicate<Class extends typeof Contracted> = (self: InstanceType<Class>) => boolean;\r\n\r\nexport type InvariantDecorator = <Class extends typeof Contracted>(\r\n predicate: InvariantPredicate<Class>\r\n) => (\r\n value: Class,\r\n context: ClassDecoratorContext<Class>\r\n) => Class | void;\r\n\r\nexport function assertInvariants<C extends typeof Contracted, T extends InstanceType<C>>(Class: C, instance: T) {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion \r\n\r\n const invariants = (Class[Symbol.metadata]?.['invariants'] ?? []) as InvariantPredicate<C>[];\r\n\r\n try {\r\n for (const inv of invariants)\r\n assert(\r\n inv(instance),\r\n `Invariant violated in class ${Class.name}: ${inv.toString()}`\r\n );\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n}\r\n\r\nexport const invariant: InvariantDecorator = (predicate) => (OriginalClass, { kind, metadata }) => {\r\n assert(kind === 'class', '@invariant decorator can only be applied to classes');\r\n assert(OriginalClass.prototype instanceof Contracted, '@invariant decorator can only be applied to classes that extend Contracted');\r\n\r\n const existing = (metadata.invariants ?? []) as InvariantPredicate<typeof OriginalClass>[]\r\n metadata.invariants = [...existing, predicate];\r\n};\r\n","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from \"./Contracted.mjs\";\r\nimport type { FeatureDecoratorContext } from './types.mjs';\r\n\r\nexport type DemandsPredicate<This extends Contracted> = (self: This, ...args: any[]) => boolean;\r\n\r\nexport type DemandsDecorator = <This extends Contracted, Feature = unknown>(\r\n predicate: DemandsPredicate<This>\r\n) => (\r\n value: Feature,\r\n context: FeatureDecoratorContext\r\n) => Feature | void;\r\n\r\nexport const demands: DemandsDecorator = (predicate) => (_feature, ctx) => {\r\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), '@demands decorator can only be applied to methods, getters, or setters');\r\n assert(ctx.static === false, '@demands decorator cannot be applied to static features');\r\n assert(ctx.private === false, '@demands decorator cannot be applied to private/protected features');\r\n assert(!String(ctx.name).startsWith('_'), '@demands decorator cannot be applied to private/protected features');\r\n\r\n ctx.addInitializer(function () {\r\n assert(this instanceof Contracted, '@demands decorator can only be applied to classes that extend Contracted');\r\n const ds = [\r\n ...(ctx.metadata as any)?.demands?.[ctx.name] ?? [],\r\n predicate\r\n ]\r\n\r\n ctx.metadata.demands = {\r\n ...(ctx.metadata?.demands ?? {}),\r\n [ctx.name]: ds\r\n };\r\n })\r\n}\r\n\r\nexport function assertDemands(instance: Contracted, propertyKey: PropertyKey, ...args: any[]) {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion \r\n\r\n const Class = instance.constructor as typeof Contracted,\r\n ds = Class[Symbol.metadata]?.demands?.[propertyKey] ?? [] as DemandsPredicate<Contracted>[];\r\n\r\n try {\r\n if (ds.length === 0) return;\r\n\r\n // If ANY demand is true then the obligation is considered fulfilled\r\n for (const d of ds)\r\n if (d(instance, ...args)) return;\r\n\r\n // If we reach here, it means all demands were false\r\n assert(false, `No demands were satisfied for ${instance.constructor.name}.${String(propertyKey)}`);\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n}","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from './Contracted.mjs';\r\nimport type { FeatureDecoratorContext } from './types.mjs';\r\n\r\nexport type EnsuresPredicate<This extends Contracted> = (self: This, args: any[], old: This) => boolean;\r\n\r\nexport type EnsuresDecorator = <\r\n This extends Contracted\r\n>(\r\n predicate: EnsuresPredicate<This>\r\n) => (\r\n value: unknown,\r\n context: FeatureDecoratorContext\r\n) => void;\r\n\r\nexport const ensures: EnsuresDecorator = (predicate) => (_feature, ctx) => {\r\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), '@ensures decorator can only be applied to methods, getters, or setters');\r\n assert(ctx.static === false, '@ensures decorator cannot be applied to static features');\r\n assert(ctx.private === false, '@ensures decorator cannot be applied to private features');\r\n assert(!String(ctx.name).startsWith('_'), '@ensures decorator cannot be applied to private/protected features');\r\n\r\n ctx.addInitializer(function () {\r\n assert(this instanceof Contracted, '@ensures decorator can only be applied to classes that extend Contracted');\r\n const es = [\r\n ...(ctx.metadata as any)?.ensures?.[ctx.name] ?? [],\r\n predicate\r\n ]\r\n\r\n ctx.metadata.ensures = {\r\n ...(ctx.metadata?.ensures ?? {}),\r\n [ctx.name]: es\r\n };\r\n })\r\n}\r\n\r\nexport function assertEnsures(instance: Contracted, old: Contracted, propertyKey: PropertyKey, args: any) {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion\r\n\r\n const Class = instance.constructor as typeof Contracted,\r\n es = Class[Symbol.metadata]?.ensures?.[propertyKey] ?? [] as EnsuresPredicate<Contracted>[];\r\n\r\n try {\r\n if (es.length === 0) return;\r\n\r\n // ALL ensures must be true for the obligation to be fulfilled\r\n for (const e of es)\r\n if (!e(instance, args, old))\r\n\r\n assert(false, `No ensurances were satisfied for ${instance.constructor.name}.${String(propertyKey)}`);\r\n // If we reach here, it means all ensures were true\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n}\r\n","import { assert } from './assert.mjs';\r\nimport { checkedMode, Contracted } from './Contracted.mjs';\r\nimport type { FeatureDecoratorContext } from './types.mjs';\r\n\r\nexport type RescueHandler<This extends Contracted> =\r\n (self: This, error: unknown, args: any[], retry: (this: This, ...args: any[]) => any) => void\r\n\r\nexport type RescueDecorator = <This extends Contracted>(\r\n handler: RescueHandler<This>\r\n) => (\r\n value: unknown,\r\n context: FeatureDecoratorContext\r\n) => void;\r\n\r\nexport const rescue: RescueDecorator = (handler) => (_feature, ctx) => {\r\n assert([\"method\", \"getter\", \"setter\"].includes(ctx.kind), '@rescue decorator can only be applied to methods, getters, or setters');\r\n assert(ctx.static === false, '@rescue decorator cannot be applied to static features');\r\n assert(ctx.private === false, '@rescue decorator cannot be applied to private features');\r\n assert(!String(ctx.name).startsWith('_'), '@rescue decorator cannot be applied to private/protected features');\r\n\r\n ctx.addInitializer(function () {\r\n assert(this instanceof Contracted, '@rescue decorator can only be applied to classes that extend Contracted');\r\n\r\n ctx.metadata.rescue = {\r\n ...(ctx.metadata?.rescue ?? {}),\r\n [ctx.name]: handler\r\n }\r\n })\r\n}\r\n\r\nexport const applyRescueHandler = (descriptorType: 'get' | 'set' | 'func', instance: Contracted, propertyKey: PropertyKey, error: unknown, args: any) => {\r\n if (!Contracted[checkedMode]) return error;\r\n\r\n const Class = instance.constructor as typeof Contracted,\r\n descriptor = Object.getOwnPropertyDescriptor(Class.prototype, propertyKey)!,\r\n r = Class[Symbol.metadata]?.rescue?.[propertyKey] as RescueHandler<Contracted> | undefined;\r\n\r\n if (!r) throw error;\r\n\r\n let hasRetried = false;\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion\r\n let result: any\r\n try {\r\n r.call(instance, instance, error, args, (...args: any[]) => {\r\n assert(!hasRetried, 'retry can only be called once');\r\n hasRetried = true;\r\n Contracted[checkedMode] = true;\r\n if (descriptorType == 'get')\r\n result = Reflect.get(instance, propertyKey, instance);\r\n else if (descriptorType == 'set')\r\n result = Reflect.set(instance, propertyKey, args[0], instance);\r\n else if (descriptorType == 'func')\r\n result = Reflect.apply(descriptor.value, instance, args);\r\n })\r\n if (!hasRetried)\r\n throw error;\r\n } finally {\r\n Contracted[checkedMode] = true;\r\n }\r\n\r\n return result;\r\n}\r\n","import { assertInvariants, InvariantPredicate } from './invariant.mjs';\r\nimport { assertDemands, DemandsPredicate } from './demands.mjs';\r\nimport { assertEnsures, EnsuresPredicate } from './ensures.mjs';\r\nimport { applyRescueHandler as applyRescueHandler, RescueHandler } from './rescue.mjs';\r\n\r\n// Symbol to store checked mode state\r\nexport const checkedMode = Symbol.for('Contracted.checkedMode');\r\n\r\nconst populateOld = (target: Contracted) => {\r\n if (!Contracted[checkedMode]) return;\r\n\r\n Contracted[checkedMode] = false; // Disable checked mode to avoid infinite recursion\r\n\r\n const old = Object.create(target)\r\n for (const key in target)\r\n Reflect.set(old, key, Reflect.get(target, key));\r\n\r\n Contracted[checkedMode] = true;\r\n\r\n return old;\r\n}\r\n\r\n// Utility to walk up the prototype chain to find a property descriptor\r\nfunction getPropertyDescriptor(obj: object, prop: PropertyKey): PropertyDescriptor | undefined {\r\n let proto = obj;\r\n while (proto && proto !== Object.prototype) {\r\n const desc = Object.getOwnPropertyDescriptor(proto, prop);\r\n if (desc) return desc;\r\n proto = Object.getPrototypeOf(proto);\r\n }\r\n return undefined;\r\n}\r\n\r\nconst proxyHandler: ProxyHandler<Contracted> = {\r\n get(target, prop, receiver) {\r\n if (!Contracted[checkedMode]) return Reflect.get(target, prop, receiver);\r\n\r\n const Class = target.constructor as typeof Contracted,\r\n descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop),\r\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\r\n hasEnsures = es.length > 0,\r\n old = hasEnsures ? populateOld(target) : undefined;\r\n\r\n if (typeof descriptor?.value === 'function') {\r\n return function (this: Contracted, ...methodArgs: any[]) {\r\n assertInvariants(Class, target);\r\n assertDemands(target, prop, methodArgs);\r\n let result\r\n try {\r\n result = Reflect.apply(descriptor.value, target, methodArgs);\r\n if (hasEnsures) assertEnsures(target, old, prop, methodArgs);\r\n } catch (error) {\r\n result = applyRescueHandler('func', target, prop as keyof Contracted, error, methodArgs);\r\n } finally {\r\n assertInvariants(Class, target);\r\n }\r\n return result;\r\n }\r\n } else if (typeof descriptor?.get === 'function') {\r\n assertInvariants(Class, target);\r\n assertDemands(target, prop, []);\r\n let result\r\n try {\r\n result = Reflect.get(target, prop, receiver);\r\n if (hasEnsures) assertEnsures(target, old, prop, [result]);\r\n } catch (error) {\r\n result = applyRescueHandler('get', target, prop, error, []);\r\n } finally {\r\n assertInvariants(Class, target);\r\n }\r\n return result;\r\n } else {\r\n return Reflect.get(target, prop, receiver);\r\n }\r\n },\r\n set(target, prop, value, receiver) {\r\n if (!Contracted[checkedMode]) return Reflect.set(target, prop, value, receiver);\r\n\r\n const descriptor = getPropertyDescriptor(Object.getPrototypeOf(target), prop)\r\n\r\n if (!(descriptor && typeof descriptor.set === 'function'))\r\n if (typeof prop === 'string' && !prop.startsWith('_'))\r\n throw new TypeError(`Cannot assign to property '${String(prop)}': only properties starting with '_' or with a setter can be set on Contracted instances.`);\r\n\r\n const Class = target.constructor as typeof Contracted,\r\n es = Class[Symbol.metadata]?.ensures?.[prop] ?? [] as EnsuresPredicate<Contracted>[],\r\n hasEnsures = es.length > 0,\r\n old = hasEnsures ? populateOld(target) : undefined;\r\n assertInvariants(Class, target);\r\n assertDemands(target, prop, [value]);\r\n let result\r\n try {\r\n result = Reflect.set(target, prop, value, receiver);\r\n if (hasEnsures) assertEnsures(target, old, prop, [value]);\r\n } catch (error) {\r\n result = applyRescueHandler('set', target, prop as keyof Contracted, error, [value])\r\n } finally {\r\n assertInvariants(Class, target);\r\n }\r\n\r\n return result;\r\n },\r\n deleteProperty(target, prop) {\r\n throw new TypeError(`Cannot delete property '${String(prop)}' from Contracted instances.`);\r\n },\r\n};\r\n\r\nexport class Contracted {\r\n static [Symbol.metadata]: {\r\n invariants: InvariantPredicate<typeof Contracted>[];\r\n demands: Record<PropertyKey, DemandsPredicate<Contracted>[]>;\r\n ensures: Record<PropertyKey, EnsuresPredicate<Contracted>[]>;\r\n rescue: Record<PropertyKey, RescueHandler<Contracted>>;\r\n };\r\n\r\n // Prevents direct instantiation of the class\r\n protected static _allowConstruction = false;\r\n\r\n // Symbol-based checked mode state\r\n public static [checkedMode]: boolean = true;\r\n\r\n static new<\r\n C extends typeof Contracted,\r\n Args extends ConstructorParameters<C>,\r\n >(this: C, ...args: Args): InstanceType<C> {\r\n (this as any)._allowConstruction = true;\r\n try {\r\n const instance = new this(...args) as InstanceType<C>;\r\n assertInvariants(this, instance);\r\n\r\n return new Proxy<InstanceType<C>>(instance, proxyHandler);\r\n } finally {\r\n (this as any)._allowConstruction = false;\r\n }\r\n }\r\n\r\n constructor(..._args: any[]) {\r\n const Class = this.constructor as typeof Contracted;\r\n if (!Class._allowConstruction)\r\n throw new TypeError(\"Use the static 'new' method to instantiate this class.\")\r\n }\r\n}"],"names":["Symbol","metadata","for","AssertionError","Error","assert","condition","message","Boolean","iff","p","q","implies","assertInvariants","Class","instance","Contracted","checkedMode","invariants","inv","name","toString","invariant","predicate","OriginalClass","kind","prototype","existing","demands","_feature","ctx","includes","static","private","String","startsWith","addInitializer","this","ds","assertDemands","propertyKey","args","constructor","length","d","ensures","es","assertEnsures","old","e","rescue","handler","applyRescueHandler","descriptorType","error","descriptor","Object","getOwnPropertyDescriptor","r","result","hasRetried","call","Reflect","get","set","apply","value","populateOld","target","create","key","getPropertyDescriptor","obj","prop","proto","desc","getPrototypeOf","proxyHandler","receiver","hasEnsures","undefined","methodArgs","TypeError","deleteProperty","_allowConstruction","Proxy","_args"],"sourceRoot":""}
|
|
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,iBAAR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B,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":""}
|
package/dist/invariant.d.mts
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
import { Contracted } from './Contracted.mjs';
|
|
2
|
+
import { type ArmOptions } from './admissibility.mjs';
|
|
3
|
+
import type { StandardSchemaV1 } from './standard-schema.mjs';
|
|
4
|
+
/**
|
|
5
|
+
* An invariant predicate: a property the instance always satisfies.
|
|
6
|
+
*/
|
|
2
7
|
export type InvariantPredicate<Class extends typeof Contracted> = (self: InstanceType<Class>) => boolean;
|
|
3
|
-
|
|
8
|
+
/**
|
|
9
|
+
* An invariant arm: a predicate, or a schema the instance must satisfy.
|
|
10
|
+
*
|
|
11
|
+
* A schema in this position validates the **instance**, which is the subject
|
|
12
|
+
* `@invariant` already describes.
|
|
13
|
+
*/
|
|
14
|
+
export type InvariantArm<Class extends typeof Contracted> = InvariantPredicate<Class> | StandardSchemaV1<unknown, any>;
|
|
15
|
+
export type InvariantDecorator = <Class extends typeof Contracted>(arm: InvariantArm<Class>, options?: ArmOptions) => (value: Class, context: ClassDecoratorContext<Class>) => Class | void;
|
|
16
|
+
/**
|
|
17
|
+
* A registered invariant arm.
|
|
18
|
+
*
|
|
19
|
+
* The options travel with the arm because `normalize` is a property of the
|
|
20
|
+
* declaration rather than of an individual evaluation.
|
|
21
|
+
*/
|
|
22
|
+
export interface RegisteredInvariant {
|
|
23
|
+
arm: InvariantArm<typeof Contracted>;
|
|
24
|
+
options?: ArmOptions;
|
|
25
|
+
}
|
|
4
26
|
export declare function assertInvariants<C extends typeof Contracted, T extends InstanceType<C>>(Class: C, instance: T): void;
|
|
5
27
|
export declare const invariant: InvariantDecorator;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Read-only views of an instance, handed to contract predicates.
|
|
3
|
+
*
|
|
4
|
+
* https://github.com/final-hill/decorator-contracts/issues/191
|
|
5
|
+
*
|
|
6
|
+
* A predicate answers a question; it must not change the state it is asked about.
|
|
7
|
+
* Side effects in a predicate are corrupting rather than merely impure: the
|
|
8
|
+
* predicate runs between the entry and exit `@invariant`, so a write there can
|
|
9
|
+
* hide a violation the invariant would otherwise have reported.
|
|
10
|
+
*
|
|
11
|
+
* `rescue` is deliberately excluded. Restoring corrupted state is its purpose, so
|
|
12
|
+
* it receives the raw target.
|
|
13
|
+
*
|
|
14
|
+
* ### Why a proxy rather than `Object.freeze`
|
|
15
|
+
*
|
|
16
|
+
* Freezing is permanent. A predicate that froze the instance would leave the
|
|
17
|
+
* feature body unable to change it, so every feature on that instance would break:
|
|
18
|
+
*
|
|
19
|
+
* ```text
|
|
20
|
+
* deposit FAILED: TypeError - Cannot assign to read only property '_balance'
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* A proxy is scoped to the predicate call, so the body still receives the raw
|
|
24
|
+
* target and mutates normally.
|
|
25
|
+
*
|
|
26
|
+
* ### What is and is not blocked
|
|
27
|
+
*
|
|
28
|
+
* Assignment, deletion, and `defineProperty` on the instance are refused. A
|
|
29
|
+
* mutation *through* a nested value (`self._items.push(x)`) still reaches the
|
|
30
|
+
* shared object, because the proxy only intercepts the instance's own surface.
|
|
31
|
+
* Closing that would require deep-wrapping every value returned from a read,
|
|
32
|
+
* which changes identity for legitimate comparisons such as
|
|
33
|
+
* `old.child === self.child`. The guarantee is therefore "a predicate cannot
|
|
34
|
+
* assign to the instance", which is the case that actually corrupts contract
|
|
35
|
+
* evaluation.
|
|
36
|
+
*/
|
|
37
|
+
/**
|
|
38
|
+
* Returns a cached read-only view of `target`.
|
|
39
|
+
*
|
|
40
|
+
* Cached because the same instance is evaluated by several contracts within one
|
|
41
|
+
* lifecycle, and creating a fresh proxy each time would make `self` a different
|
|
42
|
+
* object for each predicate — enough to break a predicate that compares `self`
|
|
43
|
+
* across two contracts.
|
|
44
|
+
*/
|
|
45
|
+
export declare const readOnlyView: <T extends object>(target: T) => T;
|
package/dist/rescue.d.mts
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
import { Contracted } from './Contracted.mjs';
|
|
2
2
|
import type { FeatureDecoratorContext } from './types.mjs';
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
/**
|
|
4
|
+
* A handler for `@rescue`.
|
|
5
|
+
*
|
|
6
|
+
* `retry` is an ordinary function, called as `retry(...)`, so it has no
|
|
7
|
+
* meaningful `this`. Declaring `this: This` on it made every consumer-written
|
|
8
|
+
* handler fail to type-check, because the `this` context of a bare call is
|
|
9
|
+
* `void`.
|
|
10
|
+
*/
|
|
11
|
+
export type RescueHandler<This extends Contracted> = (self: This, error: unknown, args: any[], retry: (...args: any[]) => any) => void;
|
|
12
|
+
export interface RescueOptions {
|
|
13
|
+
/**
|
|
14
|
+
* The maximum number of times `retry` may restart the lifecycle for a single
|
|
15
|
+
* invocation. Defaults to `Infinity`, which allows a `@rescue` to implement
|
|
16
|
+
* N-Version programming with any number of alternative strategies.
|
|
17
|
+
*
|
|
18
|
+
* Set this when a rescue handler always retries, to bound recursion.
|
|
19
|
+
*/
|
|
20
|
+
maxRetries?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface RescueDeclaration<This extends Contracted> {
|
|
23
|
+
handler: RescueHandler<This>;
|
|
24
|
+
maxRetries?: number;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Declares a rescue handler for a feature.
|
|
28
|
+
*
|
|
29
|
+
* `retry` is explicit: it passes only the arguments it is given and never
|
|
30
|
+
* replays the original arguments. Forward the `args` parameter to retry with
|
|
31
|
+
* the same arguments (`retry(...args)`); calling `retry()` retries with none.
|
|
32
|
+
*
|
|
33
|
+
* Options are declaration level because they describe the feature rather than an
|
|
34
|
+
* individual failure. `maxRetries` bounds how many times `retry` may restart the
|
|
35
|
+
* lifecycle for one invocation; it defaults to unbounded.
|
|
36
|
+
*/
|
|
37
|
+
export type RescueDecorator = <This extends Contracted>(handler: RescueHandler<This>, options?: RescueOptions) => (value: unknown, context: FeatureDecoratorContext) => void;
|
|
5
38
|
export declare const rescue: RescueDecorator;
|
|
6
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Resolves the `@rescue` declaration for `propertyKey`, walking the prototype
|
|
41
|
+
* chain so that a declaration on an ancestor feature is inherited.
|
|
42
|
+
*/
|
|
43
|
+
export declare function getRescueDeclaration(instance: Contracted, propertyKey: PropertyKey): RescueDeclaration<Contracted> | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Applies the `@rescue` handler declared for `propertyKey`, if any.
|
|
46
|
+
*
|
|
47
|
+
* When the handler calls `retry`, the arguments passed to `retry` are returned
|
|
48
|
+
* so that the caller can restart the contract lifecycle with them. This keeps
|
|
49
|
+
* the lifecycle in one place (see `runLifecycle` in `Contracted.mts`) and
|
|
50
|
+
* ensures a retried invocation is subject to `@invariant`, `@demands`, and
|
|
51
|
+
* `@ensures` like any other invocation.
|
|
52
|
+
*
|
|
53
|
+
* `retry` may be called at most once per rescue execution. Because the lifecycle
|
|
54
|
+
* re-enters `@rescue` when a retried invocation fails, a handler is executed
|
|
55
|
+
* once per attempt, which is what N-Version programming requires.
|
|
56
|
+
*
|
|
57
|
+
* @returns The arguments to retry with.
|
|
58
|
+
* @throws The original error if the handler does not call `retry`, or whatever
|
|
59
|
+
* the handler throws.
|
|
60
|
+
*/
|
|
61
|
+
export declare const applyRescueHandler: (instance: Contracted, propertyKey: PropertyKey, error: unknown, args: any) => any[];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Standard Schema V1 protocol.
|
|
3
|
+
*
|
|
4
|
+
* Declared locally rather than imported so that the library has no runtime or
|
|
5
|
+
* type dependency on any schema provider. The shapes below are structurally
|
|
6
|
+
* identical to `@standard-schema/spec`, so a Zod, Valibot, ArkType, or Effect
|
|
7
|
+
* Schema object satisfies them without the caller installing anything on our
|
|
8
|
+
* behalf — and without us choosing a vendor.
|
|
9
|
+
*
|
|
10
|
+
* ref: https://github.com/standard-schema/standard-schema
|
|
11
|
+
*/
|
|
12
|
+
export interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
13
|
+
readonly '~standard': StandardSchemaV1.Props<Input, Output>;
|
|
14
|
+
}
|
|
15
|
+
export declare namespace StandardSchemaV1 {
|
|
16
|
+
interface Props<Input = unknown, Output = Input> {
|
|
17
|
+
readonly version: 1;
|
|
18
|
+
readonly vendor: string;
|
|
19
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
20
|
+
readonly validate: (value: unknown, options?: Options) => Result<Output> | Promise<Result<Output>>;
|
|
21
|
+
}
|
|
22
|
+
interface Types<Input = unknown, Output = Input> {
|
|
23
|
+
readonly input: Input;
|
|
24
|
+
readonly output: Output;
|
|
25
|
+
}
|
|
26
|
+
interface Options {
|
|
27
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
28
|
+
}
|
|
29
|
+
type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
30
|
+
interface SuccessResult<Output> {
|
|
31
|
+
readonly value: Output;
|
|
32
|
+
readonly issues?: undefined;
|
|
33
|
+
}
|
|
34
|
+
interface FailureResult {
|
|
35
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
36
|
+
}
|
|
37
|
+
interface Issue {
|
|
38
|
+
readonly message: string;
|
|
39
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
40
|
+
}
|
|
41
|
+
interface PathSegment {
|
|
42
|
+
readonly key: PropertyKey;
|
|
43
|
+
}
|
|
44
|
+
type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['input'];
|
|
45
|
+
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
|
|
46
|
+
}
|
package/package.json
CHANGED
|
@@ -1,25 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@final-hill/decorator-contracts",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"description": "Code Contracts for TypeScript and ECMAScript classes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
".": {
|
|
8
|
-
"types": "./dist/index.d.
|
|
8
|
+
"types": "./dist/index.d.mts",
|
|
9
9
|
"import": "./dist/index.mjs"
|
|
10
10
|
}
|
|
11
11
|
},
|
|
12
|
+
"types": "./dist/index.d.mts",
|
|
13
|
+
"main": "./dist/index.mjs",
|
|
12
14
|
"scripts": {
|
|
13
15
|
"prebuild": "npm run lint",
|
|
14
16
|
"build": "webpack",
|
|
15
|
-
"lint": "eslint src/ --ext .mts --
|
|
16
|
-
"
|
|
17
|
-
"
|
|
17
|
+
"lint": "eslint src/ --ext .mts --max-warnings 0",
|
|
18
|
+
"lint:fix": "eslint src/ --ext .mts --fix",
|
|
19
|
+
"pretest": "npm run build && npm run typecheck",
|
|
20
|
+
"test": "globstar -- node --import tsx --test ./src/tests/*.test.mts",
|
|
21
|
+
"pretest:coverage": "npm run build && node -e \"require('node:fs').mkdirSync('coverage',{recursive:true})\"",
|
|
22
|
+
"test:coverage": "globstar -- node --import tsx --test --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info ./src/tests/*.test.mts",
|
|
23
|
+
"typecheck": "tsc --noEmit -p tsconfig.json && tsc -p tsconfig.test.json"
|
|
18
24
|
},
|
|
19
25
|
"homepage": "https://github.com/final-hill/decorator-contracts#readme",
|
|
20
26
|
"repository": {
|
|
21
27
|
"type": "git",
|
|
22
|
-
"url": "https://github.com/final-hill/decorator-contracts"
|
|
28
|
+
"url": "git+https://github.com/final-hill/decorator-contracts.git"
|
|
23
29
|
},
|
|
24
30
|
"bugs": {
|
|
25
31
|
"url": "https://github.com/final-hill/decorator-contracts/issues"
|
|
@@ -46,25 +52,31 @@
|
|
|
46
52
|
"requires",
|
|
47
53
|
"SOLID"
|
|
48
54
|
],
|
|
55
|
+
"engines": {
|
|
56
|
+
"node": ">=26"
|
|
57
|
+
},
|
|
49
58
|
"author": "Michael L Haufe <michael.haufe@final-hill.com> (https://final-hill.com)",
|
|
50
59
|
"license": "AGPL-3.0-only",
|
|
51
60
|
"devDependencies": {
|
|
52
|
-
"@eslint/js": "^
|
|
53
|
-
"@eslint/json": "^
|
|
54
|
-
"@eslint/markdown": "^
|
|
55
|
-
"@types/node": "^
|
|
56
|
-
"eslint": "^
|
|
57
|
-
"eslint-webpack-plugin": "^
|
|
58
|
-
"globals": "^
|
|
61
|
+
"@eslint/js": "^10.0.1",
|
|
62
|
+
"@eslint/json": "^2.1.1",
|
|
63
|
+
"@eslint/markdown": "^9.0.0",
|
|
64
|
+
"@types/node": "^26.6.6",
|
|
65
|
+
"eslint": "^10.15.0",
|
|
66
|
+
"eslint-webpack-plugin": "^6.0.0",
|
|
67
|
+
"globals": "^17.14.0",
|
|
59
68
|
"globstar": "^1.0.0",
|
|
60
|
-
"ts-loader": "^9.
|
|
61
|
-
"tsx": "^4.
|
|
62
|
-
"typescript": "^
|
|
63
|
-
"typescript-eslint": "^8.
|
|
64
|
-
"webpack": "^5.
|
|
65
|
-
"webpack-cli": "^
|
|
69
|
+
"ts-loader": "^9.6.2",
|
|
70
|
+
"tsx": "^4.23.15",
|
|
71
|
+
"typescript": "^6.0.3",
|
|
72
|
+
"typescript-eslint": "^8.73.0",
|
|
73
|
+
"webpack": "^5.113.0",
|
|
74
|
+
"webpack-cli": "^7.3.1"
|
|
66
75
|
},
|
|
67
76
|
"files": [
|
|
68
77
|
"dist"
|
|
69
|
-
]
|
|
70
|
-
|
|
78
|
+
],
|
|
79
|
+
"overrides": {
|
|
80
|
+
"katex": "^0.19.1"
|
|
81
|
+
}
|
|
82
|
+
}
|