From 55eb76a65fc29e01a081bcd1f30bdca69993c0fe Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:07:15 +0000 Subject: [PATCH 001/106] chore: groundwork for the 2.0.1 fixes - run the spec/**/*.test.ts regression files again (lost in #280) - drop inline 'type' import modifiers so the typings parse on TypeScript < 4.5 - import 'util' instead of 'node:util' (Node < 14.18 compatibility) - use registered symbols (Symbol.for) so duplicate package copies interoperate - add a 'configure' context symbol (runtime support follows) - remove the unused src/api/Constants.ts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- ava.config.js | 2 +- src/api/Arg.ts | 2 +- src/api/Constants.ts | 13 ---------- src/api/types/SubstituteMethods.ts | 1 + src/api/types/index.ts | 2 +- src/internals/SubstituteNode.ts | 8 +++++- src/internals/Types.ts | 3 ++- src/internals/utilities/Stringify.ts | 2 +- src/internals/utilities/Transformations.ts | 1 + src/shared/Constants.ts | 30 ++++++++++++++-------- 10 files changed, 34 insertions(+), 30 deletions(-) delete mode 100644 src/api/Constants.ts diff --git a/ava.config.js b/ava.config.js index d47ef16..2633e0a 100644 --- a/ava.config.js +++ b/ava.config.js @@ -1,6 +1,6 @@ module.exports = { - files: ['spec/**/*.spec.ts'], + files: ['spec/**/*.spec.ts', 'spec/**/*.test.ts'], typescript: { compile: false, rewritePaths: { diff --git a/src/api/Arg.ts b/src/api/Arg.ts index 6798412..c58d005 100644 --- a/src/api/Arg.ts +++ b/src/api/Arg.ts @@ -1,4 +1,4 @@ -import { Argument, AllArguments, type ArgumentOptions, type PredicateFunction } from '../shared' +import { Argument, AllArguments, ArgumentOptions, PredicateFunction } from '../shared' type Inversable = T & { not: T } type ExtractFirstArg = T extends AllArguments ? TArgs[0] : T diff --git a/src/api/Constants.ts b/src/api/Constants.ts deleted file mode 100644 index d53a809..0000000 --- a/src/api/Constants.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { constants as sharedConstants } from '../shared' - -const received: typeof sharedConstants.CONTEXT.received.symbol = sharedConstants.CONTEXT.received.symbol -const didNotReceive: typeof sharedConstants.CONTEXT.didNotReceive.symbol = sharedConstants.CONTEXT.didNotReceive.symbol -const clearReceivedCalls: typeof sharedConstants.CONTEXT.clearReceivedCalls.symbol = sharedConstants.CONTEXT.clearReceivedCalls.symbol -const mimick: typeof sharedConstants.CONTEXT.mimick.symbol = sharedConstants.CONTEXT.mimick.symbol -const mimicks: typeof sharedConstants.CONTEXT.mimicks.symbol = sharedConstants.CONTEXT.mimicks.symbol -const throws: typeof sharedConstants.CONTEXT.throws.symbol = sharedConstants.CONTEXT.throws.symbol -const returns: typeof sharedConstants.CONTEXT.returns.symbol = sharedConstants.CONTEXT.returns.symbol -const resolves: typeof sharedConstants.CONTEXT.resolves.symbol = sharedConstants.CONTEXT.resolves.symbol -const rejects: typeof sharedConstants.CONTEXT.rejects.symbol = sharedConstants.CONTEXT.rejects.symbol - -export { received, didNotReceive, clearReceivedCalls, mimick, mimicks, throws, returns, resolves, rejects } diff --git a/src/api/types/SubstituteMethods.ts b/src/api/types/SubstituteMethods.ts index e059418..b0b93c5 100644 --- a/src/api/types/SubstituteMethods.ts +++ b/src/api/types/SubstituteMethods.ts @@ -15,6 +15,7 @@ export const received: typeof constants.CONTEXT.received.symbol = constants.CONT export const didNotReceive: typeof constants.CONTEXT.didNotReceive.symbol = constants.CONTEXT.didNotReceive.symbol export const mimick: typeof constants.CONTEXT.mimick.symbol = constants.CONTEXT.mimick.symbol export const clearReceivedCalls: typeof constants.CONTEXT.clearReceivedCalls.symbol = constants.CONTEXT.clearReceivedCalls.symbol +export const configure: typeof constants.CONTEXT.configure.symbol = constants.CONTEXT.configure.symbol export type ObjectSubstituteMethods = (T extends { received: any } ? diff --git a/src/api/types/index.ts b/src/api/types/index.ts index ef1e2ce..db14535 100644 --- a/src/api/types/index.ts +++ b/src/api/types/index.ts @@ -5,5 +5,5 @@ export type ObjectSubstitute = ObjectSubstituteMethods & ObjectSubstituteTransformation -export { received, didNotReceive, clearReceivedCalls, mimick } from './SubstituteMethods' +export { received, didNotReceive, clearReceivedCalls, mimick, configure } from './SubstituteMethods' export { returns, throws, resolves, rejects, mimicks } from './SubstitutionLevel' diff --git a/src/internals/SubstituteNode.ts b/src/internals/SubstituteNode.ts index d549b2b..f236674 100644 --- a/src/internals/SubstituteNode.ts +++ b/src/internals/SubstituteNode.ts @@ -13,7 +13,8 @@ import { constants as sharedConstants } from '../shared/Constants' export const instance = Symbol('Substitute:Instance') type SpecialProperty = typeof instance | typeof inspect.custom | typeof Symbol.toPrimitive | 'then' | 'toJSON' -type TT = Exclude +// TODO(configure): runtime support for the configure context is not implemented yet +type TT = Exclude type ObjectSubstitute = { [P in typeof sharedConstants.CONTEXT[TT]['raw'] | typeof sharedConstants.CONTEXT[TT]['symbol']]: (...args: any[]) => T | void | Promise | Promise @@ -163,6 +164,11 @@ export class SubstituteNode extends SubstituteNodeBase implements ObjectSubstitu throw new Error('Mimick is not implemented yet') } + public [sharedConstants.CONTEXT.configure.symbol](): SubstituteNode { + // TODO(configure): placeholder until the configure context is implemented + throw SubstituteException.generic('configure is not implemented yet') + } + public [sharedConstants.CONTEXT.clearReceivedCalls.symbol](): void { this.handleMethod([]) diff --git a/src/internals/Types.ts b/src/internals/Types.ts index 560cf01..f7bc490 100644 --- a/src/internals/Types.ts +++ b/src/internals/Types.ts @@ -9,6 +9,7 @@ export type ContextReceived = Unfold export type ContextDidNotReceive = Unfold export type ContextClearReceivedCalls = Unfold export type ContextMimick = Unfold +export type ContextConfigure = Unfold export type ContextMimicks = Unfold export type ContextThrows = Unfold export type ContextReturns = Unfold @@ -16,7 +17,7 @@ export type ContextResolves = Unfold export type ContextRejects = Unfold export type AssertionMethod = ContextReceived | ContextDidNotReceive -export type ConfigurationMethod = ContextClearReceivedCalls | ContextMimick +export type ConfigurationMethod = ContextClearReceivedCalls | ContextMimick | ContextConfigure export type SubstitutionMethod = ContextMimicks | ContextThrows | ContextReturns | ContextResolves | ContextRejects export type ContextNone = Unfold diff --git a/src/internals/utilities/Stringify.ts b/src/internals/utilities/Stringify.ts index 099d7d9..45fbf5f 100644 --- a/src/internals/utilities/Stringify.ts +++ b/src/internals/utilities/Stringify.ts @@ -1,4 +1,4 @@ -import { InspectOptions, inspect } from 'node:util' +import { InspectOptions, inspect } from 'util' import { RecordedArguments } from '../RecordedArguments' import { SubstituteNodeModel } from '../Types' import { TextBuilder, TextPart } from './TextBuilder' diff --git a/src/internals/utilities/Transformations.ts b/src/internals/utilities/Transformations.ts index d593e98..ef2ede5 100644 --- a/src/internals/utilities/Transformations.ts +++ b/src/internals/utilities/Transformations.ts @@ -9,6 +9,7 @@ export const rawSymbolContextMap: Record = { [sharedConstants.CONTEXT.didNotReceive.raw]: sharedConstants.CONTEXT.didNotReceive.symbol, [sharedConstants.CONTEXT.clearReceivedCalls.raw]: sharedConstants.CONTEXT.clearReceivedCalls.symbol, [sharedConstants.CONTEXT.mimick.raw]: sharedConstants.CONTEXT.mimick.symbol, + [sharedConstants.CONTEXT.configure.raw]: sharedConstants.CONTEXT.configure.symbol, [sharedConstants.CONTEXT.mimicks.raw]: sharedConstants.CONTEXT.mimicks.symbol, [sharedConstants.CONTEXT.throws.raw]: sharedConstants.CONTEXT.throws.symbol, [sharedConstants.CONTEXT.returns.raw]: sharedConstants.CONTEXT.returns.symbol, diff --git a/src/shared/Constants.ts b/src/shared/Constants.ts index 2ba6616..26ac0f8 100644 --- a/src/shared/Constants.ts +++ b/src/shared/Constants.ts @@ -1,7 +1,7 @@ type ValueToMap = { [key in T as Uncapitalize]: key } export type AssertionMethodRaw = 'received' | 'didNotReceive' -export type ConfigurationMethodRaw = 'clearReceivedCalls' | 'mimick' +export type ConfigurationMethodRaw = 'clearReceivedCalls' | 'mimick' | 'configure' export type SubstitutionMethodRaw = 'mimicks' | 'throws' | 'returns' | 'resolves' | 'rejects' const contextMethodTypes: ValueToMap = { @@ -9,6 +9,7 @@ const contextMethodTypes: ValueToMap `@fluffy-spoon/substitute:${name}` +const received: unique symbol = Symbol.for(symbolFor(contextMethodTypes.received)) +const didNotReceive: unique symbol = Symbol.for(symbolFor(contextMethodTypes.didNotReceive)) +const clearReceivedCalls: unique symbol = Symbol.for(symbolFor(contextMethodTypes.clearReceivedCalls)) +const mimick: unique symbol = Symbol.for(symbolFor(contextMethodTypes.mimick)) +const configure: unique symbol = Symbol.for(symbolFor(contextMethodTypes.configure)) +const mimicks: unique symbol = Symbol.for(symbolFor(contextMethodTypes.mimicks)) +const throws: unique symbol = Symbol.for(symbolFor(contextMethodTypes.throws)) +const returns: unique symbol = Symbol.for(symbolFor(contextMethodTypes.returns)) +const resolves: unique symbol = Symbol.for(symbolFor(contextMethodTypes.resolves)) +const rejects: unique symbol = Symbol.for(symbolFor(contextMethodTypes.rejects)) +const none: unique symbol = Symbol.for(symbolFor('none')) const contextTypes = { none: { @@ -48,6 +52,10 @@ const contextTypes = { raw: contextMethodTypes.mimick, symbol: mimick }, + configure: { + raw: contextMethodTypes.configure, + symbol: configure + }, mimicks: { raw: contextMethodTypes.mimicks, symbol: mimicks From d928227f9fcb562454360b2ba1c682209aecc986 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:41:26 +0000 Subject: [PATCH 002/106] refactor(internals): rebuild the runtime around a per-substitute state Replace the node/recorder model with an explicit SubstituteState per substitute (root or cached auto-substitute): append-only received-call records indexed by member, configured substitutions kept apart from them, an optional mimicked instance, and a cache of auto-substitutes keyed by (kind, member, arguments). Thin proxies translate operations onto it: real use, setup chains, assertion chains and a configure view. Existing specs updated where a fix-spec decision changes behaviour: - RecordedArguments.spec: argument matching is one-directional (D3) - received.spec (#18): a bare add(Arg.all()) is a setup, not a call (D3) - issues/178: received(3).subSection fails both ways, so it throws synchronously; an ambiguous case keeps the deferred report (D9) - clearReceivedCalls.spec: asserts behaviour instead of the removed recorder internals Recorder.spec and RecordsSet.spec are removed with the classes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/RecordedArguments.spec.ts | 8 +- spec/Recorder.spec.ts | 80 ---- spec/RecordsSet.spec.ts | 66 --- spec/regression/clearReceivedCalls.spec.ts | 13 +- spec/regression/issues/178.test.ts | 5 +- spec/regression/received.spec.ts | 3 +- src/api/Arg.ts | 75 ++- src/api/Substitute.ts | 5 +- src/internals/Assertions.ts | 159 +++++++ src/internals/CallRecord.ts | 74 +++ src/internals/Constants.ts | 72 ++- src/internals/Engine.ts | 522 +++++++++++++++++++++ src/internals/RecordedArguments.ts | 117 ++++- src/internals/Recorder.ts | 73 --- src/internals/RecordsSet.ts | 75 --- src/internals/SubstituteException.ts | 133 +++++- src/internals/SubstituteNode.ts | 342 -------------- src/internals/SubstituteNodeBase.ts | 77 --- src/internals/SubstituteState.ts | 292 ++++++++++++ src/internals/Types.ts | 43 -- src/internals/index.ts | 3 +- src/internals/utilities/ArgumentHash.ts | 84 ++++ src/internals/utilities/Colors.ts | 18 + src/internals/utilities/Guards.ts | 73 --- src/internals/utilities/Stringify.ts | 110 ++--- src/internals/utilities/TextBuilder.ts | 27 +- src/internals/utilities/Transformations.ts | 18 - src/internals/utilities/index.ts | 4 +- src/shared/Arguments.ts | 69 ++- src/shared/Constants.ts | 14 + 30 files changed, 1618 insertions(+), 1036 deletions(-) delete mode 100644 spec/Recorder.spec.ts delete mode 100644 spec/RecordsSet.spec.ts create mode 100644 src/internals/Assertions.ts create mode 100644 src/internals/CallRecord.ts create mode 100644 src/internals/Engine.ts delete mode 100644 src/internals/Recorder.ts delete mode 100644 src/internals/RecordsSet.ts delete mode 100644 src/internals/SubstituteNode.ts delete mode 100644 src/internals/SubstituteNodeBase.ts create mode 100644 src/internals/SubstituteState.ts delete mode 100644 src/internals/Types.ts create mode 100644 src/internals/utilities/ArgumentHash.ts create mode 100644 src/internals/utilities/Colors.ts delete mode 100644 src/internals/utilities/Guards.ts delete mode 100644 src/internals/utilities/Transformations.ts diff --git a/spec/RecordedArguments.spec.ts b/spec/RecordedArguments.spec.ts index ea37629..1605c58 100644 --- a/spec/RecordedArguments.spec.ts +++ b/spec/RecordedArguments.spec.ts @@ -122,12 +122,16 @@ test('matches correctly with another RecordedArguments instance when object argu test('matches correctly with another RecordedArguments instance when using a wildcard argument', t => { t.true(RecordedArguments.from([Arg.all()]).match(RecordedArguments.from([1, 2, 3]))) - t.true(RecordedArguments.from(['Substitute', 'JS']).match(RecordedArguments.from([Arg.all()]))) + t.true(RecordedArguments.from([Arg.all()]).match(RecordedArguments.from(['Substitute', 'JS']))) + // D3: matching is one-directional; an Arg on the actual side is not a matcher + t.false(RecordedArguments.from(['Substitute', 'JS']).match(RecordedArguments.from([Arg.all()]))) }) test('matches correctly with another RecordedArguments instance when using predicate arguments', t => { t.true(RecordedArguments.from([Arg.any(), Arg.any('number'), Arg.is((x: number) => x === 3), 4]).match(RecordedArguments.from([1, 2, 3, 4]))) - t.true(RecordedArguments.from(['Substitute', 'JS']).match(RecordedArguments.from([Arg.is(x => typeof x === 'string'), Arg.any('string')]))) + t.true(RecordedArguments.from([Arg.is(x => typeof x === 'string'), Arg.any('string')]).match(RecordedArguments.from(['Substitute', 'JS']))) + // D3: matching is one-directional; an Arg on the actual side is not a matcher + t.false(RecordedArguments.from(['Substitute', 'JS']).match(RecordedArguments.from([Arg.is(x => typeof x === 'string'), Arg.any('string')]))) }) test('generates custom text representation', t => { diff --git a/spec/Recorder.spec.ts b/spec/Recorder.spec.ts deleted file mode 100644 index 47b55cf..0000000 --- a/spec/Recorder.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import test from 'ava' - -import { Recorder } from '../src/internals/Recorder' -import { RecordsSet } from '../src/internals/RecordsSet' -import { Substitute } from '../src/api/Substitute' -import { SubstituteNodeBase } from '../src/internals/SubstituteNodeBase' - -const nodeFactory = (key: string) => { - const node = Substitute.for() - node.key.returns(key) - return node -} - -const node = nodeFactory('node') -const otherNode = nodeFactory('otherNode') -const otherNodeDifferentInstance = nodeFactory('otherNode') - -test('adds all records once only', t => { - const recorder = Recorder.withIdentityProperty('key') - recorder.addRecord(node) - recorder.addRecord(node) - recorder.addRecord(otherNode) - recorder.addRecord(otherNode) - recorder.addRecord(otherNodeDifferentInstance) - - const allRecords = [...recorder.records] - t.deepEqual(allRecords, [node, otherNode, otherNodeDifferentInstance]) -}) - -test('indexes all records correctly', t => { - const recorder = Recorder.withIdentityProperty('key') - recorder.addIndexedRecord(node) - recorder.addIndexedRecord(node) - recorder.addIndexedRecord(otherNode) - recorder.addIndexedRecord(otherNode) - recorder.addIndexedRecord(otherNodeDifferentInstance) - - const allRecords = [...recorder.records] - t.deepEqual(allRecords, [node, otherNode, otherNodeDifferentInstance]) - - const nodeSet = recorder.indexedRecords.get(node.key) - t.true(nodeSet instanceof RecordsSet) - t.deepEqual([...nodeSet!], [node]) - - const otherNodeSet = recorder.indexedRecords.get(otherNode.key) - t.true(otherNodeSet instanceof RecordsSet) - t.deepEqual([...otherNodeSet!], [otherNode, otherNodeDifferentInstance]) -}) - -test('returns all sibling nodes', t => { - const recorder = Recorder.withIdentityProperty('key') - recorder.addIndexedRecord(node) - recorder.addIndexedRecord(otherNode) - recorder.addIndexedRecord(otherNodeDifferentInstance) - - const nodeSiblings = recorder.getSiblingsOf(node) - t.deepEqual([...nodeSiblings], []) - - const otherNodeSiblings = recorder.getSiblingsOf(otherNode) - t.deepEqual([...otherNodeSiblings], [otherNodeDifferentInstance]) - - const otherNodeDifferentInstanceSiblings = recorder.getSiblingsOf(otherNodeDifferentInstance) - t.deepEqual([...otherNodeDifferentInstanceSiblings], [otherNode]) -}) - -test('clears recorded nodes by a given filter function', t => { - const recorder = Recorder.withIdentityProperty('key') - recorder.addIndexedRecord(node) - recorder.addIndexedRecord(otherNode) - recorder.addIndexedRecord(otherNodeDifferentInstance) - - recorder.clearRecords(n => n.key === otherNode.key) - t.deepEqual([...recorder.records], [node]) - t.deepEqual([...recorder.indexedRecords.get(node.key)!], [node]) - t.is(recorder.indexedRecords.get(otherNode.key), undefined) - - recorder.clearRecords(_ => true) - t.deepEqual([...recorder.records], []) - t.deepEqual(recorder.indexedRecords.get(node.key), undefined) -}) diff --git a/spec/RecordsSet.spec.ts b/spec/RecordsSet.spec.ts deleted file mode 100644 index d17aec4..0000000 --- a/spec/RecordsSet.spec.ts +++ /dev/null @@ -1,66 +0,0 @@ -import test, { ExecutionContext } from 'ava' - -import { RecordsSet } from '../src/internals/RecordsSet' - -const dataArray = [1, 2, 3] -function* dataArrayGenerator() { - yield* dataArray -} -const inputData = [dataArray, dataArray[Symbol.iterator](), new Set(dataArray), dataArrayGenerator(), new RecordsSet(dataArray)] -const macro = test.macro((t: ExecutionContext, ...inputData: Iterable[]): void => { - inputData.forEach(input => { - const set = new RecordsSet(input) - - t.true(set.has(1)) - t.true(set.has(2)) - t.true(set.has(3)) - t.is(set.size, 3) - t.deepEqual([...set], dataArray) - t.deepEqual([...set[Symbol.iterator]()], dataArray) - t.deepEqual([...set.values()], dataArray) - - t.false(set.delete(4)) - t.true(set.delete(3)) - t.false(set.delete(3)) - t.is(set.size, 2) - - set.clear() - t.is(set.size, 0) - }) -}) - -test('behaves like a native Set object', macro, ...inputData) - -test('applies a filter function everytime the iterator is consumed', t => { - const set = new RecordsSet([1, 2, 3]) - const setWithFilter = set.filter(number => number !== 2) - - t.deepEqual([...set], [1, 2, 3]) - t.deepEqual([...setWithFilter], [1, 3]) - t.deepEqual([...setWithFilter], [1, 3]) -}) - -test('applies a map function everytime the iterator is consumed', t => { - const set = new RecordsSet([1, 2, 3]) - const setWithMap = set.map(number => number.toString()) - - t.deepEqual([...set], [1, 2, 3]) - t.deepEqual([...setWithMap], ['1', '2', '3']) - t.deepEqual([...setWithMap], ['1', '2', '3']) -}) - -test('applies and preserves the order of filter and map functions everytime the iterator is consumed', t => { - const set = new RecordsSet([1, 2, 3]) - const setWithFilter = set.filter(number => number !== 2) - const setWithFilterAndMap = setWithFilter.map(number => number.toString()) - const setWithFilterMapAndAnotherFilter = setWithFilterAndMap.filter(string => string === '3') - - t.deepEqual([...set], [1, 2, 3]) - t.deepEqual([...setWithFilter], [1, 3]) - t.deepEqual([...setWithFilterAndMap], ['1', '3']) - t.deepEqual([...setWithFilterMapAndAnotherFilter], ['3']) - - t.deepEqual([...setWithFilter], [1, 3]) - t.deepEqual([...setWithFilterAndMap], ['1', '3']) - t.deepEqual([...setWithFilterMapAndAnotherFilter], ['3']) -}) diff --git a/spec/regression/clearReceivedCalls.spec.ts b/spec/regression/clearReceivedCalls.spec.ts index 4325f5c..86f37d0 100644 --- a/spec/regression/clearReceivedCalls.spec.ts +++ b/spec/regression/clearReceivedCalls.spec.ts @@ -1,7 +1,6 @@ import test from 'ava' -import { Substitute, SubstituteOf, clearReceivedCalls } from '../../src' -import { SubstituteNode, instance } from '../../src/internals/SubstituteNode' +import { Substitute, clearReceivedCalls } from '../../src' interface Calculator { add(a: number, b: number): number @@ -10,19 +9,13 @@ interface Calculator { isEnabled: boolean } -type InstanceReturningSubstitute = SubstituteOf & { - [instance]: SubstituteNode -} - test('clears received calls on a substitute', t => { - const calculator = Substitute.for() as InstanceReturningSubstitute + const calculator = Substitute.for() calculator.add(1, 1) calculator.add(1, 1).returns(2) calculator[clearReceivedCalls](); - t.is(calculator[instance].recorder.records.size, 2) - t.is(calculator[instance].recorder.indexedRecords.size, 2) - + t.notThrows(() => calculator.didNotReceive().add(1, 1)) t.throws(() => calculator.received().add(1, 1)) t.is(2, calculator.add(1, 1)) }) diff --git a/spec/regression/issues/178.test.ts b/spec/regression/issues/178.test.ts index 78efeb6..080392e 100644 --- a/spec/regression/issues/178.test.ts +++ b/spec/regression/issues/178.test.ts @@ -36,5 +36,8 @@ test('can substitute callable interfaces', async t => { lib.received(2).subSection t.throws(() => lib.didNotReceive().subSection(), { instanceOf: SubstituteException }) t.throws(() => lib.received(2).subSection(), { instanceOf: SubstituteException }) - throwsUncaughtException(() => lib.received(3).subSection, t, { instanceOf: SubstituteException }) + // D9: fails both as a property read (2 reads) and as a method call (1 call), so it throws synchronously + t.throws(() => lib.received(3).subSection, { instanceOf: SubstituteException }) + // D9: genuinely ambiguous (2 property reads, but received(1).subSection() would pass), so only reported later + throwsUncaughtException(() => lib.received(1).subSection, t, { instanceOf: SubstituteException }) }) diff --git a/spec/regression/received.spec.ts b/spec/regression/received.spec.ts index 69651f9..4431fe2 100644 --- a/spec/regression/received.spec.ts +++ b/spec/regression/received.spec.ts @@ -119,7 +119,8 @@ test('getting a property twice with mock correctly asserts the call count', t => test('calling a method with Arg correctly asserts the call count with Arg', t => { // #18: receive with arg https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/issues/18 const calculator = Substitute.for() - calculator.add(Arg.all()) + // D3: a call with Arg matchers is a setup or an assertion, never a received call, so a real call is made here + calculator.add(1, 1) calculator.received(1).add(Arg.all()) calculator.received().add(Arg.all()) diff --git a/src/api/Arg.ts b/src/api/Arg.ts index c58d005..581ab77 100644 --- a/src/api/Arg.ts +++ b/src/api/Arg.ts @@ -1,4 +1,5 @@ -import { Argument, AllArguments, ArgumentOptions, PredicateFunction } from '../shared' +import { inspect } from 'util' +import { Argument, AllArguments, ArgumentOptions, PredicateFunction, isSubstituteProxy } from '../shared' type Inversable = T & { not: T } type ExtractFirstArg = T extends AllArguments ? TArgs[0] : T @@ -9,14 +10,31 @@ const createInversable = (target: (arg: TArg, opt?: ArgumentOptio return inversable } -const toStringify = (obj: any) => { - if (typeof obj.inspect === 'function') return obj.inspect() - if (typeof obj.toString === 'function') return obj.toString() - return obj +const describePredicate = (predicate: Function): string => { + try { + const customInspect = (predicate as any).inspect + if (typeof customInspect === 'function') return String(customInspect.call(predicate)) + } catch { /* fall through to the source text */ } + try { + return Function.prototype.toString.call(predicate) + } catch { + return '' + } +} + +const describeInvalidPredicate = (value: unknown): string => { + try { + return inspect(value, { depth: 0 }) + } catch { + return typeof value + } +} + +const isFunction = (predicate: PredicateFunction>, options?: ArgumentOptions) => { + if (typeof predicate !== 'function') + throw new TypeError(`Arg.is expects a predicate function, but received ${describeInvalidPredicate(predicate)}.`) + return new Argument(`Arg.is{${describePredicate(predicate)}}`, predicate, options) } -const isFunction = (predicate: PredicateFunction>, options?: ArgumentOptions) => new Argument( - `Arg.is{${toStringify(predicate)}}`, predicate, options -) type Is = (predicate: PredicateFunction>) => ReturnArg> type MapAnyReturn = T extends 'any' ? @@ -33,20 +51,37 @@ ReturnArg : any type AnyType = 'string' | 'number' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'array' | 'any' type Any = (type?: T) => MapAnyReturn -const anyFunction = (type: AnyType = 'any', options?: ArgumentOptions) => { - const description = `Arg.any{${type}}` - const predicate = (x: any) => { - switch (type) { - case 'any': - return true - case 'array': - return Array.isArray(x) - default: - return typeof x === type - } +const createAnyPredicate = (type: string): PredicateFunction => { + switch (type) { + case 'any': + return () => true + case 'array': + return x => Array.isArray(x) + case 'object': + // non-null objects (arrays included) and substitutes (which are function proxies) + return x => (typeof x === 'object' && x !== null) || isSubstituteProxy(x) + case 'function': + // functions, which includes substitutes + return x => typeof x === 'function' + default: + return x => typeof x === type } +} - return new Argument(description, predicate, options) +// One predicate per type, so that two Arg.any('number') matchers are recognised as the same matcher. +const anyPredicates = new Map>() +const anyPredicateFor = (type: string): PredicateFunction => { + let predicate = anyPredicates.get(type) + if (predicate === undefined) { + predicate = createAnyPredicate(type) + anyPredicates.set(type, predicate) + } + return predicate +} + +const anyFunction = (type: AnyType = 'any', options?: ArgumentOptions) => { + const description = `Arg.any{${type}}` + return new Argument(description, anyPredicateFor(type), options) } export const Arg = { diff --git a/src/api/Substitute.ts b/src/api/Substitute.ts index 384ec39..96208be 100644 --- a/src/api/Substitute.ts +++ b/src/api/Substitute.ts @@ -1,11 +1,10 @@ import { ObjectSubstitute } from './types' -import { SubstituteNode } from '../internals' +import { createSubstitute } from '../internals' export type SubstituteOf = ObjectSubstitute & T export class Substitute { public static for(): SubstituteOf { - const substitute = SubstituteNode.createRoot() - return substitute.proxy as unknown as SubstituteOf + return createSubstitute() as SubstituteOf } } diff --git a/src/internals/Assertions.ts b/src/internals/Assertions.ts new file mode 100644 index 0000000..0c9dd25 --- /dev/null +++ b/src/internals/Assertions.ts @@ -0,0 +1,159 @@ +import { inspect } from 'util' + +import { SubstituteState } from './SubstituteState' +import { RecordedArguments } from './RecordedArguments' +import { SubstituteException, ListedCall, ExpectedKind } from './SubstituteException' +import { CallRecord } from './CallRecord' + +/** undefined means "1 or more" */ +export type ExpectedCount = number | undefined + +/** received(n): n must be omitted or be a non-negative safe integer. received(0) is didNotReceive(). */ +export const validateExpectedCount = (count: unknown, stackStart?: Function): ExpectedCount => { + if (count === undefined) return undefined + if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0) { + let printed: string + try { printed = inspect(count) } catch { printed = typeof count } + throw SubstituteException.generic( + `Expected count has to be a non-negative integer (or omitted for "1 or more"), but received ${printed}.`, + stackStart + ) + } + return count +} + +const countMatches = (count: ExpectedCount, actual: number) => count === undefined ? actual >= 1 : actual === count + +const receivedText = (matches: number) => matches === 0 ? 'none' : matches.toString() + +/** Method assertion: counts invocations whose arguments match. Property reads never count. */ +export const assertCall = (state: SubstituteState, key: PropertyKey, args: any[], count: ExpectedCount, stackStart?: Function): void => { + const specification = RecordedArguments.forSpecification(args) + const records = state.recordsFor(key).filter(record => record.kind !== 'set') + const listed: ListedCall[] = [] + let matches = 0 + for (const record of records) { + if (record.kind !== 'call') { + listed.push({ record, matches: false }) + continue + } + const match = specification.matchDetailed(record.args) + if (match.matches) matches++ + listed.push({ record, matches: match.matches, predicateThrew: match.predicateThrew, predicateError: match.predicateError }) + } + if (countMatches(count, matches)) return + throw SubstituteException.forCallCountMismatch({ + substitutePath: state.path, + key, + expected: { count, kind: 'method', specification }, + receivedText: receivedText(matches), + listed + }, stackStart) +} + +/** Property assignment assertion: counts assignments whose value matches (Arg matchers allowed). */ +export const assertSet = (state: SubstituteState, key: PropertyKey, value: unknown, count: ExpectedCount, stackStart?: Function): void => { + const specification = RecordedArguments.forSpecification([value]) + const records = state.recordsFor(key).filter(record => record.kind === 'set') + const listed: ListedCall[] = [] + let matches = 0 + for (const record of records) { + const match = specification.matchDetailed(record.args) + if (match.matches) matches++ + listed.push({ record, matches: match.matches, predicateThrew: match.predicateThrew, predicateError: match.predicateError }) + } + if (countMatches(count, matches)) return + throw SubstituteException.forCallCountMismatch({ + substitutePath: state.path, + key, + expected: { count, kind: 'set', specification }, + receivedText: receivedText(matches), + listed + }, stackStart) +} + +export type DeferredAssertion = { + error: () => SubstituteException + settled: boolean +} + +const schedule = (callback: () => void) => { + // Looked up on every call so that fake timers (e.g. @sinonjs/fake-timers) can intercept it. + if (typeof process !== 'undefined' && typeof process.nextTick === 'function') process.nextTick(callback) + else setTimeout(callback, 0) +} + +/** Stops a deferred property assertion from being thrown (the access turned out to be a method assertion). */ +export const settle = (deferred: DeferredAssertion | undefined): void => { + if (deferred !== undefined) deferred.settled = true +} + +/** + * The property-style half of `sub.received(n).member`. At this point it is not known yet whether the + * member will be invoked (a method assertion, checked when it is invoked) or not (a property assertion). + * + * - The property assertion holds: nothing to do now. + * - With no count ("1 or more"), a member that has been invoked counts as received, so the property-style + * form passes and only an invocation is checked further. + * - It fails and the member has never been invoked: a method assertion would fail as well (or, for a + * count of 0, the member is treated as a property), so it throws now. + * - It fails and the member has been read as a property but a method assertion could not pass either: + * throws now. + * - The only deferred case (D9): the property-style form fails, the member has been invoked, the count is + * finite, and either a method assertion with that count could still pass or the member has only ever + * been invoked (never read as a property), so the access is most likely the start of a method assertion + * whose message needs the arguments. The failure is scheduled on process.nextTick and cancelled as soon + * as the member is invoked; only a property-style assertion that is never invoked reports it there. + */ +export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, count: ExpectedCount, stackStart?: Function): DeferredAssertion | undefined => { + const records = state.recordsFor(key).filter(record => record.kind !== 'set') + let reads = 0 + let calls = 0 + for (const record of records) { + if (record.kind === 'get') reads++ + else calls++ + } + if (countMatches(count, reads)) return undefined + if (count === undefined && calls > 0) return undefined + + const deferrable = calls > 0 && count !== undefined && (count <= calls || reads === 0) + // A deferred failure is only thrown when the member was not invoked, so it is a property assertion. + // An immediate failure fails for both readings; the kind is only named when the records show it. + const kind: ExpectedKind = deferrable || (calls === 0 && reads > 0) ? 'property' : 'unknown' + const createError = (start?: Function) => SubstituteException.forCallCountMismatch({ + substitutePath: state.path, + key, + expected: { count, kind }, + receivedText: kind === 'property' ? (reads === 0 ? 'none' : reads.toString()) : describeReceived(reads, calls), + listed: records.map((record: CallRecord) => ({ record, matches: record.kind === 'get' })) + }, start) + + if (!deferrable) throw createError(stackStart) + + // The message is only built if the failure is really reported (usually the member is invoked right away). + const site: { stack?: string } = {} + if (typeof Error.captureStackTrace === 'function' && stackStart !== undefined) Error.captureStackTrace(site, stackStart) + const deferred: DeferredAssertion = { + settled: false, + error: () => { + const error = createError() + const frames = typeof site.stack === 'string' ? site.stack.split('\n').slice(1).join('\n') : '' + if (frames !== '') error.stack = `${error.name}: ${error.message}\n${frames}` + return error + } + } + schedule(() => { + if (deferred.settled) return + deferred.settled = true + throw deferred.error() + }) + return deferred +} + +const describeReceived = (reads: number, calls: number): string => { + if (reads === 0 && calls === 0) return 'none' + if (calls === 0) return reads.toString() + const readsText = `${reads} ${reads === 1 ? 'property read' : 'property reads'}` + const callsText = `${calls} ${calls === 1 ? 'method call' : 'method calls'}` + return `${readsText} and ${callsText}` +} diff --git a/src/internals/CallRecord.ts b/src/internals/CallRecord.ts new file mode 100644 index 0000000..465ad71 --- /dev/null +++ b/src/internals/CallRecord.ts @@ -0,0 +1,74 @@ +export type RecordKind = 'get' | 'set' | 'call' + +/** + * A global, monotonically increasing operation counter. Every record that is created or converted takes + * the next number. It lets the engine recognise that two operations are adjacent, which is how an + * expression such as `sub.a.b(1).returns(2)` is recognised as one setup chain. + */ +let sequence = 0 +export const currentSequence = (): number => sequence +const nextSequence = (): number => ++sequence + +type StackHolder = { stack?: string } + +const captureStack = (stackStart: Function): StackHolder => { + const holder: StackHolder = {} + if (typeof Error.captureStackTrace === 'function') Error.captureStackTrace(holder, stackStart) + else holder.stack = new Error().stack + return holder +} + +/** + * One received interaction with a substitute: a property read, a property assignment or an invocation. + * A property read whose result is then invoked is converted into the invocation (reading a method in + * order to call it is not a property read). + */ +export class CallRecord { + public seq: number + public retracted = false + private _stackHolder: StackHolder + + constructor( + public kind: RecordKind, + public readonly key: PropertyKey, + public args: any[] | undefined, + stackStart: Function, + /** The record of the previous step when this one continues an expression chain (`a.b().c`). */ + public readonly chainPrevious?: CallRecord + ) { + this.seq = nextSequence() + this._stackHolder = captureStack(stackStart) + } + + public get stack(): string | undefined { + try { + return this._stackHolder.stack + } catch { + return undefined + } + } + + /** + * Turns a property read into an invocation. When the invocation directly follows the read (the usual + * `sub.method(...)`), the read already captured the right call site. + */ + public convertToCall(args: any[], stackStart: Function): void { + const directlyInvoked = this.seq === currentSequence() + this.kind = 'call' + this.args = args + if (!directlyInvoked) this._stackHolder = captureStack(stackStart) + this.seq = nextSequence() + } +} + +/** + * Removes a record (and the chain of records that led to it) from the received calls, because the + * expression turned out to be a setup or an assertion rather than a real use. + */ +export const retract = (record: CallRecord | undefined): void => { + let current = record + while (current !== undefined && !current.retracted) { + current.retracted = true + current = current.chainPrevious + } +} diff --git a/src/internals/Constants.ts b/src/internals/Constants.ts index 5d40f45..491243d 100644 --- a/src/internals/Constants.ts +++ b/src/internals/Constants.ts @@ -1,18 +1,64 @@ -const method = Symbol('method') -const property = Symbol('property') -const propertyTypes = { method, property } as const +import { inspect } from 'util' +import { constants as sharedConstants, substituteMarker } from '../shared' -const get = Symbol('get') -const set = Symbol('set') -const accessorTypes = { get, set } as const +const CONTEXT = sharedConstants.CONTEXT -const substituteExceptionTypes = { +/** Member key used for invoking a substitute (or an auto-substitute) itself: `fn(1, 2)`. */ +export const SELF: unique symbol = Symbol('@fluffy-spoon/substitute:self') +/** Per-copy key that gives the engine access to the internals behind a proxy. Never recorded. */ +export const INTERNAL: unique symbol = Symbol('@fluffy-spoon/substitute:internal') + +export type SubstitutionMethod = 'returns' | 'throws' | 'resolves' | 'rejects' | 'mimicks' +export type ContextMethod = 'received' | 'didNotReceive' | 'clearReceivedCalls' | 'mimick' | 'configure' +export type StringAssertionKey = 'received' | 'didNotReceive' +export type FunctionHelperKey = 'call' | 'apply' | 'bind' + +const substitutionMethods = new Map([ + ['returns', 'returns'], [CONTEXT.returns.symbol, 'returns'], + ['throws', 'throws'], [CONTEXT.throws.symbol, 'throws'], + ['resolves', 'resolves'], [CONTEXT.resolves.symbol, 'resolves'], + ['rejects', 'rejects'], [CONTEXT.rejects.symbol, 'rejects'], + ['mimicks', 'mimicks'], [CONTEXT.mimicks.symbol, 'mimicks'] +]) + +// The context methods are only reachable through their (registered) symbols. Their string names are ordinary members. +const contextMethods = new Map([ + [CONTEXT.received.symbol, 'received'], + [CONTEXT.didNotReceive.symbol, 'didNotReceive'], + [CONTEXT.clearReceivedCalls.symbol, 'clearReceivedCalls'], + [CONTEXT.mimick.symbol, 'mimick'], + [CONTEXT.configure.symbol, 'configure'] +]) + +/** `returns`, `throws`, ... (string or symbol) when the key names a substitution method. */ +export const substitutionMethodOf = (property: PropertyKey): SubstitutionMethod | undefined => substitutionMethods.get(property) +/** `received`, `didNotReceive`, ... when the key is one of the exported context symbols. */ +export const contextMethodOf = (property: PropertyKey): ContextMethod | undefined => contextMethods.get(property) + +export const isStringAssertionKey = (property: PropertyKey): property is StringAssertionKey => + property === 'received' || property === 'didNotReceive' + +export const isFunctionHelperKey = (property: PropertyKey): property is FunctionHelperKey => + property === 'call' || property === 'apply' || property === 'bind' + +export type SpecialProperty = 'then' | 'toJSON' | typeof inspect.custom | typeof Symbol.toPrimitive | typeof INTERNAL | typeof substituteMarker + +/** + * Properties that are never recorded and never configurable: `then` (substitutes are not thenables), + * printing hooks, and the library's own markers. + */ +export const isSpecialProperty = (property: PropertyKey): property is SpecialProperty => + property === 'then' || + property === 'toJSON' || + property === inspect.custom || + property === Symbol.toPrimitive || + property === INTERNAL || + property === substituteMarker + +export const keyToString = (key: PropertyKey): string => typeof key === 'symbol' ? key.toString() : String(key) + +export const EXCEPTION = { callCountMismatch: 'CallCountMismatch', propertyNotMocked: 'PropertyNotMocked' } as const - -export const constants = { - PROPERTY: propertyTypes, - ACCESSOR: accessorTypes, - EXCEPTION: substituteExceptionTypes -} as const +export type SubstituteExceptionType = typeof EXCEPTION[keyof typeof EXCEPTION] diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts new file mode 100644 index 0000000..3379fb6 --- /dev/null +++ b/src/internals/Engine.ts @@ -0,0 +1,522 @@ +import { inspect, InspectOptions } from 'util' + +import { substituteMarker } from '../shared' +import { AutoEntry, Substitution, SubstituteState } from './SubstituteState' +import { CallRecord, currentSequence, retract } from './CallRecord' +import { RecordedArguments } from './RecordedArguments' +import { SubstituteException } from './SubstituteException' +import { assertCall, assertPropertyRead, assertSet, settle, validateExpectedCount, ExpectedCount } from './Assertions' +import { + ContextMethod, FunctionHelperKey, INTERNAL, SELF, SpecialProperty, SubstitutionMethod, + contextMethodOf, isFunctionHelperKey, isSpecialProperty, isStringAssertionKey, keyToString, substitutionMethodOf +} from './Constants' +import { formatArguments, formatValue, isPrinting, withPrintGuard } from './utilities' + +/* + * The proxies handed out by the library are thin translators onto SubstituteState. + * + * A member access cannot know yet what it is part of: `sub.add` may be a property read, the callee of + * `sub.add(1, 2)`, the start of a setup (`sub.add(1, 2).returns(3)`) or of a nested use + * (`sub.logger.info('x')`). Every proxy is therefore lazy: a read is recorded as a property read and + * returns a callable handle. Invoking the handle turns that read into an invocation. Accessing a + * substitution method (`returns`, ...) on a handle turns the expression into a setup and retracts the + * records of the expression. Accessing anything else uses the auto-substitute behind the handle. + */ + +type Printer = (options?: InspectOptions) => string +type Face = + | { kind: 'root', state: SubstituteState } + | { kind: 'member', entry: AutoEntry } // the result of reading an unconfigured member + | { kind: 'result', entry: AutoEntry } // the result of an unconfigured call + +const TAKE_PENDING_READ = Symbol('take pending read') +type ReadSource = typeof TAKE_PENDING_READ | CallRecord | undefined + +const newTarget = (): any => function () { } + +// ---- printing --------------------------------------------------------------------------------- + +const memberLabel = (key: PropertyKey) => key === SELF ? 'call' : keyToString(key) + +const printState = (state: SubstituteState, colors: boolean): string => { + if (isPrinting()) return state.path + return withPrintGuard(() => { + const lines: string[] = [] + const records = state.records + if (records.length > 0) { + lines.push(' received:') + for (const record of records) { + const name = record.key === SELF ? '' : keyToString(record.key) + const suffix = record.kind === 'call' + ? formatArguments(record.args, colors) + : record.kind === 'set' ? ` = ${formatValue(record.args?.[0], colors)}` : '' + lines.push(` ${name}${suffix}`) + } + } + const substitutions = state.substitutions() + if (substitutions.length > 0) { + lines.push(' configured:') + for (const substitution of substitutions) { + const name = substitution.key === SELF ? '' : keyToString(substitution.key) + const args = substitution.kind === 'call' ? formatArguments(substitution.args?.value, colors) : '' + const values = substitution.method === 'auto' ? '' : substitution.values.map(value => formatValue(value, colors)).join(', ') + lines.push(` ${name}${args} => ${substitution.method}(${values})`) + } + } + return `${state.path} {${lines.length > 0 ? '\n' + lines.join('\n') : ''}\n}` + }) +} + +const printFace = (face: Face, colors: boolean): string => { + switch (face.kind) { + case 'root': return printState(face.state, colors) + case 'member': return `property<${memberLabel(face.entry.key)}>: ` + case 'result': return withPrintGuard(() => `method<${memberLabel(face.entry.key)}>: ${formatArguments(face.entry.args?.value, colors)}`) + } +} + +const special = (property: SpecialProperty, print: Printer, internal: unknown): any => { + switch (property) { + case 'then': + return undefined // substitutes are not thenables, so they can be awaited and resolved + case substituteMarker: + return true + case INTERNAL: + return internal + case inspect.custom: + return (_depth: number, options?: InspectOptions) => print(options) + default: // toJSON, Symbol.toPrimitive + return () => print(undefined) + } +} + +const colorsOf = (options?: InspectOptions) => options?.colors === true + +// ---- substitutes and auto-substitutes --------------------------------------------------------- + +export const createSubstitute = (): any => createFaceProxy({ kind: 'root', state: new SubstituteState() }) + +const entryProxy = (entry: AutoEntry): any => { + if (entry.proxy === undefined) + entry.proxy = createFaceProxy(entry.kind === 'get' ? { kind: 'member', entry } : { kind: 'result', entry }) + return entry.proxy +} + +const faceState = (face: Face): SubstituteState => face.kind === 'root' ? face.state : face.entry.state +const faceChainHead = (face: Face): CallRecord | undefined => face.kind === 'root' ? undefined : face.entry.chainHead() + +const createFaceProxy = (face: Face): any => new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + return faceGet(face, property, get) + }, + set: function set(_target: unknown, property: PropertyKey, value: unknown) { + faceSet(face, property, value, set) + return true + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + return faceApply(face, args, apply) + } +}) + +const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any => { + if (isSpecialProperty(property)) return special(property, options => printFace(face, colorsOf(options)), face) + + if (face.kind !== 'root') { + const entry = face.entry + const method = substitutionMethodOf(property) + if (method !== undefined) return setupFunction(entry, method) + + if (face.kind === 'member' && isFunctionHelperKey(property)) + return functionHelper(property, (args, start) => invoke(entry.parent, entry.key, args, start, TAKE_PENDING_READ)) + + // D11: `sub.received(n)` followed by a member access other than a substitution method is an assertion. + if (face.kind === 'result' && isStringAssertionKey(entry.key)) { + const assertion = resolveStringAssertion(entry, stackStart) + return assertionMember(assertion.state, property, assertion.count, stackStart) + } + } + + const context = contextMethodOf(property) + if (context !== undefined) return contextFunction(context, () => faceState(face), faceChainHead(face)) + + const chainHead = faceChainHead(face) + return realGet(faceState(face), property, chainHead, stackStart) +} + +const faceSet = (face: Face, property: PropertyKey, value: unknown, stackStart: Function): void => { + if (face.kind === 'result' && isStringAssertionKey(face.entry.key)) { + const assertion = resolveStringAssertion(face.entry, stackStart) + assertSet(assertion.state, property, value, assertion.count, stackStart) + return + } + const chainHead = faceChainHead(face) + realSet(faceState(face), property, value, chainHead, stackStart) +} + +const faceApply = (face: Face, args: any[], stackStart: Function): any => { + switch (face.kind) { + case 'root': + return invoke(face.state, SELF, args, stackStart, undefined) + case 'member': + return invoke(face.entry.parent, face.entry.key, args, stackStart, TAKE_PENDING_READ) + case 'result': { + const chainHead = face.entry.chainHead() + return invoke(face.entry.state, SELF, args, stackStart, undefined, chainHead) + } + } +} + +/** `.call`, `.apply` and `.bind` on a member behave like invoking the member (D7). */ +const functionHelper = (property: FunctionHelperKey, invokeWith: (args: any[], stackStart: Function) => any): Function => { + switch (property) { + case 'call': + return function call(_thisArg: unknown, ...args: any[]) { + return invokeWith(args, call) + } + case 'apply': + return function apply(_thisArg: unknown, args?: ArrayLike | null) { + return invokeWith(args === undefined || args === null ? [] : Array.from(args), apply) + } + case 'bind': + return function bind(_thisArg: unknown, ...boundArgs: any[]) { + const bound = function (...args: any[]) { + return invokeWith([...boundArgs, ...args], bound) + } + return bound + } + } +} + +const hasMember = (instance: any, key: PropertyKey): boolean => + ((typeof instance === 'object' && instance !== null) || typeof instance === 'function') && key in instance + +const execute = (substitution: Substitution, args?: any[]): any => { + const value = substitution.nextValue() + switch (substitution.method) { + case 'returns': + return value + case 'throws': + throw value + case 'resolves': + return Promise.resolve(value) + case 'rejects': + return Promise.reject(value) + case 'mimicks': + return args === undefined ? value() : value(...args) + case 'auto': + return entryProxy(substitution.entry!) + } +} + +/** A real property read by the code under test. */ +const realGet = (state: SubstituteState, key: PropertyKey, chainPrevious: CallRecord | undefined, stackStart: Function): any => { + const substitution = state.propertySubstitution(key) + if (substitution !== undefined) { + const record = state.addRecord('get', key, undefined, stackStart, chainPrevious) + // Configured both as a property and as a method: whether this read is a property read is only known later. + if (state.hasCallSubstitutions(key)) return deferredRead(state, key, record, substitution) + return execute(substitution) + } + + const mimicked = state.mimicked + if (mimicked !== undefined && hasMember(mimicked.instance, key)) { + const value = mimicked.instance[key] + if (typeof value !== 'function') { + state.addRecord('get', key, undefined, stackStart, chainPrevious) + return value + } + } + + const record = state.addRecord('get', key, undefined, stackStart, chainPrevious) + state.addPendingRead(record) + const entry = state.propertyEntry(key) + entry.handOut(record) + return entryProxy(entry) +} + +/** A real property assignment by the code under test. */ +const realSet = (state: SubstituteState, key: PropertyKey, value: unknown, chainPrevious: CallRecord | undefined, stackStart: Function): void => { + state.addRecord('set', key, [value], stackStart, chainPrevious) + if (state.mimicked !== undefined) state.mimicked.instance[key] = value +} + +/** + * An invocation. With Arg matchers among the arguments it is a setup (D3): nothing is recorded and no + * substitution runs. Otherwise it is a real call: it is recorded (taking over the property read of the + * method, if there is one) and resolved. + */ +const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStart: Function, readSource: ReadSource, chainPrevious?: CallRecord): any => { + const read = readSource === TAKE_PENDING_READ ? state.takePendingRead(key) : readSource + + if (RecordedArguments.containsMatchers(args)) { + const specification = RecordedArguments.forSpecification(args) + retract(read) + retract(chainPrevious) + return configureCall(state, key, specification) + } + + let record: CallRecord + if (read !== undefined && read.kind === 'get' && !read.retracted) { + read.convertToCall(args, stackStart) + record = read + } else record = state.addRecord('call', key, args, stackStart, chainPrevious) + + return resolveCall(state, key, args, record) +} + +const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], record: CallRecord): any => { + const substitution = state.findCallSubstitution(key, args) + if (substitution !== undefined) { + if (substitution.method === 'auto') substitution.entry!.handOut(record) + return execute(substitution, args) + } + + const mimicked = state.mimicked + if (mimicked !== undefined) { + const instance = mimicked.instance + if (key === SELF) { + if (typeof instance === 'function') return Reflect.apply(instance, undefined, args) + } else { + const member = instance[key] + if (typeof member === 'function') return Reflect.apply(member, instance, args) + } + } + + const entry = state.callEntry(key, args) + entry.handOut(record) + return entryProxy(entry) +} + +/** The actual arguments of the call that handed out this auto-substitute, when that was the previous operation. */ +const actualArgumentsOf = (entry: AutoEntry): any[] => { + const head = entry.chainHead() + if (head !== undefined && head.kind === 'call' && head.args !== undefined) return head.args + return entry.args?.value ?? [] +} + +/** `.returns(...)` and friends on a handle: configures the member read or the call that produced the handle. */ +const setupFunction = (entry: AutoEntry, method: SubstitutionMethod): Function => { + const specification = entry.kind === 'call' && entry.args!.argumentsClass !== 'plain' + ? RecordedArguments.from(actualArgumentsOf(entry)) // handed out by a matcher setup: configure the actual call + : entry.args + retract(entry.chainHead()) + return function substitution(...values: any[]) { + if (entry.kind === 'get') entry.parent.setPropertySubstitution(entry.key, method, values) + else entry.parent.addCallSubstitution(entry.key, specification!, method, values) + } +} + +const resolveStringAssertion = (entry: AutoEntry, stackStart: Function): { state: SubstituteState, count: ExpectedCount } => { + const args = actualArgumentsOf(entry) + retract(entry.chainHead()) + const count = entry.key === 'didNotReceive' ? 0 : validateExpectedCount(args[0], stackStart) + return { state: entry.parent, count } +} + +const validateMimickInstance = (instance: unknown, stackStart: Function) => { + if ((typeof instance !== 'object' || instance === null) && typeof instance !== 'function') + throw SubstituteException.generic(`mimick expects an object or a function to delegate to, but received ${formatValue(instance, false)}.`, stackStart) +} + +/** The functions behind the exported symbols: sub[received](n), sub[didNotReceive](), sub[configure](), ... */ +const contextFunction = (context: ContextMethod, getState: () => SubstituteState, chainHead: CallRecord | undefined): Function => { + switch (context) { + case 'received': + return function received(count?: unknown) { + const expected = validateExpectedCount(count, received) + retract(chainHead) + return createAssertionProxy(getState(), expected) + } + case 'didNotReceive': + return function didNotReceive() { + retract(chainHead) + return createAssertionProxy(getState(), 0) + } + case 'clearReceivedCalls': + return function clearReceivedCalls() { + retract(chainHead) + getState().clearReceivedCalls() + } + case 'mimick': + return function mimick(instance: unknown) { + validateMimickInstance(instance, mimick) + retract(chainHead) + getState().mimicked = { instance } + } + case 'configure': + return function configure() { + retract(chainHead) + return createConfigureProxy(getState()) + } + } +} + +/** A read of a member that is configured both as a property and as a method (see issue 178). */ +const deferredRead = (state: SubstituteState, key: PropertyKey, record: CallRecord, substitution: Substitution): any => { + let resolved = false + let value: any + const resolve = () => { + if (!resolved) { + resolved = true + value = execute(substitution) + } + return value + } + const print: Printer = () => `property<${memberLabel(key)}>: ` + return new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, undefined) + const method = substitutionMethodOf(property) + if (method !== undefined) { + if (record.seq === currentSequence()) retract(record) + return function substitution(...values: any[]) { + state.setPropertySubstitution(key, method, values) + } + } + if (isFunctionHelperKey(property)) return functionHelper(property, (args, start) => invoke(state, key, args, start, record)) + return resolve()[property] + }, + set: function set(_target: unknown, property: PropertyKey, newValue: unknown) { + resolve()[property] = newValue + return true + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + return invoke(state, key, args, apply, record) + } + }) +} + +// ---- assertions ------------------------------------------------------------------------------- + +const describeCount = (count: ExpectedCount) => count === undefined ? 'received()' : count === 0 ? 'didNotReceive()' : `received(${count})` + +const createAssertionProxy = (state: SubstituteState, count: ExpectedCount): any => { + const print: Printer = () => `${state.path}.${describeCount(count)}` + return new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, undefined) + return assertionMember(state, property, count, get) + }, + set: function set(_target: unknown, property: PropertyKey, value: unknown) { + assertSet(state, property, value, count, set) + return true + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + assertCall(state, SELF, args, count, apply) + return undefined + } + }) +} + +/** `sub.received(n).member`: a property assertion now, or a method assertion if it is invoked. */ +const assertionMember = (state: SubstituteState, key: PropertyKey, count: ExpectedCount, stackStart: Function): any => { + const deferred = assertPropertyRead(state, key, count, stackStart) + const assertInvocation = (args: any[], start: Function): undefined => { + settle(deferred) + assertCall(state, key, args, count, start) + return undefined + } + const unsupported = (property: PropertyKey, start: Function): never => { + if (deferred !== undefined && !deferred.settled) { + settle(deferred) + throw deferred.error() + } + throw SubstituteException.generic( + `Cannot use "${keyToString(property)}" on the assertion ${state.path}.${describeCount(count)}.${memberLabel(key)}: ` + + `an assertion ends with a property read, a property assignment or an invocation. ` + + `To assert on a nested substitute, start the assertion from it, e.g. sub.${memberLabel(key)}.received().member(...)`, + start + ) + } + const print: Printer = () => `${state.path}.${describeCount(count)}.${memberLabel(key)}` + return new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, undefined) + if (isFunctionHelperKey(property)) return functionHelper(property, assertInvocation) + return unsupported(property, get) + }, + set: function set(_target: unknown, property: PropertyKey) { + return unsupported(property, set) + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + return assertInvocation(args, apply) + } + }) +} + +// ---- configure view: every call is a setup ---------------------------------------------------- + +const configureSetError = (start: Function) => SubstituteException.generic( + 'Property assignments cannot be configured. Use .returns(...) on the property to configure what it returns.', + start +) + +const createConfigureProxy = (state: SubstituteState): any => { + const print: Printer = () => `${state.path}[configure]()` + return new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, undefined) + return configureMember(state, property) + }, + set: function set() { + throw configureSetError(set) + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + return configureCall(state, SELF, RecordedArguments.forSpecification(args)) + } + }) +} + +const configureMember = (state: SubstituteState, key: PropertyKey): any => { + const context = contextMethodOf(key) + if (context !== undefined) return contextFunction(context, () => state, undefined) + const print: Printer = () => `${state.memberPath(key)} (configure)` + return new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, undefined) + const method = substitutionMethodOf(property) + if (method !== undefined) return function substitution(...values: any[]) { + state.setPropertySubstitution(key, method, values) + } + if (isFunctionHelperKey(property)) + return functionHelper(property, args => configureCall(state, key, RecordedArguments.forSpecification(args))) + return configureMember(state.propertyEntry(key).state, property) + }, + set: function set() { + throw configureSetError(set) + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + return configureCall(state, key, RecordedArguments.forSpecification(args)) + } + }) +} + +/** The auto-substitute that answers calls matching the specification, registered so that real calls find it. */ +const nestedEntry = (state: SubstituteState, key: PropertyKey, specification: RecordedArguments): AutoEntry => { + const entry = state.specificationEntry(key, specification) + const existing = state.callSubstitutionFor(key, specification) + if (existing === undefined || existing.method !== 'auto' || existing.entry !== entry) + state.addCallSubstitution(key, specification, 'auto', [], entry) + return entry +} + +/** A call in a setup: `.returns(...)` configures it, anything else configures the auto-substitute it returns. */ +const configureCall = (state: SubstituteState, key: PropertyKey, specification: RecordedArguments): any => { + const print: Printer = options => withPrintGuard(() => `method<${memberLabel(key)}>: ${formatArguments(specification.value, colorsOf(options))} (configure)`) + return new Proxy(newTarget(), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, undefined) + const method = substitutionMethodOf(property) + if (method !== undefined) return function substitution(...values: any[]) { + state.addCallSubstitution(key, specification, method, values) + } + return configureMember(nestedEntry(state, key, specification).state, property) + }, + set: function set() { + throw configureSetError(set) + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + return configureCall(nestedEntry(state, key, specification).state, SELF, RecordedArguments.forSpecification(args)) + } + }) +} diff --git a/src/internals/RecordedArguments.ts b/src/internals/RecordedArguments.ts index 470d489..7fa7675 100644 --- a/src/internals/RecordedArguments.ts +++ b/src/internals/RecordedArguments.ts @@ -1,5 +1,6 @@ import { inspect, InspectOptions, isDeepStrictEqual } from 'util' -import { Argument, AllArguments } from '../shared' +import { argumentsAreEquivalent, evaluateArgument, isAllArguments, isArgumentMatcher, isSingleArgument } from '../shared' +import { SubstituteException } from './SubstituteException' type ArgumentsClass = 'plain' | 'with-predicate' | 'wildcard' const argumentsClassDigitMapper: Record = { @@ -9,6 +10,32 @@ const argumentsClassDigitMapper: Record = { none: 4 } +export type ArgumentsMatch = { + matches: boolean + /** The error thrown by an Arg.is predicate, if the match failed because a predicate threw. */ + predicateError?: unknown + predicateThrew: boolean +} + +const MATCH: ArgumentsMatch = { matches: true, predicateThrew: false } +const NO_MATCH: ArgumentsMatch = { matches: false, predicateThrew: false } + +const literalEquals = (expected: unknown, actual: unknown): boolean => { + if (expected === actual) return expected !== 0 || Object.is(expected, actual) + try { + return isDeepStrictEqual(expected, actual) + } catch { + return false + } +} + +/** + * An argument list. Either the actual arguments of a call, or the expected arguments of a setup or an + * assertion (a specification), which may contain Arg matchers. + * + * Matching is one-directional: `specification.matches(actualArguments)`. A matcher on the specification + * side matches actual values; an Arg that ends up on the actual side is never treated as a matcher. + */ export class RecordedArguments { private _argumentsClass?: ArgumentsClass private _value?: any[] @@ -28,12 +55,27 @@ export class RecordedArguments { return new this() } + /** + * Creates the specification of a setup or an assertion. Arg.all() matches the rest of the argument list, + * so anything after it is a usage error. + */ + static forSpecification(rawArguments: any[]): RecordedArguments { + const allIndex = rawArguments.findIndex(argument => isAllArguments(argument)) + if (allIndex !== -1 && allIndex !== rawArguments.length - 1) + throw SubstituteException.generic( + `Arg.all() matches all remaining arguments, so it must be the last argument. ` + + `Found ${rawArguments.length - allIndex - 1} argument(s) after it.` + ) + return new this(rawArguments) + } + + static containsMatchers(rawArguments: readonly unknown[]): boolean { + for (const argument of rawArguments) if (isArgumentMatcher(argument)) return true + return false + } + static sort(objectWithArguments: T[]): T[] { - return objectWithArguments.sort((a, b) => { - const aClass = a.recordedArguments.argumentsClass ?? 'none' - const bClass = b.recordedArguments.argumentsClass ?? 'none' - return argumentsClassDigitMapper[aClass] - argumentsClassDigitMapper[bClass] - }) + return objectWithArguments.sort((a, b) => a.recordedArguments.rank - b.recordedArguments.rank) } get argumentsClass(): ArgumentsClass | undefined { @@ -44,32 +86,65 @@ export class RecordedArguments { return this._value } + /** Specificity rank: all-literal (0) beats predicates (1) beats a leading Arg.all() wildcard (2). */ + get rank(): number { + return argumentsClassDigitMapper[this._argumentsClass ?? 'none'] + } + public hasArguments(): this is this & { argumentsClass: ArgumentsClass, value: any[] } { return Array.isArray(this._value) } + /** `this` is the specification, `other` holds the actual arguments. */ public match(other: RecordedArguments): boolean { - if (this.argumentsClass === 'wildcard' || other.argumentsClass === 'wildcard') return true - if (!this.hasArguments() || !other.hasArguments()) return !this.hasArguments() && !other.hasArguments() - if (this.value.length !== other.value.length) return false - return this.value.every((argument, index) => this.areArgumentsEqual(argument, other.value[index])) + return this.matchDetailed(other.value).matches } - private classifyArguments(rawArguments: any[]): ArgumentsClass { - const allPlain = rawArguments.every(arg => !(arg instanceof Argument || arg instanceof AllArguments)) - if (allPlain) return 'plain' + public matches(actualArguments: readonly unknown[] | undefined): boolean { + return this.matchDetailed(actualArguments).matches + } - const hasSingleArgument = rawArguments.some(arg => arg instanceof Argument) - if (hasSingleArgument) return 'with-predicate' + public matchDetailed(actualArguments: readonly unknown[] | undefined): ArgumentsMatch { + const expected = this._value + if (expected === undefined || actualArguments === undefined) + return expected === undefined && actualArguments === undefined ? MATCH : NO_MATCH + + for (let index = 0; index < expected.length; index++) { + const expectedArgument = expected[index] + if (isAllArguments(expectedArgument)) return MATCH + if (index >= actualArguments.length) return NO_MATCH + const actualArgument = actualArguments[index] + if (isSingleArgument(expectedArgument)) { + if (isArgumentMatcher(actualArgument)) return NO_MATCH + const evaluation = evaluateArgument(expectedArgument, actualArgument) + if (!evaluation.matches) + return evaluation.threw ? { matches: false, predicateThrew: true, predicateError: evaluation.error } : NO_MATCH + continue + } + if (!literalEquals(expectedArgument, actualArgument)) return NO_MATCH + } + return expected.length === actualArguments.length ? MATCH : NO_MATCH + } - return 'wildcard' + /** True when both specifications are the same (used to recognise a re-configuration). */ + public equals(other: RecordedArguments): boolean { + const a = this._value + const b = other._value + if (a === undefined || b === undefined) return a === b + if (a.length !== b.length) return false + return a.every((argument, index) => { + const otherArgument = b[index] + const aIsMatcher = isArgumentMatcher(argument) + const bIsMatcher = isArgumentMatcher(otherArgument) + if (aIsMatcher || bIsMatcher) return aIsMatcher && bIsMatcher && argumentsAreEquivalent(argument, otherArgument) + return literalEquals(argument, otherArgument) + }) } - private areArgumentsEqual(a: any, b: any): boolean { - if (a instanceof Argument && b instanceof Argument) return false - if (a instanceof Argument) return a.matches(b) - if (b instanceof Argument) return b.matches(a) - return isDeepStrictEqual(a, b) + private classifyArguments(rawArguments: any[]): ArgumentsClass { + if (!RecordedArguments.containsMatchers(rawArguments)) return 'plain' + if (rawArguments.length > 0 && isAllArguments(rawArguments[0])) return 'wildcard' + return 'with-predicate' } [inspect.custom](_: number, options: InspectOptions) { diff --git a/src/internals/Recorder.ts b/src/internals/Recorder.ts deleted file mode 100644 index c6e3540..0000000 --- a/src/internals/Recorder.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { inspect, InspectOptions } from 'util' - -import { FilterFunction } from './Types' -import { RecordsSet } from './RecordsSet' - -export class Recorder { - private _identity: PropertyKey - private _records: RecordsSet - private _indexedRecords: Map> - - private constructor(identity: PropertyKey) { - this._identity = identity - this._records = new RecordsSet() - this._indexedRecords = new Map() - } - - public static withIdentityProperty(identity: keyof TRecord): Recorder { - return new this(identity) - } - - public get records(): RecordsSet { - return this._records - } - - public get indexedRecords(): Map> { - return this._indexedRecords - } - - public addIndexedRecord(record: TRecord): void { - const id = this.getIdentity(record) - this.addRecord(record) - const existingNodes = this.indexedRecords.get(id) - if (typeof existingNodes === 'undefined') this.indexedRecords.set(id, new RecordsSet([record])) - else existingNodes.add(record) - } - - public addRecord(record: TRecord): void { - this._records.add(record) - } - - public getSiblingsOf(record: TRecord): RecordsSet { - const siblings = this.indexedRecords.get(this.getIdentity(record)) ?? new RecordsSet() - return siblings.filter(sibling => sibling !== record) - } - - public clearRecords(filterFunction: FilterFunction): void { - const recordsToRemove = this.records.filter(filterFunction) - for (const record of recordsToRemove) { - this.clearIndexedRecord(record) - this.records.delete(record) - } - } - - public [inspect.custom](_: number, options: InspectOptions): string { - const entries = [...this.indexedRecords.entries()] - return entries.map( - ([key, value]) => `\n ${key.toString()}: {\n${[...value.map(v => ` ${inspect(v, options)}`)].join(',\n')}\n }` - ).join() - } - - private getIdentity(record: TRecord): PropertyKey { - // for typescript < 4.6, we need to intersect PropertyKey with the default type - return record[this._identity as keyof TRecord] as TRecord[keyof TRecord] & PropertyKey - } - - private clearIndexedRecord(record: TRecord): void { - const id = this.getIdentity(record) - const indexedRecord = this.indexedRecords.get(id) - if (typeof indexedRecord === 'undefined') return - indexedRecord.delete(record) - if (indexedRecord.size === 0) this.indexedRecords.delete(id) - } -} diff --git a/src/internals/RecordsSet.ts b/src/internals/RecordsSet.ts deleted file mode 100644 index 06fdab3..0000000 --- a/src/internals/RecordsSet.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { FilterFunction } from './Types' - -type MapperFunction = (item: T) => R -type Transformer = { type: 'filter', predicate: FilterFunction } | { type: 'mapper', predicate: MapperFunction } - -export class RecordsSet extends Set { - private _transformer?: Transformer - private readonly _prevIter?: RecordsSet - - constructor(value?: Iterable | readonly T[]) { - const isRecordSet = value instanceof RecordsSet - super(isRecordSet ? undefined : value) - if (isRecordSet) this._prevIter = value - } - - get size(): number { - const currentSize = super.size - if (this._prevIter instanceof RecordsSet) return currentSize + this._prevIter.size - return currentSize - } - - filter(predicate: FilterFunction): RecordsSet { - const newInstance = new RecordsSet(this as RecordsSet) - newInstance._transformer = { type: 'filter', predicate } - return newInstance - } - - map(predicate: MapperFunction): RecordsSet { - const newInstance = new RecordsSet(this) - newInstance._transformer = { type: 'mapper', predicate } - return newInstance as RecordsSet - } - - has(value: T): boolean { - if (super.has(value)) return true - return this._prevIter instanceof RecordsSet ? this._prevIter.has(value) : false - } - - delete(value: T): boolean { - const deleted = super.delete(value) - if (deleted) return true - return this._prevIter instanceof RecordsSet ? this._prevIter.delete(value) : false - } - - clear() { - if (this._prevIter instanceof RecordsSet) { - this._prevIter.clear() - Object.defineProperty(this, '_prevIter', { value: undefined }) - } - super.clear() - } - - *[Symbol.iterator](): IterableIterator { - yield* this.values() - } - - *values(): IterableIterator { - if (this._prevIter instanceof RecordsSet) yield* this.applyTransform(this._prevIter) - yield* this.applyTransform(super.values()) - } - - private * applyTransform(itarable: Iterable): IterableIterator { - const transform = this._transformer - if (typeof transform === 'undefined') return yield* itarable - for (const value of itarable) { - switch (transform.type) { - case 'filter': - if (transform.predicate(value)) yield value - break - case 'mapper': yield transform.predicate(value) - break - } - } - } -} diff --git a/src/internals/SubstituteException.ts b/src/internals/SubstituteException.ts index d84706e..aeec0eb 100644 --- a/src/internals/SubstituteException.ts +++ b/src/internals/SubstituteException.ts @@ -1,47 +1,140 @@ -import { SubstituteNodeModel, SubstituteExceptionType } from './Types' -import { stringify, TextBuilder } from './utilities' -import { constants } from './Constants' +import { inspect } from 'util' + +import { EXCEPTION, SELF, SubstituteExceptionType, keyToString } from './Constants' +import { colorsEnabled, firstStackFrame, formatArguments, formatValue, plural, TextBuilder, TextPart, withPrintGuard } from './utilities' +import type { CallRecord } from './CallRecord' +import type { RecordedArguments } from './RecordedArguments' + +export type ExpectedKind = 'method' | 'property' | 'set' | 'unknown' + +export type CallCountExpectation = { + /** undefined means "1 or more" */ + count: number | undefined + kind: ExpectedKind + /** The expected arguments (for 'method') or the expected value as a one-element list (for 'set'). */ + specification?: RecordedArguments +} + +export type ListedCall = { + record: CallRecord + matches: boolean + predicateThrew?: boolean + predicateError?: unknown +} + +export type CallCountMismatch = { + /** Path of the substitute, e.g. `@Substitute` or `@Substitute.logger`. */ + substitutePath: string + key: PropertyKey + expected: CallCountExpectation + /** How many matching calls were received, already phrased (e.g. 'none', '4', '2 property reads and 1 method call'). */ + receivedText: string + listed: ListedCall[] +} + +const kindPhrase = (kind: ExpectedKind, count: number | undefined): string => { + switch (kind) { + case 'method': return plural('method call', count) + case 'property': return plural('property read', count) + case 'set': return plural('property assignment', count) + case 'unknown': return `${plural('property read', count)} or ${plural('method call', count)}` + } +} + +const memberLabel = (key: PropertyKey): string => key === SELF ? '' : keyToString(key) + +const describeExpectedCall = (mismatch: CallCountMismatch, colors: boolean): string => { + const { key, expected } = mismatch + const name = key === SELF ? mismatch.substitutePath : keyToString(key) + switch (expected.kind) { + case 'method': return `${name}${formatArguments(expected.specification?.value ?? [], colors)}` + case 'set': return `${name} = ${formatValue(expected.specification?.value?.[0], colors)}` + default: return name + } +} + +const describeRecord = (record: CallRecord, colors: boolean): string => { + switch (record.kind) { + case 'get': return '' + case 'call': return formatArguments(record.args, colors) + case 'set': return ` = ${formatValue(record.args?.[0], colors)}` + } +} + +const describeError = (error: unknown): string => { + try { + if (error instanceof Error) return `${error.name}: ${error.message}` + return inspect(error, { depth: 1, colors: false }) + } catch { + return String(typeof error) + } +} export class SubstituteException extends Error { public type?: SubstituteExceptionType - constructor(msg: string, exceptionType?: SubstituteExceptionType) { + constructor(msg: string, exceptionType?: SubstituteExceptionType, stackStart?: Function) { super(msg) this.name = new.target.name this.type = exceptionType - const errorConstructor = exceptionType !== undefined ? SubstituteException[`for${exceptionType}`] : undefined - Error.captureStackTrace(this, errorConstructor) + if (typeof Error.captureStackTrace === 'function') Error.captureStackTrace(this, stackStart ?? new.target) } - public static forCallCountMismatch( - expected: { count: number | undefined, call: SubstituteNodeModel }, - received: { matchCount: number, calls: SubstituteNodeModel[] } - ) { - const callPath = `@Substitute.${expected.call.property.toString()}` + public static forCallCountMismatch(mismatch: CallCountMismatch, stackStart?: Function): SubstituteException { + const colors = colorsEnabled() + const message = withPrintGuard(() => SubstituteException.buildCallCountMismatchMessage(mismatch, colors)) + return new this(message, EXCEPTION.callCountMismatch, stackStart) + } + + private static buildCallCountMismatchMessage(mismatch: CallCountMismatch, colors: boolean): string { + const { expected, key, substitutePath } = mismatch + const memberPath = key === SELF ? substitutePath : `${substitutePath}.${keyToString(key)}` const textBuilder = new TextBuilder() .add('Call count mismatch in ') - .add('@Substitute.', t => t.underline()) - .add(expected.call.property.toString(), t => t.bold().underline()) + if (key === SELF) textBuilder.add(substitutePath, t => t.bold().underline()) + else textBuilder + .add(`${substitutePath}.`, t => t.underline()) + .add(memberLabel(key), t => t.bold().underline()) + textBuilder .add(':') .newLine().add('Expected to receive ') - .addParts(...stringify.expectation(expected)) + .add(expected.count === undefined ? '1 or more' : expected.count.toString(), t => t.bold()) + .add(' ') + .add(kindPhrase(expected.kind, expected.count), t => t.bold()) + .add(' matching ') + .add(describeExpectedCall(mismatch, colors), t => t.bold()) .add(', but received ') - .add(received.matchCount < 1 ? 'none' : received.matchCount.toString(), t => t.faint()) + .add(mismatch.receivedText, t => t.faint()) .add('.') - if (received.calls.length > 0) textBuilder.newLine().add(`All property or method calls to ${callPath} received so far:${stringify.receivedCalls(callPath, expected.call, received.calls)}`) - return new this(textBuilder.toString(), constants.EXCEPTION.callCountMismatch) + if (mismatch.listed.length > 0) { + textBuilder.newLine().add(`All property or method calls to ${memberPath} received so far:`) + for (const listed of mismatch.listed) { + const style = (part: TextPart) => listed.matches ? part.faint() : part.bold() + textBuilder.newLine().add('› ') + .add(listed.matches ? '✔ ' : '✘ ', style) + .add(memberPath, style) + .add(describeRecord(listed.record, colors), style) + const frame = firstStackFrame(listed.record.stack) + if (frame !== undefined) textBuilder.newLine().add(frame.replace('at ', 'called at '), t => t.faint()) + if (listed.predicateThrew) + textBuilder.newLine().add(` (an Arg.is predicate threw while matching this call: ${describeError(listed.predicateError)})`, t => t.faint()) + } + textBuilder.newLine() + } + + return textBuilder.toString(colors) } public static forPropertyNotMocked(property: PropertyKey) { return new this( `There is no mock for property: ${property.toString()}`, - constants.EXCEPTION.propertyNotMocked + EXCEPTION.propertyNotMocked ) } - public static generic(message: string) { - return new this(message) + public static generic(message: string, stackStart?: Function) { + return new this(message, undefined, stackStart) } } diff --git a/src/internals/SubstituteNode.ts b/src/internals/SubstituteNode.ts deleted file mode 100644 index f236674..0000000 --- a/src/internals/SubstituteNode.ts +++ /dev/null @@ -1,342 +0,0 @@ -import { inspect, InspectOptions, types } from 'util' - -import { SubstituteNodeBase } from './SubstituteNodeBase' -import { RecordedArguments } from './RecordedArguments' -import { SubstituteException } from './SubstituteException' -import { is, stringify, transform } from './utilities' - -import { constants } from './Constants' -import type { SubstituteContext, PropertyType, SubstituteNodeModel, AccessorType, SubstituteMethod, SubstitutionMethod, AssertionMethod } from './Types' -import { constants as sharedConstants } from '../shared/Constants' - - -export const instance = Symbol('Substitute:Instance') - -type SpecialProperty = typeof instance | typeof inspect.custom | typeof Symbol.toPrimitive | 'then' | 'toJSON' -// TODO(configure): runtime support for the configure context is not implemented yet -type TT = Exclude -type ObjectSubstitute = { - [P in typeof sharedConstants.CONTEXT[TT]['raw'] | typeof sharedConstants.CONTEXT[TT]['symbol']]: - (...args: any[]) => T | void | Promise | Promise -} - -export class SubstituteNode extends SubstituteNodeBase implements ObjectSubstitute, SubstituteNodeModel { - private _proxy: SubstituteNode - - private _propertyType: PropertyType = constants.PROPERTY.property - private _accessorType: AccessorType = constants.ACCESSOR.get - private _recordedArguments: RecordedArguments = RecordedArguments.none() - - private _context: SubstituteContext = sharedConstants.CONTEXT.none.symbol - private _retrySubstitutionExecutionAttempt: boolean = false - - public stack?: string - - private constructor(key: PropertyKey, parent?: SubstituteNode) { - super(key, parent) - - this._proxy = new Proxy( - this, - { - get: function (target, property) { - if (target.isSpecialProperty(property)) { - return target.evaluateSpecialProperty(property) - } - - if (target._retrySubstitutionExecutionAttempt) { - return target.reattemptSubstitutionExecution()[property] - } - - const newNode = SubstituteNode.createChild(property, target) - if (target.isAssertion) newNode.executeAssertion() - const unresolvedAssertionFollowedBySubstitution = !target.hasContext && is.method.assertion(target.property) && !is.method.substitution(newNode.property) - if (target.hasDepthOfAtLeast(1) && unresolvedAssertionFollowedBySubstitution) { - target.assignContext(target.property) - target[target.context as AssertionMethod](...Array.isArray(target.recordedArguments.value) ? target.recordedArguments.value : [undefined]) - if (target.isAssertion) newNode.executeAssertion() - // if (target.isConfiguration) newNode.executeConfiguration() - } - if (target.isRoot() && is.method.contextValue(property) && (is.method.assertion(property) || is.method.configuration(property))) { - newNode.assignContext(property) - return newNode[property].bind(newNode) - } - Error.captureStackTrace(newNode, this.get) - return newNode.attemptSubstitutionExecution() - }, - set: function (target, property, value) { - const newNode = SubstituteNode.createChild(property, target) - newNode.handleSetter(value) - if (target.isAssertion) - newNode.executeAssertion() - - if (target.hasDepthOfAtLeast(1) && !target.hasContext && is.method.assertion(target.property)) { - target.assignContext(target.property) - target[target.property](...Array.isArray(target.recordedArguments.value) ? target.recordedArguments.value : [undefined]) - if (target.isAssertion) newNode.executeAssertion() - } - - return true - }, - apply: function (target, _thisArg, rawArguments) { - target.handleMethod(rawArguments) - if (target.hasDepthOfAtLeast(2)) { - if (is.method.substitution(target.property)) return target.parent.assignContext(target.property) - if (target.parent.isAssertion) return target.executeAssertion() - } - Error.captureStackTrace(target, this.apply) - return target.isAssertion ? target.proxy : target.attemptSubstitutionExecution() - } - } - ) - } - - public received(amount?: number | undefined) { - return this[sharedConstants.CONTEXT.received.symbol](amount); - } - - public didNotReceive() { - return this[sharedConstants.CONTEXT.didNotReceive.symbol](); - } - - public mimick(instance: unknown) { - return this[sharedConstants.CONTEXT.mimick.symbol](instance); - } - - public clearReceivedCalls() { - return this[sharedConstants.CONTEXT.clearReceivedCalls.symbol](); - } - - public static createRoot(): SubstituteNode { - return new this('*Substitute') - } - - public static createChild(key: PropertyKey, parent: SubstituteNode): SubstituteNode { - return new this(key, parent) - } - - public get proxy(): SubstituteNode { - return this._proxy - } - - get context(): SubstituteContext { - return this._context - } - - get hasContext(): boolean { - return this.context !== sharedConstants.CONTEXT.none.symbol - } - - get isSubstitution(): boolean { - return is.CONTEXT.substitution(this.context) - } - - get isAssertion(): boolean { - return is.CONTEXT.assertion(this.context) - } - - get property(): PropertyKey { - return this.key - } - - get propertyType(): PropertyType { - return this._propertyType - } - - get accessorType() { - return this._accessorType - } - - get recordedArguments(): RecordedArguments { - return this._recordedArguments - } - - public [sharedConstants.CONTEXT.received.symbol](amount?: number): SubstituteNode { - this.handleMethod([amount]) - return this.proxy - } - - public [sharedConstants.CONTEXT.didNotReceive.symbol](): SubstituteNode { - this.handleMethod([0]) - return this.proxy - } - - public [sharedConstants.CONTEXT.mimick.symbol](_instance: unknown) { - throw new Error('Mimick is not implemented yet') - } - - public [sharedConstants.CONTEXT.configure.symbol](): SubstituteNode { - // TODO(configure): placeholder until the configure context is implemented - throw SubstituteException.generic('configure is not implemented yet') - } - - public [sharedConstants.CONTEXT.clearReceivedCalls.symbol](): void { - this.handleMethod([]) - - const filter = (node: SubstituteNode) => is.CONTEXT.none(node.context) - this.recorder.clearRecords(filter) - } - - public [inspect.custom](...args: [_: number, options: InspectOptions]): string { - return types.isProxy(this) ? this[inspect.custom](...args) : this.printableForm(...args) - } - - private assignContext(context: SubstituteMethod): void { - this._context = typeof context === 'string' ? - transform.rawSymbolContextMap[context] : - context - } - - private reattemptSubstitutionExecution(): SubstituteNode | any { - const result = this.attemptSubstitutionExecution() - this._retrySubstitutionExecutionAttempt = false - return result - } - - private attemptSubstitutionExecution(): SubstituteNode | any { - const mostSuitableSubstitution = this.getMostSuitableSubstitution() - return mostSuitableSubstitution instanceof SubstituteNode - ? mostSuitableSubstitution.executeSubstitution(this.recordedArguments) - : this.proxy - } - - private executeSubstitution(contextArguments: RecordedArguments) { - if (!this.hasChild()) - throw new TypeError('Substitue node has no child') - - if (!this.child.recordedArguments.hasArguments()) - throw new TypeError('Child args') - - const substitutionMethod = this.context as SubstitutionMethod - const substitutionValue = this.child.recordedArguments.value.length > 1 - ? this.child.recordedArguments.value?.shift() - : this.child.recordedArguments.value[0] - switch (substitutionMethod) { - case sharedConstants.CONTEXT.throws.symbol: - case 'throws': - throw substitutionValue - case sharedConstants.CONTEXT.mimicks.symbol: - case 'mimicks': - if (is.PROPERTY.property(this.propertyType)) return substitutionValue() - if (!contextArguments.hasArguments()) throw new TypeError('Context arguments cannot be undefined') - return substitutionValue(...contextArguments.value) - case sharedConstants.CONTEXT.resolves.symbol: - case 'resolves': - return Promise.resolve(substitutionValue) - case sharedConstants.CONTEXT.rejects.symbol: - case 'rejects': - return Promise.reject(substitutionValue) - case sharedConstants.CONTEXT.returns.symbol: - case 'returns': - return substitutionValue - default: - throw SubstituteException.generic(`Substitution method '${substitutionMethod}' not implemented`) - } - } - - private executeAssertion(): void | never { - if (!this.hasDepthOfAtLeast(2)) - throw new Error('Depth is less than 2') - - if (!this.parent.recordedArguments.hasArguments()) - throw new Error('No parent args present') - - const expectedCount = this.parent.recordedArguments.value[0] ?? undefined - const finiteExpectation = expectedCount !== undefined - if (finiteExpectation && (!Number.isInteger(expectedCount) || expectedCount < 0)) { - return - } - - // const withContext = this.parent.property === sharedConstants.CONTEXT.received.symbol - const withContext = false - const siblings = [...this.getAllSiblings().filter(n => (withContext || !n.hasContext) && n.accessorType === this.accessorType)] - const hasBeenCalled = siblings.length > 0 - const hasSiblingOfSamePropertyType = siblings.some(sibling => sibling.propertyType === this.propertyType) - const allRecordedArguments = siblings.map(sibling => sibling.recordedArguments) - if ( - !hasBeenCalled && - (!finiteExpectation || expectedCount > 0) - ) throw SubstituteException.forCallCountMismatch( // Here we don't know here if it's a property or method, so we should throw something more generic - { count: expectedCount, call: this }, - { matchCount: 0, calls: siblings } - ) - - if (!hasBeenCalled || hasSiblingOfSamePropertyType) { - this._scheduledAssertionException = undefined - const actualCount = allRecordedArguments.filter(r => r.match(this.recordedArguments)).length - const matchedExpectation = (!finiteExpectation && actualCount > 0) || expectedCount === actualCount - if (matchedExpectation) return - const exception = SubstituteException.forCallCountMismatch( - { count: expectedCount, call: this }, - { matchCount: actualCount, calls: siblings } - ) - const potentialMethodAssertion = is.PROPERTY.property(this.propertyType) && siblings.some(sibling => is.PROPERTY.method(sibling.propertyType)) - if (potentialMethodAssertion) this.schedulePropertyAssertionException(exception) - else throw exception - } - } - - private schedulePropertyAssertionException(exception: SubstituteException) { - this._scheduledAssertionException = exception - process.nextTick(() => { - const nodeIsStillProperty = is.PROPERTY.property(this.propertyType) - if (nodeIsStillProperty && this._scheduledAssertionException !== undefined) throw this._scheduledAssertionException - }) - } - - private _scheduledAssertionException: SubstituteException | undefined - - private handleSetter(value: any) { - this._accessorType = constants.ACCESSOR.set - this._recordedArguments = RecordedArguments.from([value]) - } - - private handleMethod(rawArguments: any[]): void { - this._propertyType = constants.PROPERTY.method - this._recordedArguments = RecordedArguments.from(rawArguments) - } - - private getMostSuitableSubstitution(): SubstituteNode | void { - const commonSuitableSubstitutionsSet = this.getAllSiblings().filter(node => node.isSubstitution) - const strictSuitableSubstitutionsSet = commonSuitableSubstitutionsSet.filter( - node => node.propertyType === this.propertyType && node.recordedArguments.match(this.recordedArguments) - ) - const potentialSuitableSubstitutionsSet = is.PROPERTY.property(this.propertyType) && !this._retrySubstitutionExecutionAttempt ? - commonSuitableSubstitutionsSet.filter(node => is.PROPERTY.method(node.propertyType)) : - [] - - const strictSuitableSubstitutions = [...strictSuitableSubstitutionsSet] - const potentialSuitableSubstitutions = [...potentialSuitableSubstitutionsSet] - const hasSuitableSubstitutions = strictSuitableSubstitutions.length > 0 - const onlySubstitutionsWithThisNodePropertyType = potentialSuitableSubstitutions.length === 0 - if (onlySubstitutionsWithThisNodePropertyType && hasSuitableSubstitutions) - return RecordedArguments.sort(strictSuitableSubstitutions)[0] - - if (!onlySubstitutionsWithThisNodePropertyType) - this._retrySubstitutionExecutionAttempt = true - } - - private isSpecialProperty(property: PropertyKey): property is SpecialProperty { - return property === instance || property === inspect.custom || property === Symbol.toPrimitive || property === 'then' || property === 'toJSON' - } - - private evaluateSpecialProperty(property: SpecialProperty) { - switch (property) { - case instance: - return this - case 'toJSON': - case inspect.custom: - case Symbol.toPrimitive: - return this.printableForm.bind(this) - - case 'then': - return - - default: - throw SubstituteException.generic(`Evaluation of special property ${property} is not implemented.`) - } - } - - private printableForm(_: number, options: InspectOptions): string { - return this.isRoot() ? stringify.rootNode(this, inspect(this.recorder, options)) : stringify.node(this, this.child, options) - } -} diff --git a/src/internals/SubstituteNodeBase.ts b/src/internals/SubstituteNodeBase.ts deleted file mode 100644 index 9cbff07..0000000 --- a/src/internals/SubstituteNodeBase.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { Recorder } from './Recorder' -import { RecordsSet } from './RecordsSet' - -export abstract class SubstituteNodeBase extends Function { - private _root: this & { parent: undefined } - private _parent?: this - private _child?: this - private _depth: number - - private _recorder: Recorder - - constructor(private _key: PropertyKey, parent?: SubstituteNodeBase) { - super() - const shouldBeRoot = !this.isNode(parent) - if (shouldBeRoot) { - this._recorder = Recorder.withIdentityProperty('key') - this._root = this as this & { parent: undefined } - this._depth = 0 - return - } - - parent.assignChild(this) - this._parent = parent - this._recorder = parent.recorder - this._root = parent.root - this._depth = parent.depth + 1 - if (this.parent === this.root) this.recorder.addIndexedRecord(this) - } - - private isNode(node?: SubstituteNodeBase): node is this { - return typeof node !== 'undefined' - } - - public get key(): PropertyKey { - return this._key - } - - public get recorder(): Recorder { - return this._recorder - } - - protected get parent(): this | undefined { - return this._parent - } - - protected get child(): this | undefined { - return this._child - } - - protected get root(): this & { parent: undefined } { - return this._root - } - - protected get depth(): number { - return this._depth - } - - private assignChild(child: this): void { - this._child = child - } - - protected isRoot(): this is this & { parent: undefined } { - return typeof this._parent === 'undefined' - } - - protected hasDepthOfAtLeast(depth: TDepth): this is (TDepth extends 0 ? this & { parent: undefined } : this & { parent: ThisType }) { - return this.depth >= depth - } - - protected getAllSiblings(): RecordsSet { - return this.recorder.getSiblingsOf(this) - } - - protected hasChild(): this is this & { child: ThisType } { - return this.child instanceof SubstituteNodeBase - } -} \ No newline at end of file diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts new file mode 100644 index 0000000..4dee4b8 --- /dev/null +++ b/src/internals/SubstituteState.ts @@ -0,0 +1,292 @@ +import { inspect } from 'util' + +import { CallRecord, RecordKind, currentSequence } from './CallRecord' +import { RecordedArguments } from './RecordedArguments' +import { SELF, SubstitutionMethod, keyToString } from './Constants' +import { fingerprintArguments } from './utilities' + +let substitutionOrder = 0 + +/** A configured behaviour: `sub.add(1, Arg.any()).returns(3, 4)`, `sub.prop.throws(err)`, ... */ +export class Substitution { + private _next = 0 + public readonly order = ++substitutionOrder + + constructor( + public readonly kind: 'get' | 'call', + public readonly key: PropertyKey, + /** The expected arguments for a call; undefined for a property. */ + public readonly args: RecordedArguments | undefined, + /** 'auto' returns a cached auto-substitute; it is registered by nested setups such as `sub[configure]().a(Arg.any()).b.returns(1)`. */ + public readonly method: SubstitutionMethod | 'auto', + public readonly values: readonly any[], + public readonly entry?: AutoEntry + ) { } + + public get rank(): number { + return this.args?.rank ?? 0 + } + + /** The values are used in order and the last one keeps being used (NSubstitute semantics). */ + public nextValue(): any { + const values = this.values + if (values.length === 0) return undefined + const value = values[this._next] + if (this._next < values.length - 1) this._next++ + return value + } +} + +/** + * The auto-substitute behind an unconfigured property read (kind 'get', one per member) or an + * unconfigured call (kind 'call', one per member and argument list). Repeated access to the same path + * with matching arguments gets the same entry, so nested setups and assertions find each other. + */ +export class AutoEntry { + private _state?: SubstituteState + public proxy: any + /** The record of the operation that last handed out this entry's proxy, with the sequence number at that time. */ + public handedOutBy?: { record: CallRecord, seq: number } + + constructor( + public readonly kind: 'get' | 'call', + public readonly parent: SubstituteState, + public readonly key: PropertyKey, + public readonly args?: RecordedArguments + ) { } + + public get state(): SubstituteState { + if (this._state === undefined) this._state = new SubstituteState(this) + return this._state + } + + public get materializedState(): SubstituteState | undefined { + return this._state + } + + public handOut(record: CallRecord): void { + this.handedOutBy = { record, seq: currentSequence() } + } + + /** + * The record that handed out this proxy, if that was the most recent operation of all. Then the + * current operation continues the same expression (`sub.a.b`), and setups or assertions resolved + * later on in the chain retract it. + */ + public chainHead(): CallRecord | undefined { + const handedOutBy = this.handedOutBy + return handedOutBy !== undefined && handedOutBy.seq === currentSequence() ? handedOutBy.record : undefined + } +} + +type CallEntryIndex = { + byFingerprint: Map + unfingerprinted: AutoEntry[] +} + +const memberPath = (state: SubstituteState, key: PropertyKey): string => + key === SELF ? state.path : `${state.path}.${keyToString(key)}` + +const shortArguments = (args: RecordedArguments | undefined): string => { + const values = args?.value ?? [] + try { + return values.map(value => inspect(value, { depth: 0, colors: false, breakLength: Infinity })).join(', ') + } catch { + return '...' + } +} + +/** + * Everything the library knows about one substitute (the root, or a cached auto-substitute): + * the received calls, the configured substitutions, the mimicked instance and the auto-substitutes. + * Received calls and configured substitutions are kept apart, so that resolving a call never scans + * the history of received calls. + */ +export class SubstituteState { + private readonly _records: CallRecord[] = [] + private readonly _recordsByKey = new Map() + private readonly _pendingReads = new Map() + + private readonly _propertySubstitutions = new Map() + private readonly _callSubstitutions = new Map() + + private readonly _propertyEntries = new Map() + private readonly _callEntries = new Map() + private readonly _specificationEntries = new Map() + + public mimicked?: { instance: any } + + constructor(public readonly owner?: AutoEntry) { } + + public get path(): string { + const owner = this.owner + if (owner === undefined) return '@Substitute' + const path = memberPath(owner.parent, owner.key) + return owner.kind === 'get' ? path : `${path}(${shortArguments(owner.args)})` + } + + public memberPath(key: PropertyKey): string { + return memberPath(this, key) + } + + // ---- received calls ------------------------------------------------------------------------- + + public addRecord(kind: RecordKind, key: PropertyKey, args: any[] | undefined, stackStart: Function, chainPrevious?: CallRecord): CallRecord { + const record = new CallRecord(kind, key, args, stackStart, chainPrevious) + this._records.push(record) + const forKey = this._recordsByKey.get(key) + if (forKey === undefined) this._recordsByKey.set(key, [record]) + else forKey.push(record) + return record + } + + /** A property read whose result may still be invoked (a method read in order to call it). */ + public addPendingRead(record: CallRecord): void { + const pending = this._pendingReads.get(record.key) + if (pending === undefined) this._pendingReads.set(record.key, [record]) + else pending.push(record) + } + + /** The most recent property read of the member that has not been invoked yet. */ + public takePendingRead(key: PropertyKey): CallRecord | undefined { + const pending = this._pendingReads.get(key) + while (pending !== undefined && pending.length > 0) { + const record = pending.pop()! + if (!record.retracted && record.kind === 'get') return record + } + return undefined + } + + /** Received calls of one member, in order, without retracted records. */ + public recordsFor(key: PropertyKey): CallRecord[] { + const records = this._recordsByKey.get(key) + return records === undefined ? [] : records.filter(record => !record.retracted) + } + + public get records(): CallRecord[] { + return this._records.filter(record => !record.retracted) + } + + public clearReceivedCalls(): void { + this._records.length = 0 + this._recordsByKey.clear() + this._pendingReads.clear() + for (const entry of this.entries()) entry.materializedState?.clearReceivedCalls() + } + + // ---- substitutions -------------------------------------------------------------------------- + + public setPropertySubstitution(key: PropertyKey, method: SubstitutionMethod, values: readonly any[]): void { + this._propertySubstitutions.set(key, new Substitution('get', key, undefined, method, values)) + } + + public propertySubstitution(key: PropertyKey): Substitution | undefined { + return this._propertySubstitutions.get(key) + } + + /** Adds a call substitution. A substitution with the same specification is replaced (most recent wins). */ + public addCallSubstitution(key: PropertyKey, args: RecordedArguments, method: SubstitutionMethod | 'auto', values: readonly any[], entry?: AutoEntry): Substitution { + const substitution = new Substitution('call', key, args, method, values, entry) + const list = this._callSubstitutions.get(key) + if (list === undefined) { + this._callSubstitutions.set(key, [substitution]) + return substitution + } + const index = list.findIndex(existing => existing.args!.equals(args)) + if (index !== -1) list.splice(index, 1) + list.push(substitution) + return substitution + } + + public hasCallSubstitutions(key: PropertyKey): boolean { + const list = this._callSubstitutions.get(key) + return list !== undefined && list.length > 0 + } + + /** The substitution configured with exactly this specification, if any. */ + public callSubstitutionFor(key: PropertyKey, args: RecordedArguments): Substitution | undefined { + return this._callSubstitutions.get(key)?.find(substitution => substitution.args!.equals(args)) + } + + /** + * The substitution that answers a call: the most specific class wins (all-literal, then predicates, + * then Arg.all()), and within a class the most recently configured one wins. + */ + public findCallSubstitution(key: PropertyKey, actualArguments: readonly unknown[]): Substitution | undefined { + const list = this._callSubstitutions.get(key) + if (list === undefined) return undefined + let best: Substitution | undefined + for (let index = list.length - 1; index >= 0; index--) { + const candidate = list[index] + if (best !== undefined && candidate.rank >= best.rank) continue + if (candidate.args!.matches(actualArguments)) best = candidate + } + return best + } + + // ---- auto-substitutes ----------------------------------------------------------------------- + + public propertyEntry(key: PropertyKey): AutoEntry { + let entry = this._propertyEntries.get(key) + if (entry === undefined) { + entry = new AutoEntry('get', this, key) + this._propertyEntries.set(key, entry) + } + return entry + } + + /** The auto-substitute for a call with these actual (literal) arguments. */ + public callEntry(key: PropertyKey, actualArguments: any[]): AutoEntry { + let index = this._callEntries.get(key) + if (index === undefined) { + index = { byFingerprint: new Map(), unfingerprinted: [] } + this._callEntries.set(key, index) + } + const fingerprint = fingerprintArguments(actualArguments) + let bucket: AutoEntry[] | undefined + if (fingerprint === undefined) bucket = index.unfingerprinted + else { + bucket = index.byFingerprint.get(fingerprint) + if (bucket === undefined) { + bucket = [] + index.byFingerprint.set(fingerprint, bucket) + } + } + for (const entry of bucket) if (entry.args!.matches(actualArguments)) return entry + const entry = new AutoEntry('call', this, key, RecordedArguments.from(actualArguments)) + bucket.push(entry) + return entry + } + + /** The auto-substitute for a call specification used in a nested setup (`a(Arg.any()).b.returns(1)`). */ + public specificationEntry(key: PropertyKey, specification: RecordedArguments): AutoEntry { + if (specification.argumentsClass === 'plain') return this.callEntry(key, specification.value!) + let list = this._specificationEntries.get(key) + if (list === undefined) { + list = [] + this._specificationEntries.set(key, list) + } + let entry = list.find(existing => existing.args!.equals(specification)) + if (entry === undefined) { + entry = new AutoEntry('call', this, key, specification) + list.push(entry) + } + return entry + } + + public *entries(): IterableIterator { + yield* this._propertyEntries.values() + for (const index of this._callEntries.values()) { + for (const bucket of index.byFingerprint.values()) yield* bucket + yield* index.unfingerprinted + } + for (const list of this._specificationEntries.values()) yield* list + } + + /** Configured substitutions, for printing. */ + public substitutions(): Substitution[] { + const all: Substitution[] = [...this._propertySubstitutions.values()] + for (const list of this._callSubstitutions.values()) all.push(...list) + return all.sort((a, b) => a.order - b.order) + } +} diff --git a/src/internals/Types.ts b/src/internals/Types.ts deleted file mode 100644 index f7bc490..0000000 --- a/src/internals/Types.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { RecordedArguments } from './RecordedArguments' -import type { constants } from './Constants' -import type { constants as sharedConstants } from '../shared' - -type ContextMap = typeof sharedConstants.CONTEXT -type Unfold = T[keyof T] - -export type ContextReceived = Unfold -export type ContextDidNotReceive = Unfold -export type ContextClearReceivedCalls = Unfold -export type ContextMimick = Unfold -export type ContextConfigure = Unfold -export type ContextMimicks = Unfold -export type ContextThrows = Unfold -export type ContextReturns = Unfold -export type ContextResolves = Unfold -export type ContextRejects = Unfold - -export type AssertionMethod = ContextReceived | ContextDidNotReceive -export type ConfigurationMethod = ContextClearReceivedCalls | ContextMimick | ContextConfigure -export type SubstitutionMethod = ContextMimicks | ContextThrows | ContextReturns | ContextResolves | ContextRejects -export type ContextNone = Unfold - -export type SubstituteMethod = AssertionMethod | ConfigurationMethod | SubstitutionMethod -export type SubstituteContext = Exclude -// export type SubstituteContext2 = ContextMap[keyof ContextMap]['symbol'] -// export type ClearType = typeof constants.CLEAR[keyof typeof constants.CLEAR]['raw'] - -// export type ClearType = 'all' | 'receivedCalls' | 'substituteValues' -type PropertyType = typeof constants.PROPERTY.method | typeof constants.PROPERTY.property -type AccessorType = typeof constants.ACCESSOR.get | typeof constants.ACCESSOR.set -type SubstituteExceptionType = typeof constants.EXCEPTION.callCountMismatch | typeof constants.EXCEPTION.propertyNotMocked - -export type FilterFunction = (item: T) => boolean - -export type { PropertyType, AccessorType, SubstituteExceptionType } -export type SubstituteNodeModel = { - propertyType: PropertyType - property: PropertyKey - context: SubstituteContext - recordedArguments: RecordedArguments - stack?: string -} diff --git a/src/internals/index.ts b/src/internals/index.ts index 87c8170..7ee2978 100644 --- a/src/internals/index.ts +++ b/src/internals/index.ts @@ -1 +1,2 @@ -export * from './SubstituteNode' +export { createSubstitute } from './Engine' +export { SubstituteException } from './SubstituteException' diff --git a/src/internals/utilities/ArgumentHash.ts b/src/internals/utilities/ArgumentHash.ts new file mode 100644 index 0000000..d320c4c --- /dev/null +++ b/src/internals/utilities/ArgumentHash.ts @@ -0,0 +1,84 @@ +/** + * A cheap structural fingerprint of an argument list, used to look up the auto-substitute cached for a + * call in O(1) instead of comparing against every earlier argument list. + * + * Contract: arguments that are deep strictly equal (util.isDeepStrictEqual) always get the same + * fingerprint. The fingerprint may be coarser than equality (callers still compare with + * isDeepStrictEqual inside a bucket). Functions, and therefore substitutes, are fingerprinted by + * identity and are never traversed. Returns undefined when the arguments cannot be fingerprinted + * (for example when a getter throws). + */ +const objectIds = new WeakMap() +const symbolIds = new Map() +let nextId = 0 + +const idOfObject = (value: object): number => { + let id = objectIds.get(value) + if (id === undefined) { + id = ++nextId + objectIds.set(value, id) + } + return id +} + +const idOfSymbol = (value: symbol): number => { + let id = symbolIds.get(value) + if (id === undefined) { + id = ++nextId + symbolIds.set(value, id) + } + return id +} + +const MAX_DEPTH = 2 +const MAX_ITEMS = 8 +const MAX_KEYS = 16 +const MAX_STRING = 64 + +const fingerprintValue = (value: unknown, depth: number): string => { + switch (typeof value) { + case 'string': + return `s${value.length}:${value.length > MAX_STRING ? value.slice(0, MAX_STRING) : value}` + case 'number': + return Object.is(value, -0) ? 'n-0' : `n${value}` + case 'bigint': + return `b${value}` + case 'boolean': + return value ? 't' : 'f' + case 'undefined': + return 'u' + case 'symbol': + return `y${idOfSymbol(value)}` + case 'function': + return `F${idOfObject(value)}` + } + if (value === null) return 'N' + const object = value as object + if (depth >= MAX_DEPTH) return 'O' + if (Array.isArray(object)) { + let fingerprint = `A${object.length}[` + const length = Math.min(object.length, MAX_ITEMS) + for (let index = 0; index < length; index++) fingerprint += fingerprintValue(object[index], depth + 1) + ',' + return fingerprint + ']' + } + if (ArrayBuffer.isView(object)) return `V${object.byteLength}` + if (object instanceof Date) return `D${object.getTime()}` + if (object instanceof Map) return `M${object.size}` + if (object instanceof Set) return `S${object.size}` + const keys = Object.keys(object) + if (keys.length > MAX_KEYS) return `K${keys.length}` + keys.sort() + let fingerprint = '{' + for (const key of keys) fingerprint += `${key}:${fingerprintValue((object as any)[key], depth + 1)},` + return fingerprint + '}' +} + +export const fingerprintArguments = (args: readonly unknown[]): string | undefined => { + try { + let fingerprint = `${args.length}|` + for (const arg of args) fingerprint += fingerprintValue(arg, 0) + '|' + return fingerprint + } catch { + return undefined + } +} diff --git a/src/internals/utilities/Colors.ts b/src/internals/utilities/Colors.ts new file mode 100644 index 0000000..99f2cb2 --- /dev/null +++ b/src/internals/utilities/Colors.ts @@ -0,0 +1,18 @@ +/** + * Whether messages should contain ANSI colour codes. + * FORCE_COLOR wins (0/false disables it), then NO_COLOR (any non-empty value disables colours), + * otherwise colours are only used when stdout is a TTY. + */ +export const colorsEnabled = (): boolean => { + if (typeof process === 'undefined' || process === null) return false + const env = process.env ?? {} + const forceColor = env.FORCE_COLOR + if (forceColor !== undefined) return !(forceColor === '0' || forceColor.toLowerCase() === 'false') + const noColor = env.NO_COLOR + if (noColor !== undefined && noColor !== '') return false + try { + return process.stdout?.isTTY === true + } catch { + return false + } +} diff --git a/src/internals/utilities/Guards.ts b/src/internals/utilities/Guards.ts deleted file mode 100644 index bb6baa0..0000000 --- a/src/internals/utilities/Guards.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { AssertionMethod, ConfigurationMethod, SubstituteMethod, SubstitutionMethod, SubstituteContext, PropertyType, ContextNone, ContextReceived, ContextDidNotReceive, ContextClearReceivedCalls, ContextMimick, ContextMimicks, ContextThrows, ContextReturns, ContextResolves, ContextRejects } from '../Types' -import { constants } from '../Constants' -import { constants as sharedConstants } from '../../shared' - -const isAssertionMethod = (property: PropertyKey): property is AssertionMethod => - property === sharedConstants.CONTEXT.received.raw || - property === sharedConstants.CONTEXT.received.symbol || - property === sharedConstants.CONTEXT.didNotReceive.raw || - property === sharedConstants.CONTEXT.didNotReceive.symbol -const isConfigurationMethod = (property: PropertyKey): property is ConfigurationMethod => - property === sharedConstants.CONTEXT.clearReceivedCalls.raw || - property === sharedConstants.CONTEXT.clearReceivedCalls.symbol || - property === sharedConstants.CONTEXT.mimick.raw || - property === sharedConstants.CONTEXT.mimick.symbol -const isSubstitutionMethod = (property: PropertyKey): property is SubstitutionMethod => - property === sharedConstants.CONTEXT.mimicks.raw || - property === sharedConstants.CONTEXT.mimicks.symbol || - property === sharedConstants.CONTEXT.returns.raw || - property === sharedConstants.CONTEXT.returns.symbol || - property === sharedConstants.CONTEXT.throws.raw || - property === sharedConstants.CONTEXT.throws.symbol || - property === sharedConstants.CONTEXT.resolves.raw || - property === sharedConstants.CONTEXT.resolves.symbol || - property === sharedConstants.CONTEXT.rejects.raw || - property === sharedConstants.CONTEXT.rejects.symbol -const isSubstituteMethod = (property: PropertyKey): property is SubstituteMethod => - isSubstitutionMethod(property) || isConfigurationMethod(property) || isAssertionMethod(property) - -const isPropertyProperty = (value: PropertyType): value is (typeof constants['PROPERTY']['property']) => value === constants.PROPERTY.property -const isPropertyMethod = (value: PropertyType): value is (typeof constants['PROPERTY']['method']) => value === constants.PROPERTY.method - -const isContextNone = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.none.symbol -const isContextReceived = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.received.symbol -const isContextDidNotReceive = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.didNotReceive.symbol -const isContextClearSubstitute = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.clearReceivedCalls.symbol -const isContextMimick = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.mimick.symbol -const isContextMimicks = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.mimicks.symbol -const isContextThrows = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.throws.symbol -const isContextReturns = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.returns.symbol -const isContextResolves = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.resolves.symbol -const isContextRejects = (value: SubstituteContext): value is Exclude => value === sharedConstants.CONTEXT.rejects.symbol -const isContextSubstitution = (value: SubstituteContext): value is Exclude => typeof value !== 'string' && isSubstitutionMethod(value) -const isContextAssertion = (value: SubstituteContext): value is Exclude => typeof value !== 'string' && isAssertionMethod(value) - -const isContextValue = (property: PropertyKey): property is SubstituteContext => typeof property !== 'string' && isSubstituteMethod(property) - -export const method = { - assertion: isAssertionMethod, - configuration: isConfigurationMethod, - substitution: isSubstitutionMethod, - substitute: isSubstituteMethod, - contextValue: isContextValue -} - -export const PROPERTY = { - property: isPropertyProperty, - method: isPropertyMethod -} - -export const CONTEXT = { - none: isContextNone, - received: isContextReceived, - didNotReceive: isContextDidNotReceive, - clearSubstitute: isContextClearSubstitute, - mimick: isContextMimick, - mimicks: isContextMimicks, - throws: isContextThrows, - returns: isContextReturns, - resolves: isContextResolves, - rejects: isContextRejects, - substitution: isContextSubstitution, - assertion: isContextAssertion -} diff --git a/src/internals/utilities/Stringify.ts b/src/internals/utilities/Stringify.ts index 45fbf5f..4e0439b 100644 --- a/src/internals/utilities/Stringify.ts +++ b/src/internals/utilities/Stringify.ts @@ -1,88 +1,42 @@ -import { InspectOptions, inspect } from 'util' -import { RecordedArguments } from '../RecordedArguments' -import { SubstituteNodeModel } from '../Types' -import { TextBuilder, TextPart } from './TextBuilder' -import * as is from './Guards' - -const stringifyArguments = (args: RecordedArguments, options?: InspectOptions) => args.hasArguments() - ? `(${args.value.map(x => inspect(x, { colors: true, ...options })).join(', ')})` - : '' - -const matchBasedPrefix = (isMatch?: boolean) => { - switch (isMatch) { - case true: return '✔ ' - case false: return '✘ ' - default: return '' +import { inspect, InspectOptions } from 'util' + +let printDepth = 0 + +/** + * Runs `print` while marking that the library is printing. Substitutes met while printing (for example a + * substitute recorded as an argument of another substitute) are printed in their short form, so + * printing never recurses through substitutes, even when they reference each other. + */ +export const withPrintGuard = (print: () => T): T => { + printDepth++ + try { + return print() + } finally { + printDepth-- } } -const matchBasedTextPartModifier = (isMatch?: boolean) => (part: TextPart) => isMatch === undefined - ? part - : isMatch - ? part.faint() - : part.bold() +export const isPrinting = (): boolean => printDepth > 0 -const stringifyCall = (context: { callPath: string, expectedArguments?: RecordedArguments }) => { - return (call: SubstituteNodeModel): TextPart[] => { - const isMatch = context.expectedArguments?.match(call.recordedArguments) - const textBuilder = new TextBuilder() - .add(matchBasedPrefix(isMatch)) - .add(context.callPath) - .add(stringifyArguments(call.recordedArguments)) - if (call.stack !== undefined && isMatch !== undefined) textBuilder.newLine().add(call.stack.split('\n')[1].replace('at ', 'called at '), t => t.faint()) - return textBuilder.parts.map(matchBasedTextPartModifier(isMatch)) +export const formatValue = (value: unknown, colors: boolean, options?: InspectOptions): string => { + try { + return withPrintGuard(() => inspect(value, { ...options, colors })) + } catch { + return `<${typeof value}>` } } -const plurify = (str: string, count?: number) => `${str}${count === 1 ? '' : 's'}` - -const stringifyExpectation = (expected: { count: number | undefined, call: SubstituteNodeModel }) => { - const textBuilder = new TextBuilder() - textBuilder.add(expected.count === undefined ? '1 or more' : expected.count.toString(), t => t.bold()) - .add(' ') - .add(expected.call.propertyType.description!, t => t.bold()) - .add(plurify(' call', expected.count), t => t.bold()) - .add(' matching ') - .addParts(...stringifyCall({ callPath: expected.call.property.toString() })(expected.call).map(t => t.bold())) - return textBuilder.parts -} - -const createKey = () => { - const textBuilder = new TextBuilder() - textBuilder.newLine().add('› ') - return textBuilder -} - -const stringifyReceivedCalls = (callPath: string, expected: SubstituteNodeModel, received: SubstituteNodeModel[]) => { - const textBuilder = new TextBuilder() - const stringify = stringifyCall({ callPath, expectedArguments: expected.recordedArguments }) - received.forEach(receivedCall => textBuilder.addParts(...createKey().parts, ...stringify(receivedCall))) - return textBuilder.newLine().toString() -} - -const stringifyRootNode = (_node: SubstituteNodeModel, stringifiedChildNodes: string) => { - const instanceName = '@Substitute' - return instanceName + ' {' + stringifiedChildNodes + '\n}' - -} +export const formatArguments = (args: readonly unknown[] | undefined, colors: boolean, options?: InspectOptions): string => + args === undefined ? '' : `(${args.map(arg => formatValue(arg, colors, options)).join(', ')})` -const stringifyNode = (node: SubstituteNodeModel, childNode: SubstituteNodeModel | undefined, options: InspectOptions) => { - const hasContext = !is.CONTEXT.none(node.context) - const args = stringifyArguments(node.recordedArguments, options) - const label = is.CONTEXT.substitution(node.context) ? - ' => ' : - is.CONTEXT.assertion(node.context) ? - `${childNode?.property.toString()}` : - '' - const s = hasContext ? `${label}${inspect(childNode?.recordedArguments, options)}` : '' - - return `${node.propertyType.description}<${node.property.toString()}>: ${args}${s}` +/** The first "at ..." line of a stack trace, if there is one (there is none with Error.stackTraceLimit = 0). */ +export const firstStackFrame = (stack: string | undefined): string | undefined => { + if (typeof stack !== 'string') return undefined + const lines = stack.split('\n') + for (let index = 1; index < lines.length; index++) { + if (/^\s*at /.test(lines[index])) return lines[index] + } + return undefined } -export const stringify = { - call: stringifyCall, - expectation: stringifyExpectation, - receivedCalls: stringifyReceivedCalls, - rootNode: stringifyRootNode, - node: stringifyNode -} +export const plural = (word: string, count: number | undefined) => `${word}${count === 1 ? '' : 's'}` diff --git a/src/internals/utilities/TextBuilder.ts b/src/internals/utilities/TextBuilder.ts index b0a22d4..70d53b3 100644 --- a/src/internals/utilities/TextBuilder.ts +++ b/src/internals/utilities/TextBuilder.ts @@ -1,5 +1,7 @@ +import { colorsEnabled } from './Colors' + export class TextPart { - private _modifiers: string[] = [] + private _modifiers: number[] = [] private readonly _value: string constructor(valueOrInstance: string | TextPart) { if (valueOrInstance instanceof TextPart) { @@ -8,27 +10,23 @@ export class TextPart { } else this._value = valueOrInstance } - private baseTextModifier(modifier: number) { - return `\x1b[${modifier}m` - } - public bold() { - this._modifiers.push(this.baseTextModifier(1)) + this._modifiers.push(1) return this } public faint() { - this._modifiers.push(this.baseTextModifier(2)) + this._modifiers.push(2) return this } public italic() { - this._modifiers.push(this.baseTextModifier(3)) + this._modifiers.push(3) return this } public underline() { - this._modifiers.push(this.baseTextModifier(4)) + this._modifiers.push(4) return this } @@ -40,8 +38,9 @@ export class TextPart { return new TextPart(this) } - toString() { - return this._modifiers.length > 0 ? `${this._modifiers.join('')}${this._value}\x1b[0m` : this._value + toString(colors: boolean = colorsEnabled()) { + if (!colors || this._modifiers.length === 0) return this._value + return `${this._modifiers.map(modifier => `\x1b[${modifier}m`).join('')}${this._value}\x1b[0m` } } @@ -65,8 +64,8 @@ export class TextBuilder { return this } - public toString() { - return this._parts.join('') + public toString(colors: boolean = colorsEnabled()) { + return this._parts.map(part => part.toString(colors)).join('') } public clone() { @@ -76,4 +75,4 @@ export class TextBuilder { public get parts() { return this._parts } -} \ No newline at end of file +} diff --git a/src/internals/utilities/Transformations.ts b/src/internals/utilities/Transformations.ts deleted file mode 100644 index ef2ede5..0000000 --- a/src/internals/utilities/Transformations.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { constants as sharedConstants } from '../../shared' - -type A = typeof sharedConstants.CONTEXT[Exclude] -type B = A['raw'] -type C = A['symbol'] - -export const rawSymbolContextMap: Record = { - [sharedConstants.CONTEXT.received.raw]: sharedConstants.CONTEXT.received.symbol, - [sharedConstants.CONTEXT.didNotReceive.raw]: sharedConstants.CONTEXT.didNotReceive.symbol, - [sharedConstants.CONTEXT.clearReceivedCalls.raw]: sharedConstants.CONTEXT.clearReceivedCalls.symbol, - [sharedConstants.CONTEXT.mimick.raw]: sharedConstants.CONTEXT.mimick.symbol, - [sharedConstants.CONTEXT.configure.raw]: sharedConstants.CONTEXT.configure.symbol, - [sharedConstants.CONTEXT.mimicks.raw]: sharedConstants.CONTEXT.mimicks.symbol, - [sharedConstants.CONTEXT.throws.raw]: sharedConstants.CONTEXT.throws.symbol, - [sharedConstants.CONTEXT.returns.raw]: sharedConstants.CONTEXT.returns.symbol, - [sharedConstants.CONTEXT.resolves.raw]: sharedConstants.CONTEXT.resolves.symbol, - [sharedConstants.CONTEXT.rejects.raw]: sharedConstants.CONTEXT.rejects.symbol, -} diff --git a/src/internals/utilities/index.ts b/src/internals/utilities/index.ts index 4c92f76..b3fa32d 100644 --- a/src/internals/utilities/index.ts +++ b/src/internals/utilities/index.ts @@ -1,4 +1,4 @@ export * from './TextBuilder' export * from './Stringify' -export * as is from './Guards' -export * as transform from './Transformations' +export * from './Colors' +export * from './ArgumentHash' diff --git a/src/shared/Arguments.ts b/src/shared/Arguments.ts index 267c69c..796bc08 100644 --- a/src/shared/Arguments.ts +++ b/src/shared/Arguments.ts @@ -2,6 +2,18 @@ export type PredicateFunction = (arg: T) => boolean export type ArgumentOptions = { inverseMatch?: boolean } + +export type ArgumentEvaluation = { + matches: boolean + /** Set when the predicate threw while it was evaluated. A throwing predicate never matches. */ + error?: unknown + threw: boolean +} + +// Registered symbol so that matchers created by another copy of this package are recognised too. +const argumentBrand = Symbol.for('@fluffy-spoon/substitute:argument') +type ArgumentBrand = 'single' | 'all' + class BaseArgument { private _description: string constructor( @@ -12,9 +24,8 @@ class BaseArgument { this._description = `${this._options?.inverseMatch ? 'Not ' : ''}${description}` } - matches(arg: T) { - const inverseMatch = this._options?.inverseMatch ?? false - return inverseMatch ? !this._matchingFunction(arg) : this._matchingFunction(arg) + matches(arg: T): boolean { + return evaluateArgument(this as unknown as AnyArgument, arg).matches } toString() { @@ -42,3 +53,55 @@ export class AllArguments extends BaseArgument { return this._type // TODO: Needed? } } + +export type AnyArgument = Argument | AllArguments + +const brand = (target: object, value: ArgumentBrand) => Object.defineProperty(target, argumentBrand, { value, enumerable: false }) +brand(Argument.prototype, 'single') +brand(AllArguments.prototype, 'all') + +const brandOf = (value: unknown): ArgumentBrand | undefined => { + // Only plain objects can be matchers. Never touch functions: substitutes are function proxies, + // and reading a property from them would be recorded as a property access. + if (typeof value !== 'object' || value === null) return undefined + try { + return (value as any)[argumentBrand] + } catch { + return undefined + } +} + +/** True for matchers created with Arg.any / Arg.is (including `.not`), by any copy of this package. */ +export const isSingleArgument = (value: unknown): value is Argument => brandOf(value) === 'single' +/** True for matchers created with Arg.all, by any copy of this package. */ +export const isAllArguments = (value: unknown): value is AllArguments => brandOf(value) === 'all' +/** True for any Arg matcher. */ +export const isArgumentMatcher = (value: unknown): value is AnyArgument => brandOf(value) !== undefined + +/** + * Evaluates a matcher against a value. A predicate that throws is treated as a non-match and the error is reported. + */ +export const evaluateArgument = (argument: AnyArgument, value: unknown): ArgumentEvaluation => { + const matchingFunction = argument['_matchingFunction'] as PredicateFunction + const inverseMatch = argument['_options']?.inverseMatch ?? false + try { + const result = !!matchingFunction(value) + return { matches: inverseMatch ? !result : result, threw: false } + } catch (error) { + return { matches: false, error, threw: true } + } +} + +/** + * Two matchers are equivalent when they would always give the same answer: same kind, same predicate + * (by identity) and same inversion. Used to recognise a re-configuration of the same setup. + */ +export const argumentsAreEquivalent = (a: AnyArgument, b: AnyArgument): boolean => { + if (a === b) return true + const brandA = brandOf(a) + if (brandA === undefined || brandA !== brandOf(b)) return false + if (brandA === 'all') return true + return a['_matchingFunction'] === b['_matchingFunction'] && + (a['_options']?.inverseMatch ?? false) === (b['_options']?.inverseMatch ?? false) && + a.toString() === b.toString() +} diff --git a/src/shared/Constants.ts b/src/shared/Constants.ts index 26ac0f8..cef1c5d 100644 --- a/src/shared/Constants.ts +++ b/src/shared/Constants.ts @@ -81,3 +81,17 @@ const contextTypes = { export const constants = { CONTEXT: contextTypes } + +// Every proxy handed out by the library answers `true` for this registered symbol, without recording anything. +const substituteMarker: unique symbol = Symbol.for(symbolFor('substitute')) +export { substituteMarker } + +/** True when the value is a substitute or one of its auto-substitutes (from any copy of this package). */ +export const isSubstituteProxy = (value: unknown): boolean => { + if (typeof value !== 'function') return false + try { + return (value as any)[substituteMarker] === true + } catch { + return false + } +} From 2788049c2e2f3a159d7e0c152b2ed28c34103677 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:54:18 +0000 Subject: [PATCH 003/106] test: cover the 2.0.1 runtime and argument findings Add one regression test per audit finding (named with its id) under spec/regression/fixes/, plus tests for the decisions that add or change behaviour (D2 auto-substitute caching, D5 configure, D9 deferral, D11 string assertion forms, D12 mimick, D13, D14, D16-D19) and for two copies of the package interoperating (G:RG-8). Engine changes found while testing: - every proxy target carries the printer, because util.inspect inspects the target of a proxy instead of calling its traps - only the call-site frame is captured per call, which halves the cost of a call (D19) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/arguments.test.ts | 288 ++++++++++++++++++ spec/regression/fixes/decisions.test.ts | 285 +++++++++++++++++ .../regression/fixes/duplicate-copies.test.ts | 48 +++ spec/regression/fixes/performance.test.ts | 49 +++ spec/regression/fixes/regression.test.ts | 86 ++++++ spec/regression/fixes/runtime.test.ts | 260 ++++++++++++++++ src/internals/CallRecord.ts | 15 +- src/internals/Engine.ts | 27 +- 8 files changed, 1048 insertions(+), 10 deletions(-) create mode 100644 spec/regression/fixes/arguments.test.ts create mode 100644 spec/regression/fixes/decisions.test.ts create mode 100644 spec/regression/fixes/duplicate-copies.test.ts create mode 100644 spec/regression/fixes/performance.test.ts create mode 100644 spec/regression/fixes/regression.test.ts create mode 100644 spec/regression/fixes/runtime.test.ts diff --git a/spec/regression/fixes/arguments.test.ts b/spec/regression/fixes/arguments.test.ts new file mode 100644 index 0000000..c17b6c1 --- /dev/null +++ b/spec/regression/fixes/arguments.test.ts @@ -0,0 +1,288 @@ +import test from 'ava' +import { EventEmitter } from 'events' +import { inspect, types } from 'util' + +import { Substitute, Arg, configure } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') +const configured = (substitute: unknown): any => (substitute as any)[configure]() + +test('A:RT-1 received(n) with an invalid count throws instead of passing silently', t => { + for (const count of [-1, 1.5, NaN, Infinity, '2', null, {}]) { + const calculator = Substitute.for() + t.throws(() => calculator.received(count).add(1, 2), { instanceOf: SubstituteException }, String(count)) + t.throws(() => calculator.received(count).isEnabled, { instanceOf: SubstituteException }, String(count)) + t.throws(() => { calculator.received(count).isEnabled = true }, { instanceOf: SubstituteException }, String(count)) + } + const error = t.throws(() => Substitute.for().received(-1).add(1, 2), { instanceOf: SubstituteException }) + t.regex(error.message, /non-negative integer/) +}) + +test('A:RT-2 an overlapping setup registers a new substitution and is not recorded as a call', t => { + const factory = Substitute.for() + const repositoryA = Substitute.for() + repositoryA.name.returns('A') + const repositoryB = Substitute.for() + repositoryB.name.returns('B') + + factory.create('a').returns(repositoryA) + factory.create(Arg.any()).returns(repositoryB) + factory.create('a') + factory.create('x') + + t.is(factory.create('x').name, 'B') + t.is(factory.create('a').name, 'A') + t.throws(() => factory.received().create('never'), { instanceOf: SubstituteException }) + t.throws(() => factory.received(3).create('a'), { instanceOf: SubstituteException }) + factory.received(2).create('a') + factory.received(2).create('x') + t.throws(() => factory.received(1).create(Arg.any()), { instanceOf: SubstituteException }) + factory.received(4).create(Arg.any()) + + // re-configuring the same call + const calculator = Substitute.for() + calculator.add(1, 2).returns(3) + configured(calculator).add(1, 2).returns(4) + t.is(calculator.add(1, 2), 4) + configured(calculator).add(Arg.all()).returns(10) + t.is(calculator.add(1, 2), 4) + t.is(calculator.add(2, 2), 10) +}) + +test('A:RT-3 a method that is only read never satisfies a method assertion', t => { + const handler = Substitute.for() + new EventEmitter().on('click', handler.onClick) + t.throws(() => handler.received().onClick(42), { instanceOf: SubstituteException }) + t.throws(() => handler.received(1).onClick(42), { instanceOf: SubstituteException }) + t.throws(() => handler.received(1).onClick(Arg.all()), { instanceOf: SubstituteException }) + // the read itself is still visible as a property read + t.notThrows(() => handler.received(1).onClick) +}) + +test('A:RT-4 assertions on nested and auto-returned substitutes check that substitute', t => { + const app = Substitute.for() + app.logger.info('hi') + t.notThrows(() => app.logger.received().info('hi')) + t.notThrows(() => app.logger.received(1).info('hi')) + const error = t.throws(() => app.logger.received().info('bye'), { instanceOf: SubstituteException }) + t.true(plain(error.message).startsWith('Call count mismatch in @Substitute.logger.info:')) + t.false(plain(error.message).includes('property calls')) + + // a root call with the same name does not satisfy a nested assertion, and vice versa + const root = Substitute.for() + root.warn('disk') + t.throws(() => root.logger.received().warn('disk'), { instanceOf: SubstituteException }) + root.logger.error('x') + t.throws(() => root.received().error('x'), { instanceOf: SubstituteException }) + t.notThrows(() => root.logger.didNotReceive().warn('disk')) + + const repository = Substitute.for() + const user = repository.getUser(1) + user.save() + t.notThrows(() => user.received().save()) + t.notThrows(() => repository.getUser(1).received().save()) + t.throws(() => repository.getUser(2).received().save(), { instanceOf: SubstituteException }) +}) + +test('A:RT-5 Arg.all() after other arguments only matches when the leading arguments match', t => { + const logger = Substitute.for<{ log(message: string, ...meta: unknown[]): void }>() + logger.log('user created', { id: 1 }) + t.throws(() => logger.received().log('user DELETED', Arg.all()), { instanceOf: SubstituteException }) + t.notThrows(() => logger.received(1).log('user created', Arg.all())) + t.notThrows(() => logger.received(1).log(Arg.any(), Arg.all())) + + const calculator = Substitute.for() + calculator.add(9, Arg.all()).returns('nine') + t.true(types.isProxy(calculator.add(1, 2))) + t.is(calculator.add(9), 'nine') + t.is(calculator.add(9, 1, 2), 'nine') +}) + +test('A:RT-6 received(n).m(Arg.all()) counts invocations only, not bare reads', t => { + const callback = Substitute.for() + if (callback.onDone) callback.onDone(1) + t.notThrows(() => callback.received(1).onDone(1)) + t.notThrows(() => callback.received(1).onDone(Arg.all())) + t.throws(() => callback.received(2).onDone(Arg.all()), { instanceOf: SubstituteException }) +}) + +test('A:RT-7 a decidable property assertion failure is thrown synchronously', t => { + const component = Substitute.for() + if (component.onChange) component.onChange() + void component.onChange + // 2 property reads and 1 call: received(5) fails both as a property read and as a method call + const error = t.throws(() => component.received(5).onChange, { instanceOf: SubstituteException }) + t.regex(plain(error.message), /Expected to receive 5 property reads or method calls matching onChange, but received 2 property reads and 1 method call\./) + t.throws(() => component.received(3).onChange, { instanceOf: SubstituteException }) + t.notThrows(() => component.received(2).onChange) + + const property = Substitute.for() + void property.value + t.throws(() => property.received(2).value, { instanceOf: SubstituteException }) + t.throws(() => property.didNotReceive().value, { instanceOf: SubstituteException }) +}) + +test('A:RT-8 substitutes that reference each other print without overflowing the stack', t => { + const parent = Substitute.for() + const child = Substitute.for() + parent.addChild(child) + child.setParent(parent) + const error = t.throws(() => parent.received().addChild(parent), { instanceOf: SubstituteException }) + t.true(plain(error.message).startsWith('Call count mismatch in @Substitute.addChild:')) + t.true(plain(error.message).includes('addChild(@Substitute)')) + + const self = Substitute.for() + self.link(self) + t.throws(() => self.received().link(self, 1), { instanceOf: SubstituteException }) + t.notThrows(() => self.received(1).link(self)) + t.notThrows(() => inspect(parent)) + t.notThrows(() => inspect(self, { depth: Infinity })) + t.is(inspect(self), '@Substitute {\n received:\n link(@Substitute)\n}') +}) + +test('A:RT-9 a method assertion message names the expected arguments and never says "property calls"', t => { + const calculator = Substitute.for() + // nothing received at all: decided when the member is accessed, before the arguments are known + const unknownKind = t.throws(() => calculator.received(3).add(1, Arg.any()), { instanceOf: SubstituteException }) + t.false(plain(unknownKind.message).includes('property calls')) + t.regex(plain(unknownKind.message), /Expected to receive 3 property reads or method calls matching add, but received none\./) + + calculator.add(1, 2) + const methodKind = t.throws(() => calculator.received(3).add(1, Arg.any()), { instanceOf: SubstituteException }) + t.regex(plain(methodKind.message), /Expected to receive 3 method calls matching add\(1, Arg\.any\{any\}\), but received 1\./) + + const neverCalled = t.throws(() => calculator.received().multiply(1, 2), { instanceOf: SubstituteException }) + t.false(plain(neverCalled.message).includes('property calls')) +}) + +test('A:RT-10 a throwing Arg.is predicate counts as a non-match and is reported', t => { + const repository = Substitute.for() + repository.save(null) + repository.save({ id: 1 }) + t.notThrows(() => repository.received().save(Arg.is((x: any) => x.id === 1))) + t.notThrows(() => repository.received(1).save(Arg.is((x: any) => x.id === 1))) + const error = t.throws(() => repository.received(2).save(Arg.is((x: any) => x.id === 1)), { instanceOf: SubstituteException }) + t.regex(plain(error.message), /an Arg\.is predicate threw while matching this call: TypeError/) + + // in the code under test, a throwing predicate of a configured substitution is just a non-match + const finder = Substitute.for() + finder.find(Arg.is((x: any) => x.id === 1)).returns('one') + t.notThrows(() => finder.find(null)) + t.true(types.isProxy(finder.find(null))) + t.is(finder.find({ id: 1 }), 'one') +}) + +test('A:RT-11 Arg.any("object") matches non-null objects and substitutes, but not null', t => { + t.false(Arg.any('object').matches(null)) + t.true(Arg.any('object').matches([])) + t.true(Arg.any('object').matches({})) + + const logger = Substitute.for() + const service = Substitute.for() + service.register(logger) + service.register(null) + t.notThrows(() => service.received(1).register(Arg.any('object'))) + t.notThrows(() => service.received(1).register(Arg.any('function'))) + t.true(Arg.any('object').matches(service.someMember)) +}) + +test('A:RT-12 building a message without stack frames does not crash', t => { + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + const calculator = Substitute.for() + calculator.add(1, 2) + const error = t.throws(() => calculator.received().add(9, 9), { instanceOf: SubstituteException }) + t.regex(plain(error.message), /› ✘ @Substitute\.add\(1, 2\)/) + } finally { + Error.stackTraceLimit = stackTraceLimit + } +}) + +test('A:RT-13 Arg.is rejects a missing or non-function predicate when it is created', t => { + t.throws(() => Arg.is(undefined), { instanceOf: TypeError, message: /Arg\.is expects a predicate function/ }) + t.throws(() => Arg.is(Object.create(null)), { instanceOf: TypeError, message: /Arg\.is expects a predicate function/ }) + t.throws(() => Arg.is(5 as any), { instanceOf: TypeError, message: /Arg\.is expects a predicate function/ }) + t.throws(() => Arg.is.not('x' as any), { instanceOf: TypeError, message: /Arg\.is expects a predicate function/ }) +}) + +const withEnvironment = (environment: { NO_COLOR?: string, FORCE_COLOR?: string, tty: boolean }, run: () => void) => { + const saved = { NO_COLOR: process.env.NO_COLOR, FORCE_COLOR: process.env.FORCE_COLOR } + const ttyDescriptor = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY') + const set = (name: 'NO_COLOR' | 'FORCE_COLOR', value: string | undefined) => { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } + try { + set('NO_COLOR', environment.NO_COLOR) + set('FORCE_COLOR', environment.FORCE_COLOR) + Object.defineProperty(process.stdout, 'isTTY', { value: environment.tty, configurable: true, writable: true }) + run() + } finally { + set('NO_COLOR', saved.NO_COLOR) + set('FORCE_COLOR', saved.FORCE_COLOR) + if (ttyDescriptor !== undefined) Object.defineProperty(process.stdout, 'isTTY', ttyDescriptor) + else delete (process.stdout as any).isTTY + } +} + +test('A:RT-14 messages contain ANSI codes only when colour output is appropriate', t => { + const messageOf = () => { + const calculator = Substitute.for() + calculator.add(1, 2) + try { + calculator.received().add(9, 9) + } catch (error) { + return (error as Error).message + } + throw new Error('expected the assertion to fail') + } + const hasAnsi = (text: string) => /\x1b\[/.test(text) + + withEnvironment({ tty: false }, () => t.false(hasAnsi(messageOf()), 'not a TTY')) + withEnvironment({ tty: true }, () => t.true(hasAnsi(messageOf()), 'TTY')) + withEnvironment({ tty: true, NO_COLOR: '1' }, () => t.false(hasAnsi(messageOf()), 'NO_COLOR')) + withEnvironment({ tty: false, FORCE_COLOR: '1' }, () => t.true(hasAnsi(messageOf()), 'FORCE_COLOR=1')) + withEnvironment({ tty: true, FORCE_COLOR: '0' }, () => t.false(hasAnsi(messageOf()), 'FORCE_COLOR=0')) +}) + +test('A:DOC-1 the README "Match order" and "Partial mocks" examples work', t => { + interface Calculator { add(a: number, b: number): number, subtract(a: number, b: number): number, divide(a: number, b: number): number } + + // Match order, example 1: a specific setup after a catch-all one goes through [configure]() + const first = Substitute.for() + first.add(Arg.all()).returns(10) + configured(first).add(1, 3).returns(1337) + t.is(1337, first.add(1, 3)) + t.is(10, first.add(5, 2)) + + // Match order, example 2: the catch-all setup uses matchers, so it is a setup and the order does not matter + const second = Substitute.for() + second.add(1, 3).returns(1337) + second.add(Arg.all()).returns(10) + t.is(1337, second.add(1, 3)) + t.is(10, second.add(5, 2)) + + // Partial mocks + class RealCalculator implements Calculator { + add(a: number, b: number) { return a + b } + subtract(a: number, b: number) { return a - b } + divide(a: number, b: number) { return a / b } + } + const realCalculator = new RealCalculator() + const fakeCalculator = Substitute.for() + fakeCalculator.add(Arg.is((x: number) => x < 10), Arg.any()).mimicks(realCalculator.add) + fakeCalculator.add(Arg.is((x: number) => x >= 10), Arg.any()).returns(1337) + fakeCalculator.subtract(Arg.any(), Arg.any()).mimicks(realCalculator.subtract) + fakeCalculator.divide(10, 2).mimicks(realCalculator.divide) + fakeCalculator.divide(Arg.all()).returns(1338) + + t.is(10, fakeCalculator.subtract(20, 10)) + t.is(-1, fakeCalculator.subtract(1, 2)) + t.is(105, fakeCalculator.add(5, 100)) + t.is(1337, fakeCalculator.add(10, 100)) + t.is(5, fakeCalculator.divide(10, 2)) + t.is(1338, fakeCalculator.divide(10, 5)) + t.is(1338, fakeCalculator.divide(9, 5)) +}) diff --git a/spec/regression/fixes/decisions.test.ts b/spec/regression/fixes/decisions.test.ts new file mode 100644 index 0000000..e066b05 --- /dev/null +++ b/spec/regression/fixes/decisions.test.ts @@ -0,0 +1,285 @@ +import test, { ExecutionContext, ThrowsExpectation } from 'ava' +import * as fakeTimers from '@sinonjs/fake-timers' +import { inspect, types } from 'util' + +import { Substitute, Arg, received, didNotReceive, clearReceivedCalls, mimick, configure, returns } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') + +const throwsUncaughtException = (callback: () => unknown, t: ExecutionContext, expectation: ThrowsExpectation) => { + const clock = fakeTimers.install({ toFake: ['nextTick'] }) + try { + callback() + t.throws(() => clock.tick(1), expectation) + } finally { + clock.uninstall() + } +} + +const doesNotThrowLater = (callback: () => unknown, t: ExecutionContext) => { + const clock = fakeTimers.install({ toFake: ['nextTick'] }) + try { + callback() + t.notThrows(() => clock.tick(1)) + } finally { + clock.uninstall() + } +} + +test('D2 repeated access to the same member path returns the same auto-substitute', t => { + const app = Substitute.for() + t.is(app.logger, app.logger) + t.is(app.getCalc(), app.getCalc()) + t.is(app.getUser({ id: 1 }), app.getUser({ id: 1 })) + t.not(app.getUser({ id: 1 }), app.getUser({ id: 2 })) + t.not(app.getCalc(), app.getCalc(1)) + + // nested setups + app.getCalc().add(1, 2).returns(99) + t.is(app.getCalc().add(1, 2), 99) + app.logger.level.returns(3) + t.is(app.logger.level, 3) + app.find(Arg.any()).name.returns('any') + t.is(app.find(5).name, 'any') + t.is(app.find('x').name, 'any') + + // nested assertions + app.logger.info('hi') + app.logger.received().info('hi') + app.logger.received(1).info('hi') + t.throws(() => app.logger.received().info('bye'), { instanceOf: SubstituteException }) + t.throws(() => app.logger.didNotReceive().info('hi'), { instanceOf: SubstituteException }) + + // the expressions used for setups and assertions are not received calls themselves + const fresh = Substitute.for() + fresh.getCalc().add(1, 2).returns(99) + fresh.logger.level.returns(3) + fresh.logger.received(0).info('hi') + fresh.getCalc()[received](0).add(1, 2) + t.notThrows(() => fresh.didNotReceive().getCalc()) + t.notThrows(() => fresh.didNotReceive().logger) + t.is(fresh.getCalc().add(1, 2), 99) + t.notThrows(() => fresh.received(1).getCalc()) +}) + +test('D2 the same auto-substitute is shared with the code under test', t => { + interface Repository { save(item: string): void } + interface Unit { repository(name: string): Repository } + const unit = Substitute.for() + const codeUnderTest = (u: Unit) => u.repository('users').save('alice') + codeUnderTest(unit) + t.notThrows(() => (unit.repository('users') as any).received(1).save('alice')) + t.throws(() => (unit.repository('orders') as any).received().save('alice'), { instanceOf: SubstituteException }) + t.notThrows(() => unit.received(1).repository('users')) +}) + +test('D5 sub[configure]() makes every call a setup', t => { + const calculator = Substitute.for() + calculator.add(1, 3).returns(1) + const reconfigure = calculator[configure]() + reconfigure.add(1, 3).returns(1337) + t.is(calculator.add(1, 3), 1337) + + // configure never runs substitutions and records nothing + let mimicked = 0 + calculator.multiply(Arg.all()).mimicks(() => ++mimicked) + calculator.divide(Arg.all()).throws(new Error('no')) + t.notThrows(() => calculator[configure]().divide(4, 2).returns(2)) + calculator[configure]().multiply(2, 2).returns(4) + t.is(mimicked, 0) + t.is(calculator.divide(4, 2), 2) + t.throws(() => calculator.divide(1, 1), { message: 'no' }) + t.notThrows(() => calculator.received(1).add(1, 3)) + t.notThrows(() => calculator.didNotReceive().multiply(Arg.all())) + + // properties, nested members and the symbol substitution methods + calculator.isEnabled.returns(true) + calculator[configure]().isEnabled.returns(false) + t.is(calculator.isEnabled, false) + calculator[configure]().logger.level[returns](5) + t.is(calculator.logger.level, 5) + calculator[configure]().getCalc(1).add(Arg.any(), 1).returns(42) + t.is(calculator.getCalc(1).add(7, 1), 42) + t.throws(() => { calculator[configure]().isEnabled = true }, { instanceOf: SubstituteException }) +}) + +test('D11 the string received/didNotReceive is an assertion only when invoked and followed by a member access', t => { + const substitute = Substitute.for() + substitute.add(1, 2) + t.notThrows(() => substitute.received(1).add(1, 2)) + t.notThrows(() => substitute.received().add(1, 2)) + t.throws(() => substitute.didNotReceive().add(1, 2), { instanceOf: SubstituteException }) + + // a non-invoked received is an ordinary property chain + t.true(types.isProxy(substitute.received.x)) + + // a substitution method right after it configures a user member called received + substitute.received(10).returns('foo') + t.is(substitute.received(10), 'foo') + t.notThrows(() => substitute[received](1).received(10)) + + // the symbol forms are always assertions, whatever the member name + substitute.returns(5) + t.notThrows(() => substitute[received](1).returns(5)) + t.throws(() => substitute[received](1).returns(6), { instanceOf: SubstituteException }) + t.throws(() => substitute[didNotReceive]().returns(5), { instanceOf: SubstituteException }) + + // the assertion did not configure anything: add still records and returns an auto-substitute + t.true(types.isProxy(substitute.add(1, 2))) +}) + +test('D12 sub[mimick](instance) delegates unconfigured members to the instance', t => { + class Real { + public calls = 0 + public name = 'real' + add(a: number, b: number) { this.calls++; return a + b } + whoAmI() { return this } + get upper() { return this.name.toUpperCase() } + } + const instance = new Real() + const substitute = Substitute.for() + ;(substitute as any)[mimick](instance) + + t.is(substitute.add(1, 2), 3) + t.is(substitute.whoAmI(), instance) + t.is(substitute.name, 'real') + t.is(substitute.upper, 'REAL') + ;(substitute as any).name = 'changed' + t.is(instance.name, 'changed') + t.is(substitute.upper, 'CHANGED') + + // explicit substitutions win, and calls are recorded + ;(substitute as any)[configure]().add(5, 5).returns(0) + // a mimicked property read returns the instance value, so it is configured through [configure]() + ;(substitute as any)[configure]().calls.returns(-1) + t.is(substitute.add(5, 5), 0) + t.is(substitute.calls, -1) + t.is(instance.calls, 1) + substitute.received(1).add(1, 2) + substitute.received(1).add(5, 5) + substitute.received(2).upper + ;(substitute as any).received(1).name = 'changed' + + // assertions never run the instance + t.is(instance.calls, 1) + + // the string mimick is an ordinary member + const other = Substitute.for() + other.mimick(instance) + t.true(types.isProxy(other.add(1, 2))) + t.throws(() => (Substitute.for() as any)[mimick](42), { instanceOf: SubstituteException }) +}) + +test('D13 sub[clearReceivedCalls]() clears received calls of a substitute and its auto-substitutes only', t => { + const app = Substitute.for() + app.add(1, 2).returns(3) + app.logger.level.returns(2) + t.is(app.add(1, 2), 3) + app.logger.info('x') + app[clearReceivedCalls]() + t.notThrows(() => app.didNotReceive().add(1, 2)) + t.notThrows(() => app.logger.didNotReceive().info('x')) + t.is(app.add(1, 2), 3) + t.is(app.logger.level, 2) +}) + +test('D14 Arg.all() matches the remaining arguments and must be the last argument', t => { + const logger = Substitute.for() + logger.log('x') + logger.log('x', 1, 2) + logger.log('y', 1) + logger.received(2).log('x', Arg.all()) + logger.received(3).log(Arg.all()) + logger.received(1).log('y', Arg.all()) + logger.received(1).log('y', 1, Arg.all()) + t.throws(() => logger.received().log('z', Arg.all()), { instanceOf: SubstituteException }) + + t.throws(() => logger.received().log(Arg.all(), 'x'), { instanceOf: SubstituteException, message: /must be the last argument/ }) + t.throws(() => logger.log(Arg.all(), 1).returns(1), { instanceOf: SubstituteException, message: /must be the last argument/ }) + + logger.format('a', Arg.all()).returns('A') + t.is(logger.format('a'), 'A') + t.is(logger.format('a', 1, 2, 3), 'A') + t.true(types.isProxy(logger.format('b'))) +}) + +test('D3/D4 precedence: the most specific setup wins, then the most recent one', t => { + const calculator = Substitute.for() + calculator.add(Arg.all()).returns('all') + calculator.add(Arg.any(), Arg.any()).returns('any-any') + calculator.add(1, Arg.any()).returns('one-any') + t.is(calculator.add(1, 2), 'one-any') + t.is(calculator.add(2, 2), 'any-any') + t.is(calculator.add(2), 'all') + calculator[configure]().add(1, 2).returns('literal') + t.is(calculator.add(1, 2), 'literal') + calculator.add(Arg.is((x: number) => x === 1), Arg.any()).returns('newer predicate') + t.is(calculator.add(1, 5), 'newer predicate') + t.is(calculator.add(1, 2), 'literal') + // a call with matchers is never recorded and never runs a substitution + calculator.add(Arg.any(), 2) + t.notThrows(() => calculator.received(6).add(Arg.all())) +}) + +test('D9 a failing property-style assertion is deferred only in the ambiguous case', t => { + const component = Substitute.for() + void component.onChange + void component.onChange + component.onChange() + // 2 reads and 1 call: received(1).onChange() would pass, so the property-style failure is reported later + throwsUncaughtException(() => component.received(1).onChange, t, { instanceOf: SubstituteException }) + // ... and is cancelled when the member is invoked + doesNotThrowLater(() => component.received(1).onChange(), t) + // not ambiguous: thrown synchronously + t.throws(() => component.received(3).onChange, { instanceOf: SubstituteException }) + + // a member that was only invoked: the access is the start of a method assertion + const calculator = Substitute.for() + calculator.add(1, 2) + const error = t.throws(() => calculator.received(2).add(1, 2), { instanceOf: SubstituteException }) + t.regex(plain(error.message), /Expected to receive 2 method calls matching add\(1, 2\), but received 1\./) + doesNotThrowLater(() => calculator.received(1).add(1, 2), t) +}) + +test('D16 Arg.any types', t => { + const substitute = Substitute.for() + t.true(Arg.any('object').matches(substitute)) + t.true(Arg.any('object').matches([1])) + t.false(Arg.any('object').matches(null)) + t.false(Arg.any('object').matches(() => 1)) + t.true(Arg.any('function').matches(substitute)) + t.true(Arg.any('function').matches(class { })) + t.true(Arg.any('array').matches([])) + t.false(Arg.any('array').matches(substitute)) + t.false(Arg.any('array').matches({ length: 0 } as any)) + t.true(Arg.any.not('object').matches(null)) +}) + +test('D17 Arg.is predicates: validated at creation, a throw is a non-match', t => { + t.throws(() => Arg.is(null as any), { instanceOf: TypeError }) + const throwing = Arg.is((x: any) => x.deep.value === 1) + t.false(throwing.matches(undefined)) + t.false(Arg.is.not((x: any) => x.deep.value === 1).matches(undefined)) + t.true(throwing.matches({ deep: { value: 1 } })) +}) + +test('D18 assertion messages', t => { + const substitute = Substitute.for() + substitute.isEnabled = true + void substitute.mode + const setError = t.throws(() => { substitute.received(2).isEnabled = true }, { instanceOf: SubstituteException }) + t.regex(plain(setError.message), /Expected to receive 2 property assignments matching isEnabled = true, but received 1\./) + t.regex(plain(setError.message), /› ✔ @Substitute\.isEnabled = true/) + const readError = t.throws(() => substitute.received(2).mode, { instanceOf: SubstituteException }) + t.regex(plain(readError.message), /Expected to receive 2 property reads matching mode, but received 1\./) + t.false(plain(readError.message).includes('property calls')) + + substitute(1, 2) + t.notThrows(() => substitute[received](1)(1, 2)) + const selfError = t.throws(() => substitute[received](1)(3), { instanceOf: SubstituteException }) + t.regex(plain(selfError.message), /Expected to receive 1 method call matching @Substitute\(3\), but received none\./) + + t.is(inspect(Substitute.for()), '@Substitute {\n}') + t.is(`${substitute.someProperty}`, 'property: ') +}) diff --git a/spec/regression/fixes/duplicate-copies.test.ts b/spec/regression/fixes/duplicate-copies.test.ts new file mode 100644 index 0000000..fe68622 --- /dev/null +++ b/spec/regression/fixes/duplicate-copies.test.ts @@ -0,0 +1,48 @@ +import test from 'ava' +import * as path from 'path' + +import * as copyA from '../../../src' + +// Loads a second, independent copy of the built package, as happens with duplicate installs +// or module registries that are reset between tests. +const loadSecondCopy = (): typeof copyA => { + const entry = require.resolve('../../../src') + const root = path.dirname(entry) + path.sep + const saved = new Map() + for (const key of Object.keys(require.cache)) { + if (key.startsWith(root)) { + saved.set(key, require.cache[key]!) + delete require.cache[key] + } + } + try { + return require(entry) + } finally { + for (const key of Object.keys(require.cache)) if (key.startsWith(root)) delete require.cache[key] + for (const [key, module] of saved) require.cache[key] = module + } +} + +test('G:RG-8 the symbol API and matchers work across two copies of the package', t => { + const copyB = loadSecondCopy() + t.not(copyA.Substitute, copyB.Substitute) + + const substitute = copyA.Substitute.for() + substitute.add(1) + t.throws(() => substitute[copyB.received](2).add(1), { message: /Call count mismatch/ }) + t.notThrows(() => substitute[copyB.received](1).add(1)) + + substitute[copyB.clearReceivedCalls]() + t.notThrows(() => substitute[copyB.didNotReceive]().add(1)) + + substitute.bar()[copyB.returns](5) + t.is(substitute.bar(), 5) + + substitute[copyB.configure]().bar().returns(6) + t.is(substitute.bar(), 6) + + substitute.find(copyB.Arg.any('number')).returns('number') + t.is(substitute.find(1), 'number') + t.notThrows(() => substitute.received(1).find(copyB.Arg.is((x: unknown) => x === 1))) + t.true(copyB.Arg.any('object').matches(substitute)) +}) diff --git a/spec/regression/fixes/performance.test.ts b/spec/regression/fixes/performance.test.ts new file mode 100644 index 0000000..d14d6ed --- /dev/null +++ b/spec/regression/fixes/performance.test.ts @@ -0,0 +1,49 @@ +import test from 'ava' + +import { Substitute, Arg } from '../../../src' + +interface Logger { log(message: string): void, level: number } +interface Calculator { add(a: number, b: number): number } + +const millisecondsOf = (run: () => void) => { + const start = process.hrtime.bigint() + run() + return Number(process.hrtime.bigint() - start) / 1e6 +} + +test('R:RT-8 / D19 calls and configured reads do not scan earlier calls (10k calls + 10k configured reads < 1s)', t => { + const logger = Substitute.for() + logger.level.returns(1) + + const elapsed = millisecondsOf(() => { + for (let i = 0; i < 10_000; i++) logger.log('x') + for (let i = 0; i < 10_000; i++) void logger.level + logger.received(10_000).log('x') + logger.received(10_000).level + }) + t.true(elapsed < 1000, `took ${elapsed} ms`) +}) + +test('R:RT-8 / D19 resolving configured calls with distinct arguments stays fast (10k calls < 1s)', t => { + const calculator = Substitute.for() + calculator.add(Arg.any(), Arg.any()).returns(3) + const elapsed = millisecondsOf(() => { + for (let i = 0; i < 10_000; i++) calculator.add(i, i) + calculator.received(10_000).add(Arg.all()) + }) + t.true(elapsed < 1000, `took ${elapsed} ms`) +}) + +test('R:RT-8 / D19 the cost of a call does not grow with the number of earlier calls', t => { + const timeFor = (count: number) => { + const logger = Substitute.for() + return millisecondsOf(() => { + for (let i = 0; i < count; i++) logger.log('x') + }) + } + timeFor(2_000) // warm up + const small = timeFor(4_000) + const large = timeFor(16_000) + // quadratic growth would make the large run about 16 times slower than the small one + t.true(large < Math.max(small, 5) * 8, `4000 calls: ${small} ms, 16000 calls: ${large} ms`) +}) diff --git a/spec/regression/fixes/regression.test.ts b/spec/regression/fixes/regression.test.ts new file mode 100644 index 0000000..09028be --- /dev/null +++ b/spec/regression/fixes/regression.test.ts @@ -0,0 +1,86 @@ +import test from 'ava' +import { types } from 'util' + +import { Substitute, received, didNotReceive, mimick } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +const substitutionNames = ['returns', 'throws', 'resolves', 'rejects', 'mimicks'] + +test('G:RG-1 symbol assertions on members named returns/throws/resolves/rejects/mimicks are evaluated', t => { + for (const name of substitutionNames) { + const neverRead = Substitute.for() + t.throws(() => neverRead[received](1)[name], { instanceOf: SubstituteException }, `${name}: never read`) + + const readOnce = Substitute.for() + void readOnce[name] + t.throws(() => readOnce[received](2)[name], { instanceOf: SubstituteException }, `${name}: read once, received(2)`) + t.throws(() => readOnce[didNotReceive]()[name], { instanceOf: SubstituteException }, `${name}: read once, didNotReceive()`) + t.notThrows(() => readOnce[received](1)[name], `${name}: read once, received(1)`) + + // invoked members: the assertion checks the arguments instead of configuring the member + const invoked = Substitute.for() + invoked[name](7) + t.throws(() => invoked[received](1)[name](5), { instanceOf: SubstituteException }, `${name}(7) called, received(1).${name}(5)`) + t.throws(() => invoked[didNotReceive]()[name](7), { instanceOf: SubstituteException }, `${name}(7) called, didNotReceive().${name}(7)`) + t.notThrows(() => invoked[received](1)[name](7), `${name}(7) called, received(1).${name}(7)`) + t.notThrows(() => invoked[didNotReceive]()[name](5), `${name}(7) called, didNotReceive().${name}(5)`) + + // an assertion never turns into a substitution: later assertions keep working + const called = Substitute.for() + called.add(1, 2) + t.throws(() => called[received](1)[name](1), { instanceOf: SubstituteException }, `${name}: never called`) + t.notThrows(() => called.received(1).add(1, 2), `${name}: follow-up`) + t.notThrows(() => called[received](1).add(1, 2), `${name}: follow-up (symbol)`) + } +}) + +test('G:RG-2 received(n) with a negative, fractional or NaN count throws', t => { + const expected = 3 + const cases: Array<[string, (substitute: any) => unknown]> = [ + ['received(-1).add()', s => s.received(-1).add()], + ['received(0.5).add()', s => s.received(0.5).add()], + ['received(NaN).add()', s => s.received(NaN).add()], + ['received(expected / 2).add()', s => { s.add(); return s.received(expected / 2).add() }], + ['received(-1).v = 1', s => { s.received(-1).v = 1 }], + ['[received](-1)', s => s[received](-1)] + ] + for (const [label, run] of cases) + t.throws(() => run(Substitute.for()), { instanceOf: SubstituteException }, label) +}) + +test('G:RG-5 received/didNotReceive below the root are ordinary members unless invoked as assertions', t => { + // code under test reading a nested member called received + const inbox = Substitute.for() + t.is(typeof inbox.latest.received.getTime(), 'function') + t.notThrows(() => { inbox.latest.received.total = 3 }) + + // nested assertions check the nested substitute, not root members with the same name + const withChild = Substitute.for() + withChild.child.save() + t.notThrows(() => withChild.child.received().save()) + t.throws(() => withChild.received().save(), { instanceOf: SubstituteException }) + + const repository = Substitute.for() + const user = repository.getUser(1) + user.save() + t.notThrows(() => user.received().save()) + + const rootOnly = Substitute.for() + rootOnly.save() + t.throws(() => rootOnly.child.received().save(), { instanceOf: SubstituteException }) + t.notThrows(() => rootOnly.child.didNotReceive().save()) +}) + +test('G:RG-7 the string mimick is an ordinary member and sub[mimick](instance) is implemented', t => { + const real = { add: (a: number, b: number) => a + b } + const viaString = Substitute.for() + viaString.mimick(real) + t.true(types.isProxy(viaString.add(1, 2))) + t.notThrows(() => viaString.received(1).mimick(real)) + + const viaSymbol = Substitute.for() + viaSymbol[mimick](real) + t.is(viaSymbol.add(1, 2), 3) + t.notThrows(() => viaSymbol.received(1).add(1, 2)) + t.notThrows(() => viaSymbol.didNotReceive().mimick(real)) +}) diff --git a/spec/regression/fixes/runtime.test.ts b/spec/regression/fixes/runtime.test.ts new file mode 100644 index 0000000..8854977 --- /dev/null +++ b/spec/regression/fixes/runtime.test.ts @@ -0,0 +1,260 @@ +import test from 'ava' +import { EventEmitter } from 'events' +import { types } from 'util' + +import { Substitute, Arg, received, didNotReceive, mimick, configure } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') +const configured = (substitute: unknown): any => (substitute as any)[configure]() + +interface Logger { log(message: string): void, level: number } +interface Calculator { add(a: number, b: number): number } + +test('R:RT-1 every call through a stored or destructured method reference is recorded', t => { + const logger = Substitute.for() + const { log } = logger + log('a') + log('b') + logger.received(2).log(Arg.any()) + logger.received(1).log('a') + logger.received(1).log('b') + + const viaCallback = Substitute.for() + ;['x', 'y', 'x'].forEach(viaCallback.log) + // forEach passes (value, index, array) + viaCallback.received(3).log(Arg.all()) + viaCallback.received(2).log('x', Arg.all()) + viaCallback.received(1).log('y', 1, Arg.any()) + t.throws(() => viaCallback.received(1).log('x', Arg.all()), { instanceOf: SubstituteException }) +}) + +test('R:RT-2 asserting a configured property never runs its substitution', async t => { + interface Config { token: string, flaky: string, computed: number, ready: Promise } + const config = Substitute.for() + config.token.returns('t1', 't2', 't3') + config.flaky.throws(new Error('boom')) + let mimickCalls = 0 + config.computed.mimicks(() => ++mimickCalls) + config.ready.rejects(new Error('not ready')) + + t.is('t1', config.token) + config.received(1).token + t.is('t2', config.token) + t.is('t3', config.token) + + t.throws(() => config.flaky, { message: 'boom' }) + t.notThrows(() => config.received(1).flaky) + t.notThrows(() => config.didNotReceive().computed) + + t.is(1, config.computed) + config.received(1).computed + config.received().computed + t.is(mimickCalls, 1) + + // no rejected promise is created by the assertion (an unhandled rejection would fail this test file) + config.didNotReceive().ready + await t.throwsAsync(config.ready, { message: 'not ready' }) + config.received(1).ready + + const neverRead = Substitute.for() + neverRead.flaky.throws(new Error('boom')) + t.notThrows(() => neverRead.didNotReceive().flaky) +}) + +test('R:RT-3 a second setup that overlaps an earlier one does not run the earlier substitution', t => { + interface User { name: string } + interface Repository { find(id: number): User, remove(id: number): void, add(a: number, b: number): number } + const anyUser = Substitute.for() + anyUser.name.returns('any') + const admin = Substitute.for() + admin.name.returns('admin') + + const repository = Substitute.for() + repository.find(Arg.any()).returns(anyUser) + configured(repository).find(1).returns(admin) + t.is(repository.find(1).name, 'admin') + t.is(repository.find(2).name, 'any') + + repository.add(Arg.all()).returns(10) + configured(repository).add(1, 3).returns(1337) + t.is(1337, repository.add(1, 3)) + t.is(10, repository.add(5, 2)) + + repository.remove(Arg.any()).throws(new Error('forbidden')) + t.notThrows(() => configured(repository).remove(1).returns(undefined)) + t.is(repository.remove(1), undefined) + t.throws(() => repository.remove(2), { message: 'forbidden' }) + + // a setup with matchers after a specific one never runs the specific one + const calculator = Substitute.for() + calculator.add(1, 3).returns(1337) + calculator.add(Arg.all()).returns(10) + t.is(1337, calculator.add(1, 3)) + t.is(10, calculator.add(5, 2)) + // the setups were not recorded as calls + calculator.received(2).add(Arg.all()) + calculator.received(1).add(1, 3) +}) + +test('R:RT-4 symbol assertions on members named like substitution methods are real assertions', t => { + const neverCalled = Substitute.for() + t.throws(() => neverCalled[received](1).returns(5), { instanceOf: SubstituteException }) + + const calledWithOtherArgs = Substitute.for() + calledWithOtherArgs.returns(7) + t.throws(() => calledWithOtherArgs[received](1).returns(5), { instanceOf: SubstituteException }) + t.notThrows(() => calledWithOtherArgs[received](1).returns(7)) + + const rejected = Substitute.for() + rejected.rejects(1) + t.throws(() => rejected[didNotReceive]().rejects(1), { instanceOf: SubstituteException }) + + for (const name of ['returns', 'throws', 'resolves', 'rejects', 'mimicks']) { + const thrower = Substitute.for() + t.throws(() => thrower[received](1)[name](1), { instanceOf: SubstituteException }, name) + thrower[name](1) + t.notThrows(() => thrower[received](1)[name](1), name) + } + + const followUp = Substitute.for() + followUp.add(1, 2) + t.throws(() => (followUp as any)[received](1).returns(5), { instanceOf: SubstituteException }) + t.notThrows(() => followUp.received(1).add(1, 2)) +}) + +test('R:RT-5 code under test can read through a nested member named received or didNotReceive', t => { + const mailbox = Substitute.for() + t.notThrows(() => mailbox.getStats().sent.total) + t.notThrows(() => mailbox.getStats().received.total) + t.notThrows(() => { mailbox.getStats().received.total = 3 }) + t.notThrows(() => mailbox.inbox.didNotReceive.count) + + const email = Substitute.for() + t.is(typeof email.latest.received.getTime(), 'function') + t.is(typeof email.received.getTime(), 'function') + email.received.getTime().returns(42) + t.is(email.received.getTime(), 42) +}) + +test('R:RT-6 received(n) with an invalid count throws a SubstituteException', t => { + for (const count of [-1, 1.5, NaN, Infinity, -Infinity, 2 ** 53]) { + const calculator = Substitute.for() + t.throws(() => calculator.received(count).add(1, 2), { instanceOf: SubstituteException }, String(count)) + t.throws(() => (calculator as any)[received](count), { instanceOf: SubstituteException }, String(count)) + } + const calculator = Substitute.for() + t.notThrows(() => calculator.received(0).add(1, 2)) + t.notThrows(() => (calculator as any)[received](0).add(1, 2)) +}) + +test('R:RT-7 a root setup does not leak into a nested auto-substitute with the same member name', t => { + interface App { getCalc(): Calculator, add(a: number, b: number): number, version: string, meta: { version: string } } + const app = Substitute.for() + app.add(1, 2).returns(99) + app.version.returns('1.0') + + t.true(types.isProxy(app.getCalc().add(1, 2))) + t.true(types.isProxy(app.meta.version)) + t.is(99, app.add(1, 2)) + t.is('1.0', app.version) + + // and the other way round + const nested = Substitute.for() + nested.getCalc().add(1, 2).returns(42) + t.true(types.isProxy(nested.add(1, 2))) + t.is(nested.getCalc().add(1, 2), 42) +}) + +test('R:RT-9 sub[mimick](instance) delegates to the instance', t => { + class RealCalculator { + base = 10 + add(a: number, b: number) { return a + b + this.base } + } + const instance = new RealCalculator() + const calculator = Substitute.for() + ;(calculator as any)[mimick](instance) + t.is(calculator.add(1, 2), 13) + t.is(calculator.base, 10) + calculator.received(1).add(1, 2) +}) + +test('R:RT-10 reading a method without invoking it does not count as a call', t => { + interface Handler { onClick(x: number): void } + const handler = Substitute.for() + const button = new EventEmitter() + button.on('click', handler.onClick) + + t.throws(() => handler.received().onClick(Arg.any()), { instanceOf: SubstituteException }) + t.throws(() => handler.received(1).onClick(42), { instanceOf: SubstituteException }) + t.throws(() => (handler as any).received(1).onClick(), { instanceOf: SubstituteException }) + + const twice = Substitute.for() + void twice.save + void twice.save + t.throws(() => twice.received(2).save(1), { instanceOf: SubstituteException }) + + button.emit('click', 7) + t.notThrows(() => handler.received(1).onClick(7)) +}) + +test('R:RT-11 calls through .call, .apply and .bind return the configured value and are recorded', t => { + const calculator = Substitute.for() + calculator.add(1, 2).returns(3) + + t.is(calculator.add(1, 2), 3) + t.is(calculator.add.call(calculator, 1, 2), 3) + t.is(calculator.add.apply(calculator, [1, 2]), 3) + t.is(calculator.add.bind(calculator)(1, 2), 3) + t.is(calculator.add.bind(calculator, 1)(2), 3) + calculator.received(5).add(1, 2) + t.throws(() => calculator.received(1).add(7, 7), { instanceOf: SubstituteException }) + + const listener = Substitute.for<{ onX(value: number): string }>() + listener.onX(1).returns('one') + const emitter = new EventEmitter() + emitter.on('x', listener.onX) + emitter.on('x', listener.onX) + emitter.emit('x', 1) + listener.received(2).onX(1) + t.throws(() => listener.received(1).onX(999), { instanceOf: SubstituteException }) + t.notThrows(() => listener.didNotReceive().onX(999)) +}) + +test('R:RT-12 a failed assertion with Error.stackTraceLimit = 0 throws a SubstituteException', t => { + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + const calculator = Substitute.for() + calculator.add(1, 2) + const error = t.throws(() => calculator.received(2).add(1, 2), { instanceOf: SubstituteException }) + t.true(plain(error.message).startsWith('Call count mismatch in @Substitute.add:')) + t.false(plain(error.message).includes('called at')) + } finally { + Error.stackTraceLimit = stackTraceLimit + } +}) + +test('R:RT-13 (D1) a sequence keeps returning its last value', async t => { + const calculator = Substitute.for() + calculator.add(1, 2).returns(3, 7, 9) + t.deepEqual([1, 2, 3, 4].map(() => calculator.add(1, 2)), [3, 7, 9, 9]) + + const single = Substitute.for() + single.add(1, 2).returns(4) + t.deepEqual([single.add(1, 2), single.add(1, 2)], [4, 4]) + + const thrower = Substitute.for() + thrower.add(Arg.all()).throws(new Error('a'), new Error('b')) + t.throws(() => thrower.add(1, 1), { message: 'a' }) + t.throws(() => thrower.add(1, 1), { message: 'b' }) + t.throws(() => thrower.add(1, 1), { message: 'b' }) + + const resolver = Substitute.for<{ load(): Promise }>() + resolver.load().resolves(1, 2) + t.deepEqual([await resolver.load(), await resolver.load(), await resolver.load()], [1, 2, 2]) + + const mimicker = Substitute.for() + mimicker.add(Arg.all()).mimicks((a: number, b: number) => a + b, (a: number, b: number) => a * b) + t.deepEqual([mimicker.add(2, 3), mimicker.add(2, 3), mimicker.add(2, 3)], [5, 6, 6]) +}) diff --git a/src/internals/CallRecord.ts b/src/internals/CallRecord.ts index 465ad71..f52d6fd 100644 --- a/src/internals/CallRecord.ts +++ b/src/internals/CallRecord.ts @@ -11,10 +11,21 @@ const nextSequence = (): number => ++sequence type StackHolder = { stack?: string } +// Only the call site (the first frame) is ever shown, so only one frame is collected: collecting the +// whole stack for every call would dominate the cost of a call, especially with a raised stackTraceLimit. const captureStack = (stackStart: Function): StackHolder => { const holder: StackHolder = {} - if (typeof Error.captureStackTrace === 'function') Error.captureStackTrace(holder, stackStart) - else holder.stack = new Error().stack + if (typeof Error.captureStackTrace !== 'function') { + holder.stack = new Error().stack + return holder + } + const stackTraceLimit = Error.stackTraceLimit + if (!(stackTraceLimit >= 0 && stackTraceLimit <= 1)) Error.stackTraceLimit = 1 + try { + Error.captureStackTrace(holder, stackStart) + } finally { + Error.stackTraceLimit = stackTraceLimit + } return holder } diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 3379fb6..28309dd 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -32,7 +32,18 @@ type Face = const TAKE_PENDING_READ = Symbol('take pending read') type ReadSource = typeof TAKE_PENDING_READ | CallRecord | undefined -const newTarget = (): any => function () { } +/** + * The target of every proxy. util.inspect inspects the target of a proxy (it does not trigger traps), + * so the target carries the printer as its inspect.custom hook. + */ +const newTarget = (print: Printer): any => { + const target = function () { } + Object.defineProperty(target, inspect.custom, { + value: (_depth: number, options?: InspectOptions) => print(options), + configurable: true + }) + return target +} // ---- printing --------------------------------------------------------------------------------- @@ -105,7 +116,7 @@ const entryProxy = (entry: AutoEntry): any => { const faceState = (face: Face): SubstituteState => face.kind === 'root' ? face.state : face.entry.state const faceChainHead = (face: Face): CallRecord | undefined => face.kind === 'root' ? undefined : face.entry.chainHead() -const createFaceProxy = (face: Face): any => new Proxy(newTarget(), { +const createFaceProxy = (face: Face): any => new Proxy(newTarget(options => printFace(face, colorsOf(options))), { get: function get(_target: unknown, property: PropertyKey) { return faceGet(face, property, get) }, @@ -363,7 +374,7 @@ const deferredRead = (state: SubstituteState, key: PropertyKey, record: CallReco return value } const print: Printer = () => `property<${memberLabel(key)}>: ` - return new Proxy(newTarget(), { + return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) const method = substitutionMethodOf(property) @@ -392,7 +403,7 @@ const describeCount = (count: ExpectedCount) => count === undefined ? 'received( const createAssertionProxy = (state: SubstituteState, count: ExpectedCount): any => { const print: Printer = () => `${state.path}.${describeCount(count)}` - return new Proxy(newTarget(), { + return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) return assertionMember(state, property, count, get) @@ -429,7 +440,7 @@ const assertionMember = (state: SubstituteState, key: PropertyKey, count: Expect ) } const print: Printer = () => `${state.path}.${describeCount(count)}.${memberLabel(key)}` - return new Proxy(newTarget(), { + return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) if (isFunctionHelperKey(property)) return functionHelper(property, assertInvocation) @@ -453,7 +464,7 @@ const configureSetError = (start: Function) => SubstituteException.generic( const createConfigureProxy = (state: SubstituteState): any => { const print: Printer = () => `${state.path}[configure]()` - return new Proxy(newTarget(), { + return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) return configureMember(state, property) @@ -471,7 +482,7 @@ const configureMember = (state: SubstituteState, key: PropertyKey): any => { const context = contextMethodOf(key) if (context !== undefined) return contextFunction(context, () => state, undefined) const print: Printer = () => `${state.memberPath(key)} (configure)` - return new Proxy(newTarget(), { + return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) const method = substitutionMethodOf(property) @@ -503,7 +514,7 @@ const nestedEntry = (state: SubstituteState, key: PropertyKey, specification: Re /** A call in a setup: `.returns(...)` configures it, anything else configures the auto-substitute it returns. */ const configureCall = (state: SubstituteState, key: PropertyKey, specification: RecordedArguments): any => { const print: Printer = options => withPrintGuard(() => `method<${memberLabel(key)}>: ${formatArguments(specification.value, colorsOf(options))} (configure)`) - return new Proxy(newTarget(), { + return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) const method = substitutionMethodOf(property) From a01cf3bf0bd751e1c08a391d1a2c67d8e131538c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:57:19 +0000 Subject: [PATCH 004/106] fix(mimick): members the instance lacks read as undefined (D12) After sub[mimick](instance), reading a member that the instance does not have now returns undefined, as on the instance itself. The substitute keeps an auto-substitute only where it needs one: the string received/didNotReceive forms, members with configured calls, and members configured through nested setups. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/decisions.test.ts | 12 ++++++++++++ src/internals/Engine.ts | 10 +++++++--- src/internals/SubstituteState.ts | 5 +++++ 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/spec/regression/fixes/decisions.test.ts b/spec/regression/fixes/decisions.test.ts index e066b05..9b824a3 100644 --- a/spec/regression/fixes/decisions.test.ts +++ b/spec/regression/fixes/decisions.test.ts @@ -164,6 +164,18 @@ test('D12 sub[mimick](instance) delegates unconfigured members to the instance', // assertions never run the instance t.is(instance.calls, 1) + // a member the instance does not have reads as undefined, like on the instance itself, + // unless the substitute configures it + const loose = substitute as any + t.is(loose.missing, undefined) + t.throws(() => loose.missingMethod(), { instanceOf: TypeError }) + loose[configure]().extra(1).returns(5) + t.is(loose.extra(1), 5) + loose[configure]().nested.value.returns('n') + t.is(loose.nested.value, 'n') + loose.received(1).extra(1) + loose.received(1).missing + // the string mimick is an ordinary member const other = Substitute.for() other.mimick(instance) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 28309dd..a0de4cb 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -230,9 +230,13 @@ const realGet = (state: SubstituteState, key: PropertyKey, chainPrevious: CallRe } const mimicked = state.mimicked - if (mimicked !== undefined && hasMember(mimicked.instance, key)) { - const value = mimicked.instance[key] - if (typeof value !== 'function') { + if (mimicked !== undefined) { + // A member the instance does not have reads as undefined, like on the instance, unless the + // substitute itself needs it: the string assertion forms, configured calls and nested setups. + const delegate = hasMember(mimicked.instance, key) || + !(isStringAssertionKey(key) || state.hasCallSubstitutions(key) || state.hasConfiguredPropertyEntry(key)) + const value = delegate ? mimicked.instance[key] : undefined + if (delegate && typeof value !== 'function') { state.addRecord('get', key, undefined, stackStart, chainPrevious) return value } diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index 4dee4b8..7c7d15f 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -235,6 +235,11 @@ export class SubstituteState { return entry } + /** True when the auto-substitute behind a member has its own configuration or records. */ + public hasConfiguredPropertyEntry(key: PropertyKey): boolean { + return this._propertyEntries.get(key)?.materializedState !== undefined + } + /** The auto-substitute for a call with these actual (literal) arguments. */ public callEntry(key: PropertyKey, actualArguments: any[]): AutoEntry { let index = this._callEntries.get(key) From fffad01b3e75a9ae9f46e94ab462268f9ccf9ade Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 09:58:58 +0000 Subject: [PATCH 005/106] test: pin the D9 deferral boundaries Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/decisions.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/spec/regression/fixes/decisions.test.ts b/spec/regression/fixes/decisions.test.ts index 9b824a3..e398005 100644 --- a/spec/regression/fixes/decisions.test.ts +++ b/spec/regression/fixes/decisions.test.ts @@ -252,6 +252,14 @@ test('D9 a failing property-style assertion is deferred only in the ambiguous ca const error = t.throws(() => calculator.received(2).add(1, 2), { instanceOf: SubstituteException }) t.regex(plain(error.message), /Expected to receive 2 method calls matching add\(1, 2\), but received 1\./) doesNotThrowLater(() => calculator.received(1).add(1, 2), t) + // ... so a property-style assertion on it that is never invoked is reported later + throwsUncaughtException(() => calculator.received(2).add, t, { instanceOf: SubstituteException }) + + // a member that was never invoked is a property: decided now + const handler = Substitute.for() + void handler.onClick + t.throws(() => handler.didNotReceive().onClick, { instanceOf: SubstituteException }) + t.throws(() => handler.received(2).onClick, { instanceOf: SubstituteException }) }) test('D16 Arg.any types', t => { From a55c82bd93aab51d2f132851655db1322e753e92 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:39:32 +0000 Subject: [PATCH 006/106] fix(packaging): ESM entry point, exports map, prepack build, separate spec output - Add an "exports" map with a generated native ES module entry (dist/index.mjs + dist/index.d.mts, written by packaging/build-esm.js), so `import Substitute from '@fluffy-spoon/substitute'` is the Substitute class under native ESM and TypeScript node16/nodenext/bundler. CommonJS, "main"/"types", package.json and deep imports of dist/ files keep working. - Build before packing (prepack), so npm pack / npm publish always ship a fresh dist/ (G:PK-3). - Compile the specs into dist-spec/ (npm run build:spec), so npm test never leaves dist/ in an unpublishable state (G:PK-3). - Sync package-lock.json to 2.0.1 (G:PK-4). - engines.node stays >=10: the packed build was smoke-tested on Node 10.0.0 to 26 (CommonJS) and 12.17.0+ (ESM); Node 8 lacks util.isDeepStrictEqual (G:PK-2). - publishConfig pins the npm registry; packaging/dist-tag.js computes the npm dist-tag for a release; better keywords; volta pin moves to Node 24. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .gitignore | 1 + ava.config.js | 7 +-- package-lock.json | 4 +- package.json | 47 +++++++++++++++---- packaging/build-esm.js | 56 +++++++++++++++++++++++ packaging/dist-tag.js | 32 +++++++++++++ packaging/helpers.js | 78 ++++++++++++++++++++++++++++++++ packaging/smoke/deep-imports.js | 15 ++++++ packaging/smoke/deep-imports.mjs | 11 +++++ packaging/smoke/import.mjs | 35 ++++++++++++++ packaging/smoke/require.js | 37 +++++++++++++++ 11 files changed, 310 insertions(+), 13 deletions(-) create mode 100644 packaging/build-esm.js create mode 100644 packaging/dist-tag.js create mode 100644 packaging/helpers.js create mode 100644 packaging/smoke/deep-imports.js create mode 100644 packaging/smoke/deep-imports.mjs create mode 100644 packaging/smoke/import.mjs create mode 100644 packaging/smoke/require.js diff --git a/.gitignore b/.gitignore index ee295b7..ebfef98 100644 --- a/.gitignore +++ b/.gitignore @@ -331,5 +331,6 @@ ASALocalRun/ # Build dist/ +dist-spec/ fluffy-spoon-substitute-*.tgz package/ diff --git a/ava.config.js b/ava.config.js index 2633e0a..c061cf5 100644 --- a/ava.config.js +++ b/ava.config.js @@ -1,10 +1,11 @@ - module.exports = { - files: ['spec/**/*.spec.ts', 'spec/**/*.test.ts'], + files: ['spec/**/*.spec.ts', 'spec/**/*.test.ts', 'packaging/**/*.test.js'], typescript: { compile: false, + // `npm run build:spec` compiles the specs (and the sources they import) into dist-spec/, + // so running the tests never touches the publishable dist/ directory. rewritePaths: { - '/': 'dist/' + '/': 'dist-spec/' } }, cache: false, diff --git a/package-lock.json b/package-lock.json index 2efcbf7..f62046e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@fluffy-spoon/substitute", - "version": "2.0.0-beta.4", + "version": "2.0.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@fluffy-spoon/substitute", - "version": "2.0.0-beta.4", + "version": "2.0.1", "license": "MIT", "devDependencies": { "@ava/typescript": "^3.0.1", diff --git a/package.json b/package.json index f03b6ba..2f93e9d 100644 --- a/package.json +++ b/package.json @@ -19,14 +19,22 @@ ], "repository": { "type": "git", - "url": "https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking.git" + "url": "git+https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking.git" }, + "homepage": "https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking#readme", "keywords": [ - "NSubstitute", + "typescript", + "mock", "mocking", + "stub", + "fake", + "faking", + "substitute", + "nsubstitute", "test", "testing", - "faking" + "unit-testing", + "tdd" ], "bugs": { "url": "https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/issues" @@ -34,14 +42,37 @@ "engines": { "node": ">=10" }, - "main": "dist/index.js", - "typings": "./dist/index.d.ts", + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "default": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "./package.json": "./package.json", + "./dist/*.js": "./dist/*.js", + "./dist/*.mjs": "./dist/*.mjs", + "./dist/*": "./dist/*.js" + }, "files": [ "dist/**/*" ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, "scripts": { - "build": "rm -rf dist && tsc", - "test": "npm run build -- -p spec && ava" + "build": "rm -rf dist && tsc && node packaging/build-esm.js", + "build:spec": "rm -rf dist-spec && tsc -p spec --outDir dist-spec", + "prepack": "npm run build", + "test": "npm run build:spec && ava", + "test:compat": "npm --prefix compatibility-checks test" }, "devDependencies": { "@ava/typescript": "^3.0.1", @@ -52,6 +83,6 @@ "typescript": "^5.9.2" }, "volta": { - "node": "18.19.1" + "node": "24.22.3" } } diff --git a/packaging/build-esm.js b/packaging/build-esm.js new file mode 100644 index 0000000..ebbba63 --- /dev/null +++ b/packaging/build-esm.js @@ -0,0 +1,56 @@ +'use strict' +// Generates the native ES module entry point next to the CommonJS build: +// dist/index.mjs - re-exports every export of dist/index.js, plus the default export +// dist/index.d.mts - the matching typings for TypeScript's node16/nodenext/bundler resolution +// +// The ES module entry wraps the CommonJS build instead of being a second copy of the library, so +// CommonJS and ES module consumers share one module instance. The named exports are read from the +// CommonJS build at build time, so the wrapper never needs to be kept in sync by hand. Explicit +// `export const` bindings (instead of `export * from './index.js'`) also work on Node versions that +// cannot detect the named exports of a CommonJS module. +// +// Runs as part of `npm run build`, after tsc. + +const fs = require('fs') +const path = require('path') + +const dist = path.resolve(__dirname, '..', 'dist') +const entry = path.join(dist, 'index.js') +const cjs = require(entry) + +if (!Object.prototype.hasOwnProperty.call(cjs, 'default')) { + throw new Error(`${entry} has no default export`) +} + +const identifier = /^[A-Za-z_$][\w$]*$/ +const names = Object.keys(cjs).filter(name => name !== 'default').sort() +for (const name of names) { + if (!identifier.test(name)) throw new Error(`Cannot re-export ${JSON.stringify(name)} from an ES module`) +} + +// The typings re-export the default export under the name it has in index.d.ts (`export default Substitute`), +// so that `import Substitute from '@fluffy-spoon/substitute'` is the Substitute class for TypeScript, too. +const defaultName = names.find(name => cjs[name] === cjs.default) +if (defaultName === undefined) { + throw new Error(`The default export of ${entry} is not also a named export; cannot type it in index.d.mts`) +} + +const header = '// Generated by packaging/build-esm.js during `npm run build`. Do not edit.' + +const mjs = [ + header, + "import cjs from './index.js';", + ...names.map(name => `export const ${name} = cjs.${name};`), + 'export default cjs.default;', + '' +].join('\n') + +const dmts = [ + header, + "export * from './index.js';", + `export { ${defaultName} as default } from './index.js';`, + '' +].join('\n') + +fs.writeFileSync(path.join(dist, 'index.mjs'), mjs) +fs.writeFileSync(path.join(dist, 'index.d.mts'), dmts) diff --git a/packaging/dist-tag.js b/packaging/dist-tag.js new file mode 100644 index 0000000..9ba4ca5 --- /dev/null +++ b/packaging/dist-tag.js @@ -0,0 +1,32 @@ +'use strict' +// Prints the npm dist-tag for a release, and fails when the release tag does not match the package version. +// +// node packaging/dist-tag.js +// +// - A stable version (2.0.1) published from a normal release is tagged `latest`. +// - A semver prerelease version (2.1.0-beta.1, 3.0.0-rc.1) or a GitHub release marked as prerelease is tagged `beta`, +// so `npm install @fluffy-spoon/substitute` never picks it up by accident. +// Used by .github/workflows/npm-publish.yml. + +const [tag, version, prerelease] = process.argv.slice(2) + +const fail = message => { + console.error(message) + process.exit(1) +} + +if (!tag || !version || !['true', 'false'].includes(prerelease)) { + fail('usage: node packaging/dist-tag.js ') +} + +const semver = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/ +const parsed = semver.exec(version) +if (parsed === null) fail(`package.json version ${version} is not a valid semver version`) + +const tagVersion = tag.replace(/^v/, '') +if (tagVersion !== version) { + fail(`The release tag ${tag} does not match the package.json version ${version}. Bump the version (npm version ) or fix the tag.`) +} + +const isPrerelease = prerelease === 'true' || parsed[1] !== undefined +console.log(isPrerelease ? 'beta' : 'latest') diff --git a/packaging/helpers.js b/packaging/helpers.js new file mode 100644 index 0000000..cb5aee2 --- /dev/null +++ b/packaging/helpers.js @@ -0,0 +1,78 @@ +'use strict' +const { execFileSync } = require('child_process') +const fs = require('fs') +const os = require('os') +const path = require('path') + +const root = path.resolve(__dirname, '..') +const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm' + +const temporaryDirectories = [] +/** Creates a temporary directory that removeTemporaryDirectories() deletes again. */ +const makeTemporaryDirectory = prefix => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), `substitute-${prefix}-`)) + temporaryDirectories.push(directory) + return directory +} +const removeTemporaryDirectories = () => { + for (const directory of temporaryDirectories.splice(0)) fs.rmSync(directory, { recursive: true, force: true }) +} + +const readText = file => fs.readFileSync(path.join(root, file), 'utf8') +const readJson = file => JSON.parse(readText(file)) + +/** The environment for child processes, without what would make them behave like a child of a test runner. */ +const childEnvironment = () => { + const environment = { ...process.env } + for (const name of Object.keys(environment)) { + if (name.startsWith('NODE_TEST_') || name.startsWith('AVA_')) delete environment[name] + } + return environment +} + +/** + * Packs the repository exactly like `npm publish` does (lifecycle scripts included) and returns the + * tarball path and the list of files in it. + */ +const pack = destination => { + const output = execFileSync(npm, ['pack', '--json', '--silent', '--pack-destination', destination], { + cwd: root, + encoding: 'utf8', + env: childEnvironment(), + shell: process.platform === 'win32' + }) + const [result] = JSON.parse(output.slice(output.indexOf('['))) + return { + tarball: path.join(destination, result.filename), + files: result.files.map(file => file.path).sort() + } +} + +/** Creates an empty consumer project with the tarball extracted as node_modules/@fluffy-spoon/substitute. */ +const createConsumer = tarball => { + const consumer = makeTemporaryDirectory('consumer') + const target = path.join(consumer, 'node_modules', '@fluffy-spoon', 'substitute') + fs.mkdirSync(target, { recursive: true }) + execFileSync('tar', ['-xzf', tarball, '-C', target, '--strip-components=1']) + fs.writeFileSync(path.join(consumer, 'package.json'), JSON.stringify({ name: 'consumer', private: true })) + return consumer +} + +const runNode = (cwd, args) => execFileSync(process.execPath, args, { + cwd, + encoding: 'utf8', + env: childEnvironment(), + stdio: 'pipe' +}) + +module.exports = { + root, + readText, + readJson, + pack, + createConsumer, + runNode, + childEnvironment, + makeTemporaryDirectory, + removeTemporaryDirectories +} diff --git a/packaging/smoke/deep-imports.js b/packaging/smoke/deep-imports.js new file mode 100644 index 0000000..3cc5920 --- /dev/null +++ b/packaging/smoke/deep-imports.js @@ -0,0 +1,15 @@ +'use strict' +// Deep imports of compiled files under dist/ are not public API, but the "exports" map keeps them working +// (Node versions with subpath pattern trailer support, i.e. 14.19+ and 16.10+, and versions without "exports" support). +// Run from a directory whose node_modules contains the extracted package tarball: +// node deep-imports.js +var assert = require('assert') + +var Arg = require('@fluffy-spoon/substitute').Arg + +assert.strictEqual(require('@fluffy-spoon/substitute/dist/api/Arg').Arg, Arg, 'deep import without extension') +assert.strictEqual(require('@fluffy-spoon/substitute/dist/api/Arg.js').Arg, Arg, 'deep import with extension') +assert.strictEqual(require('@fluffy-spoon/substitute/dist/index').Arg, Arg, 'deep import of the index') +assert.strictEqual(require('@fluffy-spoon/substitute/package.json').name, '@fluffy-spoon/substitute', 'package.json') + +console.log('deep import smoke test passed on Node ' + process.version) diff --git a/packaging/smoke/deep-imports.mjs b/packaging/smoke/deep-imports.mjs new file mode 100644 index 0000000..3c2dea6 --- /dev/null +++ b/packaging/smoke/deep-imports.mjs @@ -0,0 +1,11 @@ +// ES module counterpart of deep-imports.js. +// node deep-imports.mjs +import assert from 'assert' +import { Arg } from '@fluffy-spoon/substitute' +import argModule from '@fluffy-spoon/substitute/dist/api/Arg.js' +import esmEntry from '@fluffy-spoon/substitute/dist/index.mjs' + +assert.strictEqual(argModule.Arg, Arg, 'deep import of a compiled CommonJS file') +assert.strictEqual(typeof esmEntry.for, 'function', 'deep import of the ES module entry') + +console.log('ESM deep import smoke test passed on Node ' + process.version) diff --git a/packaging/smoke/import.mjs b/packaging/smoke/import.mjs new file mode 100644 index 0000000..306b612 --- /dev/null +++ b/packaging/smoke/import.mjs @@ -0,0 +1,35 @@ +// Smoke test of the packed package through native ES module `import`. +// Run from a directory whose node_modules contains the extracted package tarball: +// node import.mjs +import assert from 'assert' +import { createRequire } from 'module' + +import Substitute, { Substitute as NamedSubstitute, Arg, received, returns } from '@fluffy-spoon/substitute' +import * as namespace from '@fluffy-spoon/substitute' + +const require = createRequire(import.meta.url) +const cjs = require('@fluffy-spoon/substitute') + +// The default import is the Substitute class, as it is for CommonJS and TypeScript consumers. +assert.strictEqual(typeof Substitute.for, 'function', 'default import: Substitute.for is a function') +assert.strictEqual(Substitute, NamedSubstitute, 'the default import is the named Substitute export') +assert.strictEqual(namespace.default, Substitute, 'namespace.default is Substitute') + +// The ES module entry wraps the CommonJS build, so both module systems share one instance. +assert.strictEqual(Substitute, cjs.Substitute, 'ESM and CommonJS share the same Substitute') +assert.strictEqual(Arg, cjs.Arg, 'ESM and CommonJS share the same Arg') + +// Every named export of the CommonJS build is available as a named ESM export. +const cjsNames = Object.keys(cjs).sort() +const esmNames = Object.keys(namespace).sort() +assert.deepStrictEqual(esmNames, cjsNames, 'the ESM entry exports the same names as the CommonJS entry') + +const calculator = Substitute.for() +calculator.add(1, 2).returns(3) +calculator.subtract(Arg.any(), 1)[returns](7) +assert.strictEqual(calculator.add(1, 2), 3, 'returns() configures the return value') +assert.strictEqual(calculator.subtract(5, 1), 7, 'the returns symbol configures the return value') +calculator[received](1).add(1, 2) +assert.throws(() => calculator.received(2).add(1, 2), error => error.name === 'SubstituteException') + +console.log('import smoke test passed on Node ' + process.version) diff --git a/packaging/smoke/require.js b/packaging/smoke/require.js new file mode 100644 index 0000000..97eacd5 --- /dev/null +++ b/packaging/smoke/require.js @@ -0,0 +1,37 @@ +'use strict' +// Smoke test of the packed package through CommonJS `require`. +// Run from a directory whose node_modules contains the extracted package tarball: +// node require.js +// Kept to syntax and APIs that the oldest supported Node version understands (see engines in package.json). + +var assert = require('assert') + +var lib = require('@fluffy-spoon/substitute') +var Substitute = lib.Substitute +var Arg = lib.Arg + +assert.strictEqual(typeof Substitute.for, 'function', 'Substitute.for is a function') +assert.strictEqual(lib.default, Substitute, 'the default export is Substitute') +assert.strictEqual(typeof lib.received, 'symbol', 'the received symbol is exported') + +var calculator = Substitute.for() +calculator.add(1, 2).returns(3) +calculator.multiply(Arg.any(), Arg.is(function (x) { return x > 5 })).returns(42) + +assert.strictEqual(calculator.add(1, 2), 3, 'returns() configures the return value') +assert.strictEqual(calculator.multiply(0, 9), 42, 'Arg matchers match') + +calculator.received(1).add(1, 2) +calculator.received(1).multiply(Arg.any(), Arg.any('number')) +calculator.didNotReceive().subtract(Arg.all()) + +var failure +try { + calculator.received(2).add(1, 2) +} catch (error) { + failure = error +} +assert.ok(failure instanceof Error, 'a failing assertion throws') +assert.strictEqual(failure.name, 'SubstituteException', 'a failing assertion throws a SubstituteException') + +console.log('require smoke test passed on Node ' + process.version) From feb0708270fcaca6ed9afe26d7f06490bf896bb9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:39:50 +0000 Subject: [PATCH 007/106] fix(compatibility-checks): run against the packed build, fix the node:test check - The pretest script (npm run install:local) packs the repository root like npm publish does and installs the tarball with --no-save; the runners import '@fluffy-spoon/substitute' instead of ../../../src (G:CI-2). - Strip NODE_TEST_* from the environment of the nested runners. A nested `node --test` inherited NODE_TEST_CONTEXT and exited 0 although its test failed, so the node:test check failed on Node 20.11+ (G:CI-2). - Accept the runners' reports for a synchronous failure as well as for an assertion thrown on process.nextTick, and match the exception name and message separately (ava and node:test print them apart). - Update the runners (ava 6.4, jest 30, mocha 12, vitest 5, tsx, ts-jest, TypeScript 5.9) so the checks run on Node 22, 24 and 26; mocha 10 failed to start on Node 26. This also removes the critical/high audit findings. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- compatibility-checks/package-lock.json | 7274 +++++++++-------- compatibility-checks/package.json | 31 +- .../scripts/install-local-build.js | 39 + .../test-runners/_common/index.ts | 2 +- compatibility-checks/test/environment.d.ts | 2 + compatibility-checks/test/environment.js | 22 + compatibility-checks/test/index.ts | 32 +- 7 files changed, 4085 insertions(+), 3317 deletions(-) create mode 100644 compatibility-checks/scripts/install-local-build.js create mode 100644 compatibility-checks/test/environment.d.ts create mode 100644 compatibility-checks/test/environment.js diff --git a/compatibility-checks/package-lock.json b/compatibility-checks/package-lock.json index c7a0171..3fdb331 100644 --- a/compatibility-checks/package-lock.json +++ b/compatibility-checks/package-lock.json @@ -9,38 +9,25 @@ "version": "0.0.0", "license": "MIT", "devDependencies": { - "@types/mocha": "^10.0.6", - "@types/node": "^20.11.25", + "@types/mocha": "^10.0.10", + "@types/node": "^22.20.5", "ansi-regex": "^6.0.1", - "ava": "^6.1.2", - "jest": "^29.7.0", - "mocha": "^10.3.0", - "ts-jest": "^29.1.2", - "tsx": "^4.7.1", - "typescript": "^5.4.2", - "vitest": "^1.3.1" + "ava": "^6.4.1", + "jest": "^30.5.2", + "mocha": "^12.0.3", + "ts-jest": "^29.4.15", + "tsx": "^4.23.15", + "typescript": "^5.9.3", + "vitest": "^5.1.0" }, "engines": { - "node": ">=20" + "node": ">=22.12" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/substitute-js#section-contribute" } }, - "node_modules/@ampproject/remapping": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@ampproject/remapping/-/remapping-2.3.0.tgz", - "integrity": "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==", - "dev": true, - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@ava/typescript": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/@ava/typescript/-/typescript-3.0.1.tgz", @@ -57,114 +44,47 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", - "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/highlight": "^7.23.4", - "chalk": "^2.4.2" + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" }, "engines": { "node": ">=6.9.0" } }, - "node_modules/@babel/code-frame/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/code-frame/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/code-frame/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/code-frame/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/@babel/compat-data": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz", - "integrity": "sha512-uU27kfDRlhfKl+w1U6vp16IuvSLtjAxdArVXPa9BvLkrr7CYIsxH5adpHObeAGY/41+syctUWOZ140a2Rvkgjw==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/core": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.24.0.tgz", - "integrity": "sha512-fQfkg0Gjkza3nf0c7/w6Xf34BW4YvzNfACRLmmb7XRLa6XHdR+K9AlJlxneFfWYf6uhOzuzZVTjF/8KfndZANw==", - "dev": true, - "dependencies": { - "@ampproject/remapping": "^2.2.0", - "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.6", - "@babel/helper-compilation-targets": "^7.23.6", - "@babel/helper-module-transforms": "^7.23.3", - "@babel/helpers": "^7.24.0", - "@babel/parser": "^7.24.0", - "@babel/template": "^7.24.0", - "@babel/traverse": "^7.24.0", - "@babel/types": "^7.24.0", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", @@ -189,29 +109,32 @@ } }, "node_modules/@babel/generator": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", - "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.14.tgz", + "integrity": "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/types": "^7.23.6", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", - "jsesc": "^2.5.1" + "@babel/parser": "^7.29.14", + "@babel/types": "^7.29.14", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-compilation-targets": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.23.6.tgz", - "integrity": "sha512-9JB548GZoQVmzrFgp8o7KxdgkTGm6xs9DW0o/Pim72UDjzr5ObUQ6ZzYPqA+g9OTS2bBQoctLJrky0RDCAWRgQ==", + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/compat-data": "^7.23.5", - "@babel/helper-validator-option": "^7.23.5", - "browserslist": "^4.22.2", + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" }, @@ -224,82 +147,55 @@ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", "dev": true, + "license": "ISC", "dependencies": { "yallist": "^3.0.2" } }, "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", "dev": true, + "license": "ISC", "bin": { "semver": "bin/semver.js" } }, - "node_modules/@babel/helper-compilation-targets/node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true - }, - "node_modules/@babel/helper-environment-visitor": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-environment-visitor/-/helper-environment-visitor-7.22.20.tgz", - "integrity": "sha512-zfedSIzFhat/gFhWfHtgWvlec0nqB9YEIVrpuwjruLlXfUSnA8cJB0miHKwqDnQ7d32aKo2xt88/xZptwxbfhA==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-function-name": { - "version": "7.23.0", - "resolved": "https://registry.npmjs.org/@babel/helper-function-name/-/helper-function-name-7.23.0.tgz", - "integrity": "sha512-OErEqsrxjZTJciZ4Oo+eoZqeW9UIiOcuYKRJA4ZAgV9myA+pOXhhmpfNCKjEH/auVfEYVFJ6y1Tc4r0eIApqiw==", - "dev": true, - "dependencies": { - "@babel/template": "^7.22.15", - "@babel/types": "^7.23.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", - "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-imports": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", - "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/types": "^7.22.15" + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", - "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" }, "engines": { "node": ">=6.9.0" @@ -309,169 +205,68 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.24.0.tgz", - "integrity": "sha512-9cUznXMG0+FxRuJfvL82QlTqIzhVW9sL0KjMPHhAOOvpQGL8QtdxnBKILjBqxlHyliz0yCa1G903ZXI/FuHy2w==", - "dev": true, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-simple-access": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-simple-access/-/helper-simple-access-7.22.5.tgz", - "integrity": "sha512-n0H99E/K+Bika3++WNL17POvo4rKWZ7lZEp1Q+fStVbUi8nxPQEBOlTmCOxW/0JsS56SKKQ+ojAe2pHKJHN35w==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-split-export-declaration": { - "version": "7.22.6", - "resolved": "https://registry.npmjs.org/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.22.6.tgz", - "integrity": "sha512-AsUnxuLhRYsisFiaJwvp1QF+I3KjD5FOxut14q/GzovUe6orHLesW2C7d754kRm53h5gqrz6sFl6sxc4BVtE/g==", - "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-string-parser": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", - "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-option": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.23.5.tgz", - "integrity": "sha512-85ttAOMLsr53VgXkTbkx8oA6YTfT4q7/HzXSLEYmjcSTJPMPQtvq1BD79Byep5xMUYbGRzEpDsjUf3dyp54IKw==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helpers": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.24.0.tgz", - "integrity": "sha512-ulDZdc0Aj5uLc5nETsa7EPx2L7rM0YJM8r7ck7U73AXi7qOV44IHHRAYZHY6iU1rr3C5N4NtTmMRUJP6kwCWeA==", - "dev": true, - "dependencies": { - "@babel/template": "^7.24.0", - "@babel/traverse": "^7.24.0", - "@babel/types": "^7.24.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", - "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.14.tgz", + "integrity": "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0" + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14" }, "engines": { "node": ">=6.9.0" } }, - "node_modules/@babel/highlight/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/highlight/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/highlight/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/highlight/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", "dev": true, + "license": "MIT", "dependencies": { - "has-flag": "^3.0.0" + "@babel/types": "^7.29.14" }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/parser": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.24.0.tgz", - "integrity": "sha512-QuP/FxEAzMSjXygs8v4N9dvdXzEHN4W1oF3PxuWAtPo08UdM17u89RDMgjLn/mlc56iM0HlLmVkO/wgR+rDgHg==", - "dev": true, "bin": { "parser": "bin/babel-parser.js" }, @@ -484,6 +279,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -496,6 +292,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -508,6 +305,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.12.13" }, @@ -515,11 +313,44 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/plugin-syntax-class-static-block": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", + "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-syntax-import-attributes": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.29.7.tgz", + "integrity": "sha512-zGYcYfq/WmZ4V+kBIXQon9dSSc8ircGZqw9ZaNhhGj9nZkeBu1jHLBDQqYYi5WA9uawvA2sIMbry2nCFhf5Djg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/plugin-syntax-import-meta": { "version": "7.10.4", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" }, @@ -532,6 +363,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -540,12 +372,13 @@ } }, "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.23.3.tgz", - "integrity": "sha512-EB2MELswq55OHUoRZLGg/zC7QWUKfNLpE57m/S2yr1uEneIgsTgrSzXP3NXEsMkVn76OlaVVnzN+ugObuYGwhg==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" + "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { "node": ">=6.9.0" @@ -559,6 +392,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" }, @@ -571,6 +405,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -583,6 +418,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.10.4" }, @@ -595,6 +431,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -607,6 +444,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -619,6 +457,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.8.0" }, @@ -626,11 +465,28 @@ "@babel/core": "^7.0.0-0" } }, + "node_modules/@babel/plugin-syntax-private-property-in-object": { + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", + "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.14.5" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, "node_modules/@babel/plugin-syntax-top-level-await": { "version": "7.14.5", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", "dev": true, + "license": "MIT", "dependencies": { "@babel/helper-plugin-utils": "^7.14.5" }, @@ -642,12 +498,13 @@ } }, "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.23.3.tgz", - "integrity": "sha512-9EiNjVJOMwCO+43TqoTrgQ8jMwcAd0sWyXi9RPfIsLTj4R2MADDDQXELhffaUx/uJv2AYcxBgPwH6j4TIA4ytQ==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", + "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.22.5" + "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { "node": ">=6.9.0" @@ -657,49 +514,48 @@ } }, "node_modules/@babel/template": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.24.0.tgz", - "integrity": "sha512-Bkf2q8lMB0AFpX0NFEqSbx1OkTHf0f+0j82mkw+ZpzBnkk7e9Ql0891vlfgi+kHwOk8tQjiQHpqh4LaSa0fKEA==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.23.5", - "@babel/parser": "^7.24.0", - "@babel/types": "^7.24.0" + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.24.0.tgz", - "integrity": "sha512-HfuJlI8qq3dEDmNU5ChzzpZRWq+oxCZQyMzIMEqLho+AQnhMnKQUzH6ydo3RBl/YjPCuk68Y6s0Gx0AeyULiWw==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.14.tgz", + "integrity": "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.6", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.24.0", - "@babel/types": "^7.24.0", - "debug": "^4.3.1", - "globals": "^11.1.0" + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.14", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.14", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14", + "debug": "^4.3.1" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/types": { - "version": "7.24.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.24.0.tgz", - "integrity": "sha512-+j7a5c253RfKh8iABBhywc8NSfP5LURe7Uh4qpsh6jc+aLJguvmIUBdjSdEMQv2bENrCR5MfRdjGo7vzS/ob7w==", + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.23.4", - "@babel/helper-validator-identifier": "^7.22.20", - "to-fast-properties": "^2.0.0" + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" }, "engines": { "node": ">=6.9.0" @@ -709,448 +565,574 @@ "version": "0.2.3", "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true + "dev": true, + "license": "MIT" + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.12.tgz", - "integrity": "sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", "cpu": [ "ppc64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "aix" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.12.tgz", - "integrity": "sha512-qg/Lj1mu3CdQlDEEiWrlC4eaPZ1KztwGJ9B6J+/6G+/4ewxJg7gqj8eVYWvao1bXrqGiW2rsBZFSX3q2lcW05w==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.12.tgz", - "integrity": "sha512-P0UVNGIienjZv3f5zq0DP3Nt2IE/3plFzuaS96vihvD0Hd6H/q4WXUGpCxD/E8YrSXfNyRPbpTq+T8ZQioSuPA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/android-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.12.tgz", - "integrity": "sha512-3k7ZoUW6Q6YqhdhIaq/WZ7HwBpnFBlW905Fa4s4qWJyiNOgT1dOqDiVAQFwBH7gBRZr17gLrlFCRzF6jFh7Kew==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.12.tgz", - "integrity": "sha512-B6IeSgZgtEzGC42jsI+YYu9Z3HKRxp8ZT3cqhvliEHovq8HSX2YX8lNocDn79gCKJXOSaEot9MVYky7AKjCs8g==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.12.tgz", - "integrity": "sha512-hKoVkKzFiToTgn+41qGhsUJXFlIjxI/jSYeZf3ugemDYZldIXIxhvwN6erJGlX4t5h417iFuheZ7l+YVn05N3A==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.12.tgz", - "integrity": "sha512-4aRvFIXmwAcDBw9AueDQ2YnGmz5L6obe5kmPT8Vd+/+x/JMVKCgdcRwH6APrbpNXsPz+K653Qg8HB/oXvXVukA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.12.tgz", - "integrity": "sha512-EYoXZ4d8xtBoVN7CEwWY2IN4ho76xjYXqSXMNccFSx2lgqOG/1TBPW0yPx1bJZk94qu3tX0fycJeeQsKovA8gg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.12.tgz", - "integrity": "sha512-J5jPms//KhSNv+LO1S1TX1UWp1ucM6N6XuL6ITdKWElCu8wXP72l9MM0zDTzzeikVyqFE6U8YAV9/tFyj0ti+w==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.12.tgz", - "integrity": "sha512-EoTjyYyLuVPfdPLsGVVVC8a0p1BFFvtpQDB/YLEhaXyf/5bczaGeN15QkR+O4S5LeJ92Tqotve7i1jn35qwvdA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.12.tgz", - "integrity": "sha512-Thsa42rrP1+UIGaWz47uydHSBOgTUnwBwNq59khgIwktK6x60Hivfbux9iNR0eHCHzOLjLMLfUMLCypBkZXMHA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", "cpu": [ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.12.tgz", - "integrity": "sha512-LiXdXA0s3IqRRjm6rV6XaWATScKAXjI4R4LoDlvO7+yQqFdlr1Bax62sRwkVvRIrwXxvtYEHHI4dm50jAXkuAA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", "cpu": [ "loong64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.12.tgz", - "integrity": "sha512-fEnAuj5VGTanfJ07ff0gOA6IPsvrVHLVb6Lyd1g2/ed67oU1eFzL0r9WL7ZzscD+/N6i3dWumGE1Un4f7Amf+w==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", "cpu": [ "mips64el" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.12.tgz", - "integrity": "sha512-nYJA2/QPimDQOh1rKWedNOe3Gfc8PabU7HT3iXWtNUbRzXS9+vgB0Fjaqr//XNbd82mCxHzik2qotuI89cfixg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", "cpu": [ "ppc64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.12.tgz", - "integrity": "sha512-2MueBrlPQCw5dVJJpQdUYgeqIzDQgw3QtiAHUC4RBz9FXPrskyyU3VI1hw7C0BSKB9OduwSJ79FTCqtGMWqJHg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", "cpu": [ "riscv64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.12.tgz", - "integrity": "sha512-+Pil1Nv3Umes4m3AZKqA2anfhJiVmNCYkPchwFJNEJN5QxmTs1uzyy4TvmDrCRNT2ApwSari7ZIgrPeUx4UZDg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", "cpu": [ "s390x" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.12.tgz", - "integrity": "sha512-B71g1QpxfwBvNrfyJdVDexenDIt1CiDN1TIXLbhOw0KhJzE78KIFGX6OJ9MrtC0oOqMWf+0xop4qEU8JrJTwCg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.12.tgz", - "integrity": "sha512-3ltjQ7n1owJgFbuC61Oj++XhtzmymoCihNFgT84UAmJnxJfm4sYCiSLTXZtE00VWYpPMYc+ZQmB6xbSdVh0JWA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.12.tgz", - "integrity": "sha512-RbrfTB9SWsr0kWmb9srfF+L933uMDdu9BIzdA7os2t0TXhCRjrQyCeOt6wVxr79CKD4c+p+YhCj31HBkYcXebw==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { - "node": ">=12" + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.12.tgz", - "integrity": "sha512-HKjJwRrW8uWtCQnQOz9qcU3mUZhTUQvi56Q8DPTLLB+DawoiQdjsYq+j+D3s9I8VFtDr+F9CjgXKKC4ss89IeA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "sunos" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.12.tgz", - "integrity": "sha512-URgtR1dJnmGvX864pn1B2YUYNzjmXkuJOIqG2HdU62MVS4EHpU2946OZoTMnRUHklGtJdJZ33QfzdjGACXhn1A==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.12.tgz", - "integrity": "sha512-+ZOE6pUkMOJfmxmBZElNOx72NKpIa/HFOMGzu8fqzQJ5kgf6aTGrcJaFsNiVMH4JKpMipyK+7k0n2UXN7a8YKQ==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", "cpu": [ "ia32" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.12.tgz", - "integrity": "sha512-T1QyPSDCyMXaO3pzBkF96E8xMkiRYbUEZADd29SyPGabqxMViNoii+NcK7eWJAEoU6RZyEm5lVSIjTmcdoB9HA==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { - "node": ">=12" + "node": ">=18" } }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", + "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", "dev": true, + "license": "ISC", "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" }, "engines": { - "node": ">=8" + "node": ">=12" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", "dev": true, - "engines": { - "node": ">=6" - } + "license": "MIT" }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", + "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", "dev": true, + "license": "MIT", "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "node_modules/@isaacs/cliui/node_modules/wrap-ansi": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", + "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", "dev": true, + "license": "MIT", "dependencies": { - "p-locate": "^4.1.0" + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" }, "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", "dev": true, + "license": "ISC", "dependencies": { - "p-try": "^2.0.0" + "minipass": "^7.0.4" }, "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=18.0.0" } }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "node_modules/@istanbuljs/load-nyc-config": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", + "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", "dev": true, + "license": "ISC", "dependencies": { - "p-limit": "^2.2.0" + "camelcase": "^5.3.1", + "find-up": "^4.1.0", + "get-package-type": "^0.1.0", + "js-yaml": "^3.13.1", + "resolve-from": "^5.0.0" }, "engines": { "node": ">=8" @@ -1166,20 +1148,21 @@ } }, "node_modules/@jest/console": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", - "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.5.2.tgz", + "integrity": "sha512-e8sQC4pCMHPBrPX7Hk8TJr+DM5dkUnImSTNag8SEWFAFAF6xIz4AJvCKapnrdHnZxep4bxw4PhG+ZbimYBMyKw==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", + "@jest/types": "30.5.1", "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", + "chalk": "^4.1.2", + "jest-message-util": "30.5.1", + "jest-util": "30.5.1", "slash": "^3.0.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/console/node_modules/ansi-styles": { @@ -1187,6 +1170,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -1202,6 +1186,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -1218,6 +1203,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -1227,6 +1213,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -1235,42 +1222,43 @@ } }, "node_modules/@jest/core": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", - "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-30.5.2.tgz", + "integrity": "sha512-/jqvFWoJF7LV1a6AUpYMbMm+2yIYsHJfR474H0SCzr9k8tnO/jl9wRg6zSG6lxgf6EozNlCG4amFzWsbZSvvZA==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/console": "^29.7.0", - "@jest/reporters": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", + "@jest/console": "30.5.2", + "@jest/pattern": "30.5.0", + "@jest/reporters": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.7.0", - "jest-config": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-resolve-dependencies": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "jest-watcher": "^29.7.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" + "ansi-escapes": "^4.3.2", + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "exit-x": "^0.2.2", + "fast-json-stable-stringify": "^2.1.0", + "graceful-fs": "^4.2.11", + "jest-changed-files": "30.5.1", + "jest-config": "30.5.2", + "jest-haste-map": "30.5.1", + "jest-message-util": "30.5.1", + "jest-regex-util": "30.5.0", + "jest-resolve": "30.5.1", + "jest-resolve-dependencies": "30.5.2", + "jest-runner": "30.5.2", + "jest-runtime": "30.5.2", + "jest-snapshot": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", + "jest-watcher": "30.5.2", + "pretty-format": "30.5.1", + "slash": "^3.0.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -1281,20 +1269,12 @@ } } }, - "node_modules/@jest/core/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/@jest/core/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -1310,6 +1290,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -1321,38 +1302,12 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/@jest/core/node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "engines": { - "node": ">=8" - } - }, "node_modules/@jest/core/node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/core/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, + "license": "MIT", "engines": { "node": ">=8" } @@ -1362,6 +1317,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -1369,111 +1325,166 @@ "node": ">=8" } }, + "node_modules/@jest/diff-sequences": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.5.0.tgz", + "integrity": "sha512-OsqBjHXCn8cadasoAZBP6nWYvMsRhpMzGXTpxJ5aO04NlbdhIz+FVe3q49l0AwVhsz/cEmIpBes6gAFl1/dWQg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, "node_modules/@jest/environment": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", - "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.2.tgz", + "integrity": "sha512-nwFPOUMbmsjNNRCpnJpB9HbSZu4C07wDDds++5j+j1MezzPLxMPDdbdUVjr2o4RULDOValnDd70taPFI1EtxAg==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", + "@jest/fake-timers": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "jest-mock": "^29.7.0" + "jest-mock": "30.5.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-30.5.2.tgz", + "integrity": "sha512-2E+1Pg6jJxbRjLNLpciC71iri/3qsKJL222/aXJEFwC0VdUSvfS+JZQQLEVjUYYc8t8pQu2MGE3cF2+bNTYRsg==", "dev": true, + "license": "MIT", "dependencies": { - "expect": "^29.7.0", - "jest-snapshot": "^29.7.0" + "expect": "30.5.2", + "jest-snapshot": "30.5.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.5.2.tgz", + "integrity": "sha512-d/HOLSrJUlBIl6n3LzOa7cjW3xdePm5H5gQw2lixZ/0h157l9sw3mLblzFqnPcTbhDzhRQdBOX3A3KcG73nm5Q==", "dev": true, + "license": "MIT", "dependencies": { - "jest-get-type": "^29.6.3" + "@jest/get-type": "30.5.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/fake-timers": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", - "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.2.tgz", + "integrity": "sha512-GKk0h0tKT5SpDPxDhPg3r9mm5s8/YCBzVNMOGdRiQXwUiMsjU10mVPlMaQstH6/cu50vOb8N9oQUMETHuwwxKw==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", - "@sinonjs/fake-timers": "^10.0.2", + "@jest/types": "30.5.1", + "@sinonjs/fake-timers": "^15.4.0", "@types/node": "*", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" + "jest-message-util": "30.5.1", + "jest-mock": "30.5.2", + "jest-util": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/get-type": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.5.0.tgz", + "integrity": "sha512-9/2VUPitAjmBzbvDvqrxmvB7BzWsBW0WmkkojX1ODuxX1NLGxx9gfaZpHB0z8DtJ9uhGNmZG/VXBhf8uO0OV8Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/globals": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", - "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-30.5.2.tgz", + "integrity": "sha512-62zfS+dL+M5aTNHXCNLyqD+j4oqxTIzDYrZbpqMP8Yn+gvlAGyzC6BSPNb1ZmFOakV1RtFYX/O3FCQXSWmQdgg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "30.5.2", + "@jest/expect": "30.5.2", + "@jest/types": "30.5.1", + "jest-mock": "30.5.2" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/pattern": { + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.5.0.tgz", + "integrity": "sha512-HdNQYSdRTEBNrginaqzQtTjG0HRMfrra/z6Ok7uL3S87vSlarIVohEsJsSj5edu3MiHoHjAkvPROz5ZjoKai+w==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/types": "^29.6.3", - "jest-mock": "^29.7.0" + "@types/node": "*", + "jest-regex-util": "30.5.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, + "node_modules/@jest/react-is-18": { + "name": "react-is", + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jest/react-is-19": { + "name": "react-is", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@jest/reporters": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", - "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-30.5.2.tgz", + "integrity": "sha512-ev6E9iG73twQcfAfoTnviuYkr3yOrYbzAtMFCimv2fxHXPIp9PBt2u1wNMt0aYWgl8FPwIcS8oqRJg6alnht4Q==", "dev": true, + "license": "MIT", "dependencies": { "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", + "@jest/console": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", + "@jridgewell/trace-mapping": "^0.3.31", "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", + "chalk": "^4.1.2", + "collect-v8-coverage": "^1.0.2", + "exit-x": "^0.2.2", + "glob": "^13.0.6", + "graceful-fs": "^4.2.11", "istanbul-lib-coverage": "^3.0.0", "istanbul-lib-instrument": "^6.0.0", "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", + "istanbul-lib-source-maps": "^5.0.0", "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", + "jest-message-util": "30.5.1", + "jest-util": "30.5.1", + "jest-worker": "30.5.1", "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", + "string-length": "^4.0.2", "v8-to-istanbul": "^9.0.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -1484,20 +1495,12 @@ } } }, - "node_modules/@jest/reporters/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/@jest/reporters/node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -1513,6 +1516,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -1529,18 +1533,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/reporters/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, + "license": "MIT", "engines": { "node": ">=8" } @@ -1550,6 +1543,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -1558,68 +1552,136 @@ } }, "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.5.0.tgz", + "integrity": "sha512-/hunigyNpc4RCjC0VaW3f5RCUZVM2+WQ65qP7z083Gmvac7or2LI50XVNOtE4YPgBpV0yxYiAgorAPGniCoJmg==", "dev": true, + "license": "MIT", "dependencies": { - "@sinclair/typebox": "^0.27.8" + "@sinclair/typebox": "^0.34.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@jest/source-map": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", - "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", + "node_modules/@jest/snapshot-utils": { + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/@jest/snapshot-utils/-/snapshot-utils-30.5.1.tgz", + "integrity": "sha512-V3wnxNtiVmw5PPVg433Cn3VdXnsOeu/ofLw3KC04Bn2y1wIlU5kozXQn48rhrgj/02LrCVtntTEF1yBha0XSUw==", "dev": true, + "license": "MIT", "dependencies": { - "@jridgewell/trace-mapping": "^0.3.18", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" + "@jest/types": "30.5.1", + "chalk": "^4.1.2", + "graceful-fs": "^4.2.11", + "natural-compare": "^1.4.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/@jest/source-map/node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "node_modules/@jest/snapshot-utils/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, "engines": { - "node": ">=6" + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/@jest/snapshot-utils/node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/@jest/snapshot-utils/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/@jest/source-map": { + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-30.5.2.tgz", + "integrity": "sha512-c5CehvkbfHX6yyNg7bMn2ylqlp9AHXuZ/3hPH/Lh5bxD/vefd/lV9HBjMqXef9yQNqkdwyZvkLSVSwB38hy8Qw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "callsites": "^3.1.0", + "convert-source-map": "^2.0.0", + "graceful-fs": "^4.2.11" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/@jest/source-map/node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" } }, "node_modules/@jest/test-result": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", - "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.5.2.tgz", + "integrity": "sha512-eO6YU5rsLfs60ne694e0IAmRgeBnoA8mu0nlxXDbl/1j5km0o2vO9/VbbUIKIH+WRKKEI+ELgwraRGn2Lhep8g==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/console": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" + "@jest/console": "30.5.2", + "@jest/types": "30.5.1", + "@types/istanbul-lib-coverage": "^2.0.6", + "collect-v8-coverage": "^1.0.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/test-sequencer": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", - "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-30.5.2.tgz", + "integrity": "sha512-bmij8jZyYAC47ExT2GeP7PcrlwSNS+Bp3KeRuBH88gpcxqDv6fljN8PemS4J/lLZ79xb6mpaennQTTq0zUAVVg==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/test-result": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", + "@jest/test-result": "30.5.2", + "graceful-fs": "^4.2.11", + "jest-haste-map": "30.5.1", "slash": "^3.0.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/test-sequencer/node_modules/slash": { @@ -1627,34 +1689,35 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/@jest/transform": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", - "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.5.2.tgz", + "integrity": "sha512-LBGwmaE886C41jDZ65eqR1YbXM7642MK3ZhTowZd5+xDlrDLuf4ePuDdDmVSvcr8NTVJ3MqxLkMbUCzuigUaoQ==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", + "@babel/core": "^7.27.4", + "@jest/types": "30.5.1", + "@jridgewell/trace-mapping": "^0.3.31", + "babel-plugin-istanbul": "^8.0.0", + "chalk": "^4.1.2", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", + "graceful-fs": "^4.2.11", + "jest-haste-map": "30.5.1", + "jest-regex-util": "30.5.0", + "jest-util": "30.5.1", + "pirates": "^4.0.7", "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" + "write-file-atomic": "^5.0.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/transform/node_modules/ansi-styles": { @@ -1688,6 +1751,19 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/@jest/transform/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@jest/transform/node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", @@ -1710,33 +1786,36 @@ } }, "node_modules/@jest/transform/node_modules/write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", + "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", "dev": true, + "license": "ISC", "dependencies": { "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" + "signal-exit": "^4.0.1" }, "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" } }, "node_modules/@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.5.1.tgz", + "integrity": "sha512-LvVYn83nnXPl+Rg98nvcFgjx6nRMTArhSn6RAX/w3ELn54S8A42TYZvsCMdGUqTM8S0wyXbtlQdU6Hi6dykj9g==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", + "@jest/pattern": "30.5.0", + "@jest/schemas": "30.5.0", + "@types/istanbul-lib-coverage": "^2.0.6", + "@types/istanbul-reports": "^3.0.4", "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" + "@types/yargs": "^17.0.33", + "chalk": "^4.1.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/types/node_modules/ansi-styles": { @@ -1783,17 +1862,25 @@ } }, "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.5.tgz", - "integrity": "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "dev": true, + "license": "MIT", "dependencies": { - "@jridgewell/set-array": "^1.2.1", - "@jridgewell/sourcemap-codec": "^1.4.10", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" - }, - "engines": { - "node": ">=6.0.0" } }, "node_modules/@jridgewell/resolve-uri": { @@ -1805,49 +1892,67 @@ "node": ">=6.0.0" } }, - "node_modules/@jridgewell/set-array": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.2.1.tgz", - "integrity": "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", - "dev": true + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "dev": true, + "license": "MIT", "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "node_modules/@mapbox/node-pre-gyp": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", - "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-2.0.3.tgz", + "integrity": "sha512-uwPAhccfFJlsfCxMYTwOdVfOz3xqyj8xYL3zJj8f0pb30tLohnnFPhLuqp4/qoEz8sNxe4SESZedcBojRefIzg==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { + "consola": "^3.2.3", "detect-libc": "^2.0.0", - "https-proxy-agent": "^5.0.0", - "make-dir": "^3.1.0", + "https-proxy-agent": "^7.0.5", "node-fetch": "^2.6.7", - "nopt": "^5.0.0", - "npmlog": "^5.0.1", - "rimraf": "^3.0.2", - "semver": "^7.3.5", - "tar": "^6.1.11" + "nopt": "^8.0.0", + "semver": "^7.5.3", + "tar": "^7.4.0" }, "bin": { "node-pre-gyp": "bin/node-pre-gyp" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, "node_modules/@nodelib/fs.scandir": { @@ -1855,6 +1960,7 @@ "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "dev": true, + "license": "MIT", "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" @@ -1868,6 +1974,7 @@ "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", "dev": true, + "license": "MIT", "engines": { "node": ">= 8" } @@ -1877,6 +1984,7 @@ "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", "dev": true, + "license": "MIT", "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" @@ -1885,211 +1993,662 @@ "node": ">= 8" } }, - "node_modules/@rollup/pluginutils": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-4.2.1.tgz", - "integrity": "sha512-iKnFXr7NkdZAIHiIWE+BX5ULi/ucVFYWD6TbAV+rZctiRTY2PL6tsIKhoIOaoskiWAkgu+VsbXgUVDNLHf+InQ==", + "node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, - "dependencies": { - "estree-walker": "^2.0.1", - "picomatch": "^2.2.2" - }, - "engines": { - "node": ">= 8.0.0" + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" } }, - "node_modules/@rollup/pluginutils/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, "engines": { - "node": ">=8.6" + "node": ">= 10.0.0" }, "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/@rollup/rollup-android-arm-eabi": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.12.1.tgz", - "integrity": "sha512-iU2Sya8hNn1LhsYyf0N+L4Gf9Qc+9eBTJJJsaOGUp+7x4n2M9dxTt8UvhJl3oeftSjblSlpCfvjA/IfP3g5VjQ==", + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", "cpu": [ - "arm" + "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "android" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-android-arm64": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.12.1.tgz", - "integrity": "sha512-wlzcWiH2Ir7rdMELxFE5vuM7D6TsOcJ2Yw0c3vaBR3VOsJFVTx9xvwnAvhgU5Ii8Gd6+I11qNHwndDscIm0HXg==", + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ - "android" - ] + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-darwin-arm64": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.12.1.tgz", - "integrity": "sha512-YRXa1+aZIFN5BaImK+84B3uNK8C6+ynKLPgvn29X9s0LTVCByp54TB7tdSMHDR7GTV39bz1lOmlLDuedgTwwHg==", + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", "cpu": [ - "arm64" + "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "darwin" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-darwin-x64": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.12.1.tgz", - "integrity": "sha512-opjWJ4MevxeA8FhlngQWPBOvVWYNPFkq6/25rGgG+KOy0r8clYwL1CFd+PGwRqqMFVQ4/Qd3sQu5t7ucP7C/Uw==", + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ - "darwin" - ] + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-linux-arm-gnueabihf": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.12.1.tgz", - "integrity": "sha512-uBkwaI+gBUlIe+EfbNnY5xNyXuhZbDSx2nzzW8tRMjUmpScd6lCQYKY2V9BATHtv5Ef2OBq6SChEP8h+/cxifQ==", + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", "cpu": [ "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-linux-arm64-gnu": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.12.1.tgz", - "integrity": "sha512-0bK9aG1kIg0Su7OcFTlexkVeNZ5IzEsnz1ept87a0TUgZ6HplSgkJAnFpEVRW7GRcikT4GlPV0pbtVedOaXHQQ==", + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", "cpu": [ - "arm64" + "arm" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-linux-arm64-musl": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.12.1.tgz", - "integrity": "sha512-qB6AFRXuP8bdkBI4D7UPUbE7OQf7u5OL+R94JE42Z2Qjmyj74FtDdLGeriRyBDhm4rQSvqAGCGC01b8Fu2LthQ==", + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-linux-riscv64-gnu": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.12.1.tgz", - "integrity": "sha512-sHig3LaGlpNgDj5o8uPEoGs98RII8HpNIqFtAI8/pYABO8i0nb1QzT0JDoXF/pxzqO+FkxvwkHZo9k0NJYDedg==", + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", "cpu": [ - "riscv64" + "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-linux-x64-gnu": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.12.1.tgz", - "integrity": "sha512-nD3YcUv6jBJbBNFvSbp0IV66+ba/1teuBcu+fBBPZ33sidxitc6ErhON3JNavaH8HlswhWMC3s5rgZpM4MtPqQ==", + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-linux-x64-musl": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.12.1.tgz", - "integrity": "sha512-7/XVZqgBby2qp/cO0TQ8uJK+9xnSdJ9ct6gSDdEr4MfABrjTyrW6Bau7HQ73a2a5tPB7hno49A0y1jhWGDN9OQ==", + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "linux" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-win32-arm64-msvc": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.12.1.tgz", - "integrity": "sha512-CYc64bnICG42UPL7TrhIwsJW4QcKkIt9gGlj21gq3VV0LL6XNb1yAdHVp1pIi9gkts9gGcT3OfUYHjGP7ETAiw==", + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", "cpu": [ "arm64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" - ] - }, - "node_modules/@rollup/rollup-win32-ia32-msvc": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.12.1.tgz", - "integrity": "sha512-LN+vnlZ9g0qlHGlS920GR4zFCqAwbv2lULrR29yGaWP9u7wF5L7GqWu9Ah6/kFZPXPUkpdZwd//TNR+9XC9hvA==", - "cpu": [ - "ia32" ], - "dev": true, - "optional": true, - "os": [ - "win32" - ] + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/@rollup/rollup-win32-x64-msvc": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.12.1.tgz", - "integrity": "sha512-n+vkrSyphvmU0qkQ6QBNXCGr2mKjhP08mPRM/Xp5Ck2FV4NrHU+y6axzDeixUrCBHVUS51TZhjqrKBBsHLKb2Q==", + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", "cpu": [ "x64" ], "dev": true, + "license": "MIT", "optional": true, "os": [ "win32" - ] + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", + "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", + "dev": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@pkgr/core": { + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", + "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/pkgr" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@rollup/pluginutils": { + "version": "5.5.1", + "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.5.1.tgz", + "integrity": "sha512-P9ZvnfouRu4MSC+ilERaw6FmZs8zqKhpHxEs4aGDGWQAMzQGXnhvCSvoNwokfNvdt7t3Y5Y4p6gStQgezeIqug==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0", + "estree-walker": "^2.0.2", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } }, "node_modules/@sinclair/typebox": { - "version": "0.27.8", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", - "integrity": "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA==", - "dev": true + "version": "0.34.52", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", + "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", + "dev": true, + "license": "MIT" }, "node_modules/@sindresorhus/merge-streams": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-2.3.0.tgz", "integrity": "sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -2102,17 +2661,31 @@ "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "type-detect": "4.0.8" } }, "node_modules/@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", + "version": "15.5.0", + "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-15.5.0.tgz", + "integrity": "sha512-i7HpIYIsUmdSTQbtBjs2b3VqMgDsVDWfzVPV3MuUrXVqJNZmzFB8YJeM9SPms2bGg5zg7HvKH31sPS1WoLLRFg==", "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@sinonjs/commons": "^3.0.1" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz", + "integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, "dependencies": { - "@sinonjs/commons": "^3.0.0" + "tslib": "^2.4.0" } }, "node_modules/@types/babel__core": { @@ -2120,6 +2693,7 @@ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", "dev": true, + "license": "MIT", "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", @@ -2129,10 +2703,11 @@ } }, "node_modules/@types/babel__generator": { - "version": "7.6.8", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", - "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/types": "^7.0.0" } @@ -2142,35 +2717,47 @@ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", "dev": true, + "license": "MIT", "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "node_modules/@types/babel__traverse": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.5.tgz", - "integrity": "sha512-WXCyOcRtH37HAUkpXhUduaxdm82b4GSlyTqajXviN4EfiuPgNYR109xMCKvpl6zPIpua0DGlMEDCq+g8EdoheQ==", + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/types": "^7.20.7" + "@babel/types": "^7.28.2" } }, - "node_modules/@types/estree": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", - "integrity": "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==", - "dev": true - }, - "node_modules/@types/graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", "dev": true, + "license": "MIT", "dependencies": { - "@types/node": "*" + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/istanbul-lib-coverage": { "version": "2.0.6", "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", @@ -2196,183 +2783,517 @@ } }, "node_modules/@types/mocha": { - "version": "10.0.6", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.6.tgz", - "integrity": "sha512-dJvrYWxP/UcXm36Qn36fxhUKu8A/xMRXVT2cliFF1Z7UA9liG5Psj3ezNSZw+5puH2czDXRLcXQxf8JbJt0ejg==", - "dev": true + "version": "10.0.10", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz", + "integrity": "sha512-xPyYSz1cMPnJQhl0CLMH68j3gprKZaTjG3s5Vi+fDgx+uhG9NOXwbVt52eFS8ECyXhyKcjDLCBEqBExKuiZb7Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/stack-utils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", + "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/yargs": { + "version": "17.0.35", + "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", + "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/yargs-parser": "*" + } + }, + "node_modules/@types/yargs-parser": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", + "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@ungap/structured-clone": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/@unrs/resolver-binding-android-arm-eabi": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.13.0.tgz", + "integrity": "sha512-60E5mvmIiW+i1E/HYeSX4iE4A8s9NJSGYPu7UM0DJght1c2tTkWwuyDyAwzsEXhKM/XbbndfnTiXdfrf27d2hw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-android-arm64": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.13.0.tgz", + "integrity": "sha512-qlh/JR3Tuy1cJ7xtf5pR4ykvLiK6os7X7EL2+zXZbrVc/s+yB8DoFdQrCAW9/a2TOxPVbR7QVNpkPWh7UWIsEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-arm64": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.13.0.tgz", + "integrity": "sha512-yynnnnJXUC99WeD1GfvuXPKsKNfvgzGYC2eRayFnUfsHVROjqrbFOkFQLZiSx1H8+PLy5BzU8vqyPyLqbRfeBQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-x64": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.13.0.tgz", + "integrity": "sha512-t8PXE0Ip9tmGyhRlfVsnEbzGM5iSvJIeNIXciUACjzpg0mmPs13fGv2x7W8sBa0S8zbIiohxKXS9fL/LXW/ERQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-freebsd-x64": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.13.0.tgz", + "integrity": "sha512-qdtl9GDWDoDx6rhzF4RU5SJutV3lcLOiTiyqD6nBxYfEO6lAgLNukfrA+HJ2u2OiyWvV8JW5iEWD3LoONw7lYA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.13.0.tgz", + "integrity": "sha512-VrMUVwdrScTarsh4B6aUhTtziUavSlglo4Hi8XZ6CpAe4+j3nquY+XoP+tYkiSBDsXZ8386ne4pv4YYYBNi02w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.13.0.tgz", + "integrity": "sha512-zSbTVwaxiTC+zYJ9xVNTC6c+BYO/kOV/odcTI3bHuFFXa+XmjLoUkb/8UxsZeU5YF4K000m17wrXoTblNWuzOg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.13.0.tgz", + "integrity": "sha512-Z/Rax87moZHsuvJ8awdfP+zrMlsCt3d7mggUPIiPe32KpeagimyzJWnZSMQoV67an9uVQghyh92Pc0VprITnYA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-musl": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.13.0.tgz", + "integrity": "sha512-oUzXz8hNvFLNEAag8lBKJe1euiV2dmGHAR+eQ5fNpsZO0F1K7IMRb4J6pqYsd7uLMRQNPiu5A1WKUJHbFLWbbw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-loong64-gnu": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-gnu/-/resolver-binding-linux-loong64-gnu-1.13.0.tgz", + "integrity": "sha512-BxhGYvZBg0YrvNOeSEGR3eNklwXYy0mUJk7oeGJvZoQMKM68zYvbbf52+fQI3Le4X0fW276FTKIoTwjpMob80A==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-loong64-musl": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-musl/-/resolver-binding-linux-loong64-musl-1.13.0.tgz", + "integrity": "sha512-nZcIuup9Ar3gAlqoZfX/KW6x83TMI11tLpCjldZG5M1KeY8qNUPNJJ71+sPvG8HMBpoh+ix1pAm5gkMFvcSAcQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.13.0.tgz", + "integrity": "sha512-AG6AgdDrkRNjAPwD/cftFJGgZUWCiJX+E8vpYCDEnwFHLTHZ7ppBiU6/vyPPwrfjcPUPQCDbbxE/eZUXsx49jQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.13.0.tgz", + "integrity": "sha512-6vOqYGcAmzpRWpUURWutzvpf1qJ6eOu5cfYObdtPJnzZ0+Kw4cw+ZkZJqIYEh8fPuTBwSYDL/FwlUhma1G/JVQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.13.0.tgz", + "integrity": "sha512-4HeIn0S2KVUowK0A+EweXrDvZ8CKHEfTtif0kx9vt3ORNsqcXNFFIFnHE0tizma3/Gt5OGrU2ovYNuj+D/bN4g==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.13.0.tgz", + "integrity": "sha512-JfkvqY7NZbxyhexLE+g6Z8Hsx4utHOGaVazAVghPiBn8Upw2iERZPpKYnW1FBVU4WStv/BiIsoK/Muke0E7asA==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-gnu": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.13.0.tgz", + "integrity": "sha512-iwjLeVdZo/8v5OKAeRIC+4VQV045t1EPZr5B/AVLgUQ04IdtNthWzg6not2cNjZgH2gHpSf4fOXMmN83aLO1FA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-musl": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.13.0.tgz", + "integrity": "sha512-TOh1fqOjyq1OPoht3BDLd7Y+HeMJRwd5g2VNmCQclknEbjp4py5GFRmT4L/rOybF5Af8q0LT9zHs2WGkwlqtrw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] }, - "node_modules/@types/node": { - "version": "20.11.25", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.25.tgz", - "integrity": "sha512-TBHyJxk2b7HceLVGFcpAUjsa5zIdsPWlR6XHfyGzd0SFu+/NFgQgMAl96MSDZgQDvJAvV6BKsFOrt6zIL09JDw==", + "node_modules/@unrs/resolver-binding-openharmony-arm64": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-openharmony-arm64/-/resolver-binding-openharmony-arm64-1.13.0.tgz", + "integrity": "sha512-3T2MNtF2dd1yjaXCVqrsi+/3VZeksEzU1hygPzqqkBLVVjn+2iJzXEkxxCKIVFrWnpmEbazeHJp/ruYD0RUVWA==", + "cpu": [ + "arm64" + ], "dev": true, - "dependencies": { - "undici-types": "~5.26.4" - } + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] }, - "node_modules/@types/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true + "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.13.0.tgz", + "integrity": "sha512-hKWfSLiN3L4cIxg0jrpyP/66AXLTcyD37jmSn//rGdOUYGlizYxTEFdJ+GZbp2NnaML3YS/A73nCysze8FaJdg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] }, - "node_modules/@types/yargs": { - "version": "17.0.32", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.32.tgz", - "integrity": "sha512-xQ67Yc/laOG5uMfX/093MRlGGCIBzZMarVa+gfNKJxWAIgykYpVGkBdbqEzGDDfCrVUj6Hiff4mTZ5BA6TmAog==", + "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.13.0.tgz", + "integrity": "sha512-N4gDKkDoiyIQEcn3vTqe2ksRxUAtBvQ8c5TiT+WonSa6FHgCAY5+RggnZ134hXJoRj57JEjv4/m+i/pAKHWrTQ==", + "cpu": [ + "ia32" + ], "dev": true, - "dependencies": { - "@types/yargs-parser": "*" - } + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] }, - "node_modules/@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", - "dev": true + "node_modules/@unrs/resolver-binding-win32-x64-msvc": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.13.0.tgz", + "integrity": "sha512-DpLMlAqlrk4zBVK3DiDjwKD0oq7pZNy+8BiIBRuByqb6dm5jsdoLMhIiyh/xR7+WejaW/1Ui+XgbgMNa4+zWJg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] }, "node_modules/@vercel/nft": { - "version": "0.26.4", - "resolved": "https://registry.npmjs.org/@vercel/nft/-/nft-0.26.4.tgz", - "integrity": "sha512-j4jCOOXke2t8cHZCIxu1dzKLHLcFmYzC3yqAK6MfZznOL1QIJKd0xcFsXK3zcqzU7ScsE2zWkiMMNHGMHgp+FA==", + "version": "0.29.4", + "resolved": "https://registry.npmjs.org/@vercel/nft/-/nft-0.29.4.tgz", + "integrity": "sha512-6lLqMNX3TuycBPABycx7A9F1bHQR7kiQln6abjFbPrf5C/05qHM9M5E4PeTE59c7z8g6vHnx1Ioihb2AQl7BTA==", "dev": true, + "license": "MIT", "dependencies": { - "@mapbox/node-pre-gyp": "^1.0.5", - "@rollup/pluginutils": "^4.0.0", + "@mapbox/node-pre-gyp": "^2.0.0", + "@rollup/pluginutils": "^5.1.3", "acorn": "^8.6.0", - "acorn-import-attributes": "^1.9.2", + "acorn-import-attributes": "^1.9.5", "async-sema": "^3.1.1", "bindings": "^1.4.0", "estree-walker": "2.0.2", - "glob": "^7.1.3", + "glob": "^10.4.5", "graceful-fs": "^4.2.9", - "micromatch": "^4.0.2", "node-gyp-build": "^4.2.2", + "picomatch": "^4.0.2", "resolve-from": "^5.0.0" }, "bin": { "nft": "out/cli.js" }, "engines": { - "node": ">=16" + "node": ">=18" } }, - "node_modules/@vitest/expect": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-1.3.1.tgz", - "integrity": "sha512-xofQFwIzfdmLLlHa6ag0dPV8YsnKOCP1KdAeVVh34vSjN2dcUiXYCD9htu/9eM7t8Xln4v03U9HLxLpPlsXdZw==", + "node_modules/@vercel/nft/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", "dev": true, - "dependencies": { - "@vitest/spy": "1.3.1", - "@vitest/utils": "1.3.1", - "chai": "^4.3.10" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } + "license": "MIT" }, - "node_modules/@vitest/runner": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-1.3.1.tgz", - "integrity": "sha512-5FzF9c3jG/z5bgCnjr8j9LNq/9OxV2uEBAITOXfoe3rdZJTdO7jzThth7FXv/6b+kdY65tpRQB7WaKhNZwX+Kg==", + "node_modules/@vercel/nft/node_modules/brace-expansion": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.8.tgz", + "integrity": "sha512-BnlDzDYQoplTsZSvPi86CNzmbcb07X8ufR8fk1zivaiEJlXJkiq1MQyDCVmlWcsWbj6aWXqHnrwwevbrm/Saig==", "dev": true, + "license": "MIT", "dependencies": { - "@vitest/utils": "1.3.1", - "p-limit": "^5.0.0", - "pathe": "^1.1.1" - }, - "funding": { - "url": "https://opencollective.com/vitest" + "balanced-match": "^1.0.0" } }, - "node_modules/@vitest/runner/node_modules/p-limit": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-5.0.0.tgz", - "integrity": "sha512-/Eaoq+QyLSiXQ4lyYV23f14mZRQcXnxfHrN0vCai+ak9G0pp9iEQukIIZq5NccEvwRB8PUnZT0KsOoDCINS1qQ==", + "node_modules/@vercel/nft/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", "dev": true, + "license": "ISC", "dependencies": { - "yocto-queue": "^1.0.0" + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" }, - "engines": { - "node": ">=18" + "bin": { + "glob": "dist/esm/bin.mjs" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@vitest/runner/node_modules/yocto-queue": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-1.0.0.tgz", - "integrity": "sha512-9bnSc/HEW2uRy67wc+T8UwauLuPJVn28jb+GtJY16iiKWyvmYJRXVT4UamsAEGQfPohgr2q4Tq0sQbQlxTfi1g==", + "node_modules/@vercel/nft/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", "dev": true, - "engines": { - "node": ">=12.20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } + "license": "ISC" }, - "node_modules/@vitest/snapshot": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-1.3.1.tgz", - "integrity": "sha512-EF++BZbt6RZmOlE3SuTPu/NfwBF6q4ABS37HHXzs2LUVPBLx2QoY/K0fKpRChSo8eLiuxcbCVfqKgx/dplCDuQ==", + "node_modules/@vercel/nft/node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", "dev": true, + "license": "ISC", "dependencies": { - "magic-string": "^0.30.5", - "pathe": "^1.1.1", - "pretty-format": "^29.7.0" + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" }, "funding": { - "url": "https://opencollective.com/vitest" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@vitest/spy": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-1.3.1.tgz", - "integrity": "sha512-xAcW+S099ylC9VLU7eZfdT9myV67Nor9w9zhf0mGCYJSO+zM2839tOeROTdikOi/8Qeusffvxb/MyBSOja1Uig==", + "node_modules/@vercel/nft/node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", "dev": true, + "license": "BlueOak-1.0.0", "dependencies": { - "tinyspy": "^2.2.0" + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" }, "funding": { - "url": "https://opencollective.com/vitest" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@vitest/utils": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-1.3.1.tgz", - "integrity": "sha512-d3Waie/299qqRyHTm2DjADeTaNdNSVsnwHPWrs20JMpjh6eiVq7ggggweO8rc4arhf6rRkWuHKwvxGvejUXZZQ==", + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", "dev": true, + "license": "MIT", "dependencies": { - "diff-sequences": "^29.6.3", + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", "estree-walker": "^3.0.3", - "loupe": "^2.3.7", - "pretty-format": "^29.7.0" + "magic-string": "^1.4.3" }, "funding": { "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } } }, - "node_modules/@vitest/utils/node_modules/estree-walker": { + "node_modules/@vitest/mocker/node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", "dev": true, + "license": "MIT", "dependencies": { "@types/estree": "^1.0.0" } }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/abbrev": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", - "dev": true + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-3.0.1.tgz", + "integrity": "sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg==", + "dev": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } }, "node_modules/acorn": { - "version": "8.11.3", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", - "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", "dev": true, + "license": "MIT", "bin": { "acorn": "bin/acorn" }, @@ -2381,42 +3302,36 @@ } }, "node_modules/acorn-import-attributes": { - "version": "1.9.2", - "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.2.tgz", - "integrity": "sha512-O+nfJwNolEA771IYJaiLWK1UAwjNsQmZbTRqqwBYxCgVQTmpFEMvBw6LOIQV0Me339L5UMVYFyRohGnGlQDdIQ==", + "version": "1.9.5", + "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", + "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", "dev": true, + "license": "MIT", "peerDependencies": { "acorn": "^8" } }, "node_modules/acorn-walk": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.2.tgz", - "integrity": "sha512-cjkyv4OtNCIeqhHrfS81QWXoCBPExR/J62oyEqepVw8WaQeSqpW2uhuLPh1m9eWhDuOo/jUXVTlifvesOWp/4A==", - "dev": true, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz", + "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==", "dev": true, + "license": "MIT", "dependencies": { - "debug": "4" + "acorn": "^8.11.0" }, "engines": { - "node": ">= 6.0.0" + "node": ">=0.4.0" } }, - "node_modules/ansi-colors": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", - "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", "dev": true, + "license": "MIT", "engines": { - "node": ">=6" + "node": ">= 14" } }, "node_modules/ansi-escapes": { @@ -2424,6 +3339,7 @@ "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", "dev": true, + "license": "MIT", "dependencies": { "type-fest": "^0.21.3" }, @@ -2439,6 +3355,7 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", "dev": true, + "license": "(MIT OR CC0-1.0)", "engines": { "node": ">=10" }, @@ -2459,10 +3376,11 @@ } }, "node_modules/ansi-styles": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.1.tgz", - "integrity": "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", "dev": true, + "license": "MIT", "engines": { "node": ">=12" }, @@ -2484,10 +3402,11 @@ } }, "node_modules/anymatch/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", "dev": true, + "license": "MIT", "engines": { "node": ">=8.6" }, @@ -2495,25 +3414,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/aproba": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", - "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==", - "dev": true - }, - "node_modules/are-we-there-yet": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", - "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", - "dev": true, - "dependencies": { - "delegates": "^1.0.0", - "readable-stream": "^3.6.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/argparse": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", @@ -2554,72 +3454,75 @@ } }, "node_modules/assertion-error": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", - "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", "dev": true, + "license": "MIT", "engines": { - "node": "*" + "node": ">=12" } }, "node_modules/async-sema": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/async-sema/-/async-sema-3.1.1.tgz", "integrity": "sha512-tLRNUXati5MFePdAk8dw7Qt7DpxPB60ofAgn8WRhW6a2rcimZnYBP9oxHiv0OHy+Wz7kPMG+t4LGdt31+4EmGg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/ava": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/ava/-/ava-6.1.2.tgz", - "integrity": "sha512-WcpxJ8yZ7mk9ABTinD0IAjcemovSeVGjuuwZx0JS9johREWFeLTl8UP6wd7l6nmnrWqkKZdwaD71a/ocH4qPKw==", + "version": "6.4.1", + "resolved": "https://registry.npmjs.org/ava/-/ava-6.4.1.tgz", + "integrity": "sha512-vxmPbi1gZx9zhAjHBgw81w/iEDKcrokeRk/fqDTyA2DQygZ0o+dUGRHFOtX8RA5N0heGJTTsIk7+xYxitDb61Q==", "dev": true, + "license": "MIT", "dependencies": { - "@vercel/nft": "^0.26.2", - "acorn": "^8.11.3", - "acorn-walk": "^8.3.2", + "@vercel/nft": "^0.29.4", + "acorn": "^8.15.0", + "acorn-walk": "^8.3.4", "ansi-styles": "^6.2.1", "arrgv": "^1.0.2", "arrify": "^3.0.0", - "callsites": "^4.1.0", - "cbor": "^9.0.1", - "chalk": "^5.3.0", + "callsites": "^4.2.0", + "cbor": "^10.0.9", + "chalk": "^5.4.1", "chunkd": "^2.0.1", - "ci-info": "^4.0.0", + "ci-info": "^4.3.0", "ci-parallel-vars": "^1.0.1", "cli-truncate": "^4.0.0", "code-excerpt": "^4.0.0", "common-path-prefix": "^3.0.0", "concordance": "^5.0.4", "currently-unhandled": "^0.4.1", - "debug": "^4.3.4", - "emittery": "^1.0.1", - "figures": "^6.0.1", - "globby": "^14.0.0", + "debug": "^4.4.1", + "emittery": "^1.2.0", + "figures": "^6.1.0", + "globby": "^14.1.0", "ignore-by-default": "^2.1.0", "indent-string": "^5.0.0", "is-plain-object": "^5.0.0", "is-promise": "^4.0.0", "matcher": "^5.0.0", - "memoize": "^10.0.0", + "memoize": "^10.1.0", "ms": "^2.1.3", - "p-map": "^7.0.1", + "p-map": "^7.0.3", "package-config": "^5.0.0", - "picomatch": "^3.0.1", + "picomatch": "^4.0.2", "plur": "^5.1.0", - "pretty-ms": "^9.0.0", + "pretty-ms": "^9.2.0", "resolve-cwd": "^3.0.0", "stack-utils": "^2.0.6", "strip-ansi": "^7.1.0", "supertap": "^3.0.1", "temp-dir": "^3.0.0", - "write-file-atomic": "^5.0.1", + "write-file-atomic": "^6.0.0", "yargs": "^17.7.2" }, "bin": { "ava": "entrypoints/cli.mjs" }, "engines": { - "node": "^18.18 || ^20.8 || ^21" + "node": "^18.18 || ^20.8 || ^22 || ^23 || >=24" }, "peerDependencies": { "@ava/typescript": "*" @@ -2631,24 +3534,25 @@ } }, "node_modules/babel-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", - "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-30.5.2.tgz", + "integrity": "sha512-ES8WeJ2fNWPEDunyAtUfJ12nHyaWUloCHdkfK2oW5uSoQSUmjNKdWiGaXJITJwvFEWoD/evHEg/QoCXAvLaQqQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/transform": "^29.7.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.6.3", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", + "@jest/transform": "30.5.2", + "@types/babel__core": "^7.20.5", + "babel-plugin-istanbul": "^8.0.0", + "babel-preset-jest": "30.5.0", + "chalk": "^4.1.2", + "graceful-fs": "^4.2.11", "slash": "^3.0.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { - "@babel/core": "^7.8.0" + "@babel/core": "^7.11.0 || ^8.0.0-0" } }, "node_modules/babel-jest/node_modules/ansi-styles": { @@ -2704,113 +3608,103 @@ } }, "node_modules/babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-8.0.0.tgz", + "integrity": "sha512-18wCskrN3DgbuBmp1gr7LBGT8xdz5xhQQqFvFhVxbkl8VBCrMKQ2YtqBWtUal1Zrc1HTuX0011+Brjw78TCFkg==", "dev": true, + "license": "BSD-3-Clause", + "workspaces": [ + "test/babel-8" + ], "dependencies": { "@babel/helper-plugin-utils": "^7.0.0", "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" + "@istanbuljs/schema": "^0.1.3", + "istanbul-lib-instrument": "^6.0.2", + "test-exclude": "^7.0.1" }, "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "bin": { - "semver": "bin/semver.js" + "node": ">=18" } }, "node_modules/babel-plugin-jest-hoist": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", - "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-30.5.0.tgz", + "integrity": "sha512-gtGo1B+u14jrZQv6TdSWIWkTqclboo7Qn+dFAGUOIuXLFuJKAdg3U5MIWzZnW4vfUb4dX9skmAMiby86e/SF4A==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" + "@types/babel__core": "^7.20.5" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/babel-preset-current-node-syntax": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.0.1.tgz", - "integrity": "sha512-M7LQ0bxarkxQoN+vz5aJPsLBn77n8QgTFmo8WK0/44auK2xlCXrYcUxHFxgU7qW5Yzw/CjmLRK2uJzaCd7LvqQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", + "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/plugin-syntax-async-generators": "^7.8.4", "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.8.3", - "@babel/plugin-syntax-import-meta": "^7.8.3", + "@babel/plugin-syntax-class-properties": "^7.12.13", + "@babel/plugin-syntax-class-static-block": "^7.14.5", + "@babel/plugin-syntax-import-attributes": "^7.24.7", + "@babel/plugin-syntax-import-meta": "^7.10.4", "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.8.3", + "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.8.3", + "@babel/plugin-syntax-numeric-separator": "^7.10.4", "@babel/plugin-syntax-object-rest-spread": "^7.8.3", "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-top-level-await": "^7.8.3" + "@babel/plugin-syntax-private-property-in-object": "^7.14.5", + "@babel/plugin-syntax-top-level-await": "^7.14.5" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^7.0.0 || ^8.0.0-0" } }, "node_modules/babel-preset-jest": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", - "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-30.5.0.tgz", + "integrity": "sha512-ZGPn5ClP4lBDpuOK8W1yQIOy359HmbnZv3suucAlIe+SEE9yDsxV4S2PjSbH2Vc97U+WmzYD7vw3kr8NsQ/i6w==", "dev": true, + "license": "MIT", "dependencies": { - "babel-plugin-jest-hoist": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0" + "babel-plugin-jest-hoist": "30.5.0", + "babel-preset-current-node-syntax": "^1.2.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { - "@babel/core": "^7.0.0" + "@babel/core": "^7.11.0 || ^8.0.0-beta.1 || ^8.0.0" } }, "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } }, - "node_modules/binary-extensions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "node_modules/baseline-browser-mapping": { + "version": "2.11.37", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.37.tgz", + "integrity": "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==", "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, "engines": { - "node": ">=8" + "node": ">=6.0.0" } }, "node_modules/bindings": { @@ -2818,6 +3712,7 @@ "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", "dev": true, + "license": "MIT", "dependencies": { "file-uri-to-path": "1.0.0" } @@ -2829,22 +3724,26 @@ "dev": true }, "node_modules/brace-expansion": { - "version": "1.1.11", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", - "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, + "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dev": true, + "license": "MIT", "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" @@ -2857,9 +3756,9 @@ "dev": true }, "node_modules/browserslist": { - "version": "4.23.0", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.23.0.tgz", - "integrity": "sha512-QW8HiM1shhT2GuzkvklfjcKDiWFXHOeFCIA/huJPwHsslwcydgk7X+z2zXpEijP98UCY7HbubZt5J2Zgvf0CaQ==", + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", "dev": true, "funding": [ { @@ -2875,11 +3774,13 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "caniuse-lite": "^1.0.30001587", - "electron-to-chromium": "^1.4.668", - "node-releases": "^2.0.14", - "update-browserslist-db": "^1.0.13" + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" @@ -2909,26 +3810,12 @@ "node-int64": "^0.4.0" } }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true - }, - "node_modules/cac": { - "version": "6.7.14", - "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz", - "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/callsites": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-4.1.0.tgz", - "integrity": "sha512-aBMbD1Xxay75ViYezwT40aQONfr+pSXTHwNKvIXhXD6+LY3F1dLIcceoC5OZKBVHbXcysz1hL9D2w0JJIMXpUw==", + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-4.2.0.tgz", + "integrity": "sha512-kfzR4zzQtAE9PC7CzZsjl3aBNbXWuXiSeOCdLcPpBfGW8YuCqQHcRPFDbr/BPVmd3EEPVpuFzLyuT/cUhPr4OQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=12.20" }, @@ -2937,21 +3824,19 @@ } }, "node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", "dev": true, + "license": "MIT", "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=6" } }, "node_modules/caniuse-lite": { - "version": "1.0.30001596", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001596.tgz", - "integrity": "sha512-zpkZ+kEr6We7w63ORkoJ2pOfBwBkY/bJrG/UZ90qNb45Isblu8wzDgevEOrRL1r9dWayHjYiiyCMEXPn4DweGQ==", + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", "dev": true, "funding": [ { @@ -2966,43 +3851,38 @@ "type": "github", "url": "https://github.com/sponsors/ai" } - ] + ], + "license": "CC-BY-4.0" }, "node_modules/cbor": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/cbor/-/cbor-9.0.2.tgz", - "integrity": "sha512-JPypkxsB10s9QOWwa6zwPzqE1Md3vqpPc+cai4sAecuCsRyAtAl/pMyhPlMbT/xtPnm2dznJZYRLui57qiRhaQ==", + "version": "10.0.12", + "resolved": "https://registry.npmjs.org/cbor/-/cbor-10.0.12.tgz", + "integrity": "sha512-exQDevYd7ZQLP4moMQcZkKCVZsXLAtUSflObr3xTh4xzFIv/xBCdvCd6L259kQOUP2kcTC0jvC6PpZIf/WmRXA==", "dev": true, + "license": "MIT", "dependencies": { - "nofilter": "^3.1.0" + "nofilter": "^3.0.2" }, "engines": { - "node": ">=16" + "node": ">=20" } }, "node_modules/chai": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.4.1.tgz", - "integrity": "sha512-13sOfMv2+DWduEU+/xbun3LScLoqN17nBeTLUsmDfKdoiC1fr0n9PU4guu4AhRcOVFk/sW8LyZWHuhWtQZiF+g==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", "dev": true, - "dependencies": { - "assertion-error": "^1.1.0", - "check-error": "^1.0.3", - "deep-eql": "^4.1.3", - "get-func-name": "^2.0.2", - "loupe": "^2.3.6", - "pathval": "^1.1.1", - "type-detect": "^4.0.8" - }, + "license": "MIT", "engines": { - "node": ">=4" + "node": ">=18" } }, "node_modules/chalk": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", - "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==", + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", "dev": true, + "license": "MIT", "engines": { "node": "^12.17.0 || ^14.13 || >=16.0.0" }, @@ -3015,56 +3895,35 @@ "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", "dev": true, + "license": "MIT", "engines": { - "node": ">=10" - } - }, - "node_modules/check-error": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", - "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", - "dev": true, - "dependencies": { - "get-func-name": "^2.0.2" - }, - "engines": { - "node": "*" + "node": ">=10" } }, "node_modules/chokidar": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", - "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://paulmillr.com/funding/" - } - ], + "license": "MIT", "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" + "readdirp": "^5.0.0" }, "engines": { - "node": ">= 8.10.0" + "node": ">= 20.19.0" }, - "optionalDependencies": { - "fsevents": "~2.3.2" + "funding": { + "url": "https://paulmillr.com/funding/" } }, "node_modules/chownr": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", - "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", "dev": true, + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/chunkd": { @@ -3074,9 +3933,9 @@ "dev": true }, "node_modules/ci-info": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.0.0.tgz", - "integrity": "sha512-TdHqgGf9odd8SXNuxtUBVx8Nv+qZOejE6qyqiy5NtbYYQOeFa6zmHkxlPzmaLxWWHsU6nJmB7AETdVPi+2NBUg==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.5.0.tgz", + "integrity": "sha512-d1uM8k5UZEyPza1n/MG3ko8nKupKN0KJpFsipgPcgaCCvV+IqIfJ+NzTjetlLM+UcXZx3+cLrNr76+eAO7G1Mw==", "dev": true, "funding": [ { @@ -3084,6 +3943,7 @@ "url": "https://github.com/sponsors/sibiraj-s" } ], + "license": "MIT", "engines": { "node": ">=8" } @@ -3095,16 +3955,18 @@ "dev": true }, "node_modules/cjs-module-lexer": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.2.3.tgz", - "integrity": "sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==", - "dev": true + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.3.0.tgz", + "integrity": "sha512-lmNyBzi6iYiqyrExTctfmjd8tInx+dHu9PBomTfH5RXS53c27JMFJgzNv5TyAnm3PgGf+MLy0+Ws41/HlVxdKQ==", + "dev": true, + "license": "MIT" }, "node_modules/cli-truncate": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz", "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==", "dev": true, + "license": "MIT", "dependencies": { "slice-ansi": "^5.0.0", "string-width": "^7.0.0" @@ -3121,6 +3983,7 @@ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", "dev": true, + "license": "ISC", "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", @@ -3135,6 +3998,7 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -3143,22 +4007,15 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/cliui/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, - "engines": { - "node": ">=8" - } + "license": "MIT" }, "node_modules/cliui/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -3173,6 +4030,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -3185,6 +4043,7 @@ "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", "dev": true, + "license": "MIT", "engines": { "iojs": ">= 1.0.0", "node": ">= 0.12.0" @@ -3203,10 +4062,11 @@ } }, "node_modules/collect-v8-coverage": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.2.tgz", - "integrity": "sha512-lHl4d5/ONEbLlJvaJNtsF/Lz+WvB07u2ycqTYbdrq7UypDXailES4valYb2eWiJFxZlVmpGekfqoxQhzyFdT4Q==", - "dev": true + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", + "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", + "dev": true, + "license": "MIT" }, "node_modules/color-convert": { "version": "2.0.1", @@ -3226,27 +4086,12 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, - "node_modules/color-support": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", - "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", - "dev": true, - "bin": { - "color-support": "bin.js" - } - }, "node_modules/common-path-prefix": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-3.0.0.tgz", "integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==", "dev": true }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true - }, "node_modules/concordance": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/concordance/-/concordance-5.0.4.tgz", @@ -3266,11 +4111,15 @@ "node": ">=10.18.0 <11 || >=12.14.0 <13 || >=14" } }, - "node_modules/console-control-strings": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", - "dev": true + "node_modules/consola": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/consola/-/consola-3.4.2.tgz", + "integrity": "sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^14.18.0 || >=16.10.0" + } }, "node_modules/convert-source-map": { "version": "2.0.0", @@ -3287,75 +4136,12 @@ "node": "^12.20.0 || ^14.13.1 || >=16.0.0" } }, - "node_modules/create-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", - "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", - "dev": true, - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "prompts": "^2.0.1" - }, - "bin": { - "create-jest": "bin/create-jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/create-jest/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/create-jest/node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/create-jest/node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, + "license": "MIT", "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -3390,12 +4176,13 @@ } }, "node_modules/debug": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, + "license": "MIT", "dependencies": { - "ms": "2.1.2" + "ms": "^2.1.3" }, "engines": { "node": ">=6.0" @@ -3406,29 +4193,12 @@ } } }, - "node_modules/debug/node_modules/ms": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "dev": true - }, - "node_modules/decamelize": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", - "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", - "dev": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/dedent": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.5.1.tgz", - "integrity": "sha512-+LxW+KLWxu3HW3M2w2ympwtqPrqYRzU8fqi6Fhd18fBALe15blJPI/I4+UHveMVG6lJqB4JNd4UG0S5cnVHwIg==", + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", + "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", "dev": true, + "license": "MIT", "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, @@ -3438,38 +4208,22 @@ } } }, - "node_modules/deep-eql": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", - "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", - "dev": true, - "dependencies": { - "type-detect": "^4.0.0" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/deepmerge": { "version": "4.3.1", "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } }, - "node_modules/delegates": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", - "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", - "dev": true - }, "node_modules/detect-libc": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz", - "integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "dev": true, + "license": "Apache-2.0", "engines": { "node": ">=8" } @@ -3479,39 +4233,41 @@ "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } }, "node_modules/diff": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", - "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-9.0.0.tgz", + "integrity": "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==", "dev": true, + "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" } }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", + "node_modules/eastasianwidth": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", + "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } + "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.4.696", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.4.696.tgz", - "integrity": "sha512-SOr0bHP52OvYg2chCsz/0+FUSMGFm8L8HKwPpx3cbwRY24EOemVJtbgTm+IFO8LzhcnPy+hXmTq7ZcZ8uUuaYg==", - "dev": true + "version": "1.5.486", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.486.tgz", + "integrity": "sha512-rpybw4Ac4ak/An6G1Me2+61xzwobowDGyuJe71QHHOVpkZv4fPVobsLl7WH6zHSKusAMpaHxGKTpOvpy7+r3dQ==", + "dev": true, + "license": "ISC" }, "node_modules/emittery": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-1.0.3.tgz", - "integrity": "sha512-tJdCJitoy2lrC2ldJcqN4vkqJ00lT+tOWNT1hBJjO/3FDMJa5TTIiYGCKGkn/WfCyOzUMObeohbVTj00fhiLiA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/emittery/-/emittery-1.2.1.tgz", + "integrity": "sha512-sFz64DCRjirhwHLxofFqxYQm6DCp6o0Ix7jwKQvuCHPn4GMRZNuBZyLPu9Ccmk/QSCAMZt6FOUqA8JZCQvA9fw==", "dev": true, + "license": "MIT", "engines": { "node": ">=14.16" }, @@ -3520,63 +4276,77 @@ } }, "node_modules/emoji-regex": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.3.0.tgz", - "integrity": "sha512-QpLs9D9v9kArv4lfDEgg1X/gN5XLnf/A6l9cs8SPZLRZR3ZkY9+kwIQTxm+fsSej5UMYGE8fdoaZVIBlqG0XTw==", - "dev": true + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "dev": true, + "license": "MIT" }, "node_modules/error-ex": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", - "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", + "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", "dev": true, + "license": "MIT", "dependencies": { "is-arrayish": "^0.2.1" } }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, "node_modules/esbuild": { - "version": "0.19.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.12.tgz", - "integrity": "sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg==", + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", "dev": true, "hasInstallScript": true, + "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, "engines": { - "node": ">=12" + "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.19.12", - "@esbuild/android-arm": "0.19.12", - "@esbuild/android-arm64": "0.19.12", - "@esbuild/android-x64": "0.19.12", - "@esbuild/darwin-arm64": "0.19.12", - "@esbuild/darwin-x64": "0.19.12", - "@esbuild/freebsd-arm64": "0.19.12", - "@esbuild/freebsd-x64": "0.19.12", - "@esbuild/linux-arm": "0.19.12", - "@esbuild/linux-arm64": "0.19.12", - "@esbuild/linux-ia32": "0.19.12", - "@esbuild/linux-loong64": "0.19.12", - "@esbuild/linux-mips64el": "0.19.12", - "@esbuild/linux-ppc64": "0.19.12", - "@esbuild/linux-riscv64": "0.19.12", - "@esbuild/linux-s390x": "0.19.12", - "@esbuild/linux-x64": "0.19.12", - "@esbuild/netbsd-x64": "0.19.12", - "@esbuild/openbsd-x64": "0.19.12", - "@esbuild/sunos-x64": "0.19.12", - "@esbuild/win32-arm64": "0.19.12", - "@esbuild/win32-ia32": "0.19.12", - "@esbuild/win32-x64": "0.19.12" + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" } }, "node_modules/escalade": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", - "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -3610,7 +4380,8 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/esutils": { "version": "2.0.3", @@ -3644,29 +4415,42 @@ "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", + "node_modules/exit-x": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/exit-x/-/exit-x-0.2.2.tgz", + "integrity": "sha512-+I6B/IkJc1o/2tiURyz/ivu/O0nKNEArIUB5O7zBrlDVJr22SCLH3xTeEry428LvFhRzIA1g8izguxJ/gbNcVQ==", "dev": true, + "license": "MIT", "engines": { "node": ">= 0.8.0" } }, "node_modules/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/expect/-/expect-30.5.2.tgz", + "integrity": "sha512-0LNuMvs8/5mRYhnCR4k+lGV7fqPMs6Bnksda4S3zsCUmdxBpAn4zU4NNzXdq1pMKe/H4W5t/zVIDSJ/H3e0vDA==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" + "@jest/expect-utils": "30.5.2", + "@jest/get-type": "30.5.0", + "jest-matcher-utils": "30.5.2", + "jest-message-util": "30.5.1", + "jest-mock": "30.5.2", + "jest-util": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" } }, "node_modules/fast-diff": { @@ -3676,16 +4460,17 @@ "dev": true }, "node_modules/fast-glob": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", - "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", "dev": true, + "license": "MIT", "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", - "micromatch": "^4.0.4" + "micromatch": "^4.0.8" }, "engines": { "node": ">=8.6.0" @@ -3698,10 +4483,11 @@ "dev": true }, "node_modules/fastq": { - "version": "1.17.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.17.1.tgz", - "integrity": "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w==", + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", "dev": true, + "license": "ISC", "dependencies": { "reusify": "^1.0.4" } @@ -3715,6 +4501,24 @@ "bser": "2.1.1" } }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/figures": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/figures/-/figures-6.1.0.tgz", @@ -3734,13 +4538,15 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dev": true, + "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" }, @@ -3749,26 +4555,25 @@ } }, "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", "dev": true, + "license": "MIT", "dependencies": { - "locate-path": "^6.0.0", + "locate-path": "^5.0.0", "path-exists": "^4.0.0" }, "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/find-up-simple": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/find-up-simple/-/find-up-simple-1.0.0.tgz", - "integrity": "sha512-q7Us7kcjj2VMePAa02hDAF6d+MzsdsAWEwYyOpwUtlerRBkOEPBCRZrAV4XfcSN8fHAgaD0hP7miwoay6DCprw==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/find-up-simple/-/find-up-simple-1.0.1.tgz", + "integrity": "sha512-afd4O7zpqHeRyg4PfDQsXmlDe2PfdHtJt6Akt8jOWaApLOZk5JXs6VMR29lz03pRe9mpykrRCYIYxaJYcfpncQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -3776,136 +4581,48 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/flat": { - "version": "5.0.2", - "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", - "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", - "dev": true, - "bin": { - "flat": "cli.js" - } - }, - "node_modules/fs-minipass": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", - "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "node_modules/foreground-child": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", + "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", "dev": true, + "license": "ISC", "dependencies": { - "minipass": "^3.0.0" + "cross-spawn": "^7.0.6", + "signal-exit": "^4.0.1" }, "engines": { - "node": ">= 8" - } - }, - "node_modules/fs-minipass/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "dev": true, - "dependencies": { - "yallist": "^4.0.0" + "node": ">=14" }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gauge": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", - "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", - "dev": true, - "dependencies": { - "aproba": "^1.0.3 || ^2.0.0", - "color-support": "^1.1.2", - "console-control-strings": "^1.0.0", - "has-unicode": "^2.0.1", - "object-assign": "^4.1.1", - "signal-exit": "^3.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1", - "wide-align": "^1.1.2" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/gauge/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/gauge/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/gauge/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "engines": { - "node": ">=8" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/gauge/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "node_modules/foreground-child/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", "dev": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, + "license": "ISC", "engines": { - "node": ">=8" + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/gauge/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], "engines": { - "node": ">=8" + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/gensync": { @@ -3922,15 +4639,17 @@ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", "dev": true, + "license": "ISC", "engines": { "node": "6.* || 8.* || >= 10.*" } }, "node_modules/get-east-asian-width": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.2.0.tgz", - "integrity": "sha512-2nk+7SIVb14QrgXFHcm84tD4bKQz0RxPuMT8Ag5KPOq7J5fEmAg0UbXdTOSHqNuHSU28k55qnceesxXRZGzKWA==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -3938,20 +4657,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/get-func-name": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", - "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", - "dev": true, - "engines": { - "node": "*" - } - }, "node_modules/get-package-type": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8.0.0" } @@ -3968,33 +4679,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/get-tsconfig": { - "version": "4.7.3", - "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.7.3.tgz", - "integrity": "sha512-ZvkrzoUA0PQZM6fy6+/Hce561s+faD1rsNwhnO5FelNjyy7EMGJ3Rz1AQ8GYDWjhRs/7dBLOEJvhK8MiEJOAFg==", - "dev": true, - "dependencies": { - "resolve-pkg-maps": "^1.0.0" - }, - "funding": { - "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" - } - }, "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "version": "13.0.7", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.7.tgz", + "integrity": "sha512-wfsFgXQ8A3SEI9XGf7Nl3Y9l7ffSrGh7SUCT7vU/2CzYPep9kjxAn1S40F9OPKxAMGCVl7HtNlJhrCJUeUq83g==", "dev": true, + "license": "BlueOak-1.0.0", "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" }, "engines": { - "node": "*" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -4005,6 +4702,7 @@ "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, + "license": "ISC", "dependencies": { "is-glob": "^4.0.1" }, @@ -4012,27 +4710,19 @@ "node": ">= 6" } }, - "node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/globby": { - "version": "14.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-14.0.1.tgz", - "integrity": "sha512-jOMLD2Z7MAhyG8aJpNOpmziMOP4rPLcc95oQPKXBazW82z+CEgPFBQvEpRUa1KeIMUJo4Wsm+q6uzO/Q/4BksQ==", + "version": "14.1.0", + "resolved": "https://registry.npmjs.org/globby/-/globby-14.1.0.tgz", + "integrity": "sha512-0Ia46fDOaT7k4og1PDW4YbodWWr3scS2vAr2lTbsplOt2WkKp0vQbkI9wKis/T5LV/dqPjO3bpS/z6GTJB82LA==", "dev": true, + "license": "MIT", "dependencies": { "@sindresorhus/merge-streams": "^2.1.0", - "fast-glob": "^3.3.2", - "ignore": "^5.2.4", - "path-type": "^5.0.0", + "fast-glob": "^3.3.3", + "ignore": "^7.0.3", + "path-type": "^6.0.0", "slash": "^5.1.0", - "unicorn-magic": "^0.1.0" + "unicorn-magic": "^0.3.0" }, "engines": { "node": ">=18" @@ -4047,59 +4737,56 @@ "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", "dev": true }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/has-unicode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", - "dev": true - }, - "node_modules/hasown": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz", - "integrity": "sha512-1/th4MHjnwncwXsIW6QMzlvYL9kG5e/CpVvLRZe4XPa8TOUNbCELqmvhDmnkNsAjwaG4+I8gJJL0JBvTTLO9qA==", + "node_modules/handlebars": { + "version": "4.7.10", + "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.10.tgz", + "integrity": "sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==", "dev": true, + "license": "MIT", "dependencies": { - "function-bind": "^1.1.2" + "minimist": "^1.2.8", + "neo-async": "^2.6.2", + "source-map": "^0.6.1", + "wordwrap": "^1.0.0" + }, + "bin": { + "handlebars": "bin/handlebars" }, "engines": { - "node": ">= 0.4" + "node": ">=0.4.7" + }, + "optionalDependencies": { + "uglify-js": "^3.1.4" } }, - "node_modules/he": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", - "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", "dev": true, - "bin": { - "he": "bin/he" + "engines": { + "node": ">=8" } }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", "dev": true, + "license": "MIT", "dependencies": { - "agent-base": "6", + "agent-base": "^7.1.2", "debug": "4" }, "engines": { - "node": ">= 6" + "node": ">= 14" } }, "node_modules/human-signals": { @@ -4112,10 +4799,11 @@ } }, "node_modules/ignore": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.1.tgz", - "integrity": "sha512-5Fytz/IraMjqpwfd34ke28PTVMjZjJG2MPn5t7OE4eUCUNf8BAa7b5WUS9/Qvr6mwOQS7Mk6vdsMno5he+T8Xw==", + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz", + "integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==", "dev": true, + "license": "MIT", "engines": { "node": ">= 4" } @@ -4130,10 +4818,11 @@ } }, "node_modules/import-local": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.1.0.tgz", - "integrity": "sha512-ASB07uLtnDs1o6EHjKpX34BKYDSqnFerfTOJL2HvMqF70LnxpjkzDB8J44oT9pu4AMPkQwf8jl6szgvNd2tRIg==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", + "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", "dev": true, + "license": "MIT", "dependencies": { "pkg-dir": "^4.2.0", "resolve-cwd": "^3.0.0" @@ -4153,6 +4842,7 @@ "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.8.19" } @@ -4169,27 +4859,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "dev": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true - }, "node_modules/irregular-plurals": { "version": "3.5.0", "resolved": "https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-3.5.0.tgz", "integrity": "sha512-1ANGLZ+Nkv1ptFb2pa8oG8Lem4krflKuX/gINiHJHjJUKaJHk/SXk5x6K3J+39/p0h1RQ2saROclJJ+QLvETCQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -4198,51 +4873,27 @@ "version": "0.2.1", "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true - }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-core-module": { - "version": "2.13.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.13.1.tgz", - "integrity": "sha512-hHrIjvZsftOsvKSn2TRYl63zvxsgE0K+0mYMoH6gD4omR5IWB2KynivBQczo3+wF1cCkjzvptnI9Q0sPU66ilw==", "dev": true, - "dependencies": { - "hasown": "^2.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } + "license": "MIT" }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } }, "node_modules/is-fullwidth-code-point": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", - "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, + "license": "MIT", "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/is-generator-fn": { @@ -4250,6 +4901,7 @@ "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -4259,6 +4911,7 @@ "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", "dev": true, + "license": "MIT", "dependencies": { "is-extglob": "^2.1.1" }, @@ -4271,24 +4924,30 @@ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.12.0" } }, - "node_modules/is-plain-obj": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", - "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", + "node_modules/is-path-inside": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-4.0.0.tgz", + "integrity": "sha512-lJJV/5dYS+RcL8uQdBDW9c9uWFLLBNRyFhnAKXw5tVqLlKZ4RMGZKv+YQ/IA3OhD+RpbJa1LLFM1FQPGyIXvOA==", "dev": true, + "license": "MIT", "engines": { - "node": ">=8" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-plain-object": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", - "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.1.0.tgz", + "integrity": "sha512-bUi/yjmtKYcRVUtWRGr0UA6xEFh2I6zWUwMrUXB3s7bmYCaZ8a+0ZsTRkrawh/mzlSD1Y0Ph8bp/U+TvBpWDNw==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } @@ -4339,10 +4998,11 @@ } }, "node_modules/istanbul-lib-instrument": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.2.tgz", - "integrity": "sha512-1WUsZ9R1lA0HtBSohTkm39WTPlNKSJ5iFk7UwqXkBLoHQT+hfqPsfsTDVuZdKGaBwn7din9bS7SsnoAr943hvw==", + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", + "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "@babel/core": "^7.23.9", "@babel/parser": "^7.23.9", @@ -4359,6 +5019,7 @@ "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "istanbul-lib-coverage": "^3.0.0", "make-dir": "^4.0.0", @@ -4368,26 +5029,12 @@ "node": ">=10" } }, - "node_modules/istanbul-lib-report/node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/istanbul-lib-report/node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4396,24 +5043,26 @@ } }, "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" + "istanbul-lib-coverage": "^3.0.0" }, "engines": { "node": ">=10" } }, "node_modules/istanbul-reports": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.1.7.tgz", - "integrity": "sha512-BewmUXImeuRk2YY0PVbxgKAysvhRPUQE0h5QRM++nVWyubKGV0l8qQ5op8+B2DOmwSe63Jivj0BjkPQVf8fP5g==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", "dev": true, + "license": "BSD-3-Clause", "dependencies": { "html-escaper": "^2.0.0", "istanbul-lib-report": "^3.0.0" @@ -4422,22 +5071,39 @@ "node": ">=8" } }, + "node_modules/jackspeak": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", + "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, "node_modules/jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", - "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest/-/jest-30.5.2.tgz", + "integrity": "sha512-3gnpdBIza8ijCl3iMV9ChE3hSt1+46865qqod863gQtJr1DixOkAU5DoGbi3u+XlRcw++BhZQMu/y4xBdHBvSQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/core": "^29.7.0", - "@jest/types": "^29.6.3", - "import-local": "^3.0.2", - "jest-cli": "^29.7.0" + "@jest/core": "30.5.2", + "@jest/types": "30.5.1", + "import-local": "^3.2.0", + "jest-cli": "30.5.2" }, "bin": { "jest": "bin/jest.js" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -4449,48 +5115,50 @@ } }, "node_modules/jest-changed-files": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", - "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-30.5.1.tgz", + "integrity": "sha512-0+bvMM/ENhDI29Z8q1r4HxiDIi4G5tnBmSw4esfPQoj9q8Nik7KIyuxHkTVnnniJQf05SxpGaKDQ+4h28ynGPg==", "dev": true, + "license": "MIT", "dependencies": { - "execa": "^5.0.0", - "jest-util": "^29.7.0", + "execa": "^5.1.1", + "jest-util": "30.5.1", "p-limit": "^3.1.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-circus": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", - "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-30.5.2.tgz", + "integrity": "sha512-vffFgjs5JSJ9q4ds1vNW3klKYPJfYfIY61LT/zaZgvTeASJOWZUt8LBfHgIcV4rwxlPBLl/ePBGccHEclS4PlQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", + "@jest/environment": "30.5.2", + "@jest/expect": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "chalk": "^4.0.0", + "chalk": "^4.1.2", "co": "^4.6.0", - "dedent": "^1.0.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.7.0", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", + "dedent": "^1.6.0", + "is-generator-fn": "^2.1.0", + "jest-each": "30.5.2", + "jest-matcher-utils": "30.5.2", + "jest-message-util": "30.5.1", + "jest-runtime": "30.5.2", + "jest-snapshot": "30.5.2", + "jest-util": "30.5.1", "p-limit": "^3.1.0", - "pretty-format": "^29.7.0", - "pure-rand": "^6.0.0", + "pretty-format": "30.5.1", + "pure-rand": "^7.0.0", "slash": "^3.0.0", - "stack-utils": "^2.0.3" + "stack-utils": "^2.0.6" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-circus/node_modules/ansi-styles": { @@ -4498,6 +5166,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4513,6 +5182,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -4529,6 +5199,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -4538,6 +5209,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4546,28 +5218,28 @@ } }, "node_modules/jest-cli": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", - "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", - "dev": true, - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "create-jest": "^29.7.0", - "exit": "^0.1.2", - "import-local": "^3.0.2", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "yargs": "^17.3.1" + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-30.5.2.tgz", + "integrity": "sha512-YYYxUUVjFgPvgEleKNKMaYGIFgR3l3832Cl0kRL/oCiDZ03v7wImUtquHl2OOBCCNgprjZgBN5bczS/JklPBDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/core": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/types": "30.5.1", + "chalk": "^4.1.2", + "exit-x": "^0.2.2", + "import-local": "^3.2.0", + "jest-config": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", + "yargs": "^17.7.2" }, "bin": { "jest": "bin/jest.js" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" @@ -4583,6 +5255,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4598,6 +5271,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -4614,6 +5288,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4622,45 +5297,51 @@ } }, "node_modules/jest-config": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", - "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-jest": "^29.7.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "micromatch": "^4.0.4", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-30.5.2.tgz", + "integrity": "sha512-U6221OZekabePvGcGPf4raIBKMvYQWFHvhobDJRojOYaFMj2HaGytAdknjDhYc6JTz2fdHW9+6k0wWUDaNeOFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.27.4", + "@jest/get-type": "30.5.0", + "@jest/pattern": "30.5.0", + "@jest/test-sequencer": "30.5.2", + "@jest/types": "30.5.1", + "babel-jest": "30.5.2", + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "deepmerge": "^4.3.1", + "glob": "^13.0.6", + "graceful-fs": "^4.2.11", + "jest-circus": "30.5.2", + "jest-docblock": "30.5.0", + "jest-environment-node": "30.5.2", + "jest-regex-util": "30.5.0", + "jest-resolve": "30.5.1", + "jest-runner": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", "parse-json": "^5.2.0", - "pretty-format": "^29.7.0", + "pretty-format": "30.5.1", "slash": "^3.0.0", "strip-json-comments": "^3.1.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { "@types/node": "*", + "esbuild-register": ">=3.4.0", "ts-node": ">=9.0.0" }, "peerDependenciesMeta": { "@types/node": { "optional": true }, + "esbuild-register": { + "optional": true + }, "ts-node": { "optional": true } @@ -4671,6 +5352,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4686,6 +5368,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -4697,26 +5380,12 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/jest-config/node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "engines": { - "node": ">=8" - } - }, "node_modules/jest-config/node_modules/slash": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -4726,6 +5395,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4734,18 +5404,19 @@ } }, "node_modules/jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.5.2.tgz", + "integrity": "sha512-rBtHnI6BWTiWj3lM7fOLVfChx7R9B0u9VV3PRHawKs79x6ZjW1QoSrKenaigNGWlvhtoi2BqvDbABDie+Os3xQ==", "dev": true, + "license": "MIT", "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" + "@jest/diff-sequences": "30.5.0", + "@jest/get-type": "30.5.0", + "chalk": "^4.1.2", + "pretty-format": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-diff/node_modules/ansi-styles": { @@ -4753,6 +5424,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4768,6 +5440,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -4784,6 +5457,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4792,31 +5466,34 @@ } }, "node_modules/jest-docblock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", - "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-30.5.0.tgz", + "integrity": "sha512-NwDqcxtoZi33RhuW+zJS/RVA3rmheQ8BnwpYZuc/Eruaz6seQb7+aoCeDZu/3X7W2XmD8DbSo9Pn72DbKsBFYw==", "dev": true, + "license": "MIT", "dependencies": { - "detect-newline": "^3.0.0" + "detect-newline": "^3.1.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-each": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", - "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-30.5.2.tgz", + "integrity": "sha512-GRrW+7fmmgmkvyfEBqc1QFdWnF1Ex5yG6Y6AWL4TTxnkWlKIT98dsKh3P3UuWm6v4XsQwVE6DEzXIPMzWJ3ZbA==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "jest-util": "^29.7.0", - "pretty-format": "^29.7.0" + "@jest/get-type": "30.5.0", + "@jest/types": "30.5.1", + "chalk": "^4.1.2", + "jest-regex-util": "30.5.0", + "jest-util": "30.5.1", + "pretty-format": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-each/node_modules/ansi-styles": { @@ -4824,6 +5501,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4839,6 +5517,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -4855,6 +5534,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4863,82 +5543,75 @@ } }, "node_modules/jest-environment-node": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", - "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-30.5.2.tgz", + "integrity": "sha512-Ciz4KgTGIbojxSKpuFImgWJj5EyqfE8xMq9NxWmOXnQywHHS03H9Mv+vaCB29J5pr3JBrY27WbRV18rBdjh8Dg==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", + "@jest/environment": "30.5.2", + "@jest/fake-timers": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" + "jest-mock": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", - "dev": true, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-haste-map": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", - "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-30.5.1.tgz", + "integrity": "sha512-VIFgt67jW480YDxKfEv9IYQKrFpYt7bOCMn3VsnjK7AK9qo7p6acpnA1DHwsVOULE3dTaYew/6JaTD/d0VDHoQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", - "@types/graceful-fs": "^4.1.3", + "@jest/types": "30.5.1", + "@parcel/watcher": "^2.6.0", "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" + "anymatch": "^3.1.3", + "fb-watchman": "^2.0.2", + "fdir": "^6.5.0", + "graceful-fs": "^4.2.11", + "jest-regex-util": "30.5.0", + "jest-util": "30.5.1", + "jest-worker": "30.5.1", + "picomatch": "^4.0.3" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "optionalDependencies": { - "fsevents": "^2.3.2" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-leak-detector": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", - "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-30.5.1.tgz", + "integrity": "sha512-gt4GT2aWgEoCNTcBe4rqS74xTIUJxi+UD9SNSu9aOk5LmTEd6fS5KSTmAKAfitCCktQHNN+upUuL6EkBfFbMDQ==", "dev": true, + "license": "MIT", "dependencies": { - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" + "@jest/get-type": "30.5.0", + "pretty-format": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.5.2.tgz", + "integrity": "sha512-lFkB365PTIHOhPzwrb9T6gvlDnPpOZ7/c3ewOKKB7bzztqjVrtlyRL2MkyfJXpyY2u2SKw001JKrTx14fBUFcQ==", "dev": true, + "license": "MIT", "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" + "@jest/get-type": "30.5.0", + "chalk": "^4.1.2", + "jest-diff": "30.5.2", + "pretty-format": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-matcher-utils/node_modules/ansi-styles": { @@ -4946,6 +5619,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -4961,6 +5635,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -4977,6 +5652,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -4985,23 +5661,25 @@ } }, "node_modules/jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.1.tgz", + "integrity": "sha512-UdQlLdd9wL/Ys7xRErckqwD6wPlSZYueosSWuHc1r2ztGLwlgPvtSJq2+BPEgaEY13WLvfFbmhTj8pba0Sd1jg==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", + "@babel/code-frame": "^7.27.1", + "@jest/types": "30.5.1", + "@types/stack-utils": "^2.0.3", + "chalk": "^4.1.2", + "graceful-fs": "^4.2.11", + "jest-util": "30.5.1", + "picomatch": "^4.0.3", + "pretty-format": "30.5.1", "slash": "^3.0.0", - "stack-utils": "^2.0.3" + "stack-utils": "^2.0.6" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-message-util/node_modules/ansi-styles": { @@ -5009,6 +5687,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5024,6 +5703,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5040,6 +5720,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -5049,6 +5730,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5057,76 +5739,62 @@ } }, "node_modules/jest-mock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", - "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-30.5.2.tgz", + "integrity": "sha512-KTHb37Fhj8xY8qPFvTFaFJHcdsumQp+ExsUlgoX232Agmc706gagBs53+CYvulV7MVQo9AgXOUxsqzzVBoJlrA==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", + "@jest/expect-utils": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "jest-util": "^29.7.0" + "jest-util": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-regex-util": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", - "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.5.0.tgz", + "integrity": "sha512-Mg0WK7A6xRHLSA1udJ8y9f3lM0uUhFTBnLKzwPmqB9AylvpleJ6BLemR8K9dK27DY+cesDryoA7yLZCAHsPG1A==", "dev": true, + "license": "MIT", "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-resolve": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", - "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-30.5.1.tgz", + "integrity": "sha512-wprhLejRtwN6h8ZgaqC0eYjGJ1uMdGPT/+b3eFncbG4NWuuP9QL+vWwRinu9waw7hkOLcpMJGVJAMgBwsPssMQ==", "dev": true, + "license": "MIT", "dependencies": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" + "chalk": "^4.1.2", + "graceful-fs": "^4.2.11", + "jest-haste-map": "30.5.1", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", + "slash": "^3.0.0", + "unrs-resolver": "^1.12.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-resolve-dependencies": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", - "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-30.5.2.tgz", + "integrity": "sha512-GMI0DP5enX9Z2qW2zFy1bOkrCfWAOPRJQ7qHt0pdfrxBPsgWxglMPrRSK2TX/wRWYxcPRSLFg3Z88qPOzHx7FQ==", "dev": true, + "license": "MIT", "dependencies": { - "jest-regex-util": "^29.6.3", - "jest-snapshot": "^29.7.0" + "jest-regex-util": "30.5.0", + "jest-snapshot": "30.5.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-resolve/node_modules/ansi-styles": { @@ -5134,6 +5802,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5149,6 +5818,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5165,6 +5835,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -5174,6 +5845,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5182,35 +5854,37 @@ } }, "node_modules/jest-runner": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", - "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-30.5.2.tgz", + "integrity": "sha512-/B6px7hiiNhVSRwuv9AGn0nawYvwsHeQZ3ItTd5Gp2diFd0EOKaWVeWqcbw3L88vx1GfpCKjQkxWItZCTl11Rw==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/console": "^29.7.0", - "@jest/environment": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", + "@jest/console": "30.5.2", + "@jest/environment": "30.5.2", + "@jest/source-map": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "chalk": "^4.0.0", + "chalk": "^4.1.2", "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-leak-detector": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-resolve": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-util": "^29.7.0", - "jest-watcher": "^29.7.0", - "jest-worker": "^29.7.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" + "exit-x": "^0.2.2", + "graceful-fs": "^4.2.11", + "jest-docblock": "30.5.0", + "jest-environment-node": "30.5.2", + "jest-haste-map": "30.5.1", + "jest-leak-detector": "30.5.1", + "jest-message-util": "30.5.1", + "jest-resolve": "30.5.1", + "jest-runtime": "30.5.2", + "jest-util": "30.5.1", + "jest-watcher": "30.5.2", + "jest-worker": "30.5.1", + "p-limit": "^3.1.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-runner/node_modules/ansi-styles": { @@ -5218,6 +5892,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5233,6 +5908,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5249,6 +5925,7 @@ "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=12" }, @@ -5261,6 +5938,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5269,36 +5947,38 @@ } }, "node_modules/jest-runtime": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", - "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", - "dev": true, - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/globals": "^29.7.0", - "@jest/source-map": "^29.6.3", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-30.5.2.tgz", + "integrity": "sha512-0paUAHBlheai10A3XSy9Xh+YBG0IROy+/qzcDPzQ/nbbXrznQzeWy5qniICWK6d3W3scaRQCVAbXdcK0ibBq4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/environment": "30.5.2", + "@jest/fake-timers": "30.5.2", + "@jest/globals": "30.5.2", + "@jest/source-map": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", + "chalk": "^4.1.2", + "cjs-module-lexer": "^2.2.0", + "collect-v8-coverage": "^1.0.2", + "es-module-lexer": "^2.1.0", + "glob": "^13.0.6", + "graceful-fs": "^4.2.11", + "jest-haste-map": "30.5.1", + "jest-message-util": "30.5.1", + "jest-mock": "30.5.2", + "jest-regex-util": "30.5.0", + "jest-resolve": "30.5.1", + "jest-snapshot": "30.5.2", + "jest-util": "30.5.1", "slash": "^3.0.0", "strip-bom": "^4.0.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-runtime/node_modules/ansi-styles": { @@ -5306,6 +5986,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5321,6 +6002,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5337,6 +6019,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -5346,6 +6029,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5354,34 +6038,36 @@ } }, "node_modules/jest-snapshot": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", - "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, - "dependencies": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.7.0", - "semver": "^7.5.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-30.5.2.tgz", + "integrity": "sha512-jKIdes25AnAH73dOCi2qE6J6vHJ6L2vyBS11M89kT50DVJcLTf2AOjvcc+2vVaN8lUbY5v2R83aqXo3Ro9fqYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.27.4", + "@babel/generator": "^7.27.5", + "@babel/plugin-syntax-jsx": "^7.27.1", + "@babel/plugin-syntax-typescript": "^7.27.1", + "@babel/types": "^7.27.3", + "@jest/expect-utils": "30.5.2", + "@jest/get-type": "30.5.0", + "@jest/snapshot-utils": "30.5.1", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", + "babel-preset-current-node-syntax": "^1.2.0", + "chalk": "^4.1.2", + "expect": "30.5.2", + "graceful-fs": "^4.2.11", + "jest-diff": "30.5.2", + "jest-matcher-utils": "30.5.2", + "jest-message-util": "30.5.1", + "jest-util": "30.5.1", + "pretty-format": "30.5.1", + "semver": "^7.7.2", + "synckit": "^0.11.8" + }, + "engines": { + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-snapshot/node_modules/ansi-styles": { @@ -5389,6 +6075,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5404,6 +6091,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5420,6 +6108,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5428,20 +6117,21 @@ } }, "node_modules/jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.5.1.tgz", + "integrity": "sha512-yKuxmNy2rSbTXw+3SIPanJo+nV4/BS1p26v44IYBFMsswSQySfMMcPHErnOncda7i9HEz0q605rIhSTBVgrZTg==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", + "@jest/types": "30.5.1", "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" + "chalk": "^4.1.2", + "ci-info": "^4.2.0", + "graceful-fs": "^4.2.11", + "picomatch": "^4.0.3" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-util/node_modules/ansi-styles": { @@ -5475,33 +6165,6 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/jest-util/node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "engines": { - "node": ">=8" - } - }, - "node_modules/jest-util/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/jest-util/node_modules/supports-color": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", @@ -5515,20 +6178,21 @@ } }, "node_modules/jest-validate": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", - "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-30.5.1.tgz", + "integrity": "sha512-i/buJ56wTpxihE93hQYNMfdOThS87+HGvLZzZJmU4xggPcdTYQq051iwALLCHp3q+SkCGH+EFejQZz5EbBSkkg==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/types": "^29.6.3", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", + "@jest/get-type": "30.5.0", + "@jest/types": "30.5.1", + "camelcase": "^6.3.0", + "chalk": "^4.1.2", "leven": "^3.1.0", - "pretty-format": "^29.7.0" + "pretty-format": "30.5.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-validate/node_modules/ansi-styles": { @@ -5536,6 +6200,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5546,11 +6211,25 @@ "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, + "node_modules/jest-validate/node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/jest-validate/node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5567,6 +6246,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5575,22 +6255,23 @@ } }, "node_modules/jest-watcher": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", - "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-30.5.2.tgz", + "integrity": "sha512-rqRgg4R11GA9m1UsEZwQeixHsgZReCn6TOHAHtIH33yXrIvoX0OGPA20Yzzjkz7X40fZvcRSxEpQppYPcWzmcQ==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", + "@jest/test-result": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", + "ansi-escapes": "^4.3.2", + "chalk": "^4.1.2", "emittery": "^0.13.1", - "jest-util": "^29.7.0", - "string-length": "^4.0.1" + "jest-util": "30.5.1", + "string-length": "^4.0.2" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-watcher/node_modules/ansi-styles": { @@ -5598,6 +6279,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -5613,6 +6295,7 @@ "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" @@ -5629,6 +6312,7 @@ "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=12" }, @@ -5641,6 +6325,7 @@ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", "dev": true, + "license": "MIT", "dependencies": { "has-flag": "^4.0.0" }, @@ -5649,18 +6334,20 @@ } }, "node_modules/jest-worker": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", - "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-30.5.1.tgz", + "integrity": "sha512-Cbxh5v7AoLuFRmFJSM4/aHdQ68rjXvUWr716EE0Dh3I7T+T/3FgFKhOERGXHcU2Meftq9+9zxPM3TSNyI9D+HA==", "dev": true, + "license": "MIT", "dependencies": { "@types/node": "*", - "jest-util": "^29.7.0", + "@ungap/structured-clone": "^1.3.0", + "jest-util": "30.5.1", "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" + "supports-color": "^8.1.1" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/js-string-escape": { @@ -5676,13 +6363,15 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -5692,22 +6381,24 @@ } }, "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", "dev": true, + "license": "MIT", "bin": { "jsesc": "bin/jsesc" }, "engines": { - "node": ">=4" + "node": ">=6" } }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/json5": { "version": "2.2.3", @@ -5721,239 +6412,382 @@ "node": ">=6" } }, - "node_modules/jsonc-parser": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.2.1.tgz", - "integrity": "sha512-AilxAyFOAcK5wA1+LeaySVBrHsGQvUFCDWXKpZjzaL0PqW+xfBOttn8GNtWKFWqneyMZj41MWF9Kl6iPWLwgOA==", - "dev": true - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true, - "engines": { - "node": ">=6" - } - }, "node_modules/leven": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true - }, - "node_modules/load-json-file": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-7.0.1.tgz", - "integrity": "sha512-Gnxj3ev3mB5TkVBGad0JM6dmLiQL+o0t23JPBZ9sd+yvSLk05mFoqKBw5N8gbbkU4TNXyqCgIrl/VM17OgUIgQ==", + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/local-pkg": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/local-pkg/-/local-pkg-0.5.0.tgz", - "integrity": "sha512-ok6z3qlYyCDS4ZEU27HaU6x/xZa9Whf8jD4ptH5UZTQYZVYeb9bnZ3ojVhiJNLiXK1Hfc0GNbLXcmZ5plLDDBg==", + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], "dev": true, - "dependencies": { - "mlly": "^1.4.2", - "pkg-types": "^1.0.3" - }, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, "engines": { - "node": ">=14" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/sponsors/antfu" + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], "dev": true, - "dependencies": { - "p-locate": "^5.0.0" - }, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, "engines": { - "node": ">=10" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", - "dev": true + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } }, - "node_modules/log-symbols": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", - "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], "dev": true, - "dependencies": { - "chalk": "^4.1.0", - "is-unicode-supported": "^0.1.0" + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, "engines": { - "node": ">=10" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/log-symbols/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], "dev": true, - "dependencies": { - "color-convert": "^2.0.1" + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, "engines": { - "node": ">=8" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/log-symbols/node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], "dev": true, - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, "engines": { - "node": ">=10" + "node": ">= 12.0.0" }, "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" + "type": "opencollective", + "url": "https://opencollective.com/parcel" } }, - "node_modules/log-symbols/node_modules/is-unicode-supported": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", - "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/load-json-file": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-7.0.1.tgz", + "integrity": "sha512-Gnxj3ev3mB5TkVBGad0JM6dmLiQL+o0t23JPBZ9sd+yvSLk05mFoqKBw5N8gbbkU4TNXyqCgIrl/VM17OgUIgQ==", "dev": true, "engines": { - "node": ">=10" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/log-symbols/node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", "dev": true, + "license": "MIT", "dependencies": { - "has-flag": "^4.0.0" + "p-locate": "^4.1.0" }, "engines": { "node": ">=8" } }, - "node_modules/loupe": { - "version": "2.3.7", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", - "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", "dev": true, - "dependencies": { - "get-func-name": "^2.0.1" - } + "license": "MIT" + }, + "node_modules/lodash.memoize": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", + "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", + "dev": true }, "node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", "dev": true, - "dependencies": { - "yallist": "^4.0.0" - }, + "license": "BlueOak-1.0.0", "engines": { - "node": ">=10" + "node": "20 || >=22" } }, "node_modules/magic-string": { - "version": "0.30.8", - "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.8.tgz", - "integrity": "sha512-ISQTe55T2ao7XtlAStud6qwYPZjE4GK1S/BeVPus4jrq6JuOnQ00YKQC581RWhR122W7msZV263KzVeLoqidyQ==", + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", "dev": true, + "license": "MIT", "dependencies": { - "@jridgewell/sourcemap-codec": "^1.4.15" - }, - "engines": { - "node": ">=12" + "@jridgewell/sourcemap-codec": "^1.6.0" } }, "node_modules/make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", "dev": true, + "license": "MIT", "dependencies": { - "semver": "^6.0.0" + "semver": "^7.5.3" }, "engines": { - "node": ">=8" + "node": ">=10" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/make-dir/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "bin": { - "semver": "bin/semver.js" - } - }, "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "dev": true }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "dependencies": { - "tmpl": "1.0.5" - } - }, "node_modules/matcher": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/matcher/-/matcher-5.0.0.tgz", "integrity": "sha512-s2EMBOWtXFc8dgqvoAzKJXxNHibcdJMV0gwqKUaw9E2JBJuGUK7DrNKrA6g/i+v72TT16+6sVm5mS3thaMLQUw==", "dev": true, + "license": "MIT", "dependencies": { "escape-string-regexp": "^5.0.0" }, @@ -5977,12 +6811,13 @@ } }, "node_modules/memoize": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/memoize/-/memoize-10.0.0.tgz", - "integrity": "sha512-H6cBLgsi6vMWOcCpvVCdFFnl3kerEXbrYh9q+lY6VXvQSmM6CkmV08VOwT+WE2tzIEqRPFfAq3fm4v/UIW6mSA==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/memoize/-/memoize-10.2.0.tgz", + "integrity": "sha512-DeC6b7QBrZsRs3Y02A6A7lQyzFbsQbqgjI6UW0GigGWV+u1s25TycMr0XHZE4cJce7rY/vyw2ctMQqfDkIhUEA==", "dev": true, + "license": "MIT", "dependencies": { - "mimic-function": "^5.0.0" + "mimic-function": "^5.0.1" }, "engines": { "node": ">=18" @@ -6002,17 +6837,19 @@ "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", "dev": true, + "license": "MIT", "engines": { "node": ">= 8" } }, "node_modules/micromatch": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.5.tgz", - "integrity": "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dev": true, + "license": "MIT", "dependencies": { - "braces": "^3.0.2", + "braces": "^3.0.3", "picomatch": "^2.3.1" }, "engines": { @@ -6020,10 +6857,11 @@ } }, "node_modules/micromatch/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", "dev": true, + "license": "MIT", "engines": { "node": ">=8.6" }, @@ -6031,23 +6869,12 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/mimic-fn": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", - "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/mimic-function": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.0.tgz", - "integrity": "sha512-RBfQ+9X9DpXdEoK7Bu+KeEU6vFhumEIiXKWECPzRBmDserEq4uR2b/VCm0LwpMSosoq2k+Zuxj/GzOr0Fn6h/g==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -6056,156 +6883,108 @@ } }, "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^1.1.7" + "brace-expansion": "^5.0.8" }, "engines": { - "node": "*" + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/minipass": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", - "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", "dev": true, - "engines": { - "node": ">=8" + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/minizlib": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", - "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", "dev": true, - "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - }, + "license": "BlueOak-1.0.0", "engines": { - "node": ">= 8" + "node": ">=16 || 14 >=14.17" } }, - "node_modules/minizlib/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", "dev": true, + "license": "MIT", "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "dev": true, - "bin": { - "mkdirp": "bin/cmd.js" + "minipass": "^7.1.2" }, "engines": { - "node": ">=10" + "node": ">= 18" } }, - "node_modules/mlly": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/mlly/-/mlly-1.6.1.tgz", - "integrity": "sha512-vLgaHvaeunuOXHSmEbZ9izxPx3USsk8KCQ8iC+aTlp5sKRSoZvwhHh5L9VbKSaVC6sJDqbyohIS76E2VmHIPAA==", + "node_modules/mocha": { + "version": "12.0.3", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-12.0.3.tgz", + "integrity": "sha512-beammieDdiWdkjANWeWPpkxUROYGi5FN88fPOkLiticz7HTg3Y+Pho3EYE6SUdcuWnZ3h2WD8EXCA55JF4o6wg==", "dev": true, + "license": "MIT", "dependencies": { - "acorn": "^8.11.3", - "pathe": "^1.1.2", - "pkg-types": "^1.0.3", - "ufo": "^1.3.2" - } - }, - "node_modules/mocha": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.3.0.tgz", - "integrity": "sha512-uF2XJs+7xSLsrmIvn37i/wnc91nw7XjOQB8ccyx5aEgdnohr7n+rEiZP23WkCYHjilR6+EboEnbq/ZQDz4LSbg==", - "dev": true, - "dependencies": { - "ansi-colors": "4.1.1", - "browser-stdout": "1.3.1", - "chokidar": "3.5.3", - "debug": "4.3.4", - "diff": "5.0.0", - "escape-string-regexp": "4.0.0", - "find-up": "5.0.0", - "glob": "8.1.0", - "he": "1.2.0", - "js-yaml": "4.1.0", - "log-symbols": "4.1.0", - "minimatch": "5.0.1", - "ms": "2.1.3", - "serialize-javascript": "6.0.0", - "strip-json-comments": "3.1.1", - "supports-color": "8.1.1", - "workerpool": "6.2.1", - "yargs": "16.2.0", - "yargs-parser": "20.2.4", - "yargs-unparser": "2.0.0" + "browser-stdout": "^1.3.1", + "chokidar": "^5.0.0", + "debug": "^4.3.5", + "diff": "^9.0.0", + "find-up-simple": "^1.0.1", + "glob": "^13.0.0", + "is-path-inside": "^4.0.0", + "is-unicode-supported": "^0.1.0", + "js-yaml": "^5.0.0", + "minimatch": "^10.2.2", + "ms": "^2.1.3", + "picocolors": "^1.1.1", + "serialize-javascript": "^7.1.1", + "strip-json-comments": "^5.0.3", + "supports-color": "^8.1.1", + "workerpool": "^10.0.0" }, "bin": { - "_mocha": "bin/_mocha", "mocha": "bin/mocha.js" }, "engines": { - "node": ">= 14.0.0" - } - }, - "node_modules/mocha/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "engines": { - "node": ">=8" + "node": "^20.19.0 || >=22.12.0" } }, "node_modules/mocha/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true - }, - "node_modules/mocha/node_modules/brace-expansion": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", - "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", - "dev": true, - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/mocha/node_modules/cliui": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", - "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-3.0.4.tgz", + "integrity": "sha512-fwWK3Zq22l4XJJjx5mcBHGikIk+hJqO+32dPm0Jur7+rtG5x1scOjSfdT9ZKeWHPpsya/l0HHK4tDImBkTrtvA==", "dev": true, - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.0", - "wrap-ansi": "^7.0.0" - } - }, - "node_modules/mocha/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "PSF-2.0" }, - "node_modules/mocha/node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "node_modules/mocha/node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", "dev": true, + "license": "MIT", "engines": { "node": ">=10" }, @@ -6213,109 +6992,40 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/mocha/node_modules/glob": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", - "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", - "dev": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^5.0.1", - "once": "^1.3.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/mocha/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "engines": { - "node": ">=8" - } - }, "node_modules/mocha/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.5.0.tgz", + "integrity": "sha512-paNr4LFIFPjeeSmwNYdrb8FafLLG/Cr2Af3GjbsHJ5CxIjH4r0c2emlmRdAtpPAieP1gRVzk6buBbVP5gBMGAg==", "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/puzrin" + }, + { + "type": "github", + "url": "https://github.com/sponsors/nodeca" + } + ], + "license": "MIT", "dependencies": { - "argparse": "^2.0.1" + "argparse": "^3.0.3" }, "bin": { - "js-yaml": "bin/js-yaml.js" + "js-yaml": "bin/js-yaml.mjs" } }, - "node_modules/mocha/node_modules/minimatch": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", - "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", - "dev": true, - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/mocha/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mocha/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "node_modules/mocha/node_modules/strip-json-comments": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.1.0.tgz", + "integrity": "sha512-ErcwpJBYr8EfX/Br7JauOIGXoRE92w0hVtuS9j92UFgbATxA+WRSIZksSUDzEeItfWB/0QCEprTZT55RSINUHQ==", "dev": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, + "license": "MIT", "engines": { - "node": ">=8" - } - }, - "node_modules/mocha/node_modules/yargs": { - "version": "16.2.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", - "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", - "dev": true, - "dependencies": { - "cliui": "^7.0.2", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.0", - "y18n": "^5.0.5", - "yargs-parser": "^20.2.2" + "node": ">=22" }, - "engines": { - "node": ">=10" - } - }, - "node_modules/mocha/node_modules/yargs-parser": { - "version": "20.2.4", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", - "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", - "dev": true, - "engines": { - "node": ">=10" + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/ms": { @@ -6325,9 +7035,9 @@ "dev": true }, "node_modules/nanoid": { - "version": "3.3.7", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz", - "integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==", + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", "dev": true, "funding": [ { @@ -6335,6 +7045,8 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", + "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -6342,17 +7054,50 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/napi-postinstall": { + "version": "0.3.8", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.8.tgz", + "integrity": "sha512-dHbDC5V1g/EI8OLEtL4Iuwbu0fgzmyykxenn2KnlsX9XdhTXL3gWnfbbP+ab+oUcgV6CFpb8QGyQt/ZXA0UXig==", + "dev": true, + "license": "MIT", + "bin": { + "napi-patch": "lib/patch.js", + "napi-postinstall": "lib/cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/napi-postinstall" + } + }, "node_modules/natural-compare": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true + "dev": true, + "license": "MIT" + }, + "node_modules/neo-async": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", + "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "dev": true, + "license": "MIT" }, "node_modules/node-fetch": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", "dev": true, + "license": "MIT", "dependencies": { "whatwg-url": "^5.0.0" }, @@ -6369,10 +7114,11 @@ } }, "node_modules/node-gyp-build": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.0.tgz", - "integrity": "sha512-u6fs2AEUljNho3EYTJNBfImO5QTo/J/1Etd+NVdCj7qWKUSN/bSLkZwhDv7I+w/MSC6qJ4cknepkAYykDdK8og==", + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", "dev": true, + "license": "MIT", "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", @@ -6386,33 +7132,39 @@ "dev": true }, "node_modules/node-releases": { - "version": "2.0.14", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.14.tgz", - "integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==", - "dev": true + "version": "2.0.64", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz", + "integrity": "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/nofilter": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/nofilter/-/nofilter-3.1.0.tgz", "integrity": "sha512-l2NNj07e9afPnhAhvgVrCD/oy2Ai1yfLpuo3EpiO1jFTsB4sFz6oIfAfSZyQzVpkZQ9xS8ZS5g1jCBgq4Hwo0g==", "dev": true, + "license": "MIT", "engines": { "node": ">=12.19" } }, "node_modules/nopt": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", - "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-8.1.0.tgz", + "integrity": "sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A==", "dev": true, + "license": "ISC", "dependencies": { - "abbrev": "1" + "abbrev": "^3.0.0" }, "bin": { "nopt": "bin/nopt.js" }, "engines": { - "node": ">=6" + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/normalize-path": { @@ -6436,34 +7188,18 @@ "node": ">=8" } }, - "node_modules/npmlog": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", - "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", - "dev": true, - "dependencies": { - "are-we-there-yet": "^2.0.0", - "console-control-strings": "^1.1.0", - "gauge": "^3.0.0", - "set-blocking": "^2.0.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "dependencies": { - "wrappy": "1" + "node": ">=12.20.0" } }, "node_modules/onetime": { @@ -6495,6 +7231,7 @@ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", "dev": true, + "license": "MIT", "dependencies": { "yocto-queue": "^0.1.0" }, @@ -6506,25 +7243,40 @@ } }, "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", "dev": true, + "license": "MIT", "dependencies": { - "p-limit": "^3.0.2" + "p-limit": "^2.2.0" }, "engines": { - "node": ">=10" + "node": ">=8" + } + }, + "node_modules/p-locate/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/p-map": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.1.tgz", - "integrity": "sha512-2wnaR0XL/FDOj+TgpDuRb2KTjLnu3Fma6b1ZUwGY7LcqenMcvP/YFpjpbPKY6WVGsbuJZRuoUz8iPrt8ORnAFw==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.1.1.tgz", + "integrity": "sha512-6Lh3jQPLthYujSrlw6ccWXBGZTkoTCz27Hd92g79LH/kjAbgoEu0t442cCCNbegPSJsA0lwDX8z0bcKtkpA32g==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -6537,6 +7289,7 @@ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=6" } @@ -6557,11 +7310,19 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/package-json-from-dist": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", + "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/parse-json": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "dev": true, + "license": "MIT", "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", @@ -6580,6 +7341,7 @@ "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-4.0.0.tgz", "integrity": "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -6592,19 +7354,11 @@ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -6614,62 +7368,62 @@ "node": ">=8" } }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true - }, - "node_modules/path-type": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-5.0.0.tgz", - "integrity": "sha512-5HviZNaZcfqP95rwpv+1HDgUamezbqdSYTyzjTvwtJSnIH+3vnbmWsItli8OFEndS984VT55M3jduxZbX351gg==", + "node_modules/path-scurry": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, "engines": { - "node": ">=12" + "node": "18 || 20 || >=22" }, "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/pathe": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", - "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==", - "dev": true - }, - "node_modules/pathval": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", - "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "node_modules/path-type": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-6.0.0.tgz", + "integrity": "sha512-Vj7sf++t5pBD637NSfkxpHSMfWaeig5+DKWLhcqIYx6mWQz5hdJTGDVMQiJcw1ZYkhs7AazKDGpRVji1LJCZUQ==", "dev": true, + "license": "MIT", "engines": { - "node": "*" + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/picocolors": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", - "integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==", - "dev": true + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" }, "node_modules/picomatch": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-3.0.1.tgz", - "integrity": "sha512-I3EurrIQMlRc9IaAZnqRR044Phh2DXY+55o7uJ0V+hYZAcQYSuFWsc9q5PvyDHUSCe1Qxn/iBz+78s86zWnGag==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, + "license": "MIT", "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" } }, "node_modules/pirates": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.6.tgz", - "integrity": "sha512-saLsH7WeYYPiD25LDuLRRY/i+6HaPYr6G1OUlN39otzkSTxKnubR9RTxS3/Kk50s1g2JTgFwWQDQyplC5/SHZg==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", "dev": true, + "license": "MIT", "engines": { "node": ">= 6" } @@ -6679,6 +7433,7 @@ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", "dev": true, + "license": "MIT", "dependencies": { "find-up": "^4.0.0" }, @@ -6686,74 +7441,12 @@ "node": ">=8" } }, - "node_modules/pkg-dir/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pkg-dir/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-types": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.0.3.tgz", - "integrity": "sha512-nN7pYi0AQqJnoLPC9eHFQ8AcyaixBUOwvqc5TDnIKCMEE6I0y8P7OKA7fPexsXGCGxQDl/cmrLAp26LhcwxZ4A==", - "dev": true, - "dependencies": { - "jsonc-parser": "^3.2.0", - "mlly": "^1.2.0", - "pathe": "^1.1.0" - } - }, "node_modules/plur": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/plur/-/plur-5.1.0.tgz", "integrity": "sha512-VP/72JeXqak2KiOzjgKtQen5y3IZHn+9GOuLDafPv0eXa47xq0At93XahYBs26MsifCQ4enGKwbjBTKgb9QJXg==", "dev": true, + "license": "MIT", "dependencies": { "irregular-plurals": "^3.3.0" }, @@ -6765,9 +7458,9 @@ } }, "node_modules/postcss": { - "version": "8.4.35", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.35.tgz", - "integrity": "sha512-u5U8qYpBCpN13BsiEB0CbR1Hhh4Gc0zLFuedrHJKMctHCHAGrMdG0PRM/KErzAL3CU6/eckEtmHNB3x6e3c0vA==", + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", "dev": true, "funding": [ { @@ -6783,27 +7476,31 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", + "peer": true, "dependencies": { - "nanoid": "^3.3.7", - "picocolors": "^1.0.0", - "source-map-js": "^1.0.2" + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" }, "engines": { "node": "^10 || ^12 || >=14" } }, "node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", + "integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==", "dev": true, + "license": "MIT", "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" + "@jest/react-is-18": "npm:react-is@^18.3.1", + "@jest/react-is-19": "npm:react-is@^19.2.5", + "@jest/schemas": "30.5.0", + "ansi-styles": "^5.2.0" }, "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/pretty-format/node_modules/ansi-styles": { @@ -6811,6 +7508,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", "dev": true, + "license": "MIT", "engines": { "node": ">=10" }, @@ -6819,10 +7517,11 @@ } }, "node_modules/pretty-ms": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.0.0.tgz", - "integrity": "sha512-E9e9HJ9R9NasGOgPaPE8VMeiPKAyWR5jcFpNnwIejslIhWqdqOrb2wShBsncMPUb+BcCd2OPYfh7p2W6oemTng==", + "version": "9.3.1", + "resolved": "https://registry.npmjs.org/pretty-ms/-/pretty-ms-9.3.1.tgz", + "integrity": "sha512-HzMy3Geq23nVALD/M2LliU+F+M+gVNsvkQWWqeBZ8HDiCgzo6YPJ/Omrmtq24EFrIsk0a3EkQGEd7bDOo+IhGA==", "dev": true, + "license": "MIT", "dependencies": { "parse-ms": "^4.0.0" }, @@ -6833,23 +7532,10 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/pure-rand": { - "version": "6.0.4", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.0.4.tgz", - "integrity": "sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-7.0.1.tgz", + "integrity": "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==", "dev": true, "funding": [ { @@ -6860,7 +7546,8 @@ "type": "opencollective", "url": "https://opencollective.com/fast-check" } - ] + ], + "license": "MIT" }, "node_modules/queue-microtask": { "version": "1.2.3", @@ -6880,59 +7567,21 @@ "type": "consulting", "url": "https://feross.org/support" } - ] - }, - "node_modules/randombytes": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", - "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", - "dev": true, - "dependencies": { - "safe-buffer": "^5.1.0" - } - }, - "node_modules/react-is": { - "version": "18.2.0", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz", - "integrity": "sha512-xWGDIW6x921xtzPkhiULtthJHoJvBbF3q26fzloPCK0hsvxtPVelvftw3zjbHWSkR2km9Z+4uxbDDK/6Zw9B8w==", - "dev": true - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } + ], + "license": "MIT" }, "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", - "dev": true, - "dependencies": { - "picomatch": "^2.2.1" - }, - "engines": { - "node": ">=8.10.0" - } - }, - "node_modules/readdirp/node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", "dev": true, + "license": "MIT", "engines": { - "node": ">=8.6" + "node": ">= 20.19.0" }, "funding": { - "url": "https://github.com/sponsors/jonschlinkert" + "type": "individual", + "url": "https://paulmillr.com/funding/" } }, "node_modules/require-directory": { @@ -6940,27 +7589,11 @@ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=0.10.0" } }, - "node_modules/resolve": { - "version": "1.22.8", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.8.tgz", - "integrity": "sha512-oKWePCxqpd6FlLvGV1VU0x7bkPmmCNolxzjMf4NczoDnQcIWrAF+cPtZn5i6n+RfD2d9i0tzpKnG6Yk168yIyw==", - "dev": true, - "dependencies": { - "is-core-module": "^2.13.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/resolve-cwd": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", @@ -6982,79 +7615,51 @@ "node": ">=8" } }, - "node_modules/resolve-pkg-maps": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", - "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", - "dev": true, - "funding": { - "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" - } - }, - "node_modules/resolve.exports": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.2.tgz", - "integrity": "sha512-X2UW6Nw3n/aMgDVy+0rSqgHlv39WZAlZrXCdnbyEiKm17DSqHX4MmQMaST3FbeWR5FTuRcUwYAziZajji0Y7mg==", - "dev": true, - "engines": { - "node": ">=10" - } - }, "node_modules/reusify": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", - "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", "dev": true, + "license": "MIT", "engines": { "iojs": ">=1.0.0", "node": ">=0.10.0" } }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "dev": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/rollup": { - "version": "4.12.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.12.1.tgz", - "integrity": "sha512-ggqQKvx/PsB0FaWXhIvVkSWh7a/PCLQAsMjBc+nA2M8Rv2/HG0X6zvixAB7KyZBRtifBUhy5k8voQX/mRnABPg==", + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, + "license": "MIT", + "peer": true, "dependencies": { - "@types/estree": "1.0.5" + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" }, "bin": { - "rollup": "dist/bin/rollup" + "rolldown": "bin/cli.mjs" }, "engines": { - "node": ">=18.0.0", - "npm": ">=8.0.0" + "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rollup/rollup-android-arm-eabi": "4.12.1", - "@rollup/rollup-android-arm64": "4.12.1", - "@rollup/rollup-darwin-arm64": "4.12.1", - "@rollup/rollup-darwin-x64": "4.12.1", - "@rollup/rollup-linux-arm-gnueabihf": "4.12.1", - "@rollup/rollup-linux-arm64-gnu": "4.12.1", - "@rollup/rollup-linux-arm64-musl": "4.12.1", - "@rollup/rollup-linux-riscv64-gnu": "4.12.1", - "@rollup/rollup-linux-x64-gnu": "4.12.1", - "@rollup/rollup-linux-x64-musl": "4.12.1", - "@rollup/rollup-win32-arm64-msvc": "4.12.1", - "@rollup/rollup-win32-ia32-msvc": "4.12.1", - "@rollup/rollup-win32-x64-msvc": "4.12.1", - "fsevents": "~2.3.2" + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, "node_modules/run-parallel": { @@ -7076,38 +7681,17 @@ "url": "https://feross.org/support" } ], + "license": "MIT", "dependencies": { "queue-microtask": "^1.2.2" } }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ] - }, "node_modules/semver": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz", - "integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, - "dependencies": { - "lru-cache": "^6.0.0" - }, + "license": "ISC", "bin": { "semver": "bin/semver.js" }, @@ -7131,20 +7715,15 @@ } }, "node_modules/serialize-javascript": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", - "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "dev": true, - "dependencies": { - "randombytes": "^2.1.0" + "license": "BSD-3-Clause", + "engines": { + "node": ">=20.0.0" } }, - "node_modules/set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", - "dev": true - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", @@ -7166,29 +7745,18 @@ "node": ">=8" } }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true - }, "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, - "node_modules/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true - }, "node_modules/slash": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", "integrity": "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==", "dev": true, + "license": "MIT", "engines": { "node": ">=14.16" }, @@ -7201,6 +7769,7 @@ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz", "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==", "dev": true, + "license": "MIT", "dependencies": { "ansi-styles": "^6.0.0", "is-fullwidth-code-point": "^4.0.0" @@ -7212,6 +7781,19 @@ "url": "https://github.com/chalk/slice-ansi?sponsor=1" } }, + "node_modules/slice-ansi/node_modules/is-fullwidth-code-point": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz", + "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/source-map": { "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", @@ -7222,24 +7804,16 @@ } }, "node_modules/source-map-js": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.0.2.tgz", - "integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, + "license": "BSD-3-Clause", + "peer": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -7267,32 +7841,19 @@ "node": ">=8" } }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true - }, "node_modules/std-env": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.7.0.tgz", - "integrity": "sha512-JPbdCEQLj1w5GilpiHAx3qJvFndqybBysA3qUOnznweH4QbNYUsW/ea8QzSrnh0vNsezMMw5bcVool8lM0gwzg==", - "dev": true - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", "dev": true, - "dependencies": { - "safe-buffer": "~5.2.0" - } + "license": "MIT" }, "node_modules/string-length": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", "dev": true, + "license": "MIT", "dependencies": { "char-regex": "^1.0.2", "strip-ansi": "^6.0.0" @@ -7306,6 +7867,7 @@ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -7315,6 +7877,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -7323,10 +7886,11 @@ } }, "node_modules/string-width": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.1.0.tgz", - "integrity": "sha512-SEIJCWiX7Kg4c129n48aDRwLbFb2LJmXXFrWBG4NGaRtMQ3myKPKbwrD1BKqQn74oCoNMBVrfDEr5M9YxCsrkw==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", "dev": true, + "license": "MIT", "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", @@ -7339,13 +7903,60 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dev": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width-cjs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/strip-ansi": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.0.tgz", - "integrity": "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", "dev": true, + "license": "MIT", "dependencies": { - "ansi-regex": "^6.0.1" + "ansi-regex": "^6.2.2" }, "engines": { "node": ">=12" @@ -7354,11 +7965,49 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi/node_modules/ansi-regex": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, "node_modules/strip-bom": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -7377,6 +8026,7 @@ "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" }, @@ -7384,24 +8034,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/strip-literal": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-2.0.0.tgz", - "integrity": "sha512-f9vHgsCWBq2ugHAkGMiiYY+AYG0D/cbloKKg0nhaaaSNsujdGIpVXCNsrJpCKr5M0f4aI31mr13UjY6GAuXCKA==", - "dev": true, - "dependencies": { - "js-tokens": "^8.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/antfu" - } - }, - "node_modules/strip-literal/node_modules/js-tokens": { - "version": "8.0.3", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-8.0.3.tgz", - "integrity": "sha512-UfJMcSJc+SEXEl9lH/VLHSZbThQyLpw1vLO1Lb+j4RWDvG3N2f7yj3PVQA3cmkTBNldJ9eFnM+xEXxHIXrYiJw==", - "dev": true - }, "node_modules/supertap": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/supertap/-/supertap-3.0.1.tgz", @@ -7432,33 +8064,47 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "node_modules/synckit": { + "version": "0.11.13", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz", + "integrity": "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg==", "dev": true, + "license": "MIT", + "dependencies": { + "@pkgr/core": "^0.3.6" + }, "engines": { - "node": ">= 0.4" + "node": "^14.18.0 || >=16.0.0" }, "funding": { - "url": "https://github.com/sponsors/ljharb" + "url": "https://opencollective.com/synckit" } }, "node_modules/tar": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.0.tgz", - "integrity": "sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ==", + "version": "7.5.23", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.23.tgz", + "integrity": "sha512-lkukzdoGngZHJZXxW4S/E4Fp9ghTDlyZXrQGRNoJ/LXvDKcXUTq2sg5yQe74po7Voea6n/IN09+wE/QvJMiifA==", "dev": true, + "license": "BlueOak-1.0.0", "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^5.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" }, "engines": { - "node": ">=10" + "node": ">=18" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" } }, "node_modules/temp-dir": { @@ -7471,17 +8117,97 @@ } }, "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz", + "integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==", "dev": true, + "license": "ISC", "dependencies": { "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" + "glob": "^10.4.1", + "minimatch": "^10.2.2" }, "engines": { - "node": ">=8" + "node": ">=18" + } + }, + "node_modules/test-exclude/node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/test-exclude/node_modules/brace-expansion": { + "version": "2.1.8", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.8.tgz", + "integrity": "sha512-BnlDzDYQoplTsZSvPi86CNzmbcb07X8ufR8fk1zivaiEJlXJkiq1MQyDCVmlWcsWbj6aWXqHnrwwevbrm/Saig==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/test-exclude/node_modules/glob": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz", + "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==", + "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", + "dev": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/test-exclude/node_modules/glob/node_modules/minimatch": { + "version": "9.0.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", + "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.2" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/test-exclude/node_modules/lru-cache": { + "version": "10.4.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", + "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/test-exclude/node_modules/path-scurry": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", + "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/time-zone": { @@ -7494,42 +8220,40 @@ } }, "node_modules/tinybench": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.6.0.tgz", - "integrity": "sha512-N8hW3PG/3aOoZAN5V/NSAEDz0ZixDSSt5b/a05iqtpgfLWMSVuCo7w0k2vVvEjdrIoeGqZzweX2WlyioNIHchA==", - "dev": true - }, - "node_modules/tinypool": { - "version": "0.8.2", - "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-0.8.2.tgz", - "integrity": "sha512-SUszKYe5wgsxnNOVlBYO6IC+8VGWdVGZWAqUxp3UErNBtptZvWbwyUOyzNL59zigz2rCA92QiL3wvG+JDSdJdQ==", + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", "dev": true, + "license": "MIT", "engines": { - "node": ">=14.0.0" + "node": ">=20.0.0" } }, - "node_modules/tinyspy": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-2.2.1.tgz", - "integrity": "sha512-KYad6Vy5VDWV4GH3fjpseMQ/XU2BhIYP7Vzd0LG44qRWm/Yt2WCOTicFdvmgo6gWaqooMQCawTtILVQJupKu7A==", + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", "dev": true, + "license": "MIT", "engines": { - "node": ">=14.0.0" + "node": ">=18" } }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true - }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, "engines": { - "node": ">=4" + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" } }, "node_modules/to-regex-range": { @@ -7537,6 +8261,7 @@ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, + "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, @@ -7548,40 +8273,48 @@ "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true + "dev": true, + "license": "MIT" }, "node_modules/ts-jest": { - "version": "29.1.2", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.2.tgz", - "integrity": "sha512-br6GJoH/WUX4pu7FbZXuWGKGNDuU7b8Uj77g/Sp7puZV6EXzuByl6JrECvm0MzVzSTkSHWTihsXt+5XYER5b+g==", + "version": "29.4.15", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.15.tgz", + "integrity": "sha512-s2qmEUYFRqbjz1wv0EmccNPVOb45HOFpFuhzQJLKShYVisuTbCFPIIAIV2EuK5rIxb4BejLDbH7dnBZfYjybUQ==", "dev": true, + "license": "MIT", "dependencies": { - "bs-logger": "0.x", - "fast-json-stable-stringify": "2.x", - "jest-util": "^29.0.0", + "bs-logger": "^0.2.6", + "fast-json-stable-stringify": "^2.1.0", + "handlebars": "^4.7.10", "json5": "^2.2.3", - "lodash.memoize": "4.x", - "make-error": "1.x", - "semver": "^7.5.3", - "yargs-parser": "^21.0.1" + "lodash.memoize": "^4.1.2", + "make-error": "^1.3.6", + "semver": "^7.8.5", + "type-fest": "^4.41.0", + "yargs-parser": "^21.1.1" }, "bin": { "ts-jest": "cli.js" }, "engines": { - "node": "^16.10.0 || ^18.0.0 || >=20.0.0" + "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" }, "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@jest/types": "^29.0.0", - "babel-jest": "^29.0.0", - "jest": "^29.0.0", - "typescript": ">=4.3 <6" + "@babel/core": ">=7.0.0-beta.0 <9", + "@jest/transform": "^29.0.0 || ^30.0.0", + "@jest/types": "^29.0.0 || ^30.0.0", + "babel-jest": "^29.0.0 || ^30.0.0", + "jest": "^29.0.0 || ^30.0.0", + "jest-util": "^29.0.0 || ^30.0.0", + "typescript": ">=4.3 <7" }, "peerDependenciesMeta": { "@babel/core": { "optional": true }, + "@jest/transform": { + "optional": true + }, "@jest/types": { "optional": true }, @@ -7590,17 +8323,42 @@ }, "esbuild": { "optional": true + }, + "jest-util": { + "optional": true } } }, + "node_modules/ts-jest/node_modules/type-fest": { + "version": "4.41.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", + "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", + "dev": true, + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true, + "peer": true + }, "node_modules/tsx": { - "version": "4.7.1", - "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.7.1.tgz", - "integrity": "sha512-8d6VuibXHtlN5E3zFkgY8u4DX7Y3Z27zvvPKVmLon/D4AjuKzarkUBTLDBgj9iTQ0hg5xM7c/mYiRVM+HETf0g==", + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", "dev": true, + "license": "MIT", "dependencies": { - "esbuild": "~0.19.10", - "get-tsconfig": "^4.7.2" + "esbuild": "~0.28.0" }, "bin": { "tsx": "dist/cli.mjs" @@ -7617,6 +8375,7 @@ "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", "dev": true, + "license": "MIT", "engines": { "node": ">=4" } @@ -7634,10 +8393,11 @@ } }, "node_modules/typescript": { - "version": "5.4.2", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.2.tgz", - "integrity": "sha512-+2/g0Fds1ERlP6JsakQQDXjZdZMM+rqpamFZJEKh4kwTIn3iDkgKtby0CeNd5ATNZ4Ry1ax15TMx0W2V+miizQ==", + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, + "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -7646,23 +8406,33 @@ "node": ">=14.17" } }, - "node_modules/ufo": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/ufo/-/ufo-1.4.0.tgz", - "integrity": "sha512-Hhy+BhRBleFjpJ2vchUNN40qgkh0366FWJGqVLYBHev0vpHTrXSA0ryT+74UiW6KWsldNurQMKGqCm1M2zBciQ==", - "dev": true + "node_modules/uglify-js": { + "version": "3.19.3", + "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", + "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", + "dev": true, + "license": "BSD-2-Clause", + "optional": true, + "bin": { + "uglifyjs": "bin/uglifyjs" + }, + "engines": { + "node": ">=0.8.0" + } }, "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", - "dev": true + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" }, "node_modules/unicorn-magic": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", - "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", + "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", "dev": true, + "license": "MIT", "engines": { "node": ">=18" }, @@ -7670,10 +8440,46 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/unrs-resolver": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.13.0.tgz", + "integrity": "sha512-mcPQo9Vm6kXd84d/WqMiYBi2CcA57QHBX/ev5PoUEb8b2oQzUvJ6xYsfseQblnCncgnVmCZGWiFwK7KkS5JZJA==", + "dev": true, + "license": "MIT", + "dependencies": { + "napi-postinstall": "^0.3.7" + }, + "funding": { + "url": "https://opencollective.com/unrs-resolver" + }, + "optionalDependencies": { + "@unrs/resolver-binding-android-arm-eabi": "1.13.0", + "@unrs/resolver-binding-android-arm64": "1.13.0", + "@unrs/resolver-binding-darwin-arm64": "1.13.0", + "@unrs/resolver-binding-darwin-x64": "1.13.0", + "@unrs/resolver-binding-freebsd-x64": "1.13.0", + "@unrs/resolver-binding-linux-arm-gnueabihf": "1.13.0", + "@unrs/resolver-binding-linux-arm-musleabihf": "1.13.0", + "@unrs/resolver-binding-linux-arm64-gnu": "1.13.0", + "@unrs/resolver-binding-linux-arm64-musl": "1.13.0", + "@unrs/resolver-binding-linux-loong64-gnu": "1.13.0", + "@unrs/resolver-binding-linux-loong64-musl": "1.13.0", + "@unrs/resolver-binding-linux-ppc64-gnu": "1.13.0", + "@unrs/resolver-binding-linux-riscv64-gnu": "1.13.0", + "@unrs/resolver-binding-linux-riscv64-musl": "1.13.0", + "@unrs/resolver-binding-linux-s390x-gnu": "1.13.0", + "@unrs/resolver-binding-linux-x64-gnu": "1.13.0", + "@unrs/resolver-binding-linux-x64-musl": "1.13.0", + "@unrs/resolver-binding-openharmony-arm64": "1.13.0", + "@unrs/resolver-binding-win32-arm64-msvc": "1.13.0", + "@unrs/resolver-binding-win32-ia32-msvc": "1.13.0", + "@unrs/resolver-binding-win32-x64-msvc": "1.13.0" + } + }, "node_modules/update-browserslist-db": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.0.13.tgz", - "integrity": "sha512-xebP81SNcPuNpPP3uzeW1NYXxI3rxyJzF3pD6sH4jE7o/IX+WtSpwnVU+qIsDPyk0d3hmFQ7mjqc6AtV604hbg==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", "dev": true, "funding": [ { @@ -7689,9 +8495,10 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "escalade": "^3.1.1", - "picocolors": "^1.0.0" + "escalade": "^3.2.0", + "picocolors": "^1.1.1" }, "bin": { "update-browserslist-db": "cli.js" @@ -7700,17 +8507,12 @@ "browserslist": ">= 4.21.0" } }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true - }, "node_modules/v8-to-istanbul": { - "version": "9.2.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.2.0.tgz", - "integrity": "sha512-/EH/sDgxU2eGxajKdwLCDmQ4FWq+kpi3uCmBGpw1xJtnAxEjlD8j8PEiGWpCIMIs3ciNAgH0d3TTJiUkYzyZjA==", + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", + "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", "dev": true, + "license": "ISC", "dependencies": { "@jridgewell/trace-mapping": "^0.3.12", "@types/istanbul-lib-coverage": "^2.0.1", @@ -7721,20 +8523,24 @@ } }, "node_modules/vite": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-5.1.5.tgz", - "integrity": "sha512-BdN1xh0Of/oQafhU+FvopafUp6WaYenLU/NFoL5WyJL++GxkNfieKzBhM24H3HVsPQrlAqB7iJYTHabzaRed5Q==", + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "dev": true, + "license": "MIT", + "peer": true, "dependencies": { - "esbuild": "^0.19.3", - "postcss": "^8.4.35", - "rollup": "^4.2.0" + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" }, "bin": { "vite": "bin/vite.js" }, "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^20.19.0 || >=22.12.0" }, "funding": { "url": "https://github.com/vitejs/vite?sponsor=1" @@ -7743,112 +8549,125 @@ "fsevents": "~2.3.3" }, "peerDependencies": { - "@types/node": "^18.0.0 || >=20.0.0", - "less": "*", - "lightningcss": "^1.21.0", - "sass": "*", - "stylus": "*", - "sugarss": "*", - "terser": "^5.4.0" + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" }, "peerDependenciesMeta": { "@types/node": { "optional": true }, - "less": { + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { "optional": true }, - "lightningcss": { + "less": { "optional": true }, "sass": { "optional": true }, + "sass-embedded": { + "optional": true + }, "stylus": { "optional": true }, - "sugarss": { + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { "optional": true }, - "terser": { + "yaml": { "optional": true } } }, - "node_modules/vite-node": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-1.3.1.tgz", - "integrity": "sha512-azbRrqRxlWTJEVbzInZCTchx0X69M/XPTCz4H+TLvlTcR/xH/3hkRqhOakT41fMJCMzXTu4UvegkZiEoJAWvng==", + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", "dev": true, + "license": "MIT", "dependencies": { - "cac": "^6.7.14", - "debug": "^4.3.4", - "pathe": "^1.1.1", - "picocolors": "^1.0.0", - "vite": "^5.0.0" - }, - "bin": { - "vite-node": "vite-node.mjs" - }, - "engines": { - "node": "^18.0.0 || >=20.0.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/vitest": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-1.3.1.tgz", - "integrity": "sha512-/1QJqXs8YbCrfv/GPQ05wAZf2eakUPLPa18vkJAKE7RXOKfVHqMZZ1WlTjiwl6Gcn65M5vpNUB6EFLnEdRdEXQ==", - "dev": true, - "dependencies": { - "@vitest/expect": "1.3.1", - "@vitest/runner": "1.3.1", - "@vitest/snapshot": "1.3.1", - "@vitest/spy": "1.3.1", - "@vitest/utils": "1.3.1", - "acorn-walk": "^8.3.2", - "chai": "^4.3.10", - "debug": "^4.3.4", - "execa": "^8.0.1", - "local-pkg": "^0.5.0", - "magic-string": "^0.30.5", - "pathe": "^1.1.1", - "picocolors": "^1.0.0", - "std-env": "^3.5.0", - "strip-literal": "^2.0.0", - "tinybench": "^2.5.1", - "tinypool": "^0.8.2", - "vite": "^5.0.0", - "vite-node": "1.3.1", - "why-is-node-running": "^2.2.2" + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" }, "bin": { "vitest": "vitest.mjs" }, "engines": { - "node": "^18.0.0 || >=20.0.0" + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { "@edge-runtime/vm": "*", - "@types/node": "^18.0.0 || >=20.0.0", - "@vitest/browser": "1.3.1", - "@vitest/ui": "1.3.1", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", "happy-dom": "*", - "jsdom": "*" + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "@edge-runtime/vm": { "optional": true }, + "@opentelemetry/api": { + "optional": true + }, "@types/node": { "optional": true }, - "@vitest/browser": { + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { "optional": true }, "@vitest/ui": { @@ -7859,145 +8678,18 @@ }, "jsdom": { "optional": true + }, + "vite": { + "optional": false } } }, - "node_modules/vitest/node_modules/execa": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-8.0.1.tgz", - "integrity": "sha512-VyhnebXciFV2DESc+p6B+y0LjSm0krU4OgJN44qFAhBY0TJ+1V61tYD2+wHusZ6F9n5K+vl8k0sTy7PEfV4qpg==", - "dev": true, - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^8.0.1", - "human-signals": "^5.0.0", - "is-stream": "^3.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^5.1.0", - "onetime": "^6.0.0", - "signal-exit": "^4.1.0", - "strip-final-newline": "^3.0.0" - }, - "engines": { - "node": ">=16.17" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/vitest/node_modules/get-stream": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", - "integrity": "sha512-VaUJspBffn/LMCJVoMvSAdmscJyS1auj5Zulnn5UoYcY531UWmdwhRWkcGKnGU93m5HSXP9LP2usOryrBtQowA==", - "dev": true, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/human-signals": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-5.0.0.tgz", - "integrity": "sha512-AXcZb6vzzrFAUE61HnN4mpLqd/cSIwNQjtNWR0euPm6y0iqx3G4gOXaIDdtdDwZmhwe82LA6+zinmW4UBWVePQ==", - "dev": true, - "engines": { - "node": ">=16.17.0" - } - }, - "node_modules/vitest/node_modules/is-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-3.0.0.tgz", - "integrity": "sha512-LnQR4bZ9IADDRSkvpqMGvt/tEJWclzklNgSw48V5EAaAeDd6qGvN8ei6k5p0tvxSR171VmGyHuTiAOfxAbr8kA==", - "dev": true, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/npm-run-path": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-5.3.0.tgz", - "integrity": "sha512-ppwTtiJZq0O/ai0z7yfudtBpWIoxM8yE6nHi1X47eFR2EWORqfbu6CnPlNsjeN683eT0qG6H/Pyf9fCcvjnnnQ==", - "dev": true, - "dependencies": { - "path-key": "^4.0.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/onetime": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-6.0.0.tgz", - "integrity": "sha512-1FlR+gjXK7X+AsAHso35MnyN5KqGwJRi/31ft6x0M194ht7S+rWAvd7PHss9xSKMzE0asv1pyIHaJYq+BbacAQ==", - "dev": true, - "dependencies": { - "mimic-fn": "^4.0.0" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/path-key": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-4.0.0.tgz", - "integrity": "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/vitest/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/vitest/node_modules/strip-final-newline": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-3.0.0.tgz", - "integrity": "sha512-dOESqjYr96iWYylGObzd39EuNTa5VJxyvVAEm5Jnh7KGo75V43Hk1odPQkNDyXNmUR6k+gEiDVXnjB8HJ3crXw==", - "dev": true, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "dependencies": { - "makeerror": "1.0.12" - } - }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true + "dev": true, + "license": "BSD-2-Clause" }, "node_modules/well-known-symbols": { "version": "2.0.0", @@ -8013,6 +8705,7 @@ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", "dev": true, + "license": "MIT", "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" @@ -8034,59 +8727,108 @@ } }, "node_modules/why-is-node-running": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.2.2.tgz", - "integrity": "sha512-6tSwToZxTOcotxHeA+qGCq1mVzKR3CwcJGmVcY+QE8SHy6TnpFnh8PAvPNHYr7EcuVeG0QSMxtYCuO1ta/G/oA==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", "dev": true, - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, + "license": "MIT", "bin": { "why-is-node-running": "cli.js" }, "engines": { - "node": ">=8" + "node": ">=20.11" + } + }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/workerpool": { + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-10.0.3.tgz", + "integrity": "sha512-6z2Iis68Wqth93/G/wJP9u+R3O+d2XTlgWChGCwuT1qLbBsOYueGRZuJ++v3mtDP5KjYdy+WzvWC+VWETSVXJA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/wide-align": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", - "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, + "license": "MIT", "dependencies": { - "string-width": "^1.0.2 || 2 || 3 || 4" + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/wide-align/node_modules/ansi-regex": { + "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } }, - "node_modules/wide-align/node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/wide-align/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, "engines": { "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" } }, - "node_modules/wide-align/node_modules/string-width": { + "node_modules/wrap-ansi-cjs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "dev": true, + "license": "MIT" + }, + "node_modules/wrap-ansi-cjs/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -8096,11 +8838,12 @@ "node": ">=8" } }, - "node_modules/wide-align/node_modules/strip-ansi": { + "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -8108,34 +8851,12 @@ "node": ">=8" } }, - "node_modules/workerpool": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.1.tgz", - "integrity": "sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==", - "dev": true - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, "node_modules/wrap-ansi/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -8145,6 +8866,7 @@ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", "dev": true, + "license": "MIT", "dependencies": { "color-convert": "^2.0.1" }, @@ -8159,22 +8881,15 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, - "engines": { - "node": ">=8" - } + "license": "MIT" }, "node_modules/wrap-ansi/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -8189,6 +8904,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -8196,23 +8912,18 @@ "node": ">=8" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true - }, "node_modules/write-file-atomic": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", - "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-6.0.0.tgz", + "integrity": "sha512-GmqrO8WJ1NuzJ2DrziEI2o57jKAVIQNf8a18W3nCYU3H7PNWqCCVTeH6/NQE93CIllIgQS98rrmVkYgTX9fFJQ==", "dev": true, + "license": "ISC", "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" }, "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + "node": "^18.17.0 || >=20.5.0" } }, "node_modules/write-file-atomic/node_modules/signal-exit": { @@ -8220,6 +8931,7 @@ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", "dev": true, + "license": "ISC", "engines": { "node": ">=14" }, @@ -8232,21 +8944,24 @@ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", "dev": true, + "license": "ISC", "engines": { "node": ">=10" } }, "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" }, "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", "dev": true, + "license": "MIT", "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", @@ -8269,26 +8984,12 @@ "node": ">=12" } }, - "node_modules/yargs-unparser": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", - "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", - "dev": true, - "dependencies": { - "camelcase": "^6.0.0", - "decamelize": "^4.0.0", - "flat": "^5.0.2", - "is-plain-obj": "^2.1.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/yargs/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, + "license": "MIT", "engines": { "node": ">=8" } @@ -8297,22 +8998,15 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true - }, - "node_modules/yargs/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, - "engines": { - "node": ">=8" - } + "license": "MIT" }, "node_modules/yargs/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, + "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -8327,6 +9021,7 @@ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, + "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" }, @@ -8339,6 +9034,7 @@ "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=10" }, diff --git a/compatibility-checks/package.json b/compatibility-checks/package.json index b611b98..075dfd1 100644 --- a/compatibility-checks/package.json +++ b/compatibility-checks/package.json @@ -1,7 +1,8 @@ { "name": "substitute-compatibility-checks", "version": "0.0.0", - "description": "Checks compatibility of @fluffy-spoon/substitute with various test runners.", + "private": true, + "description": "Checks compatibility of the packed @fluffy-spoon/substitute build with various test runners.", "license": "MIT", "funding": { "type": "opencollective", @@ -12,29 +13,31 @@ "url": "https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking.git" }, "engines": { - "node": ">=20" + "node": ">=22.12" }, "scripts": { + "install:local": "node scripts/install-local-build.js", "validate:ava": "ava test-runners/ava/**.ts", "validate:jest": "jest test-runners/jest/**.ts", "validate:mocha": "mocha --require tsx/cjs test-runners/mocha/**.ts", "validate:nodejs": "node --require tsx/cjs --test ./test-runners/nodejs/*.ts", "validate:vitest": "vitest run ./test-runners/vitest/*.ts", - "test": "node --require tsx/cjs --test test/**" + "pretest": "npm run install:local", + "test": "node --require tsx/cjs --test test/index.ts" }, "devDependencies": { - "@types/mocha": "^10.0.6", - "@types/node": "^20.11.25", + "@types/mocha": "^10.0.10", + "@types/node": "^22.20.5", "ansi-regex": "^6.0.1", - "ava": "^6.1.2", - "jest": "^29.7.0", - "mocha": "^10.3.0", - "ts-jest": "^29.1.2", - "tsx": "^4.7.1", - "typescript": "^5.4.2", - "vitest": "^1.3.1" + "ava": "^6.4.1", + "jest": "^30.5.2", + "mocha": "^12.0.3", + "ts-jest": "^29.4.15", + "tsx": "^4.23.15", + "typescript": "^5.9.3", + "vitest": "^5.1.0" }, "volta": { - "node": "20.11.1" + "node": "24.22.3" } -} \ No newline at end of file +} diff --git a/compatibility-checks/scripts/install-local-build.js b/compatibility-checks/scripts/install-local-build.js new file mode 100644 index 0000000..ee4bb17 --- /dev/null +++ b/compatibility-checks/scripts/install-local-build.js @@ -0,0 +1,39 @@ +'use strict' +// Packs the repository root exactly like `npm publish` does (its prepack script builds dist/) and installs +// the tarball into this project, so the compatibility checks run against what would be published, not +// against ../src. Runs automatically before `npm test` (the pretest script). +// +// The tarball is installed with --no-save, so package.json and package-lock.json here stay untouched. + +const { execFileSync } = require('child_process') +const fs = require('fs') +const os = require('os') +const path = require('path') + +const here = path.resolve(__dirname, '..') +const root = path.resolve(here, '..') +const isWindows = process.platform === 'win32' +const npm = isWindows ? 'npm.cmd' : 'npm' + +const destination = fs.mkdtempSync(path.join(os.tmpdir(), 'substitute-compatibility-')) +try { + const output = execFileSync(npm, ['pack', '--json', '--silent', '--pack-destination', destination], { + cwd: root, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'inherit'], + shell: isWindows + }) + const [{ filename }] = JSON.parse(output.slice(output.indexOf('['))) + const tarball = path.join(destination, filename) + // Remove a previously installed build, so that npm never keeps a stale copy. + fs.rmSync(path.join(here, 'node_modules', '@fluffy-spoon', 'substitute'), { recursive: true, force: true }) + execFileSync(npm, ['install', '--no-save', '--no-audit', '--no-fund', tarball], { + cwd: here, + stdio: 'inherit', + shell: isWindows + }) + const installed = require(path.join(here, 'node_modules', '@fluffy-spoon', 'substitute', 'package.json')) + console.log(`Installed ${installed.name}@${installed.version} from ${filename}`) +} finally { + fs.rmSync(destination, { recursive: true, force: true }) +} diff --git a/compatibility-checks/test-runners/_common/index.ts b/compatibility-checks/test-runners/_common/index.ts index 3eadf2d..941f286 100644 --- a/compatibility-checks/test-runners/_common/index.ts +++ b/compatibility-checks/test-runners/_common/index.ts @@ -1,4 +1,4 @@ -import Substitute from '../../../src' +import Substitute from '@fluffy-spoon/substitute' interface Library { subSection: AmbiguousSection diff --git a/compatibility-checks/test/environment.d.ts b/compatibility-checks/test/environment.d.ts new file mode 100644 index 0000000..70cad13 --- /dev/null +++ b/compatibility-checks/test/environment.d.ts @@ -0,0 +1,2 @@ +/** The environment the compatibility checks start each test runner with (see environment.js). */ +export declare const testRunnerEnvironment: (base?: Record) => Record diff --git a/compatibility-checks/test/environment.js b/compatibility-checks/test/environment.js new file mode 100644 index 0000000..227be6e --- /dev/null +++ b/compatibility-checks/test/environment.js @@ -0,0 +1,22 @@ +'use strict' +// The environment the compatibility checks start each test runner with. +// +// `node --test` sets NODE_TEST_CONTEXT in every process it runs. A nested `node --test` (the node:test +// compatibility check) that inherits it believes it is a child of the outer runner: it reports its results +// to the parent instead and exits with code 0 even when its own test failed. So every NODE_TEST_* variable +// is removed. Colours are disabled so that the output can be searched for plain text. + +/** + * @param {Record} [base] + * @returns {Record} + */ +const testRunnerEnvironment = (base = process.env) => { + const environment = { ...base, CI: '1', NO_COLOR: '1' } + delete environment.FORCE_COLOR + for (const name of Object.keys(environment)) { + if (name.startsWith('NODE_TEST_')) delete environment[name] + } + return environment +} + +module.exports = { testRunnerEnvironment } diff --git a/compatibility-checks/test/index.ts b/compatibility-checks/test/index.ts index afaa9ff..54476e2 100644 --- a/compatibility-checks/test/index.ts +++ b/compatibility-checks/test/index.ts @@ -1,18 +1,23 @@ import * as test from 'node:test' import * as assert from 'node:assert' import { execSync } from 'node:child_process' +import { testRunnerEnvironment } from './environment' type TestRunner = { name: string - failureAcknowledgementText: string + /** + * One of these must appear in the runner's output. The shared scenario fails with a SubstituteException that is + * thrown either synchronously (a failed test) or on process.nextTick after the test returned (an uncaught exception), + * depending on whether the library can decide the assertion right away, so both reports are accepted. + */ + failureAcknowledgementTexts: string[] failureLocationText: string } test.describe('Verifies test runner compatibility', () => { const failingExec = (command: string): string => { - const { FORCE_COLOR, ...environment } = { ...process.env, CI: '1', NO_COLOR: '1' } as Partial> try { - execSync(command, { env: environment, stdio: 'pipe' }) + execSync(command, { env: testRunnerEnvironment(), stdio: 'pipe' }) assert.fail('Execution should have failed with a non-zero exit code. We expect the test runner have 1 failing test.') } catch (error) { if (error instanceof assert.AssertionError) throw error @@ -22,27 +27,28 @@ test.describe('Verifies test runner compatibility', () => { } const testRunners: TestRunner[] = [ - { name: 'ava', failureAcknowledgementText: '1 uncaught exception', failureLocationText: 'test-runners/ava/index.ts' }, - { name: 'jest', failureAcknowledgementText: '', failureLocationText: 'test-runners/jest/index.spec.ts' }, - { name: 'mocha', failureAcknowledgementText: '1 failing', failureLocationText: 'can substitute callable interfaces:' }, - { name: 'nodejs', failureAcknowledgementText: 'fail 1', failureLocationText: 'test-runners/nodejs/index.ts' }, - { name: 'vitest', failureAcknowledgementText: '1 error', failureLocationText: 'error originated in "test-runners/vitest/index.spec.ts" test file' } + { name: 'ava', failureAcknowledgementTexts: ['1 uncaught exception', '1 test failed'], failureLocationText: 'test-runners/ava/index.ts' }, + { name: 'jest', failureAcknowledgementTexts: ['Tests: 1 failed', "type: 'CallCountMismatch'"], failureLocationText: 'test-runners/jest/index.spec.ts' }, + { name: 'mocha', failureAcknowledgementTexts: ['1 failing'], failureLocationText: 'can substitute callable interfaces:' }, + // G:CI-2: this check used to pass vacuously or fail, because the nested `node --test` inherited NODE_TEST_CONTEXT. + { name: 'nodejs', failureAcknowledgementTexts: ['fail 1'], failureLocationText: 'test-runners/nodejs/index.ts' }, + { name: 'vitest', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest/index.spec.ts' } ] testRunners.forEach(testRunner => { test.describe(testRunner.name, () => { - test.it('reports the uncaught Substitute exception', () => { + test.it('reports the Substitute exception', () => { const result = failingExec(`npm run validate:${testRunner.name}`) assert.ok( - result.includes(testRunner.failureAcknowledgementText), - `Could not find the expected failure acknowledgement in the output. Expected "${testRunner.failureAcknowledgementText}"` + testRunner.failureAcknowledgementTexts.some(text => result.includes(text)), + `Could not find the expected failure acknowledgement in the output. Expected one of ${JSON.stringify(testRunner.failureAcknowledgementTexts)}: ${result}` ) assert.ok( result.includes(testRunner.failureLocationText), - `Could not find the expected failure location in the output. Expected "${testRunner.failureLocationText}"` + `Could not find the expected failure location in the output. Expected "${testRunner.failureLocationText}": ${result}` ) assert.ok( - result.includes('SubstituteException: Call count mismatch'), + result.includes('SubstituteException') && result.includes('Call count mismatch'), `Could not find the expected exception message in the output: ${result}` ) }) From ccb01fa61f7dcb55eb6c6bb22e14fee8836e13d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:39:50 +0000 Subject: [PATCH 008/106] ci: test every supported LTS line, the oldest Node and the test runners; fix publishing - Node CI: run on push and pull_request (and as a reusable workflow) on Node 22, 24 and 26 instead of 18/20/21, and run `npm run test:types --if-present`. - New compatibility job: the compatibility checks against the packed package (G:CI-2). - New minimum-node job: packs the package and smoke-tests it on MINIMUM_NODE_VERSION (10.0.0, = engines.node) and on 12.17.0 for the ES module entry (G:PK-2). - Publish: trigger on `published` releases, run the full CI workflow first, check that the release tag matches package.json, publish stable versions as `latest` and prereleases as `beta`, with provenance. - Remove the GitHub Packages job. GitHub Packages only accepts packages whose scope is the repository owner (@ffmathy), so it could never host @fluffy-spoon/substitute and failed every release (G:CI-1). - CodeQL: action v4, drop the obsolete HEAD^2 checkout, explicit permissions. Dependabot also watches compatibility-checks/. The bug report template asks for the module system and the test runner. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .github/ISSUE_TEMPLATE/bug_report.md | 2 + .github/dependabot.yml | 7 ++ .github/workflows/codeql-analysis.yml | 26 +++--- .github/workflows/nodejs.yml | 129 ++++++++++++++++++++++---- .github/workflows/npm-publish.yml | 91 ++++++++---------- 5 files changed, 173 insertions(+), 82 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 0eb2f96..3ed0881 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -22,6 +22,8 @@ A clear and concise description of what you expected to happen. - Typescript version: ` ` - substitute.js version: ` ` - Node version: ` ` +- Module system (CommonJS, native ESM, bundler): ` ` +- Test runner (ava, jest, mocha, node:test, vitest, ...): ` ` **Additional context** Add any other context about the problem here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5570919..2a17ec2 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -12,3 +12,10 @@ updates: interval: daily time: "04:00" open-pull-requests-limit: 10 + + # The test runners used by compatibility-checks/ (dev tooling only). + - package-ecosystem: npm + directory: "/compatibility-checks" + schedule: + interval: weekly + open-pull-requests-limit: 5 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 50341b8..67c33a1 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -8,37 +8,37 @@ on: schedule: - cron: '0 6 * * 1' +permissions: + contents: read + jobs: analyze: name: Analyze runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write strategy: fail-fast: false matrix: language: ['javascript-typescript'] - # Learn more... - # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + # https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 show-progress: false - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v3 + uses: github/codeql-action/init@v4 with: languages: ${{ matrix.language }} - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 + uses: github/codeql-action/analyze@v4 + with: + category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index b566fe3..02f4fdf 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -1,27 +1,118 @@ name: Node CI -on: [push] + +on: + push: + pull_request: + workflow_dispatch: + # The publish workflow runs exactly these checks before it publishes. + workflow_call: + +permissions: + contents: read + +env: + # The oldest Node.js version the package supports. It must equal engines.node in package.json + # (packaging/package.test.js checks that), and the minimum-node job below smoke-tests the packed package on it. + MINIMUM_NODE_VERSION: '10.0.0' + # The oldest Node.js version with native ES module support, for the ESM entry point (dist/index.mjs). + MINIMUM_ESM_NODE_VERSION: '12.17.0' jobs: - build: + test: + name: Test on Node ${{ matrix.node-version }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Every Node.js LTS line that is still supported: https://nodejs.org/en/about/previous-releases + node-version: [22, 24, 26] + steps: + - uses: actions/checkout@v5 + with: + show-progress: false + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node-version }} + cache: npm + - name: Install dependencies + run: npm ci + - name: Build + run: npm run build + - name: Run the specs and the packaging checks + run: npm test + - name: Run the type tests + run: npm run test:types --if-present + + compatibility: + name: Test runner compatibility on Node ${{ matrix.node-version }} runs-on: ubuntu-latest strategy: + fail-fast: false matrix: - node-version: [18, 20, 21] + node-version: [22, 24, 26] + steps: + - uses: actions/checkout@v5 + with: + show-progress: false + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v5 + with: + node-version: ${{ matrix.node-version }} + cache: npm + cache-dependency-path: | + package-lock.json + compatibility-checks/package-lock.json + - name: Install dependencies + run: npm ci + - name: Install the compatibility check dependencies + run: npm ci + working-directory: compatibility-checks + # The pretest script packs the repository like npm publish does and installs that tarball, + # so ava, jest, mocha, node:test and vitest run against the package as it would be published. + - name: Run the compatibility checks against the packed package + run: npm test + working-directory: compatibility-checks + minimum-node: + name: Packed package on the oldest supported Node versions + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - with: - show-progress: false - - name: Use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v4 - with: - node-version: ${{ matrix.node-version }} - cache: 'npm' - - name: Install dependencies - run: npm ci - - name: Transpile typescript - run: npm run build --if-present - - name: Run tests - run: npm test - env: - CI: true + - uses: actions/checkout@v5 + with: + show-progress: false + - name: Use the development Node.js version + uses: actions/setup-node@v5 + with: + node-version-file: package.json + cache: npm + - name: Install dependencies + run: npm ci + - name: Pack the package like npm publish does + run: | + consumer="$RUNNER_TEMP/consumer" + mkdir -p "$consumer/node_modules/@fluffy-spoon/substitute" + npm pack --pack-destination "$RUNNER_TEMP" + tar -xzf "$RUNNER_TEMP"/fluffy-spoon-substitute-*.tgz -C "$consumer/node_modules/@fluffy-spoon/substitute" --strip-components=1 + cp packaging/smoke/* "$consumer/" + - name: Use Node.js ${{ env.MINIMUM_NODE_VERSION }} + uses: actions/setup-node@v5 + with: + node-version: ${{ env.MINIMUM_NODE_VERSION }} + # G:PK-2: engines.node must be a version the package really runs on. + - name: CommonJS smoke test on Node ${{ env.MINIMUM_NODE_VERSION }} + working-directory: ${{ runner.temp }}/consumer + run: | + node --version + node require.js + node deep-imports.js + - name: Use Node.js ${{ env.MINIMUM_ESM_NODE_VERSION }} + uses: actions/setup-node@v5 + with: + node-version: ${{ env.MINIMUM_ESM_NODE_VERSION }} + - name: CommonJS and ES module smoke test on Node ${{ env.MINIMUM_ESM_NODE_VERSION }} + working-directory: ${{ runner.temp }}/consumer + run: | + node --version + node require.js + node import.mjs diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 6198b96..78db841 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -1,66 +1,57 @@ name: Publish +# Publishing a GitHub release publishes the package to npm. See CONTRIBUTING.md ("Releasing"). +# - The release tag must match the version in package.json (v2.0.1 or 2.0.1 for version 2.0.1). +# - A stable version is published with the npm dist-tag `latest`. A prerelease version (2.1.0-beta.1) or a release +# marked as a prerelease on GitHub is published with the dist-tag `beta`. +# +# There is no GitHub Packages job: GitHub Packages only hosts npm packages whose scope is the repository owner +# (@ffmathy), so it cannot host @fluffy-spoon/substitute, and the former job failed on every release. on: release: - types: [created] + # `published` also fires for a release that was saved as a draft first (`created` does not). + types: [published] + +permissions: + contents: read jobs: - build-test: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - show-progress: false - - uses: actions/setup-node@v4 - with: - node-version: 18 - cache: 'npm' - - run: npm ci --ignore-scripts - - run: npm test + ci: + name: CI + uses: ./.github/workflows/nodejs.yml publish-npm: - needs: build-test - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - show-progress: false - - uses: actions/setup-node@v4 - with: - node-version: 18 - registry-url: https://registry.npmjs.org/ - cache: 'npm' - - run: npm ci --ignore-scripts - - run: npm run build - - run: echo "tag=latest" >> $GITHUB_ENV - - name: Sets npm tag - if: contains(github.event.release.tag_name, 'beta') - run: echo "tag=beta" >> $GITHUB_ENV - - run: npm publish --access public --tag ${{ env.tag }} - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }} - - publish-github: - needs: build-test + name: Publish to npm + needs: ci runs-on: ubuntu-latest permissions: contents: read - packages: write + # Lets npm publish with provenance (and with trusted publishing, if it is configured on npmjs.com). + id-token: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: show-progress: false - - uses: actions/setup-node@v4 + - uses: actions/setup-node@v5 with: - node-version: 18 - registry-url: https://npm.pkg.github.com/ - cache: 'npm' - - run: npm ci --ignore-scripts - - run: npm run build - - run: echo "tag=latest" >> $GITHUB_ENV - - name: Sets npm tag - if: contains(github.event.release.tag_name, 'beta') - run: echo "tag=beta" >> $GITHUB_ENV - - run: npm publish --tag ${{ env.tag }} + node-version-file: package.json + registry-url: https://registry.npmjs.org/ + cache: npm + - name: Install dependencies + run: npm ci --ignore-scripts + - name: Determine the npm dist-tag + id: dist-tag env: - NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_TAG: ${{ github.event.release.tag_name }} + PRERELEASE: ${{ github.event.release.prerelease }} + run: | + version="$(node -p "require('./package.json').version")" + tag="$(node packaging/dist-tag.js "$RELEASE_TAG" "$version" "$PRERELEASE")" + echo "Publishing $version with the dist-tag $tag" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + # npm publish runs the prepack script, which builds dist/ from scratch. + - name: Publish + run: npm publish --provenance --access public --tag "$DIST_TAG" + env: + DIST_TAG: ${{ steps.dist-tag.outputs.tag }} + NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }} From 9d51d2c9cd882cd92f41dfcd9a0ab82272e973ca Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:39:50 +0000 Subject: [PATCH 009/106] test(packaging): packaging, release and CI checks; add CONTRIBUTING.md packaging/package.test.js runs with `npm test`. It packs the repository like npm publish does (starting from a stale dist/), installs the tarball into a fresh consumer project and checks: - G:PK-3: the tarball has the entry points and no spec/stale output; the spec build goes to dist-spec/. - DOCS:ESM: the default import works under native ESM and in TypeScript (node10, node16, nodenext, bundler); require, deep imports and package.json still work. - G:PK-4: package-lock.json version = package.json version. - G:PK-2: engines.node = the version the minimum-node CI job tests. - G:CI-1 / CI:dist-tag: publishing only targets npm, tag logic. - G:CI-2: nested node --test runs report failures; CI runs the compatibility checks against the packed build. - CI:matrix: supported LTS lines and the type tests. CONTRIBUTING.md (linked from the README, previously a 404) documents install, build, test, test:types, the compatibility checks, CI and the release process. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CONTRIBUTING.md | 156 ++++++++++++++++++++++++++ packaging/package.test.js | 227 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 383 insertions(+) create mode 100644 CONTRIBUTING.md create mode 100644 packaging/package.test.js diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9663802 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,156 @@ +# Contributing to @fluffy-spoon/substitute + +Thanks for helping out! This document describes the development workflow: how to build and test the +library, how the packaging checks work, and how a release is published. + +Bug reports and feature requests go to the [issue tracker](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/issues). +Please include a small snippet that reproduces the problem, your TypeScript and Node.js versions, your module +system (CommonJS, native ESM or a bundler) and your test runner. + +## Prerequisites + +- Node.js: the version pinned in `package.json` under `volta` (currently 24.x). If you use [Volta](https://volta.sh) + it is picked automatically. Any supported LTS line (22, 24 or 26) works for development. +- npm (comes with Node.js). + +The published package itself supports much older Node.js versions than the development tooling. See +`engines.node` in `package.json`; CI smoke-tests the packed package on exactly that version. + +## Install + +```sh +npm ci +``` + +## Project layout + +| Path | What it is | +| --- | --- | +| `src/` | The library source (TypeScript). `src/index.ts` is the public entry point. | +| `spec/` | The runtime specs, run with [ava](https://github.com/avajs/ava). | +| `packaging/` | Packaging checks (run as part of `npm test`), the ES module wrapper generator and the smoke tests. | +| `compatibility-checks/` | A separate npm project that checks the packed package with ava, jest, mocha, node:test and vitest. | +| `dist/` | Build output that gets published (generated, not committed). | +| `dist-spec/` | Compiled specs used by `npm test` (generated, not committed). | + +## Build + +```sh +npm run build +``` + +This compiles `src/` into `dist/` with `tsc` (CommonJS plus `.d.ts` typings) and then runs +`packaging/build-esm.js`, which generates the native ES module entry point next to it: + +- `dist/index.mjs` re-exports every export of `dist/index.js`, plus the default export. It wraps the CommonJS + build instead of being a second copy, so CommonJS and ESM consumers share one module instance. +- `dist/index.d.mts` holds the matching typings for TypeScript's `node16`, `nodenext` and `bundler` resolution. + +The `exports` map in `package.json` sends `import` to the ES module entry and everything else (`require`, older +resolvers) to the CommonJS entry. `main` and `types` are kept for resolvers that do not read `exports`. Deep +imports of compiled files (`@fluffy-spoon/substitute/dist/...`, with or without `.js`) stay available through +the `./dist/*` subpaths, but they are not public API. + +## Test + +```sh +npm test +``` + +`npm test` runs `npm run build:spec`, which compiles the specs together with the sources they import into +`dist-spec/`, and then ava. It never writes into `dist/`, so running the tests cannot leave a broken `dist/` +behind for publishing. + +ava runs two groups of tests: + +- `spec/**/*.spec.ts` and `spec/**/*.test.ts`: the runtime behaviour of the library. +- `packaging/**/*.test.js`: packaging and release checks. They pack the repository exactly like `npm publish` + does (which rebuilds `dist/` through the `prepack` script), extract the tarball into a fresh consumer project + and check it there: the tarball contents, `require` and native `import` (including the default import), + deep imports, TypeScript resolution in `node10`, `node16`, `nodenext` and `bundler` mode, and the consistency + of `package.json`, `package-lock.json` and the workflows. + +To run a single file or test, use ava's options after building the specs, for example: + +```sh +npm run build:spec && npx ava spec/regression/returns.spec.ts --match '*sequence*' +``` + +### Type tests + +```sh +npm run test:types +``` + +Type-level tests check the public typings with the TypeScript compiler. CI runs them with +`npm run test:types --if-present`. + +### Compatibility checks + +`compatibility-checks/` is a separate npm project with its own dependencies. It verifies that every supported +test runner (ava, jest, mocha, node:test and vitest) reports a failing Substitute assertion, including one that +is thrown after the test function has returned. It runs against the packed package, not against `src/`: + +```sh +cd compatibility-checks +npm ci +npm test +``` + +`npm test` there first runs `npm run install:local`, which packs the repository root like `npm publish` +(building `dist/` on the way) and installs the tarball with `npm install --no-save`, so neither `package.json` +nor `package-lock.json` of the compatibility checks changes. From the repository root, `npm run test:compat` +does the same once the compatibility check dependencies are installed. + +To try a single runner by hand after `npm run install:local`, use `npm run validate:` (`ava`, `jest`, +`mocha`, `nodejs` or `vitest`). Each of them is expected to fail with exactly one failing test. + +## Continuous integration + +`.github/workflows/nodejs.yml` runs on every push and pull request: + +- **test**: `npm ci`, `npm run build`, `npm test` and `npm run test:types --if-present` on every supported + Node.js LTS line (22, 24 and 26). +- **compatibility**: the compatibility checks against the packed package on the same Node.js versions. +- **minimum-node**: packs the package and smoke-tests it (`packaging/smoke/`) on the oldest supported Node.js + version (`MINIMUM_NODE_VERSION`, which must equal `engines.node`) and on the oldest version with native ES + modules (`MINIMUM_ESM_NODE_VERSION`). If a change needs a newer Node.js, raise `engines.node` and + `MINIMUM_NODE_VERSION` together; a packaging test checks that they match. + +`.github/workflows/codeql-analysis.yml` runs CodeQL on pushes and pull requests to `master` and weekly. + +## Releasing + +Releases are published to npm by `.github/workflows/npm-publish.yml` when a GitHub release is published. + +1. Bump the version with npm, which updates `package.json` and `package-lock.json` together and creates the + matching git tag: + + ```sh + npm version 2.0.2 # or: npm version patch | minor | major + npm version 2.1.0-beta.1 # a prerelease + ``` + +2. Push the commit and the tag: `git push --follow-tags`. +3. Create a GitHub release for that tag (for example `v2.0.2`) and publish it. A draft does nothing until it is + published. + +The publish workflow then: + +1. runs the complete CI workflow above (tests, type tests, compatibility checks and the oldest Node.js versions); +2. checks that the release tag matches the `package.json` version (`v2.0.2` or `2.0.2` for version 2.0.2) and + stops otherwise; +3. picks the npm dist-tag with `packaging/dist-tag.js`: `latest` for a stable version such as 2.0.1, `beta` for a + prerelease version such as 2.1.0-beta.1 or for a release that is marked as a prerelease on GitHub; +4. runs `npm publish --provenance --access public --tag `. The `prepack` script rebuilds `dist/` from + scratch first. + +Publishing uses the `NPM_PUBLISH_TOKEN` repository secret (a granular npm access token with publish rights for +`@fluffy-spoon/substitute`). The job also has the `id-token: write` permission, so npm attaches a provenance +statement, and npm's trusted publishing works once it is configured for this repository on npmjs.com. + +The package is only published to npm. GitHub Packages is not used: it only accepts npm packages whose scope +is the repository owner (`@ffmathy`), so it cannot host `@fluffy-spoon/substitute`. + +Never publish by hand from a working copy unless you have to. If you do, `npm publish` still runs `prepack`, +so the published `dist/` is always a fresh build. diff --git a/packaging/package.test.js b/packaging/package.test.js new file mode 100644 index 0000000..233c25d --- /dev/null +++ b/packaging/package.test.js @@ -0,0 +1,227 @@ +'use strict' +// Packaging, release and CI checks. These run as part of `npm test` (see ava.config.js). +// They pack the repository the way `npm publish` does and use the tarball from a fresh consumer project. +const test = require('ava') +const { execFile, spawnSync } = require('child_process') +const fs = require('fs') +const path = require('path') + +const { + root, readText, readJson, pack, createConsumer, runNode, childEnvironment, makeTemporaryDirectory, removeTemporaryDirectories +} = require('./helpers') + +const packageJson = readJson('package.json') +const ciWorkflow = readText('.github/workflows/nodejs.yml') +const publishWorkflow = readText('.github/workflows/npm-publish.yml') +const minutes = n => n * 60 * 1000 + +/** Runs a command without blocking, so that slow checks run concurrently. */ +const run = (command, args, cwd) => new Promise(resolve => { + execFile(command, args, { cwd, encoding: 'utf8', env: childEnvironment() }, (error, stdout, stderr) => { + resolve({ status: error ? (typeof error.code === 'number' ? error.code : 1) : 0, output: stdout + stderr }) + }) +}) + +const state = {} + +test.before('pack the repository like npm publish does', t => { + t.timeout(minutes(5)) + // Start from a stale dist/ like the one `npm test` used to leave behind: spec output and no dist/index.js. + // Packing must rebuild the library from scratch. + const dist = path.join(root, 'dist') + fs.rmSync(dist, { recursive: true, force: true }) + fs.mkdirSync(path.join(dist, 'spec'), { recursive: true }) + fs.writeFileSync(path.join(dist, 'spec', 'Stale.spec.js'), '') + + const destination = makeTemporaryDirectory('pack') + state.packed = pack(destination) + state.consumer = createConsumer(state.packed.tarball) + for (const file of fs.readdirSync(path.join(__dirname, 'smoke'))) { + fs.copyFileSync(path.join(__dirname, 'smoke', file), path.join(state.consumer, file)) + } +}) + +test.after.always('remove temporary directories', () => { + removeTemporaryDirectories() +}) + +test('G:PK-3 npm pack rebuilds dist/ first: the tarball has the entry points and no stale or spec output', t => { + const { files } = state.packed + for (const entry of ['dist/index.js', 'dist/index.d.ts', 'dist/index.mjs', 'dist/index.d.mts', 'package.json', 'README.md', 'LICENSE']) { + t.true(files.includes(entry), `${entry} is in the tarball`) + } + t.deepEqual(files.filter(file => /(^|\/)spec(\/|$)|\.spec\.|\.test\.|dist-spec/.test(file)), [], 'no spec output in the tarball') + t.deepEqual(files.filter(file => !file.startsWith('dist/') && !['package.json', 'README.md', 'LICENSE'].includes(file)), [], 'only dist/ and the package metadata are published') + t.is(packageJson.scripts.prepack, 'npm run build', 'prepack builds the library') +}) + +test('G:PK-3 npm test compiles the specs into dist-spec/, so it never leaves dist/ unpublishable', t => { + const avaConfig = require('../ava.config.js') + t.deepEqual(avaConfig.typescript.rewritePaths, { '/': 'dist-spec/' }) + t.regex(packageJson.scripts['build:spec'], /--outDir dist-spec\b/) + t.regex(packageJson.scripts.test, /^npm run build:spec && ava\b/) + t.false(/\bnpm run build\b(?!:)/.test(packageJson.scripts.test), 'npm test does not run the library build with other options') +}) + +test('DOCS:ESM the default import is the Substitute class under native ESM', t => { + const output = runNode(state.consumer, ['import.mjs']) + t.regex(output, /import smoke test passed/) +}) + +test('DOCS:ESM CommonJS require, deep imports and package.json still work with the exports map', t => { + t.regex(runNode(state.consumer, ['require.js']), /require smoke test passed/) + t.regex(runNode(state.consumer, ['deep-imports.js']), /deep import smoke test passed/) + t.regex(runNode(state.consumer, ['deep-imports.mjs']), /ESM deep import smoke test passed/) +}) + +const typeScriptConsumer = [ + "import Substitute, { Arg, Substitute as Named } from '@fluffy-spoon/substitute'", + "import { Arg as DeepArg } from '@fluffy-spoon/substitute/dist/api/Arg'", + 'interface Calculator { add(a: number, b: number): number }', + 'const calculator = Substitute.for()', + 'calculator.add(1, Arg.any()).returns(3)', + 'const same: typeof Named = Substitute', + 'const deep: typeof Arg = DeepArg', + 'export const result: number = calculator.add(1, 2) + (same === Named ? 0 : 1) + (deep === Arg ? 0 : 1)', + '' +].join('\n') + +const typeScriptModes = [ + { name: 'nodenext (ESM)', file: 'esm.mts', options: ['--module', 'nodenext', '--moduleResolution', 'nodenext'] }, + { name: 'nodenext (CommonJS)', file: 'cjs.cts', options: ['--module', 'nodenext', '--moduleResolution', 'nodenext'] }, + { name: 'node16 (ESM)', file: 'esm.mts', options: ['--module', 'node16', '--moduleResolution', 'node16'] }, + { name: 'bundler', file: 'bundler.ts', options: ['--module', 'esnext', '--moduleResolution', 'bundler'] }, + { name: 'node10', file: 'node10.ts', options: ['--module', 'commonjs', '--moduleResolution', 'node'] } +] + +for (const mode of typeScriptModes) { + test(`DOCS:ESM TypeScript types the default import as Substitute with moduleResolution ${mode.name}`, async t => { + t.timeout(minutes(2)) + const directory = path.join(state.consumer, mode.name.replace(/\W+/g, '-')) + fs.mkdirSync(directory) + fs.writeFileSync(path.join(directory, mode.file), typeScriptConsumer) + const tsc = require.resolve('typescript/bin/tsc', { paths: [root] }) + const typeRoots = path.join(root, 'node_modules', '@types') + const result = await run(process.execPath, [ + tsc, '--noEmit', '--strict', '--skipLibCheck', '--target', 'es2019', '--typeRoots', typeRoots, '--types', 'node', + ...mode.options, mode.file + ], directory) + t.is(result.status, 0, `${mode.name}: ${result.output}`) + }) +} + +test('G:PK-4 package-lock.json has the same version as package.json', t => { + const lock = readJson('package-lock.json') + t.is(lock.version, packageJson.version) + t.is(lock.packages[''].version, packageJson.version) +}) + +const normalizeVersion = version => { + const parts = version.split('.') + while (parts.length < 3) parts.push('0') + return parts.join('.') +} + +test('G:PK-2 engines.node is the minimum Node version that CI smoke-tests the packed package on', t => { + const engines = /^>=\s*(\d+(?:\.\d+){0,2})$/.exec(packageJson.engines.node) + t.truthy(engines, `engines.node is a plain lower bound: ${packageJson.engines.node}`) + const minimum = /MINIMUM_NODE_VERSION:\s*['"]?(\d+\.\d+\.\d+)['"]?/.exec(ciWorkflow) + t.truthy(minimum, 'nodejs.yml defines MINIMUM_NODE_VERSION') + t.is(normalizeVersion(engines[1]), minimum[1], 'engines.node matches the version CI tests') + t.regex(ciWorkflow, /node-version:\s*\$\{\{\s*env\.MINIMUM_NODE_VERSION\s*\}\}/, 'a CI job runs on MINIMUM_NODE_VERSION') + t.regex(ciWorkflow, /node\s+require\.js/, 'that job runs the CommonJS smoke test') +}) + +test('G:CI-1 the release workflow only publishes to registries it can authenticate against', t => { + const owner = /github\.com\/([^/]+)\//.exec(packageJson.repository.url)[1].toLowerCase() + const scope = packageJson.name.split('/')[0] + for (const [, registry] of publishWorkflow.matchAll(/registry-url:\s*['"]?([^'"\s]+)/g)) { + if (registry.includes('npm.pkg.github.com')) { + // GitHub Packages only accepts packages whose scope is the repository owner. + t.is(scope, `@${owner}`, `GitHub Packages cannot host ${packageJson.name}: its scope is not @${owner}`) + } else { + t.is(registry, 'https://registry.npmjs.org/') + } + } + t.notRegex(publishWorkflow, /npm\.pkg\.github\.com/, 'no job publishes to GitHub Packages') + t.regex(publishWorkflow, /NODE_AUTH_TOKEN:\s*\$\{\{\s*secrets\.NPM_PUBLISH_TOKEN\s*\}\}/) + t.is(packageJson.publishConfig && packageJson.publishConfig.registry, 'https://registry.npmjs.org/') +}) + +const distTag = (...args) => spawnSync(process.execPath, [path.join(__dirname, 'dist-tag.js'), ...args], { + cwd: root, + encoding: 'utf8', + env: childEnvironment() +}) + +test('CI:dist-tag a stable release tag publishes as latest, a prerelease as beta', t => { + const cases = [ + { tag: 'v2.0.1', version: '2.0.1', prerelease: 'false', expected: 'latest' }, + { tag: '2.0.1', version: '2.0.1', prerelease: 'false', expected: 'latest' }, + { tag: 'v2.1.0-beta.1', version: '2.1.0-beta.1', prerelease: 'true', expected: 'beta' }, + { tag: 'v3.0.0-rc.2', version: '3.0.0-rc.2', prerelease: 'false', expected: 'beta' }, + { tag: 'v2.0.2', version: '2.0.2', prerelease: 'true', expected: 'beta' } + ] + for (const { tag, version, prerelease, expected } of cases) { + const result = distTag(tag, version, prerelease) + t.is(result.status, 0, result.stderr) + t.is(result.stdout.trim(), expected, `${tag} (prerelease: ${prerelease})`) + } + t.regex(publishWorkflow, /node packaging\/dist-tag\.js/, 'the publish workflow uses packaging/dist-tag.js') + t.notRegex(publishWorkflow, /contains\(github\.event\.release\.tag_name, 'beta'\)/) +}) + +test('CI:dist-tag a release tag that does not match package.json is rejected', t => { + const result = distTag('v2.0.2', '2.0.1', 'false') + t.not(result.status, 0) + t.regex(result.stderr, /does not match/) +}) + +test('G:CI-2 a nested node --test run reports its failures (NODE_TEST_CONTEXT is not inherited)', t => { + t.timeout(minutes(1)) + const { testRunnerEnvironment } = require('../compatibility-checks/test/environment.js') + const directory = makeTemporaryDirectory('node-test') + const inner = path.join(directory, 'inner.js') + const outer = path.join(directory, 'outer.js') + fs.writeFileSync(inner, "require('node:test').test('fails', () => { throw new Error('inner failure') })\n") + fs.writeFileSync(outer, [ + "const { spawnSync } = require('child_process')", + `const { testRunnerEnvironment } = require(${JSON.stringify(path.join(root, 'compatibility-checks', 'test', 'environment.js'))})`, + "require('node:test').test('nested run fails', () => {", + ` const result = spawnSync(process.execPath, ['--test', ${JSON.stringify(inner)}], { env: testRunnerEnvironment(), encoding: 'utf8' })`, + " if (result.status === 0) throw new Error('the nested node --test run did not report its failure')", + '})', + '' + ].join('\n')) + const result = spawnSync(process.execPath, ['--test', outer], { encoding: 'utf8', env: childEnvironment() }) + t.is(result.status, 0, result.stdout + result.stderr) + t.is(testRunnerEnvironment({ NODE_TEST_CONTEXT: 'child-v8', KEEP: '1' }).NODE_TEST_CONTEXT, undefined) + t.is(testRunnerEnvironment({ NODE_TEST_CONTEXT: 'child-v8', KEEP: '1' }).KEEP, '1') +}) + +test('G:CI-2 CI runs the compatibility checks against the packed local build', t => { + const compatibility = JSON.parse(fs.readFileSync(path.join(root, 'compatibility-checks', 'package.json'), 'utf8')) + t.is(compatibility.scripts.pretest, 'npm run install:local', 'npm test in compatibility-checks installs the packed local build first') + t.regex(compatibility.scripts['install:local'], /^node scripts\/install-local-build\.js$/) + const common = fs.readFileSync(path.join(root, 'compatibility-checks', 'test-runners', '_common', 'index.ts'), 'utf8') + t.regex(common, /from '@fluffy-spoon\/substitute'/, 'the test runners import the package, not ../src') + t.notRegex(common, /\.\.\/src/) + t.regex(ciWorkflow, /working-directory:\s*compatibility-checks[\s\S]*?run:\s*npm test|run:\s*npm test\s*\n\s*working-directory:\s*compatibility-checks/, 'a CI job runs npm test in compatibility-checks') +}) + +test('CI:matrix CI tests every supported Node LTS line and runs the type tests', t => { + const matrix = /node-version:\s*\[([^\]]+)\]/.exec(ciWorkflow) + t.truthy(matrix, 'nodejs.yml has a node-version matrix') + const versions = matrix[1].split(',').map(version => version.trim().replace(/['"]/g, '')) + for (const version of ['22', '24', '26']) t.true(versions.includes(version), `Node ${version} is tested`) + for (const version of ['18', '20', '21']) t.false(versions.includes(version), `end-of-life Node ${version} is not in the matrix`) + t.regex(ciWorkflow, /npm run test:types --if-present/) + t.regex(ciWorkflow, /pull_request/) +}) + +test('DOCS:CONTRIBUTING CONTRIBUTING.md (linked from the README) exists and documents the release process', t => { + const contributing = readText('CONTRIBUTING.md') + for (const topic of ['npm test', 'test:types', 'compatibility-checks', 'release']) { + t.true(contributing.includes(topic), `CONTRIBUTING.md mentions ${topic}`) + } +}) From 2604a0a85b25278972e6a8b76dcf5b85889eb27b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:42:14 +0000 Subject: [PATCH 010/106] docs(contributing): use a --match pattern that selects tests Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9663802..92e66ee 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -73,7 +73,7 @@ ava runs two groups of tests: To run a single file or test, use ava's options after building the specs, for example: ```sh -npm run build:spec && npx ava spec/regression/returns.spec.ts --match '*sequence*' +npm run build:spec && npx ava spec/regression/returns.spec.ts --match '*order*' ``` ### Type tests From 3ec797b139d82d448e760c83b1419387f5353617 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:43:23 +0000 Subject: [PATCH 011/106] fix(types): rework the public typings - One rule for the setup methods (T:TY-2, G:RG-4): `.returns` / `.throws` / `.mimicks` / `.resolves` / `.rejects` are offered unless the value they are accessed on (property type or return type) has a member with that name; the symbol forms are always offered. Checks are non-distributive for the method types, so union return types keep a single `mimicks` (T:TY-1). - D11: `sub.received` / `sub.didNotReceive` are only offered when T has no public or private member named received, didNotReceive, returns, throws, resolves, rejects or mimicks; the symbol forms are always available, including on SubstituteOf for a generic T (T:TY-3, G:RG-3, T:TY-14). - D12: `mimick` is symbol-only (`sub[mimick](instance)`) (T:TY-5). - D5: `sub[configure]()` returns a view whose members only expose the setup API. - Overloads: up to 8 overloads in one bivariant inference step (T:TY-11), zero-parameter overloads anywhere (T:TY-10), `(...args: unknown[])` (T:TY-13), positional signatures before the Arg.all() ones. - Optional members (T:TY-7), index signatures next to named members (T:TY-8), members returning `never` (T:TY-12), `then` typed `never` and `toJSON` without setup API (T:TY-16, D20). - Export SubstituteException from the index through a public interface, so the typings do not reach the internals or @types/node (G:RG-9). - overlap.spec.ts: use the string received/didNotReceive forms through `any`, since D11 no longer offers them in the typings for these types. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/overlap.spec.ts | 15 ++-- src/api/types/FunctionSubstitute.ts | 135 ++++++++++++++++++---------- src/api/types/Substitute.ts | 103 +++++++++++++-------- src/api/types/SubstituteMethods.ts | 59 +++++++----- src/api/types/SubstitutionLevel.ts | 117 +++++++++++++++++------- src/api/types/Utilities.ts | 45 ++++++++++ src/index.ts | 18 ++++ 7 files changed, 347 insertions(+), 145 deletions(-) create mode 100644 src/api/types/Utilities.ts diff --git a/spec/regression/overlap.spec.ts b/spec/regression/overlap.spec.ts index b2cc942..6120fb3 100644 --- a/spec/regression/overlap.spec.ts +++ b/spec/regression/overlap.spec.ts @@ -2,6 +2,9 @@ import test from 'ava' import { Substitute, received, didNotReceive } from '../../src' +// D11: when T has a member named received/didNotReceive (or returns/throws/resolves/rejects/mimicks), the typings only +// offer the symbol forms [received]/[didNotReceive]. The string forms keep working at runtime (for JavaScript users), +// which is what the `as any` lines below exercise. export interface OverlappingInterface { received(value: number): string didNotReceive(): unknown @@ -11,7 +14,7 @@ export interface OverlappingInterface { test('(clearReceivedCalls) handles overlaps safely without substitutions', t => { const substitute = Substitute.for>() substitute.clearReceivedCalls() - t.notThrows(() => substitute.received(1).clearReceivedCalls()) + t.notThrows(() => (substitute as any).received(1).clearReceivedCalls()) t.throws(() => substitute[didNotReceive]().clearReceivedCalls()) }) @@ -19,7 +22,7 @@ test('(clearReceivedCalls) handles overlaps safely with substitutions', t => { const substitute = Substitute.for>() substitute.clearReceivedCalls().returns() substitute.clearReceivedCalls() - t.notThrows(() => substitute.received(1).clearReceivedCalls()) + t.notThrows(() => (substitute as any).received(1).clearReceivedCalls()) t.throws(() => substitute[didNotReceive]().clearReceivedCalls()) }) @@ -27,7 +30,7 @@ test('(received) handles overlaps safely without substitutions', t => { const substitute = Substitute.for>() substitute.received(10) t.notThrows(() => substitute[received](1).received(10)) - t.throws(() => substitute.didNotReceive().received(10)) + t.throws(() => (substitute as any).didNotReceive().received(10)) }) test('(received) handles overlaps safely with substitutions', t => { @@ -35,13 +38,13 @@ test('(received) handles overlaps safely with substitutions', t => { substitute.received(10).returns('foo') t.is('foo', substitute.received(10)) t.notThrows(() => substitute[received](1).received(10)) - t.throws(() => substitute.didNotReceive().received(10)) + t.throws(() => (substitute as any).didNotReceive().received(10)) }) test('(didNotReceive) handles overlaps safely without substitutions', t => { const substitute = Substitute.for>() substitute.didNotReceive() - t.notThrows(() => substitute.received(1).didNotReceive()) + t.notThrows(() => (substitute as any).received(1).didNotReceive()) t.throws(() => substitute[didNotReceive]().didNotReceive()) }) @@ -49,6 +52,6 @@ test('(didNotReceive) handles overlaps safely with substitutions', t => { const substitute = Substitute.for>() substitute.didNotReceive().returns('foo') t.is('foo' as unknown, substitute.didNotReceive()) - t.notThrows(() => substitute.received(1).didNotReceive()) + t.notThrows(() => (substitute as any).received(1).didNotReceive()) t.throws(() => substitute[didNotReceive]().didNotReceive()) }) diff --git a/src/api/types/FunctionSubstitute.ts b/src/api/types/FunctionSubstitute.ts index 872faec..e37b783 100644 --- a/src/api/types/FunctionSubstitute.ts +++ b/src/api/types/FunctionSubstitute.ts @@ -1,48 +1,89 @@ import { AllArguments } from '../../shared' -import { MockObjectMixin, NoArgumentMockObjectMixin } from './SubstitutionLevel' - -type TerminatingFunction = ((...args: TArguments) => void) & ((arg: AllArguments) => void) -export type FunctionSubstitute = - ((...args: TArguments) => (TReturnType & MockObjectMixin)) & - ((allArguments: AllArguments) => (TReturnType & MockObjectMixin)) - -export type FunctionSubstituteWithOverloads = - TFunc extends { - (...args: infer A1): infer R1; - (...args: infer A2): infer R2; - (...args: infer A3): infer R3; - (...args: infer A4): infer R4; - (...args: infer A5): infer R5; - } ? - FunctionHandler & FunctionHandler & - FunctionHandler & FunctionHandler - & FunctionHandler : TFunc extends { - (...args: infer A1): infer R1; - (...args: infer A2): infer R2; - (...args: infer A3): infer R3; - (...args: infer A4): infer R4; - } ? - FunctionHandler & FunctionHandler & - FunctionHandler & FunctionHandler : TFunc extends { - (...args: infer A1): infer R1; - (...args: infer A2): infer R2; - (...args: infer A3): infer R3; - } ? - FunctionHandler & FunctionHandler - & FunctionHandler : TFunc extends { - (...args: infer A1): infer R1; - (...args: infer A2): infer R2; - } ? - FunctionHandler & FunctionHandler : TFunc extends { - (...args: infer A1): infer R1; - } ? - FunctionHandler : never; - -type Equals = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false; -type FunctionHandler = - Equals extends true ? - {} : Terminating extends true ? - TerminatingFunction : - FunctionSubstitute - -export type NoArgumentFunctionSubstitute = () => TReturnType & NoArgumentMockObjectMixin +import { ConfigurationResult, SubstitutionResult } from './SubstitutionLevel' +import { Equals, IsAny, IsNever } from './Utilities' + +/** + * What a call returns in each view of a substitute: + * - `substitute`: the configured value intersected with the setup API (`sub.add(1, 2).returns(3)`) + * - `configure`: the setup API only (`sub[configure]().add(1, 2).returns(3)`) + * - `assertion`: nothing (`sub.received().add(1, 2)`) + */ +export type SubstituteView = 'substitute' | 'configure' | 'assertion' + +type CallResult = + TView extends 'assertion' ? void : + TView extends 'configure' ? ConfigurationResult TReturnType> : + SubstitutionResult TReturnType> + +type Overload = { arguments: TArguments, returnType: TReturnType } +// Not `undefined`: without strictNullChecks `undefined` would match `Overload`. +type NoOverload = { readonly noOverload: true } + +// When a function has fewer overloads than the pattern below, the leading slots of the pattern receive no overload of +// their own: TypeScript <= 5.0 leaves them as `(...args: unknown[]) => unknown`, newer versions repeat the first +// overload. Inference pairs the signatures from the end, so the last slot always holds the last overload. A slot is +// skipped when it is empty or identical to the next slot. (A genuine `(...args: unknown[]) => unknown` overload that is +// not the last overload is indistinguishable from an empty slot and is skipped as well.) +type IsSameOverload = + Equals extends true ? Equals : false +type IsEmptySlot = IsSameOverload +type Slot = TArguments extends any[] ? + (IsEmptySlot extends true ? NoOverload : + IsSameOverload extends true ? NoOverload : + Overload) : + NoOverload +type LastSlot = TArguments extends any[] ? Overload : NoOverload + +/** + * The overloads of a function type, as a fixed-length list of `Overload | NoOverload` (empty slots first), or only + * `NoOverload` when the type is not callable. + * The pattern uses method signatures, which TypeScript compares bivariantly even with `strictFunctionTypes`, so it + * matches any function with 1 to 8 overloads in one step. Functions with more than 8 overloads keep their substitute + * typing for the last 8 only (T:TY-11). + * The checked type is intersected with `TFunction` itself so that TypeScript defers the check until `TFunction` is + * known (an object type that merely contains a type parameter would be resolved eagerly, and wrongly). + */ +type Overloads = ({ substituteOverloads: TFunction } & TFunction) extends { + substituteOverloads(...args: infer A1): infer R1 + substituteOverloads(...args: infer A2): infer R2 + substituteOverloads(...args: infer A3): infer R3 + substituteOverloads(...args: infer A4): infer R4 + substituteOverloads(...args: infer A5): infer R5 + substituteOverloads(...args: infer A6): infer R6 + substituteOverloads(...args: infer A7): infer R7 + substituteOverloads(...args: infer A8): infer R8 +} ? [ + Slot, Slot, Slot, Slot, + Slot, Slot, Slot, LastSlot +] : + [NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload] + +type PositionalSignature = TOverload extends Overload ? + (...args: TOverload['arguments']) => CallResult : + {} + +type AllArgumentsSignature = TOverload extends Overload ? + (allArguments: AllArguments) => CallResult : + {} + +// All positional signatures come before the `Arg.all()` signatures, so a call with a single matcher +// (`Arg.any()`, `Arg.is(...)`) resolves against the real parameter lists first (T:TY-10). +type OverloadSignatures = + PositionalSignature & PositionalSignature & + PositionalSignature & PositionalSignature & + PositionalSignature & PositionalSignature & + PositionalSignature & PositionalSignature & + AllArgumentsSignature & AllArgumentsSignature & + AllArgumentsSignature & AllArgumentsSignature & + AllArgumentsSignature & AllArgumentsSignature & + AllArgumentsSignature & AllArgumentsSignature + +/** + * The call signatures a member of type `TFunction` has on a substitute, one pair per overload: the overload's own + * parameter list, and a single `Arg.all()` argument. `{}` when `TFunction` is not callable. + */ +export type FunctionSubstitute = + IsNever extends true ? {} : + IsAny extends true ? (...args: any[]) => CallResult : + // Not `[TFunction] extends [(...args: any) => any]`: in its true branch TypeScript would add that signature to TFunction. + OverloadSignatures, TView> diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index 6921940..c9a4fe3 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -1,38 +1,67 @@ -import { NoArgumentMockObjectMixin } from './SubstitutionLevel' -import { FunctionSubstituteWithOverloads, NoArgumentFunctionSubstitute } from './FunctionSubstitute' - -export type PropertySubstitute = - TReturnType & - NoArgumentMockObjectMixin; - -export type TryToExpandNonArgumentedTerminatingFunction = - TObject[TProperty] extends (...args: []) => unknown ? - () => void : - {} - -export type TryToExpandArgumentedTerminatingFunction = - TObject[TProperty] extends (...args: any) => any ? - FunctionSubstituteWithOverloads : - {} - -type TryToExpandNonArgumentedFunctionSubstitute = - TObject[TProperty] extends (...args: []) => infer R ? - NoArgumentFunctionSubstitute : - {} - -type TryToExpandArgumentedFunctionSubstitute = - TObject[TProperty] extends (...args: infer F) => any ? - F extends [] ? - {} : - FunctionSubstituteWithOverloads : - {} - -type TryToExpandPropertySubstitute = - PropertySubstitute - -export type ObjectSubstituteTransformation> = { - [P in keyof T]: - TryToExpandNonArgumentedFunctionSubstitute & - TryToExpandArgumentedFunctionSubstitute & - TryToExpandPropertySubstitute; +import { ConfigurationResult, SubstitutionResult } from './SubstitutionLevel' +import { FunctionSubstitute } from './FunctionSubstitute' + +/** A member read on a substitute: its value intersected with the setup API (`sub.isEnabled.returns(true)`). */ +export type PropertySubstitute = SubstitutionResult TValue> + +/** + * The object type whose members the views below map. + * A type with a string index signature is mapped directly: a homomorphic mapping over it keeps the named members next to + * the index signature (T:TY-8), whereas `keyof T` is just `string | number`. Any other type is first turned into a plain + * object type with the same members, so that primitives (`Substitute.for()`) and arrays are mapped member by + * member too (a homomorphic mapping would return a primitive unchanged and only map the elements of an array). + */ +type Members = string extends keyof T ? T : Pick + +// All views are mapped with `-?` and expand calls from the member type without `null | undefined`, so optional members +// (`prop?`, `method?()`) are configured and asserted like required ones (T:TY-7). +// +// Special members (T:TY-16, D20). At runtime a substitute never exposes `then`, so that it is not a thenable +// (`await sub` resolves to the substitute itself); the typings make `then` `never`. `toJSON` is answered by the +// substitute itself (it serializes the substitute): it keeps its declared type on the substitute (through `& T`) but +// has no setup API, and it cannot be configured or asserted. +// Symbol.toPrimitive and util.inspect.custom are special-cased at runtime as well but are not reflected here. + +type SubstituteMember = FunctionSubstitute, 'substitute'> & PropertySubstitute + +type SubstituteMembers = { + [P in keyof T]-?: + P extends 'then' ? never : + P extends 'toJSON' ? unknown : + SubstituteMember +} + +/** The members of a substitute (without the assertion and configuration methods). */ +export type ObjectSubstituteTransformation = SubstituteMembers> + +type AssertionMember = FunctionSubstitute, 'assertion'> & TValue + +type AssertionMembers = { + [P in keyof T]-?: + P extends 'then' ? never : + P extends 'toJSON' ? never : + AssertionMember } + +/** + * The object returned by `received()` / `didNotReceive()`: calls return nothing, property reads and writes keep the + * member type (`sub.received().isEnabled = true`). + */ +export type TerminatingObject = AssertionMembers> + +type ConfigurationMember = + FunctionSubstitute, 'configure'> & ConfigurationResult TValue> + +type ConfigurationMembers = { + [P in keyof T]-?: + P extends 'then' ? never : + P extends 'toJSON' ? never : + ConfigurationMember +} + +/** + * The object returned by `sub[configure]()`. Member reads and calls on it are always setups, so they only expose the + * setup API. The string forms (`.returns`, `.throws`, ...) are always offered here: the configured value is never + * returned from this view, so there is nothing for them to conflict with. + */ +export type ConfigureView = ConfigurationMembers> diff --git a/src/api/types/SubstituteMethods.ts b/src/api/types/SubstituteMethods.ts index b0b93c5..4a7fd52 100644 --- a/src/api/types/SubstituteMethods.ts +++ b/src/api/types/SubstituteMethods.ts @@ -1,15 +1,6 @@ import { constants } from '../../shared' -import { - TryToExpandNonArgumentedTerminatingFunction, - TryToExpandArgumentedTerminatingFunction -} from './Substitute' - -type TerminatingObject = { - [P in keyof T]: - TryToExpandNonArgumentedTerminatingFunction & - TryToExpandArgumentedTerminatingFunction & - T[P] -} +import { ConfigureView, TerminatingObject } from './Substitute' +import { HasAnyMember, LibraryMemberName } from './Utilities' export const received: typeof constants.CONTEXT.received.symbol = constants.CONTEXT.received.symbol export const didNotReceive: typeof constants.CONTEXT.didNotReceive.symbol = constants.CONTEXT.didNotReceive.symbol @@ -17,14 +8,38 @@ export const mimick: typeof constants.CONTEXT.mimick.symbol = constants.CONTEXT. export const clearReceivedCalls: typeof constants.CONTEXT.clearReceivedCalls.symbol = constants.CONTEXT.clearReceivedCalls.symbol export const configure: typeof constants.CONTEXT.configure.symbol = constants.CONTEXT.configure.symbol -export type ObjectSubstituteMethods = - (T extends { received: any } ? - { [received](amount?: number): TerminatingObject } : - { received(amount?: number): TerminatingObject }) & - (T extends { didNotReceive: any } ? - { [didNotReceive](): TerminatingObject } : - { didNotReceive(): TerminatingObject }) & - (T extends { mimick: any } ? - { [mimick](instance: T): void } : - { mimick(instance: T): void }) & - { [clearReceivedCalls](): void } +/** + * The symbol API is always available, also on `SubstituteOf` for a generic `T` (T:TY-3). + */ +type SymbolSubstituteMethods = { + /** Asserts that the following member access, call or set happened `amount` times (1 or more when omitted). */ + [received](amount?: number): TerminatingObject + /** Asserts that the following member access, call or set never happened. Same as `[received](0)`. */ + [didNotReceive](): TerminatingObject + /** Delegates every member access, call or set without a matching substitution to `instance`. */ + [mimick](instance: T): void + /** Clears the received calls of this substitute; configured substitutions are kept. */ + [clearReceivedCalls](): void + /** A view of the substitute where every member access or call is a setup (`sub[configure]().add(1, 2).returns(3)`). */ + [configure](): ConfigureView +} + +type StringSubstituteMethods = { + /** Asserts that the following member access, call or set happened `amount` times (1 or more when omitted). */ + received(amount?: number): TerminatingObject + /** Asserts that the following member access, call or set never happened. Same as `received(0)`. */ + didNotReceive(): TerminatingObject +} + +// If `T` has a public or private member named received, didNotReceive, returns, throws, resolves, rejects or +// mimicks, `sub.received` / `sub.didNotReceive` are not offered and the symbol forms `sub[received]()` / +// `sub[didNotReceive]()` must be used (D11). This rules out the ambiguous `sub.received().returns(...)`, which the +// runtime treats as a setup of a member called `received`. +// Distributive over `T`, so that for a type parameter with a constraint (`T extends Calculator`) TypeScript resolves the +// check against the constraint. For an unconstrained type parameter the check cannot be resolved, so only the symbol +// forms are offered. +type StringSubstituteMethodsUnlessConflicting = T extends unknown ? + (HasAnyMember extends true ? {} : StringSubstituteMethods) : + never + +export type ObjectSubstituteMethods = SymbolSubstituteMethods & StringSubstituteMethodsUnlessConflicting diff --git a/src/api/types/SubstitutionLevel.ts b/src/api/types/SubstitutionLevel.ts index 8cf326d..c3a91bc 100644 --- a/src/api/types/SubstitutionLevel.ts +++ b/src/api/types/SubstitutionLevel.ts @@ -1,4 +1,5 @@ import { constants } from '../../shared' +import { HasMember, LibraryMemberName } from './Utilities' export const returns: typeof constants.CONTEXT.returns.symbol = constants.CONTEXT.returns.symbol export const throws: typeof constants.CONTEXT.throws.symbol = constants.CONTEXT.throws.symbol @@ -6,36 +7,86 @@ export const resolves: typeof constants.CONTEXT.resolves.symbol = constants.CONT export const rejects: typeof constants.CONTEXT.rejects.symbol = constants.CONTEXT.rejects.symbol export const mimicks: typeof constants.CONTEXT.mimicks.symbol = constants.CONTEXT.mimicks.symbol -type OneArgumentRequiredFunction = (requiredInput: TArgs, ...restInputs: TArgs[]) => TReturnType; - -type MockObjectPromise = TReturnType extends Promise ? ( - (TReturnType extends { resolves: any } ? - { [resolves]: OneArgumentRequiredFunction } : - { resolves: OneArgumentRequiredFunction }) & - (TReturnType extends { rejects: any } ? - { [rejects]: OneArgumentRequiredFunction } : - { rejects: OneArgumentRequiredFunction }) -) : {} - -type BaseMockObjectMixin = - MockObjectPromise & - ( - (TObject extends { returns: any } ? - { [returns]: OneArgumentRequiredFunction } : - { returns: OneArgumentRequiredFunction }) & - (TObject extends { throws: any } ? - { [throws]: OneArgumentRequiredFunction } : - { throws: OneArgumentRequiredFunction }) - ) - -export type NoArgumentMockObjectMixin = - BaseMockObjectMixin & - (TObject extends { mimicks: any } ? - { [mimicks]: OneArgumentRequiredFunction<() => TReturnType, void> } : - { mimicks: OneArgumentRequiredFunction<() => TReturnType, void> }) - -export type MockObjectMixin = - BaseMockObjectMixin & - (TReturnType extends { mimicks: any } ? - { [mimicks]: OneArgumentRequiredFunction<(...args: TArguments) => TReturnType, void> } : - { mimicks: OneArgumentRequiredFunction<(...args: TArguments) => TReturnType, void> }) +type OneArgumentRequiredFunction = (requiredInput: TArgs, ...restInputs: TArgs[]) => TReturnType + +type ReturnsFunction = OneArgumentRequiredFunction +type ThrowsFunction = OneArgumentRequiredFunction +type MimicksFunction = OneArgumentRequiredFunction +type ResolvesFunction = OneArgumentRequiredFunction +type RejectsFunction = OneArgumentRequiredFunction + +// `null | undefined` are ignored when deciding whether the value is a promise or has a conflicting member: +// `Promise | undefined` still offers resolves/rejects. The check is not distributive (see T:TY-1). +type PromiseValue = [NonNullable] extends [Promise] ? U : never +type IsPromise = [NonNullable] extends [never] ? false : + [NonNullable] extends [Promise] ? true : false + +type SymbolSetupMethods = { + [returns]: ReturnsFunction + [throws]: ThrowsFunction + [mimicks]: MimicksFunction +} & (IsPromise extends true ? { + [resolves]: ResolvesFunction> + [rejects]: RejectsFunction +} : {}) + +type StringSetupMethods = { + returns: ReturnsFunction + throws: ThrowsFunction + mimicks: MimicksFunction +} & (IsPromise extends true ? { + resolves: ResolvesFunction> + rejects: RejectsFunction +} : {}) + +// The string form of a setup method is offered only when the value it is accessed on has no member with that name. +// Otherwise `value.returns` would be the value's own member (the symbol form `value[returns]` always works). +// `TValue` is checked per union member (so that a constrained type parameter is resolved through its constraint), but the +// method type is computed from the whole value type, so a union return type does not split the method (T:TY-1). +type StringForm = TValue extends unknown ? + (HasMember extends true ? {} : { [P in TName]: TMethod }) : + never + +type CheckedStringSetupMethods = + StringForm, 'returns', ReturnsFunction> & + StringForm, 'throws', ThrowsFunction> & + StringForm, 'mimicks', MimicksFunction> & + (IsPromise extends true ? ( + StringForm, 'resolves', ResolvesFunction>> & + StringForm, 'rejects', RejectsFunction> + ) : {}) + +// A member that never returns can only throw (or mimick an implementation that throws). +type NeverSetupMethods = { + [throws]: ThrowsFunction + [mimicks]: MimicksFunction + throws: ThrowsFunction + mimicks: MimicksFunction +} + +/** + * The setup API offered on the result of a member access or call of a substitute. + * `TReturnType` is the member's value (or return) type, `TImplementation` the function type `mimicks` accepts. + * `TReturnType` must not be `never`, `null` or `undefined` (see `SubstitutionResult`). + */ +type SetupMethods = + SymbolSetupMethods & CheckedStringSetupMethods + +/** The setup API without name-conflict checks, used where the value itself is not exposed (`[configure]()`). */ +export type UncheckedSetupMethods = + SymbolSetupMethods & StringSetupMethods + +/** + * The type of a member access or call on a substitute: the value intersected with the setup API. + * `null` and `undefined` cannot carry the setup API, so they are dropped from the value part (T:TY-9), while the + * setup methods still accept them. `never` (a member that always throws) only offers `throws` and `mimicks` (T:TY-12). + */ +export type SubstitutionResult = + [TReturnType] extends [never] ? NeverSetupMethods : + [NonNullable] extends [never] ? UncheckedSetupMethods : + NonNullable & SetupMethods + +/** The type of a member access or call on the `[configure]()` view: only the setup API. */ +export type ConfigurationResult = + [TReturnType] extends [never] ? NeverSetupMethods : + UncheckedSetupMethods diff --git a/src/api/types/Utilities.ts b/src/api/types/Utilities.ts new file mode 100644 index 0000000..1b20825 --- /dev/null +++ b/src/api/types/Utilities.ts @@ -0,0 +1,45 @@ +// Type-level helpers shared by the public typings. +// Keep these compatible with old TypeScript versions: no `as` clauses in mapped types, no template literal types, +// no variadic tuples and no `infer X extends Y` (see `npm run test:types:min-ts`). + +export type Equals = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false + +export type IsNever = [T] extends [never] ? true : false + +export type IsAny = 0 extends (1 & T) ? true : false + +/** The names the library uses: these are the names whose presence in a type the typings check. */ +export type LibraryMemberName = 'received' | 'didNotReceive' | 'returns' | 'throws' | 'resolves' | 'rejects' | 'mimicks' + +// The keys of T without those that only exist through a string index signature. +type KnownKeys = string extends keyof T ? + { [K in keyof T]: string extends K ? never : number extends K ? never : K }[keyof T] : + keyof T + +// A private member is not part of `keyof T`, but a public member with the same name cannot coexist with it: the +// intersection reduces to `never` (TypeScript >= 3.9). The probes have to be written out: the reduction does not +// happen for the properties of a mapped type such as `{ [P in K]: unknown }`. +type PrivateMemberProbe = { + received: { received: unknown } + didNotReceive: { didNotReceive: unknown } + returns: { returns: unknown } + throws: { throws: unknown } + resolves: { resolves: unknown } + rejects: { rejects: unknown } + mimicks: { mimicks: unknown } +} + +/** + * `true` when `T` has a public or private member named `K`, otherwise `false`. A protected member does not count (it + * does not clash with a public member of the same name), and neither does an index signature. The check is not + * distributive: for a union `T` it is `true` only when every member of the union has `K`. + */ +export type HasMember = + IsAny extends true ? true : + [K] extends [KnownKeys] ? true : + [T & PrivateMemberProbe[K]] extends [never] ? true : + false + +/** `true` when `T` has a member with at least one of the names in `K`. */ +export type HasAnyMember = + true extends (K extends LibraryMemberName ? HasMember : never) ? true : false diff --git a/src/index.ts b/src/index.ts index 75f54fb..a5c6567 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,21 @@ import { Substitute } from './api' +import { SubstituteException as SubstituteExceptionClass } from './internals/SubstituteException' + export * from './api' export default Substitute + +/** + * The error thrown when an assertion (`received` / `didNotReceive`) fails and on invalid use of the library. + * Use it with `instanceof`: `t.throws(() => sub.received().add(1, 2), { instanceOf: SubstituteException })`. + */ +export interface SubstituteException extends Error { + /** The kind of failure, e.g. 'CallCountMismatch'. */ + type?: string +} + +// Declared through a public interface so that the published typings do not depend on the internals (which reference +// Node's `util` typings). +export const SubstituteException: { + new (message: string): SubstituteException + readonly prototype: SubstituteException +} = SubstituteExceptionClass From 8ec9c1a2ce5370aad2fe7592e5024aabb9711a83 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 10:43:23 +0000 Subject: [PATCH 012/106] test(types): add type-level tests and a minimum TypeScript check - spec-types/: fixtures type-checked by `npm run test:types` (strict, and spec-types/loose without strict), one file per finding; must-fail lines use `@ts-expect-error`. `npm test` runs them first. - spec-types/min-ts: `npm run test:types:min-ts` builds dist/ and type-checks a consumer of the built typings (resolved through package.json, without @types/node) with an old TypeScript installed by npx (default 3.6, the measured minimum; other versions as arguments). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- package.json | 4 +- spec-types/D05.configure.ts | 64 +++++++++ spec-types/D11.assertion-name-conflicts.ts | 74 ++++++++++ spec-types/G-RG-9.substitute-exception.ts | 20 +++ spec-types/T-TY-01.mimicks-union-return.ts | 33 +++++ ...Y-02.G-RG-4.setup-method-name-conflicts.ts | 90 ++++++++++++ spec-types/T-TY-03.G-RG-3.generic-helpers.ts | 61 ++++++++ spec-types/T-TY-05.D12.mimick-symbol-only.ts | 23 +++ spec-types/T-TY-07.optional-members.ts | 35 +++++ spec-types/T-TY-08.index-signatures.ts | 36 +++++ spec-types/T-TY-10.zero-argument-overloads.ts | 33 +++++ spec-types/T-TY-11.many-overloads.ts | 61 ++++++++ spec-types/T-TY-12.never-return.ts | 17 +++ spec-types/T-TY-13.unknown-rest-parameters.ts | 19 +++ .../T-TY-14.private-member-conflicts.ts | 44 ++++++ spec-types/T-TY-16.D20.special-members.ts | 41 ++++++ spec-types/helpers.ts | 13 ++ spec-types/limitations.ts | 42 ++++++ spec-types/loose/non-strict.ts | 59 ++++++++ spec-types/loose/tsconfig.json | 12 ++ spec-types/min-ts/check.js | 78 ++++++++++ spec-types/min-ts/consumer.ts | 103 ++++++++++++++ spec-types/readme.ts | 134 ++++++++++++++++++ spec-types/tsconfig.json | 11 ++ 24 files changed, 1106 insertions(+), 1 deletion(-) create mode 100644 spec-types/D05.configure.ts create mode 100644 spec-types/D11.assertion-name-conflicts.ts create mode 100644 spec-types/G-RG-9.substitute-exception.ts create mode 100644 spec-types/T-TY-01.mimicks-union-return.ts create mode 100644 spec-types/T-TY-02.G-RG-4.setup-method-name-conflicts.ts create mode 100644 spec-types/T-TY-03.G-RG-3.generic-helpers.ts create mode 100644 spec-types/T-TY-05.D12.mimick-symbol-only.ts create mode 100644 spec-types/T-TY-07.optional-members.ts create mode 100644 spec-types/T-TY-08.index-signatures.ts create mode 100644 spec-types/T-TY-10.zero-argument-overloads.ts create mode 100644 spec-types/T-TY-11.many-overloads.ts create mode 100644 spec-types/T-TY-12.never-return.ts create mode 100644 spec-types/T-TY-13.unknown-rest-parameters.ts create mode 100644 spec-types/T-TY-14.private-member-conflicts.ts create mode 100644 spec-types/T-TY-16.D20.special-members.ts create mode 100644 spec-types/helpers.ts create mode 100644 spec-types/limitations.ts create mode 100644 spec-types/loose/non-strict.ts create mode 100644 spec-types/loose/tsconfig.json create mode 100644 spec-types/min-ts/check.js create mode 100644 spec-types/min-ts/consumer.ts create mode 100644 spec-types/readme.ts create mode 100644 spec-types/tsconfig.json diff --git a/package.json b/package.json index f03b6ba..527baec 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,9 @@ ], "scripts": { "build": "rm -rf dist && tsc", - "test": "npm run build -- -p spec && ava" + "test": "npm run test:types && npm run build -- -p spec && ava", + "test:types": "tsc -p spec-types && tsc -p spec-types/loose", + "test:types:min-ts": "npm run build && node spec-types/min-ts/check.js" }, "devDependencies": { "@ava/typescript": "^3.0.1", diff --git a/spec-types/D05.configure.ts b/spec-types/D05.configure.ts new file mode 100644 index 0000000..e4b9cbb --- /dev/null +++ b/spec-types/D05.configure.ts @@ -0,0 +1,64 @@ +// D5 `sub[configure]()` is a view of the substitute in which member reads and calls are always setups. They expose the +// setup API (returns / throws / mimicks, and resolves / rejects for promises) and nothing else: no received / +// didNotReceive, and not the configured value. +import { Substitute, Arg, configure, returns, throws, mimicks, resolves, rejects } from '../src' +import { expectType } from './helpers' + +interface Calculator { + add(a: number, b: number): number + divide(a: number, b: number): number + heavyOperation(): Promise + find(id: string): string | null + reset(): void + isEnabled: boolean + received(count: number): string + returns: string[] +} + +const calculator = Substitute.for() +const setup = calculator[configure]() +setup.add(1, 3).returns(1337) +setup.add(1, 3).returns(1, 2, 3) +setup.add(Arg.all()).mimicks((a, b) => a + b) +setup.add(Arg.any(), Arg.is(b => b > 0)).throws(new Error()) +setup.divide(1, 0)[throws](new Error('Cannot divide by 0')) +setup.heavyOperation().resolves(4) +setup.heavyOperation().rejects(new Error()) +setup.heavyOperation()[resolves](4) +setup.heavyOperation()[rejects](new Error()) +setup.find('1').returns(null) +setup.reset().returns() +setup.isEnabled.returns(true) +setup.isEnabled[mimicks](() => false) +setup.add.returns((a, b) => a * b) +// members named like the library's methods are ordinary members here +setup.received(1).returns('one') +setup.returns.returns(['r']) +setup.returns[returns](['r']) + +// @ts-expect-error the configured value must have the member's type +setup.add(1, 3).returns('1337') +// @ts-expect-error resolves() is only offered for promises +setup.add(1, 3).resolves(1) +// @ts-expect-error the view only offers the setup API, not the value +const value: number = setup.add(1, 3) +// @ts-expect-error no assertions on the configure view +calculator[configure]().received(1).add(1, 3) +// @ts-expect-error the view has no assertion methods +setup.didNotReceive() +// @ts-expect-error the view has no configure method itself +setup[configure]() + +expectType(calculator.add(1, 3)) +export { value } + +// members typed `any` +interface Loose { value: any; call: any; method(input: any): any } +const loose = Substitute.for() +loose[configure]().call(1, 2).returns(3) +loose[configure]().value.returns(1) +loose[configure]().method(Arg.any()).returns(2) +loose.call(1).returns(3) +loose.value.returns(1) +loose.method(1).returns(2) +loose.received().call(1) diff --git a/spec-types/D11.assertion-name-conflicts.ts b/spec-types/D11.assertion-name-conflicts.ts new file mode 100644 index 0000000..7e985f0 --- /dev/null +++ b/spec-types/D11.assertion-name-conflicts.ts @@ -0,0 +1,74 @@ +// D11 If T has a member named received, didNotReceive, returns, throws, resolves, rejects or mimicks, only the symbol +// forms `sub[received]()` / `sub[didNotReceive]()` are offered. This rules out the ambiguous `sub.received().returns(5)`, +// which the runtime treats as a setup of a member called `received`. The symbol forms are always offered. +import { Substitute, Arg, received, didNotReceive, clearReceivedCalls } from '../src' + +interface Plain { add(a: number, b: number): number } +const plain = Substitute.for() +plain.received().add(1, 2) +plain.received(2).add(1, 2) +plain.didNotReceive().add(1, 2) +plain[received]().add(1, 2) +plain[received](0).add(1, 2) +plain[didNotReceive]().add(1, 2) +plain[clearReceivedCalls]() + +interface Account { + returns(item: string): number + balance(): number +} +const account = Substitute.for() +account.returns('book').returns(5) +account[received]().returns('book') +account[received](1).balance() +account[didNotReceive]().returns(Arg.any()) +// @ts-expect-error ambiguous: Account has a member named `returns` +account.received().returns('book') +// @ts-expect-error ambiguous: Account has a member named `returns` +account.didNotReceive().balance() + +interface Inbox { + received: string[] + didNotReceive(): boolean + open(): void +} +const inbox = Substitute.for() +inbox.received.returns(['mail']) +inbox.didNotReceive().returns(true) +inbox[received]().open() +inbox[received]().didNotReceive() +inbox[received](2).received +inbox[didNotReceive]().open() +// `inbox.received` is the member, not the assertion +// @ts-expect-error string[] is not callable +inbox.received(1) + +// every name in the rule +interface WithThrows { throws: boolean; run(): void } +interface WithResolves { resolves(): void; run(): void } +interface WithRejects { rejects: number; run(): void } +interface WithMimicks { mimicks(): void; run(): void } +const withThrows = Substitute.for() +const withResolves = Substitute.for() +const withRejects = Substitute.for() +const withMimicks = Substitute.for() +withThrows[received]().run() +withResolves[received]().run() +withRejects[received]().run() +withMimicks[received]().run() +// @ts-expect-error WithThrows has a member named `throws` +withThrows.received() +// @ts-expect-error WithResolves has a member named `resolves` +withResolves.received() +// @ts-expect-error WithRejects has a member named `rejects` +withRejects.didNotReceive() +// @ts-expect-error WithMimicks has a member named `mimicks` +withMimicks.didNotReceive() + +// Members named mimick, configure or clearReceivedCalls do not conflict: those are symbol-only APIs. +interface Tools { mimick(): void; configure(): void; clearReceivedCalls(): void } +const tools = Substitute.for() +tools.received().configure() +tools.configure().returns() +tools.clearReceivedCalls() +tools[clearReceivedCalls]() diff --git a/spec-types/G-RG-9.substitute-exception.ts b/spec-types/G-RG-9.substitute-exception.ts new file mode 100644 index 0000000..22fc028 --- /dev/null +++ b/spec-types/G-RG-9.substitute-exception.ts @@ -0,0 +1,20 @@ +// G:RG-9 SubstituteException is exported from the package index, so `instanceof` works without deep imports. +import SubstituteDefault, { Substitute, SubstituteException } from '../src' +import { expectType } from './helpers' + +interface Calculator { add(a: number, b: number): number } +const calculator = Substitute.for() + +try { + calculator.received().add(1, 2) +} catch (error) { + if (error instanceof SubstituteException) { + expectType(error.message) + expectType(error.type) + expectType(error) + } +} + +const exception: Error = new SubstituteException('message') +expectType(SubstituteDefault) +export { exception } diff --git a/spec-types/T-TY-01.mimicks-union-return.ts b/spec-types/T-TY-01.mimicks-union-return.ts new file mode 100644 index 0000000..e0d704e --- /dev/null +++ b/spec-types/T-TY-01.mimicks-union-return.ts @@ -0,0 +1,33 @@ +// T:TY-1 mimicks() on methods with parameters whose return type is a union (boolean, T | undefined, enums, literal unions) +import { Substitute, Arg, mimicks } from '../src' + +enum Status { Active, Disabled } + +interface Validator { + isValid(input: string): boolean + find(id: number): string | undefined + status(id: number): Status + level(id: number): 'low' | 'high' + isReady(): boolean + enabled: boolean +} + +const v = Substitute.for() +v.isValid(Arg.any()).mimicks((input: string) => input.length > 3) +v.find(Arg.any()).mimicks((id: number) => (id > 0 ? 'found' : undefined)) +v.status(Arg.all()).mimicks((id: number) => Status.Active) +v.level(1).mimicks(id => (id > 1 ? 'high' : 'low')) +v.isValid('x')[mimicks](() => true) +v.isReady().mimicks(() => false) +v.enabled.mimicks(() => true) + +v.isValid('x').returns(true) +v.isValid('x').returns(false, true) +v.find(1).returns(undefined) +v.find(1).returns('a', undefined) +v.status(1).returns(Status.Disabled) + +// @ts-expect-error the implementation must return the member's return type +v.isValid('x').mimicks(() => 'yes') +// @ts-expect-error the implementation must accept the member's parameters +v.find(1).mimicks((id: string) => id) diff --git a/spec-types/T-TY-02.G-RG-4.setup-method-name-conflicts.ts b/spec-types/T-TY-02.G-RG-4.setup-method-name-conflicts.ts new file mode 100644 index 0000000..38625e5 --- /dev/null +++ b/spec-types/T-TY-02.G-RG-4.setup-method-name-conflicts.ts @@ -0,0 +1,90 @@ +// T:TY-2 / G:RG-4 One rule for `.returns` vs `[returns]` (also throws, mimicks, resolves, rejects): +// the string form is offered unless the VALUE it is accessed on (the property type or the call's return type) has a +// member with that name. The symbol form is always offered. Whether the containing interface has such a member does +// not matter, and properties, methods without arguments and methods with arguments all behave the same. +import { Substitute, Arg, returns, throws, mimicks, resolves, rejects, configure } from '../src' +import { expectType } from './helpers' + +// (A) the mocked interface has members named returns / throws / mimicks +interface Order { + returns: string[] + throws: boolean + mimicks(): void + id: string + total(): number + lineTotal(index: number): number +} +const order = Substitute.for() +order.lineTotal(0).returns(5) +order.total().returns(10) +order.id.returns('o-1') +order.lineTotal(0).throws(new Error()) +order.total().throws(new Error()) +order.id.throws(new Error()) +order.lineTotal(0).mimicks(index => index * 2) +order.total().mimicks(() => 1) +order.id.mimicks(() => 'o-2') +order.lineTotal(0)[returns](5) +order.total()[returns](10) +order.id[returns]('o-1') +order.id[throws](new Error()) +order.total()[mimicks](() => 1) +// the conflicting members themselves are ordinary members +order.returns.returns(['r-1']) +order.throws.returns(true) +order.mimicks().returns() + +// (B) a member's VALUE type has members named returns / throws / mimicks +interface Shop { + current: Order + latest(): Order + find(id: string): Order + maybe(id: string): Order | undefined + load(): Promise +} +const shop = Substitute.for() +const o: Order = Substitute.for() +shop.find('1')[returns](o) +shop.latest()[returns](o) +shop.current[returns](o) +shop.maybe('1')[returns](o) +shop.maybe('1')[returns](undefined) +shop.find('1')[throws](new Error()) +shop.latest()[mimicks](() => o) +shop.find(Arg.any())[mimicks](() => o) +// `.returns` / `.throws` / `.mimicks` are the Order's own members there +expectType(shop.find('1').returns) +expectType(shop.current.throws) +// @ts-expect-error not the setup method: Order's own `returns: string[]` +shop.find('1').returns(o) +// @ts-expect-error not the setup method: Order's own `returns: string[]` +shop.latest().returns(o) +// @ts-expect-error not the setup method: Order's own `returns: string[]` +shop.current.returns(o) +// @ts-expect-error not the setup method: Order's own `returns: string[]` +shop.maybe('1').returns(o) +// @ts-expect-error not the setup method: Order's own `mimicks(): void` +shop.find('1').mimicks(() => o) +// a Promise has no member named returns, so the string form is offered there +shop.load().returns(Promise.resolve(o)) +shop.load().resolves(o) + +// (C) resolves / rejects on a promise type that has members with those names +interface Deferred extends Promise { + resolves: number + rejects: number +} +interface Scheduler { next(): Deferred } +const scheduler = Substitute.for() +scheduler.next()[resolves]('done') +scheduler.next()[rejects](new Error()) +scheduler.next().returns(value>()) +// @ts-expect-error not the setup method: Deferred's own `resolves: number` +scheduler.next().resolves('done') + +// The [configure]() view never returns the value itself, so the string forms are always offered there. +shop[configure]().find('1').returns(o) +shop[configure]().current.returns(o) +shop[configure]().latest().mimicks(() => o) + +declare function value(): T diff --git a/spec-types/T-TY-03.G-RG-3.generic-helpers.ts b/spec-types/T-TY-03.G-RG-3.generic-helpers.ts new file mode 100644 index 0000000..8ffe4aa --- /dev/null +++ b/spec-types/T-TY-03.G-RG-3.generic-helpers.ts @@ -0,0 +1,61 @@ +// T:TY-3 / G:RG-3 received / didNotReceive / clearReceivedCalls / mimick / configure on SubstituteOf for a generic T. +// The symbol API is always available. The string forms `sub.received()` / `sub.didNotReceive()` are offered only when +// TypeScript can tell that T has no conflicting member (D11): for a constrained type parameter it checks the constraint, +// for an unconstrained one it cannot, so generic helpers use the symbol forms. +import { Substitute, SubstituteOf, received, didNotReceive, clearReceivedCalls, mimick, configure } from '../src' + +export function expectNoCalls(sub: SubstituteOf) { + return sub[didNotReceive]() +} +export function expectSomeCall(sub: SubstituteOf) { + return sub[received]() +} +export function once(sub: SubstituteOf) { + return sub[received](1) +} +export function reset(sub: SubstituteOf) { + sub[clearReceivedCalls]() +} +export function setup(sub: SubstituteOf) { + return sub[configure]() +} +export function delegate(sub: SubstituteOf, instance: T) { + sub[mimick](instance) +} +export function create(): SubstituteOf { + const sub = Substitute.for() + sub[received]() + return sub +} +export class Fixture { + sub = Substitute.for() + verify() { + return this.sub[received]() + } +} + +interface Calculator { add(a: number, b: number): number } + +const calculator = create() +calculator.add(1, 2) +once(calculator).add(1, 2) +expectNoCalls(calculator).add(3, 4) +expectSomeCall(calculator).add(1, 2) +setup(calculator).add(1, 2).returns(3) +delegate(calculator, { add: (a, b) => a + b }) +new Fixture().verify().add(1, 2) + +// A constraint without conflicting members keeps the string forms. +export function viaConstraint(sub: SubstituteOf) { + sub.received().add(1, 2) + sub.didNotReceive().add(1, 2) + sub[received](2).add(1, 2) +} + +// An unconstrained T could have a member named `received` (or `returns`, ...), so the string forms are not offered. +export function stringFormsNeedAKnownType(sub: SubstituteOf) { + // @ts-expect-error use sub[received]() in generic code + sub.received() + // @ts-expect-error use sub[didNotReceive]() in generic code + sub.didNotReceive() +} diff --git a/spec-types/T-TY-05.D12.mimick-symbol-only.ts b/spec-types/T-TY-05.D12.mimick-symbol-only.ts new file mode 100644 index 0000000..cad9f2b --- /dev/null +++ b/spec-types/T-TY-05.D12.mimick-symbol-only.ts @@ -0,0 +1,23 @@ +// T:TY-5 / D12 `mimick` is a symbol-only API: `sub[mimick](instance)`. The string `mimick` is never a library method, +// it is an ordinary member of T (if T has one). +import { Substitute, mimick } from '../src' + +interface Calculator { add(a: number, b: number): number } +const real: Calculator = { add: (a, b) => a + b } +const calculator = Substitute.for() +calculator[mimick](real) +calculator[mimick]({ add: () => 0 }) +// @ts-expect-error the string form is not a library method +calculator.mimick(real) +// @ts-expect-error the instance must implement T +calculator[mimick]({ subtract: (a: number, b: number) => a - b }) + +// A member called `mimick` is just a member. +interface Puppet { + mimick(sound: string): string + speak(): string +} +const puppet = Substitute.for() +puppet.mimick('woof').returns('WOOF') +puppet.received().mimick('woof') +puppet[mimick]({ mimick: sound => sound, speak: () => 'hi' }) diff --git a/spec-types/T-TY-07.optional-members.ts b/spec-types/T-TY-07.optional-members.ts new file mode 100644 index 0000000..20b3d29 --- /dev/null +++ b/spec-types/T-TY-07.optional-members.ts @@ -0,0 +1,35 @@ +// T:TY-7 Optional properties and methods (`prop?`, `method?()`) are configured and asserted like required ones. +import { Substitute, Arg, configure, received } from '../src' + +interface Options { + timeout?: number + onDone?(): string + format?(value: number): string + callback?: (error: Error | null) => void + nested?: { level: number } +} + +const o = Substitute.for() +o.timeout.returns(1000) +o.timeout.returns(undefined) +o.onDone().returns('done') +o.format(1).returns('1') +o.format(Arg.any()).mimicks(value => String(value)) +o.callback(null).returns() +o.nested.returns({ level: 1 }) +o.received().format(1) +o.received().onDone() +o.didNotReceive().callback(Arg.any()) +o.received().timeout = 5 +o[received](1).timeout +o[configure]().timeout.returns(1) +o[configure]().format(Arg.all()).returns('x') + +// The substitute is still an Options. +const options: Options = o +export { options } + +// @ts-expect-error the configured value must have the member's type +o.timeout.returns('1000') +// @ts-expect-error wrong argument type +o.format('1') diff --git a/spec-types/T-TY-08.index-signatures.ts b/spec-types/T-TY-08.index-signatures.ts new file mode 100644 index 0000000..ba34c47 --- /dev/null +++ b/spec-types/T-TY-08.index-signatures.ts @@ -0,0 +1,36 @@ +// T:TY-8 An index signature does not wipe out the substitute typing of the named members. +import { Substitute } from '../src' + +interface Config { + name: string + load(): string + get(key: string): string + [key: string]: unknown +} +const c = Substitute.for() +c.name.returns('app') +c.load().returns('loaded') +c.get('a').returns('b') +c.received().get('a') +c.anything.returns(42) + +interface Registry { + [id: string]: (input: number) => number +} +const registry = Substitute.for() +registry.double(2).returns(4) +registry.received().double(2) + +interface NumberIndexed { + length: number + [index: number]: string +} +const list = Substitute.for() +list.length.returns(1) +list[0].returns('first') + +const record = Substitute.for number>>() +record.foo().returns(1) + +// @ts-expect-error the configured value must have the member's type +c.name.returns(1) diff --git a/spec-types/T-TY-10.zero-argument-overloads.ts b/spec-types/T-TY-10.zero-argument-overloads.ts new file mode 100644 index 0000000..ad868db --- /dev/null +++ b/spec-types/T-TY-10.zero-argument-overloads.ts @@ -0,0 +1,33 @@ +// T:TY-10 Overloads without parameters do not break the other overloads, and a single matcher argument resolves to +// the overload with one parameter (not to an Arg.all() signature of the zero-parameter overload). +import { Substitute, Arg } from '../src' +import { expectType } from './helpers' + +// (a) zero-parameter overload declared last +interface Field { + value(newValue: string): void + value(): string +} +const field = Substitute.for() +field.value().returns('current') +field.value('x').throws(new Error('read-only')) +field.value(Arg.any()).returns() +field.received().value('x') +field.received().value() + +// (b) zero-parameter overload declared first +interface Store { + get(): string[] + get(key: string): string +} +const store = Substitute.for() +store.get('k').returns('v') +store.get(Arg.any()).returns('v') +store.get(Arg.is(k => k.startsWith('user:'))).returns('v') +store.get().returns(['a']) +store.received().get(Arg.is(k => k.length > 0)) +expectType(store.get('k')) +expectType(store.get()) + +// @ts-expect-error the overload with a parameter returns a string +store.get(Arg.any()).returns(['v']) diff --git a/spec-types/T-TY-11.many-overloads.ts b/spec-types/T-TY-11.many-overloads.ts new file mode 100644 index 0000000..2890981 --- /dev/null +++ b/spec-types/T-TY-11.many-overloads.ts @@ -0,0 +1,61 @@ +// T:TY-11 Methods with up to 8 overloads keep the substitute typing on every overload. (With more than 8 overloads, +// only the last 8 have it; that limit is documented.) +import { Substitute, Arg, configure } from '../src' + +interface A { a: 1 } interface B { b: 1 } interface C { c: 1 } interface D { d: 1 } +interface E { e: 1 } interface F { f: 1 } interface G { g: 1 } interface H { h: 1 } + +interface Six { + f(a: string): string[] + f(a: number): number[] + f(a: boolean): boolean[] + f(a: symbol): symbol[] + f(a: Date): Date[] + f(a: RegExp): RegExp[] +} +const six = Substitute.for() +six.f('x').returns(['x']) +six.f(1).returns([1]) +six.f(true).returns([true]) +six.f(Symbol.iterator).returns([Symbol.iterator]) +six.f(new Date()).returns([]) +six.f(/x/).returns([/x/]) +six.f(Arg.all()).returns(['any']) +six.received().f('x') +six.received().f(/x/) + +interface Eight { + g(a: A): 'A' + g(a: B): 'B' + g(a: C): 'C' + g(a: D): 'D' + g(a: E): 'E' + g(a: F): 'F' + g(a: G): 'G' + g(a: H): 'H' +} +const eight = Substitute.for() +eight.g({ a: 1 }).returns('A') +eight.g({ d: 1 }).returns('D') +eight.g({ h: 1 }).returns('H') + +// @ts-expect-error each overload keeps its own return type +six.f('x').returns([1]) +// @ts-expect-error each overload keeps its own return type +eight.g({ a: 1 }).returns('B') + +// Overloads whose parameters are declared with literal types (`f(a: 'x')`, `f(a: null)`) are tried first by TypeScript, +// before any other signature, so a direct call resolves to the interface's own declaration and has no setup API. +// The [configure]() view has no such declarations: use it to configure these overloads. +interface Events { + on(event: 'data', listener: (chunk: string) => void): this + on(event: 'end', listener: () => void): this + get(key: null): undefined + get(key: string): string +} +const events = Substitute.for() +events[configure]().on('data', Arg.any()).returns(events) +events[configure]().on('end', Arg.any()).returns(events) +events[configure]().get(null).returns(undefined) +events.get('k').returns('v') +events.received().on('data', Arg.any()) diff --git a/spec-types/T-TY-12.never-return.ts b/spec-types/T-TY-12.never-return.ts new file mode 100644 index 0000000..e7efaf1 --- /dev/null +++ b/spec-types/T-TY-12.never-return.ts @@ -0,0 +1,17 @@ +// T:TY-12 Members that return `never` can be configured with .throws() (and .mimicks()). +import { Substitute, Arg, throws } from '../src' + +interface Guard { + fail(message: string): never + abort(): never +} +const g = Substitute.for() +g.fail('boom').throws(new Error('boom')) +g.fail(Arg.any()).throws(new Error('boom')) +g.abort().throws(new Error('abort')) +g.abort()[throws](new Error('abort')) +g.fail(Arg.all()).mimicks((message: string) => { throw new Error(message) }) +g.received().fail('boom') + +// @ts-expect-error nothing can be returned from a member that never returns +g.abort().returns(1) diff --git a/spec-types/T-TY-13.unknown-rest-parameters.ts b/spec-types/T-TY-13.unknown-rest-parameters.ts new file mode 100644 index 0000000..b776e4b --- /dev/null +++ b/spec-types/T-TY-13.unknown-rest-parameters.ts @@ -0,0 +1,19 @@ +// T:TY-13 Methods declared with `(...args: unknown[])` keep the substitute typing. +import { Substitute, Arg } from '../src' + +interface Logger { + format(...args: unknown[]): string + formatAny(...args: any[]): string + log(message: string, ...rest: unknown[]): void + anything(...args: unknown[]): unknown +} +const logger = Substitute.for() +logger.format('a', 1).returns('a 1') +logger.format(Arg.all()).mimicks((...args: unknown[]) => args.join(' ')) +logger.formatAny('a', 1).returns('a 1') +logger.log('x', 1, 2).returns() +logger.anything(1).returns(2) +logger.received().format('a', 1) + +// @ts-expect-error the configured value must be a string +logger.format('a', 1).returns(1) diff --git a/spec-types/T-TY-14.private-member-conflicts.ts b/spec-types/T-TY-14.private-member-conflicts.ts new file mode 100644 index 0000000..d9219f2 --- /dev/null +++ b/spec-types/T-TY-14.private-member-conflicts.ts @@ -0,0 +1,44 @@ +// T:TY-14 A class with a private member named received / didNotReceive / mimick (or returns, throws, ...) does not turn +// the substitute type into `never`. Such a class is treated like a conflicting member (D11): use the symbol forms. +import { Substitute, received, didNotReceive, returns } from '../src' + +class Inbox { + private received: string[] = [] + count(): number { return this.received.length } +} +const inbox = Substitute.for() +inbox.count().returns(3) +inbox[received]().count() +inbox[didNotReceive]().count() +const asInbox: Inbox = inbox + +class Outbox { + private didNotReceive = false + private mimick = 1 + send(message: string): boolean { return !this.didNotReceive && this.mimick > 0 && message.length > 0 } +} +const outbox = Substitute.for() +outbox.send('hi').returns(true) +outbox[received]().send('hi') + +// A value type with a private member named like a setup method uses the symbol form for it. +class Receipt { + private returns = 0 + total(): number { return this.returns } +} +interface Till { print(): Receipt } +const till = Substitute.for() +const receipt: Receipt = Substitute.for() +till.print()[returns](receipt) +till.print().throws(new Error()) +till.print().total() + +class Protected { + protected received = 1 + size(): number { return this.received } +} +const prot = Substitute.for() +prot.size().returns(2) +prot[received]().size() + +export { asInbox } diff --git a/spec-types/T-TY-16.D20.special-members.ts b/spec-types/T-TY-16.D20.special-members.ts new file mode 100644 index 0000000..176c37b --- /dev/null +++ b/spec-types/T-TY-16.D20.special-members.ts @@ -0,0 +1,41 @@ +// T:TY-16 / D20 Members the runtime special-cases. +// - `then`: a substitute never exposes it (so that it is not a thenable and `await sub` resolves to the substitute). +// It is `never` on the substitute: calling, configuring or asserting it does not compile. +// - `toJSON`: answered by the substitute itself (it serializes the substitute). It keeps its declared type, but it has +// no setup API and cannot be configured or asserted. +import { Substitute, Arg, configure, received } from '../src' +import { expectType } from './helpers' + +interface Job { + then(callback: (value: number) => void): void + toJSON(): string + run(): number +} +const j = Substitute.for() +j.run().returns(1) +expectType(j.toJSON()) +// The substitute is still a Job (for the code under test). +const asJob: Job = j +async function awaitsTheSubstitute() { + const awaited = await j + return awaited.run() +} + +// @ts-expect-error `then` is never exposed by a substitute +j.then(Arg.any()) +// @ts-expect-error `then` cannot be configured +j.then.returns(() => undefined) +// @ts-expect-error `toJSON` cannot be configured +j.toJSON().returns('{}') +// @ts-expect-error `toJSON` cannot be configured +j.toJSON.returns(() => '{}') +// @ts-expect-error `then` cannot be asserted +j.received().then(Arg.any()) +// @ts-expect-error `toJSON` cannot be asserted +j[received]().toJSON() +// @ts-expect-error `then` cannot be configured +j[configure]().then(Arg.any()) +// @ts-expect-error `toJSON` cannot be configured +j[configure]().toJSON().returns('{}') + +export { asJob, awaitsTheSubstitute } diff --git a/spec-types/helpers.ts b/spec-types/helpers.ts new file mode 100644 index 0000000..9907154 --- /dev/null +++ b/spec-types/helpers.ts @@ -0,0 +1,13 @@ +// Helpers for the type-level tests. Nothing in spec-types/ is executed: `npm run test:types` only type-checks it. +// Lines that must NOT compile are marked with `// @ts-expect-error` (tsc fails if such a line compiles). + +export type Equals = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false + +/** Compile-time assertion: `assert>()` compiles only when X and Y are the same type. */ +export function assert(): void { } + +/** Compile-time assertion: compiles only when `value` is assignable to `T`. */ +export function expectType(_value: T): void { } + +/** A value of any type, for arguments whose value does not matter. */ +export declare function value(): T diff --git a/spec-types/limitations.ts b/spec-types/limitations.ts new file mode 100644 index 0000000..c52010d --- /dev/null +++ b/spec-types/limitations.ts @@ -0,0 +1,42 @@ +// Documented limitations of the typings (TypeScript cannot express these). Each `@ts-expect-error` line shows the +// limitation, the line after it a way around it. +import { Substitute, Arg, configure } from '../src' + +// T:TY-6 Assigning a property directly on a substitute: the property's type carries the setup API (`.returns`, ...), +// and TypeScript uses the same type for reads and writes of a mapped property. +interface Calculator { isEnabled: boolean } +const calculator = Substitute.for() +// @ts-expect-error `true` lacks the setup API +calculator.isEnabled = true +const asCalculator: Calculator = calculator +asCalculator.isEnabled = true // as the code under test does it +calculator.received().isEnabled = true + +// T:TY-9 `null` / `undefined` cannot carry the setup API, so they are not part of the type of a call or property read +// (strictNullChecks). The value is still assignable to the declared type. +interface UserRepo { find(id: number): string | null } +const repo = Substitute.for() +repo.find(1).returns(null) +const found: string | null = repo.find(1) +declare function is(actual: Actual, expected: Expected): void // like ava's t.is +// @ts-expect-error `null` is not part of `string & setup API` +is(repo.find(1), null) +is(repo.find(1), null) + +// T:TY-15 Explicit type arguments on a generic method resolve to the interface's own declaration (TypeScript cannot +// carry a method's type parameters over to the substitute's signatures). +interface Repository { get(id: string): T } +const repository = Substitute.for() +repository.get('1').returns({ a: 1 }) +// @ts-expect-error no setup API on the interface's own declaration +repository.get('1').returns(1) +repository.get('1').returns(1) + +// Overloads whose parameters are declared with literal types: see T-TY-11.many-overloads.ts. +interface Events { on(event: 'data', listener: () => void): this } +const events = Substitute.for() +// @ts-expect-error resolves to the interface's own declaration +events.on('data', Arg.any()).returns(events) +events[configure]().on('data', Arg.any()).returns(events) + +export { found } diff --git a/spec-types/loose/non-strict.ts b/spec-types/loose/non-strict.ts new file mode 100644 index 0000000..0ab9ecf --- /dev/null +++ b/spec-types/loose/non-strict.ts @@ -0,0 +1,59 @@ +// The typings must also work without `strict` (no strictNullChecks, no strictFunctionTypes), as in spec/tsconfig.json. +import { Substitute, Arg, received, returns, configure, mimick } from '../../src' + +interface Calculator { + add(a: number, b: number): number + divide(a: number, b: number): number + heavyOperation(...numbers: number[]): Promise + find(id: number): string | null + isValid(input: string): boolean + timeout?: number + format?(value: number): string + isEnabled: boolean +} +const calculator = Substitute.for() +calculator.add(1, 2).returns(3) +calculator.add(Arg.all()).mimicks((a, b) => a + b) +calculator.add(Arg.is(x => x > 1), Arg.any()).returns(1) +calculator.heavyOperation(1, 2).resolves(4) +calculator.find(1).returns(null) +calculator.isValid(Arg.any()).mimicks(input => input.length > 3) +calculator.timeout.returns(1) +calculator.format(1).returns('1') +calculator.isEnabled.returns(true) +calculator.received().add(1, 2) +calculator.received(2).isEnabled = true +calculator[received]().add(1, 2) +calculator[configure]().add(1, 2).returns(3) +calculator[mimick]({} as Calculator) +const asCalculator: Calculator = calculator + +// overloads, including one without parameters +interface Store { + get(): string[] + get(key: string): string + set(key: string, value: string): void + set(entries: Record): void +} +const store = Substitute.for() +store.get().returns(['a']) +store.get('k').returns('v') +store.get(Arg.is(k => k.startsWith('a'))).returns('v') +store.set('k', 'v').returns() +store.set({ k: 'v' }).throws(new Error()) +store.received().set(Arg.all()) + +// value types with conflicting member names +interface Order { returns: string[]; total(): number } +interface Shop { find(id: string): Order } +const shop = Substitute.for() +shop.find('1')[returns](Substitute.for()) +// @ts-expect-error Order's own `returns` member +shop.find('1').returns(Substitute.for()) + +// @ts-expect-error the configured value must have the member's type +calculator.add(1, 2).returns('3') +// @ts-expect-error resolves() is only offered for promises +calculator.add(1, 2).resolves(3) + +export { asCalculator } diff --git a/spec-types/loose/tsconfig.json b/spec-types/loose/tsconfig.json new file mode 100644 index 0000000..19a390b --- /dev/null +++ b/spec-types/loose/tsconfig.json @@ -0,0 +1,12 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "declaration": false, + "strict": false, + "noImplicitAny": true + }, + "include": [ + "./*.ts" + ] +} diff --git a/spec-types/min-ts/check.js b/spec-types/min-ts/check.js new file mode 100644 index 0000000..ea05ac3 --- /dev/null +++ b/spec-types/min-ts/check.js @@ -0,0 +1,78 @@ +#!/usr/bin/env node +// Type-checks spec-types/min-ts/consumer.ts against the BUILT package typings (dist/*.d.ts, resolved through +// package.json like an installed package) with older TypeScript versions, each installed on the fly with npx. +// +// npm run test:types:min-ts # builds dist/, then checks the minimum supported version +// node spec-types/min-ts/check.js 3.9 4.0 4.4 # after `npm run build`: check other versions +// +// The consumer is compiled with `strict`, without @types/node and with skipLibCheck both off and on. +'use strict' +const { spawnSync } = require('child_process') +const fs = require('fs') +const os = require('os') +const path = require('path') + +const MINIMUM_TYPESCRIPT_VERSION = '3.6' + +const root = path.resolve(__dirname, '..', '..') +const versions = process.argv.slice(2).length > 0 ? process.argv.slice(2) : [MINIMUM_TYPESCRIPT_VERSION] +const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx' + +const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) +const typings = packageJson.types || packageJson.typings +if (!typings || !fs.existsSync(path.join(root, typings))) { + console.error(`The package typings (${typings}) were not found: run \`npm run build\` first.`) + process.exit(1) +} + +const copyDirectory = (from, to) => { + fs.mkdirSync(to, { recursive: true }) + for (const entry of fs.readdirSync(from, { withFileTypes: true })) { + const source = path.join(from, entry.name) + const target = path.join(to, entry.name) + if (entry.isDirectory()) copyDirectory(source, target) + else fs.copyFileSync(source, target) + } +} + +const workDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'substitute-min-ts-')) +let failed = false +try { + const packageDirectory = path.join(workDirectory, 'node_modules', '@fluffy-spoon', 'substitute') + fs.mkdirSync(packageDirectory, { recursive: true }) + fs.copyFileSync(path.join(root, 'package.json'), path.join(packageDirectory, 'package.json')) + copyDirectory(path.join(root, 'dist'), path.join(packageDirectory, 'dist')) + fs.copyFileSync(path.join(__dirname, 'consumer.ts'), path.join(workDirectory, 'consumer.ts')) + + for (const skipLibCheck of [false, true]) { + const compilerOptions = { + module: 'commonjs', + moduleResolution: 'node', + target: 'es2018', + lib: ['es2018'], + strict: true, + noEmit: true, + skipLibCheck, + types: [] + } + fs.writeFileSync( + path.join(workDirectory, `tsconfig.${skipLibCheck}.json`), + JSON.stringify({ compilerOptions, files: ['consumer.ts'] }, null, 2) + ) + } + + for (const version of versions) { + for (const skipLibCheck of [false, true]) { + const args = ['--yes', '-p', `typescript@${version}`, 'tsc', '-p', path.join(workDirectory, `tsconfig.${skipLibCheck}.json`)] + const result = spawnSync(npx, args, { cwd: workDirectory, encoding: 'utf8' }) + const ok = result.status === 0 + failed = failed || !ok + console.log(`${ok ? 'ok ' : 'FAIL'} typescript@${version} (skipLibCheck: ${skipLibCheck})`) + if (!ok) console.log(`${result.stdout || ''}${result.stderr || ''}`.trim().replace(/^/gm, ' ')) + } + } +} finally { + if (fs.rmSync) fs.rmSync(workDirectory, { recursive: true, force: true }) + else fs.rmdirSync(workDirectory, { recursive: true }) +} +process.exit(failed ? 1 : 0) diff --git a/spec-types/min-ts/consumer.ts b/spec-types/min-ts/consumer.ts new file mode 100644 index 0000000..523d19f --- /dev/null +++ b/spec-types/min-ts/consumer.ts @@ -0,0 +1,103 @@ +// A consumer of the BUILT package typings (dist/*.d.ts), type-checked with old TypeScript versions by +// `npm run test:types:min-ts`. Only plain code that must compile: no `@ts-expect-error` (TypeScript >= 3.9). +import Substitute, { + Arg, SubstituteOf, SubstituteException, + received, didNotReceive, clearReceivedCalls, configure, mimick, returns, throws, mimicks, resolves, rejects +} from '@fluffy-spoon/substitute' + +enum Status { Active, Disabled } + +interface Calculator { + add(a: number, b: number): number + divide(a: number, b: number): number + heavyOperation(...numbers: number[]): Promise + isValid(input: string): boolean + status(id: number): Status + find(id: number): string | null + reset(): void + fail(message: string): never + format(...args: unknown[]): string + timeout?: number + onDone?(): string + isEnabled: boolean +} + +const calculator = Substitute.for() +const asCalculator: Calculator = calculator +calculator.add(1, 2).returns(3) +calculator.add(1, 2).returns(3, 4, 5) +calculator.add(Arg.any(), Arg.is(b => b > 0)).returns(1) +calculator.add(Arg.all()).mimicks((a, b) => a + b) +calculator.divide(Arg.any('number'), 0).throws(new Error('Cannot divide by 0')) +calculator.heavyOperation(1, 2).resolves(4) +calculator.heavyOperation().rejects(new Error()) +calculator.isValid(Arg.any()).mimicks(input => input.length > 3) +calculator.status(1).mimicks(() => Status.Active) +calculator.find(1).returns(null) +calculator.reset().returns() +calculator.fail('x').throws(new Error('x')) +calculator.format('a', 1).returns('a 1') +calculator.timeout.returns(1000) +calculator.onDone().returns('done') +calculator.isEnabled.returns(true) +calculator.add(1, 2)[returns](3) +calculator.add(1, 2)[throws](new Error()) +calculator.add(1, 2)[mimicks]((a, b) => a - b) +calculator.heavyOperation()[resolves](1) +calculator.heavyOperation()[rejects](new Error()) + +calculator.received().add(1, 2) +calculator.received(2).add(Arg.all()) +calculator.didNotReceive().divide(1, 0) +calculator.received().isEnabled = true +calculator[received](1).add(1, 2) +calculator[didNotReceive]().onDone() +calculator[clearReceivedCalls]() +calculator[configure]().add(1, 2).returns(3) +calculator[mimick]({} as Calculator) + +// overloads, including one without parameters +interface Store { + get(): string[] + get(key: string): string +} +const store = Substitute.for() +store.get().returns(['a']) +store.get('k').returns('v') +store.get(Arg.is(key => key.length > 0)).returns('v') + +// index signatures +interface Config { + name: string + [key: string]: unknown +} +const config = Substitute.for() +config.name.returns('app') + +// members that conflict with the library's names +interface Order { + returns: string[] + total(): number +} +interface Shop { find(id: string): Order } +const shop = Substitute.for() +const order = Substitute.for() +order.total().returns(1) +order[received]().total() +shop.find('1')[returns](order) + +// generic helpers +function once(sub: SubstituteOf) { + return sub[received](1) +} +once(calculator).add(1, 2) + +try { + calculator.received().add(9, 9) +} catch (error) { + if (error instanceof SubstituteException) { + const message: string = error.message + } +} + +export { asCalculator } diff --git a/spec-types/readme.ts b/spec-types/readme.ts new file mode 100644 index 0000000..b3a62ca --- /dev/null +++ b/spec-types/readme.ts @@ -0,0 +1,134 @@ +// The README examples, written the way they are meant to be used, must type-check. +import { Substitute, Arg, received, SubstituteOf } from '../src' +import { expectType } from './helpers' + +interface Calculator { + add(a: number, b: number): number + subtract(a: number, b: number): number + divide(a: number, b: number): number + heavyOperation(...numbers: number[]): Promise + isEnabled: boolean +} + +// Usage +const calculator = Substitute.for() +calculator.add(1, 2).returns(3) +calculator.received().add(1, Arg.any()) +calculator.didNotReceive().add(2, 2) + +// The substitute can be passed wherever a Calculator is expected. +const asCalculator: Calculator = calculator +expectType>(calculator) + +// Setting return types +calculator.add(1, 2).returns(4) +calculator.add(1, 2).returns(3, 7, 9) +calculator.isEnabled.returns(true) +calculator.isEnabled.returns(false, true) + +// Working with promises +calculator.heavyOperation(1, 2).resolves(4) +calculator.heavyOperation(1, 2).rejects(new Error()) +calculator.heavyOperation(1, 2).returns(Promise.resolve(4)) +async function awaitsTheConfiguredValue() { + const result: number = await calculator.heavyOperation(1, 2) + return result +} + +// Verifying calls +const foo: number = calculator.add(1, 2) +calculator.received().add(1, 2) +calculator.received().isEnabled = true +calculator.received(2).isEnabled = Arg.any() +calculator.received().isEnabled = Arg.is(enabled => enabled) +const readEnabled: boolean = calculator.received(1).isEnabled + +// Matching specific arguments +calculator.add(Arg.any(), 2).returns(10) +calculator.received().add(1, Arg.is(x => x < 0)) +calculator.add(Arg.is(x => { expectType(x); return x > 0 }), 2).returns(1) + +// Generic and inverse matchers +const equalToZero = (x: number) => x === 0 +calculator.divide(Arg.any('number'), Arg.is.not(equalToZero)).returns(10) +const argIsNotZero = Arg.is.not(equalToZero) +calculator.received(1).divide(argIsNotZero, argIsNotZero) + +// Ignoring all arguments +calculator.add(Arg.all()).returns(10) +calculator.received(2).add(Arg.all()) + +// Partial mocks +class RealCalculator implements Calculator { + isEnabled = true + add(a: number, b: number) { return a + b } + subtract(a: number, b: number) { return a - b } + divide(a: number, b: number) { return a / b } + async heavyOperation(...numbers: number[]) { return numbers.length } +} +const realCalculator = new RealCalculator() +const fakeCalculator = Substitute.for() +fakeCalculator.subtract(Arg.all()).mimicks(realCalculator.subtract) +fakeCalculator.add(Arg.is(x => x < 10), Arg.any()).mimicks(realCalculator.add) +fakeCalculator.add(Arg.is(x => x >= 10), Arg.any()).returns(1337) +fakeCalculator.divide(10, 2).mimicks(realCalculator.divide) +fakeCalculator.divide(Arg.all()).returns(1338) +fakeCalculator.isEnabled.mimicks(() => realCalculator.isEnabled) + +// Throwing exceptions +calculator.divide(Arg.any(), 0).throws(new Error('Cannot divide by 0')) +calculator.isEnabled.throws(new Error('not available')) + +// Names that conflict with the library +class Example { + received(someNumber: number) { return someNumber } +} +const fake = Substitute.for() +fake.received(1337) // the class' own method +fake.received(1).returns(2) +fake[received]().received(1337) +fake[received](1).received(Arg.any()) + +// Overloaded methods +interface Formatter { + format(value: number): string + format(value: Date, pattern: string): string +} +const formatter = Substitute.for() +formatter.format(1).returns('1') +formatter.format(new Date(), 'yyyy').returns('2026') +formatter.format(Arg.any()).returns('any number') +formatter.format(Arg.is(date => date.getFullYear() > 2000), Arg.any()).returns('any recent date') +formatter.format(Arg.all()).returns('anything') +formatter.received(2).format(Arg.all()) +formatter.received().format(Arg.is(n => n > 1)) + +// Generic methods (without explicit type arguments, see limitations.ts) +interface Repository { + get(id: string): T + save(entity: T): T +} +const repository = Substitute.for() +repository.get('1').returns({ a: 1 }) +repository.save(Arg.any()).returns({ id: '1' }) +repository.received().get('1') + +// Misuse is still rejected +// @ts-expect-error resolves() is only offered for promises +calculator.add(1, 2).resolves(3) +// @ts-expect-error the configured value must have the member's type +calculator.add(1, 2).returns('3') +// @ts-expect-error returns() needs a value +calculator.add(1, 2).returns() +// @ts-expect-error an assertion cannot be configured +calculator.received().add(1, 2).returns(3) +// @ts-expect-error wrong argument type +calculator.add('1', 2) +// @ts-expect-error the predicate must accept the parameter type +calculator.add(Arg.is((x: string) => x.length > 0), 2) +// @ts-expect-error received() takes a count, not a string +calculator.received('2') +// @ts-expect-error a property assertion with a wrong value type +calculator.received().isEnabled = 'yes' + +export { asCalculator, foo, readEnabled, awaitsTheConfiguredValue } diff --git a/spec-types/tsconfig.json b/spec-types/tsconfig.json new file mode 100644 index 0000000..10705e0 --- /dev/null +++ b/spec-types/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "noEmit": true, + "declaration": false, + "strict": true + }, + "include": [ + "./*.ts" + ] +} From 9e2e85ace8d60e137e6447529b0881b0e3e53f26 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:07:44 +0000 Subject: [PATCH 013/106] test(compatibility-checks): keep covering the deferred assertion report With the D9 engine change, the old scenario fails synchronously. Three calls followed by a property-style received(2) can only be reported on process.nextTick, so the runners are still checked for that path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- compatibility-checks/test-runners/_common/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/compatibility-checks/test-runners/_common/index.ts b/compatibility-checks/test-runners/_common/index.ts index 941f286..eb0dbb7 100644 --- a/compatibility-checks/test-runners/_common/index.ts +++ b/compatibility-checks/test-runners/_common/index.ts @@ -15,7 +15,11 @@ export const ambiguousPropertyTypeAssertion = () => { lib.subSection().returns('subSection as method') lib.subSection.returns({ subMethod: () => 'subSection as property' } as AmbiguousSection) + // Three calls, then a property-style assertion with a finite count that a method assertion could still + // satisfy. The member is never invoked afterwards, so the failure can only be reported on process.nextTick, + // after the test function has returned. Every test runner must still attribute it to the test. + lib.subSection() + lib.subSection() lib.subSection() - lib.subSection.subMethod() lib.received(2).subSection } From 135bc610771c0e9d55ea08d6c0af780b027c7960 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:08:48 +0000 Subject: [PATCH 014/106] build: keep JSDoc comments in the emitted typings Editors then show the documentation of received, didNotReceive, configure, mimick and the setup methods on hover. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tsconfig.json b/tsconfig.json index 668168a..0d12e37 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -7,7 +7,7 @@ "declaration": true, "outDir": "dist", "strict": true, - "removeComments": true + "removeComments": false }, "include": [ "src/**/*" From b8c7bf86de4b56be65aad88c64d02110e72db91a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:21:36 +0000 Subject: [PATCH 015/106] fix(engine): reject substitution symbols on a substitute itself (D22) sub[returns](1) (and [throws], [resolves], [rejects], [mimicks]) on a root substitute, or on its configure() view, used to read a member keyed by the symbol and return an auto-substitute, so nothing was configured. It now throws a SubstituteException usage error that points to member/call setups and to sub[configure]() for a substitute returned by a configured call. The string names stay ordinary members (D11). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 63 ++++++++++++++++++++++++ src/internals/Engine.ts | 20 +++++++- 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 spec/regression/fixes/amendments.test.ts diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts new file mode 100644 index 0000000..5ac2031 --- /dev/null +++ b/spec/regression/fixes/amendments.test.ts @@ -0,0 +1,63 @@ +import test from 'ava' +import { types } from 'util' + +import { Substitute, Arg, configure, mimick, received, returns, throws, resolves, rejects, mimicks } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +// Round 2 amendments of the fix spec (D22-D24, the amended D9 message) and the message hints. + +const substitutionSymbols = { returns, throws, resolves, rejects, mimicks } + +test('D22 a substitution symbol read on a root substitute is a usage error', t => { + for (const [name, symbol] of Object.entries(substitutionSymbols)) { + const substitute = Substitute.for() + const error = t.throws(() => substitute[symbol], { instanceOf: SubstituteException }, name) + t.true(error.message.startsWith(`[${name}] cannot be used on a substitute itself`), name) + t.true(error.message.includes(`sub.member[${name}](value)`), name) + t.is(error.type, undefined, `${name}: a usage error, not a call count mismatch`) + + // the read was not recorded and nothing was configured + t.notThrows(() => substitute.received(0)[name], name) + t.true(types.isProxy(substitute.add(1)), name) + + // the configure view of the substitute rejects them as well + t.throws(() => substitute[configure]()[symbol], { instanceOf: SubstituteException }, `${name}: configure view`) + // a mimicking substitute too + const mimicking = Substitute.for() + mimicking[mimick]({ value: 1 }) + t.throws(() => mimicking[symbol], { instanceOf: SubstituteException }, `${name}: mimicking`) + } + + // the error starts at the user's line, not in the library + const error = t.throws(() => (Substitute.for() as any)[returns](1), { instanceOf: SubstituteException }) + t.regex(error.stack!.split('\n')[1], /amendments\.test/) +}) + +test('D22 substitution symbols on members and calls, and the string names on the root, keep working', t => { + const substitute = Substitute.for() + substitute.value[returns](1) + substitute.add(1, 2)[returns](3) + substitute.find(Arg.any())[throws](new Error('nope')) + substitute.logger.level[returns](4) + substitute.getCalc()[returns]('calc') + t.is(substitute.value, 1) + t.is(substitute.add(1, 2), 3) + t.throws(() => substitute.find(1), { message: 'nope' }) + t.is(substitute.logger.level, 4) + t.is(substitute.getCalc(), 'calc') + + // the string names are ordinary members on the root (D11) + const shop = Substitute.for() + shop.returns(5) + t.notThrows(() => shop.received(1).returns(5)) + t.notThrows(() => shop[received](1).returns(5)) + + // a substitute returned by a configured call is a root: [returns] on it points to configure() + const factory = Substitute.for() + const repository = Substitute.for() + factory.create('a').returns(repository) + const error = t.throws(() => factory.create('a')[returns](Substitute.for()), { instanceOf: SubstituteException }) + t.true(error.message.includes('sub[configure]()')) + factory[configure]().create('a').returns('reconfigured') + t.is(factory.create('a'), 'reconfigured') +}) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index a0de4cb..7f29837 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -129,10 +129,27 @@ const createFaceProxy = (face: Face): any => new Proxy(newTarget(options => prin } }) +/** + * D22: the substitution symbols configure a member or a call. On a substitute itself they cannot mean anything + * (and would otherwise silently turn into a member keyed by the symbol), so they are a usage error. The string + * names stay ordinary members there (a member called `returns` is allowed, D11). + */ +const isSubstitutionSymbol = (property: PropertyKey): boolean => + typeof property === 'symbol' && substitutionMethodOf(property) !== undefined + +const substitutionOnSubstituteError = (property: PropertyKey, start: Function) => SubstituteException.generic( + `[${substitutionMethodOf(property)}] cannot be used on a substitute itself: it configures a member or a call, ` + + `e.g. sub.member[${substitutionMethodOf(property)}](value) or sub.method(1)[${substitutionMethodOf(property)}](value). ` + + `If this substitute is the value of a call that is already configured, configure that call again through sub[configure]().`, + start +) + const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any => { if (isSpecialProperty(property)) return special(property, options => printFace(face, colorsOf(options)), face) - if (face.kind !== 'root') { + if (face.kind === 'root') { + if (isSubstitutionSymbol(property)) throw substitutionOnSubstituteError(property, stackStart) + } else { const entry = face.entry const method = substitutionMethodOf(property) if (method !== undefined) return setupFunction(entry, method) @@ -471,6 +488,7 @@ const createConfigureProxy = (state: SubstituteState): any => { return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) + if (isSubstitutionSymbol(property)) throw substitutionOnSubstituteError(property, get) return configureMember(state, property) }, set: function set() { From ea77525839978be9a8e7039084e3b50e9d786c6c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:22:24 +0000 Subject: [PATCH 016/106] fix(messages): list at most 50 received calls in a failure message (D23) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A failing assertion on a member with hundreds of received calls produced a message with one or two lines per call. The listing now stops after 50 entries with "› … and N more", using the listing's own marker. The counts in the expectation line still cover every call. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 44 ++++++++++++++++++++++++ src/internals/SubstituteException.ts | 8 ++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index 5ac2031..8b31fdb 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -6,6 +6,9 @@ import { SubstituteException } from '../../../src/internals/SubstituteException' // Round 2 amendments of the fix spec (D22-D24, the amended D9 message) and the message hints. +const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') +const listedLines = (message: string) => plain(message).split('\n').filter(line => line.startsWith('› ')) + const substitutionSymbols = { returns, throws, resolves, rejects, mimicks } test('D22 a substitution symbol read on a root substitute is a usage error', t => { @@ -61,3 +64,44 @@ test('D22 substitution symbols on members and calls, and the string names on the factory[configure]().create('a').returns('reconfigured') t.is(factory.create('a'), 'reconfigured') }) + +test('D23 a message lists at most 50 received calls, then "… and N more"', t => { + const logger = Substitute.for() + for (let index = 0; index < 60; index++) logger.log(index) + const error = t.throws(() => logger.received(1).log('x'), { instanceOf: SubstituteException }) + const message = plain(error.message) + t.true(message.includes('\n› … and 10 more\n')) + const lines = listedLines(message) + t.is(lines.length, 51) + t.is(lines[0], '› ✘ @Substitute.log(0)') + t.is(lines[49], '› ✘ @Substitute.log(49)') + t.is(lines[50], '› … and 10 more') + t.false(message.includes('@Substitute.log(50)')) + t.true(message.endsWith('› … and 10 more\n')) + + // the count in the expectation line still covers every call + const tooMany = t.throws(() => logger.received(61).log(Arg.any()), { instanceOf: SubstituteException }) + t.regex(plain(tooMany.message), /Expected to receive 61 method calls matching log\(Arg\.any\{any\}\), but received 60\./) + t.true(plain(tooMany.message).includes('› ✔ @Substitute.log(49)\n')) + t.true(plain(tooMany.message).includes('› … and 10 more')) + + // exactly 50 calls: no "more" line + const fifty = Substitute.for() + for (let index = 0; index < 50; index++) fifty.log(index) + const complete = plain(t.throws(() => fifty.received(1).log('x'), { instanceOf: SubstituteException }).message) + t.is(listedLines(complete).length, 50) + t.false(complete.includes('more')) + + // property reads and assignments are capped the same way + const settings = Substitute.for() + for (let index = 0; index < 55; index++) { + void settings.value + settings.value = index + } + const reads = plain(t.throws(() => settings.received(56).value, { instanceOf: SubstituteException }).message) + t.true(reads.includes('› … and 5 more')) + const sets = plain(t.throws(() => { settings.received(1).value = -1 }, { instanceOf: SubstituteException }).message) + t.is(listedLines(sets).length, 51) + t.true(sets.includes('› ✘ @Substitute.value = 49\n')) + t.true(sets.includes('› … and 5 more')) +}) diff --git a/src/internals/SubstituteException.ts b/src/internals/SubstituteException.ts index aeec0eb..4cf53ff 100644 --- a/src/internals/SubstituteException.ts +++ b/src/internals/SubstituteException.ts @@ -43,6 +43,9 @@ const kindPhrase = (kind: ExpectedKind, count: number | undefined): string => { const memberLabel = (key: PropertyKey): string => key === SELF ? '' : keyToString(key) +/** D23: a failure message lists at most this many received calls, then "› … and N more". */ +export const MAX_LISTED_CALLS = 50 + const describeExpectedCall = (mismatch: CallCountMismatch, colors: boolean): string => { const { key, expected } = mismatch const name = key === SELF ? mismatch.substitutePath : keyToString(key) @@ -110,7 +113,8 @@ export class SubstituteException extends Error { if (mismatch.listed.length > 0) { textBuilder.newLine().add(`All property or method calls to ${memberPath} received so far:`) - for (const listed of mismatch.listed) { + const shown = mismatch.listed.length > MAX_LISTED_CALLS ? mismatch.listed.slice(0, MAX_LISTED_CALLS) : mismatch.listed + for (const listed of shown) { const style = (part: TextPart) => listed.matches ? part.faint() : part.bold() textBuilder.newLine().add('› ') .add(listed.matches ? '✔ ' : '✘ ', style) @@ -121,6 +125,8 @@ export class SubstituteException extends Error { if (listed.predicateThrew) textBuilder.newLine().add(` (an Arg.is predicate threw while matching this call: ${describeError(listed.predicateError)})`, t => t.faint()) } + const hidden = mismatch.listed.length - shown.length + if (hidden > 0) textBuilder.newLine().add(`› … and ${hidden} more`, t => t.faint()) textBuilder.newLine() } From b0c38e4ea2f554c5198ad5d4b1f2478d1aee6886 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:23:46 +0000 Subject: [PATCH 017/106] fix(messages): no colours with NODE_DISABLE_COLORS or TERM=dumb (D24) The colour decision now follows Node's own policy more closely: FORCE_COLOR still wins ('0'/'false' off, anything else on); otherwise a non-empty NO_COLOR or NODE_DISABLE_COLORS, or TERM=dumb, turn colours off; otherwise stdout must be a TTY. The decision is a pure function, shouldUseColors(env, stdoutIsTTY), so it is tested without a real TTY. The existing A:RT-14 test now also clears NODE_DISABLE_COLORS and TERM, so its TTY case does not depend on the environment the tests run in. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 78 ++++++++++++++++++++++++ spec/regression/fixes/arguments.test.ts | 12 ++-- src/internals/utilities/Colors.ts | 29 ++++++--- 3 files changed, 106 insertions(+), 13 deletions(-) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index 8b31fdb..5ab3787 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -3,6 +3,7 @@ import { types } from 'util' import { Substitute, Arg, configure, mimick, received, returns, throws, resolves, rejects, mimicks } from '../../../src' import { SubstituteException } from '../../../src/internals/SubstituteException' +import { shouldUseColors } from '../../../src/internals/utilities/Colors' // Round 2 amendments of the fix spec (D22-D24, the amended D9 message) and the message hints. @@ -105,3 +106,80 @@ test('D23 a message lists at most 50 received calls, then "… and N more"', t = t.true(sets.includes('› ✘ @Substitute.value = 49\n')) t.true(sets.includes('› … and 5 more')) }) + +test('D24 the colour decision honours FORCE_COLOR, NO_COLOR, NODE_DISABLE_COLORS, TERM=dumb and the TTY', t => { + const cases: Array<[Record, boolean, boolean]> = [ + // [environment, stdout is a TTY, colours] + [{}, true, true], + [{}, false, false], + [{ TERM: 'xterm-256color' }, true, true], + [{ NO_COLOR: '1' }, true, false], + [{ NO_COLOR: '' }, true, true], + [{ NODE_DISABLE_COLORS: '1' }, true, false], + [{ NODE_DISABLE_COLORS: 'true' }, true, false], + [{ NODE_DISABLE_COLORS: '' }, true, true], + [{ TERM: 'dumb' }, true, false], + [{ TERM: 'dumb', NODE_DISABLE_COLORS: '1', NO_COLOR: '1' }, true, false], + // FORCE_COLOR forces them on, whatever else is set, and also without a TTY + [{ FORCE_COLOR: '1' }, false, true], + [{ FORCE_COLOR: '' }, false, true], + [{ FORCE_COLOR: '3' }, false, true], + [{ FORCE_COLOR: '1', TERM: 'dumb' }, false, true], + [{ FORCE_COLOR: '1', NODE_DISABLE_COLORS: '1' }, false, true], + [{ FORCE_COLOR: '1', NO_COLOR: '1' }, false, true], + // ... or off + [{ FORCE_COLOR: '0' }, true, false], + [{ FORCE_COLOR: 'false' }, true, false], + [{ FORCE_COLOR: 'FALSE', TERM: 'xterm' }, true, false] + ] + for (const [env, tty, expected] of cases) + t.is(shouldUseColors(env, () => tty), expected, `${JSON.stringify(env)}, TTY: ${tty}`) + + // the TTY is only looked at when the environment does not decide, and a throwing check means no colours + let asked = 0 + const askTTY = () => { asked++; return true } + shouldUseColors({ FORCE_COLOR: '1' }, askTTY) + shouldUseColors({ NO_COLOR: '1' }, askTTY) + shouldUseColors({ TERM: 'dumb' }, askTTY) + t.is(asked, 0) + t.false(shouldUseColors({}, () => { throw new Error('no stdout') })) +}) + +const withProcessEnvironment = (environment: Record, tty: boolean, run: () => void) => { + const names = ['FORCE_COLOR', 'NO_COLOR', 'NODE_DISABLE_COLORS', 'TERM'] + const saved = names.map(name => [name, process.env[name]] as const) + const ttyDescriptor = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY') + const set = (name: string, value: string | undefined) => { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } + try { + for (const name of names) set(name, environment[name]) + Object.defineProperty(process.stdout, 'isTTY', { value: tty, configurable: true, writable: true }) + run() + } finally { + for (const [name, value] of saved) set(name, value) + if (ttyDescriptor !== undefined) Object.defineProperty(process.stdout, 'isTTY', ttyDescriptor) + else delete (process.stdout as any).isTTY + } +} + +test('D24 assertion messages have no ANSI codes with NODE_DISABLE_COLORS or TERM=dumb, unless FORCE_COLOR is set', t => { + const messageOf = () => { + const calculator = Substitute.for() + calculator.add(1, 2) + try { + calculator.received().add(9, 9) + } catch (error) { + return (error as Error).message + } + throw new Error('expected the assertion to fail') + } + const hasAnsi = (text: string) => /\x1b\[/.test(text) + + withProcessEnvironment({ TERM: 'xterm' }, true, () => t.true(hasAnsi(messageOf()), 'TTY')) + withProcessEnvironment({ TERM: 'dumb' }, true, () => t.false(hasAnsi(messageOf()), 'TERM=dumb')) + withProcessEnvironment({ NODE_DISABLE_COLORS: '1' }, true, () => t.false(hasAnsi(messageOf()), 'NODE_DISABLE_COLORS=1')) + withProcessEnvironment({ NODE_DISABLE_COLORS: '1', FORCE_COLOR: '1' }, true, () => t.true(hasAnsi(messageOf()), 'forced')) + withProcessEnvironment({ TERM: 'dumb', FORCE_COLOR: '1' }, false, () => t.true(hasAnsi(messageOf()), 'forced without a TTY')) +}) diff --git a/spec/regression/fixes/arguments.test.ts b/spec/regression/fixes/arguments.test.ts index c17b6c1..0c789a7 100644 --- a/spec/regression/fixes/arguments.test.ts +++ b/spec/regression/fixes/arguments.test.ts @@ -208,20 +208,24 @@ test('A:RT-13 Arg.is rejects a missing or non-function predicate when it is crea }) const withEnvironment = (environment: { NO_COLOR?: string, FORCE_COLOR?: string, tty: boolean }, run: () => void) => { - const saved = { NO_COLOR: process.env.NO_COLOR, FORCE_COLOR: process.env.FORCE_COLOR } + // NODE_DISABLE_COLORS and TERM=dumb also turn colours off (D24): they are cleared so that the result does not + // depend on the environment the tests run in. + const names = ['NO_COLOR', 'FORCE_COLOR', 'NODE_DISABLE_COLORS', 'TERM'] as const + const saved = names.map(name => [name, process.env[name]] as const) const ttyDescriptor = Object.getOwnPropertyDescriptor(process.stdout, 'isTTY') - const set = (name: 'NO_COLOR' | 'FORCE_COLOR', value: string | undefined) => { + const set = (name: typeof names[number], value: string | undefined) => { if (value === undefined) delete process.env[name] else process.env[name] = value } try { set('NO_COLOR', environment.NO_COLOR) set('FORCE_COLOR', environment.FORCE_COLOR) + set('NODE_DISABLE_COLORS', undefined) + set('TERM', undefined) Object.defineProperty(process.stdout, 'isTTY', { value: environment.tty, configurable: true, writable: true }) run() } finally { - set('NO_COLOR', saved.NO_COLOR) - set('FORCE_COLOR', saved.FORCE_COLOR) + for (const [name, value] of saved) set(name, value) if (ttyDescriptor !== undefined) Object.defineProperty(process.stdout, 'isTTY', ttyDescriptor) else delete (process.stdout as any).isTTY } diff --git a/src/internals/utilities/Colors.ts b/src/internals/utilities/Colors.ts index 99f2cb2..cfec3c3 100644 --- a/src/internals/utilities/Colors.ts +++ b/src/internals/utilities/Colors.ts @@ -1,18 +1,29 @@ +export type ColorEnvironment = Readonly> + +const isSet = (value: string | undefined): boolean => value !== undefined && value !== '' + /** - * Whether messages should contain ANSI colour codes. - * FORCE_COLOR wins (0/false disables it), then NO_COLOR (any non-empty value disables colours), - * otherwise colours are only used when stdout is a TTY. + * Whether messages should contain ANSI colour codes, for an environment and the TTY state of stdout. + * The TTY state is only asked for when the environment does not decide (reading process.stdout creates the stream). + * + * 1. FORCE_COLOR wins: '0' or 'false' turns colours off, any other value (including '') turns them on. + * 2. Otherwise NO_COLOR or NODE_DISABLE_COLORS with a non-empty value, or TERM=dumb, turn them off (D18, D24). + * 3. Otherwise colours are used only when stdout is a TTY. */ -export const colorsEnabled = (): boolean => { - if (typeof process === 'undefined' || process === null) return false - const env = process.env ?? {} +export const shouldUseColors = (env: ColorEnvironment, stdoutIsTTY: () => boolean): boolean => { const forceColor = env.FORCE_COLOR if (forceColor !== undefined) return !(forceColor === '0' || forceColor.toLowerCase() === 'false') - const noColor = env.NO_COLOR - if (noColor !== undefined && noColor !== '') return false + if (isSet(env.NO_COLOR) || isSet(env.NODE_DISABLE_COLORS)) return false + if (env.TERM === 'dumb') return false try { - return process.stdout?.isTTY === true + return stdoutIsTTY() === true } catch { return false } } + +/** The colour decision for this process (see shouldUseColors). It is made again for every message. */ +export const colorsEnabled = (): boolean => { + if (typeof process === 'undefined' || process === null) return false + return shouldUseColors(process.env ?? {}, () => process.stdout?.isTTY === true) +} From 69486d71c3aed773ef7836650f36f942d0774870 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:25:57 +0000 Subject: [PATCH 018/106] feat(messages): explain reads that were not calls Two hints, after the listing of received calls: - When a method assertion finds too few calls and the member was also read without being invoked: "@Substitute.m was read N time(s) without being called; reading a method does not count as calling it." The same hint is given when a member that was read and invoked fails a property-style check with a count above its calls. - When didNotReceive().m(...) fails on a member that was only read, for example passed as a callback (the A:RT-3 residual forced by D9): the hint explains that the assertion is decided when the member is read and that sub[clearReceivedCalls]() after the arrange step resets the reads. SubstituteException's mismatch description gains optional `explanation` (continues the expectation line) and `hints` (lines after the listing). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 69 +++++++++++++++++++++++- src/internals/Assertions.ts | 33 +++++++++++- src/internals/SubstituteException.ts | 11 ++++ 3 files changed, 110 insertions(+), 3 deletions(-) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index 5ab3787..6d8f6a7 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -1,7 +1,8 @@ import test from 'ava' +import { EventEmitter } from 'events' import { types } from 'util' -import { Substitute, Arg, configure, mimick, received, returns, throws, resolves, rejects, mimicks } from '../../../src' +import { Substitute, Arg, clearReceivedCalls, configure, mimick, received, returns, throws, resolves, rejects, mimicks } from '../../../src' import { SubstituteException } from '../../../src/internals/SubstituteException' import { shouldUseColors } from '../../../src/internals/utilities/Colors' @@ -183,3 +184,69 @@ test('D24 assertion messages have no ANSI codes with NODE_DISABLE_COLORS or TERM withProcessEnvironment({ NODE_DISABLE_COLORS: '1', FORCE_COLOR: '1' }, true, () => t.true(hasAnsi(messageOf()), 'forced')) withProcessEnvironment({ TERM: 'dumb', FORCE_COLOR: '1' }, false, () => t.true(hasAnsi(messageOf()), 'forced without a TTY')) }) + +const messageOf = (assertion: () => unknown): string => { + try { + assertion() + } catch (error) { + if (!(error instanceof SubstituteException)) throw error + return plain(error.message) + } + throw new Error('expected the assertion to fail') +} + +test('hint: a failed method assertion says when the method was read without being called', t => { + const hint = (path: string, times: string) => + `${path} was read ${times} without being called; reading a method does not count as calling it.` + + const handler = Substitute.for() + new EventEmitter().on('click', handler.onClick) + const message = messageOf(() => handler.received(1).onClick('x', 1)) + t.true(message.includes("Expected to receive 1 method call matching onClick('x', 1), but received none.")) + t.true(message.endsWith(`\n${hint('@Substitute.onClick', '1 time')}\n`)) + void handler.onClick + t.true(messageOf(() => handler.received().onClick(Arg.all())).includes(hint('@Substitute.onClick', '2 times'))) + + // nested paths; a read and a call, with a count above the calls (decided when the member is read, D9) + const app = Substitute.for() + void app.logger.flush + app.logger.flush() + t.true(messageOf(() => app.logger.received(2).flush()).includes(hint('@Substitute.logger.flush', '1 time'))) + t.true(messageOf(() => app.logger.received(1).flush(1)).includes(hint('@Substitute.logger.flush', '1 time'))) + + // no hint when there were no reads, when there were too many calls, or for a member that is only a property + const calculator = Substitute.for() + calculator.add(1) + t.false(messageOf(() => calculator.received(2).add(1)).includes('without being called')) + t.false(messageOf(() => app.logger.didNotReceive().flush()).includes('without being called')) + const settings = Substitute.for() + void settings.flag + const property = messageOf(() => settings.received(2).flag) + t.false(property.includes('without being called')) + t.false(property.includes('never called')) +}) + +test('hint: didNotReceive() on a member that was only read points to clearReceivedCalls (A:RT-3 residual)', t => { + const handler = Substitute.for() + const callback = handler.onClick + new EventEmitter().on('click', callback) + + // forced by D9: the assertion is decided when onClick is read, and it was read once + const message = messageOf(() => handler.didNotReceive().onClick(42)) + t.true(message.includes('Expected to receive 0 property reads matching onClick, but received 1.')) + const hint = '@Substitute.onClick was read 1 time but never called. ' + + 'If it is a method that was only read, for example passed as a callback, these reads still fail didNotReceive().onClick(...): ' + + 'the assertion is decided when onClick is read, before it is known whether it is called. ' + + 'Call sub[clearReceivedCalls]() after the arrange step to reset the reads.' + t.true(message.endsWith(`\n${hint}\n`)) + t.true(messageOf(() => handler.received(0).onClick).includes(hint)) + + // the workaround from the hint + handler[clearReceivedCalls]() + t.notThrows(() => handler.didNotReceive().onClick(42)) + callback(42) + const called = messageOf(() => handler.didNotReceive().onClick(42)) + t.true(called.includes('Expected to receive 0 method calls matching onClick(42), but received 1.')) + t.false(called.includes('never called')) + t.notThrows(() => handler.didNotReceive().onClick(43)) +}) diff --git a/src/internals/Assertions.ts b/src/internals/Assertions.ts index 0c9dd25..4d6e6d2 100644 --- a/src/internals/Assertions.ts +++ b/src/internals/Assertions.ts @@ -4,6 +4,8 @@ import { SubstituteState } from './SubstituteState' import { RecordedArguments } from './RecordedArguments' import { SubstituteException, ListedCall, ExpectedKind } from './SubstituteException' import { CallRecord } from './CallRecord' +import { keyToString } from './Constants' +import { plural } from './utilities' /** undefined means "1 or more" */ export type ExpectedCount = number | undefined @@ -26,14 +28,34 @@ const countMatches = (count: ExpectedCount, actual: number) => count === undefin const receivedText = (matches: number) => matches === 0 ? 'none' : matches.toString() +const times = (count: number) => `${count} ${plural('time', count)}` + +/** A method assertion found too few calls, and the member was also read without being invoked. */ +const readWithoutCallHint = (state: SubstituteState, key: PropertyKey, reads: number): string => + `${state.memberPath(key)} was read ${times(reads)} without being called; reading a method does not count as calling it.` + +/** + * didNotReceive().m(...) on a member that was only read (A:RT-3). The property-style half of the assertion is + * decided when the member is read (D9), so the reads fail it even when an invocation follows. + */ +const onlyReadHint = (state: SubstituteState, key: PropertyKey, reads: number): string => { + const name = keyToString(key) + return `${state.memberPath(key)} was read ${times(reads)} but never called. ` + + `If it is a method that was only read, for example passed as a callback, these reads still fail didNotReceive().${name}(...): ` + + `the assertion is decided when ${name} is read, before it is known whether it is called. ` + + `Call sub[clearReceivedCalls]() after the arrange step to reset the reads.` +} + /** Method assertion: counts invocations whose arguments match. Property reads never count. */ export const assertCall = (state: SubstituteState, key: PropertyKey, args: any[], count: ExpectedCount, stackStart?: Function): void => { const specification = RecordedArguments.forSpecification(args) const records = state.recordsFor(key).filter(record => record.kind !== 'set') const listed: ListedCall[] = [] let matches = 0 + let reads = 0 for (const record of records) { if (record.kind !== 'call') { + reads++ listed.push({ record, matches: false }) continue } @@ -42,12 +64,14 @@ export const assertCall = (state: SubstituteState, key: PropertyKey, args: any[] listed.push({ record, matches: match.matches, predicateThrew: match.predicateThrew, predicateError: match.predicateError }) } if (countMatches(count, matches)) return + const tooFew = matches < (count ?? 1) throw SubstituteException.forCallCountMismatch({ substitutePath: state.path, key, expected: { count, kind: 'method', specification }, receivedText: receivedText(matches), - listed + listed, + hints: tooFew && reads > 0 ? [readWithoutCallHint(state, key, reads)] : undefined }, stackStart) } @@ -125,7 +149,12 @@ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, cou key, expected: { count, kind }, receivedText: kind === 'property' ? (reads === 0 ? 'none' : reads.toString()) : describeReceived(reads, calls), - listed: records.map((record: CallRecord) => ({ record, matches: record.kind === 'get' })) + listed: records.map((record: CallRecord) => ({ record, matches: record.kind === 'get' })), + hints: reads === 0 ? undefined + : count === 0 && calls === 0 ? [onlyReadHint(state, key, reads)] + // invoked as well, so most likely a method, with fewer calls than expected + : calls > 0 && count !== undefined && calls < count ? [readWithoutCallHint(state, key, reads)] + : undefined }, start) if (!deferrable) throw createError(stackStart) diff --git a/src/internals/SubstituteException.ts b/src/internals/SubstituteException.ts index 4cf53ff..5273d63 100644 --- a/src/internals/SubstituteException.ts +++ b/src/internals/SubstituteException.ts @@ -29,7 +29,11 @@ export type CallCountMismatch = { expected: CallCountExpectation /** How many matching calls were received, already phrased (e.g. 'none', '4', '2 property reads and 1 method call'). */ receivedText: string + /** Continues the expectation line, e.g. to explain what was received instead. */ + explanation?: string listed: ListedCall[] + /** Lines after the listing that explain a likely mistake. */ + hints?: string[] } const kindPhrase = (kind: ExpectedKind, count: number | undefined): string => { @@ -110,6 +114,7 @@ export class SubstituteException extends Error { .add(', but received ') .add(mismatch.receivedText, t => t.faint()) .add('.') + if (mismatch.explanation !== undefined) textBuilder.add(` ${mismatch.explanation}`) if (mismatch.listed.length > 0) { textBuilder.newLine().add(`All property or method calls to ${memberPath} received so far:`) @@ -130,6 +135,12 @@ export class SubstituteException extends Error { textBuilder.newLine() } + const hints = mismatch.hints ?? [] + if (hints.length > 0) { + if (mismatch.listed.length === 0) textBuilder.newLine() + for (const hint of hints) textBuilder.add(hint).newLine() + } + return textBuilder.toString(colors) } From 31109df5a3ea5837114739578e80ba94736e47fc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:27:28 +0000 Subject: [PATCH 019/106] fix(messages): the deferred D9 report says the member was called as a method Amended D9: a property-style assertion such as `sub.received(2).m` on a member that has only ever been invoked is reported on process.nextTick when it is not invoked. Its message said "Expected to receive 2 property reads matching m, but received none." and nothing else. It now continues with "m was never read as a property; it was called 1 time as a method. To assert calls, invoke it: sub.received(2).m(...)", with the path of nested substitutes (sub.logger.received(2).info(...)). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 50 ++++++++++++++++++++++++ src/internals/Assertions.ts | 16 ++++++++ 2 files changed, 66 insertions(+) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index 6d8f6a7..2b2981b 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -1,4 +1,5 @@ import test from 'ava' +import * as fakeTimers from '@sinonjs/fake-timers' import { EventEmitter } from 'events' import { types } from 'util' @@ -250,3 +251,52 @@ test('hint: didNotReceive() on a member that was only read points to clearReceiv t.false(called.includes('never called')) t.notThrows(() => handler.didNotReceive().onClick(43)) }) + +/** The message of a failure that is only reported on process.nextTick (D9); asserts that nothing is thrown before. */ +const deferredMessageOf = (t: any, assertion: () => unknown): string => { + const clock = fakeTimers.install({ toFake: ['nextTick'] }) + try { + t.notThrows(assertion, 'nothing is thrown synchronously') + const error = t.throws(() => clock.tick(1), { instanceOf: SubstituteException }) as SubstituteException + return plain(error.message) + } finally { + clock.uninstall() + } +} + +test('D9 (amended) the deferred report on a member that was only invoked says it was called as a method', t => { + const calculator = Substitute.for() + calculator.m(1) + const message = deferredMessageOf(t, () => calculator.received(2).m) + t.is(message.split('\n')[1], + 'Expected to receive 2 property reads matching m, but received none. ' + + 'm was never read as a property; it was called 1 time as a method. To assert calls, invoke it: sub.received(2).m(...)') + t.true(message.includes('\n› ✘ @Substitute.m(1)\n')) + // it does not report property reads that never happened + t.false(/received \d+ property read/.test(message)) + t.false(message.includes('reads and')) + + // more calls than expected, nested substitutes, members that are not identifiers + const app = Substitute.for() + app.logger.info('a') + app.logger.info('b') + app.logger.info('c') + t.true(deferredMessageOf(t, () => app.logger.received(2).info) + .includes('info was never read as a property; it was called 3 times as a method. To assert calls, invoke it: sub.logger.received(2).info(...)')) + app.getRepository('users')['find-all']() + t.true(deferredMessageOf(t, () => app.getRepository('users').received(4)['find-all']) + .includes("To assert calls, invoke it: sub.getRepository('users').received(4)['find-all'](...)")) + + // invoking the member right away cancels the report and gives the method assertion's message + const error = t.throws(() => calculator.received(2).m(1), { instanceOf: SubstituteException }) + t.regex(plain(error.message), /Expected to receive 2 method calls matching m\(1\), but received 1\./) + + // a member that was also read keeps the property wording, without the explanation + const component = Substitute.for() + void component.onChange + void component.onChange + component.onChange() + const ambiguous = deferredMessageOf(t, () => component.received(1).onChange) + t.true(ambiguous.includes('Expected to receive 1 property read matching onChange, but received 2.\n')) + t.false(ambiguous.includes('never read as a property')) +}) diff --git a/src/internals/Assertions.ts b/src/internals/Assertions.ts index 4d6e6d2..f79e20b 100644 --- a/src/internals/Assertions.ts +++ b/src/internals/Assertions.ts @@ -46,6 +46,20 @@ const onlyReadHint = (state: SubstituteState, key: PropertyKey, reads: number): `Call sub[clearReceivedCalls]() after the arrange step to reset the reads.` } +/** `sub`, `sub.logger`, `sub.getCalc()`, ...: the substitute as it would be written in a test. */ +const asExpression = (state: SubstituteState): string => state.path.replace(/^@Substitute/, 'sub') + +const memberAccess = (key: PropertyKey): string => + typeof key === 'string' && /^[A-Za-z_$][\w$]*$/.test(key) ? `.${key}` : `[${typeof key === 'symbol' ? keyToString(key) : inspect(key)}]` + +/** + * The amended D9 case: a property-style assertion on a member that has only ever been invoked, never read as a + * property, and the assertion was not invoked either. A method assertion was most likely intended. + */ +const onlyInvokedExplanation = (state: SubstituteState, key: PropertyKey, calls: number, count: number): string => + `${keyToString(key)} was never read as a property; it was called ${times(calls)} as a method. ` + + `To assert calls, invoke it: ${asExpression(state)}.received(${count})${memberAccess(key)}(...)` + /** Method assertion: counts invocations whose arguments match. Property reads never count. */ export const assertCall = (state: SubstituteState, key: PropertyKey, args: any[], count: ExpectedCount, stackStart?: Function): void => { const specification = RecordedArguments.forSpecification(args) @@ -128,6 +142,7 @@ export const settle = (deferred: DeferredAssertion | undefined): void => { * been invoked (never read as a property), so the access is most likely the start of a method assertion * whose message needs the arguments. The failure is scheduled on process.nextTick and cancelled as soon * as the member is invoked; only a property-style assertion that is never invoked reports it there. + * For a member that was only invoked, the report says so and shows the method assertion to write instead. */ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, count: ExpectedCount, stackStart?: Function): DeferredAssertion | undefined => { const records = state.recordsFor(key).filter(record => record.kind !== 'set') @@ -149,6 +164,7 @@ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, cou key, expected: { count, kind }, receivedText: kind === 'property' ? (reads === 0 ? 'none' : reads.toString()) : describeReceived(reads, calls), + explanation: deferrable && reads === 0 ? onlyInvokedExplanation(state, key, calls, count!) : undefined, listed: records.map((record: CallRecord) => ({ record, matches: record.kind === 'get' })), hints: reads === 0 ? undefined : count === 0 && calls === 0 ? [onlyReadHint(state, key, reads)] From 6fed868317ec0ed7f1d753eab585f2ff89b880b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:36:02 +0000 Subject: [PATCH 020/106] perf(engine): index literal substitutions; keep auto-substitutes of mutated arguments Resolving a call compared it against every literal substitution of the member, and configuring one compared it against all earlier ones, so 8000 literal setups plus 8000 calls took about 4.6 s. All-literal substitutions are now indexed per member by a stable fingerprint of their arguments: primitives by value, functions, substitutes and symbols by identity, and an object only as "an object", so the key never goes stale when an argument object is mutated after the setup (literal arguments are compared as they are when the call is made, D15). The deep-equal confirmation and the D4 precedence (most specific class, then most recent) are unchanged. The same workload now takes about 0.17 s. Literal setups with object arguments still compare against the setups with the same primitives in the same places. The auto-substitute cache looked entries up by a structural fingerprint only, which goes stale when an argument object is mutated: after api.get(request).body.returns('ok') and request.headers = {...}, api.get(request).body was a new auto-substitute (D2). Entries are now also found by the identity of the argument objects. The ratio test 'the cost of a call does not grow' now takes the best of three runs and compares 2000 with 32000 calls against a bound of 48x (linear is about 16x, quadratic about 256x), so CPU load does not fail it. New: 8000 literal setups plus 8000 matching calls in under 1 s (best of three, directly and through configure()) and a growth check for them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 103 +++++++++++++++- spec/regression/fixes/performance.test.ts | 62 ++++++++-- src/internals/SubstituteState.ts | 139 ++++++++++++++++++---- src/internals/utilities/ArgumentHash.ts | 42 +++++-- 4 files changed, 296 insertions(+), 50 deletions(-) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index 2b2981b..de46053 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -1,13 +1,13 @@ import test from 'ava' import * as fakeTimers from '@sinonjs/fake-timers' import { EventEmitter } from 'events' -import { types } from 'util' +import { inspect, types } from 'util' import { Substitute, Arg, clearReceivedCalls, configure, mimick, received, returns, throws, resolves, rejects, mimicks } from '../../../src' import { SubstituteException } from '../../../src/internals/SubstituteException' import { shouldUseColors } from '../../../src/internals/utilities/Colors' -// Round 2 amendments of the fix spec (D22-D24, the amended D9 message) and the message hints. +// Round 2: the amendments of the fix spec (D22-D24, the amended D9 message), the message hints, and fixes from review. const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') const listedLines = (message: string) => plain(message).split('\n').filter(line => line.startsWith('› ')) @@ -300,3 +300,102 @@ test('D9 (amended) the deferred report on a member that was only invoked says it t.true(ambiguous.includes('Expected to receive 1 property read matching onChange, but received 2.\n')) t.false(ambiguous.includes('never read as a property')) }) + +test('R:RT-8 / D4 / D15 indexing literal substitutions does not change which substitution answers a call', t => { + const calculator = Substitute.for() + // the most specific class wins, then the most recent one (D4) + calculator.add(1, 2).returns('literal') + calculator.add(Arg.any(), 2).returns('predicate') + calculator.add(Arg.all()).returns('wildcard') + calculator.add(Arg.any(), Arg.any()).returns('newer predicate') + t.is(calculator.add(1, 2), 'literal') + t.is(calculator.add(5, 2), 'newer predicate') + t.is(calculator.add(5), 'wildcard') + calculator[configure]().add(1, 2).returns('newer literal') + t.is(calculator.add(1, 2), 'newer literal') + + // values that look alike are still told apart, values that are equal still match + const values = Substitute.for() + const long = 'x'.repeat(100) + const symbol = Symbol('s') + const fn = () => 1 + const other = Substitute.for() + values.f(0).returns('0') + values[configure]().f(-0).returns('-0') + values.f(NaN).returns('NaN') + values.f(1).returns('number') + values.f('1').returns('string') + values.f(BigInt(1)).returns('bigint') + values.f(`${long}a`).returns('long a') + values.f(`${long}b`).returns('long b') + values.f(symbol).returns('symbol') + values.f(fn).returns('function') + values.f(other).returns('substitute') + values.f(undefined).returns('undefined') + values.f(null).returns('null') + values.f().returns('no arguments') + values.f([1, 2]).returns('array') + values.f({ a: 1 }).returns('object') + values.f(new Date(5)).returns('date') + t.deepEqual( + [0, -0, NaN, 1, '1', BigInt(1), `${long}a`, `${long}b`, symbol, fn, other, undefined, null].map(value => values.f(value)), + ['0', '-0', 'NaN', 'number', 'string', 'bigint', 'long a', 'long b', 'symbol', 'function', 'substitute', 'undefined', 'null'] + ) + t.is(values.f(), 'no arguments') + t.is(values.f([1, 2]), 'array') + t.is(values.f({ a: 1 }), 'object') + t.is(values.f(new Date(5)), 'date') + t.true(types.isProxy(values.f([2, 1]))) + t.true(types.isProxy(values.f({ a: 2 }))) + t.true(types.isProxy(values.f(Symbol('s')))) + t.true(types.isProxy(values.f(() => 1))) + t.true(types.isProxy(values.f(1, undefined))) + + // literal arguments are compared as they are when the call is made (D15), also after a mutation + const repository = Substitute.for() + const user = { name: 'a', tags: ['x'] } + repository.save(user).returns('saved') + user.name = 'b' + user.tags.push('y') + t.is(repository.save(user), 'saved') + t.is(repository.save({ name: 'b', tags: ['x', 'y'] }), 'saved') + t.true(types.isProxy(repository.save({ name: 'a', tags: ['x'] }))) + // ... and the most recent of several matching literal substitutions wins + const copy = { name: 'b', tags: ['x', 'y'] } + repository.save(copy, 1).returns('older') + repository[configure]().save({ name: 'c', tags: [] }, 1).returns('newer') + copy.name = 'c' + copy.tags.length = 0 + t.is(repository.save({ name: 'c', tags: [] }, 1), 'newer') + + // re-configuring the same specification replaces the earlier substitution + const printed = Substitute.for() + printed.f(1).returns('a') + printed[configure]().f(1).returns('b') + printed.f(Arg.any()).returns('c') + printed[configure]().f(Arg.any()).returns('d') + t.is(printed.f(1), 'b') + t.is(printed.f(2), 'd') + t.regex(inspect(printed), /configured:\n {4}f\(1\) => returns\('b'\)\n {4}f\(Arg\.any\{any\}\) => returns\('d'\)\n\}$/) +}) + +test('D2 an argument object that is mutated after a call keeps its auto-substitute', t => { + const api = Substitute.for() + const request: { id: number, headers?: object } = { id: 1 } + api.get(request).body.returns('ok') + const response = api.get(request) + request.headers = { accept: 'json' } + t.is(api.get(request), response) + t.is(api.get(request).body, 'ok') + t.notThrows(() => api.received(3).get(request)) + + // a fresh object that is only equal to the arguments as they were gets its own auto-substitute + t.not(api.get({ id: 1 }), response) + + // nested assertions through the same object + const service = Substitute.for() + const query = { page: 1 } + service.find(query).log('first') + query.page = 2 + t.notThrows(() => service.find(query).received(1).log('first')) +}) diff --git a/spec/regression/fixes/performance.test.ts b/spec/regression/fixes/performance.test.ts index d14d6ed..34623d5 100644 --- a/spec/regression/fixes/performance.test.ts +++ b/spec/regression/fixes/performance.test.ts @@ -1,6 +1,6 @@ import test from 'ava' -import { Substitute, Arg } from '../../../src' +import { Substitute, Arg, configure } from '../../../src' interface Logger { log(message: string): void, level: number } interface Calculator { add(a: number, b: number): number } @@ -34,16 +34,56 @@ test('R:RT-8 / D19 resolving configured calls with distinct arguments stays fast t.true(elapsed < 1000, `took ${elapsed} ms`) }) +/** + * The best of three runs, so that a run slowed down by other processes or by a garbage collection does not count. + * `run` sets up its own substitute, so every run starts from scratch. + */ +const bestOfThree = (run: () => void) => Math.min(millisecondsOf(run), millisecondsOf(run), millisecondsOf(run)) + +/** + * Compares a run of `small` operations with a run of 16 times as many. Linear growth makes the large run about + * 16 times slower, quadratic growth up to 256 times. The bound of 48 leaves three times the linear ratio for + * noise, and fails once the quadratic part dominates the large run: scanning every earlier call on each call + * gives a ratio of about 150 (2000 calls: 16 ms, 32000 calls: 2.4 s). + */ +const growthOf = (small: number, run: (count: number) => void) => { + run(small) // warm up + const smallTime = bestOfThree(() => run(small)) + const largeTime = bestOfThree(() => run(small * 16)) + return { grows: largeTime >= Math.max(smallTime, 2) * 48, report: `${small}: ${smallTime} ms, ${small * 16}: ${largeTime} ms` } +} + test('R:RT-8 / D19 the cost of a call does not grow with the number of earlier calls', t => { - const timeFor = (count: number) => { + const { grows, report } = growthOf(2_000, count => { const logger = Substitute.for() - return millisecondsOf(() => { - for (let i = 0; i < count; i++) logger.log('x') - }) - } - timeFor(2_000) // warm up - const small = timeFor(4_000) - const large = timeFor(16_000) - // quadratic growth would make the large run about 16 times slower than the small one - t.true(large < Math.max(small, 5) * 8, `4000 calls: ${small} ms, 16000 calls: ${large} ms`) + for (let i = 0; i < count; i++) logger.log('x') + }) + t.false(grows, report) +}) + +const literalSetupsAndCalls = (count: number) => { + const calculator = Substitute.for() + for (let i = 0; i < count; i++) calculator.add(i, 1).returns(i) + for (let i = 0; i < count; i++) if (calculator.add(i, 1) !== i) throw new Error(`add(${i}, 1) did not return ${i}`) +} + +test('R:RT-8 / D19 8000 literal setups and 8000 matching calls finish in under 1s (literal substitutions are indexed)', t => { + literalSetupsAndCalls(1_000) // warm up + const elapsed = bestOfThree(() => literalSetupsAndCalls(8_000)) + t.true(elapsed < 1000, `took ${elapsed} ms`) + + // the same through configure(), on a substitute that also has matcher setups + const calculator = Substitute.for() + calculator.add(Arg.all()).returns(-1) + calculator.add(Arg.any(), 0).returns(-2) + const configured = millisecondsOf(() => { + for (let i = 0; i < 8_000; i++) calculator[configure]().add(i, 1).returns(i) + for (let i = 0; i < 8_000; i++) if (calculator.add(i, 1) !== i) throw new Error(`add(${i}, 1) did not return ${i}`) + }) + t.true(configured < 1000, `took ${configured} ms through configure()`) + t.is(calculator.add(1, 0), -2) + t.is(calculator.add(1, 2), -1) + + const { grows, report } = growthOf(1_000, literalSetupsAndCalls) + t.false(grows, report) }) diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index 7c7d15f..0911073 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -3,7 +3,7 @@ import { inspect } from 'util' import { CallRecord, RecordKind, currentSequence } from './CallRecord' import { RecordedArguments } from './RecordedArguments' import { SELF, SubstitutionMethod, keyToString } from './Constants' -import { fingerprintArguments } from './utilities' +import { fingerprintArguments, identityFingerprintArguments, stableFingerprintArguments } from './utilities' let substitutionOrder = 0 @@ -81,9 +81,95 @@ export class AutoEntry { type CallEntryIndex = { byFingerprint: Map + /** The entry last handed out for exactly these primitives and objects (see identityFingerprintArguments). */ + byIdentity: Map unfingerprinted: AutoEntry[] } +/** The most recent substitution in `list` (kept in configuration order) that matches, if it is more recent than `best`. */ +const mostRecentMatch = (list: readonly Substitution[], actualArguments: readonly unknown[], best: Substitution | undefined): Substitution | undefined => { + for (let index = list.length - 1; index >= 0; index--) { + const candidate = list[index] + if (best !== undefined && candidate.order < best.order) return best + if (candidate.args!.matches(actualArguments)) return candidate + } + return best +} + +/** + * The call substitutions configured for one member. + * + * All-literal substitutions (the most specific class, D4) are indexed by the stable fingerprint of their + * arguments, which deep strictly equal argument lists share and which does not change when an object in the + * arguments is mutated after the setup (literal arguments are compared as they are when the call is made, D15). + * A call therefore only compares against the literal substitutions with the same primitives in the same places: + * a single one for distinct primitive arguments, however many there are. Substitutions with Arg matchers are kept + * in a list. + */ +class CallSubstitutions { + private readonly _literal = new Map() + /** All-literal substitutions whose arguments could not be fingerprinted. */ + private readonly _unindexed: Substitution[] = [] + private readonly _withMatchers: Substitution[] = [] + private _size = 0 + + public get size(): number { + return this._size + } + + private listFor(args: RecordedArguments, create: boolean): Substitution[] | undefined { + if (args.argumentsClass !== 'plain') return this._withMatchers + const fingerprint = stableFingerprintArguments(args.value!) + if (fingerprint === undefined) return this._unindexed + let list = this._literal.get(fingerprint) + if (list === undefined && create) { + list = [] + this._literal.set(fingerprint, list) + } + return list + } + + /** Adds a substitution. One with the same specification is replaced (most recent wins). */ + public add(substitution: Substitution): void { + const list = this.listFor(substitution.args!, true)! + const index = list.findIndex(existing => existing.args!.equals(substitution.args!)) + if (index !== -1) list.splice(index, 1) + else this._size++ + list.push(substitution) + } + + /** The substitution configured with exactly this specification. */ + public withSpecification(args: RecordedArguments): Substitution | undefined { + return this.listFor(args, false)?.find(substitution => substitution.args!.equals(args)) + } + + /** The most specific class wins (all-literal, then predicates, then Arg.all()); within a class the most recent one. */ + public match(actualArguments: readonly unknown[]): Substitution | undefined { + let best: Substitution | undefined + const fingerprint = stableFingerprintArguments(actualArguments) + if (fingerprint !== undefined) { + const list = this._literal.get(fingerprint) + if (list !== undefined) best = mostRecentMatch(list, actualArguments, best) + } else for (const list of this._literal.values()) best = mostRecentMatch(list, actualArguments, best) + best = mostRecentMatch(this._unindexed, actualArguments, best) + if (best !== undefined) return best + + const withMatchers = this._withMatchers + for (let index = withMatchers.length - 1; index >= 0; index--) { + const candidate = withMatchers[index] + if (best !== undefined && candidate.rank >= best.rank) continue + if (candidate.args!.matches(actualArguments)) best = candidate + } + return best + } + + public *all(): IterableIterator { + for (const list of this._literal.values()) yield* list + yield* this._unindexed + yield* this._withMatchers + } +} + const memberPath = (state: SubstituteState, key: PropertyKey): string => key === SELF ? state.path : `${state.path}.${keyToString(key)}` @@ -108,7 +194,7 @@ export class SubstituteState { private readonly _pendingReads = new Map() private readonly _propertySubstitutions = new Map() - private readonly _callSubstitutions = new Map() + private readonly _callSubstitutions = new Map() private readonly _propertyEntries = new Map() private readonly _callEntries = new Map() @@ -187,25 +273,23 @@ export class SubstituteState { /** Adds a call substitution. A substitution with the same specification is replaced (most recent wins). */ public addCallSubstitution(key: PropertyKey, args: RecordedArguments, method: SubstitutionMethod | 'auto', values: readonly any[], entry?: AutoEntry): Substitution { const substitution = new Substitution('call', key, args, method, values, entry) - const list = this._callSubstitutions.get(key) - if (list === undefined) { - this._callSubstitutions.set(key, [substitution]) - return substitution + let substitutions = this._callSubstitutions.get(key) + if (substitutions === undefined) { + substitutions = new CallSubstitutions() + this._callSubstitutions.set(key, substitutions) } - const index = list.findIndex(existing => existing.args!.equals(args)) - if (index !== -1) list.splice(index, 1) - list.push(substitution) + substitutions.add(substitution) return substitution } public hasCallSubstitutions(key: PropertyKey): boolean { - const list = this._callSubstitutions.get(key) - return list !== undefined && list.length > 0 + const substitutions = this._callSubstitutions.get(key) + return substitutions !== undefined && substitutions.size > 0 } /** The substitution configured with exactly this specification, if any. */ public callSubstitutionFor(key: PropertyKey, args: RecordedArguments): Substitution | undefined { - return this._callSubstitutions.get(key)?.find(substitution => substitution.args!.equals(args)) + return this._callSubstitutions.get(key)?.withSpecification(args) } /** @@ -213,15 +297,7 @@ export class SubstituteState { * then Arg.all()), and within a class the most recently configured one wins. */ public findCallSubstitution(key: PropertyKey, actualArguments: readonly unknown[]): Substitution | undefined { - const list = this._callSubstitutions.get(key) - if (list === undefined) return undefined - let best: Substitution | undefined - for (let index = list.length - 1; index >= 0; index--) { - const candidate = list[index] - if (best !== undefined && candidate.rank >= best.rank) continue - if (candidate.args!.matches(actualArguments)) best = candidate - } - return best + return this._callSubstitutions.get(key)?.match(actualArguments) } // ---- auto-substitutes ----------------------------------------------------------------------- @@ -240,13 +316,28 @@ export class SubstituteState { return this._propertyEntries.get(key)?.materializedState !== undefined } - /** The auto-substitute for a call with these actual (literal) arguments. */ + /** + * The auto-substitute for a call with these actual (literal) arguments. The same objects get the same + * auto-substitute even when they were mutated in between (their structural fingerprint has gone stale then), + * so that after `api.get(request).body.returns(1)` and `request.x = 1`, `api.get(request).body` is still 1 (D2). + */ public callEntry(key: PropertyKey, actualArguments: any[]): AutoEntry { let index = this._callEntries.get(key) if (index === undefined) { - index = { byFingerprint: new Map(), unfingerprinted: [] } + index = { byFingerprint: new Map(), byIdentity: new Map(), unfingerprinted: [] } this._callEntries.set(key, index) } + const identity = identityFingerprintArguments(actualArguments) + if (identity !== undefined) { + const known = index.byIdentity.get(identity) + if (known !== undefined && known.args!.matches(actualArguments)) return known + } + const entry = this.structuralCallEntry(index, key, actualArguments) + if (identity !== undefined) index.byIdentity.set(identity, entry) + return entry + } + + private structuralCallEntry(index: CallEntryIndex, key: PropertyKey, actualArguments: any[]): AutoEntry { const fingerprint = fingerprintArguments(actualArguments) let bucket: AutoEntry[] | undefined if (fingerprint === undefined) bucket = index.unfingerprinted @@ -291,7 +382,7 @@ export class SubstituteState { /** Configured substitutions, for printing. */ public substitutions(): Substitution[] { const all: Substitution[] = [...this._propertySubstitutions.values()] - for (const list of this._callSubstitutions.values()) all.push(...list) + for (const substitutions of this._callSubstitutions.values()) all.push(...substitutions.all()) return all.sort((a, b) => a.order - b.order) } } diff --git a/src/internals/utilities/ArgumentHash.ts b/src/internals/utilities/ArgumentHash.ts index d320c4c..d33e7d7 100644 --- a/src/internals/utilities/ArgumentHash.ts +++ b/src/internals/utilities/ArgumentHash.ts @@ -1,12 +1,18 @@ /** - * A cheap structural fingerprint of an argument list, used to look up the auto-substitute cached for a - * call in O(1) instead of comparing against every earlier argument list. + * Cheap fingerprints of an argument list, used to look up the auto-substitute cached for a call, or the literal + * substitutions that can answer a call, in O(1) instead of comparing against every earlier argument list. * - * Contract: arguments that are deep strictly equal (util.isDeepStrictEqual) always get the same - * fingerprint. The fingerprint may be coarser than equality (callers still compare with - * isDeepStrictEqual inside a bucket). Functions, and therefore substitutes, are fingerprinted by - * identity and are never traversed. Returns undefined when the arguments cannot be fingerprinted - * (for example when a getter throws). + * Contract: arguments that are deep strictly equal (util.isDeepStrictEqual) always get the same structural and + * the same stable fingerprint. A fingerprint may be coarser than equality (callers still compare with + * isDeepStrictEqual inside a bucket). Functions, and therefore substitutes, are fingerprinted by identity and are + * never traversed. Returns undefined when the arguments cannot be fingerprinted (for example when a getter throws). + * + * - structural: looks into objects (two levels deep). It describes the arguments as they are now, so it goes + * stale when an object in them is mutated later. + * - stable: an object only counts as "an object", so it never goes stale. Used for configured substitutions, + * whose arguments are compared as they are when a call is made. + * - identity: an object counts by identity. Equal identity fingerprints mean the same primitives and the same + * objects, so the arguments are equal however the objects were mutated since. */ const objectIds = new WeakMap() const symbolIds = new Map() @@ -35,7 +41,9 @@ const MAX_ITEMS = 8 const MAX_KEYS = 16 const MAX_STRING = 64 -const fingerprintValue = (value: unknown, depth: number): string => { +type ObjectMode = 'structure' | 'stable' | 'identity' + +const fingerprintValue = (value: unknown, depth: number, objects: ObjectMode): string => { switch (typeof value) { case 'string': return `s${value.length}:${value.length > MAX_STRING ? value.slice(0, MAX_STRING) : value}` @@ -54,11 +62,12 @@ const fingerprintValue = (value: unknown, depth: number): string => { } if (value === null) return 'N' const object = value as object - if (depth >= MAX_DEPTH) return 'O' + if (objects === 'identity') return `I${idOfObject(object)}` + if (objects === 'stable' || depth >= MAX_DEPTH) return 'O' if (Array.isArray(object)) { let fingerprint = `A${object.length}[` const length = Math.min(object.length, MAX_ITEMS) - for (let index = 0; index < length; index++) fingerprint += fingerprintValue(object[index], depth + 1) + ',' + for (let index = 0; index < length; index++) fingerprint += fingerprintValue(object[index], depth + 1, objects) + ',' return fingerprint + ']' } if (ArrayBuffer.isView(object)) return `V${object.byteLength}` @@ -69,16 +78,23 @@ const fingerprintValue = (value: unknown, depth: number): string => { if (keys.length > MAX_KEYS) return `K${keys.length}` keys.sort() let fingerprint = '{' - for (const key of keys) fingerprint += `${key}:${fingerprintValue((object as any)[key], depth + 1)},` + for (const key of keys) fingerprint += `${key}:${fingerprintValue((object as any)[key], depth + 1, objects)},` return fingerprint + '}' } -export const fingerprintArguments = (args: readonly unknown[]): string | undefined => { +const fingerprintWith = (args: readonly unknown[], objects: ObjectMode): string | undefined => { try { let fingerprint = `${args.length}|` - for (const arg of args) fingerprint += fingerprintValue(arg, 0) + '|' + for (const arg of args) fingerprint += fingerprintValue(arg, 0, objects) + '|' return fingerprint } catch { return undefined } } + +/** Looks into objects; goes stale when they are mutated (see above). */ +export const fingerprintArguments = (args: readonly unknown[]): string | undefined => fingerprintWith(args, 'structure') +/** Objects only count as objects, so it never goes stale. */ +export const stableFingerprintArguments = (args: readonly unknown[]): string | undefined => fingerprintWith(args, 'stable') +/** Objects count by identity. */ +export const identityFingerprintArguments = (args: readonly unknown[]): string | undefined => fingerprintWith(args, 'identity') From 75e7a1ef9fd1510b5cfc8c3ee53efdd2c2c82185 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:39:16 +0000 Subject: [PATCH 021/106] docs(readme): rewrite the README for 2.0.1 Every example now compiles under strict TypeScript and does what the text says (the old snippets mostly failed to compile or crashed at runtime). - Fix the malformed badge HTML and the requirements: Node.js 10 for CommonJS, 12.17 for the ES module entry point, TypeScript 3.6. - Document importing (CommonJS, ES module default and named imports), sequences that repeat their last value, promises on properties, mimicks, the Arg.any type strings, Arg.all() for the rest of the arguments, the .not matchers, match order and precedence, configure(), partial mocks with [mimick](), auto-substitutes and nested members, received(count) validation, property checks, what counts as a call, clearReceivedCalls, SubstituteException, the assertions reported on process.nextTick, the name-conflict rules for TypeScript and JavaScript, the symbol API, special members, typing limitations and test runners. - Replace the Substitute.disableFor section, which described an API that no longer exists. - Link the migration guide, the changelog and CONTRIBUTING.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- README.md | 841 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 704 insertions(+), 137 deletions(-) diff --git a/README.md b/README.md index 56d1c1e..49cdff1 100644 --- a/README.md +++ b/README.md @@ -1,247 +1,814 @@ - +Financial Contributors on Open Collective # What is this? [`@fluffy-spoon/substitute`](https://www.npmjs.com/package/@fluffy-spoon/substitute) is a TypeScript port of [NSubstitute](http://nsubstitute.github.io), which aims to provide a much more fluent mocking opportunity for strong-typed languages. -*You can read an in-depth comparison of `substitute.js` versus other popular TypeScript mocking frameworks here: https://medium.com/@mathiaslykkegaardlorenzen/with-typescript-3-and-substitute-js-you-are-already-missing-out-when-mocking-or-faking-a3b3240c4607* +*You can read an in-depth comparison of `substitute.js` versus other popular TypeScript mocking frameworks here: https://medium.com/@mathiaslykkegaardlorenzen/with-typescript-3-and-substitute-js-you-are-already-missing-out-when-mocking-or-faking-a3b3240c4607 (written for version 1; the ideas still apply).* **PRs are very welcome! Help is much appreciated.** +> Upgrading from 1.x or from a 2.0.0 beta? Read the [migration guide](MIGRATION.md). What changed in each version is in the [changelog](CHANGELOG.md). + +# Table of contents +- [Installing](#installing) · [Requirements](#requirements) · [Importing](#importing) +- [Usage](#usage): [creating a substitute](#creating-a-substitute), [return values](#setting-return-values), [promises](#working-with-promises), [exceptions](#throwing-exceptions), [mimicking](#mimicking-an-implementation) +- [Argument matchers](#argument-matchers) and [match order](#match-order) +- [Re-configuring a call](#re-configuring-a-call-configure) · [Partial mocks](#partial-mocks) · [Auto-substitutes](#auto-substitutes-and-nested-members) +- [Verifying calls](#verifying-calls): [counts](#received-and-didnotreceive), [properties](#properties), [what counts as a call](#what-counts-as-a-call), [clearing](#clearing-received-calls), [SubstituteException](#substituteexception), [deferred failures](#assertions-that-fail-later) +- [Names that conflict with the library](#names-that-conflict-with-the-library) and [the symbol API](#the-symbol-api) +- [Special members](#special-members) · [Typing limitations](#typing-limitations) · [Test runners](#test-runners) + # Installing -`npm install @fluffy-spoon/substitute --save-dev` +```sh +npm install @fluffy-spoon/substitute --save-dev +``` + +This README describes version 2. Until 2.0.1, `npm install` installed 1.208.0 (the `latest` tag). If you depend on version 1, pin it with `npm install @fluffy-spoon/substitute@1 --save-dev`; its README is at the [v1.208.0 tag](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/tree/v1.208.0#readme). # Requirements -* `TypeScript^3.0.0` +* Node.js 10 or newer for CommonJS (`require`), and Node.js 12.17 or newer for the ES module entry point (`import`). +* TypeScript 3.6 or newer, if you use TypeScript. `strict` mode, including `strictNullChecks`, is supported. +* Any test runner. ava, jest, mocha, node:test and vitest are tested on every change (see [Test runners](#test-runners)). + +# Importing +TypeScript, or code compiled by a bundler: + +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' +// or: import Substitute, { Arg } from '@fluffy-spoon/substitute' +``` + +CommonJS: + +```js +const { Substitute, Arg } = require('@fluffy-spoon/substitute') + +const calculator = Substitute.for() +calculator.add(1, Arg.any()).returns(3) +console.log(calculator.add(1, 2)) // prints 3 +``` + +Native ES modules (`.mjs` files or `"type": "module"`). The default import is the `Substitute` class, and named imports work too: + + +```js +import Substitute, { Arg, received } from '@fluffy-spoon/substitute' + +const calculator = Substitute.for() +calculator.add(Arg.all()).returns(3) +console.log(calculator.add(1, 2)) // prints 3 +calculator[received](1).add(1, 2) +``` + +The ES module entry point wraps the CommonJS build, so both share one copy of the library. Everything is exported from the package root: `Substitute`, `Arg`, `SubstituteException`, the type `SubstituteOf`, and the symbols `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. Paths inside the package (`@fluffy-spoon/substitute/dist/...`) are not public API and can change in any release. # Usage +The examples in this README use this interface: + + ```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute'; +import { Substitute, Arg } from '@fluffy-spoon/substitute' interface Calculator { - add(a: number, b: number): number; - subtract(a: number, b: number): number; - divide(a: number, b: number): number; - async heavyOperation(): Promise; - - isEnabled: boolean; + add(a: number, b: number): number + subtract(a: number, b: number): number + divide(a: number, b: number): number + heavyOperation(...numbers: number[]): Promise + isEnabled: boolean } // Create: -const calculator = Substitute.for(); - +const calculator = Substitute.for() +``` + +Each of the following examples starts with a fresh `calculator`: + + +```typescript // Set a return value: -calculator.add(1, 2).returns(3); - +calculator.add(1, 2).returns(3) + +// Use the substitute wherever a Calculator is expected (normally in the code under test): +const sum = (c: Calculator) => c.add(1, 2) +console.log(sum(calculator)) // prints 3 + // Check received calls: -calculator.received().add(1, Arg.any()); -calculator.didNotReceive().add(2, 2); +calculator.received().add(1, Arg.any()) +calculator.didNotReceive().add(2, 2) ``` -## Creating a mock -`const calculator = Substitute.for();` - -## Setting return types -See the example below. The same syntax also applies to properties and fields. +## Creating a substitute +`Substitute.for()` creates a substitute for an interface, a class or any other type. Its type, `SubstituteOf`, is assignable to `T`, so you can hand it to the code under test. Nothing of a real instance is used: every member is substituted. (To use parts of a real instance, see [Partial mocks](#partial-mocks).) + ```typescript -// single return type -calculator.add(1, 2).returns(4); -console.log(calculator.add(1, 2)); // prints 4 -console.log(calculator.add(1, 2)); // prints undefined +class Display { + constructor(private readonly calculator: Calculator) { } + + showSum(a: number, b: number) { + return `${a} + ${b} = ${this.calculator.add(a, b)}` + } +} -// multiple return types in sequence -calculator.add(1, 2).returns(3, 7, 9); -console.log(calculator.add(1, 2)); // prints 3 -console.log(calculator.add(1, 2)); // prints 7 -console.log(calculator.add(1, 2)); // prints 9 -console.log(calculator.add(1, 2)); // prints undefined +calculator.add(1, 2).returns(3) +console.log(new Display(calculator).showSum(1, 2)) // prints 1 + 2 = 3 ``` +## Setting return values +Make the call with the arguments you want to configure, then call `.returns()` on it. The same syntax works for properties. + + +```typescript +// a single value is returned by every matching call +calculator.add(1, 2).returns(4) +console.log(calculator.add(1, 2)) // prints 4 +console.log(calculator.add(1, 2)) // prints 4 + +// several values are returned in sequence, and then the last value repeats +calculator.subtract(5, 1).returns(3, 7, 9) +console.log(calculator.subtract(5, 1)) // prints 3 +console.log(calculator.subtract(5, 1)) // prints 7 +console.log(calculator.subtract(5, 1)) // prints 9 +console.log(calculator.subtract(5, 1)) // prints 9 + +// properties work the same way +calculator.isEnabled.returns(true) +console.log(calculator.isEnabled) // prints true +``` + +A call or property that is not configured does not return `undefined`: it returns an [auto-substitute](#auto-substitutes-and-nested-members). A configured value can be changed later with [`configure`](#re-configuring-a-call-configure). Another substitute is a fine return value, too. + ## Working with promises -When working with promises you can also use `resolves()` and `rejects()` to return a promise. +For members that return a promise, `resolves()` and `rejects()` are shortcuts for returning a resolved or rejected promise. They work on methods and on promise-typed properties. + ```typescript -calculator.heavyOperation(1, 2).resolves(4); -// same as calculator.heavyOperation(1, 2).returns(Promise.resolve(4)); -console.log(await calculator.heavyOperation(1, 2)); // prints 4 +calculator.heavyOperation(1, 2).resolves(4) +// same as calculator.heavyOperation(1, 2).returns(Promise.resolve(4)) + +calculator.heavyOperation(0).rejects(new Error('too light')) +// like calculator.heavyOperation(0).returns(Promise.reject(new Error('too light'))), except that the +// rejected promise is only created when heavyOperation(0) is called + +async function run() { + console.log(await calculator.heavyOperation(1, 2)) // prints 4 + await calculator.heavyOperation(0).catch(error => console.log(error.message)) // prints too light +} +run() ``` ```typescript -calculator.heavyOperation(1, 2).rejects(new Error()); -// same as calculator.heavyOperation(1, 2).returns(Promise.reject(new Error())); -console.log(await calculator.heavyOperation(1, 2)); // throws Error +import { Substitute } from '@fluffy-spoon/substitute' + +interface Connection { + ready: Promise +} + +const connection = Substitute.for() +connection.ready.resolves(true) +connection.ready.then(ready => console.log(ready)) // prints true ``` -## Verifying calls +## Throwing exceptions +Exceptions can be thrown from methods and properties, with different exceptions for different arguments. The exception is thrown when the configured call happens. + + ```typescript -calculator.enabled = true; -const foo = calculator.add(1, 2); +calculator.divide(Arg.any(), 0).throws(new Error('Cannot divide by 0')) +calculator.divide(1, 0) // throws Error: Cannot divide by 0 + +calculator.isEnabled.throws(new Error('Not available')) +calculator.isEnabled // throws Error: Not available +``` + +Like `returns()`, `throws()`, `resolves()`, `rejects()` and `mimicks()` take several values, which are used in sequence. The last one repeats. -// verify call to add(1, 2) -calculator.received().add(1, 2); +## Mimicking an implementation +`mimicks()` runs a function of your own for the matching calls. It gets the call's arguments, and its return value is returned. -// verify property set to "true" -calculator.received().enabled = true; + +```typescript +calculator.add(Arg.all()).mimicks((a, b) => a + b) +console.log(calculator.add(2, 3)) // prints 5 + +let enabled = false +calculator.isEnabled.mimicks(() => enabled) +console.log(calculator.isEnabled) // prints false +enabled = true +console.log(calculator.isEnabled) // prints true ``` -## Argument matchers -There are several ways of matching arguments. The examples below also applies to properties and fields - both when setting up calls and verifying them. +The function is not called with the substitute as `this`. Pass an arrow function or a bound method if the implementation needs `this`. + +# Argument matchers +There are several ways of matching arguments. They work the same when you set up calls and when you verify them, and they also work for property assignments (`calculator.received().isEnabled = Arg.any()`). + +## Matching specific arguments +`Arg.any()` matches any value. `Arg.is(predicate)` matches the values for which the predicate returns `true`. When `Arg.is` replaces an argument, the type of the predicate's parameter is inferred from that argument. -### Matching specific arguments + ```typescript -import { Arg } from '@fluffy-spoon/substitute'; +// ignoring the first argument +calculator.add(Arg.any(), 2).returns(10) +console.log(calculator.add(1337, 2)) // prints 10 +// calculator.add(1337, 3) does not match: it returns an auto-substitute, not 10 -// ignoring first argument -calculator.add(Arg.any(), 2).returns(10); -console.log(calculator.add(1337, 3)); // prints undefined since second argument doesn't match -console.log(calculator.add(1337, 2)); // prints 10 since second argument matches +// x is inferred as a number +calculator.subtract(Arg.is(x => x < 0), Arg.any()).returns(0) +console.log(calculator.subtract(-5, 3)) // prints 0 -// received call with first arg 1 and second arg less than 0 -calculator.received().add(1, Arg.is(x => x < 0)); +// matchers verify received calls, too +calculator.received().add(Arg.is(x => x > 1000), 2) ``` -### Generic and inverse matchers +Outside of an argument position, for example in a variable, there is nothing to infer the type from, so annotate the parameter: + + ```typescript -import { Arg } from '@fluffy-spoon/substitute'; +const negative = Arg.is((x: number) => x < 0) +calculator.divide(negative, negative).returns(1) +console.log(calculator.divide(-4, -2)) // prints 1 +``` + +`Arg.is()` with something other than a function throws a `TypeError` right away. A predicate that throws, for example because it reads a property of `null`, counts as a non-match: the code under test is not affected, and a failed assertion says that the predicate threw. -const equalToZero = (x: number) => x === 0; +## Matching by type +`Arg.any(type)` matches values of a type: -// first argument will match any number -// second argument will match a number that is not '0' -calculator.divide(Arg.any('number'), Arg.is.not(equalToZero)).returns(10); -console.log(calculator.divide(100, 10)); // prints 10 +| `type` | Matches | +|---|---| +| `'any'` (the default) | any value, including `undefined` and `null` | +| `'string'`, `'number'`, `'boolean'`, `'symbol'`, `'undefined'` | values with that `typeof` | +| `'object'` | objects, arrays and substitutes, but not `null` | +| `'function'` | functions (and classes) and substitutes | +| `'array'` | arrays (`Array.isArray`) | -const argIsNotZero = Arg.is.not(equalToZero); -calculator.received(1).divide(argIsNotZero, argIsNotZero); +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' + +interface Printer { + print(value: unknown): string +} + +const printer = Substitute.for() +printer.print(Arg.any('string')).returns('a string') +printer.print(Arg.any('object')).returns('an object') +printer.print(Arg.any('array')).returns('an array') + +console.log(printer.print('hello')) // prints a string +console.log(printer.print({ id: 1 })) // prints an object +// an array matches both 'object' and 'array'; the setup made last wins (see "Match order") +console.log(printer.print([1, 2])) // prints an array + +printer.print(null) +// { id: 1 } and [1, 2] are objects, null is not +printer.received(2).print(Arg.any('object')) ``` -> #### Note: `Arg.is()` will automatically infer the type of the argument it's replacing +## Inverse matchers +`Arg.is.not(predicate)` and `Arg.any.not(type)` match the values that the matcher without `.not` does not match. -### Ignoring all arguments + ```typescript -// ignoring all arguments -calculator.add(Arg.all()).returns(10); -console.log(calculator.add(1, 3)); // prints 10 -console.log(calculator.add(5, 2)); // prints 10 +const isZero = (x: number) => x === 0 + +// the first argument matches any number, the second any number except 0 +calculator.divide(Arg.any('number'), Arg.is.not(isZero)).returns(10) +console.log(calculator.divide(100, 10)) // prints 10 +// calculator.divide(100, 0) does not match + +calculator.received(1).divide(Arg.any(), Arg.is.not(isZero)) +calculator.didNotReceive().divide(Arg.any.not('number'), Arg.any()) ``` -### Match order -The order of argument matchers matters. The first matcher that matches will always be used. Below are two examples. +## Ignoring all arguments +`Arg.all()` as the only argument matches every call, whatever its arguments: + ```typescript -calculator.add(Arg.all()).returns(10); -calculator.add(1, 3).returns(1337); -console.log(calculator.add(1, 3)); // prints 10 -console.log(calculator.add(5, 2)); // prints 10 +calculator.add(Arg.all()).returns(10) +console.log(calculator.add(1, 3)) // prints 10 +console.log(calculator.add(5, 2)) // prints 10 ``` +After other arguments, `Arg.all()` matches the rest of the arguments, which can also be none. The arguments before it must match as usual. Arguments after `Arg.all()` are an error (a `SubstituteException`). + ```typescript -calculator.add(1, 3).returns(1337); -calculator.add(Arg.all()).returns(10); -console.log(calculator.add(1, 3)); // prints 1337 -console.log(calculator.add(5, 2)); // prints 10 +import { Substitute, Arg } from '@fluffy-spoon/substitute' + +interface Logger { + log(message: string, ...details: unknown[]): void +} + +const logger = Substitute.for() +logger.log('saved') +logger.log('saved', 42, 'extra') +logger.log('deleted', 7) + +logger.received(2).log('saved', Arg.all()) +logger.received(1).log('deleted', Arg.all()) +logger.received(3).log(Arg.all()) ``` -## Partial mocks -With partial mocks you always start with a true substitute where everything is mocked and then opt-out of substitutions in certain scenarios. +## Match order +When several setups match a call, the most specific one wins: + +1. a setup whose arguments are all literal values, +2. then a setup with at least one `Arg.any()` / `Arg.is()` matcher (or literals followed by `Arg.all()`), +3. then a setup with `Arg.all()` as its only argument. +Among setups of the same kind, the one configured last wins, so a later setup overrides an earlier one. + + ```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute'; +calculator.add(1, 3).returns(1337) +calculator.add(Arg.all()).returns(10) +calculator.add(Arg.is(a => a > 100), Arg.any()).returns(100) + +// literal arguments win over matchers, and matchers win over Arg.all() +console.log(calculator.add(1, 3)) // prints 1337 +console.log(calculator.add(200, 3)) // prints 100 +console.log(calculator.add(5, 2)) // prints 10 + +// among setups with matchers, the newest one wins +calculator.add(Arg.any(), Arg.is(b => b > 10)).returns(-1) +console.log(calculator.add(200, 30)) // prints -1 +console.log(calculator.add(200, 3)) // prints 100 +``` + +## Re-configuring a call (configure) +Outside of a setup, a call whose literal arguments match an existing setup is a real call: it returns the configured value. A primitive value like `10` has no `.returns()`, so you cannot configure such a call again by writing it out. (If the configured value is an object or a substitute, `.returns()` would even configure that object instead.) +Use `sub[configure]()` instead. It gives a view of the substitute in which every call and property read is a setup: it never runs an existing setup and is never recorded as a received call. + + +```typescript +import { configure } from '@fluffy-spoon/substitute' + +calculator.add(Arg.all()).returns(10) +// add(1, 3) matches the setup above, so it returns 10 and has no .returns(): +calculator.add(1, 3).returns(1337) // throws TypeError: calculator.add(...).returns is not a function + +calculator[configure]().add(1, 3).returns(1337) +console.log(calculator.add(1, 3)) // prints 1337 +console.log(calculator.add(5, 2)) // prints 10 + +// the same applies to changing a value that is already configured, and to properties +calculator.isEnabled.returns(true) +calculator[configure]().isEnabled.returns(false) +console.log(calculator.isEnabled) // prints false +``` + +Calls with argument matchers are always setups (see [What counts as a call](#what-counts-as-a-call)), so a catch-all setup *after* a specific one needs no `configure`. In TypeScript, the `configure` view only offers the setup methods. + +# Partial mocks +With partial mocks you always start with a true substitute where everything is mocked, and then opt out of substitutions in certain scenarios: per call with `mimicks()`, or for a whole instance with `[mimick]()`. The examples use this implementation: + + +```typescript class RealCalculator implements Calculator { - add(a: number, b: number) => a + b; - subtract(a: number, b: number) => a - b; - divide(a: number, b: number) => a / b; + isEnabled = true + add(a: number, b: number) { return a + b } + subtract(a: number, b: number) { return a - b } + divide(a: number, b: number) { return a / b } + async heavyOperation(...numbers: number[]) { return numbers.reduce((total, n) => total + n, 0) } } -const realCalculator = new RealCalculator(); -const fakeCalculator = Substitute.for(); +const realCalculator = new RealCalculator() +``` + +```typescript // let the subtract method always use the real method -fakeCalculator.subtract(Arg.all()).mimicks(realCalculator.subtract); -console.log(fakeCalculator.subtract(20, 10)); // prints 10 -console.log(fakeCalculator.subtract(1, 2)); // prints -1 +calculator.subtract(Arg.all()).mimicks(realCalculator.subtract) +console.log(calculator.subtract(20, 10)) // prints 10 +console.log(calculator.subtract(1, 2)) // prints -1 + +// for the add method, use the real method only when the first argument is less than 10 +// else, always return 1337 +calculator.add(Arg.is(x => x < 10), Arg.any()).mimicks(realCalculator.add) +calculator.add(Arg.is(x => x >= 10), Arg.any()).returns(1337) +console.log(calculator.add(5, 100)) // prints 105 +console.log(calculator.add(210, 7)) // prints 1337 + +// for the divide method, use the real method only for these exact arguments +calculator.divide(10, 2).mimicks(realCalculator.divide) +calculator.divide(Arg.all()).returns(1338) +console.log(calculator.divide(10, 2)) // prints 5 +console.log(calculator.divide(10, 5)) // prints 1338 +``` -// for the add method, we only use the real method when the first arg is less than 10 -// else, we always return 1337 -fakeCalculator.add(Arg.is(x < 10), Arg.any()).mimicks(realCalculator.add); -fakeCalculator.add(Arg.is(x >= 10), Arg.any()).returns(1337); -console.log(fakeCalculator.add(5, 100)); // prints 105 via real method -console.log(fakeCalculator.add(210, 7)); // prints 1337 via fake method +`sub[mimick](instance)` hands everything that is not configured to a real instance: property reads return the instance's values, method calls run the instance's methods (with `this` being the instance), and assignments write to the instance. Members that the instance does not have read as `undefined`. Setups still win, and every call is recorded, so you can verify it. Because real calls are passed on to the instance, configure a mimicked substitute through [`[configure]()`](#re-configuring-a-call-configure). -// for the divide method, we only use the real method for explicit arguments -fakeCalculator.divide(10, 2).mimicks(realCalculator.divide); -fakeCalculator.divide(Arg.all()).returns(1338); -console.log(fakeCalculator.divide(10, 5)); // prints 5 -console.log(fakeCalculator.divide(9, 5)); // prints 1338 + +```typescript +import { mimick, configure } from '@fluffy-spoon/substitute' + +calculator[mimick](realCalculator) +console.log(calculator.add(2, 3)) // prints 5 +console.log(calculator.isEnabled) // prints true + +calculator[configure]().divide(Arg.all()).returns(0) +console.log(calculator.divide(1, 1)) // prints 0 + +// the code under test sets a property +const disable = (c: Calculator) => { c.isEnabled = false } +disable(calculator) +console.log(realCalculator.isEnabled) // prints false + +calculator.received().add(2, 3) +calculator.received().isEnabled = false ``` -## Throwing exceptions -Exceptions can be thrown on properties or methods. You can add different exceptions for different arguments +The string `mimick` is not part of the API (any more): `sub.mimick(...)` is an ordinary member, like every name except the [conflicting names](#names-that-conflict-with-the-library). + +# Auto-substitutes and nested members +A member or call that is not configured returns an auto-substitute: a substitute of its own, created the first time and then reused. The same member, or the same method with equal arguments, always gives the same auto-substitute. So the code under test can use nested members without crashing, and you can configure and verify them: + +```js +const { Substitute } = require('@fluffy-spoon/substitute') + +const app = Substitute.for() +console.log(app.logger === app.logger) // prints true +console.log(app.getCalculator() === app.getCalculator()) // prints true + +app.getCalculator().add(1, 2).returns(99) +console.log(app.getCalculator().add(1, 2)) // prints 99 + +// the code under test logs a message +app.logger.info('started') + +app.logger.received().info('started') +app.logger.didNotReceive().info('stopped') +``` + +Setups and calls never leak between members: `app.add(1, 2).returns(99)` does not configure `app.getCalculator().add(1, 2)`, and the other way round. The calls in a setup or an assertion (`app.getCalculator()` above) are not recorded as received calls. + +**Typing limitation:** in TypeScript, nested auto-substitutes are typed as plain values, not as substitutes, so `app.getCalculator().add(1, 2).returns(99)` and `app.logger.received()` do not compile. They do work at runtime (in JavaScript, or through a cast). In TypeScript, configure the member to return a substitute you create yourself; that is fully typed: ```typescript -import { Substitute, Arg } from '@fluffy-spoon/substitute'; +import { Substitute } from '@fluffy-spoon/substitute' -interface Calculator { - add(a: number, b: number): number; - subtract(a: number, b: number): number; - divide(a: number, b: number): number; - isEnabled: boolean; +interface Logger { info(message: string): void } +interface Calculator { add(a: number, b: number): number } +interface App { + logger: Logger + getCalculator(): Calculator } -const calculator = Substitute.for(); -calculator.divide(Arg.any(), 0).throws(new Error('Cannot divide by 0')); -calculator.divide(1, 0); // throws the exception Error: Cannot divide by 0 +const app = Substitute.for() +const logger = Substitute.for() +const calculator = Substitute.for() +app.logger.returns(logger) +app.getCalculator().returns(calculator) + +calculator.add(1, 2).returns(99) +console.log(app.getCalculator().add(1, 2)) // prints 99 + +app.logger.info('started') +logger.received().info('started') ``` -# Benefits over other mocking libraries -- Easier-to-understand fluent syntax. -- No need to cast to `any` in certain places (for instance, when overriding read-only properties) due to the `myProperty.returns(...)` syntax. -- Doesn't weigh much. -- Produces very clean and descriptive error messages. Try it out - you'll love it. -- Doesn't rely on object instances - you can produce a strong-typed fake from nothing, ensuring that everything is mocked. +# Verifying calls +## received and didNotReceive +`received()` checks that a call was received at least once, `received(count)` that it was received exactly `count` times, and `didNotReceive()` that it was never received. A failed check throws a [`SubstituteException`](#substituteexception). + + +```typescript +calculator.add(1, 2) +calculator.add(1, 2) +calculator.add(3, 4) -# Beware -## Names that conflict with Substitute.js -Let's say we have a class with a method called `received`, `didNotReceive` or `mimick` keyword - how do we mock it? +calculator.received().add(1, 2) +calculator.received(2).add(1, 2) +calculator.received(3).add(Arg.all()) +calculator.didNotReceive().add(5, 6) +calculator.received(0).add(5, 6) // the same as didNotReceive() -Simple! We disable the proxy methods temporarily while invoking the method by using the `disableFor` method which disables these special methods. +calculator.received(1).add(1, 2) // throws SubstituteException +``` + +The count must be a non-negative integer, or left out (meaning "1 or more"). Anything else (a negative or fractional number, `NaN`, `Infinity`, a string) throws a `SubstituteException` instead of letting the check pass: + + +```typescript +const items = ['a', 'b'] +calculator.received(items.length - 3).add(1, 2) // throws SubstituteException: Expected count has to be a non-negative integer +``` + +A failed check describes what was expected and lists the calls that were received (at most 50 of them): + + +```typescript +calculator.add(1, 2) +calculator.received().add(3, 4) // throws SubstituteException +``` + + +```text +SubstituteException: Call count mismatch in @Substitute.add: +Expected to receive 1 or more method calls matching add(3, 4), but received none. +All property or method calls to @Substitute.add received so far: +› ✘ @Substitute.add(1, 2) + called at Object. (test/calculator.test.ts:2:12) +``` + +The message contains ANSI colours only when the output is a terminal. `NO_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb` turn colours off, and `FORCE_COLOR` turns them on. + +## Properties +`received().property` counts reads of a property, and `received().property = value` counts assignments of that value (matchers work here as well). + + +```typescript +// the code under test reads the property and sets it +const toggle = (c: Calculator) => { c.isEnabled = !c.isEnabled } + +calculator.isEnabled.returns(false) +toggle(calculator) + +calculator.received(1).isEnabled +calculator.received().isEnabled = true +calculator.received(1).isEnabled = Arg.any() +calculator.didNotReceive().isEnabled = false +``` + +In TypeScript, assigning a property on the substitute itself (`calculator.isEnabled = true`) does not compile, see [Typing limitations](#typing-limitations). The code under test assigns through its own type, like `toggle` above. + +## What counts as a call +* Every invocation is a call of its own, also through a stored or destructured reference, a callback, or `.call()` / `.apply()` / `.bind()`. +* Reading a method without calling it, for example to register it as an event handler that never fires, is not a call. Method checks (`received().subtract(...)`, also with `Arg.all()`) only count invocations. +* A call with an argument matcher (`Arg.any()`, `Arg.is()`, `Arg.all()`, also with `.not`) is a setup or a check, never a received call. It does not run an existing setup either. +* Checks never run setups or mimicked implementations, and are never recorded themselves. Checking a property configured with `throws()` does not throw, and checking a property configured with a sequence does not use up a value. + + +```typescript +const { add } = calculator +for (const n of [1, 2, 3]) add(n, n) +calculator.received(3).add(Arg.all()) + +const handler = calculator.subtract +calculator.received().subtract(Arg.all()) // throws SubstituteException + +calculator.divide(Arg.any(), 2) // a setup without a value, not a call +calculator.didNotReceive().divide(Arg.all()) +``` + +**Known issue in 2.0.1:** `didNotReceive().subtract(...)` (or `received(0)`) on a method that has been read but never called fails, because the library decides at `.subtract` whether you check a property read or a method call. If the code under test registers a method without calling it, clear the received calls after that (see below) before you check that it was not called. + +## Clearing received calls +`sub[clearReceivedCalls]()` forgets the received calls of a substitute and of its auto-substitutes. Setups are kept, including the position in a sequence of return values. To start over completely, create a new substitute. + ```typescript +import { clearReceivedCalls } from '@fluffy-spoon/substitute' + +calculator.add(1, 2).returns(3) +calculator.add(1, 2) +calculator[clearReceivedCalls]() + +calculator.didNotReceive().add(1, 2) +console.log(calculator.add(1, 2)) // prints 3 +``` + +## SubstituteException +Failed checks, and invalid use of the library such as `received(-1)` or arguments after `Arg.all()`, throw a `SubstituteException`. It is exported, so you can check for it with `instanceof`: + + +```typescript +import { SubstituteException } from '@fluffy-spoon/substitute' + +try { + calculator.received().add(1, 2) +} catch (error) { + console.log(error instanceof SubstituteException) // prints true +} +``` + +## Assertions that fail later +Checks throw right away, with one exception. In a property-style check, `sub.received(count).member` that is not followed by a call, on a member that has been called as a method, the library cannot know yet whether you are about to call it (`sub.received(2).member(...)`). If the property check fails, the failure is reported on `process.nextTick`, and it is cancelled if you call the member. Such a failure escapes `try`/`catch` and `t.throws()`. Test runners report it as an uncaught exception in the running test. + + +```typescript +calculator.add(1, 2) +calculator.add(1, 2) +calculator.add(3, 4) + +// not followed by a call, so the library cannot decide yet: +// the SubstituteException is thrown later, on process.nextTick +calculator.received(2).add +``` + +To avoid this, check methods with a call (`calculator.received(2).add(1, 2)`, or `.add(Arg.all())`). Those are decided right away. + +# Names that conflict with the library +A substituted type may have members with the same names as the library's methods: `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`. Each of them has a symbol (exported from the package) that always means the library method. + +## In TypeScript +If the substituted type has a member with one of these names, `sub.received()` and `sub.didNotReceive()` are not offered, because they would be ambiguous. Use the symbols `sub[received]()` and `sub[didNotReceive]()`; they are always available. + +```typescript +import { Substitute, Arg, received } from '@fluffy-spoon/substitute' + class Example { received(someNumber: number) { - console.log(someNumber); + return someNumber } } -const fake = Substitute.for(); +const fake = Substitute.for() -// BAD: this would have called substitute.js' "received" method. -// fake.received(2); +// `fake.received` is the class' own method +fake.received(1).returns(2) +console.log(fake.received(1)) // prints 2 -// GOOD: we now call the "received" method we have defined in the class above. -Substitute.disableFor(fake).received(1337); +// check it with the symbol +fake[received]().received(1) +fake[received](1).received(Arg.any()) +fake[received](2).received(1) // throws SubstituteException +``` -// now we can assert that we received a call to the "received" method. -fake.received().received(1337); +In the same way, `.returns()`, `.throws()`, `.mimicks()`, `.resolves()` and `.rejects()` are not offered on a value that has its own member with that name. That value is the property's type, or the return type of the call. Use the symbols `[returns]`, `[throws]`, `[mimicks]`, `[resolves]` and `[rejects]` there; they always work. + +```typescript +import { Substitute, returns } from '@fluffy-spoon/substitute' + +interface Order { + returns: string[] + total(): number +} + +interface Shop { + find(id: string): Order +} + +const shop = Substitute.for() +const order = Substitute.for() + +// an Order has a member called `returns`, so shop.find('1').returns is that member +shop.find('1')[returns](order) +order.total().returns(42) + +console.log(shop.find('1').total()) // prints 42 +``` + +`clearReceivedCalls`, `mimick` and `configure` exist only as symbols, so members with those names never conflict. + +## In JavaScript +Without types, the library decides by how a name is used: + +* `sub.received(...)` and `sub.didNotReceive()` are checks when they are called and followed by a member, like `sub.received(2).add(1, 2)`. Followed by `.returns()`, `.throws()`, `.resolves()`, `.rejects()` or `.mimicks()`, they configure a member of your own called `received` or `didNotReceive`. +* `sub.received` that is not called is an ordinary member, so the code under test can read a property called `received`. +* The symbols `sub[received]()` and `sub[didNotReceive]()` are always checks. Use them to check members called `returns`, `throws`, `resolves`, `rejects` or `mimicks`. + +```js +const { Substitute, received } = require('@fluffy-spoon/substitute') + +const mailbox = Substitute.for() +mailbox.received(1).returns(['mail']) +console.log(mailbox.received(1)) // prints [ 'mail' ] + +const builder = Substitute.for() +builder.returns(5) // the code under test calls its own `returns` method +builder[received]().returns(5) ``` -## Contributors +# The symbol API +All of these are exported from the package root. + +| Symbol | Usage | Notes | +|---|---|---| +| `received` | `sub[received](count?).member...` | Always a check. | +| `didNotReceive` | `sub[didNotReceive]().member...` | Always a check, the same as `[received](0)`. | +| `clearReceivedCalls` | `sub[clearReceivedCalls]()` | Symbol only. See [Clearing received calls](#clearing-received-calls). | +| `mimick` | `sub[mimick](instance)` | Symbol only. See [Partial mocks](#partial-mocks). | +| `configure` | `sub[configure]().member...` | Symbol only. See [Re-configuring a call](#re-configuring-a-call-configure). | +| `returns`, `throws`, `resolves`, `rejects`, `mimicks` | `sub.member(...)[returns](value)`, `sub.property[throws](error)` | The same as the string methods. They configure a member or a call, so using them on the substitute itself (`sub[returns](1)`) is an error. | + +The symbols are registered with `Symbol.for()`, so they also work when two copies of the package are installed. + +# Special members +A few members are handled by the substitute itself and cannot be configured or checked: + +* `then` is always `undefined`, so a substitute is not a thenable. You can return it from an `async` function or `await` it, and you get the substitute back. In TypeScript, a member called `then` is typed `never`. +* `toJSON`: `JSON.stringify(sub)` gives a short description of the substitute. +* `Symbol.toPrimitive` and `util.inspect.custom`: `String(sub)`, template strings and `console.log(sub)` show the substitute's setups and received calls. + +```typescript +import { Substitute } from '@fluffy-spoon/substitute' + +interface Calculator { add(a: number, b: number): number } + +const calculator = Substitute.for() +async function load() { return calculator } +load().then(loaded => console.log(loaded === calculator)) // prints true +``` + +# Typing limitations +TypeScript cannot express a few things about substitutes: + +* **Assigning a property on the substitute** (`calculator.isEnabled = true`) does not compile, because the property's type also carries the setup API (`.returns()` and so on). Assign through the interface type, as the code under test does, and check with `calculator.received().isEnabled = true`. +* **`null` and `undefined`** are not part of the type of a call or property under `strictNullChecks`, although `.returns(null)` is accepted. Assign the value to the declared type, or give explicit type arguments (`t.is(repository.find(1), null)`). +* **A generic method called with explicit type arguments** (`store.get('answer')`) has no setup API. Call it without type arguments. +* **Overloads whose parameters have literal types** (`on(event: 'data', ...)`) resolve to the interface's own declaration when you call them directly. Configure them with `sub[configure]().on('data', ...)`. +* **More than 8 overloads:** only the last 8 have the setup API. +* **A property typed `never`** cannot be configured. +* **Nested auto-substitutes** are not typed as substitutes, see [Auto-substitutes](#auto-substitutes-and-nested-members). + + +```typescript +import { configure } from '@fluffy-spoon/substitute' + +// @ts-expect-error the property's type carries the setup API +calculator.isEnabled = true +const asCalculator: Calculator = calculator +asCalculator.isEnabled = true +// at runtime, both assignments are recorded +calculator.received(2).isEnabled = true + +interface Repository { + find(id: number): string | null +} +const repository = Substitute.for() +repository.find(1).returns(null) +const found: string | null = repository.find(1) +console.log(found) // prints null + +interface Store { + get(key: string): T +} +const store = Substitute.for() +store.get('answer').returns(42) +console.log(store.get('answer')) // prints 42 + +interface Socket { + on(event: 'data', listener: (data: string) => void): Socket + on(event: 'close', listener: () => void): Socket +} +const socket = Substitute.for() +socket[configure]().on('data', Arg.any()).returns(socket) +console.log(socket.on('data', () => { }) === socket) // prints true +``` + +# Test runners +Checks throw a `SubstituteException`, so they work with any test runner: a failed check fails the test, and you can expect one with your runner's `throws` assertion. ava, jest, mocha, node:test and vitest are tested on every change, including a check that [fails later](#assertions-that-fail-later), which each of them reports as a failure. + +```typescript +import { test } from 'node:test' +import * as assert from 'node:assert' +import { Substitute, SubstituteException } from '@fluffy-spoon/substitute' + +interface Calculator { add(a: number, b: number): number } + +test('adds the numbers', () => { + const calculator = Substitute.for() + calculator.add(1, 2) + + calculator.received().add(1, 2) + assert.throws(() => calculator.received().add(3, 4), SubstituteException) +}) +``` + +With ava: + + +```typescript +import test from 'ava' +import { Substitute, SubstituteException } from '@fluffy-spoon/substitute' + +interface Calculator { add(a: number, b: number): number } + +test('adds the numbers', t => { + const calculator = Substitute.for() + calculator.add(1, 2) + + t.notThrows(() => calculator.received().add(1, 2)) + t.throws(() => calculator.received().add(3, 4), { instanceOf: SubstituteException }) +}) +``` + +# Benefits over other mocking libraries +- Easier-to-understand fluent syntax. +- No need to cast to `any` in certain places (for instance, when overriding read-only properties) due to the `myProperty.returns(...)` syntax. +- Doesn't weigh much. +- Produces very clean and descriptive error messages. Try it out - you'll love it. +- Doesn't rely on object instances - you can produce a strong-typed fake from nothing, ensuring that everything is mocked. + +# Contributors -### Code Contributors +## Code Contributors This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. -### Financial Contributors +## Financial Contributors Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/substitute-js/contribute)] -#### Individuals +### Individuals -#### Organizations +### Organizations Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/substitute-js/contribute)] From 4ce3511b4b64e227db40f5475e50b1eebaf888a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:39:23 +0000 Subject: [PATCH 022/106] docs: add a migration guide for 1.x and the 2.0.0 betas Covers npm latest moving from 1.208.0 to 2.x, the Node.js and TypeScript minimums, the removed APIs (Substitute.disableFor, clearSubstitute and ClearType, the string mimick(instance)) with their replacements, the symbol API and the name-conflict rules, and the behaviour changes: sequences repeating their last value, cached auto-substitutes and nested checks that really check, matcher calls being setups, match order, configure(), what counts as a call, checks never running setups, received(count) validation, matchers and messages. Also the ES module default import, the exports map and the moved deep import paths. Each section says which old versions it applies to; the "after" examples are checked like the README's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- MIGRATION.md | 365 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 365 insertions(+) create mode 100644 MIGRATION.md diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..ff2a780 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,365 @@ +# Migration guide +This guide covers upgrading to 2.0.1 from 1.x (1.208.0 and older) and from the 2.0.0 betas (2.0.0-beta.0 to 2.0.0-beta.4). 2.0.1 is the first stable release of version 2; there was no 2.0.0 release. The [README](README.md) describes the 2.x API, and the [changelog](CHANGELOG.md) lists every change. + +Each section says which versions it applies to. Code marked "Before" is for the old version and is not valid 2.x code. + +- [Installing: `latest` is now 2.x](#installing-latest-is-now-2x) +- [Requirements](#requirements) +- [Removed APIs](#removed-apis): [`Substitute.disableFor`](#substitutedisablefor), [`clearSubstitute` and `ClearType`](#clearsubstitute-and-cleartype), [string `mimick(instance)`](#the-string-mimickinstance) +- [Names that conflict with the library: the symbol API](#names-that-conflict-with-the-library-the-symbol-api) +- [Behaviour changes](#behaviour-changes): [sequences](#sequences-repeat-the-last-value), [auto-substitutes](#auto-substitutes-and-nested-checks), [matcher calls](#calls-with-argument-matchers-are-setups), [match order](#match-order), [re-configuring](#re-configuring-a-call), [what counts as a call](#what-counts-as-a-call), [checks](#checks-never-run-setups), [`received(count)`](#receivedcount-is-validated), [matchers](#matchers), [messages](#messages) +- [Imports and packaging](#imports-and-packaging) +- [TypeScript](#typescript) + +The examples use this interface: + + +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' + +interface Calculator { + add(a: number, b: number): number + subtract(a: number, b: number): number + isEnabled: boolean +} + +const calculator = Substitute.for() +``` + +## Installing: `latest` is now 2.x +*Applies to: everyone.* + +Up to 2.0.1, the npm `latest` tag pointed at 1.208.0, and the betas were published under `beta`. From 2.0.1 on, `latest` is version 2, so a plain `npm install @fluffy-spoon/substitute` (or a `"latest"` / `"*"` version range) now installs 2.x with the breaking changes below. A `^1` range in package.json (like `^1.208.0`) keeps you on 1.x. To stay on version 1 explicitly: + +```sh +npm install @fluffy-spoon/substitute@1 --save-dev +``` + +Prereleases are still published under the `beta` tag. + +## Requirements +*Applies to: everyone.* + +* Node.js 10 or newer for CommonJS, and 12.17 or newer for the native ES module entry point. +* TypeScript 3.6 or newer. The 1.x README said TypeScript 3.0; 2.0.0-beta.4 needed 3.8. +* `strict` mode, including `strictNullChecks`, is supported. The 1.x README told you to turn `strictNullChecks` off; that is no longer needed. + +## Removed APIs +### `Substitute.disableFor` +*Applies to: 1.x and the betas.* + +`Substitute.disableFor(sub)` returned a view of the substitute in which `received`, `didNotReceive` and `mimick` were not the library's methods. It was used to call a member of your own with one of these names, for example in a test that wants to record such a call before checking it. It is gone, because it is no longer needed: + +* A member of your own called `received` or `didNotReceive` is called as usual: `fake.received(1337)`. +* The library's checks have symbols that never conflict: `fake[received]()`, `fake[didNotReceive]()`. +* `mimick` is never the library's method any more (see below), so a member called `mimick` is an ordinary member. + +Before: + + +```typescript +const fake = Substitute.for() +Substitute.disableFor(fake).received(1337) +fake.received().received(1337) +``` + +After: + +```typescript +import { Substitute, received } from '@fluffy-spoon/substitute' + +class Example { + received(someNumber: number) { + return someNumber + } +} + +const fake = Substitute.for() +fake.received(1337) // the class' own method, like the code under test would call it +fake[received]().received(1337) + +// configuring the member works, too +fake.received(1).returns(2) +console.log(fake.received(1)) // prints 2 +``` + +In TypeScript, `fake.received()` is the class' own method here, so the string check is not offered for this type at all. In JavaScript, the library decides by how the name is used; see [Names that conflict with the library](README.md#names-that-conflict-with-the-library). If the code under test reads a member of what its own `received(...)` returns, configure that call with `.returns(...)`, so it returns your value instead of a substitute. + +### `clearSubstitute` and `ClearType` +*Applies to: the betas.* + +`sub.clearSubstitute(clearType?)` and the `ClearType` export were removed. What replaces them: + +| Before | After | +|---|---| +| `sub.clearSubstitute(ClearType.receivedCalls)` or `sub.clearSubstitute('receivedCalls')` | `sub[clearReceivedCalls]()` | +| `sub.clearSubstitute(ClearType.substituteValues)` or `sub.clearSubstitute('substituteValues')` | create a new substitute | +| `sub.clearSubstitute()` / `sub.clearSubstitute(ClearType.all)` | create a new substitute | + +`[clearReceivedCalls]()` forgets the received calls of the substitute and its auto-substitutes, and keeps every setup. There is no way to remove setups from a substitute: create the substitute in each test (for example in a `beforeEach` hook) instead of clearing a shared one. + +Before: + + +```typescript +import { Substitute, ClearType } from '@fluffy-spoon/substitute' + +calculator.add(1, 2) +calculator.clearSubstitute(ClearType.receivedCalls) +calculator.didNotReceive().add(1, 2) +``` + +After: + + +```typescript +import { clearReceivedCalls } from '@fluffy-spoon/substitute' + +calculator.add(1, 2).returns(3) +calculator.add(1, 2) +calculator[clearReceivedCalls]() +calculator.didNotReceive().add(1, 2) +console.log(calculator.add(1, 2)) // prints 3 +``` + +TypeScript reports the old calls as errors. **In JavaScript they fail silently:** `sub.clearSubstitute()` and `sub.clearReceivedCalls()` are now ordinary member calls that clear nothing, and `ClearType` is `undefined`. Search your tests for `clearSubstitute`, `clearReceivedCalls(` and `ClearType`. + +### The string `mimick(instance)` +*Applies to: 1.x and the betas.* + +`sub.mimick(instance)` was typed, but did nothing in 1.x and threw "Mimick is not implemented yet" in 2.0.0-beta.4. It is replaced by the symbol `sub[mimick](instance)`, which works: everything that is not configured is handed to the instance, and the calls are still recorded. The string `mimick` is now an ordinary member. + +Before: + + +```typescript +calculator.mimick(new RealCalculator()) +``` + +After: + + +```typescript +import { mimick } from '@fluffy-spoon/substitute' + +class RealCalculator implements Calculator { + isEnabled = true + add(a: number, b: number) { return a + b } + subtract(a: number, b: number) { return a - b } +} + +calculator[mimick](new RealCalculator()) +console.log(calculator.add(2, 3)) // prints 5 +calculator.received().add(2, 3) +``` + +To configure members of a mimicked substitute, use [`sub[configure]()`](README.md#re-configuring-a-call-configure). + +## Names that conflict with the library: the symbol API +*Applies to: 1.x and the betas (the symbols are new in 2.0.1).* + +The package exports symbols for its methods: `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. They always mean the library's method, so they are the way to handle members with the same names as the library's methods. + +* `clearReceivedCalls`, `mimick` and `configure` exist **only** as symbols. +* In TypeScript, if a type has a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, its substitute offers only `sub[received]()` and `sub[didNotReceive]()`. Code that used the string forms on such a type no longer compiles. +* `.returns()`, `.throws()`, `.mimicks()`, `.resolves()` and `.rejects()` are not offered on a value that has its own member with that name. Use `[returns]` and so on there. (In 2.0.0-beta.4, a member called `returns` on the substituted interface removed `.returns()` from all of its properties; that is fixed.) + + +```typescript +import { received, didNotReceive, returns } from '@fluffy-spoon/substitute' + +calculator.add(1, 2)[returns](3) +console.log(calculator.add(1, 2)) // prints 3 +calculator[received](1).add(1, 2) +calculator[didNotReceive]().subtract(Arg.all()) +``` + +## Behaviour changes +### Sequences repeat the last value +*Applies to: 1.x.* + +`returns(a, b, c)` returns `a`, `b` and `c`, and then keeps returning `c`. In 1.x, the calls after the sequence returned `undefined`. The same applies to `throws`, `resolves`, `rejects` and `mimicks` with several values. + + +```typescript +calculator.add(1, 2).returns(3, 7, 9) +console.log(calculator.add(1, 2)) // prints 3 +console.log(calculator.add(1, 2)) // prints 7 +console.log(calculator.add(1, 2)) // prints 9 +console.log(calculator.add(1, 2)) // prints 9 +``` + +If a test relied on `undefined` after the sequence, add it to the sequence where the type allows it (`returns(3, 7, 9, undefined)`). + +### Auto-substitutes and nested checks +*Applies to: 1.x and the betas.* + +A member or call that is not configured returns an auto-substitute. (The 1.x README said such calls return `undefined`; they returned a proxy in every version.) What is new: + +* The same member, or the same method with equal arguments, always returns the same auto-substitute, so nested setups work: `app.getCalculator().add(1, 2).returns(99)`. +* **Nested checks really check.** In 1.x and the betas, `app.logger.received().info('hi')` passed whatever had been called. Now it fails when `info('hi')` was not called on `app.logger`. Tests that passed only because of this now fail. +* Setups and calls on the substitute never leak into nested members with the same name, or the other way round. + +```js +const { Substitute } = require('@fluffy-spoon/substitute') + +const app = Substitute.for() +app.logger.info('hi') + +app.logger.received().info('hi') +app.logger.received().info('bye') // throws SubstituteException +``` + +In TypeScript, nested auto-substitutes are not typed as substitutes; see the [README](README.md#auto-substitutes-and-nested-members) for the typed alternative. + +### Calls with argument matchers are setups +*Applies to: 1.x and the betas.* + +A call with an `Arg.any()`, `Arg.is()` or `Arg.all()` matcher (or their `.not` forms) is always a setup or a check. It is never recorded as a received call, and it never runs an existing setup. Before, `calculator.add(Arg.all()).returns(10)` after `calculator.add(1, 3).returns(1337)` ran the first setup, and failed with `TypeError: ... returns is not a function`. A bare `calculator.add(Arg.any(), 2)` statement was counted as a call. + + +```typescript +calculator.add(1, 3).returns(1337) +calculator.add(Arg.all()).returns(10) +console.log(calculator.add(1, 3)) // prints 1337 +console.log(calculator.add(5, 2)) // prints 10 + +calculator.subtract(Arg.any(), 2) +calculator.didNotReceive().subtract(Arg.all()) +``` + +### Match order +*Applies to: 1.x and the betas.* + +The README used to say that the first matching setup wins. Now the most specific setup wins: literal arguments, then matchers, then `Arg.all()` alone. Among setups of the same kind, the most recent one wins, so configuring the same call again overrides it. See [Match order](README.md#match-order). + + +```typescript +calculator.add(Arg.any(), Arg.any()).returns(1) +calculator.add(Arg.is(a => a > 10), Arg.any()).returns(2) +console.log(calculator.add(20, 0)) // prints 2 +console.log(calculator.add(5, 0)) // prints 1 +``` + +### Re-configuring a call +*Applies to: 1.x and the betas.* + +A call whose literal arguments match an existing setup returns the configured value, so `calculator.add(1, 2).returns(5)` after `calculator.add(1, 2).returns(4)` fails (a number has no `.returns`). Use the new `sub[configure]()` view, in which every call is a setup: + + +```typescript +import { configure } from '@fluffy-spoon/substitute' + +calculator.add(1, 2).returns(4) +calculator[configure]().add(1, 2).returns(5) +console.log(calculator.add(1, 2)) // prints 5 + +calculator.add(Arg.all()).returns(10) +calculator[configure]().add(1, 3).returns(1337) +console.log(calculator.add(1, 3)) // prints 1337 +``` + +### What counts as a call +*Applies to: 1.x and the betas.* + +* Reading a method without calling it is not a call. Before, merely reading a method (for example to register it as an event handler) satisfied `received().method(...)`. +* `.call()`, `.apply()` and `.bind()` on a method return the configured value and are recorded like a direct call. Before, `.call()` and `.apply()` returned a proxy. +* Every call through a stored or destructured reference, or a callback, is recorded. In the betas, each such call overwrote the previous one (1.x was not affected). + + +```typescript +const { add } = calculator +add(1, 1) +add(2, 2) +calculator.received(2).add(Arg.all()) + +const handler = calculator.subtract +calculator.received().subtract(Arg.all()) // throws SubstituteException +``` + +### Checks never run setups +*Applies to: the betas.* + +`received()` and `didNotReceive()` never run setups or mimicked implementations, and are never recorded. In the betas, checking a property ran its setup: it threw the configured error, used up a value of a `returns()` sequence, ran the `mimicks()` function again, or left an unhandled rejection behind. + + +```typescript +calculator.isEnabled.returns(true, false) +console.log(calculator.isEnabled) // prints true +calculator.received(1).isEnabled +console.log(calculator.isEnabled) // prints false +``` + +### `received(count)` is validated +*Applies to: 1.x and the betas.* + +The count must be a non-negative integer, or left out for "1 or more". Anything else throws a `SubstituteException` that says so. Invalid counts failed before, too, but with a different error: a plain `Error` in 2.0.0-beta.4, a call count mismatch in 1.x. `received(0)` is the same as `didNotReceive()`. + + +```typescript +calculator.received(0).add(1, 2) +calculator.received(1.5).add(1, 2) // throws SubstituteException: Expected count has to be a non-negative integer +``` + +### Matchers +*Applies to: 1.x and the betas.* + +* `Arg.all()` after other arguments matches the rest of the arguments, and the arguments before it must match. Before, it made the whole call match anything. Arguments after `Arg.all()` throw a `SubstituteException`. +* `Arg.any('object')` no longer matches `null`, and now matches substitutes. `Arg.any('function')` matches substitutes, and `Arg.any('array')` uses `Array.isArray`. +* `Arg.is()` with something other than a function throws a `TypeError` right away. A predicate that throws counts as a non-match instead of crashing the code under test. +* Substitutes passed as arguments are compared by identity, and are never compared or printed member by member. In the betas, a failed check overflowed the stack when substitutes referred to each other through their arguments. + +### Messages +*Applies to: 1.x and the betas.* + +The wording of `SubstituteException` messages changed, for example "Expected to receive 2 method calls matching add(1, 2), but received 1.", followed by the calls that were received (at most 50). Tests that compare message texts need updating. Messages contain ANSI colours only when the output is a terminal (`NO_COLOR`, `NODE_DISABLE_COLORS`, `TERM=dumb` and `FORCE_COLOR` are honoured). In the betas, messages always contained them; 1.x messages had no colours. + +`SubstituteException` is now exported from the package root: `import { SubstituteException } from '@fluffy-spoon/substitute'`. + +## Imports and packaging +*Applies to: 1.x and the betas.* + +**The ES module default import works.** Under native ES modules, `import Substitute from '@fluffy-spoon/substitute'` used to give the CommonJS module object, so `Substitute.for` was not a function. It is now the `Substitute` class. Named imports work as before, and ES modules and CommonJS share one copy of the library. + + +```js +import Substitute, { Arg } from '@fluffy-spoon/substitute' + +const calculator = Substitute.for() +calculator.add(Arg.any(), 2).returns(3) +console.log(calculator.add(1, 2)) // prints 3 +``` + +**Deep imports moved.** package.json now has an `exports` map. The public entry point is the package root; import everything from there: + +| Before | After | +|---|---| +| `@fluffy-spoon/substitute/dist/Substitute` (`Substitute`, `SubstituteOf`) | `@fluffy-spoon/substitute` | +| `@fluffy-spoon/substitute/dist/Arguments` (`Arg`) | `@fluffy-spoon/substitute` | +| `@fluffy-spoon/substitute/dist/SubstituteException` (betas), `.../dist/SubstituteBase` (1.x) | `import { SubstituteException } from '@fluffy-spoon/substitute'` | +| `@fluffy-spoon/substitute/dist/Transformations` (`ObjectSubstitute`, ...) | `SubstituteOf` from `@fluffy-spoon/substitute` | + + +```typescript +import { SubstituteOf, SubstituteException } from '@fluffy-spoon/substitute' + +const asSubstitute: SubstituteOf = calculator +try { + asSubstitute.received().add(1, 2) +} catch (error) { + console.log(error instanceof SubstituteException) // prints true +} +``` + +The compiled files now live under `dist/api`, `dist/internals` and `dist/shared`. They can still be imported as `@fluffy-spoon/substitute/dist/` (with or without `.js`), but they are not public API and can change in any release. Directory imports such as `@fluffy-spoon/substitute/dist/api` no longer resolve on Node.js versions that read `exports`. + +## TypeScript +*Applies to: 1.x and the betas.* + +The typings were reworked. Most code compiles unchanged, but: + +* The [symbol rules](#names-that-conflict-with-the-library-the-symbol-api) above: string checks are not offered on types with conflicting member names, and `mimick(instance)` is symbol only. +* The symbol API is available on every substitute, also on `SubstituteOf` for a generic `T` (in the betas, generic helpers could not call `received()`). +* A member called `then` is typed `never`: substitutes are never thenables. +* Now supported: `mimicks()` on methods that return a union (including `boolean`), optional members, named members next to an index signature, overloads without parameters, up to 8 overloads, `(...args: unknown[])` methods, and `.throws()` on methods that return `never`. +* See [Typing limitations](README.md#typing-limitations) for what TypeScript cannot express. From 8541485df993e1141a5f7e914727fd6dbf76aa9a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:39:23 +0000 Subject: [PATCH 023/106] docs: add a changelog Keep a Changelog format. The 2.0.1 entry summarises the fixes, changes, additions and removals since 2.0.0-beta.4 in user terms; the beta entries are reconstructed from the git history. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CHANGELOG.md | 105 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..53be49b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,105 @@ +# Changelog +All notable changes to `@fluffy-spoon/substitute` are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Upgrading? Read the [migration guide](MIGRATION.md). + +## [2.0.1] - Unreleased +The first stable release of version 2 (there was no 2.0.0 release). It is published as the npm `latest` version, which was 1.208.0 until now. See the [migration guide](MIGRATION.md) for upgrading from 1.x or from a beta. + +### Added +- Symbols for the library's methods, exported from the package root: `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. They always mean the library's method, so they handle members with the same names, and they work when two copies of the package are installed. +- `sub[configure]()`: a view of a substitute in which every call and property read is a setup. Use it to change a call that is already configured, or to configure a mimicked substitute. +- `sub[mimick](instance)`: hands everything that is not configured to a real instance. Calls are still recorded, and setups still win. +- `sub[clearReceivedCalls]()`: forgets the received calls of a substitute and its auto-substitutes, and keeps the setups. +- `SubstituteException` is exported from the package root, for `instanceof` checks. +- Auto-substitutes are cached, so nested setups and checks work at runtime: `app.getCalculator().add(1, 2).returns(99)` and `app.logger.received().info('hi')`. +- `Arg.all()` after other arguments matches the rest of the arguments, including none: `log('x', Arg.all())`. +- A native ES module entry point and an `exports` map, with typings for the `node16`, `nodenext` and `bundler` module resolutions. The ES module entry point shares one copy of the library with CommonJS. +- `console.log`, `util.inspect` and `String()` show a substitute's setups and received calls. +- The public typings carry documentation comments for editors. +- A [migration guide](MIGRATION.md), this changelog and [contributing guidelines](CONTRIBUTING.md). The README examples are type-checked and run in CI. + +### Changed +- When several setups match a call, the most specific one wins: literal arguments, then matchers, then `Arg.all()` alone. Among setups of the same kind, the most recent one wins, and configuring the same call again replaces it. (The README said that the first matching setup wins.) +- A call with an argument matcher (`Arg.any`, `Arg.is`, `Arg.all`, also with `.not`) is always a setup or a check. It is never recorded as a received call and never runs an existing setup. +- Reading a method without calling it is no longer a call; method checks count invocations only. +- `received(count)` throws a `SubstituteException` unless the count is a non-negative integer (or left out). `received(0)` is the same as `didNotReceive()`. +- `Arg.any('object')` matches objects, arrays and substitutes, but no longer `null`. `Arg.any('function')` matches substitutes, and `Arg.any('array')` uses `Array.isArray`. +- `Arg.is()` throws a `TypeError` right away when it is not given a function. A predicate that throws counts as a non-match, and the failure message says so. +- Failure messages say what kind of call was expected (method calls, property reads or property assignments), with the expected arguments and the path of nested substitutes. They list at most 50 received calls. They contain ANSI colours only when the output is a terminal, and honour `NO_COLOR`, `FORCE_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb`. +- Failed checks throw right away. Only a property-style check on a member that was called as a method can be reported later, on `process.nextTick` (see the README). +- TypeScript: on a type with a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, only the symbol forms `sub[received]()` and `sub[didNotReceive]()` are offered. `.returns()` and the other setup methods are offered unless the configured value has its own member with that name. +- TypeScript: a member called `then` is typed `never`, because substitutes are never thenables. +- The minimum TypeScript version is 3.6 (2.0.0-beta.4 needed 3.8). The package runs on Node.js 10 and newer with CommonJS, and 12.17 and newer as an ES module. +- Releases are published to npm with provenance: stable versions as `latest`, prereleases as `beta`. + +### Fixed +- Configuring a call whose arguments overlap an existing setup ran that setup instead. It failed with `TypeError: ... returns is not a function`, or silently configured the wrong thing. This broke the README's "Match order" and "Partial mocks" examples. +- Checking a configured property ran its setup: it threw the configured error, used up values of a `returns()` sequence, ran `mimicks()` again or left an unhandled rejection. +- Calls through a stored or destructured method reference, or a callback, were recorded only once. +- Merely reading a method (for example to register it as a callback) satisfied `received().method(...)`. +- `.call()`, `.apply()` and `.bind()` on a configured method returned a proxy instead of the configured value. +- Checks on members called `returns`, `throws`, `resolves`, `rejects` or `mimicks` passed silently. +- `received(count)` with a negative, fractional or `NaN` count passed silently. +- A setup on the substitute leaked into nested members with the same name. Nested checks were checked against the root members, and code under test that read a nested member called `received` threw. +- `Arg.all()` after other arguments ignored those arguments. +- Every call scanned all earlier calls, which made large tests slow. 10,000 calls now take well under a second. +- A failed check overflowed the stack when substitutes referred to each other through their arguments, and threw a `TypeError` with `Error.stackTraceLimit = 0`. +- An exception thrown by an `Arg.is()` predicate escaped into the code under test. +- Failure messages for methods said "property calls" and left out the expected arguments. +- The symbol API did not work across two copies of the package. +- TypeScript: `mimicks()` on methods that return a union (including `boolean`); `received()` in generic helpers over `SubstituteOf`; a member called `returns` removing `.returns()` from all properties; optional members; named members next to an index signature; overloads without parameters; methods with more than 5 overloads; `.throws()` on methods returning `never`; `(...args: unknown[])` methods; a private member called `received` turning the substitute type into `never`. +- Under native ES modules, the default import was the CommonJS module object, so `Substitute.for` was not a function. +- The package could not be loaded on Node.js versions before 14.18. +- A manual `npm publish` after `npm test` could publish a package without its entry point. `package-lock.json` had an outdated version. + +### Removed +- `Substitute.disableFor()`. Call members with conflicting names directly, and use the symbols for the library's methods. +- `sub.clearSubstitute(clearType)` and the `ClearType` export. Use `sub[clearReceivedCalls]()`, or create a new substitute to drop setups. +- The string `sub.mimick(instance)`. Use `sub[mimick](instance)`; `mimick` is now an ordinary member name. +- The 2.0.0-beta deep import paths (`dist/Substitute`, `dist/Arguments`, `dist/SubstituteException`, ...). Import from the package root. Directory deep imports (`.../dist/api`) no longer resolve on Node.js versions that read `exports`. +- The GitHub Packages publishing job, which could not publish the `@fluffy-spoon` scope. + +## [2.0.0-beta.4] - 2024-03-21 +### Changed +- Failure messages list the received calls with the place each call was made, and mark the ones that matched ([#281](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/281)). + +## [2.0.0-beta.3] - 2024-03-08 +### Added +- Members used both as a property and as a method (callable interfaces) can be configured and checked in both ways ([#248](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/248)). +- Compatibility checks with the ava, jest, mocha, node:test and vitest test runners. + +### Changed +- Tested on Node.js 18 and the current LTS versions; Node.js 10 was dropped from the test matrix ([#245](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/245)). + +## [2.0.0-beta.2] - 2022-10-09 +### Added +- The `ClearType` export, with the values for `clearSubstitute()` (`ClearType.receivedCalls`, ...). + +### Changed +- The core was simplified ([#243](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/243)). +- `strict` mode, including `strictNullChecks`, is supported; it no longer needs to be turned off ([#244](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/244)). + +### Fixed +- Typings for TypeScript versions before 4.6. + +## [2.0.0-beta.1] - 2022-06-02 +The version 2 rework ([#139](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/139)) was merged, with the same features as 2.0.0-beta.0. + +## [2.0.0-beta.0] - 2021-10-24 +### Added +- `sub.clearSubstitute(clearType)` with `ClearType` `'all'`, `'receivedCalls'` or `'substituteValues'` ([#233](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/233), [#46](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/issues/46)). + +### Changed +- The substitution logic was rewritten ([#139](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/139), [#232](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/pull/232)). +- After a sequence of values (`returns(1, 2, 3)`), the last value repeats. Version 1 returned `undefined`. + +## 1.x +Version 1 has no changelog. See the [GitHub releases](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/releases) and the [1.208.0 README](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/tree/v1.208.0#readme). + +[2.0.1]: https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/compare/v2.0.0-beta.4...v2.0.1 +[2.0.0-beta.4]: https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/compare/v2.0.0-beta.3...v2.0.0-beta.4 +[2.0.0-beta.3]: https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/compare/v2.0.0-beta.2...v2.0.0-beta.3 +[2.0.0-beta.2]: https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/compare/v2.0.0-beta.1...v2.0.0-beta.2 +[2.0.0-beta.1]: https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/compare/v2.0.0-beta.0...v2.0.0-beta.1 +[2.0.0-beta.0]: https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/compare/v1.208.0...v2.0.0-beta.0 From c6fd66deee28f950951469333dd9c212b1c03cb3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:39:41 +0000 Subject: [PATCH 024/106] test(docs): type-check and run the documentation examples `npm run test:docs` builds the package, then spec-docs/check.js extracts every typescript and js code block from README.md, MIGRATION.md and CHANGELOG.md, type-checks the TypeScript ones under strict against the built package (resolved through package.json and its exports map, like an installed copy) and runs each block in its own Node.js process. Examples state what they do in comments that the check enforces: `// prints ` must print exactly that, and `// throws ` must throw. Any other output, exception, uncaught exception or unhandled rejection fails the check. HTML comment directives share setup code between blocks (name=/uses=), mark ES modules, compile-only and skipped blocks, an expected uncaught exception, and an error message text that must match. Relative links and #anchors are checked too. spec-docs/self-test.js runs the check on fixtures/broken.md, whose blocks and links are broken on purpose, and fails unless each problem is reported. The whole run takes about 10 seconds. CI runs it in the test job. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .github/workflows/nodejs.yml | 3 + package.json | 1 + spec-docs/README.md | 49 +++ spec-docs/check.js | 612 +++++++++++++++++++++++++++++++++++ spec-docs/fixtures/broken.md | 236 ++++++++++++++ spec-docs/harness.js | 59 ++++ spec-docs/self-test.js | 64 ++++ 7 files changed, 1024 insertions(+) create mode 100644 spec-docs/README.md create mode 100644 spec-docs/check.js create mode 100644 spec-docs/fixtures/broken.md create mode 100644 spec-docs/harness.js create mode 100644 spec-docs/self-test.js diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 02f4fdf..bbb028a 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -43,6 +43,9 @@ jobs: run: npm test - name: Run the type tests run: npm run test:types --if-present + # Type-checks and runs the code examples of README.md and MIGRATION.md against the built package, and checks links. + - name: Check the code examples in the documentation + run: npm run test:docs compatibility: name: Test runner compatibility on Node ${{ matrix.node-version }} diff --git a/package.json b/package.json index 7fa65a0..d0dccf4 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "test": "npm run build:spec && ava", "test:types": "tsc -p spec-types && tsc -p spec-types/loose", "test:types:min-ts": "npm run build && node spec-types/min-ts/check.js", + "test:docs": "npm run build && node spec-docs/check.js && node spec-docs/self-test.js", "test:compat": "npm --prefix compatibility-checks test" }, "devDependencies": { diff --git a/spec-docs/README.md b/spec-docs/README.md new file mode 100644 index 0000000..ae0dc38 --- /dev/null +++ b/spec-docs/README.md @@ -0,0 +1,49 @@ +# Documentation check + +`npm run test:docs` builds the package and checks every code example in [README.md](../README.md), +[MIGRATION.md](../MIGRATION.md) and [CHANGELOG.md](../CHANGELOG.md), so the documentation cannot drift away from the +library: + +* ```` ```typescript ```` / ```` ```ts ```` blocks are type-checked under `strict` against the built package (resolved + through `package.json` like an installed copy, so the `exports` map and the published typings are what is checked), + and then run with Node.js, one process per block. +* ```` ```js ```` / ```` ```javascript ```` blocks are run with Node.js. +* Every block must have a language tag. Blocks in other languages (`sh`, `text`, ...) are not checked. +* Relative links must point to an existing file, and `#anchors` to an existing heading. + +It takes a few seconds. Then `spec-docs/self-test.js` runs the check on [fixtures/broken.md](fixtures/broken.md), whose +code blocks and links are broken on purpose, and fails if the check does not report each of them. + +## Writing examples +Promise what the code does in a comment, and the check holds the example to it: + +```ts +console.log(calculator.add(1, 2)) // prints 3 +calculator.received(2).add(1, 2) // throws SubstituteException +calculator.received(-1).add(1, 2) // throws SubstituteException: Expected count has to be a non-negative integer +``` + +* `console.log(...) // prints `: the line must print exactly `` (the `util.format` output, as console.log + prints it), exactly once. It also works inside a callback: `.then(value => console.log(value)) // prints 4`. +* ` // throws ` or `// throws : `: the statement must throw an error with that + `name`, whose message contains ``. It must be a complete statement on one line. +* A `console.log` without `// prints` fails the check, and so does any exception, uncaught exception, unhandled rejection + or non-zero exit code that the example does not promise. + +Blocks can be marked with an HTML comment right before the fence (several directives are separated by spaces): + +| Directive | Meaning | +|---|---| +| `` | Other blocks can use this block's code. Such a block must not contain `// prints` or `// throws`. | +| `` | Runs the named blocks' code first (and the code they use in turn), in the same module. Every block gets its own fresh copy. Several names are separated by commas. | +| `` | Only type-checked, for example code that needs a test runner. | +| `` | An ES module (`.mts` / `.mjs`) instead of CommonJS. | +| `` | The block must end with that uncaught exception (an assertion reported on `process.nextTick`). | +| `` | On a ```` ```text ```` block: must equal `: ` of the error thrown by the last `// throws` line of the checked block before it. Lines starting with `called at` match any stack frame. | +| `` | Not checked at all: code for an old version, or deliberately partial code. | + +Use `// @ts-expect-error` to show code that must not compile. To debug a failure, keep the generated files: + +```sh +npm run build && node spec-docs/check.js --keep README.md +``` diff --git a/spec-docs/check.js b/spec-docs/check.js new file mode 100644 index 0000000..c0ef21e --- /dev/null +++ b/spec-docs/check.js @@ -0,0 +1,612 @@ +#!/usr/bin/env node +'use strict' +// The documentation check (`npm run test:docs`). It keeps README.md, MIGRATION.md and CHANGELOG.md honest: +// +// - Every ```typescript / ```ts block is type-checked under `strict` against the BUILT package (dist/, resolved through +// package.json like an installed copy of @fluffy-spoon/substitute), then run with Node.js. +// - Every ```javascript / ```js block is run with Node.js. +// - `console.log(...) // prints ` must print exactly (util.format output, like console.log). +// - ` // throws ` and ` // throws : ` must throw that error (by its +// `name`; the message must contain ). Both must be complete single-line statements. +// - Any other console.log, an unexpected exception, an uncaught exception or an unhandled rejection fails the check. +// - Relative links must point to an existing file, and #anchors to an existing heading. +// +// A block can be marked with an HTML comment on the lines before its fence: +// skip not checked at all (code for old versions, deliberately partial code) +// compile-only type-checked but not run (e.g. code that needs a test runner) +// name= lets other blocks use this block's code +// uses=[,] the named blocks' code (and the code they use) runs first, in the same module; each block +// gets a fresh copy +// esm an ES module (.mts / .mjs) instead of CommonJS +// uncaught= the block must end with an uncaught (an assertion reported on process.nextTick) +// A ```text block marked must equal ": " of the error thrown by the +// last `// throws` line of the preceding checked block (lines starting with "called at" match any stack frame). +// +// Usage: node spec-docs/check.js [--keep] [file.md ...] (default: README.md MIGRATION.md CHANGELOG.md; build first) +// See spec-docs/README.md for examples. +const fs = require('fs') +const os = require('os') +const path = require('path') +const { spawn } = require('child_process') + +const root = path.resolve(__dirname, '..') +const defaultFiles = ['README.md', 'MIGRATION.md', 'CHANGELOG.md'] +const checkedLanguages = { typescript: 'ts', ts: 'ts', javascript: 'js', js: 'js' } +const knownDirectives = new Set(['skip', 'compile-only', 'name', 'uses', 'esm', 'uncaught', 'error-message']) +const snippetTimeout = 20 * 1000 + +// --------------------------------------------------------------------------------------------------------------------- +// Markdown + +const directivePattern = /^\s*\s*$/ +const commentPattern = /^\s*\s*$/ +const fenceOpenPattern = /^(\s*)(`{3,}|~{3,})(.*)$/ + +const parseDirectives = (text, problems, location) => { + const directives = {} + const tokens = text.trim().split(/\s+/).filter(Boolean) + for (let index = 0; index < tokens.length; index++) { + const token = tokens[index] + const [key, ...rest] = token.split('=') + const value = rest.join('=') + if (!knownDirectives.has(key)) { + problems.push({ ...location, message: `unknown docs-check directive "${token}"` }) + continue + } + if (key === 'skip') { + directives.skip = tokens.slice(index + 1).join(' ') || 'no reason given' + break + } + if (key === 'compile-only') directives.compileOnly = true + else if (key === 'esm') directives.esm = true + else if (key === 'error-message') directives.errorMessage = true + else if (!value) problems.push({ ...location, message: `docs-check directive "${key}" needs a value (${key}=...)` }) + else if (key === 'name') directives.name = value + else if (key === 'uses') directives.uses = value.split(',').filter(Boolean) + else if (key === 'uncaught') directives.uncaught = value + } + return directives +} + +/** Splits a Markdown file into fenced code blocks, with the HTML comments directly before each fence. */ +const parseMarkdown = (file, text) => { + const lines = text.split(/\r?\n/) + const blocks = [] + const problems = [] + let pending = [] + for (let index = 0; index < lines.length; index++) { + const line = lines[index] + const open = fenceOpenPattern.exec(line) + if (open) { + const [, indent, fence, info] = open + const language = info.trim().split(/\s+/)[0] || '' + const fenceLine = index + 1 + const code = [] + let closed = false + for (index++; index < lines.length; index++) { + const close = /^\s*(`{3,}|~{3,})\s*$/.exec(lines[index]) + if (close && close[1][0] === fence[0] && close[1].length >= fence.length) { + closed = true + break + } + const content = lines[index] + const strip = Math.min(indent.length, content.length - content.trimStart().length) + code.push(content.slice(strip)) + } + const location = { file, line: fenceLine } + if (!closed) problems.push({ ...location, message: 'code block is not closed' }) + const directives = {} + const comments = [] + for (const comment of pending) { + comments.push(comment.text) + if (comment.directives) Object.assign(directives, parseDirectives(comment.directives, problems, location)) + } + pending = [] + blocks.push({ file, fenceLine, firstLine: fenceLine + 1, language, code, directives, comments }) + continue + } + const directive = directivePattern.exec(line) + const comment = commentPattern.exec(line) + if (comment) { + pending.push({ text: comment[1].trim(), line: index + 1, directives: directive ? directive[1] : undefined }) + } else if (line.trim() !== '') { + for (const comment of pending.filter(c => c.directives !== undefined)) { + problems.push({ file, line: comment.line, message: 'docs-check directive is not followed by a code block' }) + } + pending = [] + } + } + for (const comment of pending.filter(c => c.directives !== undefined)) { + problems.push({ file, line: comment.line, message: 'docs-check directive is not followed by a code block' }) + } + return { blocks, problems } +} + +// --------------------------------------------------------------------------------------------------------------------- +// Links: relative links must point to an existing file, and #anchors to an existing heading (GitHub's anchor rules). + +/** The lines of a Markdown file outside of fenced code blocks, with their line numbers. */ +const proseLines = text => { + const result = [] + let fence + text.split(/\r?\n/).forEach((line, index) => { + const marker = /^\s*(`{3,}|~{3,})/.exec(line) + if (fence) { + if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && line.trim() === marker[1]) fence = undefined + } else if (marker) { + fence = marker[1] + } else { + result.push({ line, number: index + 1 }) + } + }) + return result +} + +const headingAnchors = text => { + const counts = new Map() + const anchors = new Set() + for (const { line } of proseLines(text)) { + const heading = /^#{1,6}\s+(.*?)\s*#*\s*$/.exec(line) + if (!heading) continue + const slug = heading[1] + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/<[^>]*>/g, '') + .toLowerCase() + .replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '') + .replace(/ /g, '-') + const count = counts.get(slug) || 0 + counts.set(slug, count + 1) + anchors.add(count === 0 ? slug : `${slug}-${count}`) + } + return anchors +} + +const checkLinks = (file, text) => { + const problems = [] + const anchorsOf = new Map() + const anchors = target => { + if (!anchorsOf.has(target)) anchorsOf.set(target, headingAnchors(fs.readFileSync(target, 'utf8'))) + return anchorsOf.get(target) + } + for (const { line, number } of proseLines(text)) { + const withoutCode = line.replace(/`+[^`]*`+/g, '') + for (const [, target] of withoutCode.matchAll(/\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)) { + if (/^[a-z][a-z+.-]*:/i.test(target)) continue + const [pathPart, anchor] = target.split('#') + const targetFile = pathPart ? path.resolve(root, path.dirname(file), pathPart) : path.resolve(root, file) + const location = { file, line: number } + if (!fs.existsSync(targetFile)) { + problems.push({ ...location, message: `broken link ${target}: ${path.relative(root, targetFile)} does not exist` }) + } else if (anchor !== undefined && targetFile.endsWith('.md') && !anchors(targetFile).has(anchor)) { + problems.push({ ...location, message: `broken link ${target}: ${path.relative(root, targetFile)} has no heading with the anchor #${anchor}` }) + } + } + } + return problems +} + +// --------------------------------------------------------------------------------------------------------------------- +// Snippets + +const printsPattern = /^(.*?)\s*\/\/ prints (.*?)\s*$/ +const throwsPattern = /^(\s*)(.*?);?\s*\/\/ throws ([A-Za-z_$][\w$]*)(?::\s*(.*?))?\s*$/ + +/** Rewrites the `// prints` and `// throws` lines of a block and collects what they promise. Keeps the line count. */ +const instrument = (block, problems) => { + const expectations = [] + const lines = block.code.map((line, offset) => { + const markdownLine = block.firstLine + offset + const location = { file: block.file, line: markdownLine } + const prints = printsPattern.exec(line) + if (prints) { + const [, code, text] = prints + if (!code.includes('console.log(')) { + problems.push({ ...location, message: '"// prints" needs a console.log(...) call on the same line' }) + return line + } + expectations.push({ kind: 'prints', line: markdownLine, text }) + return code.replace('console.log(', `__docs.print(${markdownLine}, `) + } + const throws = throwsPattern.exec(line) + if (throws) { + const [, indent, code, name, message] = throws + expectations.push({ kind: 'throws', line: markdownLine, name, message }) + return `${indent}__docs.throws(${markdownLine}, () => { ${code} })` + } + if (line.includes('console.log(')) { + problems.push({ ...location, message: 'console.log(...) without a "// prints " comment' }) + } + return line + }) + return { lines, expectations } +} + +const slug = file => path.basename(file).replace(/\.md$/i, '').replace(/[^\w]+/g, '-').toLowerCase() + +const buildSnippets = parsed => { + const problems = [] + const named = new Map() + const snippets = [] + const messageChecks = [] + for (const { blocks } of parsed) { + let previous + for (const block of blocks) { + const location = { file: block.file, line: block.fenceLine } + const kind = checkedLanguages[block.language] + const { directives } = block + if (block.language === '') { + problems.push({ ...location, message: 'code block without a language tag (use ```typescript, ```js, ```sh, ```text, ...)' }) + continue + } + if (directives.errorMessage) { + if (block.language !== 'text') problems.push({ ...location, message: 'error-message is only allowed on ```text blocks' }) + else if (!previous) problems.push({ ...location, message: 'error-message block has no checked code block before it' }) + else messageChecks.push({ block, snippet: previous }) + continue + } + if (!kind) { + if (Object.keys(directives).length > 0 && !directives.skip) { + problems.push({ ...location, message: `docs-check directives on a \`\`\`${block.language} block, which is not checked` }) + } + continue + } + if (directives.skip) continue + const snippetProblems = [] + const { lines, expectations } = instrument(block, snippetProblems) + if (directives.compileOnly && expectations.length > 0) { + snippetProblems.push({ ...location, message: '"// prints" and "// throws" cannot be checked in a compile-only block' }) + } + if (kind === 'js' && directives.compileOnly) { + snippetProblems.push({ ...location, message: 'compile-only is only allowed on TypeScript blocks' }) + } + const extension = kind === 'ts' ? (directives.esm ? '.mts' : '.ts') : (directives.esm ? '.mjs' : '.js') + const snippet = { + id: `${slug(block.file)}-${String(block.fenceLine).padStart(4, '0')}`, + block, + kind, + extension, + lines, + expectations, + problems: snippetProblems, + directives + } + if (directives.name) { + if (named.has(directives.name)) problems.push({ ...location, message: `there is already a block named "${directives.name}"` }) + named.set(directives.name, snippet) + } + snippets.push(snippet) + previous = snippet + } + } + // The blocks a snippet uses, transitively and in order, each once. + const usedBlocks = (snippet, location, problems, path = []) => { + const result = [] + for (const name of snippet.directives.uses || []) { + const used = named.get(name) + if (!used) { + problems.push({ ...location, message: `uses=${name}: there is no block named "${name}"` }) + continue + } + if (used === snippet || path.includes(used)) { + problems.push({ ...location, message: `uses=${name}: blocks cannot use each other in a cycle` }) + continue + } + if (used.kind !== snippet.kind) problems.push({ ...location, message: `uses=${name}: a ${snippet.kind} block cannot use a ${used.kind} block` }) + if (used.expectations.length > 0) problems.push({ ...location, message: `uses=${name}: a block that other blocks use must not contain "// prints" or "// throws"` }) + for (const block of [...usedBlocks(used, location, problems, [...path, snippet]), used]) { + if (!result.includes(block)) result.push(block) + } + } + return result + } + for (const snippet of snippets) { + const location = { file: snippet.block.file, line: snippet.block.fenceLine } + snippet.source = [] + snippet.lineMap = [] + for (const used of usedBlocks(snippet, location, snippet.problems)) { + used.lines.forEach((line, offset) => { + snippet.source.push(line) + snippet.lineMap.push({ file: used.block.file, line: used.block.firstLine + offset }) + }) + } + snippet.lines.forEach((line, offset) => { + snippet.source.push(line) + snippet.lineMap.push({ file: snippet.block.file, line: snippet.block.firstLine + offset }) + }) + } + return { snippets, messageChecks, problems } +} + +// --------------------------------------------------------------------------------------------------------------------- +// Type-checking and running + +const globalsDeclaration = [ + '// Generated by spec-docs/check.js: the helpers that the `// prints` and `// throws` lines are rewritten to.', + 'declare const __docs: {', + ' print(line: number, ...values: unknown[]): void', + ' throws(line: number, statement: () => unknown): void', + '}', + '' +].join('\n') + +const prepareWorkDirectory = () => { + const work = fs.mkdtempSync(path.join(os.tmpdir(), 'substitute-docs-')) + fs.mkdirSync(path.join(work, 'src')) + fs.mkdirSync(path.join(work, 'out')) + const modules = path.join(work, 'node_modules') + fs.mkdirSync(path.join(modules, '@fluffy-spoon'), { recursive: true }) + // The package itself, resolved through its package.json (exports map, types) like an installed copy. + fs.symlinkSync(root, path.join(modules, '@fluffy-spoon', 'substitute'), 'junction') + // Test runners that examples may import (compile-only examples). + for (const name of ['ava']) { + const target = path.join(root, 'node_modules', name) + if (fs.existsSync(target)) fs.symlinkSync(target, path.join(modules, name), 'junction') + } + fs.writeFileSync(path.join(work, 'package.json'), JSON.stringify({ name: 'docs-check', private: true, type: 'commonjs' })) + return work +} + +const typeCheckAndEmit = (work, snippets) => { + const ts = require('typescript') + const sourceDirectory = path.join(work, 'src') + const outDirectory = path.join(work, 'out') + const byFile = new Map() + const rootNames = [path.join(sourceDirectory, 'docs-check-globals.d.ts')] + fs.writeFileSync(rootNames[0], globalsDeclaration) + for (const snippet of snippets.filter(s => s.kind === 'ts')) { + const file = path.join(sourceDirectory, snippet.id + snippet.extension) + fs.writeFileSync(file, snippet.source.join('\n') + '\n') + rootNames.push(file) + byFile.set(path.normalize(file), snippet) + snippet.sourceFile = file + snippet.outputFile = path.join(outDirectory, snippet.id + (snippet.extension === '.mts' ? '.mjs' : '.js')) + } + const options = { + strict: true, + target: ts.ScriptTarget.ES2019, + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + moduleDetection: ts.ModuleDetectionKind.Force, + esModuleInterop: true, + types: ['node'], + typeRoots: [path.join(root, 'node_modules', '@types')], + rootDir: sourceDirectory, + outDir: outDirectory, + inlineSourceMap: true, + newLine: ts.NewLineKind.LineFeed, + skipLibCheck: false + } + const program = ts.createProgram({ rootNames, options }) + const general = [] + for (const diagnostic of ts.getPreEmitDiagnostics(program)) { + const text = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n') + const snippet = diagnostic.file && byFile.get(path.normalize(diagnostic.file.fileName)) + if (snippet && diagnostic.start !== undefined) { + const { line } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start) + const mapped = snippet.lineMap[line] || { file: snippet.block.file, line: snippet.block.fenceLine } + snippet.problems.push({ ...mapped, message: `error TS${diagnostic.code}: ${text}` }) + snippet.typeErrors = true + } else { + const where = diagnostic.file ? path.relative(root, diagnostic.file.fileName) : 'TypeScript' + general.push({ file: where, line: 0, message: `error TS${diagnostic.code}: ${text}` }) + } + } + program.emit() + return general +} + +const childEnvironment = () => { + const environment = { ...process.env, NO_COLOR: '1' } + for (const name of Object.keys(environment)) { + if (name === 'FORCE_COLOR' || name.startsWith('NODE_TEST_') || name.startsWith('AVA_')) delete environment[name] + } + return environment +} + +const runSnippet = (work, snippet) => new Promise(resolve => { + const resultFile = path.join(work, `${snippet.id}.result.json`) + const child = spawn(process.execPath, ['--enable-source-maps', path.join(__dirname, 'harness.js'), snippet.outputFile, resultFile], { + cwd: work, + env: childEnvironment(), + stdio: ['ignore', 'pipe', 'pipe'] + }) + let output = '' + child.stdout.on('data', data => { output += data }) + child.stderr.on('data', data => { output += data }) + const timer = setTimeout(() => child.kill('SIGKILL'), snippetTimeout) + child.on('close', (code, signal) => { + clearTimeout(timer) + let result + try { + result = JSON.parse(fs.readFileSync(resultFile, 'utf8')) + } catch (_) { + result = undefined + } + resolve({ code, signal, output, result }) + }) +}) + +const runAll = async (work, snippets) => { + const queue = snippets.slice() + const workers = Math.max(2, Math.min(8, os.cpus().length)) + const runWorker = async () => { + for (let snippet = queue.shift(); snippet; snippet = queue.shift()) { + snippet.run = await runSnippet(work, snippet) + } + } + await Promise.all(Array.from({ length: workers }, runWorker)) +} + +// --------------------------------------------------------------------------------------------------------------------- +// Evaluation + +/** Replaces positions in the generated snippet files with Markdown positions. */ +const mapStack = (snippet, text) => { + if (!text) return '' + const files = [snippet.sourceFile, snippet.outputFile].filter(Boolean) + let mapped = text + for (const file of files) { + const escaped = file.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + mapped = mapped.replace(new RegExp(`(?:file://)?${escaped}:(\\d+)(?::\\d+)?`, 'g'), (match, line) => { + const location = snippet.lineMap[Number(line) - 1] + return location ? `${location.file}:${location.line}` : match + }) + } + return mapped +} + +const quote = text => JSON.stringify(text) +const describeError = (snippet, error) => { + const message = mapStack(snippet, `${error.name}: ${error.message}`) + // The first lines of a stack repeat the message; show the frames after it. + const frames = mapStack(snippet, error.stack || '').split('\n').filter(line => /^\s+at /.test(line)).slice(0, 5) + return [message, ...frames].join('\n') +} + +const evaluateSnippet = snippet => { + const { run, block, directives } = snippet + const location = { file: block.file, line: block.fenceLine } + const problems = snippet.problems + if (!run.result) { + const reason = run.signal ? `was killed (${run.signal}, timeout ${snippetTimeout / 1000} s)` : `exited with code ${run.code}` + problems.push({ ...location, message: `the snippet ${reason} before reporting a result\n${mapStack(snippet, run.output)}` }) + return + } + const { prints, throws, uncaught, error } = run.result + if (error) problems.push({ ...location, message: `the snippet threw ${describeError(snippet, error)}` }) + for (const expectation of snippet.expectations) { + const at = { file: block.file, line: expectation.line } + if (expectation.kind === 'prints') { + const printed = prints.filter(p => p.line === expectation.line) + if (printed.length === 0 && !error) problems.push({ ...at, message: `expected to print ${quote(expectation.text)}, but the line printed nothing` }) + else if (printed.length > 1) problems.push({ ...at, message: `expected to print once, but printed ${printed.length} times: ${printed.map(p => quote(p.text)).join(', ')}` }) + else if (printed.length === 1 && printed[0].text !== expectation.text) { + problems.push({ ...at, message: `expected to print ${quote(expectation.text)}, but printed ${quote(printed[0].text)}` }) + } + } else { + const records = throws.filter(t => t.line === expectation.line) + const expected = expectation.name + (expectation.message ? `: ${expectation.message}` : '') + if (records.length === 0 && !error) problems.push({ ...at, message: `expected to throw ${expected}, but the line did not run` }) + for (const record of records) { + if (!record.threw) problems.push({ ...at, message: `expected to throw ${expected}, but it did not throw` }) + else if (record.name !== expectation.name || (expectation.message && !record.message.includes(expectation.message))) { + problems.push({ ...at, message: `expected to throw ${expected}, but it threw ${record.name}: ${record.message}` }) + } + } + } + } + const expectedUncaught = directives.uncaught + for (const failure of uncaught) { + if (expectedUncaught && failure.name === expectedUncaught && failure.kind === 'uncaught exception') continue + problems.push({ ...location, message: `${failure.kind}: ${describeError(snippet, failure)}` }) + } + if (expectedUncaught && !uncaught.some(f => f.name === expectedUncaught && f.kind === 'uncaught exception')) { + problems.push({ ...location, message: `expected an uncaught ${expectedUncaught} (uncaught=${expectedUncaught}), but there was none` }) + } + if (run.code !== 0 && problems.length === 0) { + problems.push({ ...location, message: `the snippet exited with code ${run.code}\n${mapStack(snippet, run.output)}` }) + } +} + +const normalizeMessage = text => { + const lines = text.split(/\r?\n/).map(line => line.trimEnd().replace(/^(\s*called at ).*$/, '$1…')) + while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop() + return lines.join('\n') +} + +const evaluateMessageCheck = ({ block, snippet }, problems) => { + const location = { file: block.file, line: block.fenceLine } + const throwsLines = snippet.expectations.filter(e => e.kind === 'throws') + if (throwsLines.length === 0) { + problems.push({ ...location, message: 'error-message block: the code block before it has no "// throws" line' }) + return + } + if (!snippet.run || !snippet.run.result) { + problems.push({ ...location, message: 'error-message block: the code block before it did not run' }) + return + } + const last = throwsLines[throwsLines.length - 1] + const record = snippet.run.result.throws.find(t => t.line === last.line && t.threw) + if (!record) { + problems.push({ ...location, message: `error-message block: line ${last.line} did not throw` }) + return + } + const expected = normalizeMessage(block.code.join('\n')) + const actual = normalizeMessage(`${record.name}: ${record.message}`) + if (expected !== actual) { + problems.push({ ...location, message: `error-message block does not match the message thrown on line ${last.line}.\n--- expected (README)\n${expected}\n--- actual\n${actual}` }) + } +} + +// --------------------------------------------------------------------------------------------------------------------- + +/** + * Checks the code blocks of the given Markdown files. Returns every problem, and per code block the problems that + * belong to it (used by spec-docs/self-test.js). + */ +const checkDocs = async ({ files = defaultFiles, keep = false } = {}) => { + const absolute = files.map(file => path.resolve(root, file)) + const texts = absolute.map(file => ({ file: path.relative(root, file), text: fs.readFileSync(file, 'utf8') })) + const parsed = texts.map(({ file, text }) => parseMarkdown(file, text)) + const { snippets, messageChecks, problems: buildProblems } = buildSnippets(parsed) + const problems = [...parsed.flatMap(p => p.problems), ...buildProblems, ...texts.flatMap(({ file, text }) => checkLinks(file, text))] + + if (!fs.existsSync(path.join(root, 'dist', 'index.js')) || !fs.existsSync(path.join(root, 'dist', 'index.mjs'))) { + problems.push({ file: 'dist', line: 0, message: 'dist/ is not built: run `npm run build` first (or `npm run test:docs`)' }) + return { problems, snippets, blocks: parsed.flatMap(p => p.blocks), files: texts.map(t => t.file) } + } + + const work = prepareWorkDirectory() + try { + problems.push(...typeCheckAndEmit(work, snippets)) + for (const snippet of snippets.filter(s => s.kind === 'js')) { + snippet.outputFile = path.join(work, 'out', snippet.id + snippet.extension) + fs.writeFileSync(snippet.outputFile, snippet.source.join('\n') + '\n') + } + const runnable = snippets.filter(s => !s.directives.compileOnly && !s.typeErrors && s.problems.length === 0) + await runAll(work, runnable) + for (const snippet of runnable) evaluateSnippet(snippet) + for (const check of messageChecks) evaluateMessageCheck(check, problems) + } finally { + if (keep) console.log(`docs-check: kept the generated files in ${work}`) + else fs.rmSync(work, { recursive: true, force: true }) + } + for (const snippet of snippets) problems.push(...snippet.problems) + return { + problems, + snippets, + blocks: parsed.flatMap(p => p.blocks), + files: texts.map(t => t.file), + runnableCount: snippets.filter(s => s.run).length + } +} + +const formatProblem = problem => `${problem.file}:${problem.line}: ${problem.message.replace(/\n/g, '\n ')}` + +const main = async () => { + const args = process.argv.slice(2) + const keep = args.includes('--keep') + const files = args.filter(arg => !arg.startsWith('--')) + const started = Date.now() + const result = await checkDocs({ files: files.length > 0 ? files : defaultFiles, keep }) + const { problems, snippets, blocks, runnableCount } = result + const unique = [...new Map(problems.map(p => [formatProblem(p), p])).values()] + .sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line) + const checkedFiles = result.files.join(', ') + const skipped = blocks.filter(b => checkedLanguages[b.language] && b.directives.skip).length + const compileOnly = snippets.filter(s => s.directives.compileOnly).length + const seconds = ((Date.now() - started) / 1000).toFixed(1) + for (const problem of unique) console.error(formatProblem(problem)) + console.log(`docs-check: ${snippets.length} code blocks in ${checkedFiles}: ${runnableCount || 0} type-checked and run, ` + + `${compileOnly} only type-checked, ${skipped} skipped; ${unique.length} problem(s) in ${seconds} s`) + process.exitCode = unique.length > 0 ? 1 : 0 +} + +if (require.main === module) { + main().catch(error => { + console.error(error) + process.exitCode = 1 + }) +} + +module.exports = { checkDocs, parseMarkdown, formatProblem } diff --git a/spec-docs/fixtures/broken.md b/spec-docs/fixtures/broken.md new file mode 100644 index 0000000..527933a --- /dev/null +++ b/spec-docs/fixtures/broken.md @@ -0,0 +1,236 @@ +# Fixture for spec-docs/self-test.js + +Every code block below is broken on purpose. `` says which problem the docs check must +report for the block (a substring of the message); `expect=pass` marks the control blocks that must pass. + + + +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' + +interface Calculator { + add(a: number, b: number): number + isEnabled: boolean +} + +const calculator = Substitute.for() +``` + + + +```typescript +calculator.add(1, 2).returns(3) +console.log(calculator.add(1, 2)) // prints 3 +calculator.received(1).add(1, 2) +calculator.received(2).add(1, 2) // throws SubstituteException: Expected to receive 2 method calls +``` + +A type error: + + + +```typescript +calculator.add('1', 2).returns(3) +``` + +The README text and the runtime disagree about a printed value: + + + +```typescript +calculator.add(1, 2).returns(3) +console.log(calculator.add(1, 2)) // prints 4 +``` + +The README promises an exception that does not happen: + + + +```typescript +calculator.add(1, 2) +calculator.received(1).add(1, 2) // throws SubstituteException +``` + +The wrong exception: + + + +```typescript +calculator.add(1, 2).throws(new Error('boom')) +calculator.add(1, 2) // throws SubstituteException +``` + +An exception the README does not mention: + + + +```typescript +calculator.received().add(1, 2) +``` + +A line that never runs: + + + +```typescript +if (calculator.isEnabled === true) { + console.log('never') // prints never +} +``` + +Output that is not checked: + + + +```typescript +console.log(calculator.add(1, 2)) +``` + +An assertion that is reported later, but the README does not say so: + + + +```typescript +calculator.add(1, 2) +calculator.add(1, 2) +calculator.add(1, 2) +calculator.received(2).add +``` + +The README says a failure is reported later, but it is not: + + + +```typescript +calculator.add(1, 2) +calculator.received(1).add(1, 2) +``` + +An unhandled rejection: + + +```typescript +Promise.reject(new Error('nobody waits for this')) +``` + +Top-level await in a CommonJS module: + + +```typescript +await Promise.resolve(1) +``` + +A failing node:test test: + + +```typescript +import { test } from 'node:test' +import * as assert from 'node:assert' + +test('fails', () => { + assert.strictEqual(1, 2) +}) +``` + +A block that uses a block that does not exist: + + + +```typescript +calculator.add(1, 2) +``` + +An unknown directive: + + + +```typescript +const value = 1 +``` + +A code block without a language: + + +``` +const value = 1 +``` + +`// prints` without console.log: + + + +```typescript +calculator.add(1, 2) // prints 3 +``` + +An ES module that cannot import a name: + + + +```js +import { Mock } from '@fluffy-spoon/substitute' +Mock.for() +``` + +An error message that does not match: + + + +```typescript +calculator.add(1, 2) +calculator.received().add(3, 4) // throws SubstituteException +``` + + + +```text +SubstituteException: Call count mismatch in @Substitute.add: +Expected to receive 1 or more method calls matching add(3, 5), but received none. +All property or method calls to @Substitute.add received so far: +› ✘ @Substitute.add(1, 2) + called at somewhere +``` + +Skipped blocks are not checked: + + + +```typescript +this is not TypeScript +``` + +Blocks can build on blocks that build on other blocks: + + + +```typescript +calculator.add(1, 1).returns(2) +``` + + + +```typescript +console.log(calculator.add(1, 1)) // prints 2 +``` + +But not in a cycle: + + + +```typescript +const a = 1 +``` + + + +```typescript +const b = 2 +``` + +Links are checked, too. These work: [the top of this file](#fixture-for-spec-docsself-testjs), [the README](../../README.md#usage) and `[not a link](in code)`. + + +A link to [a heading that does not exist](#no-such-heading). + + +A link to [a file that does not exist](MISSING.md). diff --git a/spec-docs/harness.js b/spec-docs/harness.js new file mode 100644 index 0000000..13a3592 --- /dev/null +++ b/spec-docs/harness.js @@ -0,0 +1,59 @@ +'use strict' +// Runs one compiled documentation snippet in its own process and records what it did: +// node harness.js +// check.js rewrites the `// prints` and `// throws` lines of a snippet into calls of the global `__docs` object below, +// so the result file says, per Markdown line, what was printed and what was thrown. Uncaught exceptions and unhandled +// rejections are recorded too (the snippet keeps running, like it would in a test runner). +const fs = require('fs') +const util = require('util') +const { pathToFileURL } = require('url') + +const [snippet, resultFile] = process.argv.slice(2) +const result = { prints: [], throws: [], uncaught: [], error: null } + +const describe = error => { + if (error === null || (typeof error !== 'object' && typeof error !== 'function')) { + return { name: typeof error, message: String(error), stack: '' } + } + let name + let message + let stack + try { name = String(error.name) } catch (_) { name = 'unknown' } + try { message = String(error.message) } catch (_) { message = '' } + try { stack = String(error.stack) } catch (_) { stack = '' } + return { name, message, stack } +} + +global.__docs = { + print (line, ...values) { + result.prints.push({ line, text: util.format(...values) }) + }, + throws (line, statement) { + try { + statement() + } catch (error) { + result.throws.push(Object.assign({ line, threw: true }, describe(error))) + return + } + result.throws.push({ line, threw: false }) + } +} + +process.on('uncaughtException', error => { + result.uncaught.push(Object.assign({ kind: 'uncaught exception' }, describe(error))) +}) +process.on('unhandledRejection', error => { + result.uncaught.push(Object.assign({ kind: 'unhandled rejection' }, describe(error))) +}) +process.on('exit', () => { + fs.writeFileSync(resultFile, JSON.stringify(result)) +}) + +const run = async () => { + if (snippet.endsWith('.mjs')) await import(pathToFileURL(snippet).href) + else require(snippet) +} + +run().catch(error => { + result.error = describe(error) +}) diff --git a/spec-docs/self-test.js b/spec-docs/self-test.js new file mode 100644 index 0000000..74d8d59 --- /dev/null +++ b/spec-docs/self-test.js @@ -0,0 +1,64 @@ +#!/usr/bin/env node +'use strict' +// Checks that the docs check fails when it should: runs it on spec-docs/fixtures/broken.md, whose code blocks are +// broken on purpose, and compares the problems it reports with the `` comment of each +// block, and with the `` comments for problems in the text (links). Part of +// `npm run test:docs`. +const fs = require('fs') +const path = require('path') +const { checkDocs, formatProblem } = require('./check') + +const fixture = path.join('spec-docs', 'fixtures', 'broken.md') + +const main = async () => { + const { problems, blocks } = await checkDocs({ files: [fixture] }) + const failures = [] + const claimed = new Set() + for (const block of blocks) { + const comment = block.comments.find(text => text.startsWith('self-test:')) + if (!comment) { + failures.push(`${fixture}:${block.fenceLine}: the block has no comment`) + continue + } + const expected = comment.replace(/^self-test:\s*expect=/, '').trim() + const lastLine = block.fenceLine + block.code.length + 1 + const own = problems.filter(problem => problem.line >= block.fenceLine && problem.line <= lastLine) + own.forEach(problem => claimed.add(problem)) + if (expected === 'pass') { + if (own.length > 0) failures.push(`${fixture}:${block.fenceLine}: expected no problems, but got:\n ${own.map(formatProblem).join('\n ')}`) + } else if (!own.some(problem => problem.message.includes(expected))) { + failures.push(`${fixture}:${block.fenceLine}: expected a problem containing ${JSON.stringify(expected)}, but got:\n ` + + (own.length > 0 ? own.map(formatProblem).join('\n ') : '(none)')) + } + } + const lines = fs.readFileSync(path.resolve(__dirname, '..', fixture), 'utf8').split(/\r?\n/) + let brokenLines = 0 + lines.forEach((line, index) => { + const comment = //.exec(line) + if (!comment) return + brokenLines++ + const own = problems.filter(problem => problem.line === index + 2) + own.forEach(problem => claimed.add(problem)) + if (!own.some(problem => problem.message.includes(comment[1]))) { + failures.push(`${fixture}:${index + 2}: expected a problem containing ${JSON.stringify(comment[1])}, but got:\n ` + + (own.length > 0 ? own.map(formatProblem).join('\n ') : '(none)')) + } + }) + for (const problem of problems.filter(p => !claimed.has(p))) { + failures.push(`unexpected problem outside of the fixture's code blocks: ${formatProblem(problem)}`) + } + const broken = blocks.filter(block => !block.comments.some(text => text === 'self-test: expect=pass')).length + if (failures.length > 0) { + console.error(failures.join('\n')) + console.error(`docs-check self-test: ${failures.length} of ${blocks.length} expectations failed`) + process.exitCode = 1 + } else { + console.log(`docs-check self-test: all ${broken} deliberately broken code blocks and ${brokenLines} broken links were reported, ` + + `the ${blocks.length - broken} other code blocks passed`) + } +} + +main().catch(error => { + console.error(error) + process.exitCode = 1 +}) From 9ad5d7ee7457256035fe45ca73a23c439f03fb71 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:40:21 +0000 Subject: [PATCH 025/106] fix(engine): received(Arg...) followed by a member access is an assertion (D10, D11) A call of the string `received` / `didNotReceive` with an Arg matcher among its arguments was always taken as a setup (D3) of a member with that name, so `sub.received(Arg.any()).add(1)` silently configured something and the "assertion" passed, and `sub.didNotReceive(Arg.any()).value = 1` threw "Property assignments cannot be configured". By D11 such a call followed by a member access or an assignment is the assertion API: received() now reports the invalid count (D10) and didNotReceive() asserts, ignoring its arguments as it does without matchers. Followed by a substitution method, and inside a configure() view, it is still a setup of the user's member. Found by porting engine A's D11 test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 36 ++++++++++++++++++++++++ src/internals/Engine.ts | 22 +++++++++++---- 2 files changed, 53 insertions(+), 5 deletions(-) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index de46053..848b34b 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -399,3 +399,39 @@ test('D2 an argument object that is mutated after a call keeps its auto-substitu query.page = 2 t.notThrows(() => service.find(query).received(1).log('first')) }) + +test('D10 / D11 received(Arg...) followed by a member access is an assertion and reports the invalid count', t => { + const calculator = Substitute.for() + calculator.add(1) + calculator.value = 1 + + // it used to configure a member called `received` silently, so the "assertion" always passed + for (const count of [Arg.any(), Arg.is(() => true), Arg.all()]) { + t.throws(() => calculator.received(count).add(1), { instanceOf: SubstituteException, message: /non-negative integer/ }) + t.throws(() => calculator.received(count).add(2), { instanceOf: SubstituteException, message: /non-negative integer/ }) + t.throws(() => { calculator.received(count).value = 1 }, { instanceOf: SubstituteException, message: /non-negative integer/ }) + t.throws(() => calculator.received(count).value, { instanceOf: SubstituteException, message: /non-negative integer/ }) + } + t.throws(() => calculator.logger.received(Arg.any()).info('x'), { instanceOf: SubstituteException, message: /non-negative integer/ }) + + // didNotReceive() ignores its arguments, as without matchers: these are real assertions + t.notThrows(() => calculator.didNotReceive(Arg.any()).add(2)) + t.throws(() => calculator.didNotReceive(Arg.any()).add(1), { instanceOf: SubstituteException, message: /Call count mismatch/ }) + t.notThrows(() => { calculator.didNotReceive(Arg.any()).value = 2 }) + t.throws(() => { calculator.didNotReceive(Arg.any()).value = 1 }, { instanceOf: SubstituteException, message: /Call count mismatch/ }) + + // none of this was recorded or configured + t.notThrows(() => calculator.didNotReceive().received) + t.notThrows(() => calculator.didNotReceive().didNotReceive) + t.true(types.isProxy(calculator.received(5))) + + // followed by a substitution method it stays a setup of a member called received (D3, D11) + const overlapping = Substitute.for() + overlapping.received(Arg.any()).returns('any') + overlapping.didNotReceive(Arg.all()).returns('all') + t.is(overlapping.received(7), 'any') + t.is(overlapping.didNotReceive(), 'all') + // ... and so is everything in a configure() view + overlapping[configure]().received(Arg.any()).returns('configured') + t.is(overlapping.received(8), 'configured') +}) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 7f29837..dab16ca 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -284,7 +284,7 @@ const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStar const specification = RecordedArguments.forSpecification(args) retract(read) retract(chainPrevious) - return configureCall(state, key, specification) + return configureCall(state, key, specification, isStringAssertionKey(key)) } let record: CallRecord @@ -533,9 +533,18 @@ const nestedEntry = (state: SubstituteState, key: PropertyKey, specification: Re return entry } -/** A call in a setup: `.returns(...)` configures it, anything else configures the auto-substitute it returns. */ -const configureCall = (state: SubstituteState, key: PropertyKey, specification: RecordedArguments): any => { +/** + * A call in a setup: `.returns(...)` configures it, anything else configures the auto-substitute it returns. + * + * `stringAssertion` marks a call of the string `received` / `didNotReceive` with Arg matchers among its + * arguments, outside a configure() view. Followed by a substitution method it is a setup of a member with that + * name like any other; followed by any other member access or an assignment it is the assertion API (D11), so + * `sub.received(Arg.any()).add(1)` reports the invalid count (D10) instead of configuring something silently. + */ +const configureCall = (state: SubstituteState, key: PropertyKey, specification: RecordedArguments, stringAssertion = false): any => { const print: Printer = options => withPrintGuard(() => `method<${memberLabel(key)}>: ${formatArguments(specification.value, colorsOf(options))} (configure)`) + const assertionCount = (start: Function): ExpectedCount => + key === 'didNotReceive' ? 0 : validateExpectedCount(specification.value?.[0], start) return new Proxy(newTarget(print), { get: function get(_target: unknown, property: PropertyKey) { if (isSpecialProperty(property)) return special(property, print, undefined) @@ -543,10 +552,13 @@ const configureCall = (state: SubstituteState, key: PropertyKey, specification: if (method !== undefined) return function substitution(...values: any[]) { state.addCallSubstitution(key, specification, method, values) } + if (stringAssertion) return assertionMember(state, property, assertionCount(get), get) return configureMember(nestedEntry(state, key, specification).state, property) }, - set: function set() { - throw configureSetError(set) + set: function set(_target: unknown, property: PropertyKey, value: unknown) { + if (!stringAssertion) throw configureSetError(set) + assertSet(state, property, value, assertionCount(set), set) + return true }, apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { return configureCall(nestedEntry(state, key, specification).state, SELF, RecordedArguments.forSpecification(args)) From 0c983ec74fb7e38ceda7ddcfb3da7e71f95c8d45 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:40:21 +0000 Subject: [PATCH 026/106] fix(messages): name assignments in the listing of an assignment assertion A failed `sub.received(1).isEnabled = false` listed the assignments under "All property or method calls to @Substitute.isEnabled received so far:". The listing of an assignment assertion only contains assignments, so it is now headed "All property assignments to ... received so far:". The other headings are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 15 +++++++++++++++ src/internals/SubstituteException.ts | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index 848b34b..a577e28 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -435,3 +435,18 @@ test('D10 / D11 received(Arg...) followed by a member access is an assertion and overlapping[configure]().received(Arg.any()).returns('configured') t.is(overlapping.received(8), 'configured') }) + +test('D18 an assignment assertion lists the assignments under "All property assignments to"', t => { + const settings = Substitute.for() + settings.isEnabled = true + void settings.isEnabled + const message = messageOf(() => { settings.received(1).isEnabled = false }) + t.true(message.startsWith( + 'Call count mismatch in @Substitute.isEnabled:\n' + + 'Expected to receive 1 property assignment matching isEnabled = false, but received none.\n' + + 'All property assignments to @Substitute.isEnabled received so far:\n' + + '› ✘ @Substitute.isEnabled = true\n' + )) + t.is(listedLines(message).length, 1) + t.true(messageOf(() => settings.received(2).isEnabled).includes('All property or method calls to @Substitute.isEnabled received so far:')) +}) diff --git a/src/internals/SubstituteException.ts b/src/internals/SubstituteException.ts index 5273d63..97ca582 100644 --- a/src/internals/SubstituteException.ts +++ b/src/internals/SubstituteException.ts @@ -117,7 +117,9 @@ export class SubstituteException extends Error { if (mismatch.explanation !== undefined) textBuilder.add(` ${mismatch.explanation}`) if (mismatch.listed.length > 0) { - textBuilder.newLine().add(`All property or method calls to ${memberPath} received so far:`) + // an assignment assertion lists only the assignments, the others list reads and calls + const heading = expected.kind === 'set' ? 'All property assignments to' : 'All property or method calls to' + textBuilder.newLine().add(`${heading} ${memberPath} received so far:`) const shown = mismatch.listed.length > MAX_LISTED_CALLS ? mismatch.listed.slice(0, MAX_LISTED_CALLS) : mismatch.listed for (const listed of shown) { const style = (part: TextPart) => listed.matches ? part.faint() : part.bold() From 7d294786f7dc00cf10f7b547d84cbab4540ed08a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:41:04 +0000 Subject: [PATCH 027/106] docs(readme): note that setup method names on unconfigured values are setups Code under test that reads a member called returns (or throws, resolves, rejects, mimicks) on an unconfigured call result gets the setup method, so calling it reconfigures the substitute. Configuring the value first avoids that. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 49cdff1..04b1148 100644 --- a/README.md +++ b/README.md @@ -651,6 +651,8 @@ order.total().returns(42) console.log(shop.find('1').total()) // prints 42 ``` +At runtime, `.returns`, `.throws`, `.resolves`, `.rejects` and `.mimicks` on a member or call that is *not* configured always mean the setup methods. So if the code under test uses a member with one of these names on a value it gets from a substitute, configure that value first, as `shop.find('1')` above. + `clearReceivedCalls`, `mimick` and `configure` exist only as symbols, so members with those names never conflict. ## In JavaScript From 94830e60d736d92ea2fe163c7ad9b377bfc28493 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:43:03 +0000 Subject: [PATCH 028/106] test: port engine A's behavioural tests that pass unchanged 32 tests from fix/engine-a's spec/regression/fixes/{decisions,runtime, arguments,regression}.spec.ts, with their bodies unchanged, in spec/regression/fixes/ported-from-a.spec.ts: D2 (x3), D3-D8, the D9 deferral limit, D11 (string form followed by a substitution method), D12-D15, R:RT-1/2/3/5/8/10/11/12/13, 'D5 without configure()', A:RT-4/5/6, G:RG-1/5/8, and 'R:RT-4 ... on the root they are a usage error' (D22). Tests whose checks are all covered by the existing *.test.ts files are left out; the file header lists them with the covering tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/ported-from-a.spec.ts | 815 ++++++++++++++++++++ 1 file changed, 815 insertions(+) create mode 100644 spec/regression/fixes/ported-from-a.spec.ts diff --git a/spec/regression/fixes/ported-from-a.spec.ts b/spec/regression/fixes/ported-from-a.spec.ts new file mode 100644 index 0000000..6ee74b8 --- /dev/null +++ b/spec/regression/fixes/ported-from-a.spec.ts @@ -0,0 +1,815 @@ +import test, { ExecutionContext, ThrowsExpectation } from 'ava' +import * as fakeTimers from '@sinonjs/fake-timers' +import { EventEmitter } from 'events' +import * as path from 'path' +import { inspect, types } from 'util' + +import * as library from '../../../src' +import { Substitute, Arg, received, didNotReceive, configure, mimick, clearReceivedCalls, returns, throws, mimicks } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +/* + * Behavioural tests ported unchanged from the other round-1 engine (branch fix/engine-a, + * spec/regression/fixes/{decisions,runtime,arguments,regression}.spec.ts). Their bodies are kept as they were + * written there; only the tests that add coverage to spec/regression/fixes/*.test.ts are ported. + * + * Left out as duplicates (everything they check is covered by the named tests): + * - D16, D17, A:RT-11: decisions.test.ts D16 / D17 and arguments.test.ts A:RT-11 + * - R:RT-4 'symbol assertions on members named like substitution methods': runtime.test.ts R:RT-4, regression.test.ts G:RG-1 + * - R:RT-7, R:RT-9: runtime.test.ts R:RT-7 / R:RT-9 + * - A:RT-1, A:RT-2, A:RT-7, A:DOC-1: arguments.test.ts, runtime.test.ts R:RT-6, regression.test.ts G:RG-2 + * - A:RT-10: arguments.test.ts A:RT-10 (the same behaviour; engine A words the note differently) + * - A:RT-14: arguments.test.ts A:RT-14 and amendments.test.ts D24 + * - G:RG-2, G:RG-7: regression.test.ts G:RG-2 / G:RG-7 + * The tests that depend on engine A's wording are ported, with this engine's wording, in ported-from-a-messages.spec.ts. + */ + +const plain = (message: string) => message.replace(/\x1b\[\d+m/g, '') +// runtime behaviour only: the substitutes are untyped so that the specs do not depend on the typings +const substitute = (): any => Substitute.for() + +const throwsOnNextTick = (cb: () => unknown, t: ExecutionContext, expectation: ThrowsExpectation) => { + const clock = fakeTimers.install({ toFake: ['nextTick'] }) + try { + cb() + t.throws(() => clock.tick(1), expectation) + } finally { + clock.uninstall() + } +} + +const doesNotThrowOnNextTick = (cb: () => unknown, t: ExecutionContext) => { + const clock = fakeTimers.install({ toFake: ['nextTick'] }) + try { + cb() + t.notThrows(() => clock.tick(1)) + } finally { + clock.uninstall() + } +} + +interface Logger { + log(message: string, ...meta: unknown[]): void + level: number +} + +interface Config { + token: string + flaky: string + computed: number + ready: Promise +} + +interface User { name: string } +interface Repository { + find(id: number): User + remove(id: number): void + add(a: number, b: number): number + sequence(id: number): number +} + +interface Shop { + returns(orderId: number): void + rejects(orderId: number): void + throws(code: number): void + add(a: number, b: number): number +} + +interface Counter { total: number } +interface Mailbox { + getStats(): { received: Counter, sent: Counter } + inbox: { received: Counter, didNotReceive: Counter } + received: Date +} + +interface Calculator { add(a: number, b: number): number } + +interface Handler { onClick(x: number): void } + +test('D2 repeated access to the same member path with matching arguments returns the same auto-substitute', t => { + const app = substitute() + t.is(app.logger, app.logger) + t.is(app.getCalc(), app.getCalc()) + t.is(app.find({ id: 1, tags: ['a'] }), app.find({ tags: ['a'], id: 1 })) + t.is(app.a.b(1).c, app.a.b(1).c) + t.not(app.getCalc(1), app.getCalc(2)) + t.not(app.getCalc(0), app.getCalc(-0)) + t.not(app.getCalc(1), app.getCalc('1')) + t.not(app.find({ id: 1 }), app.find({ id: 2 })) + + // substitutes as arguments compare by identity + const first = substitute() + const second = substitute() + t.is(app.use(first), app.use(first)) + t.not(app.use(first), app.use(second)) + + // the same holds for many distinct arguments + const results = Array.from({ length: 50 }, (_, index) => app.item(index)) + t.true(results.every((result, index) => result === app.item(index))) +}) + +test('D2 nested setups and nested assertions work at runtime', t => { + const app = substitute() + app.getCalc().add(1, 2).returns(99) + app.config.retries.returns(3) + app.logger.info('hi') + + t.is(app.getCalc().add(1, 2), 99) + t.true(types.isProxy(app.getCalc().add(2, 2))) + t.is(app.config.retries, 3) + + t.notThrows(() => app.logger.received().info('hi')) + t.throws(() => app.logger.received().info('bye'), { instanceOf: SubstituteException }) + t.notThrows(() => app.getCalc().received(1).add(1, 2)) + t.notThrows(() => app.getCalc().didNotReceive().add(2, 3)) + + // the setup and assertion chains are not received calls (getCalc() was called twice above) + t.notThrows(() => app.received(2).getCalc()) + t.notThrows(() => app.received(1).config) + t.notThrows(() => app.received(1).logger) + t.notThrows(() => app.config.received(1).retries) +}) + +test('D2 a setup or call on the root never leaks into a nested member with the same name, and vice versa', t => { + const app = substitute() + app.add(1, 2).returns(99) + app.nested.add(1, 2).returns(5) + app.add(1, 2) + app.nested.add(1, 2) + app.nested.add(1, 2) + + t.is(app.add(1, 2), 99) + t.is(app.nested.add(1, 2), 5) + t.notThrows(() => app.received(2).add(1, 2)) + t.notThrows(() => app.nested.received(3).add(1, 2)) + t.true(types.isProxy(app.other.add(1, 2))) +}) + +test('D3 calls with Arg matchers are setups: never executed and never recorded', t => { + const calculator = substitute() + let calls = 0 + calculator.add(Arg.all()).mimicks(() => ++calls) + calculator.add(Arg.any(), Arg.is(() => true)).returns(1) + calculator.add(Arg.any.not('string'), 1) + t.is(calls, 0) + t.notThrows(() => calculator.didNotReceive().add(Arg.all())) + + t.is(calculator.add(1, 1), 1) + t.is(calculator.add(1, 2, 3), 1) + t.is(calls, 1) + t.notThrows(() => calculator.received(2).add(Arg.all())) + + // a literal in a setup never matches an Arg passed by a later call + const strict = substitute() + strict.find(1).returns('one') + t.true(types.isProxy(strict.find(Arg.any()))) + strict.value = Arg.any() + t.notThrows(() => strict.didNotReceive().value = Arg.any()) +}) + +test('D4 the most specific substitution wins, then the most recently configured one', t => { + const calculator = substitute() + calculator.add(1, 2).returns('literal') + calculator.add(Arg.any(), 2).returns('predicate') + calculator.add(Arg.all()).returns('wildcard') + t.is(calculator.add(1, 2), 'literal') + t.is(calculator.add(5, 2), 'predicate') + t.is(calculator.add(5, 5), 'wildcard') + + calculator.add(Arg.any(), Arg.any()).returns('newer predicate') + t.is(calculator.add(1, 2), 'literal') + t.is(calculator.add(5, 2), 'newer predicate') + calculator[configure]().add(1, 2).returns('newer literal') + t.is(calculator.add(1, 2), 'newer literal') + calculator.add(Arg.all()).returns('newer wildcard') + t.is(calculator.add(5, 5, 5), 'newer wildcard') + t.is(calculator.add(5, 5), 'newer predicate') + + calculator.value.returns(1) + calculator[configure]().value.returns(2) + t.is(calculator.value, 2) +}) + +test('D5 configure() is a view in which every call is a setup', t => { + const calculator = substitute() + let mimickCalls = 0 + calculator.add(Arg.all()).mimicks(() => ++mimickCalls) + calculator.divide(Arg.any(), 0).throws(new Error('division by zero')) + calculator.enabled.returns(false) + + calculator[configure]().add(1, 3).returns(1337) + calculator[configure]().divide(0, 0).returns(NaN) + calculator[configure]().enabled.returns(true) + calculator[configure]().enabled[returns](true) + calculator[configure]().multiply(2, 2)[mimicks]((a: number, b: number) => a * b) + calculator[configure]().fail()[throws](new Error('fail')) + t.is(mimickCalls, 0) + + t.is(calculator.add(1, 3), 1337) + t.is(calculator.add(1, 4), 1) + t.true(Number.isNaN(calculator.divide(0, 0))) + t.throws(() => calculator.divide(1, 0), { message: 'division by zero' }) + t.true(calculator.enabled) + t.is(calculator.multiply(2, 2), 4) + t.throws(() => calculator.fail(), { message: 'fail' }) + + // configuring is never recorded + t.notThrows(() => calculator.received(1).add(1, 3)) + t.notThrows(() => calculator.received(1).divide(0, 0)) + t.notThrows(() => calculator.received(1).enabled) + + // nested members, calls of returned functions and the substitute itself + const app = substitute() + app[configure]().services.getRepository('users').find(1).returns('alice') + t.notThrows(() => app.didNotReceive().services) + t.is(app.services.getRepository('users').find(1), 'alice') + app[configure]().factory()(2).returns('two') + t.is(app.factory()(2), 'two') + const fn = substitute() + fn[configure]()(1).returns('one') + t.is(fn(1), 'one') + t.notThrows(() => app.received(1).services) + + t.throws(() => { calculator[configure]().value = 1 }, { instanceOf: SubstituteException }) +}) + +test('D5 without configure() a literal call matching a substitution keeps returning the configured value', t => { + const repository = substitute() + repository.add(Arg.all()).returns(10) + + t.throws(() => (repository.add(1, 3) as any).returns(1337), { instanceOf: TypeError }) + t.is(repository.add(1, 3), 10) +}) + +test('D6 assertions never execute substitutions or mimicks and are never recorded', t => { + const calculator = substitute() + let calls = 0 + calculator.add(Arg.all()).mimicks(() => ++calls) + calculator.value.mimicks(() => ++calls) + calculator.broken.throws(new Error('broken')) + + calculator.add(1, 2) + void calculator.value + t.is(calls, 2) + + calculator.received(1).add(1, 2) + calculator[received](1).add(Arg.any(), Arg.any()) + calculator.didNotReceive().add(2, 2) + calculator.received(1).value + calculator[didNotReceive]().broken + t.is(calls, 2) + + t.notThrows(() => calculator.received(1).add(1, 2)) + t.notThrows(() => calculator.received(1).value) + t.notThrows(() => calculator.didNotReceive().received) + t.notThrows(() => calculator.didNotReceive().didNotReceive) +}) + +test('D7 each invocation is its own record, also through stored references, callbacks and call/apply/bind', t => { + const logger = substitute() + logger.log(Arg.all()).returns('logged') + const log = logger.log + const bound = logger.log.bind(logger) + + t.is(log(1), 'logged') + t.is(log(2), 'logged') + t.is(bound(3), 'logged') + t.is(logger.log.call(null, 4), 'logged') + t.is(logger.log.apply(null, [5]), 'logged') + t.deepEqual([6, 7].map(logger.log), ['logged', 'logged']) + + t.notThrows(() => logger.received(7).log(Arg.all())) + for (const value of [1, 2, 3, 4, 5]) t.notThrows(() => logger.received(1).log(value)) + t.notThrows(() => logger.received(1).log(6, 0, [6, 7])) + // every read of `log` above was followed by invocations: none of them is a property read + t.notThrows(() => logger.received(0).log) + + const guard = substitute() + if (guard.onDone) guard.onDone(1) + const stored = guard.onDone + void guard.onDone + stored(2) + t.notThrows(() => guard.received(2).onDone(Arg.all())) + t.notThrows(() => guard.received(2).onDone) +}) + +test('D8 property assertions count reads, set assertions count sets, method assertions count invocations', t => { + const component = substitute() + void component.value + void component.value + component.value = 1 + component.value(1) + + t.notThrows(() => component.received(2).value) + t.notThrows(() => { component.received(1).value = 1 }) + t.notThrows(() => component.received(1).value(1)) + t.notThrows(() => component.received(1).value(Arg.all())) + t.throws(() => component.received(3).value(Arg.all()), { instanceOf: SubstituteException }) +}) + +test('D9 the deferred case is limited to members also invoked as a method, with a count a call could satisfy', t => { + const component = substitute() + component.onChange() + void component.onChange + void component.onChange + + // property-style: 2 reads, 1 call. received(1) could still be a method assertion that passes + throwsOnNextTick(() => component.received(1).onChange, t, { instanceOf: SubstituteException }) + doesNotThrowOnNextTick(() => component.received(1).onChange(), t) + doesNotThrowOnNextTick(() => t.throws(() => component.didNotReceive().onChange(), { instanceOf: SubstituteException }), t) +}) + +test('D11 the string form followed by a substitution method stays a setup of a member named received', t => { + const overlapping = substitute() + overlapping.received(10).returns('foo') + t.is(overlapping.received(10), 'foo') + t.notThrows(() => overlapping[received](1).received(10)) + t.throws(() => overlapping.didNotReceive().received(10), { instanceOf: SubstituteException }) +}) + +test('D12 [mimick] delegates unconfigured member reads, calls and sets to the instance', t => { + class Counter { + public count = 1 + public get double() { return this.count * 2 } + public increment(by: number) { + this.count += by + return this + } + } + const real = new Counter() + const counter = substitute() + counter[mimick](real) + + t.is(counter.count, 1) + t.is(counter.increment(2), real) + t.is(real.count, 3) + t.is(counter.double, 6) + counter.count = 10 + t.is(real.count, 10) + t.is(counter.missing, undefined) + + t.notThrows(() => counter.received(1).increment(2)) + t.notThrows(() => counter.received(1).count) + t.notThrows(() => { counter.received(1).count = 10 }) + + // explicit substitutions take precedence; after mimick, configure() sets them up + counter[configure]().increment(5).returns('configured') + counter[configure]().double.returns(-1) + t.is(counter.increment(5), 'configured') + t.is(counter.increment(1), real) + t.is(counter.double, -1) + + const fn = substitute() + fn[mimick]((a: number) => a * 3) + t.is(fn(2), 6) +}) + +test('D13 clearReceivedCalls clears the received calls of the substitute and its auto-substitutes, not its substitutions', t => { + const app = substitute() + app.add(1, 1).returns(2) + app.value.returns(1, 2, 3) + app.add(1, 1) + void app.value + app.logger.info('x') + app.getCalc().add(1) + + app[clearReceivedCalls]() + + t.notThrows(() => app.didNotReceive().add(1, 1)) + t.notThrows(() => app.didNotReceive().value) + t.notThrows(() => app.logger.didNotReceive().info('x')) + t.notThrows(() => app.getCalc().didNotReceive().add(1)) + t.is(app.add(1, 1), 2) + t.is(app.value, 2) + + app.logger.info('y') + app.logger[clearReceivedCalls]() + t.notThrows(() => app.logger.didNotReceive().info('y')) + t.notThrows(() => app.received(1).add(1, 1)) +}) + +test('D14 Arg.all() matches any (possibly empty) remainder; arguments before it match normally', t => { + const logger = substitute() + logger.log('x') + logger.log('x', 1, 2) + logger.log('y', 1) + logger.log() + + t.notThrows(() => logger.received(2).log('x', Arg.all())) + t.notThrows(() => logger.received(4).log(Arg.all())) + t.notThrows(() => logger.received(3).log(Arg.any(), Arg.all())) + t.notThrows(() => logger.received(1).log('x', 1, Arg.all())) + t.notThrows(() => logger.received(0).log('z', Arg.all())) + + logger.format('x', Arg.all()).returns('prefixed') + t.is(logger.format('x'), 'prefixed') + t.is(logger.format('x', 1), 'prefixed') + t.true(types.isProxy(logger.format('y'))) + + t.throws(() => logger.log(Arg.all(), 'x'), { instanceOf: SubstituteException }) + t.throws(() => logger.received().log('x', Arg.all(), Arg.all()), { instanceOf: SubstituteException }) +}) + +test('D15 substitutes are compared by identity and never traversed', t => { + const service = substitute() + const first = substitute() + const second = substitute() + service.register(first) + service.register({ dependency: first }) + + t.notThrows(() => service.received(1).register(first)) + t.throws(() => service.received().register(second), { instanceOf: SubstituteException }) + t.notThrows(() => service.received(1).register({ dependency: first })) + t.throws(() => service.received().register({ dependency: second }), { instanceOf: SubstituteException }) + // matching did not record anything on the substitutes passed as arguments + t.is(inspect(first), '@Substitute {\n}') + t.is(inspect(second), '@Substitute {\n}') +}) + +test('R:RT-1 every call through a stored method reference is its own call record', t => { + const logger = substitute() + const { log } = logger + log('a') + log('b') + + t.notThrows(() => logger.received(2).log(Arg.any())) + t.notThrows(() => logger.received(1).log('a')) + t.notThrows(() => logger.received(1).log('b')) + + const sameArgs = substitute() + const stored = sameArgs.log + stored('same') + stored('same') + t.throws(() => sameArgs.received(1).log('same'), { instanceOf: SubstituteException }) + t.notThrows(() => sameArgs.received(2).log('same')) + + const callback = substitute() + ;['x', 'y', 'z'].forEach(callback.log) + t.notThrows(() => callback.received(3).log(Arg.all())) + t.notThrows(() => callback.received(1).log('y', 1, ['x', 'y', 'z'])) +}) + +test('R:RT-2 assertions on configured properties never execute the substitution', async t => { + const config = substitute() + config.token.returns('t1', 't2', 't3') + config.flaky.throws(new Error('boom')) + let mimickCalls = 0 + config.computed.mimicks(() => ++mimickCalls) + config.ready.rejects(new Error('not ready')) + + t.is(config.token, 't1') + t.notThrows(() => config.received(1).token) + t.is(config.token, 't2') + t.is(config.token, 't3') + + t.throws(() => config.flaky, { message: 'boom' }) + t.notThrows(() => config.received(1).flaky) + t.notThrows(() => config[received](1).flaky) + + const neverRead = substitute() + neverRead.flaky.throws(new Error('boom')) + t.notThrows(() => neverRead.didNotReceive().flaky) + + t.is(config.computed, 1) + config.received(1).computed + config.received().computed + t.is(mimickCalls, 1) + + await t.throwsAsync(config.ready, { message: 'not ready' }) + let unhandled = 0 + const onUnhandled = () => unhandled++ + process.on('unhandledRejection', onUnhandled) + try { + config.received(1).ready + await new Promise(resolve => setTimeout(resolve, 10)) + } finally { + process.off('unhandledRejection', onUnhandled) + } + t.is(unhandled, 0) +}) + +test('R:RT-3 configure() overrides a setup whose literal arguments match an existing substitution', t => { + const anyUser = substitute() + anyUser.name.returns('any') + const admin = substitute() + admin.name.returns('admin') + + const repository = substitute() + repository.find(Arg.any()).returns(anyUser) + repository[configure]().find(1).returns(admin) + t.is(repository.find(1).name, 'admin') + t.is(repository.find(2).name, 'any') + + // README "Match order", first example + repository.add(Arg.all()).returns(10) + repository[configure]().add(1, 3).returns(1337) + t.is(repository.add(1, 3), 1337) + t.is(repository.add(5, 2), 10) + + // a throws() default does not fire while configuring a specific call + repository.remove(Arg.any()).throws(new Error('forbidden')) + t.notThrows(() => repository[configure]().remove(1).returns()) + t.is(repository.remove(1), undefined) + t.throws(() => repository.remove(2), { message: 'forbidden' }) + + // a sequence is not used up by configuring + repository.sequence(Arg.any()).returns(1, 2) + repository[configure]().sequence(7).returns(70) + t.is(repository.sequence(1), 1) + t.is(repository.sequence(7), 70) + t.is(repository.sequence(1), 2) + + // re-configuring the same call: the most recent setup wins + const users = substitute() + users.find(5).returns(anyUser) + t.is(users.find(5), anyUser) + users[configure]().find(5).returns(admin) + t.is(users.find(5), admin) + + // configuring is not a call + t.notThrows(() => users.received(2).find(5)) + t.notThrows(() => repository.received(1).find(1)) + t.notThrows(() => repository.didNotReceive().sequence(7 * 100)) +}) + +test('R:RT-4 symbol substitution methods on a call configure it; on the root they are a usage error', t => { + const shop = substitute() + ;(shop.add(1, 2) as any)[returns](3) + ;(shop.add(2, 2) as any)[throws](new Error('nope')) + t.is(shop.add(1, 2), 3) + t.throws(() => shop.add(2, 2), { message: 'nope' }) + t.throws(() => (shop as any)[returns](1), { instanceOf: SubstituteException }) +}) + +test('R:RT-5 members named received/didNotReceive that are not invoked are ordinary members', t => { + const mailbox = substitute() + + t.true(types.isProxy(mailbox.getStats().sent.total)) + t.true(types.isProxy(mailbox.getStats().received.total)) + t.notThrows(() => { (mailbox.getStats().received as any).total = 3 }) + t.true(types.isProxy(mailbox.inbox.received.total)) + t.true(types.isProxy(mailbox.inbox.didNotReceive.total)) + t.is(typeof mailbox.received.getTime(), 'function') + + t.notThrows(() => mailbox.getStats().received.received(1).total) + t.throws(() => mailbox.getStats().received.received(2).total, { instanceOf: SubstituteException }) +}) + +test('R:RT-8 / D19 resolving calls does not scan the received calls: 10k calls and 10k configured reads finish quickly', t => { + const logger = substitute() + logger.level.returns(1) + logger.format(Arg.any()).returns('formatted') + + const start = Date.now() + for (let index = 0; index < 10_000; index++) logger.log('message', index % 10) + for (let index = 0; index < 10_000; index++) void logger.level + for (let index = 0; index < 10_000; index++) logger.format(index) + const elapsed = Date.now() - start + t.true(elapsed < 1000, `took ${elapsed} ms`) + + // unconfigured calls with distinct arguments each get their own (cached) auto-substitute + const tracker = substitute() + const trackingStart = Date.now() + for (let index = 0; index < 10_000; index++) tracker.track({ id: index }) + const trackingElapsed = Date.now() - trackingStart + t.true(trackingElapsed < 1000, `took ${trackingElapsed} ms`) + + t.notThrows(() => logger.received(10_000).log('message', Arg.any())) + t.notThrows(() => logger.received(10_000).level) + t.notThrows(() => tracker.received(1).track({ id: 9_999 })) + t.is(tracker.track({ id: 5 }), tracker.track({ id: 5 })) +}) + +test('R:RT-10 reading a method without invoking it is not a method call', t => { + const handler = substitute() + const button = new EventEmitter() + button.on('click', handler.onClick) + + t.throws(() => handler.received().onClick(Arg.any()), { instanceOf: SubstituteException }) + t.throws(() => handler.received(1).onClick(42), { instanceOf: SubstituteException }) + t.throws(() => handler.received(1).onClick(), { instanceOf: SubstituteException }) + + const twice = substitute() + void twice.onClick + void twice.onClick + t.throws(() => twice.received(2).onClick(1), { instanceOf: SubstituteException }) + t.notThrows(() => twice.received(2).onClick) + + button.emit('click', 42) + t.notThrows(() => handler.received(1).onClick(42)) +}) + +test('R:RT-11 .call, .apply and .bind behave like a direct call', t => { + const calculator = substitute() + calculator.add(1, 2).returns(3) + + t.is(calculator.add(1, 2), 3) + t.is(calculator.add.call(calculator, 1, 2), 3) + t.is(calculator.add.apply(calculator, [1, 2]), 3) + t.is(calculator.add.bind(calculator)(1, 2), 3) + t.is(calculator.add.bind(calculator, 1)(2), 3) + t.is(Reflect.apply(calculator.add, calculator, [1, 2]), 3) + + t.notThrows(() => calculator.received(6).add(1, 2)) + t.throws(() => calculator.received(1).add(7, 7), { instanceOf: SubstituteException }) + + const handler = substitute<{ onX(value: number): void }>() + const emitter = new EventEmitter() + emitter.on('x', handler.onX) + emitter.emit('x', 1) + t.notThrows(() => handler.received(1).onX(1)) + t.throws(() => handler.received(1).onX(999), { instanceOf: SubstituteException }) + t.notThrows(() => handler.didNotReceive().onX(999)) +}) + +test('R:RT-12 assertion messages are built when Error.stackTraceLimit is 0', t => { + const limit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + const calculator = substitute() + calculator.add(1, 2) + const { message } = t.throws(() => calculator.received(2).add(1, 2), { instanceOf: SubstituteException }) + t.regex(plain(message), /Call count mismatch in @Substitute\.add/) + t.throws(() => calculator.received(1).add(9, 9), { instanceOf: SubstituteException }) + } finally { + Error.stackTraceLimit = limit + } + + delete (Error as any).stackTraceLimit + try { + const calculator = substitute() + calculator.add(1, 2) + t.throws(() => calculator.received(1).add(9, 9), { instanceOf: SubstituteException }) + } finally { + Error.stackTraceLimit = limit + } +}) + +test('R:RT-13 sequences yield their values and then keep yielding the last one (D1)', async t => { + const calculator = substitute, fail(): void }>() + calculator.add(1, 2).returns(3, 7, 9) + t.deepEqual([1, 2, 3, 4, 5].map(() => calculator.add(1, 2)), [3, 7, 9, 9, 9]) + + calculator.value.returns(1, 2) + t.deepEqual([calculator.value, calculator.value, calculator.value], [1, 2, 2]) + + calculator.load().resolves(1, 2) + t.deepEqual([await calculator.load(), await calculator.load(), await calculator.load()], [1, 2, 2]) + + calculator.fail().throws(new Error('first'), new Error('last')) + t.throws(() => calculator.fail(), { message: 'first' }) + t.throws(() => calculator.fail(), { message: 'last' }) + t.throws(() => calculator.fail(), { message: 'last' }) + + calculator[configure]().add(2, 2).mimicks(() => 'a', () => 'b') + t.deepEqual([calculator.add(2, 2), calculator.add(2, 2), calculator.add(2, 2)], ['a', 'b', 'b'] as unknown[]) +}) + +test('A:RT-4 assertions on nested and auto-returned substitutes check their own calls (D2)', t => { + const app = substitute() + app.logger.info('hi') + t.notThrows(() => app.logger.received().info('hi')) + t.notThrows(() => app.logger.received(1).info('hi')) + t.notThrows(() => app.logger[received](1).info('hi')) + const { message } = t.throws(() => app.logger.received().info('bye'), { instanceOf: SubstituteException }) + t.true(plain(message).startsWith('Call count mismatch in @Substitute.logger.info:\nExpected to receive 1 or more method calls matching info(\'bye\'), but received none.')) + + // a call on the root never satisfies a nested assertion + const root = substitute() + root.warn('disk') + t.throws(() => root.logger.received().warn('disk'), { instanceOf: SubstituteException }) + + // auto-returned substitutes + const factory = substitute() + const repository = factory.getRepo() + repository.save(1) + t.notThrows(() => repository.received().save(1)) + t.notThrows(() => factory.getRepo().received(1).save(1)) + t.throws(() => factory.getRepo(2).received().save(1), { instanceOf: SubstituteException }) + // the assertion chains above are not received calls + t.notThrows(() => factory.received(1).getRepo()) + t.notThrows(() => app.received(1).logger) +}) + +test('A:RT-5 Arg.all() after other arguments matches the remaining arguments only (D14)', t => { + const logger = substitute() + logger.log('user created', { id: 1 }) + t.throws(() => logger.received().log('user DELETED', Arg.all()), { instanceOf: SubstituteException }) + t.notThrows(() => logger.received(1).log('user created', Arg.all())) + t.notThrows(() => logger.received(1).log(Arg.any('string'), Arg.all())) + + const calculator = substitute() + calculator.add(9, Arg.all()).returns('nine') + t.true(types.isProxy(calculator.add(1, 2))) + t.is(calculator.add(9), 'nine') + t.is(calculator.add(9, 1, 2), 'nine') + + t.throws(() => calculator.add(Arg.all(), 1), { instanceOf: SubstituteException, message: /Arg\.all\(\).*last argument/ }) + t.throws(() => calculator.received().add(Arg.all(), 1), { instanceOf: SubstituteException, message: /Arg\.all\(\).*last argument/ }) +}) + +test('A:RT-6 received(n).method(Arg.all()) does not count property reads of the method', t => { + const callbacks = substitute() + if (callbacks.onDone) callbacks.onDone(1) + + t.notThrows(() => callbacks.received(1).onDone(1)) + t.notThrows(() => callbacks.received(1).onDone(Arg.all())) + t.notThrows(() => callbacks.received(1).onDone(Arg.any())) + t.notThrows(() => callbacks.received(1).onDone) +}) + +test('G:RG-1 symbol assertions on a member named returns/throws/resolves/rejects/mimicks are always assertions', t => { + for (const name of ['returns', 'throws', 'resolves', 'rejects', 'mimicks']) { + const neverRead = substitute() + t.throws(() => neverRead[received](1)[name], { instanceOf: SubstituteException }, name) + t.notThrows(() => neverRead[didNotReceive]()[name], name) + + const readOnce = substitute() + void readOnce[name] + t.notThrows(() => readOnce[received](1)[name], name) + t.throws(() => readOnce[received](3)[name], { instanceOf: SubstituteException }, name) + t.throws(() => readOnce[didNotReceive]()[name], { instanceOf: SubstituteException }, name) + + // the assertion did not configure anything + t.true(types.isProxy(readOnce.received(1)), name) + + // the same for method calls: an assertion never turns into a substitution + const calledOnce = substitute() + calledOnce[name](1) + t.throws(() => calledOnce[received](1)[name](2), { instanceOf: SubstituteException }, name) + t.throws(() => calledOnce[didNotReceive]()[name](1), { instanceOf: SubstituteException }, name) + t.notThrows(() => calledOnce[received](1)[name](1), name) + t.true(types.isProxy(calledOnce[name](3)), name) + t.notThrows(() => calledOnce[received](2)[name](Arg.any()), name) + } +}) + +test('G:RG-5 a nested member named received is an ordinary member, and nested assertions check the nested node', t => { + // code under test reading `received` on an unconfigured recursive auto-substitute + const inbox = substitute() + t.is(typeof inbox.latest.received.getTime(), 'function') + t.is(typeof inbox.lastMessage.received.toISOString(), 'function') + const configured = substitute() + configured.latest.received.returns(new Date(0)) + t.is(configured.latest.received.getTime(), 0) + + // root getTime() was called: the nested chain still returns an auto-substitute + const withRootCall = substitute() + withRootCall.getTime() + t.true(types.isProxy(withRootCall.x.y.received.getTime())) + + // nested assertions + const child = substitute() + child.child.save() + t.notThrows(() => child.child.received().save()) + const repository = substitute() + const user = repository.getUser(1) + user.save() + t.notThrows(() => user.received().save()) + t.notThrows(() => repository.getUser(1).received(1).save()) + const rootOnly = substitute() + rootOnly.save() + t.throws(() => rootOnly.child.received().save(), { instanceOf: SubstituteException }) +}) + +test('G:RG-8 two separately loaded copies of the package interoperate', t => { + const sourceDirectory = path.dirname(require.resolve('../../../src')) + const isOwnModule = (file: string) => file.startsWith(sourceDirectory + path.sep) + const cached = Object.keys(require.cache).filter(isOwnModule).map(file => [file, require.cache[file]] as const) + t.true(cached.length > 0) + + let copy: typeof library + try { + for (const [file] of cached) delete require.cache[file] + copy = require('../../../src') + } finally { + for (const [file] of Object.keys(require.cache).filter(isOwnModule).map(file => [file] as const)) delete require.cache[file] + for (const [file, module] of cached) require.cache[file] = module + } + + t.not(copy.Substitute, library.Substitute) + t.is(copy.received, library.received) + + const calculator: any = library.Substitute.for() + calculator.add(1) + t.throws(() => calculator[copy.received](2).add(1), { instanceOf: SubstituteException }) + t.notThrows(() => calculator[copy.received](1).add(1)) + + calculator[copy.clearReceivedCalls]() + t.notThrows(() => calculator.didNotReceive().add(1)) + + calculator.value()[copy.returns](5) + t.is(calculator.value(), 5) + calculator[copy.configure]().value().returns(6) + t.is(calculator.value(), 6) + + calculator.find(copy.Arg.any('number')).returns('found') + t.is(calculator.find(1), 'found') + t.notThrows(() => calculator.received(1).find(copy.Arg.all())) + + const fromCopy: any = copy.Substitute.for() + t.true(Arg.any('object').matches(fromCopy)) + calculator.register(fromCopy) + t.notThrows(() => calculator.received(1).register(fromCopy)) + t.throws(() => calculator.received(1).register(library.Substitute.for()), { instanceOf: SubstituteException }) +}) From 88094783cf73d07df5514571cd344d4e06af4366 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 11:43:04 +0000 Subject: [PATCH 029/106] test: port engine A's wording-dependent tests with this engine's wording A:RT-3 (unchanged: the read-without-call hint now matches), A:RT-8, A:RT-9, A:RT-12, A:RT-13, D9 (decided when the member is read, with the clearReceivedCalls hint), D11 (invalid counts, including received(Arg.any()) followed by a member access), D18 and R:RT-6, in spec/regression/fixes/ported-from-a-messages.spec.ts. The expected texts are this engine's. Engine A's D18 check that pinned its strict D9 (received(2).add on an only-invoked member thrown at once) now checks the amended D9 report on process.nextTick instead. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .../fixes/ported-from-a-messages.spec.ts | 209 ++++++++++++++++++ 1 file changed, 209 insertions(+) create mode 100644 spec/regression/fixes/ported-from-a-messages.spec.ts diff --git a/spec/regression/fixes/ported-from-a-messages.spec.ts b/spec/regression/fixes/ported-from-a-messages.spec.ts new file mode 100644 index 0000000..c3102e5 --- /dev/null +++ b/spec/regression/fixes/ported-from-a-messages.spec.ts @@ -0,0 +1,209 @@ +import test, { ExecutionContext } from 'ava' +import * as fakeTimers from '@sinonjs/fake-timers' +import { EventEmitter } from 'events' +import { inspect, types } from 'util' + +import { Substitute, Arg, received, clearReceivedCalls } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' + +/* + * The tests of the other round-1 engine (branch fix/engine-a) that depend on its message wording, ported with + * this engine's wording (see ported-from-a.spec.ts for the ones ported unchanged). Every check is kept, except + * where engine A pinned its strict D9 (a property-style failure on a member that was only invoked thrown at once): + * the amended D9 reports that case on process.nextTick, and the ported check says so. + */ + +const plain = (message: string) => message.replace(/\x1b\[\d+m/g, '') +const withoutCallSites = (message: string) => plain(message).split('\n').filter(line => !line.includes('called at')).join('\n') +// runtime behaviour only: the substitutes are untyped so that the specs do not depend on the typings +const substitute = (): any => Substitute.for() + +/** The message of a failure that is only reported on process.nextTick; nothing may be thrown before. */ +const messageOnNextTick = (cb: () => unknown, t: ExecutionContext): string => { + const clock = fakeTimers.install({ toFake: ['nextTick'] }) + try { + t.notThrows(cb) + return plain(t.throws(() => clock.tick(1), { instanceOf: SubstituteException }).message) + } finally { + clock.uninstall() + } +} + +test('A:RT-3 a method that was only read is not a received method call', t => { + const handler = substitute() + new EventEmitter().on('click', handler.onClick) + + t.throws(() => handler.received().onClick(42), { instanceOf: SubstituteException }) + t.throws(() => handler.received(1).onClick(42), { instanceOf: SubstituteException }) + const { message } = t.throws(() => handler.received(1).onClick('x', 1), { instanceOf: SubstituteException }) + t.true(plain(message).includes('Expected to receive 1 method call matching onClick(\'x\', 1), but received none.')) + t.true(plain(message).includes('was read 1 time without being called')) + + // once the reads are cleared, didNotReceive().onClick(...) is a method assertion (see the D9 spec for why it is not before) + handler[clearReceivedCalls]() + t.notThrows(() => handler.didNotReceive().onClick(42)) +}) + +test('A:RT-8 mutually referencing substitutes give a SubstituteException, not a stack overflow', t => { + const parent = substitute() + const child = substitute() + parent.addChild(child) + child.setParent(parent) + + const { message } = t.throws(() => parent.received().addChild(parent), { instanceOf: SubstituteException }) + t.true(withoutCallSites(message).includes('› ✘ @Substitute.addChild(@Substitute)')) + t.notThrows(() => parent.received().addChild(child)) + + const self = substitute() + self.link(self) + t.throws(() => self.received().link(2), { instanceOf: SubstituteException }) + t.notThrows(() => self.received(1).link(self)) + // wording: this engine prints the received calls of a substitute under "received:" + t.regex(inspect(self), /@Substitute \{\n {2}received:\n {4}link\(@Substitute\)\n\}/) + + const value: { self?: unknown } = {} + const holder = substitute() + value.self = holder + holder.take(value) + const { message: objectMessage } = t.throws(() => holder.received().take(5), { instanceOf: SubstituteException }) + t.true(withoutCallSites(objectMessage).includes('@Substitute.take({ self: @Substitute })')) + t.notThrows(() => holder.received().take({ self: holder })) +}) + +test('A:RT-9 a never-called method is not reported as "property calls"; expected arguments are included when known', t => { + const calculator = substitute() + const { message } = t.throws(() => calculator.received(3).add(1, Arg.any()), { instanceOf: SubstituteException }) + t.false(plain(message).includes('property call')) + // wording: decided when add is read (D9), before the arguments are known, so both kinds are named + t.is(plain(message), 'Call count mismatch in @Substitute.add:\nExpected to receive 3 property reads or method calls matching add, but received none.') + + calculator.multiply(7, 8) + const { message: withArguments } = t.throws(() => calculator.received(1).multiply(7, Arg.is((x: number) => x > 8)), { instanceOf: SubstituteException }) + t.true(plain(withArguments).startsWith( + 'Call count mismatch in @Substitute.multiply:\n' + + 'Expected to receive 1 method call matching multiply(7, Arg.is{(x) => x > 8}), but received none.\n' + + 'All property or method calls to @Substitute.multiply received so far:\n' + + '› ✘ @Substitute.multiply(7, 8)' + )) + + calculator.isEnabled = true + const { message: setMessage } = t.throws(() => { calculator.received(1).isEnabled = false }, { instanceOf: SubstituteException }) + t.true(plain(setMessage).startsWith( + 'Call count mismatch in @Substitute.isEnabled:\n' + + 'Expected to receive 1 property assignment matching isEnabled = false, but received none.\n' + + 'All property assignments to @Substitute.isEnabled received so far:\n' + + '› ✘ @Substitute.isEnabled = true' + )) +}) + +test('A:RT-12 failing assertions with recorded calls build their message when Error.stackTraceLimit is 0 (D18)', t => { + const limit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + const calculator = substitute() + calculator.add(1, 2) + const { message } = t.throws(() => calculator.received().add(9, 9), { instanceOf: SubstituteException }) + t.is(plain(message), 'Call count mismatch in @Substitute.add:\n' + + 'Expected to receive 1 or more method calls matching add(9, 9), but received none.\n' + + 'All property or method calls to @Substitute.add received so far:\n' + + '› ✘ @Substitute.add(1, 2)\n') + } finally { + Error.stackTraceLimit = limit + } +}) + +test('A:RT-13 Arg.is() with a predicate that is not a function throws a TypeError right away (D17)', t => { + for (const predicate of [undefined, null, 5, 'x', {}, Object.create(null)]) { + t.throws(() => Arg.is(predicate as any), { instanceOf: TypeError, message: /Arg\.is expects a predicate function/ }) + t.throws(() => Arg.is.not(predicate as any), { instanceOf: TypeError, message: /Arg\.is expects a predicate function/ }) + } +}) + +test('D9 a property-style assertion is decided when the member is read; reading a method fails didNotReceive() on it', t => { + // A never-invoked member that was read cannot be told apart from a property: the assertion is decided when it is + // read (synchronously), so didNotReceive().onClick(...) fails after onClick was only read (e.g. to register it as a + // callback). Clearing the received calls after reading it is the way to assert it is never invoked. + const handler = substitute() + const callback = handler.onClick + const { message } = t.throws(() => handler.didNotReceive().onClick(42), { instanceOf: SubstituteException }) + t.true(plain(message).includes('Expected to receive 0 property reads matching onClick, but received 1.')) + t.true(plain(message).includes('Call sub[clearReceivedCalls]() after the arrange step to reset the reads.')) + + handler[clearReceivedCalls]() + t.notThrows(() => handler.didNotReceive().onClick(42)) + callback(42) + t.throws(() => handler.didNotReceive().onClick(42), { instanceOf: SubstituteException }) + t.notThrows(() => handler.didNotReceive().onClick(43)) + + // "1 or more" is satisfied by a property read as well as by an invocation of the member + const component = substitute() + component.render() + t.notThrows(() => component.received().render) + t.notThrows(() => component.received().render()) +}) + +test('D11 the string received/didNotReceive is the assertion API only when invoked and followed by a member access', t => { + const message = substitute() + t.is(typeof message.received.getTime(), 'function') + t.true(types.isProxy(message.received.x.y)) + message.didNotReceive.value = 1 + + const overlapping = substitute() + overlapping.received(10).returns('ten') + overlapping.didNotReceive().returns('nothing') + t.is(overlapping.received(10), 'ten') + t.is(overlapping.didNotReceive(), 'nothing') + t.notThrows(() => overlapping[received](1).received(10)) + t.notThrows(() => overlapping[received](1).didNotReceive()) + + const calculator = substitute() + calculator.add(1) + t.notThrows(() => calculator.received(1).add(1)) + t.throws(() => calculator.received(2).add(1), { instanceOf: SubstituteException }) + // wording: "Expected count has to be a non-negative integer (or omitted for "1 or more"), but received ..." + t.throws(() => calculator.received('x').add(1), { instanceOf: SubstituteException, message: /non-negative integer/ }) + t.throws(() => calculator.received(Arg.any()).add(1), { instanceOf: SubstituteException, message: /non-negative integer/ }) + t.notThrows(() => calculator.didNotReceive(Arg.any()).add(2)) + t.notThrows(() => { calculator.didNotReceive(Arg.any()).value = 1 }) + t.throws(() => { calculator.received(Arg.any()).value = 1 }, { instanceOf: SubstituteException, message: /non-negative integer/ }) + t.notThrows(() => calculator.didNotReceive().received) +}) + +test('D18 messages: kind-neutral wording when the kind is unknown, expected arguments when known', t => { + const calculator = substitute() + calculator.add(1, 2) + void calculator.total + + t.is(plain(t.throws(() => calculator.received(2).total)!.message).split('\n')[1], 'Expected to receive 2 property reads matching total, but received 1.') + // amended D9: add was only invoked, so a property-style failure is reported on process.nextTick (engine A threw it + // at once) and says that add was called as a method + t.is(messageOnNextTick(() => calculator.received(2).add, t).split('\n')[1], + 'Expected to receive 2 property reads matching add, but received none. ' + + 'add was never read as a property; it was called 1 time as a method. To assert calls, invoke it: sub.received(2).add(...)') + t.is(plain(t.throws(() => calculator.received().missing)!.message).split('\n')[1], 'Expected to receive 1 or more property reads or method calls matching missing, but received none.') + t.is(plain(t.throws(() => calculator.received(1).add(1, Arg.any('string')))!.message).split('\n')[1], 'Expected to receive 1 method call matching add(1, Arg.any{string}), but received none.') + t.is(plain(t.throws(() => calculator.received(0).add(1, 2))!.message).split('\n')[1], 'Expected to receive 0 method calls matching add(1, 2), but received 1.') + + const many = substitute() + for (let index = 0; index < 60; index++) many.log(index) + const { message } = t.throws(() => many.received(1).log('x'), { instanceOf: SubstituteException }) + t.true(plain(message).includes('› … and 10 more')) +}) + +interface Repository { add(a: number, b: number): number } + +test('R:RT-6 received() with an invalid count throws synchronously', t => { + for (const count of [-1, 1.5, NaN, Infinity, -Infinity, Number.MAX_SAFE_INTEGER + 1, '2', null, {}]) { + const repository = substitute() + // wording: "Expected count has to be a non-negative integer (or omitted for "1 or more"), but received ..." + t.throws(() => repository.received(count as any).add(1, 2), { instanceOf: SubstituteException, message: /non-negative integer/ }, String(count)) + t.throws(() => repository[received](count as any), { instanceOf: SubstituteException, message: /non-negative integer/ }, String(count)) + } + + const repository = substitute() + repository.add(1, 2) + t.notThrows(() => repository.received(1).add(1, 2)) + t.notThrows(() => repository.received(undefined).add(1, 2)) + t.notThrows(() => repository.received(0).add(2, 1)) + t.throws(() => repository.received(0).add(1, 2), { instanceOf: SubstituteException }) +}) From aa65ad9b2485b8b113fa87197c5f9d0033a78710 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:00:08 +0000 Subject: [PATCH 030/106] fix(assertions): D33 deferred report for property-style didNotReceive().m, D34 captured nextTick, D36 kind-neutral read failure - didNotReceive().m / received(0).m on a member that was only invoked, and is not invoked right after, gets a cancellable deferred report (ENG2-13). - Deferred reports use the process.nextTick captured at module load, so fake timers installed later cannot swallow them (ENG2-14). The tests run the reports through an internal seam instead of faking nextTick. - received(n).m on a member that was only read, with n above the reads, fails kind-neutrally and carries the read-without-call hint (V2-3). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/helpers/deferredReports.ts | 32 +++++ spec/regression/fixes/amendments.test.ts | 12 +- spec/regression/fixes/decisions.test.ts | 9 +- .../fixes/ported-from-a-messages.spec.ts | 8 +- spec/regression/fixes/ported-from-a.spec.ts | 14 +- spec/regression/fixes/round3.test.ts | 121 ++++++++++++++++++ spec/regression/issues/178.test.ts | 4 +- src/internals/Assertions.ts | 73 ++++++++--- 8 files changed, 240 insertions(+), 33 deletions(-) create mode 100644 spec/helpers/deferredReports.ts create mode 100644 spec/regression/fixes/round3.test.ts diff --git a/spec/helpers/deferredReports.ts b/spec/helpers/deferredReports.ts new file mode 100644 index 0000000..2ba0749 --- /dev/null +++ b/spec/helpers/deferredReports.ts @@ -0,0 +1,32 @@ +import { deferredReports } from '../../src/internals/Assertions' + +/** + * Runs the library's deferred reports (D9, D33) on demand instead of on process.nextTick. + * + * Since D34 the library captures the real process.nextTick when it is loaded, so fake timers installed by a test + * no longer intercept the reports. The tests use this stand-in, which has the same shape as the fake clock they + * used before: `tick()` runs the reports scheduled so far and rethrows the first one that throws. + */ +export const interceptDeferredReports = () => { + const original = deferredReports.schedule + let queue: Array<() => void> = [] + deferredReports.schedule = callback => { queue.push(callback) } + return { + tick(_milliseconds?: number): void { + const scheduled = queue + queue = [] + let failure: { error: unknown } | undefined + for (const callback of scheduled) { + try { + callback() + } catch (error) { + if (failure === undefined) failure = { error } + } + } + if (failure !== undefined) throw failure.error + }, + uninstall(): void { + deferredReports.schedule = original + } + } +} diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index a577e28..efba667 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -1,5 +1,5 @@ import test from 'ava' -import * as fakeTimers from '@sinonjs/fake-timers' +import { interceptDeferredReports } from '../../helpers/deferredReports' import { EventEmitter } from 'events' import { inspect, types } from 'util' @@ -215,16 +215,20 @@ test('hint: a failed method assertion says when the method was read without bein t.true(messageOf(() => app.logger.received(2).flush()).includes(hint('@Substitute.logger.flush', '1 time'))) t.true(messageOf(() => app.logger.received(1).flush(1)).includes(hint('@Substitute.logger.flush', '1 time'))) - // no hint when there were no reads, when there were too many calls, or for a member that is only a property + // no hint when there were no reads, or when there were too many calls const calculator = Substitute.for() calculator.add(1) t.false(messageOf(() => calculator.received(2).add(1)).includes('without being called')) t.false(messageOf(() => app.logger.didNotReceive().flush()).includes('without being called')) + // D36 (round 3): a member that was only read, with a count above the reads, may be a method (the failure is + // decided at the read), so it gets the hint too; with fewer expected reads it is a property failure without it const settings = Substitute.for() void settings.flag const property = messageOf(() => settings.received(2).flag) - t.false(property.includes('without being called')) + t.true(property.includes(hint('@Substitute.flag', '1 time'))) t.false(property.includes('never called')) + void settings.flag + t.false(messageOf(() => settings.received(1).flag).includes('without being called')) }) test('hint: didNotReceive() on a member that was only read points to clearReceivedCalls (A:RT-3 residual)', t => { @@ -254,7 +258,7 @@ test('hint: didNotReceive() on a member that was only read points to clearReceiv /** The message of a failure that is only reported on process.nextTick (D9); asserts that nothing is thrown before. */ const deferredMessageOf = (t: any, assertion: () => unknown): string => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() try { t.notThrows(assertion, 'nothing is thrown synchronously') const error = t.throws(() => clock.tick(1), { instanceOf: SubstituteException }) as SubstituteException diff --git a/spec/regression/fixes/decisions.test.ts b/spec/regression/fixes/decisions.test.ts index e398005..e19da8f 100644 --- a/spec/regression/fixes/decisions.test.ts +++ b/spec/regression/fixes/decisions.test.ts @@ -1,5 +1,5 @@ import test, { ExecutionContext, ThrowsExpectation } from 'ava' -import * as fakeTimers from '@sinonjs/fake-timers' +import { interceptDeferredReports } from '../../helpers/deferredReports' import { inspect, types } from 'util' import { Substitute, Arg, received, didNotReceive, clearReceivedCalls, mimick, configure, returns } from '../../../src' @@ -8,7 +8,7 @@ import { SubstituteException } from '../../../src/internals/SubstituteException' const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') const throwsUncaughtException = (callback: () => unknown, t: ExecutionContext, expectation: ThrowsExpectation) => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() try { callback() t.throws(() => clock.tick(1), expectation) @@ -18,7 +18,7 @@ const throwsUncaughtException = (callback: () => unknown, t: ExecutionContext, e } const doesNotThrowLater = (callback: () => unknown, t: ExecutionContext) => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() try { callback() t.notThrows(() => clock.tick(1)) @@ -292,7 +292,8 @@ test('D18 assertion messages', t => { t.regex(plain(setError.message), /Expected to receive 2 property assignments matching isEnabled = true, but received 1\./) t.regex(plain(setError.message), /› ✔ @Substitute\.isEnabled = true/) const readError = t.throws(() => substitute.received(2).mode, { instanceOf: SubstituteException }) - t.regex(plain(readError.message), /Expected to receive 2 property reads matching mode, but received 1\./) + // D36 (round 3): mode was only read, with a count above the reads, so the failure is kind-neutral + t.regex(plain(readError.message), /Expected to receive 2 property reads or method calls matching mode, but received 1 property read and no method calls\./) t.false(plain(readError.message).includes('property calls')) substitute(1, 2) diff --git a/spec/regression/fixes/ported-from-a-messages.spec.ts b/spec/regression/fixes/ported-from-a-messages.spec.ts index c3102e5..f9fea20 100644 --- a/spec/regression/fixes/ported-from-a-messages.spec.ts +++ b/spec/regression/fixes/ported-from-a-messages.spec.ts @@ -1,5 +1,5 @@ import test, { ExecutionContext } from 'ava' -import * as fakeTimers from '@sinonjs/fake-timers' +import { interceptDeferredReports } from '../../helpers/deferredReports' import { EventEmitter } from 'events' import { inspect, types } from 'util' @@ -20,7 +20,7 @@ const substitute = (): any => Substitute.for() /** The message of a failure that is only reported on process.nextTick; nothing may be thrown before. */ const messageOnNextTick = (cb: () => unknown, t: ExecutionContext): string => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() try { t.notThrows(cb) return plain(t.throws(() => clock.tick(1), { instanceOf: SubstituteException }).message) @@ -174,7 +174,9 @@ test('D18 messages: kind-neutral wording when the kind is unknown, expected argu calculator.add(1, 2) void calculator.total - t.is(plain(t.throws(() => calculator.received(2).total)!.message).split('\n')[1], 'Expected to receive 2 property reads matching total, but received 1.') + // D36 (round 3): total was only read, with a count above the reads, so it fails for both readings + t.is(plain(t.throws(() => calculator.received(2).total)!.message).split('\n')[1], + 'Expected to receive 2 property reads or method calls matching total, but received 1 property read and no method calls.') // amended D9: add was only invoked, so a property-style failure is reported on process.nextTick (engine A threw it // at once) and says that add was called as a method t.is(messageOnNextTick(() => calculator.received(2).add, t).split('\n')[1], diff --git a/spec/regression/fixes/ported-from-a.spec.ts b/spec/regression/fixes/ported-from-a.spec.ts index 6ee74b8..bd6c9f1 100644 --- a/spec/regression/fixes/ported-from-a.spec.ts +++ b/spec/regression/fixes/ported-from-a.spec.ts @@ -1,5 +1,5 @@ import test, { ExecutionContext, ThrowsExpectation } from 'ava' -import * as fakeTimers from '@sinonjs/fake-timers' +import { interceptDeferredReports } from '../../helpers/deferredReports' import { EventEmitter } from 'events' import * as path from 'path' import { inspect, types } from 'util' @@ -29,7 +29,7 @@ const plain = (message: string) => message.replace(/\x1b\[\d+m/g, '') const substitute = (): any => Substitute.for() const throwsOnNextTick = (cb: () => unknown, t: ExecutionContext, expectation: ThrowsExpectation) => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() try { cb() t.throws(() => clock.tick(1), expectation) @@ -39,7 +39,7 @@ const throwsOnNextTick = (cb: () => unknown, t: ExecutionContext, expectation: T } const doesNotThrowOnNextTick = (cb: () => unknown, t: ExecutionContext) => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() try { cb() t.notThrows(() => clock.tick(1)) @@ -281,8 +281,12 @@ test('D7 each invocation is its own record, also through stored references, call t.notThrows(() => logger.received(7).log(Arg.all())) for (const value of [1, 2, 3, 4, 5]) t.notThrows(() => logger.received(1).log(value)) t.notThrows(() => logger.received(1).log(6, 0, [6, 7])) - // every read of `log` above was followed by invocations: none of them is a property read - t.notThrows(() => logger.received(0).log) + // every read of `log` above was followed by invocations: none of them is a property read. Since D33 (round 3) the + // property-style received(0).log on a member that was only invoked is reported later, and the report says so. + throwsOnNextTick(() => logger.received(0).log, t, { + instanceOf: SubstituteException, + message: /but received 7 method calls\. log was called 7 times as a method/ + }) const guard = substitute() if (guard.onDone) guard.onDone(1) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts new file mode 100644 index 0000000..d06b5ae --- /dev/null +++ b/spec/regression/fixes/round3.test.ts @@ -0,0 +1,121 @@ +import test, { ExecutionContext } from 'ava' +import { spawnSync } from 'child_process' +import * as path from 'path' + +import { Substitute, Arg } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' +import { interceptDeferredReports } from '../../helpers/deferredReports' + +// Round 3: the runtime findings of the round-2 verification (ENG2-*, V2-*), decided in the fix spec as D25-D36. + +const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') +const withoutCallSites = (message: string) => plain(message).split('\n').filter(line => !line.includes('called at')).join('\n') + +const messageOf = (assertion: () => unknown): string => { + try { + assertion() + } catch (error) { + if (!(error instanceof SubstituteException)) throw error + return withoutCallSites(error.message) + } + throw new Error('expected the assertion to fail') +} + +/** The message of a failure that is only reported later (D9, D33); asserts that nothing is thrown before. */ +const deferredMessageOf = (t: ExecutionContext, assertion: () => unknown): string => { + const clock = interceptDeferredReports() + try { + t.notThrows(assertion, 'nothing is thrown synchronously') + return withoutCallSites(t.throws(() => clock.tick(), { instanceOf: SubstituteException }).message) + } finally { + clock.uninstall() + } +} + +const reportsNothingLater = (t: ExecutionContext, run: () => unknown) => { + const clock = interceptDeferredReports() + try { + run() + t.notThrows(() => clock.tick()) + } finally { + clock.uninstall() + } +} + +test('ENG2-13 (D33) a property-style didNotReceive().m on a member that was only invoked is reported later', t => { + const logger = Substitute.for() + logger.error('disk full') + const message = deferredMessageOf(t, () => logger.didNotReceive().error) + t.is(message.split('\n')[1], + 'Expected to receive 0 property reads or method calls matching error, but received 1 method call. ' + + 'error was called 1 time as a method; to assert calls, invoke it: sub.didNotReceive().error(...)') + t.true(message.includes("\n› ✘ @Substitute.error('disk full')")) + + // received(0) is didNotReceive(), also on nested substitutes and with several calls + const app = Substitute.for() + app.logger.warn(1) + app.logger.warn(2) + t.true(deferredMessageOf(t, () => app.logger.received(0).warn) + .includes('warn was called 2 times as a method; to assert calls, invoke it: sub.logger.didNotReceive().warn(...)')) + + // invoking the member right away cancels the report: the method assertion decides + reportsNothingLater(t, () => t.notThrows(() => logger.didNotReceive().error('other'))) + reportsNothingLater(t, () => t.throws(() => logger.didNotReceive().error('disk full'), { instanceOf: SubstituteException })) + reportsNothingLater(t, () => t.notThrows(() => logger.didNotReceive().error(Arg.is((text: string) => text.startsWith('x'))))) + + // nothing to report for members that were never touched, or that are properties + const settings = Substitute.for() + reportsNothingLater(t, () => t.notThrows(() => settings.didNotReceive().flag)) + settings.flag = 1 + reportsNothingLater(t, () => t.notThrows(() => settings.didNotReceive().flag)) +}) + +test('ENG2-14 (D34) deferred reports are not swallowed by fake timers installed after the library was loaded', t => { + const library = path.resolve(__dirname, '../../../src/index.js') + const fakeTimers = require.resolve('@sinonjs/fake-timers') + const script = ` + const { Substitute } = require(${JSON.stringify(library)}) + const FakeTimers = require(${JSON.stringify(fakeTimers)}) + const clock = FakeTimers.install({ toFake: ['nextTick', 'setTimeout', 'setImmediate', 'queueMicrotask'] }) + process.on('uncaughtException', error => { + console.log('reported: ' + error.constructor.name + ': ' + error.message.split('\\n')[1]) + }) + const calculator = Substitute.for() + calculator.add(1, 2) + calculator.add(1, 2) + calculator.add(3, 4) + calculator.received(2).add + console.log('nothing thrown synchronously; the fake clock is never advanced') + ` + const result = spawnSync(process.execPath, ['-e', script], { encoding: 'utf8', env: { ...process.env, NO_COLOR: '1' } }) + t.is(result.stderr, '') + t.is(result.stdout, + 'nothing thrown synchronously; the fake clock is never advanced\n' + + 'reported: SubstituteException: Expected to receive 2 property reads matching add, but received none. ' + + 'add was never read as a property; it was called 3 times as a method. To assert calls, invoke it: sub.received(2).add(...)\n') +}) + +test('V2-3 (D36) received(n).m(...) on a method that was only read gives a kind-neutral failure with the read hint', t => { + const handler = Substitute.for() + const registered = handler.onClick + t.is(typeof registered, 'function') + + const message = messageOf(() => handler.received(2).onClick(42)) + const lines = message.split('\n') + t.is(lines[1], 'Expected to receive 2 property reads or method calls matching onClick, but received 1 property read and no method calls.') + t.is(lines[3], '› ✘ @Substitute.onClick') + t.true(message.endsWith('\n@Substitute.onClick was read 1 time without being called; reading a method does not count as calling it.\n')) + + // the same failure for the property-style form (it is decided at the read) and on nested substitutes + const app = Substitute.for() + void app.view.render + void app.view.render + const nested = messageOf(() => app.view.received(3).render) + t.true(nested.includes('Expected to receive 3 property reads or method calls matching render, but received 2 property reads and no method calls.')) + t.true(nested.includes('@Substitute.view.render was read 2 times without being called')) + + // unchanged: fewer expected reads than received is a property failure without the hint + const fewer = messageOf(() => app.view.received(1).render) + t.true(fewer.includes('Expected to receive 1 property read matching render, but received 2.')) + t.false(fewer.includes('without being called')) +}) diff --git a/spec/regression/issues/178.test.ts b/spec/regression/issues/178.test.ts index 080392e..1b73a28 100644 --- a/spec/regression/issues/178.test.ts +++ b/spec/regression/issues/178.test.ts @@ -1,5 +1,5 @@ import test, { ExecutionContext, ThrowsExpectation } from 'ava' -import * as fakeTimers from '@sinonjs/fake-timers' +import { interceptDeferredReports } from '../../helpers/deferredReports' import { types } from 'util' import { Substitute } from '../../../src' @@ -16,7 +16,7 @@ interface Subsection { } const throwsUncaughtException = (cb: () => any, t: ExecutionContext, expectation: ThrowsExpectation) => { - const clock = fakeTimers.install({ toFake: ['nextTick'] }) + const clock = interceptDeferredReports() cb() t.throws(() => clock.tick(1), expectation) clock.uninstall() diff --git a/src/internals/Assertions.ts b/src/internals/Assertions.ts index f79e20b..3b569f3 100644 --- a/src/internals/Assertions.ts +++ b/src/internals/Assertions.ts @@ -115,12 +115,32 @@ export type DeferredAssertion = { settled: boolean } -const schedule = (callback: () => void) => { - // Looked up on every call so that fake timers (e.g. @sinonjs/fake-timers) can intercept it. - if (typeof process !== 'undefined' && typeof process.nextTick === 'function') process.nextTick(callback) - else setTimeout(callback, 0) +type Schedule = (callback: () => void) => void + +/** + * D34: the scheduler of deferred reports is captured when the library is loaded, so that fake timers installed + * later (jest.useFakeTimers(), @sinonjs/fake-timers faking nextTick) cannot swallow a report. Fake timers that are + * installed before the library is loaded can still delay it. + */ +const captureSchedule = (): Schedule => { + if (typeof process !== 'undefined' && process !== null && typeof process.nextTick === 'function') { + const nextTick = process.nextTick + return callback => { nextTick.call(process, callback) } + } + if (typeof setImmediate === 'function') { + const immediate = setImmediate + return callback => { immediate(callback) } + } + const timeout = setTimeout + return callback => { timeout(callback, 0) } } +/** + * Where deferred reports are scheduled. Not part of the public API: the library's own tests replace `schedule` + * to run the reports on demand. + */ +export const deferredReports: { schedule: Schedule } = { schedule: captureSchedule() } + /** Stops a deferred property assertion from being thrown (the access turned out to be a method assertion). */ export const settle = (deferred: DeferredAssertion | undefined): void => { if (deferred !== undefined) deferred.settled = true @@ -143,6 +163,9 @@ export const settle = (deferred: DeferredAssertion | undefined): void => { * whose message needs the arguments. The failure is scheduled on process.nextTick and cancelled as soon * as the member is invoked; only a property-style assertion that is never invoked reports it there. * For a member that was only invoked, the report says so and shows the method assertion to write instead. + * - D33: a property-style `didNotReceive().m` / `received(0).m` on a member that was only invoked holds as a + * property assertion, but is most likely a method assertion whose parentheses were forgotten. It gets the same + * cancellable deferred report. */ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, count: ExpectedCount, stackStart?: Function): DeferredAssertion | undefined => { const records = state.recordsFor(key).filter(record => record.kind !== 'set') @@ -152,30 +175,50 @@ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, cou if (record.kind === 'get') reads++ else calls++ } - if (countMatches(count, reads)) return undefined + if (countMatches(count, reads)) { + if (count === 0 && reads === 0 && calls > 0) return defer(stackStart, () => SubstituteException.forCallCountMismatch({ + substitutePath: state.path, + key, + expected: { count, kind: 'unknown' }, + receivedText: `${calls} ${plural('method call', calls)}`, + explanation: `${keyToString(key)} was called ${times(calls)} as a method; ` + + `to assert calls, invoke it: ${asExpression(state)}.didNotReceive()${memberAccess(key)}(...)`, + listed: records.map((record: CallRecord) => ({ record, matches: false })) + })) + return undefined + } if (count === undefined && calls > 0) return undefined const deferrable = calls > 0 && count !== undefined && (count <= calls || reads === 0) + // D36: a member that was only read, with a count above the reads, fails as a property assertion and as a method + // assertion (no calls at all), and it is not known yet which one this is. + const onlyReadTooFew = calls === 0 && reads > 0 && count !== undefined && count > reads // A deferred failure is only thrown when the member was not invoked, so it is a property assertion. // An immediate failure fails for both readings; the kind is only named when the records show it. - const kind: ExpectedKind = deferrable || (calls === 0 && reads > 0) ? 'property' : 'unknown' + const kind: ExpectedKind = deferrable || (calls === 0 && reads > 0 && !onlyReadTooFew) ? 'property' : 'unknown' const createError = (start?: Function) => SubstituteException.forCallCountMismatch({ substitutePath: state.path, key, expected: { count, kind }, receivedText: kind === 'property' ? (reads === 0 ? 'none' : reads.toString()) : describeReceived(reads, calls), explanation: deferrable && reads === 0 ? onlyInvokedExplanation(state, key, calls, count!) : undefined, - listed: records.map((record: CallRecord) => ({ record, matches: record.kind === 'get' })), + listed: records.map((record: CallRecord) => ({ record, matches: record.kind === 'get' && !onlyReadTooFew })), hints: reads === 0 ? undefined : count === 0 && calls === 0 ? [onlyReadHint(state, key, reads)] - // invoked as well, so most likely a method, with fewer calls than expected - : calls > 0 && count !== undefined && calls < count ? [readWithoutCallHint(state, key, reads)] + // read but never invoked, or invoked as well: most likely a method, with fewer calls than expected + : onlyReadTooFew || (calls > 0 && count !== undefined && calls < count) ? [readWithoutCallHint(state, key, reads)] : undefined }, start) if (!deferrable) throw createError(stackStart) + return defer(stackStart, createError) +} - // The message is only built if the failure is really reported (usually the member is invoked right away). +/** + * Schedules a failure that is only reported if the assertion is not invoked (see assertPropertyRead). + * The message is only built if the failure is really reported (usually the member is invoked right away). + */ +const defer = (stackStart: Function | undefined, createError: () => SubstituteException): DeferredAssertion => { const site: { stack?: string } = {} if (typeof Error.captureStackTrace === 'function' && stackStart !== undefined) Error.captureStackTrace(site, stackStart) const deferred: DeferredAssertion = { @@ -187,7 +230,7 @@ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, cou return error } } - schedule(() => { + deferredReports.schedule(() => { if (deferred.settled) return deferred.settled = true throw deferred.error() @@ -195,10 +238,10 @@ export const assertPropertyRead = (state: SubstituteState, key: PropertyKey, cou return deferred } +/** What was received, for a failure that does not know yet whether it is about reads or calls. */ const describeReceived = (reads: number, calls: number): string => { if (reads === 0 && calls === 0) return 'none' - if (calls === 0) return reads.toString() - const readsText = `${reads} ${reads === 1 ? 'property read' : 'property reads'}` - const callsText = `${calls} ${calls === 1 ? 'method call' : 'method calls'}` - return `${readsText} and ${callsText}` + const readsText = `${reads} ${plural('property read', reads)}` + if (calls === 0) return `${readsText} and no method calls` + return `${readsText} and ${calls} ${plural('method call', calls)}` } From cf1c239420da5916ca720115a01ce391b9121b29 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:01:49 +0000 Subject: [PATCH 031/106] fix(engine): D28 unconfigured protocol keys read as undefined and are not recorded Well-known symbols (except Symbol.toPrimitive), util.promisify.custom and asymmetricMatch answer undefined unless they are configured through sub[configure]() or mimicked, so built-in algorithms, util.promisify and jest treat a substitute as a plain function or object (ENG2-6, ENG2-7). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 64 +++++++++++++++++++++++++++- src/internals/Constants.ts | 21 ++++++++- src/internals/Engine.ts | 11 ++++- 3 files changed, 93 insertions(+), 3 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index d06b5ae..dd58ee7 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -1,8 +1,9 @@ import test, { ExecutionContext } from 'ava' import { spawnSync } from 'child_process' import * as path from 'path' +import { inspect, promisify } from 'util' -import { Substitute, Arg } from '../../../src' +import { Substitute, Arg, configure, mimick } from '../../../src' import { SubstituteException } from '../../../src/internals/SubstituteException' import { interceptDeferredReports } from '../../helpers/deferredReports' @@ -42,6 +43,67 @@ const reportsNothingLater = (t: ExecutionContext, run: () => unknown) => { } } +test('ENG2-6 (D28) unconfigured well-known protocol symbols read as undefined and are not recorded', async t => { + const callback = Substitute.for() + t.is([].concat(callback).length, 1) + t.true([() => 1].concat(callback).includes(callback)) + const toArray = (value: any) => typeof value[Symbol.iterator] === 'function' ? [...value] : [value] + t.is(toArray(callback).length, 1) + t.is(Object.prototype.toString.call(callback), '[object Function]') + await t.throwsAsync(Promise.all(callback), { instanceOf: TypeError }) + + const deps = Substitute.for() + t.notThrows(() => 'https://x/a'.startsWith(deps.baseUrl)) + t.false(new Error() instanceof deps.HttpError) + for (const key of [Symbol.iterator, Symbol.asyncIterator, Symbol.hasInstance, Symbol.isConcatSpreadable, Symbol.match, + Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split, Symbol.species, Symbol.toStringTag, Symbol.unscopables, + promisify.custom]) + t.is(deps[key], undefined, String(key)) + t.is(deps.nested.member[Symbol.iterator], undefined) + t.is(deps.call(1)[Symbol.asyncIterator], undefined) + + const fs = Substitute.for() + fs.readFile(Arg.any(), Arg.any()).mimicks((file: string, done: Function) => done(null, `contents of ${file}`)) + t.is(await promisify(fs.readFile)('/etc/app.json'), 'contents of /etc/app.json') + fs.received(1).readFile('/etc/app.json', Arg.any('function')) + + // none of the probes is recorded + t.is(inspect(callback), '@Substitute {\n}') + t.notThrows(() => deps.didNotReceive()[Symbol.iterator]) + t.notThrows(() => deps.received(1).HttpError) + + // explicit configuration and mimicking still answer + const numbers = Substitute.for() + numbers[configure]()[Symbol.iterator]().returns([1, 2][Symbol.iterator]()) + t.deepEqual([...numbers], [1, 2]) + numbers.received(1)[Symbol.iterator]() + const tagged = Substitute.for() + tagged[configure]()[Symbol.toStringTag].returns('Tagged') + t.is(Object.prototype.toString.call(tagged), '[object Tagged]') + const list = Substitute.for() + list[mimick](['a', 'b']) + t.deepEqual([...list], ['a', 'b']) + const readFile = Substitute.for() + readFile[mimick]({ [promisify.custom]: async () => 'custom' }) + t.is(typeof readFile[promisify.custom], 'function') +}) + +test('ENG2-7 (D28) a substitute is not a jest asymmetric matcher unless asymmetricMatch is configured', t => { + // the check @jest/expect-utils uses to recognise asymmetric matchers + const isAsymmetric = (value: any) => !!value && typeof value.asymmetricMatch === 'function' + const logger = Substitute.for() + t.false(isAsymmetric(logger)) + t.false(isAsymmetric(logger.child)) + t.false(isAsymmetric(logger.create('x'))) + t.is(inspect(logger), '@Substitute {\n received:\n child\n create(\'x\')\n}') + + const matcher = Substitute.for() + matcher[configure]().asymmetricMatch(Arg.any()).returns(true) + t.true(isAsymmetric(matcher)) + t.true(matcher.asymmetricMatch(42)) + matcher.received(1).asymmetricMatch(42) +}) + test('ENG2-13 (D33) a property-style didNotReceive().m on a member that was only invoked is reported later', t => { const logger = Substitute.for() logger.error('disk full') diff --git a/src/internals/Constants.ts b/src/internals/Constants.ts index 491243d..80c00bb 100644 --- a/src/internals/Constants.ts +++ b/src/internals/Constants.ts @@ -55,7 +55,26 @@ export const isSpecialProperty = (property: PropertyKey): property is SpecialPro property === INTERNAL || property === substituteMarker -export const keyToString = (key: PropertyKey): string => typeof key === 'symbol' ? key.toString() : String(key) +/** + * D28: keys that built-in algorithms, Node and test runners read to probe what kind of value they are looking at + * (is it iterable, a RegExp, a promisify-able function, a jest asymmetric matcher, ...). An unconfigured read of + * one of them answers undefined and is not recorded, the same way `then` is handled, so that a substitute behaves + * like a plain function or object to those algorithms. Configuring the key (through sub[configure]()) or mimicking + * an instance that has it makes the read answer as usual. + */ +const wellKnownSymbols = Symbol as unknown as Record +const protocolKeys = new Set([ + // every well-known symbol except Symbol.toPrimitive, which is a special property (see isSpecialProperty); + // asyncIterator and matchAll are looked up by name because older runtimes do not have them + ...['iterator', 'asyncIterator', 'hasInstance', 'isConcatSpreadable', 'match', 'matchAll', 'replace', 'search', + 'split', 'species', 'toStringTag', 'unscopables'].map(name => wellKnownSymbols[name]), + Symbol.for('nodejs.util.promisify.custom'), + 'asymmetricMatch' +].filter(key => key !== undefined) as PropertyKey[]) + +export const isProtocolKey = (property: PropertyKey): boolean => protocolKeys.has(property) + +export const keyToString =(key: PropertyKey): string => typeof key === 'symbol' ? key.toString() : String(key) export const EXCEPTION = { callCountMismatch: 'CallCountMismatch', diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index dab16ca..5b9fb57 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -8,7 +8,7 @@ import { SubstituteException } from './SubstituteException' import { assertCall, assertPropertyRead, assertSet, settle, validateExpectedCount, ExpectedCount } from './Assertions' import { ContextMethod, FunctionHelperKey, INTERNAL, SELF, SpecialProperty, SubstitutionMethod, - contextMethodOf, isFunctionHelperKey, isSpecialProperty, isStringAssertionKey, keyToString, substitutionMethodOf + contextMethodOf, isFunctionHelperKey, isProtocolKey, isSpecialProperty, isStringAssertionKey, keyToString, substitutionMethodOf } from './Constants' import { formatArguments, formatValue, isPrinting, withPrintGuard } from './utilities' @@ -236,8 +236,17 @@ const execute = (substitution: Substitution, args?: any[]): any => { } } +/** D28: whether a protocol key is configured or mimicked, so that reading it answers as usual. */ +const answersProtocolKey = (state: SubstituteState, key: PropertyKey): boolean => + state.propertySubstitution(key) !== undefined || + state.hasCallSubstitutions(key) || + state.hasConfiguredPropertyEntry(key) || + (state.mimicked !== undefined && hasMember(state.mimicked.instance, key)) + /** A real property read by the code under test. */ const realGet = (state: SubstituteState, key: PropertyKey, chainPrevious: CallRecord | undefined, stackStart: Function): any => { + if (isProtocolKey(key) && !answersProtocolKey(state, key)) return undefined + const substitution = state.propertySubstitution(key) if (substitution !== undefined) { const record = state.addRecord('get', key, undefined, stackStart, chainPrevious) From 739be9001509c9ed5f7e7ec2e2fc9de3a71caf86 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:02:31 +0000 Subject: [PATCH 032/106] fix(engine): D32 methods of a property value run with the value as this A member configured both as a property and as a method returns a deferred handle; members read from it now bind functions to the resolved value, so size.toFixed(1), date.getTime() or map.get() work (ENG2-12). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 34 ++++++++++++++++++++++++++++ src/internals/Engine.ts | 8 +++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index dd58ee7..973810c 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -104,6 +104,40 @@ test('ENG2-7 (D28) a substitute is not a jest asymmetric matcher unless asymmetr matcher.received(1).asymmetricMatch(42) }) +test('ENG2-12 (D32) methods read from the value of a member configured as property and method run on that value', t => { + const sizes = Substitute.for() + sizes.size(Arg.any()).returns(10) + sizes.size.returns(3) + t.is(sizes.size.toFixed(1), '3.0') + t.is(sizes.size(1), 10) + + const dates = Substitute.for() + dates.when(Arg.all()).returns('x') + dates.when.returns(new Date(0)) + t.is(dates.when.getTime(), 0) + + const maps = Substitute.for() + maps.items(Arg.all()).returns([]) + maps.items.returns(new Map([['a', 1]])) + t.is(maps.items.get('a'), 1) + t.true(maps.items.has('a')) + + const names = Substitute.for() + names.name(1).returns('x') + names.name.returns('Ann') + t.is(names.name.toUpperCase(), 'ANN') + t.is(names.name.length, 3) + + // a substitute value records and resolves its own calls + const inner = Substitute.for() + inner.greet().returns('hi') + const outer = Substitute.for() + outer.child(1).returns(1) + outer.child.returns(inner) + t.is(outer.child.greet(), 'hi') + inner.received(1).greet() +}) + test('ENG2-13 (D33) a property-style didNotReceive().m on a member that was only invoked is reported later', t => { const logger = Substitute.for() logger.error('disk full') diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 5b9fb57..cec6eef 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -1,6 +1,6 @@ import { inspect, InspectOptions } from 'util' -import { substituteMarker } from '../shared' +import { isSubstituteProxy, substituteMarker } from '../shared' import { AutoEntry, Substitution, SubstituteState } from './SubstituteState' import { CallRecord, currentSequence, retract } from './CallRecord' import { RecordedArguments } from './RecordedArguments' @@ -415,7 +415,11 @@ const deferredRead = (state: SubstituteState, key: PropertyKey, record: CallReco } } if (isFunctionHelperKey(property)) return functionHelper(property, (args, start) => invoke(state, key, args, start, record)) - return resolve()[property] + // D32: a method of the property value runs with the value as `this`, as `value.method()` would + // (a substitute value records and resolves its own calls) + const resolved = resolve() + const member = resolved[property] + return typeof member === 'function' && !isSubstituteProxy(resolved) ? member.bind(resolved) : member }, set: function set(_target: unknown, property: PropertyKey, newValue: unknown) { resolve()[property] = newValue From 9042ed3eb846c7843c5a3e346469f9dbabcc8022 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:09:10 +0000 Subject: [PATCH 033/106] perf(engine): D35 structural hash for the auto-substitute cache and the literal-substitution index A structural hash consistent with util.isDeepStrictEqual (equal values always hash equal; cycles, throwing getters and oversized graphs fall back to one constant bucket) replaces the bounded fingerprints. Lookups by identity come first, so the same objects still find their entry after a mutation; a fresh object equal to a mutated setup argument no longer matches (amended D15). 10k unconfigured calls with nested objects, Buffers, long strings, long arrays, Maps, Sets or Dates, and 4000 object setups plus 4000 calls, now take well under 1s (ENG2-2, V2-5). Symbols are hashed by their description, so no process-global map keeps them alive (ENG2-10). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/amendments.test.ts | 5 +- spec/regression/fixes/round3-hashing.test.ts | 262 ++++++++++++++++++ src/internals/Engine.ts | 7 +- src/internals/SubstituteState.ts | 202 +++++++++----- src/internals/utilities/ArgumentHash.ts | 276 ++++++++++++++----- 5 files changed, 599 insertions(+), 153 deletions(-) create mode 100644 spec/regression/fixes/round3-hashing.test.ts diff --git a/spec/regression/fixes/amendments.test.ts b/spec/regression/fixes/amendments.test.ts index efba667..48a9d4d 100644 --- a/spec/regression/fixes/amendments.test.ts +++ b/spec/regression/fixes/amendments.test.ts @@ -355,14 +355,15 @@ test('R:RT-8 / D4 / D15 indexing literal substitutions does not change which sub t.true(types.isProxy(values.f(() => 1))) t.true(types.isProxy(values.f(1, undefined))) - // literal arguments are compared as they are when the call is made (D15), also after a mutation + // amended D15 (round 3): mutating an argument object after the setup is not supported, except that the same + // object still matches; a fresh object equal to the mutated one no longer does, nor one equal to the original const repository = Substitute.for() const user = { name: 'a', tags: ['x'] } repository.save(user).returns('saved') user.name = 'b' user.tags.push('y') t.is(repository.save(user), 'saved') - t.is(repository.save({ name: 'b', tags: ['x', 'y'] }), 'saved') + t.true(types.isProxy(repository.save({ name: 'b', tags: ['x', 'y'] }))) t.true(types.isProxy(repository.save({ name: 'a', tags: ['x'] }))) // ... and the most recent of several matching literal substitutions wins const copy = { name: 'b', tags: ['x', 'y'] } diff --git a/spec/regression/fixes/round3-hashing.test.ts b/spec/regression/fixes/round3-hashing.test.ts new file mode 100644 index 0000000..1e6399b --- /dev/null +++ b/spec/regression/fixes/round3-hashing.test.ts @@ -0,0 +1,262 @@ +import test from 'ava' +import { inspect, isDeepStrictEqual } from 'util' + +import { Substitute, Arg, configure } from '../../../src' +import { FALLBACK_HASH, hashArguments, identityHashArguments, structuralHash } from '../../../src/internals/utilities/ArgumentHash' + +// Round 3, D35: the structural hash behind the auto-substitute cache and the index of literal substitutions. + +/** A small deterministic PRNG (mulberry32), so that a failure can be reproduced. */ +const random = (seed: number) => () => { + seed = (seed + 0x6d2b79f5) | 0 + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 +} + +class Point { constructor(public x: unknown, public y: unknown) { } } +class Empty { } + +const sharedSymbols = [Symbol('a'), Symbol('b'), Symbol.for('registered'), Symbol()] +const sharedFunctions = [() => 1, function named() { }, Substitute.for(), Substitute.for().member] + +type Next = () => number + +const generate = (next: Next, depth: number): unknown => { + const pick = (items: readonly T[]): T => items[Math.floor(next() * items.length)] + const leaf = () => pick<() => unknown>([ + () => undefined, () => null, () => next() < 0.5, + () => pick([0, -0, 1, -1, 2 ** 31, -(2 ** 31) - 1, 1.5, -2.25, NaN, Infinity, -Infinity, Number.MAX_VALUE, Number.MIN_VALUE]), + () => Math.floor(next() * 1000), + () => pick(['', 'a', 'b', 'ab', 'ba', 'é', '😀', 'x'.repeat(100), 'x'.repeat(99) + 'y']), + () => BigInt(Math.floor(next() * 5)), + () => pick(sharedSymbols), + () => pick(sharedFunctions), + () => new Date(pick([0, 1, 1e12])), // invalid Dates are never deep strictly equal, not even to themselves' copies + () => pick([/a/, /a/g, /b/i, new RegExp('a', 'gi')]), + () => pick<() => unknown>([() => new Number(pick([0, -0, 1, NaN])), () => new String(pick(['', 'a'])), () => new Boolean(next() < 0.5), + () => Object(pick(sharedSymbols)), () => Object(BigInt(pick([0, 1])))])(), + () => pick<() => unknown>([ + () => new Uint8Array([1, 2, 3].slice(0, Math.floor(next() * 4))), + () => Buffer.from(pick(['', 'ab', 'abc'])), + () => new Float64Array([pick([0, -0, NaN, 1.5])]), + () => new Int16Array([Math.floor(next() * 3)]), + () => new Uint8Array([1, 2]).buffer, + () => new DataView(new Uint8Array([Math.floor(next() * 3)]).buffer) + ])() + ])() + if (depth <= 0 || next() < 0.35) return leaf() + const size = Math.floor(next() * 4) + const children = () => Array.from({ length: size }, () => generate(next, depth - 1)) + return pick<() => unknown>([ + () => children(), + () => { const sparse = new Array(size + 1); if (size > 0) sparse[0] = generate(next, depth - 1); return sparse }, + () => Object.fromEntries(children().map((value, index) => [pick(['a', 'b', 'c', 'd']) + index, value])), + () => Object.assign(Object.create(null), { k: generate(next, depth - 1) }), + () => new Point(generate(next, depth - 1), generate(next, depth - 1)), + () => new Empty(), + () => ({ [pick(sharedSymbols)]: generate(next, depth - 1), plain: size }), + () => { const hidden = { visible: size }; Object.defineProperty(hidden, pick(sharedSymbols), { value: next(), enumerable: false }); return hidden }, + () => new Map(children().map((value, index) => [index % 2 === 0 ? index : { key: index }, value])), + () => new Set(children()), + () => [generate(next, depth - 1), { nested: [generate(next, depth - 1)] }] + ])() +} + +const shuffle = (next: Next, items: T[]): T[] => { + for (let index = items.length - 1; index > 0; index--) { + const other = Math.floor(next() * (index + 1)) + ;[items[index], items[other]] = [items[other], items[index]] + } + return items +} + +/** A deep strictly equal copy with other identities, other key orders and other Map/Set insertion orders. */ +const copy = (next: Next, value: unknown, seen = new Map()): unknown => { + if (typeof value !== 'object' || value === null) return value + if (seen.has(value)) return seen.get(value) + if (Array.isArray(value)) { + const result: unknown[] = new Array(value.length) + seen.set(value, result) + for (const key of Object.keys(value)) (result as any)[key] = copy(next, (value as any)[key], seen) + return result + } + if (Buffer.isBuffer(value)) return Buffer.from(value) + if (ArrayBuffer.isView(value)) { + const bytes = new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice() + return value instanceof DataView ? new DataView(bytes.buffer) : new (value.constructor as any)(bytes.buffer) + } + if (value instanceof ArrayBuffer) return value.slice(0) + if (value instanceof Date) return new Date(value.getTime()) + if (value instanceof RegExp) return new RegExp(value.source, value.flags) + if (value instanceof Map) return new Map(shuffle(next, [...value].map(([k, v]) => [copy(next, k, seen), copy(next, v, seen)]))) + if (value instanceof Set) return new Set(shuffle(next, [...value].map(item => copy(next, item, seen)))) + if (value instanceof Number || value instanceof String || value instanceof Boolean || value instanceof Symbol || value instanceof BigInt) + return Object(value.valueOf()) + const result = Object.create(Object.getPrototypeOf(value)) + seen.set(value, result) + for (const key of shuffle(next, Reflect.ownKeys(value))) { + const descriptor = Object.getOwnPropertyDescriptor(value, key)! + Object.defineProperty(result, key, { ...descriptor, value: copy(next, descriptor.value, seen) }) + } + return result +} + +test('ENG2-2 (D35) the structural hash is consistent with isDeepStrictEqual (property test over generated values)', t => { + const next = random(20261116) + const values: unknown[] = [] + let equalPairs = 0 + for (let index = 0; index < 4000; index++) { + const value = generate(next, 4) + values.push(value) + const twin = copy(next, value) + t.true(isDeepStrictEqual(value, twin), 'the copy is deep strictly equal') + if (structuralHash(value) !== structuralHash(twin) || hashArguments([value, 1]) !== hashArguments([twin, 1])) + t.fail(`equal values hash differently: ${String(index)}`) + equalPairs++ + } + + // random pairs: equal ones must hash equal; unequal ones should rarely collide + let unequal = 0 + let collisions = 0 + for (let index = 0; index < 20000; index++) { + const a = values[Math.floor(next() * values.length)] + const b = values[Math.floor(next() * values.length)] + const sameHash = structuralHash(a) === structuralHash(b) + if (isDeepStrictEqual(a, b)) { + equalPairs++ + if (!sameHash) t.fail('equal values hash differently') + } else { + unequal++ + if (sameHash) collisions++ + } + } + t.true(equalPairs > 4000) + t.true(unequal > 1000) + // only values that differ in what the hash leaves out collide: prototypes, holes, non-enumerable keys, symbols + // with the same description, ... + t.true(collisions / unequal < 0.05, `${collisions} collisions in ${unequal} unequal pairs`) +}) + +test('ENG2-2 (D35) the structural hash: special values, and values that cannot be hashed never crash', t => { + const same = (a: unknown, b: unknown, message: string) => { + t.true(isDeepStrictEqual(a, b), message) + t.is(structuralHash(a), structuralHash(b), message) + } + same(NaN, NaN, 'NaN') + same([NaN], [Number.NaN], 'NaN in arrays') + same(new Number(NaN), new Number(NaN), 'boxed NaN') + t.false(isDeepStrictEqual(0, -0)) + same({ a: 1, b: [1, 2] }, { b: [1, 2], a: 1 }, 'key order') + same(new Map([[1, 'a'], [2, 'b']]), new Map([[2, 'b'], [1, 'a']]), 'Map order') + same(new Map([[{ k: 1 }, 'a']]), new Map([[{ k: 1 }, 'a']]), 'Map object keys') + same(new Set([1, { a: 2 }]), new Set([{ a: 2 }, 1]), 'Set order') + same(new Date(5), new Date(5), 'Dates') + t.false(isDeepStrictEqual(new Date(NaN), new Date(NaN)), 'invalid Dates are never equal') + same(/x/gi, new RegExp('x', 'gi'), 'RegExps') + same(Buffer.from('abc'), Buffer.from('abc'), 'Buffers') + same(new Float64Array([-0, NaN]), new Float64Array([-0, NaN]), 'typed arrays') + same(Object.assign(Object.create(null), { a: 1 }), Object.assign(Object.create(null), { a: 1 }), 'null prototype') + same(new Point(1, { z: 2 }), new Point(1, { z: 2 }), 'class instances') + const symbol = Symbol('key') + same({ [symbol]: 1, a: 2 }, { a: 2, [symbol]: 1 }, 'symbol keys') + same('x'.repeat(1000) + 'a', 'x'.repeat(1000) + 'a', 'long strings') + const sparse = [1, , 3] // eslint-disable-line no-sparse-arrays + same(sparse, [1, , 3], 'sparse arrays') // eslint-disable-line no-sparse-arrays + + // values that differ get different hashes (not required by the contract, but the index relies on it in practice) + const differ = (a: unknown, b: unknown, message: string) => t.not(structuralHash(a), structuralHash(b), message) + differ('x'.repeat(70) + 'a', 'x'.repeat(70) + 'b', 'long strings with a common prefix') + differ(Buffer.from('abcdefghijklmnop'), Buffer.from('abcdefghijklmnoq'), 'Buffers of the same length') + differ({ order: { customer: { id: 1 } } }, { order: { customer: { id: 2 } } }, 'deep objects') + differ(Array.from({ length: 20 }, (_, i) => i), Array.from({ length: 20 }, (_, i) => (i === 19 ? -1 : i)), 'long arrays') + differ(new Map([[1, 2]]), new Map([[1, 3]]), 'Maps of the same size') + differ(new Set([1]), new Set([2]), 'Sets of the same size') + differ(new Date(1), new Date(2), 'Dates') + differ(Symbol('a'), Symbol('b'), 'symbols with other descriptions') + + // cycles (also cycles of a different shape that are deep strictly equal), throwing getters, revoked proxies + const cyclic: any = { name: 'a' } + cyclic.self = cyclic + const longer: any = { name: 'a', self: { name: 'a' } } + longer.self.self = longer + t.true(isDeepStrictEqual(cyclic, longer)) + t.is(structuralHash(cyclic), FALLBACK_HASH) + t.is(structuralHash(longer), FALLBACK_HASH) + const throwing = { get value(): never { throw new Error('getter') } } + t.is(structuralHash(throwing), FALLBACK_HASH) + t.is(hashArguments([1, throwing]), FALLBACK_HASH) + const { proxy, revoke } = Proxy.revocable({}, {}) + revoke() + t.is(structuralHash(proxy), FALLBACK_HASH) + const wide: any[] = [] + for (let index = 0; index < 20; index++) wide.push(wide.length === 0 ? {} : [wide[index - 1], wide[index - 1]]) + t.is(structuralHash(wide[19]), FALLBACK_HASH, 'more nested objects than the limit (through shared references)') + + // substitutes and functions by identity, never traversed + const substitute = Substitute.for() + t.is(structuralHash(substitute), structuralHash(substitute)) + t.not(structuralHash(substitute), structuralHash(Substitute.for())) + t.is(inspect(substitute), '@Substitute {\n}', 'nothing about it was recorded') + + // the identity hash is only there for arguments with objects + t.is(identityHashArguments([1, 'a', () => 1]), undefined) + const object = { a: 1 } + t.is(identityHashArguments([object]), identityHashArguments([object])) + t.not(identityHashArguments([object]), identityHashArguments([{ a: 1 }])) +}) + +const millisecondsOf = (run: () => void) => { + const start = process.hrtime.bigint() + run() + return Number(process.hrtime.bigint() - start) / 1e6 +} +const bestOfThree = (run: () => void) => Math.min(millisecondsOf(run), millisecondsOf(run), millisecondsOf(run)) + +const shapes: Array<[string, (index: number) => unknown]> = [ + ['nested objects', index => ({ order: { customer: { id: index } } })], + ['Buffers', index => Buffer.from(`payload-${String(index).padStart(8, '0')}`)], + ['long strings with a common prefix', index => `${'x'.repeat(70)}${index}`], + ['arrays of 20 items', index => Array.from({ length: 20 }, (_, item) => (item === 19 ? index : item))], + ['Maps', index => new Map([['id', index]])], + ['Sets', index => new Set([index])], + ['Dates', index => new Date(index)] +] + +test('ENG2-2 (D35) 10k unconfigured calls with arguments of any shape finish well under 1s', t => { + for (const [name, argument] of shapes) { + const run = () => { + const repository = Substitute.for() + for (let index = 0; index < 10_000; index++) repository.save(argument(index)) + } + run() // warm up + const elapsed = bestOfThree(run) + t.true(elapsed < 1000, `${name}: ${elapsed} ms`) + } + + // the cache still gives the same auto-substitute for equal arguments + const repository = Substitute.for() + for (const [name, argument] of shapes) t.is(repository.save(argument(7)), repository.save(argument(7)), name) +}) + +test('V2-5 (D35) 4000 object-argument setups and 4000 matching calls finish well under 1s', t => { + const run = () => { + const finder = Substitute.for() + for (let index = 0; index < 4_000; index++) finder.find({ id: index, tags: [index] }).returns(index) + for (let index = 0; index < 4_000; index++) if (finder.find({ id: index, tags: [index] }) !== index) throw new Error(`find(${index})`) + for (let index = 0; index < 4_000; index++) finder.find({ id: -index - 1, tags: [] }) + } + run() // warm up + const elapsed = bestOfThree(run) + t.true(elapsed < 1000, `took ${elapsed} ms`) + + // through configure(), and with matcher setups next to the literal ones + const finder = Substitute.for() + finder.find(Arg.any()).returns('any') + const configured = millisecondsOf(() => { + for (let index = 0; index < 4_000; index++) finder[configure]().find([index, { nested: index }]).returns(index) + for (let index = 0; index < 4_000; index++) if (finder.find([index, { nested: index }]) !== index) throw new Error(`find(${index})`) + }) + t.true(configured < 1000, `took ${configured} ms through configure()`) + t.is(finder.find([1, { nested: 2 }]), 'any') +}) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index cec6eef..bb814f3 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -1,7 +1,7 @@ import { inspect, InspectOptions } from 'util' import { isSubstituteProxy, substituteMarker } from '../shared' -import { AutoEntry, Substitution, SubstituteState } from './SubstituteState' +import { ArgumentHashes, AutoEntry, Substitution, SubstituteState } from './SubstituteState' import { CallRecord, currentSequence, retract } from './CallRecord' import { RecordedArguments } from './RecordedArguments' import { SubstituteException } from './SubstituteException' @@ -306,7 +306,8 @@ const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStar } const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], record: CallRecord): any => { - const substitution = state.findCallSubstitution(key, args) + const hashes = new ArgumentHashes(args) + const substitution = state.findCallSubstitution(key, hashes) if (substitution !== undefined) { if (substitution.method === 'auto') substitution.entry!.handOut(record) return execute(substitution, args) @@ -323,7 +324,7 @@ const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], reco } } - const entry = state.callEntry(key, args) + const entry = state.callEntry(key, hashes) entry.handOut(record) return entryProxy(entry) } diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index 0911073..2342b69 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -3,14 +3,69 @@ import { inspect } from 'util' import { CallRecord, RecordKind, currentSequence } from './CallRecord' import { RecordedArguments } from './RecordedArguments' import { SELF, SubstitutionMethod, keyToString } from './Constants' -import { fingerprintArguments, identityFingerprintArguments, stableFingerprintArguments } from './utilities' +import { hashArguments, identityHashArguments } from './utilities' let substitutionOrder = 0 +/** + * The hashes of the actual arguments of one call (see ArgumentHash), computed when first needed and shared by the + * lookups the call makes (the literal substitutions, then the auto-substitute cache). + */ +export class ArgumentHashes { + private _structural?: number + private _identity?: number | null + + constructor(public readonly args: readonly unknown[]) { } + + public get structural(): number { + if (this._structural === undefined) this._structural = hashArguments(this.args) + return this._structural + } + + public get identity(): number | undefined { + if (this._identity === undefined) this._identity = identityHashArguments(this.args) ?? null + return this._identity ?? undefined + } +} + +/** A map from hashes to the items with that hash, which stores a single item without an array. */ +type Buckets = Map + +const bucketAdd = (buckets: Buckets, hash: number, item: T): void => { + const bucket = buckets.get(hash) + if (bucket === undefined) buckets.set(hash, item) + else if (Array.isArray(bucket)) bucket.push(item) + else buckets.set(hash, [bucket, item]) +} + +const bucketItems = (buckets: Buckets, hash: number): readonly T[] | undefined => { + const bucket = buckets.get(hash) + return bucket === undefined ? undefined : Array.isArray(bucket) ? bucket : [bucket] +} + +const bucketRemove = (buckets: Buckets, hash: number, item: T): void => { + const bucket = buckets.get(hash) + if (bucket === item) buckets.delete(hash) + else if (Array.isArray(bucket)) { + const index = bucket.indexOf(item) + if (index !== -1) bucket.splice(index, 1) + if (bucket.length === 0) buckets.delete(hash) + } +} + +function* allBucketItems(buckets: Buckets): IterableIterator { + for (const bucket of buckets.values()) { + if (Array.isArray(bucket)) yield* bucket + else yield bucket + } +} + /** A configured behaviour: `sub.add(1, Arg.any()).returns(3, 4)`, `sub.prop.throws(err)`, ... */ export class Substitution { private _next = 0 public readonly order = ++substitutionOrder + /** For a literal substitution whose arguments contain objects: their identity hash (see CallSubstitutions). */ + public identity?: number constructor( public readonly kind: 'get' | 'call', @@ -80,10 +135,10 @@ export class AutoEntry { } type CallEntryIndex = { - byFingerprint: Map - /** The entry last handed out for exactly these primitives and objects (see identityFingerprintArguments). */ - byIdentity: Map - unfingerprinted: AutoEntry[] + /** Every entry, by the structural hash of its arguments when it was created. */ + byHash: Buckets + /** The entries handed out for arguments with objects, by their identity hash. */ + byIdentity?: Buckets } /** The most recent substitution in `list` (kept in configuration order) that matches, if it is more recent than `best`. */ @@ -99,17 +154,17 @@ const mostRecentMatch = (list: readonly Substitution[], actualArguments: readonl /** * The call substitutions configured for one member. * - * All-literal substitutions (the most specific class, D4) are indexed by the stable fingerprint of their - * arguments, which deep strictly equal argument lists share and which does not change when an object in the - * arguments is mutated after the setup (literal arguments are compared as they are when the call is made, D15). - * A call therefore only compares against the literal substitutions with the same primitives in the same places: - * a single one for distinct primitive arguments, however many there are. Substitutions with Arg matchers are kept - * in a list. + * All-literal substitutions (the most specific class, D4) are indexed by the structural hash of their arguments at + * setup time (D35), which deep strictly equal argument lists share, so a call only compares (with live deep equality) + * against the literal substitutions with the same hash: usually none or one, however many there are and whatever the + * shape of the arguments. Those with objects among their arguments are also indexed by identity, so passing the same + * objects again still matches after they were mutated (mutating an argument after the setup is otherwise not + * supported, amended D15). Substitutions with Arg matchers are kept in a list. */ class CallSubstitutions { - private readonly _literal = new Map() - /** All-literal substitutions whose arguments could not be fingerprinted. */ - private readonly _unindexed: Substitution[] = [] + /** In configuration order within each bucket. */ + private readonly _literal: Buckets = new Map() + private readonly _byIdentity: Buckets = new Map() private readonly _withMatchers: Substitution[] = [] private _size = 0 @@ -117,42 +172,50 @@ class CallSubstitutions { return this._size } - private listFor(args: RecordedArguments, create: boolean): Substitution[] | undefined { - if (args.argumentsClass !== 'plain') return this._withMatchers - const fingerprint = stableFingerprintArguments(args.value!) - if (fingerprint === undefined) return this._unindexed - let list = this._literal.get(fingerprint) - if (list === undefined && create) { - list = [] - this._literal.set(fingerprint, list) - } - return list - } - /** Adds a substitution. One with the same specification is replaced (most recent wins). */ public add(substitution: Substitution): void { - const list = this.listFor(substitution.args!, true)! - const index = list.findIndex(existing => existing.args!.equals(substitution.args!)) - if (index !== -1) list.splice(index, 1) - else this._size++ - list.push(substitution) + const args = substitution.args! + if (args.argumentsClass !== 'plain') { + const index = this._withMatchers.findIndex(existing => existing.args!.equals(args)) + if (index !== -1) this._withMatchers.splice(index, 1) + else this._size++ + this._withMatchers.push(substitution) + return + } + const hash = hashArguments(args.value!) + const replaced = bucketItems(this._literal, hash)?.find(existing => existing.args!.equals(args)) + if (replaced !== undefined) { + bucketRemove(this._literal, hash, replaced) + if (replaced.identity !== undefined) bucketRemove(this._byIdentity, replaced.identity, replaced) + } else this._size++ + bucketAdd(this._literal, hash, substitution) + const identity = identityHashArguments(args.value!) + if (identity !== undefined) { + substitution.identity = identity + bucketAdd(this._byIdentity, identity, substitution) + } } /** The substitution configured with exactly this specification. */ public withSpecification(args: RecordedArguments): Substitution | undefined { - return this.listFor(args, false)?.find(substitution => substitution.args!.equals(args)) + const candidates = args.argumentsClass !== 'plain' ? this._withMatchers : bucketItems(this._literal, hashArguments(args.value!)) + return candidates?.find(substitution => substitution.args!.equals(args)) } /** The most specific class wins (all-literal, then predicates, then Arg.all()); within a class the most recent one. */ - public match(actualArguments: readonly unknown[]): Substitution | undefined { + public match(hashes: ArgumentHashes): Substitution | undefined { + const actualArguments = hashes.args let best: Substitution | undefined - const fingerprint = stableFingerprintArguments(actualArguments) - if (fingerprint !== undefined) { - const list = this._literal.get(fingerprint) - if (list !== undefined) best = mostRecentMatch(list, actualArguments, best) - } else for (const list of this._literal.values()) best = mostRecentMatch(list, actualArguments, best) - best = mostRecentMatch(this._unindexed, actualArguments, best) - if (best !== undefined) return best + if (this._literal.size > 0) { + const literal = bucketItems(this._literal, hashes.structural) + if (literal !== undefined) best = mostRecentMatch(literal, actualArguments, best) + if (this._byIdentity.size > 0) { + const identity = hashes.identity + const sameObjects = identity === undefined ? undefined : bucketItems(this._byIdentity, identity) + if (sameObjects !== undefined) best = mostRecentMatch(sameObjects, actualArguments, best) + } + if (best !== undefined) return best + } const withMatchers = this._withMatchers for (let index = withMatchers.length - 1; index >= 0; index--) { @@ -164,8 +227,7 @@ class CallSubstitutions { } public *all(): IterableIterator { - for (const list of this._literal.values()) yield* list - yield* this._unindexed + yield* allBucketItems(this._literal) yield* this._withMatchers } } @@ -296,7 +358,7 @@ export class SubstituteState { * The substitution that answers a call: the most specific class wins (all-literal, then predicates, * then Arg.all()), and within a class the most recently configured one wins. */ - public findCallSubstitution(key: PropertyKey, actualArguments: readonly unknown[]): Substitution | undefined { + public findCallSubstitution(key: PropertyKey, actualArguments: ArgumentHashes): Substitution | undefined { return this._callSubstitutions.get(key)?.match(actualArguments) } @@ -317,46 +379,41 @@ export class SubstituteState { } /** - * The auto-substitute for a call with these actual (literal) arguments. The same objects get the same - * auto-substitute even when they were mutated in between (their structural fingerprint has gone stale then), - * so that after `api.get(request).body.returns(1)` and `request.x = 1`, `api.get(request).body` is still 1 (D2). + * The auto-substitute for a call with these actual (literal) arguments (D2), found in O(1) expected time by the + * structural hash of the arguments (D35). The same objects get the same auto-substitute even when they were + * mutated in between (the structural hash has gone stale then), so that after `api.get(request).body.returns(1)` + * and `request.x = 1`, `api.get(request).body` is still 1: entries for arguments with objects are also found by + * the identity of those objects, first. */ - public callEntry(key: PropertyKey, actualArguments: any[]): AutoEntry { + public callEntry(key: PropertyKey, actual: ArgumentHashes): AutoEntry { + const actualArguments = actual.args let index = this._callEntries.get(key) if (index === undefined) { - index = { byFingerprint: new Map(), byIdentity: new Map(), unfingerprinted: [] } + index = { byHash: new Map() } this._callEntries.set(key, index) } - const identity = identityFingerprintArguments(actualArguments) - if (identity !== undefined) { - const known = index.byIdentity.get(identity) - if (known !== undefined && known.args!.matches(actualArguments)) return known + const identity = actual.identity + if (identity !== undefined && index.byIdentity !== undefined) { + const known = bucketItems(index.byIdentity, identity)?.find(entry => entry.args!.matches(actualArguments)) + if (known !== undefined) return known } - const entry = this.structuralCallEntry(index, key, actualArguments) - if (identity !== undefined) index.byIdentity.set(identity, entry) - return entry - } - private structuralCallEntry(index: CallEntryIndex, key: PropertyKey, actualArguments: any[]): AutoEntry { - const fingerprint = fingerprintArguments(actualArguments) - let bucket: AutoEntry[] | undefined - if (fingerprint === undefined) bucket = index.unfingerprinted - else { - bucket = index.byFingerprint.get(fingerprint) - if (bucket === undefined) { - bucket = [] - index.byFingerprint.set(fingerprint, bucket) - } + const hash = actual.structural + let entry = bucketItems(index.byHash, hash)?.find(candidate => candidate.args!.matches(actualArguments)) + if (entry === undefined) { + entry = new AutoEntry('call', this, key, RecordedArguments.from(actualArguments as any[])) + bucketAdd(index.byHash, hash, entry) + } + if (identity !== undefined) { + if (index.byIdentity === undefined) index.byIdentity = new Map() + bucketAdd(index.byIdentity, identity, entry) } - for (const entry of bucket) if (entry.args!.matches(actualArguments)) return entry - const entry = new AutoEntry('call', this, key, RecordedArguments.from(actualArguments)) - bucket.push(entry) return entry } /** The auto-substitute for a call specification used in a nested setup (`a(Arg.any()).b.returns(1)`). */ public specificationEntry(key: PropertyKey, specification: RecordedArguments): AutoEntry { - if (specification.argumentsClass === 'plain') return this.callEntry(key, specification.value!) + if (specification.argumentsClass === 'plain') return this.callEntry(key, new ArgumentHashes(specification.value!)) let list = this._specificationEntries.get(key) if (list === undefined) { list = [] @@ -372,10 +429,7 @@ export class SubstituteState { public *entries(): IterableIterator { yield* this._propertyEntries.values() - for (const index of this._callEntries.values()) { - for (const bucket of index.byFingerprint.values()) yield* bucket - yield* index.unfingerprinted - } + for (const index of this._callEntries.values()) yield* allBucketItems(index.byHash) for (const list of this._specificationEntries.values()) yield* list } diff --git a/src/internals/utilities/ArgumentHash.ts b/src/internals/utilities/ArgumentHash.ts index d33e7d7..9cf52fb 100644 --- a/src/internals/utilities/ArgumentHash.ts +++ b/src/internals/utilities/ArgumentHash.ts @@ -1,100 +1,228 @@ +import { types } from 'util' + /** - * Cheap fingerprints of an argument list, used to look up the auto-substitute cached for a call, or the literal - * substitutions that can answer a call, in O(1) instead of comparing against every earlier argument list. + * Structural hashes of argument lists (D35). They let the auto-substitute cache and the index of literal + * substitutions find the candidates for a call in O(1) expected time, whatever the shape of the arguments, instead of + * comparing the call against every earlier argument list. * - * Contract: arguments that are deep strictly equal (util.isDeepStrictEqual) always get the same structural and - * the same stable fingerprint. A fingerprint may be coarser than equality (callers still compare with - * isDeepStrictEqual inside a bucket). Functions, and therefore substitutes, are fingerprinted by identity and are - * never traversed. Returns undefined when the arguments cannot be fingerprinted (for example when a getter throws). + * Contract: argument lists that are deep strictly equal (util.isDeepStrictEqual, element by element) always get the + * same structural hash. Unequal lists may share a hash (callers confirm every candidate with live deep equality), + * so the hash only looks at what deep strict equality compares, and may leave things out: + * - primitives by value (NaN as one value, symbols by their description), functions (substitutes included) by + * identity: they are never traversed; + * - arrays element by element (a hole counts as undefined), plain objects and class instances by their own + * enumerable string and symbol keys and values, in any key order (prototypes are left out); + * - Maps and Sets by their entries, in any order; Dates, RegExps and boxed primitives by their value; typed arrays, + * DataViews and ArrayBuffers by their bytes. + * Arguments that cannot be hashed give the constant FALLBACK_HASH: a cycle (a value deep strictly equal to a cyclic + * value is cyclic as well), more than MAX_OBJECTS nested objects (deep strictly equal values have the same number), + * or anything that throws while it is read, such as a throwing getter or a revoked proxy. * - * - structural: looks into objects (two levels deep). It describes the arguments as they are now, so it goes - * stale when an object in them is mutated later. - * - stable: an object only counts as "an object", so it never goes stale. Used for configured substitutions, - * whose arguments are compared as they are when a call is made. - * - identity: an object counts by identity. Equal identity fingerprints mean the same primitives and the same - * objects, so the arguments are equal however the objects were mutated since. + * The identity hash counts objects by identity (and is undefined when there are no objects among the arguments, as + * the structural hash is exact then). It finds the entry recorded for the same objects again after they were mutated. */ -const objectIds = new WeakMap() -const symbolIds = new Map() -let nextId = 0 -const idOfObject = (value: object): number => { +export const FALLBACK_HASH = 0x2f6b1c33 + +/** Objects (and functions) by identity. Weak, so that hashing never keeps a value alive. */ +const objectIds = new WeakMap() +let nextObjectId = 0 +const idOf = (value: object): number => { let id = objectIds.get(value) if (id === undefined) { - id = ++nextId + id = ++nextObjectId objectIds.set(value, id) } return id } -const idOfSymbol = (value: symbol): number => { - let id = symbolIds.get(value) - if (id === undefined) { - id = ++nextId - symbolIds.set(value, id) - } - return id +const MAX_OBJECTS = 100_000 +/** The depth from which the ancestors of the current value are also kept in a Set (cycle detection stays O(1)). */ +const ANCESTOR_SET_DEPTH = 16 + +/** Thrown to stop hashing; the arguments then get FALLBACK_HASH. Not an Error, so that no stack trace is captured. */ +const CANNOT_HASH = { reason: 'cannot hash' } + +// tags that keep the kinds of values apart +const enum Tag { + Undefined = 0x1b873593, Null = 0x2e5c4a1d, True = 0x5a9e1d27, False = 0x3c6ef372, Number = 0x7f4a7c15, + NaN = 0x6c078965, String = 0x0bad5eed, BigInt = 0x4cf5ad43, Symbol = 0x1f83d9ab, Function = 0x5be0cd19, + Array = 0x6a09e667, Object = 0x3c6ef373, Map = 0x510e527f, Set = 0x9b05688c, Date = 0x1f83d9ac, + RegExp = 0x5be0cd1a, Bytes = 0x428a2f98, Boxed = 0x71374491, Identity = 0x2a5c4e2b, Arguments = 0x0f1bbcdc +} + +const mix = (hash: number, value: number): number => { + let h = Math.imul(hash ^ value, 0x5bd1e995) + h ^= h >>> 15 + return Math.imul(h, 0x27d4eb2d) | 0 +} + +/** Mixes a hash into an order-independent sum (for object keys, Map and Set entries). */ +const spread = (value: number): number => { + let h = Math.imul(value ^ (value >>> 16), 0x85ebca6b) + h ^= h >>> 13 + return Math.imul(h, 0xc2b2ae35) | 0 +} + +const hashString = (text: string, seed: number): number => { + let h = mix(seed, text.length) + for (let index = 0; index < text.length; index++) h = Math.imul(h ^ text.charCodeAt(index), 0x01000193) + return mix(h, 0) } -const MAX_DEPTH = 2 -const MAX_ITEMS = 8 -const MAX_KEYS = 16 -const MAX_STRING = 64 +const float = new Float64Array(1) +const floatWords = new Int32Array(float.buffer) +const hashNumber = (value: number): number => { + if ((value | 0) === value && !Object.is(value, -0)) return mix(Tag.Number, value) + if (value !== value) return Tag.NaN + float[0] = value + return mix(mix(Tag.Number, floatWords[0]), floatWords[1]) +} + +const hashBytes = (bytes: Uint8Array): number => { + let h = mix(Tag.Bytes, bytes.length) + for (let index = 0; index < bytes.length; index++) h = Math.imul(h ^ bytes[index], 0x01000193) + return mix(h, 0) +} -type ObjectMode = 'structure' | 'stable' | 'identity' +// util.types.isBigIntObject is missing from older runtimes (and from the Node typings in use) +const typeChecks = types as unknown as Record boolean) | undefined> +const isBigIntObject: (value: unknown) => boolean = typeChecks.isBigIntObject ?? (() => false) -const fingerprintValue = (value: unknown, depth: number, objects: ObjectMode): string => { +const hashPrimitive = (value: unknown): number => { switch (typeof value) { - case 'string': - return `s${value.length}:${value.length > MAX_STRING ? value.slice(0, MAX_STRING) : value}` - case 'number': - return Object.is(value, -0) ? 'n-0' : `n${value}` - case 'bigint': - return `b${value}` - case 'boolean': - return value ? 't' : 'f' - case 'undefined': - return 'u' - case 'symbol': - return `y${idOfSymbol(value)}` - case 'function': - return `F${idOfObject(value)}` + case 'string': return hashString(value, Tag.String) + case 'number': return hashNumber(value) + case 'boolean': return value ? Tag.True : Tag.False + case 'undefined': return Tag.Undefined + // D30: by description, so that no symbol is kept alive; equality confirms the identity + case 'symbol': return hashString(value.toString(), Tag.Symbol) + case 'bigint': return hashString(value.toString(), Tag.BigInt) } - if (value === null) return 'N' - const object = value as object - if (objects === 'identity') return `I${idOfObject(object)}` - if (objects === 'stable' || depth >= MAX_DEPTH) return 'O' - if (Array.isArray(object)) { - let fingerprint = `A${object.length}[` - const length = Math.min(object.length, MAX_ITEMS) - for (let index = 0; index < length; index++) fingerprint += fingerprintValue(object[index], depth + 1, objects) + ',' - return fingerprint + ']' + return Tag.Null +} + +/** One structural hashing run over an argument list. */ +class StructuralHasher { + private _objects = 0 + private readonly _ancestors: object[] = [] + private _ancestorSet?: Set + + public hash(value: unknown): number { + if (typeof value === 'function') return mix(Tag.Function, idOf(value)) + if (typeof value !== 'object' || value === null) return hashPrimitive(value) + return this.hashObject(value) + } + + private enter(object: object): void { + if (++this._objects > MAX_OBJECTS) throw CANNOT_HASH + const set = this._ancestorSet + if (set !== undefined) { + if (set.has(object)) throw CANNOT_HASH + set.add(object) + } else if (this._ancestors.indexOf(object) !== -1) throw CANNOT_HASH + this._ancestors.push(object) + if (set === undefined && this._ancestors.length > ANCESTOR_SET_DEPTH) this._ancestorSet = new Set(this._ancestors) + } + + private exit(object: object): void { + this._ancestors.pop() + this._ancestorSet?.delete(object) + } + + private hashObject(object: object): number { + this.enter(object) + try { + return this.hashContents(object) + } finally { + this.exit(object) + } + } + + private hashContents(object: object): number { + if (Array.isArray(object)) { + let h = mix(Tag.Array, object.length) + for (let index = 0; index < object.length; index++) h = mix(h, this.hash(object[index])) + return h + } + if (ArrayBuffer.isView(object)) return hashBytes(new Uint8Array(object.buffer, object.byteOffset, object.byteLength)) + if (types.isAnyArrayBuffer(object)) return hashBytes(new Uint8Array(object as ArrayBuffer)) + if (types.isDate(object)) return mix(Tag.Date, hashNumber(Date.prototype.getTime.call(object))) + if (types.isRegExp(object)) { + const regExp = object as RegExp + return mix(hashString(regExp.source, Tag.RegExp), hashString(regExp.flags, Tag.RegExp)) + } + if (types.isMap(object)) { + let sum = 0 + for (const [key, value] of object as Map) sum = (sum + spread(mix(this.hash(key), this.hash(value)))) | 0 + return mix(mix(Tag.Map, (object as Map).size), sum) + } + if (types.isSet(object)) { + let sum = 0 + for (const value of object as Set) sum = (sum + spread(this.hash(value))) | 0 + return mix(mix(Tag.Set, (object as Set).size), sum) + } + if (types.isNumberObject(object)) return mix(Tag.Boxed, hashNumber(Number.prototype.valueOf.call(object))) + if (types.isStringObject(object)) return mix(Tag.Boxed, hashString(String.prototype.valueOf.call(object), Tag.String)) + if (types.isBooleanObject(object)) return mix(Tag.Boxed, Boolean.prototype.valueOf.call(object) ? Tag.True : Tag.False) + if (types.isSymbolObject(object)) return mix(Tag.Boxed, hashString(Symbol.prototype.toString.call(object), Tag.Symbol)) + if (isBigIntObject(object)) return mix(Tag.Boxed, hashString(String(object), Tag.BigInt)) + + // own enumerable string and symbol keys, in any order + const keys = Object.keys(object) + let sum = 0 + for (const key of keys) sum = (sum + spread(mix(hashString(key, Tag.Object), this.hash((object as any)[key])))) | 0 + let count = keys.length + for (const symbol of Object.getOwnPropertySymbols(object)) { + if (!Object.prototype.propertyIsEnumerable.call(object, symbol)) continue + count++ + sum = (sum + spread(mix(hashPrimitive(symbol), this.hash((object as any)[symbol])))) | 0 + } + return mix(mix(types.isArgumentsObject(object) ? Tag.Arguments : Tag.Object, count), sum) } - if (ArrayBuffer.isView(object)) return `V${object.byteLength}` - if (object instanceof Date) return `D${object.getTime()}` - if (object instanceof Map) return `M${object.size}` - if (object instanceof Set) return `S${object.size}` - const keys = Object.keys(object) - if (keys.length > MAX_KEYS) return `K${keys.length}` - keys.sort() - let fingerprint = '{' - for (const key of keys) fingerprint += `${key}:${fingerprintValue((object as any)[key], depth + 1, objects)},` - return fingerprint + '}' } -const fingerprintWith = (args: readonly unknown[], objects: ObjectMode): string | undefined => { +/** The hash of one value (see above). Exported for the tests of the contract. */ +export const structuralHash = (value: unknown): number => { try { - let fingerprint = `${args.length}|` - for (const arg of args) fingerprint += fingerprintValue(arg, 0, objects) + '|' - return fingerprint + return new StructuralHasher().hash(value) } catch { - return undefined + return FALLBACK_HASH } } -/** Looks into objects; goes stale when they are mutated (see above). */ -export const fingerprintArguments = (args: readonly unknown[]): string | undefined => fingerprintWith(args, 'structure') -/** Objects only count as objects, so it never goes stale. */ -export const stableFingerprintArguments = (args: readonly unknown[]): string | undefined => fingerprintWith(args, 'stable') -/** Objects count by identity. */ -export const identityFingerprintArguments = (args: readonly unknown[]): string | undefined => fingerprintWith(args, 'identity') +/** The structural hash of an argument list (see above). */ +export const hashArguments = (args: readonly unknown[]): number => { + // the common cases need no hasher: no arguments, and primitives only + let h = mix(Tag.Array, args.length) + let hasher: StructuralHasher | undefined + try { + for (let index = 0; index < args.length; index++) { + const value = args[index] + if (typeof value === 'object' && value !== null) { + if (hasher === undefined) hasher = new StructuralHasher() + h = mix(h, hasher.hash(value)) + } else h = mix(h, typeof value === 'function' ? mix(Tag.Function, idOf(value)) : hashPrimitive(value)) + } + } catch { + return FALLBACK_HASH + } + return h +} + +/** + * The hash of an argument list with objects counted by identity, or undefined when there is no object among the + * arguments (the structural hash already finds the same arguments then). + */ +export const identityHashArguments = (args: readonly unknown[]): number | undefined => { + let h = mix(Tag.Identity, args.length) + let hasObject = false + for (let index = 0; index < args.length; index++) { + const value = args[index] + if (typeof value === 'object' && value !== null) { + hasObject = true + h = mix(h, idOf(value)) + } else h = mix(h, typeof value === 'function' ? mix(Tag.Function, idOf(value)) : hashPrimitive(value)) + } + return hasObject ? h : undefined +} From 65e999ea37d6510acc6536ba13ade68fc2c040e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:15:30 +0000 Subject: [PATCH 034/106] perf(engine): D30 smaller auto-substitutes All substitute proxies share one handler; each target is a function bound to its face, with the printer inherited from a shared prototype. The hand-out record is kept in two fields instead of an object, and the actual arguments of an auto-substitute are only wrapped when needed. A distinct unconfigured call now costs about 200 bytes beyond its received-call record instead of about 1 KB (ENG2-9); the tests measure both. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3-hashing.test.ts | 48 ++++++++ src/internals/Engine.ts | 113 ++++++++++++------- src/internals/RecordedArguments.ts | 7 ++ src/internals/SubstituteState.ts | 40 +++++-- 4 files changed, 154 insertions(+), 54 deletions(-) diff --git a/spec/regression/fixes/round3-hashing.test.ts b/spec/regression/fixes/round3-hashing.test.ts index 1e6399b..37af1ce 100644 --- a/spec/regression/fixes/round3-hashing.test.ts +++ b/spec/regression/fixes/round3-hashing.test.ts @@ -1,4 +1,6 @@ import test from 'ava' +import { spawnSync } from 'child_process' +import * as path from 'path' import { inspect, isDeepStrictEqual } from 'util' import { Substitute, Arg, configure } from '../../../src' @@ -206,6 +208,52 @@ test('ENG2-2 (D35) the structural hash: special values, and values that cannot b t.not(identityHashArguments([object]), identityHashArguments([{ a: 1 }])) }) +/** Runs a script with the library in a child process with --expose-gc, and returns what it prints as JSON. */ +const measure = (script: string): any => { + const library = path.resolve(__dirname, '../../../src/index.js') + const result = spawnSync(process.execPath, ['--expose-gc', '-e', ` + const { Substitute, Arg } = require(${JSON.stringify(library)}) + const heap = () => { global.gc(); global.gc(); return process.memoryUsage().heapUsed } + ${script} + `], { encoding: 'utf8' }) + if (result.status !== 0) throw new Error(result.stderr) + return JSON.parse(result.stdout) +} + +test('ENG2-9 (D30) an unconfigured call with distinct arguments costs little memory beyond its record', t => { + const { unconfigured, configured } = measure(` + const bytesPerCall = configure => { + const calls = 50000 + const before = heap() + const logger = Substitute.for() + if (configure) logger.log(Arg.any()).returns(undefined) + for (let index = 0; index < calls; index++) logger.log(index) + const bytes = (heap() - before) / calls + if (logger.log(1) === null) console.log('keeps the substitute alive until here') + return Math.round(bytes) + } + console.log(JSON.stringify({ configured: bytesPerCall(true), unconfigured: bytesPerCall(false) })) + `) + t.log(`bytes per call: ${unconfigured} unconfigured (an auto-substitute each), ${configured} configured (the record only)`) + // before D30 the auto-substitute cost about 1 KB more than the record (Node 22: 1309 against 279 bytes) + t.true(unconfigured - configured < 450, `${unconfigured} - ${configured} bytes per call`) +}) + +test('ENG2-10 (D30) hashing does not keep symbols alive after the substitute that saw them is gone', t => { + const { retained } = measure(` + const before = heap() + const run = () => { + const emitter = Substitute.for() + emitter.emit(0).returns(1) + for (let index = 0; index < 100000; index++) emitter.emit(Symbol('event-' + index)) + } + run() + console.log(JSON.stringify({ retained: (heap() - before) / 1048576 })) + `) + t.log(`${retained.toFixed(2)} MB retained`) + t.true(retained < 2, `${retained} MB retained`) +}) + const millisecondsOf = (run: () => void) => { const start = process.hrtime.bigint() run() diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index bb814f3..aa65f68 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -1,4 +1,4 @@ -import { inspect, InspectOptions } from 'util' +import { inspect, InspectOptions, types } from 'util' import { isSubstituteProxy, substituteMarker } from '../shared' import { ArgumentHashes, AutoEntry, Substitution, SubstituteState } from './SubstituteState' @@ -24,17 +24,18 @@ import { formatArguments, formatValue, isPrinting, withPrintGuard } from './util */ type Printer = (options?: InspectOptions) => string -type Face = - | { kind: 'root', state: SubstituteState } - | { kind: 'member', entry: AutoEntry } // the result of reading an unconfigured member - | { kind: 'result', entry: AutoEntry } // the result of an unconfigured call +/** + * What a substitute proxy stands for: a substitute itself (its state), the result of reading an unconfigured member + * (an AutoEntry of kind 'get', a "member" handle) or the result of an unconfigured call (an AutoEntry of kind 'call'). + */ +type Face = SubstituteState | AutoEntry const TAKE_PENDING_READ = Symbol('take pending read') type ReadSource = typeof TAKE_PENDING_READ | CallRecord | undefined /** - * The target of every proxy. util.inspect inspects the target of a proxy (it does not trigger traps), - * so the target carries the printer as its inspect.custom hook. + * The target of the short-lived proxies (assertions, configure views, deferred reads). util.inspect inspects the + * target of a proxy (it does not trigger traps), so the target carries the printer as its inspect.custom hook. */ const newTarget = (print: Printer): any => { const target = function () { } @@ -79,11 +80,9 @@ const printState = (state: SubstituteState, colors: boolean): string => { } const printFace = (face: Face, colors: boolean): string => { - switch (face.kind) { - case 'root': return printState(face.state, colors) - case 'member': return `property<${memberLabel(face.entry.key)}>: ` - case 'result': return withPrintGuard(() => `method<${memberLabel(face.entry.key)}>: ${formatArguments(face.entry.args?.value, colors)}`) - } + if (!(face instanceof AutoEntry)) return printState(face, colors) + if (face.kind === 'get') return `property<${memberLabel(face.key)}>: ` + return withPrintGuard(() => `method<${memberLabel(face.key)}>: ${formatArguments(face.args?.value, colors)}`) } const special = (property: SpecialProperty, print: Printer, internal: unknown): any => { @@ -105,29 +104,64 @@ const colorsOf = (options?: InspectOptions) => options?.colors === true // ---- substitutes and auto-substitutes --------------------------------------------------------- -export const createSubstitute = (): any => createFaceProxy({ kind: 'root', state: new SubstituteState() }) +export const createSubstitute = (): any => createFaceProxy(new SubstituteState()) const entryProxy = (entry: AutoEntry): any => { - if (entry.proxy === undefined) - entry.proxy = createFaceProxy(entry.kind === 'get' ? { kind: 'member', entry } : { kind: 'result', entry }) + if (entry.proxy === undefined) entry.proxy = createFaceProxy(entry) return entry.proxy } -const faceState = (face: Face): SubstituteState => face.kind === 'root' ? face.state : face.entry.state -const faceChainHead = (face: Face): CallRecord | undefined => face.kind === 'root' ? undefined : face.entry.chainHead() +const faceState = (face: Face): SubstituteState => face instanceof AutoEntry ? face.state : face +const faceChainHead = (face: Face): CallRecord | undefined => face instanceof AutoEntry ? face.chainHead() : undefined + +/* + * D30: a substitute, and every auto-substitute (one per distinct unconfigured call), is a proxy. To keep them small, + * all of them share one handler, and the target of each one is a function that returns its face. util.inspect looks + * at the target of a proxy without triggering traps, so the printer is inherited from a shared prototype. + */ +type FaceTarget = () => Face + +const faceOfInspected = (value: any): Face | undefined => { + try { + return typeof value === 'function' && !types.isProxy(value) ? value() : value[INTERNAL] + } catch { + return undefined + } +} + +const faceTargetPrototype = Object.create(Function.prototype, { + [inspect.custom]: { + value: function (this: unknown, _depth: number, options?: InspectOptions) { + const face = faceOfInspected(this) + return face === undefined ? '' : printFace(face, colorsOf(options)) + }, + configurable: true + } +}) -const createFaceProxy = (face: Face): any => new Proxy(newTarget(options => printFace(face, colorsOf(options))), { - get: function get(_target: unknown, property: PropertyKey) { - return faceGet(face, property, get) +const faceHandler: ProxyHandler = { + get: function get(target: FaceTarget, property: PropertyKey) { + return faceGet(target(), property, get) }, - set: function set(_target: unknown, property: PropertyKey, value: unknown) { - faceSet(face, property, value, set) + set: function set(target: FaceTarget, property: PropertyKey, value: unknown) { + faceSet(target(), property, value, set) return true }, - apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { - return faceApply(face, args, apply) - } -}) + apply: function apply(target: FaceTarget, thisArg: unknown, args: any[]) { + return faceApply(target(), thisArg, args, apply) + }, + // like constructing the plain function the target used to be: an empty object, nothing recorded + construct: () => ({}) +} + +// bound to the face: a bound function is smaller than a closure and its context +const returnThis = function (this: Face): Face { return this } + +const createFaceProxy = (face: Face): any => { + const target: FaceTarget = returnThis.bind(face) + Object.setPrototypeOf(target, faceTargetPrototype) + return new Proxy(target, faceHandler) +} /** * D22: the substitution symbols configure a member or a call. On a substitute itself they cannot mean anything @@ -147,18 +181,18 @@ const substitutionOnSubstituteError = (property: PropertyKey, start: Function) = const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any => { if (isSpecialProperty(property)) return special(property, options => printFace(face, colorsOf(options)), face) - if (face.kind === 'root') { + if (!(face instanceof AutoEntry)) { if (isSubstitutionSymbol(property)) throw substitutionOnSubstituteError(property, stackStart) } else { - const entry = face.entry + const entry = face const method = substitutionMethodOf(property) if (method !== undefined) return setupFunction(entry, method) - if (face.kind === 'member' && isFunctionHelperKey(property)) + if (entry.kind === 'get' && isFunctionHelperKey(property)) return functionHelper(property, (args, start) => invoke(entry.parent, entry.key, args, start, TAKE_PENDING_READ)) // D11: `sub.received(n)` followed by a member access other than a substitution method is an assertion. - if (face.kind === 'result' && isStringAssertionKey(entry.key)) { + if (entry.kind === 'call' && isStringAssertionKey(entry.key)) { const assertion = resolveStringAssertion(entry, stackStart) return assertionMember(assertion.state, property, assertion.count, stackStart) } @@ -172,8 +206,8 @@ const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any = } const faceSet = (face: Face, property: PropertyKey, value: unknown, stackStart: Function): void => { - if (face.kind === 'result' && isStringAssertionKey(face.entry.key)) { - const assertion = resolveStringAssertion(face.entry, stackStart) + if (face instanceof AutoEntry && face.kind === 'call' && isStringAssertionKey(face.key)) { + const assertion = resolveStringAssertion(face, stackStart) assertSet(assertion.state, property, value, assertion.count, stackStart) return } @@ -181,17 +215,10 @@ const faceSet = (face: Face, property: PropertyKey, value: unknown, stackStart: realSet(faceState(face), property, value, chainHead, stackStart) } -const faceApply = (face: Face, args: any[], stackStart: Function): any => { - switch (face.kind) { - case 'root': - return invoke(face.state, SELF, args, stackStart, undefined) - case 'member': - return invoke(face.entry.parent, face.entry.key, args, stackStart, TAKE_PENDING_READ) - case 'result': { - const chainHead = face.entry.chainHead() - return invoke(face.entry.state, SELF, args, stackStart, undefined, chainHead) - } - } +const faceApply = (face: Face, _thisArg: unknown, args: any[], stackStart: Function): any => { + if (!(face instanceof AutoEntry)) return invoke(face, SELF, args, stackStart, undefined) + if (face.kind === 'get') return invoke(face.parent, face.key, args, stackStart, TAKE_PENDING_READ) + return invoke(face.state, SELF, args, stackStart, undefined, face.chainHead()) } /** `.call`, `.apply` and `.bind` on a member behave like invoking the member (D7). */ diff --git a/src/internals/RecordedArguments.ts b/src/internals/RecordedArguments.ts index 7fa7675..aa350e7 100644 --- a/src/internals/RecordedArguments.ts +++ b/src/internals/RecordedArguments.ts @@ -69,6 +69,13 @@ export class RecordedArguments { return new this(rawArguments) } + /** Whether two lists of actual (matcher-free) arguments are equal, argument by argument. */ + static literalsEqual(expected: readonly unknown[], actual: readonly unknown[]): boolean { + if (expected.length !== actual.length) return false + for (let index = 0; index < expected.length; index++) if (!literalEquals(expected[index], actual[index])) return false + return true + } + static containsMatchers(rawArguments: readonly unknown[]): boolean { for (const argument of rawArguments) if (isArgumentMatcher(argument)) return true return false diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index 2342b69..2ee2c4a 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -98,18 +98,36 @@ export class Substitution { * with matching arguments gets the same entry, so nested setups and assertions find each other. */ export class AutoEntry { - private _state?: SubstituteState - public proxy: any - /** The record of the operation that last handed out this entry's proxy, with the sequence number at that time. */ - public handedOutBy?: { record: CallRecord, seq: number } + // D30: the state (records, configuration, nested auto-substitutes) is only allocated when it is needed + private _state?: SubstituteState = undefined + public proxy: any = undefined + /** The record of the operation that last handed out this entry's proxy, and the sequence number at that time. */ + private _handedOutBy?: CallRecord = undefined + private _handedOutAt = 0 constructor( public readonly kind: 'get' | 'call', public readonly parent: SubstituteState, public readonly key: PropertyKey, - public readonly args?: RecordedArguments + /** The arguments of a call entry: a specification, or (D30: wrapped only when needed) the actual arguments. */ + private _args?: RecordedArguments | readonly unknown[] ) { } + public get args(): RecordedArguments | undefined { + const args = this._args + if (!Array.isArray(args)) return args as RecordedArguments | undefined + const wrapped = RecordedArguments.from(args) + this._args = wrapped + return wrapped + } + + /** Whether the arguments of this call entry match a call with these actual arguments. */ + public matchesCall(actualArguments: readonly unknown[]): boolean { + const args = this._args + if (args === undefined) return false + return Array.isArray(args) ? RecordedArguments.literalsEqual(args, actualArguments) : (args as RecordedArguments).matches(actualArguments) + } + public get state(): SubstituteState { if (this._state === undefined) this._state = new SubstituteState(this) return this._state @@ -120,7 +138,8 @@ export class AutoEntry { } public handOut(record: CallRecord): void { - this.handedOutBy = { record, seq: currentSequence() } + this._handedOutBy = record + this._handedOutAt = currentSequence() } /** @@ -129,8 +148,7 @@ export class AutoEntry { * later on in the chain retract it. */ public chainHead(): CallRecord | undefined { - const handedOutBy = this.handedOutBy - return handedOutBy !== undefined && handedOutBy.seq === currentSequence() ? handedOutBy.record : undefined + return this._handedOutAt === currentSequence() ? this._handedOutBy : undefined } } @@ -394,14 +412,14 @@ export class SubstituteState { } const identity = actual.identity if (identity !== undefined && index.byIdentity !== undefined) { - const known = bucketItems(index.byIdentity, identity)?.find(entry => entry.args!.matches(actualArguments)) + const known = bucketItems(index.byIdentity, identity)?.find(entry => entry.matchesCall(actualArguments)) if (known !== undefined) return known } const hash = actual.structural - let entry = bucketItems(index.byHash, hash)?.find(candidate => candidate.args!.matches(actualArguments)) + let entry = bucketItems(index.byHash, hash)?.find(candidate => candidate.matchesCall(actualArguments)) if (entry === undefined) { - entry = new AutoEntry('call', this, key, RecordedArguments.from(actualArguments as any[])) + entry = new AutoEntry('call', this, key, actualArguments) bucketAdd(index.byHash, hash, entry) } if (identity !== undefined) { From fb752db5f2ce572e743e322e8b834a1edc0579ec Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:19:05 +0000 Subject: [PATCH 035/106] feat(arguments): D27 Arg matchers nested in plain objects and arrays A matcher anywhere inside a plain object (prototype Object.prototype or null) or an array makes the call a setup or an assertion (D3), ranked with-predicate (D4). Matching is deep: the same prototype, the same length or own enumerable keys, nested matchers by their own logic (Arg.all() as the last array item matches the remaining items), deep strict equality for the rest. Cycles end. Matchers inside class instances, Maps and Sets stay literal (ENG2-5). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 79 ++++++++++- src/internals/RecordedArguments.ts | 200 +++++++++++++++++++++++++-- 2 files changed, 267 insertions(+), 12 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index 973810c..dc3f69e 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -1,7 +1,7 @@ import test, { ExecutionContext } from 'ava' import { spawnSync } from 'child_process' import * as path from 'path' -import { inspect, promisify } from 'util' +import { inspect, promisify, types } from 'util' import { Substitute, Arg, configure, mimick } from '../../../src' import { SubstituteException } from '../../../src/internals/SubstituteException' @@ -43,6 +43,83 @@ const reportsNothingLater = (t: ExecutionContext, run: () => unknown) => { } } +test('ENG2-5 (D27) Arg matchers nested in plain objects and arrays match deeply, and make the call a setup', t => { + const repository = Substitute.for() + repository.save({ id: Arg.any(), name: 'bob' }).returns('saved') + t.is(repository.save({ id: 1, name: 'bob' }), 'saved') + t.is(repository.save({ name: 'bob', id: 'x' }), 'saved', 'in any key order') + t.true(types.isProxy(repository.save({ id: 1, name: 'ann' }))) + t.true(types.isProxy(repository.save({ id: 1, name: 'bob', extra: true })), 'the same keys are needed') + t.true(types.isProxy(repository.save({ name: 'bob' }))) + t.true(types.isProxy(repository.save(Object.assign(Object.create(null), { id: 1, name: 'bob' }))), 'and the same prototype') + // D3: the setup was not recorded, the six real calls were + repository.received(6).save(Arg.all()) + repository.received(2).save({ id: Arg.any(), name: 'bob' }) + repository.received(1).save({ id: Arg.is((id: unknown) => id === 1), name: 'bob' }) + repository.didNotReceive().save({ id: Arg.any('string'), name: 'ann' }) + t.throws(() => repository.received(1).save({ id: Arg.any('boolean') }), { instanceOf: SubstituteException }) + + // arrays: the same length, item by item; Arg.all() as the last item matches the remaining items + const list = Substitute.for() + list.add([Arg.any('number'), 'x']).returns('pair') + t.is(list.add([1, 'x']), 'pair') + t.true(types.isProxy(list.add([1, 'x', 2]))) + t.true(types.isProxy(list.add(['1', 'x']))) + list.log(['level', Arg.all()]).returns('rest') + t.is(list.log(['level']), 'rest') + t.is(list.log(['level', 1, { a: 2 }]), 'rest') + t.true(types.isProxy(list.log(['other']))) + t.throws(() => list.find([Arg.all(), 1]), { instanceOf: SubstituteException, message: /must be the last item/ }) + + // deep nesting, null-prototype objects, symbol keys, Arg.all() as an object value + const key = Symbol('key') + const deep = Substitute.for() + deep.post({ body: { items: [{ sku: Arg.is((sku: string) => sku.startsWith('A')) }] }, [key]: Arg.all() }).returns('deep') + t.is(deep.post({ body: { items: [{ sku: 'A-1' }] }, [key]: undefined }), 'deep') + t.true(types.isProxy(deep.post({ body: { items: [{ sku: 'B-1' }] }, [key]: 1 }))) + t.true(types.isProxy(deep.post({ body: { items: [{ sku: 'A-1' }] } }))) + deep.put(Object.assign(Object.create(null), { id: Arg.any() })).returns('bare') + t.is(deep.put(Object.assign(Object.create(null), { id: 7 })), 'bare') + + // D4: ranked "with-predicate": a literal setup wins, and it wins over a wildcard + const ranked = Substitute.for() + ranked.get(Arg.all()).returns('wildcard') + ranked.get({ id: Arg.any() }).returns('nested') + ranked[configure]().get({ id: 1 }).returns('literal') // get({ id: 1 }) already answers 'nested' (D5) + t.is(ranked.get({ id: 1 }), 'literal') + t.is(ranked.get({ id: 2 }), 'nested') + t.is(ranked.get(3), 'wildcard') + // re-configuring the same nested specification replaces it + ranked.get({ id: Arg.any() }).returns('nested again') + t.is(ranked.get({ id: 2 }), 'nested again') + t.is(inspect(ranked).split('nested').length - 1, 1, 'one nested substitution, printed with its matcher') + t.true(inspect(ranked).includes("get({ id: Arg.any{any} }) => returns('nested again')")) + + // a throwing predicate is a non-match, and the message says so + const throwing = Substitute.for() + throwing.run({ value: 1 }) + const message = messageOf(() => throwing.received(1).run({ value: Arg.is(() => { throw new Error('boom') }) })) + t.true(message.includes('an Arg.is predicate threw while matching this call: Error: boom')) + + // matchers inside class instances, Maps and Sets stay literal (the call is a real call) + const literal = Substitute.for() + class Box { constructor(public value: unknown) { } } + literal.put(new Box(Arg.any())) + literal.put(new Map([['k', Arg.any()]])) + literal.received(2).put(Arg.all()) + + // cycles end, in the specification and in the actual arguments + const cyclicSpecification: any = { name: Arg.any() } + cyclicSpecification.self = cyclicSpecification + const cycles = Substitute.for() + cycles.visit(cyclicSpecification).returns('cyclic') + const cyclicValue: any = { name: 'x' } + cyclicValue.self = cyclicValue + t.is(cycles.visit(cyclicValue), 'cyclic') + cycles.visit({ name: 'x', self: { name: 'y', self: cyclicValue } }) + t.notThrows(() => cycles.received(2).visit(Arg.all())) +}) + test('ENG2-6 (D28) unconfigured well-known protocol symbols read as undefined and are not recorded', async t => { const callback = Substitute.for() t.is([].concat(callback).length, 1) diff --git a/src/internals/RecordedArguments.ts b/src/internals/RecordedArguments.ts index aa350e7..aae88b8 100644 --- a/src/internals/RecordedArguments.ts +++ b/src/internals/RecordedArguments.ts @@ -29,6 +29,160 @@ const literalEquals = (expected: unknown, actual: unknown): boolean => { } } +// ---- D27: matchers nested in plain objects and arrays ------------------------------------------ + +/** Arrays, and objects whose prototype is Object.prototype or null: the only values that may hold nested matchers. */ +const isPlainContainer = (value: unknown): value is object => { + if (typeof value !== 'object' || value === null || isArgumentMatcher(value)) return false + if (Array.isArray(value)) return true + const prototype = Object.getPrototypeOf(value) + return prototype === Object.prototype || prototype === null +} + +/** The own enumerable string and symbol keys of a plain object (the keys deep strict equality compares). */ +const ownEnumerableKeys = (object: object): PropertyKey[] => { + const keys: PropertyKey[] = Object.keys(object) + for (const symbol of Object.getOwnPropertySymbols(object)) + if (Object.prototype.propertyIsEnumerable.call(object, symbol)) keys.push(symbol) + return keys +} + +/** The values inside a plain container, with the position each one is at. */ +const containerEntries = (container: object): Array<[PropertyKey, unknown]> => Array.isArray(container) + ? Array.from({ length: container.length }, (_, index): [PropertyKey, unknown] => [index, container[index]]) + : ownEnumerableKeys(container).map((key): [PropertyKey, unknown] => [key, (container as any)[key]]) + +/** Whether some value inside a plain container satisfies the predicate, without allocating per item. */ +const someItem = (container: object, predicate: (item: unknown) => boolean): boolean => { + if (Array.isArray(container)) { + for (let index = 0; index < container.length; index++) if (predicate(container[index])) return true + return false + } + for (const key of Object.keys(container)) if (predicate((container as any)[key])) return true + for (const symbol of Object.getOwnPropertySymbols(container)) + if (Object.prototype.propertyIsEnumerable.call(container, symbol) && predicate((container as any)[symbol])) return true + return false +} + +const holdsMatcher = (container: object, visited: Set): boolean => { + visited.add(container) + return someItem(container, item => isArgumentMatcher(item) || (isPlainContainer(item) && !visited.has(item) && holdsMatcher(item, visited))) +} + +/** + * Whether a value has a matcher nested in a plain object or array (D27), at any depth. Every container is visited + * once, so cycles end. A container that cannot be read (a throwing getter) holds no matcher. + */ +const containsNestedMatcher = (value: unknown): boolean => { + if (!isPlainContainer(value)) return false + try { + return holdsMatcher(value, new Set()) + } catch { + return false + } +} + +/** The plain containers in `value` that hold a matcher somewhere inside, for a specification. */ +const collectMatcherContainers = (value: unknown, found: Set, visited: Set): boolean => { + if (isArgumentMatcher(value)) return true + if (!isPlainContainer(value) || visited.has(value)) return found.has(value as object) + visited.add(value) + let holds = false + try { + for (const [, item] of containerEntries(value)) if (collectMatcherContainers(item, found, visited)) holds = true + } catch { + return false + } + if (holds) found.add(value) + return holds +} + +const validateNestedAll = (container: object, matcherContainers: ReadonlySet, visited = new Set()): void => { + if (visited.has(container)) return + visited.add(container) + const entries = containerEntries(container) + entries.forEach(([, item], index) => { + if (Array.isArray(container) && isAllArguments(item) && index !== entries.length - 1) + throw SubstituteException.generic( + `Arg.all() in an array matches all remaining items, so it must be the last item. ` + + `Found ${entries.length - index - 1} item(s) after it.` + ) + if (matcherContainers.has(item as object)) validateNestedAll(item as object, matcherContainers, visited) + }) +} + +type Evaluation = { matches: boolean, predicateThrew?: boolean, predicateError?: unknown } +const MATCHES: Evaluation = { matches: true } +const DIFFERS: Evaluation = { matches: false } + +/** + * Matches an expected value that may hold nested matchers against an actual value (D27). Containers with matchers + * are compared structurally: the same kind (array, or object with the same prototype), the same length or the same + * own enumerable keys, and every item matches. A trailing Arg.all() in an array matches the remaining items, and + * Arg.all() as an object value matches any value. Everything else is compared with deep strict equality. + * A pair of containers that is already being compared further up matches (cycles end). + */ +const matchNested = (expected: unknown, actual: unknown, matcherContainers: ReadonlySet, comparing: Array<[unknown, unknown]>): Evaluation => { + if (isSingleArgument(expected)) { + if (isArgumentMatcher(actual)) return DIFFERS + const evaluation = evaluateArgument(expected, actual) + return evaluation.matches ? MATCHES : { matches: false, predicateThrew: evaluation.threw, predicateError: evaluation.error } + } + if (isAllArguments(expected)) return MATCHES + if (!matcherContainers.has(expected as object)) return literalEquals(expected, actual) ? MATCHES : DIFFERS + if (comparing.some(([e, a]) => e === expected && a === actual)) return MATCHES + + const container = expected as object + try { + if (typeof actual !== 'object' || actual === null || isArgumentMatcher(actual)) return DIFFERS + if (Array.isArray(container) !== Array.isArray(actual) || Object.getPrototypeOf(container) !== Object.getPrototypeOf(actual)) return DIFFERS + let pairs: Array<[unknown, unknown]> + if (Array.isArray(container)) { + const items = actual as unknown[] + const restIndex = container.length > 0 && isAllArguments(container[container.length - 1]) ? container.length - 1 : -1 + if (restIndex === -1 ? items.length !== container.length : items.length < restIndex) return DIFFERS + const compared = restIndex === -1 ? container.length : restIndex + pairs = Array.from({ length: compared }, (_, index): [unknown, unknown] => [container[index], items[index]]) + } else { + const keys = ownEnumerableKeys(container) + const actualKeys = ownEnumerableKeys(actual) + if (keys.length !== actualKeys.length || !keys.every(key => actualKeys.indexOf(key) !== -1)) return DIFFERS + pairs = keys.map((key): [unknown, unknown] => [(container as any)[key], (actual as any)[key]]) + } + comparing.push([expected, actual]) + try { + for (const [expectedItem, actualItem] of pairs) { + const evaluation = matchNested(expectedItem, actualItem, matcherContainers, comparing) + if (!evaluation.matches) return evaluation + } + } finally { + comparing.pop() + } + return MATCHES + } catch { + return DIFFERS + } +} + +/** Whether two expected values are the same specification (re-configuration), matchers compared as matchers. */ +const equivalentNested = (a: unknown, b: unknown, depth = 0): boolean => { + const aIsMatcher = isArgumentMatcher(a) + const bIsMatcher = isArgumentMatcher(b) + if (aIsMatcher || bIsMatcher) return aIsMatcher && bIsMatcher && argumentsAreEquivalent(a, b) + if (!containsNestedMatcher(a) && !containsNestedMatcher(b)) return literalEquals(a, b) + if (depth > 64 || !isPlainContainer(a) || !isPlainContainer(b)) return false + if (Array.isArray(a) !== Array.isArray(b) || Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false + try { + const aEntries = containerEntries(a) + const bEntries = containerEntries(b) + if (aEntries.length !== bEntries.length) return false + const bValues = new Map(bEntries) + return aEntries.every(([key, value]) => bValues.has(key) && equivalentNested(value, bValues.get(key), depth + 1)) + } catch { + return false + } +} + /** * An argument list. Either the actual arguments of a call, or the expected arguments of a setup or an * assertion (a specification), which may contain Arg matchers. @@ -39,12 +193,21 @@ const literalEquals = (expected: unknown, actual: unknown): boolean => { export class RecordedArguments { private _argumentsClass?: ArgumentsClass private _value?: any[] + /** D27: the plain objects and arrays among the arguments that hold matchers (undefined when there are none). */ + private _matcherContainers?: ReadonlySet private constructor(rawArguments: any[] | void) { if (typeof rawArguments === 'undefined') return this - this._argumentsClass = this.classifyArguments(rawArguments) this._value = rawArguments + let containers: Set | undefined + for (const argument of rawArguments) { + if (isArgumentMatcher(argument) || !containsNestedMatcher(argument)) continue + if (containers === undefined) containers = new Set() + collectMatcherContainers(argument, containers, new Set()) + } + this._matcherContainers = containers + this._argumentsClass = this.classifyArguments(rawArguments) } static from(rawArguments: any[]): RecordedArguments { @@ -66,7 +229,11 @@ export class RecordedArguments { `Arg.all() matches all remaining arguments, so it must be the last argument. ` + `Found ${rawArguments.length - allIndex - 1} argument(s) after it.` ) - return new this(rawArguments) + const specification = new this(rawArguments) + const containers = specification._matcherContainers + if (containers !== undefined) + for (const argument of rawArguments) if (containers.has(argument)) validateNestedAll(argument, containers) + return specification } /** Whether two lists of actual (matcher-free) arguments are equal, argument by argument. */ @@ -76,8 +243,9 @@ export class RecordedArguments { return true } + /** Whether the arguments hold an Arg matcher, as an argument or nested in plain objects and arrays (D3, D27). */ static containsMatchers(rawArguments: readonly unknown[]): boolean { - for (const argument of rawArguments) if (isArgumentMatcher(argument)) return true + for (const argument of rawArguments) if (isArgumentMatcher(argument) || containsNestedMatcher(argument)) return true return false } @@ -128,6 +296,13 @@ export class RecordedArguments { return evaluation.threw ? { matches: false, predicateThrew: true, predicateError: evaluation.error } : NO_MATCH continue } + const containers = this._matcherContainers + if (containers !== undefined && containers.has(expectedArgument)) { + const evaluation = matchNested(expectedArgument, actualArgument, containers, []) + if (!evaluation.matches) + return evaluation.predicateThrew === true ? { matches: false, predicateThrew: true, predicateError: evaluation.predicateError } : NO_MATCH + continue + } if (!literalEquals(expectedArgument, actualArgument)) return NO_MATCH } return expected.length === actualArguments.length ? MATCH : NO_MATCH @@ -139,17 +314,20 @@ export class RecordedArguments { const b = other._value if (a === undefined || b === undefined) return a === b if (a.length !== b.length) return false - return a.every((argument, index) => { - const otherArgument = b[index] - const aIsMatcher = isArgumentMatcher(argument) - const bIsMatcher = isArgumentMatcher(otherArgument) - if (aIsMatcher || bIsMatcher) return aIsMatcher && bIsMatcher && argumentsAreEquivalent(argument, otherArgument) - return literalEquals(argument, otherArgument) - }) + if (this._matcherContainers === undefined && other._matcherContainers === undefined) { + return a.every((argument, index) => { + const otherArgument = b[index] + const aIsMatcher = isArgumentMatcher(argument) + const bIsMatcher = isArgumentMatcher(otherArgument) + if (aIsMatcher || bIsMatcher) return aIsMatcher && bIsMatcher && argumentsAreEquivalent(argument, otherArgument) + return literalEquals(argument, otherArgument) + }) + } + return a.every((argument, index) => equivalentNested(argument, b[index])) } private classifyArguments(rawArguments: any[]): ArgumentsClass { - if (!RecordedArguments.containsMatchers(rawArguments)) return 'plain' + if (this._matcherContainers === undefined && !rawArguments.some(argument => isArgumentMatcher(argument))) return 'plain' if (rawArguments.length > 0 && isAllArguments(rawArguments[0])) return 'wildcard' return 'with-predicate' } From 3f0a214dc8b3f33d91cb990d4e4ccb1d2fd844ed Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:23:47 +0000 Subject: [PATCH 036/106] fix(engine): D25 chains only span operations from the same function A step continues the expression of the operation that handed out its proxy only when that operation was the last one of all and both have their first stack frame outside the library in the same file and the same enclosing function (V8 structured call sites, read lazily from the captured stacks). A setup or check on a value the code under test returned therefore no longer retracts the code under test's call (ENG2-1, V2-1). Without stack frames (Error.stackTraceLimit = 0) adjacency alone decides, as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 139 ++++++++++++++++++++++++++- src/internals/CallRecord.ts | 47 +++++---- src/internals/CallSite.ts | 135 ++++++++++++++++++++++++++ src/internals/Engine.ts | 90 +++++++++++------ src/internals/SubstituteState.ts | 12 +-- 5 files changed, 361 insertions(+), 62 deletions(-) create mode 100644 src/internals/CallSite.ts diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index dc3f69e..6b0bb7d 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -3,7 +3,7 @@ import { spawnSync } from 'child_process' import * as path from 'path' import { inspect, promisify, types } from 'util' -import { Substitute, Arg, configure, mimick } from '../../../src' +import { Substitute, Arg, configure, didNotReceive, mimick, received } from '../../../src' import { SubstituteException } from '../../../src/internals/SubstituteException' import { interceptDeferredReports } from '../../helpers/deferredReports' @@ -43,6 +43,143 @@ const reportsNothingLater = (t: ExecutionContext, run: () => unknown) => { } } +// ---- D25: code under test for the chain tests, in functions of its own (as in a module under test) ---- + +function getConnection(cache: any, driver: any) { + cache.get('conn') + return driver.connect('db://x') +} + +class Service { + constructor(private readonly app: any) { } + getLogger() { return this.app.logger } +} + +// test helpers in the same file as the code under test +function arrangeOpen(connection: any) { + connection.isOpen.returns(true) +} + +function arrangeCalculator(app: any) { + app.getCalc().add(1, 2).returns(99) +} + +test('ENG2-1 / V2-1 (D25) a setup or check on a value the code under test returned keeps the call that returned it', t => { + const cache = Substitute.for() + const driver = Substitute.for() + const connection = getConnection(cache, driver) + connection.isOpen.returns(true) + t.true(connection.isOpen) + t.throws(() => driver.didNotReceive().connect('db://x'), { instanceOf: SubstituteException }) + t.notThrows(() => driver.received(1).connect('db://x')) + t.notThrows(() => cache.received(1).get('conn')) + + // V2-1: a check on the returned auto-substitute + const factory = Substitute.for() + const connect = () => factory.create('db') + const created = connect() + created.didNotReceive().close() + t.notThrows(() => factory.received(1).create('db')) + + // a nested member returned by a method, checked with the string and the symbol forms, or configured + const app = Substitute.for() + const logger = new Service(app).getLogger() + logger.didNotReceive().info('x') + logger[didNotReceive]().warn('x') + logger[configure]().level.returns(3) + t.is(logger.level, 3) + t.notThrows(() => app.received(1).logger) + + // a value the code under test configured nothing on, asserted with a matcher call + const repository = Substitute.for() + const users = (() => repository.table('users'))() + users.find(Arg.any()).returns('found') + t.is(users.find(1), 'found') + t.notThrows(() => repository.received(1).table('users')) +}) + +test('ENG2-1 (D25) a chain written over several lines in one function is still one expression', t => { + const app = Substitute.for() + app + .getCalc() + .add(1, 2) + .returns(99) + t.is(inspect(app), '@Substitute {\n}', 'nothing of the setup is recorded') + t.is(app.getCalc().add(1, 2), 99) + app.received(1).getCalc() + + const service = Substitute.for() + service.logger.info('hi') + service + .logger + .received(1) + .info('hi') + service + .logger[received](1) + .info('hi') + t.notThrows(() => service.received(1).logger, 'only the real read is left') + + // the test's own stored handle, used in the same function, is part of the setup (accepted by D25) + const settings = Substitute.for() + const handle = settings.display + handle.level.returns(3) + t.is(settings.display.level, 3) + t.notThrows(() => settings.received(1).display) +}) + +test('ENG2-1 (D25) chains in a helper function in the same file as the code under test', t => { + const driver = Substitute.for() + const connection = getConnection(Substitute.for(), driver) + arrangeOpen(connection) + t.true(connection.isOpen) + t.notThrows(() => driver.received(1).connect('db://x')) + + const app = Substitute.for() + arrangeCalculator(app) + t.is(inspect(app), '@Substitute {\n}') + t.is(app.getCalc().add(1, 2), 99) +}) + +test('ENG2-1 (D25) code under test defined as an arrow function inside the test function', t => { + const driver = Substitute.for() + const open = (url: string) => driver.connect(url) + const connection = open('db://y') + connection.query('select 1').returns([1]) + t.deepEqual(connection.query('select 1'), [1]) + t.notThrows(() => driver.received(1).connect('db://y')) + t.throws(() => driver.didNotReceive().connect('db://y'), { instanceOf: SubstituteException }) + + const handlers = Substitute.for() + const register = function () { return handlers.on('click') } + register().didNotReceive().off() + t.notThrows(() => handlers.received(1).on('click')) +}) + +test('ENG2-1 (D25) without stack frames (Error.stackTraceLimit = 0) adjacency alone decides', t => { + const stackTraceLimit = Error.stackTraceLimit + Error.stackTraceLimit = 0 + try { + const app = Substitute.for() + app.getCalc().add(1, 2).returns(99) + t.is(inspect(app), '@Substitute {\n}') + t.is(app.getCalc().add(1, 2), 99) + + // the fallback: a setup right after the call that returned the value retracts that call... + const driver = Substitute.for() + const connection = getConnection(Substitute.for(), driver) + connection.isOpen.returns(true) + t.notThrows(() => driver.didNotReceive().connect('db://x')) + // ... unless another operation on a substitute happened in between + const other = Substitute.for() + const kept = getConnection(Substitute.for(), other) + Substitute.for().ping() + kept.isOpen.returns(true) + t.notThrows(() => other.received(1).connect('db://x')) + } finally { + Error.stackTraceLimit = stackTraceLimit + } +}) + test('ENG2-5 (D27) Arg matchers nested in plain objects and arrays match deeply, and make the call a setup', t => { const repository = Substitute.for() repository.save({ id: Arg.any(), name: 'bob' }).returns('saved') diff --git a/src/internals/CallRecord.ts b/src/internals/CallRecord.ts index f52d6fd..7e81e5c 100644 --- a/src/internals/CallRecord.ts +++ b/src/internals/CallRecord.ts @@ -1,3 +1,5 @@ +import { CallSite, Frame, StackHolder, captureStack } from './CallSite' + export type RecordKind = 'get' | 'set' | 'call' /** @@ -9,26 +11,6 @@ let sequence = 0 export const currentSequence = (): number => sequence const nextSequence = (): number => ++sequence -type StackHolder = { stack?: string } - -// Only the call site (the first frame) is ever shown, so only one frame is collected: collecting the -// whole stack for every call would dominate the cost of a call, especially with a raised stackTraceLimit. -const captureStack = (stackStart: Function): StackHolder => { - const holder: StackHolder = {} - if (typeof Error.captureStackTrace !== 'function') { - holder.stack = new Error().stack - return holder - } - const stackTraceLimit = Error.stackTraceLimit - if (!(stackTraceLimit >= 0 && stackTraceLimit <= 1)) Error.stackTraceLimit = 1 - try { - Error.captureStackTrace(holder, stackStart) - } finally { - Error.stackTraceLimit = stackTraceLimit - } - return holder -} - /** * One received interaction with a substitute: a property read, a property assignment or an invocation. * A property read whose result is then invoked is converted into the invocation (reading a method in @@ -37,7 +19,8 @@ const captureStack = (stackStart: Function): StackHolder => { export class CallRecord { public seq: number public retracted = false - private _stackHolder: StackHolder + /** The captured stack, wrapped in a CallSite (D30: only when it is needed). */ + private _site: StackHolder | CallSite constructor( public kind: RecordKind, @@ -45,20 +28,34 @@ export class CallRecord { public args: any[] | undefined, stackStart: Function, /** The record of the previous step when this one continues an expression chain (`a.b().c`). */ - public readonly chainPrevious?: CallRecord + public chainPrevious?: CallRecord ) { this.seq = nextSequence() - this._stackHolder = captureStack(stackStart) + this._site = captureStack(stackStart) + } + + private get site(): CallSite { + const site = this._site + if (site instanceof CallSite) return site + const wrapped = new CallSite(site) + this._site = wrapped + return wrapped } + /** The call site as a stack trace text, for messages. */ public get stack(): string | undefined { try { - return this._stackHolder.stack + return this.site.stack } catch { return undefined } } + /** The first frame outside the library (D25), or null when there is none. */ + public get frame(): Frame | null { + return this.site.frame + } + /** * Turns a property read into an invocation. When the invocation directly follows the read (the usual * `sub.method(...)`), the read already captured the right call site. @@ -67,7 +64,7 @@ export class CallRecord { const directlyInvoked = this.seq === currentSequence() this.kind = 'call' this.args = args - if (!directlyInvoked) this._stackHolder = captureStack(stackStart) + if (!directlyInvoked) this._site = captureStack(stackStart) this.seq = nextSequence() } } diff --git a/src/internals/CallSite.ts b/src/internals/CallSite.ts new file mode 100644 index 0000000..f30eb8e --- /dev/null +++ b/src/internals/CallSite.ts @@ -0,0 +1,135 @@ +/** + * Call sites of operations on substitutes: the first stack frame outside the library. + * + * Every received call keeps its call site, to show it in assertion messages. Collecting a stack trace is cheap; it + * is the formatting into text that costs, so V8 does it lazily, when `stack` is first read. The engine also needs to + * know, now and then, whether two operations come from the same expression in a test (D25). For that it reads the + * structured call site (file and enclosing function) of a captured stack, once, by formatting it with a + * prepareStackTrace that returns the V8 call sites. The text is then produced from those call sites when a message + * needs it. + */ + +type V8CallSite = { + getFileName(): string | null | undefined + getFunctionName(): string | null + getEnclosingLineNumber?(): number | null + getEnclosingColumnNumber?(): number | null + toString(): string +} + +/** A captured stack trace: V8 installs a lazily formatted `stack` property on it. */ +export type StackHolder = { stack?: unknown } + +/** + * The function the first frame outside the library runs in: its file, and the position where the function starts + * (V8 since Node 14.18) or, on older runtimes, its name. + */ +export type Frame = { readonly file: string | null | undefined, readonly enclosing: string | null } + +// Only the call site (the first frame) is ever used, so only one frame is collected: collecting the whole stack for +// every call would dominate the cost of a call, especially with a raised stackTraceLimit. Error.stackTraceLimit = 0 +// is honoured: then there is no call site at all. +export const captureStack = (stackStart: Function): StackHolder => { + const holder: StackHolder = {} + if (typeof Error.captureStackTrace !== 'function') { + holder.stack = new Error().stack + return holder + } + const stackTraceLimit = Error.stackTraceLimit + if (!(stackTraceLimit >= 0 && stackTraceLimit <= 1)) Error.stackTraceLimit = 1 + try { + Error.captureStackTrace(holder, stackStart) + } finally { + Error.stackTraceLimit = stackTraceLimit + } + return holder +} + +const returnCallSites = (_error: unknown, callSites: unknown) => callSites + +/** Reads the stack of a holder with a prepareStackTrace that returns the V8 call sites (undefined if it cannot). */ +const readCallSites = (holder: StackHolder): { callSites?: V8CallSite[], text?: unknown } => { + const errorConstructor = Error as { prepareStackTrace?: unknown } + const prepare = errorConstructor.prepareStackTrace + let replaced = false + try { + errorConstructor.prepareStackTrace = returnCallSites + replaced = errorConstructor.prepareStackTrace === returnCallSites + } catch { /* a frozen Error: no structured call sites */ } + let value: unknown + try { + value = holder.stack + } catch { + value = undefined + } finally { + if (replaced) { + try { + errorConstructor.prepareStackTrace = prepare + } catch { /* it was writable a moment ago */ } + } + } + return Array.isArray(value) ? { callSites: value as V8CallSite[] } : { text: value } +} + +const frameOf = (callSite: V8CallSite | undefined): Frame | null => { + if (callSite === undefined) return null + try { + const line = typeof callSite.getEnclosingLineNumber === 'function' ? callSite.getEnclosingLineNumber() : null + const column = typeof callSite.getEnclosingColumnNumber === 'function' ? callSite.getEnclosingColumnNumber() : null + const enclosing = typeof line === 'number' && typeof column === 'number' ? `${line}:${column}` : callSite.getFunctionName() + return { file: callSite.getFileName(), enclosing } + } catch { + return null + } +} + +const formatCallSites = (holder: StackHolder, callSites: V8CallSite[]): string => { + const prepare = (Error as { prepareStackTrace?: unknown }).prepareStackTrace + if (typeof prepare === 'function') { + try { + const formatted = prepare.call(Error, holder, callSites) + if (typeof formatted === 'string') return formatted + } catch { /* fall back to the default format */ } + } + return ['Error', ...callSites.map(callSite => ` at ${String(callSite)}`)].join('\n') +} + +/** The call site of one operation. The structured frame and the text are both worked out lazily. */ +export class CallSite { + // undefined: not read yet; null: not available (no frame, or not a V8 runtime) + private _frame?: Frame | null = undefined + private _callSites?: V8CallSite[] = undefined + private _text?: string = undefined + + constructor(private readonly _holder: StackHolder) { } + + public static capture(stackStart: Function): CallSite { + return new CallSite(captureStack(stackStart)) + } + + /** The first frame outside the library, or null when there is none (e.g. Error.stackTraceLimit = 0). */ + public get frame(): Frame | null { + if (this._frame === undefined) { + const { callSites, text } = readCallSites(this._holder) + this._callSites = callSites + if (typeof text === 'string') this._text = text + this._frame = callSites === undefined ? null : frameOf(callSites[0]) + } + return this._frame + } + + /** The stack trace as text (only the call site), for messages. */ + public get stack(): string | undefined { + if (this._frame === undefined) void this.frame // the call sites are read once, for the frame and the text + if (this._text !== undefined) return this._text + if (this._callSites === undefined) return undefined + return this._text = formatCallSites(this._holder, this._callSites) + } +} + +/** + * D25: whether two operations belong to the same expression: their call sites are in the same file and the same + * enclosing function. When a call site is not available, only adjacency counts (the caller has checked it). + */ +export const sameExpression = (a: Frame | null, b: Frame | null): boolean => + a === null || b === null || (a.file === b.file && a.enclosing === b.enclosing) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index aa65f68..2d4f4f6 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -3,6 +3,7 @@ import { inspect, InspectOptions, types } from 'util' import { isSubstituteProxy, substituteMarker } from '../shared' import { ArgumentHashes, AutoEntry, Substitution, SubstituteState } from './SubstituteState' import { CallRecord, currentSequence, retract } from './CallRecord' +import { CallSite, Frame, sameExpression } from './CallSite' import { RecordedArguments } from './RecordedArguments' import { SubstituteException } from './SubstituteException' import { assertCall, assertPropertyRead, assertSet, settle, validateExpectedCount, ExpectedCount } from './Assertions' @@ -112,7 +113,34 @@ const entryProxy = (entry: AutoEntry): any => { } const faceState = (face: Face): SubstituteState => face instanceof AutoEntry ? face.state : face -const faceChainHead = (face: Face): CallRecord | undefined => face instanceof AutoEntry ? face.chainHead() : undefined + +/* + * D25: chains. `sub.a.b(1).returns(2)` reads `a`, reads `b` on the auto-substitute that read handed out, and + * so on; a setup or an assertion at the end of the chain retracts the records of the whole expression. A step + * continues the expression of the operation that handed out its proxy when that operation was the last one of + * all (adjacency) and both come from the same function in the same file (their first stack frames outside the + * library). So a value that the code under test got from a substitute, and returned, does not take the code under + * test's call with it when the test configures or checks that value. Without stack frames (Error.stackTraceLimit + * = 0), adjacency alone decides. + */ + +/** The frame of the current operation, read only when it is needed (the trap function is the stack start). */ +const frameAt = (stackStart: Function) => (): Frame | null => CallSite.capture(stackStart).frame + +/** The candidate (an adjacent hand-out) if the current operation continues its expression. */ +const continuedChain = (candidate: CallRecord | undefined, current: () => Frame | null): CallRecord | undefined => { + if (candidate === undefined) return undefined + const head = candidate.frame + return head === null || sameExpression(head, current()) ? candidate : undefined +} + +/** Links a new record to the candidate if it continues the candidate's expression. */ +const linkChain = (record: CallRecord, candidate: CallRecord | undefined): CallRecord => { + if (continuedChain(candidate, () => record.frame) !== undefined) record.chainPrevious = candidate + return record +} + +const adjacentHandOut = (face: Face): CallRecord | undefined => face instanceof AutoEntry ? face.adjacentHandOut() : undefined /* * D30: a substitute, and every auto-substitute (one per distinct unconfigured call), is a proxy. To keep them small, @@ -181,44 +209,47 @@ const substitutionOnSubstituteError = (property: PropertyKey, start: Function) = const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any => { if (isSpecialProperty(property)) return special(property, options => printFace(face, colorsOf(options)), face) + const candidate = adjacentHandOut(face) + // for the operations that create no record: compared with the frame of this access + const chainHead = () => continuedChain(candidate, frameAt(stackStart)) + if (!(face instanceof AutoEntry)) { if (isSubstitutionSymbol(property)) throw substitutionOnSubstituteError(property, stackStart) } else { const entry = face const method = substitutionMethodOf(property) - if (method !== undefined) return setupFunction(entry, method) + if (method !== undefined) return setupFunction(entry, method, chainHead()) if (entry.kind === 'get' && isFunctionHelperKey(property)) return functionHelper(property, (args, start) => invoke(entry.parent, entry.key, args, start, TAKE_PENDING_READ)) // D11: `sub.received(n)` followed by a member access other than a substitution method is an assertion. if (entry.kind === 'call' && isStringAssertionKey(entry.key)) { - const assertion = resolveStringAssertion(entry, stackStart) + const assertion = resolveStringAssertion(entry, chainHead(), stackStart) return assertionMember(assertion.state, property, assertion.count, stackStart) } } const context = contextMethodOf(property) - if (context !== undefined) return contextFunction(context, () => faceState(face), faceChainHead(face)) + if (context !== undefined) return contextFunction(context, () => faceState(face), chainHead()) - const chainHead = faceChainHead(face) - return realGet(faceState(face), property, chainHead, stackStart) + return realGet(faceState(face), property, candidate, stackStart) } const faceSet = (face: Face, property: PropertyKey, value: unknown, stackStart: Function): void => { + const candidate = adjacentHandOut(face) if (face instanceof AutoEntry && face.kind === 'call' && isStringAssertionKey(face.key)) { - const assertion = resolveStringAssertion(face, stackStart) + const assertion = resolveStringAssertion(face, continuedChain(candidate, frameAt(stackStart)), stackStart) assertSet(assertion.state, property, value, assertion.count, stackStart) return } - const chainHead = faceChainHead(face) - realSet(faceState(face), property, value, chainHead, stackStart) + realSet(faceState(face), property, value, candidate, stackStart) } const faceApply = (face: Face, _thisArg: unknown, args: any[], stackStart: Function): any => { if (!(face instanceof AutoEntry)) return invoke(face, SELF, args, stackStart, undefined) if (face.kind === 'get') return invoke(face.parent, face.key, args, stackStart, TAKE_PENDING_READ) - return invoke(face.state, SELF, args, stackStart, undefined, face.chainHead()) + return invoke(face.state, SELF, args, stackStart, undefined, face.adjacentHandOut()) } /** `.call`, `.apply` and `.bind` on a member behave like invoking the member (D7). */ @@ -271,12 +302,12 @@ const answersProtocolKey = (state: SubstituteState, key: PropertyKey): boolean = (state.mimicked !== undefined && hasMember(state.mimicked.instance, key)) /** A real property read by the code under test. */ -const realGet = (state: SubstituteState, key: PropertyKey, chainPrevious: CallRecord | undefined, stackStart: Function): any => { +const realGet = (state: SubstituteState, key: PropertyKey, chainCandidate: CallRecord | undefined, stackStart: Function): any => { if (isProtocolKey(key) && !answersProtocolKey(state, key)) return undefined const substitution = state.propertySubstitution(key) if (substitution !== undefined) { - const record = state.addRecord('get', key, undefined, stackStart, chainPrevious) + const record = linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) // Configured both as a property and as a method: whether this read is a property read is only known later. if (state.hasCallSubstitutions(key)) return deferredRead(state, key, record, substitution) return execute(substitution) @@ -290,12 +321,12 @@ const realGet = (state: SubstituteState, key: PropertyKey, chainPrevious: CallRe !(isStringAssertionKey(key) || state.hasCallSubstitutions(key) || state.hasConfiguredPropertyEntry(key)) const value = delegate ? mimicked.instance[key] : undefined if (delegate && typeof value !== 'function') { - state.addRecord('get', key, undefined, stackStart, chainPrevious) + linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) return value } } - const record = state.addRecord('get', key, undefined, stackStart, chainPrevious) + const record = linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) state.addPendingRead(record) const entry = state.propertyEntry(key) entry.handOut(record) @@ -303,8 +334,8 @@ const realGet = (state: SubstituteState, key: PropertyKey, chainPrevious: CallRe } /** A real property assignment by the code under test. */ -const realSet = (state: SubstituteState, key: PropertyKey, value: unknown, chainPrevious: CallRecord | undefined, stackStart: Function): void => { - state.addRecord('set', key, [value], stackStart, chainPrevious) +const realSet = (state: SubstituteState, key: PropertyKey, value: unknown, chainCandidate: CallRecord | undefined, stackStart: Function): void => { + linkChain(state.addRecord('set', key, [value], stackStart), chainCandidate) if (state.mimicked !== undefined) state.mimicked.instance[key] = value } @@ -313,13 +344,13 @@ const realSet = (state: SubstituteState, key: PropertyKey, value: unknown, chain * substitution runs. Otherwise it is a real call: it is recorded (taking over the property read of the * method, if there is one) and resolved. */ -const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStart: Function, readSource: ReadSource, chainPrevious?: CallRecord): any => { +const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStart: Function, readSource: ReadSource, chainCandidate?: CallRecord): any => { const read = readSource === TAKE_PENDING_READ ? state.takePendingRead(key) : readSource if (RecordedArguments.containsMatchers(args)) { const specification = RecordedArguments.forSpecification(args) retract(read) - retract(chainPrevious) + retract(continuedChain(chainCandidate, frameAt(stackStart))) return configureCall(state, key, specification, isStringAssertionKey(key)) } @@ -327,7 +358,7 @@ const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStar if (read !== undefined && read.kind === 'get' && !read.retracted) { read.convertToCall(args, stackStart) record = read - } else record = state.addRecord('call', key, args, stackStart, chainPrevious) + } else record = linkChain(state.addRecord('call', key, args, stackStart), chainCandidate) return resolveCall(state, key, args, record) } @@ -356,28 +387,27 @@ const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], reco return entryProxy(entry) } -/** The actual arguments of the call that handed out this auto-substitute, when that was the previous operation. */ -const actualArgumentsOf = (entry: AutoEntry): any[] => { - const head = entry.chainHead() - if (head !== undefined && head.kind === 'call' && head.args !== undefined) return head.args +/** The actual arguments of the call that handed out this auto-substitute, when it is part of the same expression. */ +const actualArgumentsOf = (entry: AutoEntry, chainHead: CallRecord | undefined): any[] => { + if (chainHead !== undefined && chainHead.kind === 'call' && chainHead.args !== undefined) return chainHead.args return entry.args?.value ?? [] } /** `.returns(...)` and friends on a handle: configures the member read or the call that produced the handle. */ -const setupFunction = (entry: AutoEntry, method: SubstitutionMethod): Function => { +const setupFunction = (entry: AutoEntry, method: SubstitutionMethod, chainHead: CallRecord | undefined): Function => { const specification = entry.kind === 'call' && entry.args!.argumentsClass !== 'plain' - ? RecordedArguments.from(actualArgumentsOf(entry)) // handed out by a matcher setup: configure the actual call + ? RecordedArguments.from(actualArgumentsOf(entry, chainHead)) // handed out by a matcher setup: configure the actual call : entry.args - retract(entry.chainHead()) + retract(chainHead) return function substitution(...values: any[]) { if (entry.kind === 'get') entry.parent.setPropertySubstitution(entry.key, method, values) else entry.parent.addCallSubstitution(entry.key, specification!, method, values) } } -const resolveStringAssertion = (entry: AutoEntry, stackStart: Function): { state: SubstituteState, count: ExpectedCount } => { - const args = actualArgumentsOf(entry) - retract(entry.chainHead()) +const resolveStringAssertion = (entry: AutoEntry, chainHead: CallRecord | undefined, stackStart: Function): { state: SubstituteState, count: ExpectedCount } => { + const args = actualArgumentsOf(entry, chainHead) + retract(chainHead) const count = entry.key === 'didNotReceive' ? 0 : validateExpectedCount(args[0], stackStart) return { state: entry.parent, count } } @@ -437,7 +467,7 @@ const deferredRead = (state: SubstituteState, key: PropertyKey, record: CallReco if (isSpecialProperty(property)) return special(property, print, undefined) const method = substitutionMethodOf(property) if (method !== undefined) { - if (record.seq === currentSequence()) retract(record) + if (record.seq === currentSequence()) retract(continuedChain(record, frameAt(get))) return function substitution(...values: any[]) { state.setPropertySubstitution(key, method, values) } diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index 2ee2c4a..6daab60 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -143,11 +143,11 @@ export class AutoEntry { } /** - * The record that handed out this proxy, if that was the most recent operation of all. Then the - * current operation continues the same expression (`sub.a.b`), and setups or assertions resolved - * later on in the chain retract it. + * The record that handed out this proxy, if that was the most recent operation of all. Then the current + * operation may continue the same expression (`sub.a.b`): the engine checks that both come from the same + * function (D25), and setups or assertions resolved later on in the chain retract it. */ - public chainHead(): CallRecord | undefined { + public adjacentHandOut(): CallRecord | undefined { return this._handedOutAt === currentSequence() ? this._handedOutBy : undefined } } @@ -297,8 +297,8 @@ export class SubstituteState { // ---- received calls ------------------------------------------------------------------------- - public addRecord(kind: RecordKind, key: PropertyKey, args: any[] | undefined, stackStart: Function, chainPrevious?: CallRecord): CallRecord { - const record = new CallRecord(kind, key, args, stackStart, chainPrevious) + public addRecord(kind: RecordKind, key: PropertyKey, args: any[] | undefined, stackStart: Function): CallRecord { + const record = new CallRecord(kind, key, args, stackStart) this._records.push(record) const forKey = this._recordsByKey.get(key) if (forKey === undefined) this._recordsByKey.set(key, [record]) From cc41db29107556ebb7ba9347848fb00b3dec2548 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:27:26 +0000 Subject: [PATCH 037/106] types: keep the setup API and string assertions in generic code (TD-2, V2-2) With an unresolved type parameter, `repo.get(id).returns(value)` (a call that returns T) and `sub.received()` / `sub.didNotReceive()` on SubstituteOf no longer fail to compile; 2.0.0-beta.4 accepted both (T26). - SubstitutionResult has no separate `never` branch any more: for a type parameter the check is deferred and TypeScript only offers the members that all branches share, and the `never` branch had no `returns`. For `never` itself, `returns` takes `never`, so only `throws` and `mimicks` can be used. ConfigurationResult is the plain setup API. - The name-conflict checks (D11 / T:TY-2) are distributive over `NonNullable & {}` (resp. `T & {}`). For a constrained type parameter TypeScript still decides them through the constraint; an unconstrained one gets the constraint `{}`, which has no conflicting member, so all string forms are offered. T-TY-03 now expects the string forms in unconstrained generic helpers and adds the constrained-with-conflict case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/T-TY-03.G-RG-3.generic-helpers.ts | 21 ++++-- spec-types/TD-2.V2-2.T26.generic-code.ts | 79 ++++++++++++++++++++ src/api/types/SubstituteMethods.ts | 13 ++-- src/api/types/SubstitutionLevel.ts | 39 +++++----- 4 files changed, 117 insertions(+), 35 deletions(-) create mode 100644 spec-types/TD-2.V2-2.T26.generic-code.ts diff --git a/spec-types/T-TY-03.G-RG-3.generic-helpers.ts b/spec-types/T-TY-03.G-RG-3.generic-helpers.ts index 8ffe4aa..b27ec0a 100644 --- a/spec-types/T-TY-03.G-RG-3.generic-helpers.ts +++ b/spec-types/T-TY-03.G-RG-3.generic-helpers.ts @@ -1,7 +1,8 @@ // T:TY-3 / G:RG-3 received / didNotReceive / clearReceivedCalls / mimick / configure on SubstituteOf for a generic T. -// The symbol API is always available. The string forms `sub.received()` / `sub.didNotReceive()` are offered only when -// TypeScript can tell that T has no conflicting member (D11): for a constrained type parameter it checks the constraint, -// for an unconstrained one it cannot, so generic helpers use the symbol forms. +// The symbol API is always available. The string forms `sub.received()` / `sub.didNotReceive()` are offered unless +// TypeScript can tell that T has a conflicting member (D11): for a constrained type parameter it checks the constraint. +// For an unconstrained one the conflict cannot be decided, so the string forms are offered, as in 2.0.0-beta.4 (T26, +// see TD-2.V2-2.T26.generic-code.ts). import { Substitute, SubstituteOf, received, didNotReceive, clearReceivedCalls, mimick, configure } from '../src' export function expectNoCalls(sub: SubstituteOf) { @@ -52,10 +53,16 @@ export function viaConstraint(sub: SubstituteOf) { sub[received](2).add(1, 2) } -// An unconstrained T could have a member named `received` (or `returns`, ...), so the string forms are not offered. -export function stringFormsNeedAKnownType(sub: SubstituteOf) { - // @ts-expect-error use sub[received]() in generic code +// For an unconstrained T the conflict cannot be decided, so the string forms are offered (T26). +export function stringFormsInGenericCode(sub: SubstituteOf) { sub.received() - // @ts-expect-error use sub[didNotReceive]() in generic code sub.didNotReceive() } + +// A constraint with a conflicting member decides it: only the symbol forms. +interface Account { returns(item: string): number } +export function viaConflictingConstraint(sub: SubstituteOf) { + sub[received]().returns('book') + // @ts-expect-error ambiguous: the constraint has a member named `returns` + sub.received() +} diff --git a/spec-types/TD-2.V2-2.T26.generic-code.ts b/spec-types/TD-2.V2-2.T26.generic-code.ts new file mode 100644 index 0000000..39a24db --- /dev/null +++ b/spec-types/TD-2.V2-2.T26.generic-code.ts @@ -0,0 +1,79 @@ +// TD-2 / V2-2 / T26 Generic code, where a type is an unresolved type parameter. +// - The setup API (`.returns`, `.throws`, `.mimicks`, `.resolves`, the symbol forms and the configure view) is offered on +// calls that return the type parameter, as in 2.0.0-beta.4. +// - `sub.received()` / `sub.didNotReceive()` are offered on SubstituteOf for an unconstrained T: the D11 conflict rule +// applies only where it can be decided (concrete types, or a constraint; see T-TY-03.G-RG-3.generic-helpers.ts). +import { Substitute, SubstituteOf, Arg, configure, received, didNotReceive, returns, throws } from '../src' + +interface Repo { + get(id: string): T + find(id: string): T | undefined + all(): T[] + load(id: string): Promise + count: number + current: T + items: T[] +} + +export function stubRepo(repo: SubstituteOf>, value: T) { + repo.count.returns(1) + repo.get(Arg.any()).returns(value) + repo.get('a').returns(value, value) + repo.get('a').throws(new Error()) + repo.get('a').mimicks(id => value) + repo.get('a')[returns](value) + repo.get('a')[throws](new Error()) + repo.find('a').returns(undefined) + repo.find('a').returns(value) + repo.all().returns([value]) + repo.load('a').resolves(value) + repo.load('a').rejects(new Error()) + repo.items.returns([value]) + repo.current.returns(value) + repo[configure]().get('b').returns(value) + repo[configure]().find(Arg.all()).returns(value) + repo[configure]().current.returns(value) + repo.received().get('a') + repo.received(2).count + repo.didNotReceive().find(Arg.any()) + repo[received]().all() + repo[didNotReceive]().load('a') + + // @ts-expect-error the configured value must be a T + repo.get('a').returns(1) + // @ts-expect-error resolves() is only offered for promises + repo.get('a').resolves(value) +} + +// The G:RG-3 / V2-2 helpers +export function once(sub: SubstituteOf) { + return sub.received(1) +} +export function never(sub: SubstituteOf) { + return sub.didNotReceive() +} +export function expectNoCalls(sub: SubstituteOf) { + sub.didNotReceive() + sub.received() +} +export class Fixture { + sub = Substitute.for() + verify() { + return this.sub.received() + } +} + +interface Calc { add(a: number, b: number): number } +const calculator = Substitute.for() +calculator.add(1, 2) +once(calculator).add(1, 2) +never(calculator).add(3, 4) +new Fixture().verify().add(1, 2) +// @ts-expect-error the helpers keep the substituted type +once(calculator).subtract(1, 2) + +interface Entity { id: string } +export function stubEntity(repo: SubstituteOf>, value: T) { + repo.get('a').returns(value) + repo.received().get(value.id) +} diff --git a/src/api/types/SubstituteMethods.ts b/src/api/types/SubstituteMethods.ts index 4a7fd52..249037b 100644 --- a/src/api/types/SubstituteMethods.ts +++ b/src/api/types/SubstituteMethods.ts @@ -35,11 +35,12 @@ type StringSubstituteMethods = { // mimicks, `sub.received` / `sub.didNotReceive` are not offered and the symbol forms `sub[received]()` / // `sub[didNotReceive]()` must be used (D11). This rules out the ambiguous `sub.received().returns(...)`, which the // runtime treats as a setup of a member called `received`. -// Distributive over `T`, so that for a type parameter with a constraint (`T extends Calculator`) TypeScript resolves the -// check against the constraint. For an unconstrained type parameter the check cannot be resolved, so only the symbol -// forms are offered. -type StringSubstituteMethodsUnlessConflicting = T extends unknown ? - (HasAnyMember extends true ? {} : StringSubstituteMethods) : +// The check is distributive over `TCheck` (`T & {}`), so that for a type parameter TypeScript resolves it through the +// parameter's constraint (`T extends Calculator` is checked against Calculator). An unconstrained type parameter gets +// the constraint `{}` from the `& {}`: nothing conflicts, so generic helpers keep the string forms, as in 2.0.0-beta.4 +// (V2-2, TD-2, T26). The conflict rule applies where it can be decided: for concrete types and constraints. +type StringSubstituteMethodsUnlessConflicting = TCheck extends unknown ? + (HasAnyMember extends true ? {} : StringSubstituteMethods) : never -export type ObjectSubstituteMethods = SymbolSubstituteMethods & StringSubstituteMethodsUnlessConflicting +export type ObjectSubstituteMethods = SymbolSubstituteMethods & StringSubstituteMethodsUnlessConflicting diff --git a/src/api/types/SubstitutionLevel.ts b/src/api/types/SubstitutionLevel.ts index c3a91bc..1fdb270 100644 --- a/src/api/types/SubstitutionLevel.ts +++ b/src/api/types/SubstitutionLevel.ts @@ -41,29 +41,23 @@ type StringSetupMethods = { // The string form of a setup method is offered only when the value it is accessed on has no member with that name. // Otherwise `value.returns` would be the value's own member (the symbol form `value[returns]` always works). -// `TValue` is checked per union member (so that a constrained type parameter is resolved through its constraint), but the -// method type is computed from the whole value type, so a union return type does not split the method (T:TY-1). -type StringForm = TValue extends unknown ? - (HasMember extends true ? {} : { [P in TName]: TMethod }) : +// `TCheck` is `NonNullable & {}`. The check is distributive over it, so that TypeScript resolves the check +// for a type parameter through the parameter's constraint, and the `& {}` gives an unconstrained type parameter the +// constraint `{}`, which has no conflicting member: in generic code all string forms are offered (TD-2, T26). The method +// type itself is computed from the whole value type, so a union return type does not split the method (T:TY-1). +type StringForm = TCheck extends unknown ? + (HasMember extends true ? {} : { [P in TName]: TMethod }) : never type CheckedStringSetupMethods = - StringForm, 'returns', ReturnsFunction> & - StringForm, 'throws', ThrowsFunction> & - StringForm, 'mimicks', MimicksFunction> & + StringForm & {}, 'returns', ReturnsFunction> & + StringForm & {}, 'throws', ThrowsFunction> & + StringForm & {}, 'mimicks', MimicksFunction> & (IsPromise extends true ? ( - StringForm, 'resolves', ResolvesFunction>> & - StringForm, 'rejects', RejectsFunction> + StringForm & {}, 'resolves', ResolvesFunction>> & + StringForm & {}, 'rejects', RejectsFunction> ) : {}) -// A member that never returns can only throw (or mimick an implementation that throws). -type NeverSetupMethods = { - [throws]: ThrowsFunction - [mimicks]: MimicksFunction - throws: ThrowsFunction - mimicks: MimicksFunction -} - /** * The setup API offered on the result of a member access or call of a substitute. * `TReturnType` is the member's value (or return) type, `TImplementation` the function type `mimicks` accepts. @@ -79,14 +73,15 @@ export type UncheckedSetupMethods = /** * The type of a member access or call on a substitute: the value intersected with the setup API. * `null` and `undefined` cannot carry the setup API, so they are dropped from the value part (T:TY-9), while the - * setup methods still accept them. `never` (a member that always throws) only offers `throws` and `mimicks` (T:TY-12). + * setup methods still accept them. When nothing is left (`null`, `undefined` or `never`), only the setup API remains. + * For `never` (a member that always throws) `returns` accepts no value (T:TY-12), so only `throws` and `mimicks` can be + * used. + * There is deliberately no separate branch for `never`: for a type parameter (generic code) the check cannot be + * decided, and TypeScript then only offers the members that all branches have (TD-2, T26). */ export type SubstitutionResult = - [TReturnType] extends [never] ? NeverSetupMethods : [NonNullable] extends [never] ? UncheckedSetupMethods : NonNullable & SetupMethods /** The type of a member access or call on the `[configure]()` view: only the setup API. */ -export type ConfigurationResult = - [TReturnType] extends [never] ? NeverSetupMethods : - UncheckedSetupMethods +export type ConfigurationResult = UncheckedSetupMethods From 78a502908a171efd0e3207f7f6d3d96f7b9d1375 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:28:09 +0000 Subject: [PATCH 038/106] types: members typed only null/undefined keep their plain type (TD-1) A member whose type is only `null` and/or `undefined` (`error?: undefined` in an XOR-style type, lib.dom's `Document.ownerDocument: null`) was mapped to the setup API, an object type. Intersected with the member's own `null` / `undefined` through `& T`, it made TypeScript reduce the whole SubstituteOf to `never`, so `Substitute.for()` was unusable (T25). Such members are now `unknown` in the mapped part, so they keep their plain type from `T` and have no setup API (there is nothing to configure). Trade-off, documented in the fixtures: for a PROPERTY whose type is an unresolved type parameter (`current: T` in generic code) TypeScript cannot decide this check, so that property has no setup API in generic code; it is configured with `sub[configure]().current`. Calls returning the type parameter are not affected. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/TD-1.T25.null-only-members.ts | 51 ++++++++++++++++++++++++ spec-types/TD-2.V2-2.T26.generic-code.ts | 6 ++- src/api/types/Substitute.ts | 9 +++++ 3 files changed, 65 insertions(+), 1 deletion(-) create mode 100644 spec-types/TD-1.T25.null-only-members.ts diff --git a/spec-types/TD-1.T25.null-only-members.ts b/spec-types/TD-1.T25.null-only-members.ts new file mode 100644 index 0000000..939bedb --- /dev/null +++ b/spec-types/TD-1.T25.null-only-members.ts @@ -0,0 +1,51 @@ +// TD-1 / T25 A member typed only `null` and/or `undefined` (`error?: undefined`, `ownerDocument: null`) does not +// reduce SubstituteOf to `never`. Such a member keeps its plain type and has no setup API. +import { Substitute, Arg, received } from '../src' +import { assert, Equals } from './helpers' + +// A variant of a discriminated union, written the usual "XOR" way +interface Ok { data: string; error?: undefined } +const ok = Substitute.for() +ok.data.returns('x') +ok.received().data +ok[received](1).data +assert>() +const asOk: Ok = ok + +interface Members { + nothing: null + missing: undefined + maybeNothing?: null + either: null | undefined + count: number + reset(): void + find(id: string): null +} +const members = Substitute.for() +members.count.returns(1) +members.reset().returns() +members.find(Arg.any()).returns(null) +assert>() +assert>() +assert>() +members.received().find('1') +const asMembers: Members = members + +// @ts-expect-error nothing to configure on a member that can only be null +members.nothing.returns(null) +// @ts-expect-error nothing to configure on a member that can only be undefined +ok.error.returns(undefined) + +// lib.dom: Document.ownerDocument is `null`, as are the `textContent` overrides of Document and DocumentType +const doc = Substitute.for() +doc.title.returns('t') +doc.getElementById('x').returns(null) +doc.querySelector(Arg.any()).returns(null) +doc.received().getElementById('x') +assert>() +const asDocument: Document = doc +const documentType = Substitute.for() +documentType.name.returns('html') +const asDocumentType: DocumentType = documentType + +export { asOk, asMembers, asDocument, asDocumentType } diff --git a/spec-types/TD-2.V2-2.T26.generic-code.ts b/spec-types/TD-2.V2-2.T26.generic-code.ts index 39a24db..10c144e 100644 --- a/spec-types/TD-2.V2-2.T26.generic-code.ts +++ b/spec-types/TD-2.V2-2.T26.generic-code.ts @@ -3,6 +3,9 @@ // calls that return the type parameter, as in 2.0.0-beta.4. // - `sub.received()` / `sub.didNotReceive()` are offered on SubstituteOf for an unconstrained T: the D11 conflict rule // applies only where it can be decided (concrete types, or a constraint; see T-TY-03.G-RG-3.generic-helpers.ts). +// - Limitation: a PROPERTY whose type is the type parameter itself (`current: T`) has no setup API on the substitute +// (TypeScript cannot tell it apart from a member that can only be null or undefined, see TD-1.T25.null-only-members.ts). +// Configure it through the configure view: `repo[configure]().current.returns(value)`. import { Substitute, SubstituteOf, Arg, configure, received, didNotReceive, returns, throws } from '../src' interface Repo { @@ -29,7 +32,6 @@ export function stubRepo(repo: SubstituteOf>, value: T) { repo.load('a').resolves(value) repo.load('a').rejects(new Error()) repo.items.returns([value]) - repo.current.returns(value) repo[configure]().get('b').returns(value) repo[configure]().find(Arg.all()).returns(value) repo[configure]().current.returns(value) @@ -43,6 +45,8 @@ export function stubRepo(repo: SubstituteOf>, value: T) { repo.get('a').returns(1) // @ts-expect-error resolves() is only offered for promises repo.get('a').resolves(value) + // @ts-expect-error limitation: a property typed as the type parameter itself; use repo[configure]().current + repo.current.returns(value) } // The G:RG-3 / V2-2 helpers diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index c9a4fe3..4fc9a8c 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -16,6 +16,14 @@ type Members = string extends keyof T ? T : Pick // All views are mapped with `-?` and expand calls from the member type without `null | undefined`, so optional members // (`prop?`, `method?()`) are configured and asserted like required ones (T:TY-7). // +// Members whose type is only `null` and/or `undefined` (`error?: undefined`, `ownerDocument: null`) get no setup API: +// there is nothing to configure, and an object type intersected with `null` would reduce the whole substitute to +// `never` (TD-1, T25). They are `unknown` here, so that `SubstituteOf` gives them their plain type from `T`. +// For a property whose type is an unresolved type parameter (`current: T` in generic code), TypeScript cannot decide +// this check and only keeps what both branches have, i.e. nothing: such a property has no setup API in generic code. +// It is configured through `sub[configure]().current`. (Calls are not affected: their results never meet `T`'s own +// property types, so they keep the setup API in both branches; see `SubstitutionResult`.) +// // Special members (T:TY-16, D20). At runtime a substitute never exposes `then`, so that it is not a thenable // (`await sub` resolves to the substitute itself); the typings make `then` `never`. `toJSON` is answered by the // substitute itself (it serializes the substitute): it keeps its declared type on the substitute (through `& T`) but @@ -28,6 +36,7 @@ type SubstituteMembers = { [P in keyof T]-?: P extends 'then' ? never : P extends 'toJSON' ? unknown : + [NonNullable] extends [never] ? unknown : SubstituteMember } From 9623604ab141f70ea5c4bc847bfd398a3f882daf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:28:29 +0000 Subject: [PATCH 039/106] feat(engine): D26 call, apply and bind with a member and a direct-call reading On any function-like substitute value (a substitute, a member handle, a call result, a nested auto-substitute), x.call / x.apply / x.bind give a helper. Invoking it answers with a substitution on x's member of that name when one matches the raw arguments (or a mimicked instance's own member), and otherwise behaves like Function.prototype.call/apply/bind on x. The invocation is recorded once with both readings, so x.received().call(t, 1) and x.received()(1) both count it; String(sub) and assertion listings show it once, as 'm(1) via .call(t, 1)'. Setups through the helpers configure the member reading; for bind, invoking the bound function is the direct call. The this of a direct call reaches a mimicked function and mimicks() (ENG2-3, ENG2-4). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 107 +++++++++++++ src/internals/CallRecord.ts | 28 +++- src/internals/Engine.ts | 221 ++++++++++++++++++++++++--- src/internals/SubstituteException.ts | 4 +- src/internals/utilities/Stringify.ts | 13 ++ 5 files changed, 343 insertions(+), 30 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index 6b0bb7d..46c895c 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -180,6 +180,113 @@ test('ENG2-1 (D25) without stack frames (Error.stackTraceLimit = 0) adjacency al } }) +test('ENG2-3 (D26) call/apply/bind on a function substitute or a call result behave like a direct call', t => { + // a once()-style helper forwards with fn.apply(this, args) + const once = (fn: any) => { + let done = false + let result: unknown + return function (this: unknown, ...args: unknown[]) { + if (!done) { + done = true + result = fn.apply(this, args) + } + return result + } + } + const listener = Substitute.for() + listener('saved').returns('ack') + t.is(once(listener)('saved'), 'ack') + t.throws(() => listener[didNotReceive]()(Arg.all()), { instanceOf: SubstituteException }) + t.notThrows(() => listener[received](1)('saved')) + t.notThrows(() => listener[received](1).apply(undefined, ['saved']), 'the member reading counts it too') + t.is(inspect(listener).split('\n')[2], " ('saved') via .apply(undefined, [ 'saved' ])", 'shown once') + + const callback = Substitute.for() + callback(1).returns(5) + t.is(callback.call(null, 1), 5) + t.is(callback.apply(null, [1]), 5) + t.is(callback.bind(null)(1), 5) + t.is(callback.bind(null, 1)(), 5) + t.notThrows(() => callback[received](4)(1)) + t.notThrows(() => callback[received](1).bind(null, 1), 'the bind call itself only counts as a call of the member bind') + t.true(types.isProxy(callback.call(null, 9))) + + // call results and nested auto-substitutes + const factory = Substitute.for() + factory.create()(2).returns('two') + t.is(factory.create().call(null, 2), 'two') + t.is(factory.create().apply(null, [2]), 'two') + factory.handlers.onSave('x').returns('saved') + t.is(factory.handlers.onSave.call(null, 'x'), 'saved') + t.notThrows(() => factory.handlers.received(1).onSave('x')) + + // the thisArg reaches a mimicked function and mimicks(), also through the proxy apply trap + const add = Substitute.for() + add[mimick](function (this: any, value: number) { return this.base + value }) + const calculator = { base: 5, add } + t.is(calculator.add(1), 6) + t.is(add.call({ base: 10 }, 1), 11) + t.is(add.apply({ base: 20 }, [1]), 21) + t.is(add.bind({ base: 30 })(1), 31) + t.notThrows(() => add[received](4)(1)) + const scale = Substitute.for() + scale(Arg.any()).mimicks(function (this: any, value: number) { return this.factor * value }) + t.is(scale.call({ factor: 3 }, 2), 6) + const scaler = { factor: 4, scale } + t.is(scaler.scale(2), 8) + const service = Substitute.for() + service[mimick]({ base: 1, plus(this: any, value: number) { return this.base + value } }) + t.is(service.plus(1), 2, 'a mimicked instance method still runs on the instance (D12)') + t.is(service.plus.call({ base: 100 }, 1), 101, 'unless a thisArg is given') +}) + +test('ENG2-4 (D26) members named call/apply/bind keep their member reading', t => { + const shop = Substitute.for() + const cart = { total: 10 } + shop.discount.apply(cart) + shop.socket.bind(8080) + shop.rpc.call('getUser', 1) + t.notThrows(() => shop.discount.received().apply(cart)) + t.notThrows(() => shop.socket.received().bind(8080)) + t.notThrows(() => shop.rpc.received().call('getUser', 1)) + t.notThrows(() => shop.rpc.received(1).call('getUser', Arg.any())) + t.throws(() => shop.rpc.received().call('deleteUser', 1), { instanceOf: SubstituteException }) + // ... and the direct reading counts them as well (bind only when the bound function is invoked) + t.notThrows(() => shop.received(1).rpc(1)) + t.notThrows(() => shop.received(1).discount()) + t.notThrows(() => shop.received(1).socket, 'socket was only read: the bind call is a call of its member bind') + t.is(inspect(shop), "@Substitute {\n received:\n discount() via .apply({ total: 10 })\n socket\n rpc(1) via .call('getUser', 1)\n}") + const message = messageOf(() => shop.received(2).rpc(1)) + t.true(message.includes("› ✔ @Substitute.rpc(1) via .call('getUser', 1)")) + + // setups through call configure the member reading + const app = Substitute.for() + app.rpc.call('getUser', 1).returns({ name: 'ann' }) + t.deepEqual(app.rpc.call('getUser', 1), { name: 'ann' }) + t.true(types.isProxy(app.rpc.call('deleteUser', 1))) + t.true(types.isProxy(app.rpc(1)), 'the direct reading is not configured by it') + app[configure]().rpc.call('list').returns(['a']) + t.deepEqual(app.rpc.call('list'), ['a']) + app.rpc.apply(Arg.any(), Arg.is((list: unknown[]) => list.length === 0)).returns('empty') + t.is(app.rpc.apply(null, []), 'empty') + app.bus.bind('topic').returns('subscription') + t.is(app.bus.bind('topic'), 'subscription') + t.true(types.isProxy(app.bus.bind('other'))) + t.is(inspect(app).includes('received:'), true) + t.notThrows(() => app.rpc.received(1).call('getUser', 1)) + + // a mimicked instance with a member named call answers under the member reading + const client = Substitute.for() + client[mimick]({ call: (method: string, id: number) => `${method}:${id}` }) + t.is(client.call('getUser', 1), 'getUser:1') + t.notThrows(() => client.received(1).call('getUser', 1)) + + // a member named call configured as a property answers as a property + const property = Substitute.for() + property[configure]().call.returns('configured') + t.is(property.call, 'configured') +}) + test('ENG2-5 (D27) Arg matchers nested in plain objects and arrays match deeply, and make the call a setup', t => { const repository = Substitute.for() repository.save({ id: Arg.any(), name: 'bob' }).returns('saved') diff --git a/src/internals/CallRecord.ts b/src/internals/CallRecord.ts index 7e81e5c..a2745d9 100644 --- a/src/internals/CallRecord.ts +++ b/src/internals/CallRecord.ts @@ -21,6 +21,15 @@ export class CallRecord { public retracted = false /** The captured stack, wrapped in a CallSite (D30: only when it is needed). */ private _site: StackHolder | CallSite + /** + * D26: an invocation through `x.call(...)` / `x.apply(...)` is recorded once, with two readings: a call of x's + * member `call` / `apply` with the raw arguments, and a direct call of x. Each reading is a record of its own + * substitute and member, so that assertions match either one, and each one points to the other. Retracting one + * retracts both. (Left undeclared on ordinary records, which then do not carry the fields.) + */ + public twin?: CallRecord + /** True on the direct-call reading of such an invocation. */ + public directReading?: boolean constructor( public kind: RecordKind, @@ -74,9 +83,20 @@ export class CallRecord { * expression turned out to be a setup or an assertion rather than a real use. */ export const retract = (record: CallRecord | undefined): void => { - let current = record - while (current !== undefined && !current.retracted) { - current.retracted = true - current = current.chainPrevious + const pending: CallRecord[] = record === undefined ? [] : [record] + while (pending.length > 0) { + let current: CallRecord | undefined = pending.pop() + while (current !== undefined && !current.retracted) { + current.retracted = true + if (current.twin !== undefined && !current.twin.retracted) pending.push(current.twin) + current = current.chainPrevious + } } } + +/** D26: makes two records the member reading and the direct-call reading of one invocation. */ +export const pairReadings = (memberReading: CallRecord, directReading: CallRecord): void => { + memberReading.twin = directReading + directReading.twin = memberReading + directReading.directReading = true +} diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 2d4f4f6..05836c1 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -2,7 +2,7 @@ import { inspect, InspectOptions, types } from 'util' import { isSubstituteProxy, substituteMarker } from '../shared' import { ArgumentHashes, AutoEntry, Substitution, SubstituteState } from './SubstituteState' -import { CallRecord, currentSequence, retract } from './CallRecord' +import { CallRecord, currentSequence, pairReadings, retract } from './CallRecord' import { CallSite, Frame, sameExpression } from './CallSite' import { RecordedArguments } from './RecordedArguments' import { SubstituteException } from './SubstituteException' @@ -11,7 +11,7 @@ import { ContextMethod, FunctionHelperKey, INTERNAL, SELF, SpecialProperty, SubstitutionMethod, contextMethodOf, isFunctionHelperKey, isProtocolKey, isSpecialProperty, isStringAssertionKey, keyToString, substitutionMethodOf } from './Constants' -import { formatArguments, formatValue, isPrinting, withPrintGuard } from './utilities' +import { describeOtherReading, formatArguments, formatValue, isPrinting, withPrintGuard } from './utilities' /* * The proxies handed out by the library are thin translators onto SubstituteState. @@ -56,12 +56,15 @@ const printState = (state: SubstituteState, colors: boolean): string => { return withPrintGuard(() => { const lines: string[] = [] const records = state.records - if (records.length > 0) { + // D26: an invocation through call/apply is shown once, as its direct-call reading + const directReadings = new Set(records.filter(record => record.directReading === true)) + const shown = records.filter(record => record.twin === undefined || record.directReading === true || !directReadings.has(record.twin)) + if (shown.length > 0) { lines.push(' received:') - for (const record of records) { + for (const record of shown) { const name = record.key === SELF ? '' : keyToString(record.key) const suffix = record.kind === 'call' - ? formatArguments(record.args, colors) + ? formatArguments(record.args, colors) + describeOtherReading(record, colors) : record.kind === 'set' ? ` = ${formatValue(record.args?.[0], colors)}` : '' lines.push(` ${name}${suffix}`) } @@ -220,9 +223,6 @@ const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any = const method = substitutionMethodOf(property) if (method !== undefined) return setupFunction(entry, method, chainHead()) - if (entry.kind === 'get' && isFunctionHelperKey(property)) - return functionHelper(property, (args, start) => invoke(entry.parent, entry.key, args, start, TAKE_PENDING_READ)) - // D11: `sub.received(n)` followed by a member access other than a substitution method is an assertion. if (entry.kind === 'call' && isStringAssertionKey(entry.key)) { const assertion = resolveStringAssertion(entry, chainHead(), stackStart) @@ -230,6 +230,10 @@ const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any = } } + // D26: call/apply/bind, unless the member with that name is configured as a property + if (isFunctionHelperKey(property) && memberStateOf(face)?.propertySubstitution(property) === undefined) + return dualHelper(face, property, chainHead()) + const context = contextMethodOf(property) if (context !== undefined) return contextFunction(context, () => faceState(face), chainHead()) @@ -246,13 +250,170 @@ const faceSet = (face: Face, property: PropertyKey, value: unknown, stackStart: realSet(faceState(face), property, value, candidate, stackStart) } -const faceApply = (face: Face, _thisArg: unknown, args: any[], stackStart: Function): any => { - if (!(face instanceof AutoEntry)) return invoke(face, SELF, args, stackStart, undefined) - if (face.kind === 'get') return invoke(face.parent, face.key, args, stackStart, TAKE_PENDING_READ) - return invoke(face.state, SELF, args, stackStart, undefined, face.adjacentHandOut()) +/** + * A direct invocation of a substitute (the proxy apply trap). D26: the `this` of the invocation is passed on to a + * mimicked function and to mimicks(), so that `obj.add = fnSubstitute; obj.add(1)` runs with `this === obj`. + * (A mimicked instance's own method keeps running on the instance, D12.) + */ +const faceApply = (face: Face, thisArg: unknown, args: any[], stackStart: Function): any => { + const self = { thisArg, explicit: false } + if (!(face instanceof AutoEntry)) return invoke(face, SELF, args, stackStart, undefined, undefined, self) + if (face.kind === 'get') return invoke(face.parent, face.key, args, stackStart, TAKE_PENDING_READ, undefined, self) + return invoke(face.state, SELF, args, stackStart, undefined, face.adjacentHandOut(), self) +} + +// ---- D26: call, apply and bind ---------------------------------------------------------------- + +/** The substitute whose members `x.call` and friends are under the member reading (undefined: not created yet). */ +const memberStateOf = (face: Face): SubstituteState | undefined => face instanceof AutoEntry ? face.materializedState : face + +/** Where a direct call of the substitute is recorded and resolved: `fn(...)`, `sub.method(...)` or `sub.f()(...)`. */ +type DirectReading = { state: SubstituteState, key: PropertyKey, readSource: ReadSource } +const directReadingOf = (face: Face): DirectReading => { + if (!(face instanceof AutoEntry)) return { state: face, key: SELF, readSource: undefined } + if (face.kind === 'get') return { state: face.parent, key: face.key, readSource: TAKE_PENDING_READ } + return { state: face.state, key: SELF, readSource: undefined } +} + +const NOT_CONFIGURED: unique symbol = Symbol('not configured') + +/** + * The member reading answers when a substitution configured on the member named call/apply/bind matches the raw + * arguments, or when a mimicked instance has such a member of its own (a function's call/apply/bind inherited from + * Function.prototype is the direct reading itself, recorded as such). + */ +const memberReadingAnswer = (state: SubstituteState, helper: FunctionHelperKey, rawArgs: any[], hashes: ArgumentHashes, record: CallRecord, thisArg: unknown): any => { + const substitution = state.findCallSubstitution(helper, hashes) + if (substitution !== undefined) { + if (substitution.method === 'auto') substitution.entry!.handOut(record) + return execute(substitution, rawArgs, thisArg) + } + const instance = state.mimicked?.instance + if (instance !== undefined && hasMember(instance, helper)) { + const member = instance[helper] + if (typeof member === 'function' && member !== (Function.prototype as any)[helper]) return Reflect.apply(member, instance, rawArgs) + } + return NOT_CONFIGURED +} + +/** The arguments `x.apply(thisArg, list)` passes to x, or undefined when the list is not array-like. */ +const applyArguments = (list: unknown): any[] | undefined => { + if (list === undefined || list === null) return [] + if (typeof list !== 'object' && typeof list !== 'function') return undefined + try { + return Array.from(list as ArrayLike) + } catch { + return undefined + } +} + +/** + * `x.call` / `x.apply` / `x.bind` on any function-like substitute value (D26). Invoking the helper: + * (a) answers with a substitution configured on x's member of that name, when one matches the raw arguments; + * (b) otherwise behaves like Function.prototype.call/apply/bind on x: the configured value of x(...arguments) (a + * mimicked function or mimicks() receives the thisArg). + * The invocation is recorded once, with both readings (see CallRecord.twin), so that `x.received().call(t, 1)` and + * `x.received()(1)` both count it. Setups written through the helper (`.returns` on its result, or arguments with + * matchers) configure the member reading. For bind, the bind call is only a call of the member `bind`; invoking the + * bound function is a direct call of x with the bound arguments first. + */ +const dualHelper = (face: Face, helper: FunctionHelperKey, chainHead: CallRecord | undefined): Function => { + const invokeHelper = (rawArgs: any[], thisArg: unknown, directArgs: any[] | undefined, stackStart: Function): any => { + const direct = directReadingOf(face) + const read = direct.readSource === TAKE_PENDING_READ ? direct.state.takePendingRead(direct.key) : undefined + const memberState = faceState(face) + + if (RecordedArguments.containsMatchers(rawArgs)) { + const specification = RecordedArguments.forSpecification(rawArgs) + retract(read) + retract(chainHead) + return configureCall(memberState, helper, specification) + } + + // the direct reading takes over the read of the member (`sub.method.call(...)`), as a direct call would + let directRecord: CallRecord | undefined + if (directArgs !== undefined) { + if (read !== undefined && read.kind === 'get' && !read.retracted) { + read.convertToCall(directArgs, stackStart) + directRecord = read + } else { + directRecord = direct.state.addRecord('call', direct.key, directArgs, stackStart) + directRecord.chainPrevious = chainHead + } + } + const memberRecord = memberState.addRecord('call', helper, rawArgs, stackStart) + memberRecord.chainPrevious = directRecord ?? read ?? chainHead + if (directRecord !== undefined) pairReadings(memberRecord, directRecord) + + const hashes = new ArgumentHashes(rawArgs) + const answer = memberReadingAnswer(memberState, helper, rawArgs, hashes, memberRecord, thisArg) + if (answer !== NOT_CONFIGURED) return answer + if (directRecord !== undefined) { + const directAnswer = configuredAnswer(direct.state, direct.key, directArgs!, new ArgumentHashes(directArgs!), directRecord, { thisArg, explicit: true }) + if (directAnswer !== NOT_CONFIGURED) return directAnswer + } + const entry = memberState.callEntry(helper, hashes) + entry.handOut(memberRecord) + return entryProxy(entry) + } + + switch (helper) { + case 'call': + return function call(thisArg: unknown, ...args: any[]) { + return invokeHelper([thisArg, ...args], thisArg, args, call) + } + case 'apply': + return function apply(thisArg: unknown, list?: unknown) { + return invokeHelper(arguments.length < 2 ? [thisArg] : [thisArg, list], thisArg, applyArguments(list), apply) + } + case 'bind': + return function bind(thisArg: unknown, ...boundArgs: any[]) { + const rawArgs = [thisArg, ...boundArgs] + const memberState = faceState(face) + if (RecordedArguments.containsMatchers(rawArgs)) { + const specification = RecordedArguments.forSpecification(rawArgs) + retract(chainHead) + return configureCall(memberState, 'bind', specification) + } + const memberRecord = memberState.addRecord('call', 'bind', rawArgs, bind) + memberRecord.chainPrevious = chainHead + const hashes = new ArgumentHashes(rawArgs) + const answer = memberReadingAnswer(memberState, 'bind', rawArgs, hashes, memberRecord, thisArg) + if (answer !== NOT_CONFIGURED) return answer + const entry = memberState.callEntry('bind', hashes) + entry.handOut(memberRecord) + return createBoundProxy(face, entry, thisArg, boundArgs) + } + } +} + +/** + * The function `x.bind(thisArg, ...boundArgs)` returns (D26). Invoking it is a direct call of x with the bound + * arguments first and thisArg as `this`. Anything else on it is the result of the call of x's member `bind`: + * `.returns(...)` configures that call (the member reading), other members are those of its auto-substitute. + */ +const createBoundProxy = (face: Face, bindEntry: AutoEntry, thisArg: unknown, boundArgs: any[]): any => { + const print: Printer = options => printFace(bindEntry, colorsOf(options)) + const proxy: any = new Proxy(newTarget(print), { + get: function get(_target: unknown, property: PropertyKey) { + if (isSpecialProperty(property)) return special(property, print, bindEntry) + // a bound function ignores the `this` it is called with + if (isFunctionHelperKey(property)) return (Function.prototype as any)[property].bind(proxy) + return faceGet(bindEntry, property, get) + }, + set: function set(_target: unknown, property: PropertyKey, value: unknown) { + faceSet(bindEntry, property, value, set) + return true + }, + apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + const direct = directReadingOf(face) + return invoke(direct.state, direct.key, [...boundArgs, ...args], apply, direct.readSource, undefined, { thisArg, explicit: true }) + } + }) + return proxy } -/** `.call`, `.apply` and `.bind` on a member behave like invoking the member (D7). */ +/** `.call`, `.apply` and `.bind` on assertions and deferred reads behave like invoking the member (D7). */ const functionHelper = (property: FunctionHelperKey, invokeWith: (args: any[], stackStart: Function) => any): Function => { switch (property) { case 'call': @@ -276,7 +437,7 @@ const functionHelper = (property: FunctionHelperKey, invokeWith: (args: any[], s const hasMember = (instance: any, key: PropertyKey): boolean => ((typeof instance === 'object' && instance !== null) || typeof instance === 'function') && key in instance -const execute = (substitution: Substitution, args?: any[]): any => { +const execute = (substitution: Substitution, args?: any[], thisArg?: unknown): any => { const value = substitution.nextValue() switch (substitution.method) { case 'returns': @@ -288,7 +449,7 @@ const execute = (substitution: Substitution, args?: any[]): any => { case 'rejects': return Promise.reject(value) case 'mimicks': - return args === undefined ? value() : value(...args) + return Reflect.apply(value, thisArg, args ?? []) case 'auto': return entryProxy(substitution.entry!) } @@ -344,7 +505,7 @@ const realSet = (state: SubstituteState, key: PropertyKey, value: unknown, chain * substitution runs. Otherwise it is a real call: it is recorded (taking over the property read of the * method, if there is one) and resolved. */ -const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStart: Function, readSource: ReadSource, chainCandidate?: CallRecord): any => { +const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStart: Function, readSource: ReadSource, chainCandidate?: CallRecord, self: Self = NO_SELF): any => { const read = readSource === TAKE_PENDING_READ ? state.takePendingRead(key) : readSource if (RecordedArguments.containsMatchers(args)) { @@ -360,28 +521,41 @@ const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStar record = read } else record = linkChain(state.addRecord('call', key, args, stackStart), chainCandidate) - return resolveCall(state, key, args, record) + return resolveCall(state, key, args, record, self) } -const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], record: CallRecord): any => { - const hashes = new ArgumentHashes(args) +/** + * The `this` of an invocation. `explicit` when it was given through call/apply/bind: then a mimicked instance's + * method runs with it as well, instead of with the instance. + */ +type Self = { thisArg: unknown, explicit: boolean } +const NO_SELF: Self = { thisArg: undefined, explicit: false } + +/** The configured answer to a call: a matching substitution, or the mimicked instance. NOT_CONFIGURED otherwise. */ +const configuredAnswer = (state: SubstituteState, key: PropertyKey, args: any[], hashes: ArgumentHashes, record: CallRecord, self: Self): any => { const substitution = state.findCallSubstitution(key, hashes) if (substitution !== undefined) { if (substitution.method === 'auto') substitution.entry!.handOut(record) - return execute(substitution, args) + return execute(substitution, args, self.thisArg) } const mimicked = state.mimicked if (mimicked !== undefined) { const instance = mimicked.instance if (key === SELF) { - if (typeof instance === 'function') return Reflect.apply(instance, undefined, args) + if (typeof instance === 'function') return Reflect.apply(instance, self.thisArg, args) } else { const member = instance[key] - if (typeof member === 'function') return Reflect.apply(member, instance, args) + if (typeof member === 'function') return Reflect.apply(member, self.explicit ? self.thisArg : instance, args) } } + return NOT_CONFIGURED +} +const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], record: CallRecord, self: Self): any => { + const hashes = new ArgumentHashes(args) + const answer = configuredAnswer(state, key, args, hashes, record, self) + if (answer !== NOT_CONFIGURED) return answer const entry = state.callEntry(key, hashes) entry.handOut(record) return entryProxy(entry) @@ -582,8 +756,7 @@ const configureMember = (state: SubstituteState, key: PropertyKey): any => { if (method !== undefined) return function substitution(...values: any[]) { state.setPropertySubstitution(key, method, values) } - if (isFunctionHelperKey(property)) - return functionHelper(property, args => configureCall(state, key, RecordedArguments.forSpecification(args))) + // D26: call/apply/bind are members here like any other: setups through them configure the member reading return configureMember(state.propertyEntry(key).state, property) }, set: function set() { diff --git a/src/internals/SubstituteException.ts b/src/internals/SubstituteException.ts index 97ca582..3db78c8 100644 --- a/src/internals/SubstituteException.ts +++ b/src/internals/SubstituteException.ts @@ -1,7 +1,7 @@ import { inspect } from 'util' import { EXCEPTION, SELF, SubstituteExceptionType, keyToString } from './Constants' -import { colorsEnabled, firstStackFrame, formatArguments, formatValue, plural, TextBuilder, TextPart, withPrintGuard } from './utilities' +import { colorsEnabled, describeOtherReading, firstStackFrame, formatArguments, formatValue, plural, TextBuilder, TextPart, withPrintGuard } from './utilities' import type { CallRecord } from './CallRecord' import type { RecordedArguments } from './RecordedArguments' @@ -63,7 +63,7 @@ const describeExpectedCall = (mismatch: CallCountMismatch, colors: boolean): str const describeRecord = (record: CallRecord, colors: boolean): string => { switch (record.kind) { case 'get': return '' - case 'call': return formatArguments(record.args, colors) + case 'call': return formatArguments(record.args, colors) + describeOtherReading(record, colors) case 'set': return ` = ${formatValue(record.args?.[0], colors)}` } } diff --git a/src/internals/utilities/Stringify.ts b/src/internals/utilities/Stringify.ts index 4e0439b..1e0606b 100644 --- a/src/internals/utilities/Stringify.ts +++ b/src/internals/utilities/Stringify.ts @@ -29,6 +29,19 @@ export const formatValue = (value: unknown, colors: boolean, options?: InspectOp export const formatArguments = (args: readonly unknown[] | undefined, colors: boolean, options?: InspectOptions): string => args === undefined ? '' : `(${args.map(arg => formatValue(arg, colors, options)).join(', ')})` +/** + * D26: for the direct-call reading of an invocation through call/apply, how it was written (` via .call(t, 1)`). + * Typed structurally, so that this module does not depend on CallRecord. + */ +export const describeOtherReading = ( + record: { directReading?: boolean, twin?: { key: PropertyKey, args?: readonly unknown[] } }, + colors: boolean +): string => { + const twin = record.twin + if (record.directReading !== true || twin === undefined) return '' + return ` via .${String(twin.key)}${formatArguments(twin.args, colors)}` +} + /** The first "at ..." line of a stack trace, if there is one (there is none with Error.stackTraceLimit = 0). */ export const firstStackFrame = (stack: string | undefined): string | undefined => { if (typeof stack !== 'string') return undefined From b83187c4cd7a90da36679a27e153f86169339512 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:29:06 +0000 Subject: [PATCH 040/106] types: no TS2590 for members with very large literal unions (TD-8) Substitutes of lib.dom's HTMLInputElement, HTMLSelectElement and HTMLTextAreaElement (`autocomplete: AutoFill`, a template-literal union with thousands of members), and of any type with such a member, failed with TS2590 ("union type that is too complex to represent") on every use (T31). - A property read no longer intersects the value with the setup API. The value already comes from `& T` in SubstituteOf; intersecting it twice multiplied the union with itself, and TypeScript computes that product when it checks the intersection for conflicting members. Calls keep the value part (nothing else supplies it). - Primitive value types (and unions of literals) skip the per-member name-conflict check and the overload pattern, instead of distributing them over every member of the union. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/TD-8.T31.large-unions.ts | 42 +++++++++++++++++++++++++++++ src/api/types/FunctionSubstitute.ts | 35 +++++++++++++----------- src/api/types/Substitute.ts | 10 ++++--- src/api/types/SubstitutionLevel.ts | 11 +++++--- src/api/types/Utilities.ts | 6 +++++ 5 files changed, 82 insertions(+), 22 deletions(-) create mode 100644 spec-types/TD-8.T31.large-unions.ts diff --git a/spec-types/TD-8.T31.large-unions.ts b/spec-types/TD-8.T31.large-unions.ts new file mode 100644 index 0000000..01e4472 --- /dev/null +++ b/spec-types/TD-8.T31.large-unions.ts @@ -0,0 +1,42 @@ +// TD-8 / T31 Types with a member whose type is a very large union of string literals (lib.dom's HTMLInputElement, +// HTMLSelectElement and HTMLTextAreaElement have `autocomplete: AutoFill`) do not fail with TS2590 ("union type that +// is too complex to represent"). +import { Substitute, Arg } from '../src' + +const input = Substitute.for() +input.value.returns('x') +input.autocomplete.returns('on') +input.checkValidity().returns(true) +input.received().value = 'y' +input.received().focus() +const asInput: HTMLInputElement = input + +const select = Substitute.for() +select.value.returns('a') +select.item(Arg.any()).returns(null) +const asSelect: HTMLSelectElement = select + +const textArea = Substitute.for() +textArea.value.returns('text') +const asTextArea: HTMLTextAreaElement = textArea + +// A user type with a 10 000-member template literal union +type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' +type Code = `${Digit}${Digit}${Digit}${Digit}` +interface Lock { + code: Code + open(code: Code): boolean + current(): Code +} +const lock = Substitute.for() +lock.code.returns('1234') +lock.open('1234').returns(true) +lock.open(Arg.any()).returns(false) +lock.current().returns('0000') +lock.received().open('1234') +const asLock: Lock = lock + +// @ts-expect-error the configured value keeps its type +lock.code.returns('12345') + +export { asInput, asSelect, asTextArea, asLock } diff --git a/src/api/types/FunctionSubstitute.ts b/src/api/types/FunctionSubstitute.ts index e37b783..cd6c2bb 100644 --- a/src/api/types/FunctionSubstitute.ts +++ b/src/api/types/FunctionSubstitute.ts @@ -1,6 +1,6 @@ import { AllArguments } from '../../shared' import { ConfigurationResult, SubstitutionResult } from './SubstitutionLevel' -import { Equals, IsAny, IsNever } from './Utilities' +import { Equals, IsAny, IsNever, Primitive } from './Utilities' /** * What a call returns in each view of a substitute: @@ -34,6 +34,8 @@ type Slot = TArguments NoOverload type LastSlot = TArguments extends any[] ? Overload : NoOverload +type NoOverloads = [NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload] + /** * The overloads of a function type, as a fixed-length list of `Overload | NoOverload` (empty slots first), or only * `NoOverload` when the type is not callable. @@ -42,21 +44,24 @@ type LastSlot = TArguments extends any[] ? Overload = ({ substituteOverloads: TFunction } & TFunction) extends { - substituteOverloads(...args: infer A1): infer R1 - substituteOverloads(...args: infer A2): infer R2 - substituteOverloads(...args: infer A3): infer R3 - substituteOverloads(...args: infer A4): infer R4 - substituteOverloads(...args: infer A5): infer R5 - substituteOverloads(...args: infer A6): infer R6 - substituteOverloads(...args: infer A7): infer R7 - substituteOverloads(...args: infer A8): infer R8 -} ? [ - Slot, Slot, Slot, Slot, - Slot, Slot, Slot, LastSlot -] : - [NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload, NoOverload] +type Overloads = [TFunction] extends [Primitive] ? NoOverloads : + ({ substituteOverloads: TFunction } & TFunction) extends { + substituteOverloads(...args: infer A1): infer R1 + substituteOverloads(...args: infer A2): infer R2 + substituteOverloads(...args: infer A3): infer R3 + substituteOverloads(...args: infer A4): infer R4 + substituteOverloads(...args: infer A5): infer R5 + substituteOverloads(...args: infer A6): infer R6 + substituteOverloads(...args: infer A7): infer R7 + substituteOverloads(...args: infer A8): infer R8 + } ? [ + Slot, Slot, Slot, Slot, + Slot, Slot, Slot, LastSlot + ] : + NoOverloads type PositionalSignature = TOverload extends Overload ? (...args: TOverload['arguments']) => CallResult : diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index 4fc9a8c..6f29781 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -1,8 +1,12 @@ -import { ConfigurationResult, SubstitutionResult } from './SubstitutionLevel' +import { ConfigurationResult, SetupMethods } from './SubstitutionLevel' import { FunctionSubstitute } from './FunctionSubstitute' -/** A member read on a substitute: its value intersected with the setup API (`sub.isEnabled.returns(true)`). */ -export type PropertySubstitute = SubstitutionResult TValue> +/** + * The setup API of a member read on a substitute (`sub.isEnabled.returns(true)`). The value itself is not part of it: + * `SubstituteOf` intersects the members with `T`, which supplies it. Intersecting the value here as well would + * multiply a large union member type with itself (lib.dom's `HTMLInputElement.autocomplete`, TS2590, TD-8). + */ +export type PropertySubstitute = SetupMethods TValue> /** * The object type whose members the views below map. diff --git a/src/api/types/SubstitutionLevel.ts b/src/api/types/SubstitutionLevel.ts index 1fdb270..68596a8 100644 --- a/src/api/types/SubstitutionLevel.ts +++ b/src/api/types/SubstitutionLevel.ts @@ -1,5 +1,5 @@ import { constants } from '../../shared' -import { HasMember, LibraryMemberName } from './Utilities' +import { HasMember, LibraryMemberName, Primitive } from './Utilities' export const returns: typeof constants.CONTEXT.returns.symbol = constants.CONTEXT.returns.symbol export const throws: typeof constants.CONTEXT.throws.symbol = constants.CONTEXT.throws.symbol @@ -50,6 +50,8 @@ type StringForm = TCheck exten never type CheckedStringSetupMethods = + // Primitives (and unions of literals, however large) have no conflicting member: skip the per-member check (TD-8). + [NonNullable] extends [Primitive] ? StringSetupMethods : StringForm & {}, 'returns', ReturnsFunction> & StringForm & {}, 'throws', ThrowsFunction> & StringForm & {}, 'mimicks', MimicksFunction> & @@ -59,11 +61,12 @@ type CheckedStringSetupMethods = ) : {}) /** - * The setup API offered on the result of a member access or call of a substitute. + * The setup API offered on the result of a member access or call of a substitute: the symbol forms, plus each string + * form unless the value has a member with that name. * `TReturnType` is the member's value (or return) type, `TImplementation` the function type `mimicks` accepts. * `TReturnType` must not be `never`, `null` or `undefined` (see `SubstitutionResult`). */ -type SetupMethods = +export type SetupMethods = SymbolSetupMethods & CheckedStringSetupMethods /** The setup API without name-conflict checks, used where the value itself is not exposed (`[configure]()`). */ @@ -71,7 +74,7 @@ export type UncheckedSetupMethods = SymbolSetupMethods & StringSetupMethods /** - * The type of a member access or call on a substitute: the value intersected with the setup API. + * The type of a call on a substitute: the returned value intersected with the setup API. * `null` and `undefined` cannot carry the setup API, so they are dropped from the value part (T:TY-9), while the * setup methods still accept them. When nothing is left (`null`, `undefined` or `never`), only the setup API remains. * For `never` (a member that always throws) `returns` accepts no value (T:TY-12), so only `throws` and `mimicks` can be diff --git a/src/api/types/Utilities.ts b/src/api/types/Utilities.ts index 1b20825..8f527a0 100644 --- a/src/api/types/Utilities.ts +++ b/src/api/types/Utilities.ts @@ -8,6 +8,12 @@ export type IsNever = [T] extends [never] ? true : false export type IsAny = 0 extends (1 & T) ? true : false +/** + * The non-nullish primitive types. They are not callable, and the typings assume that they have no members named like + * the library's methods. + */ +export type Primitive = string | number | boolean | bigint | symbol + /** The names the library uses: these are the names whose presence in a type the typings check. */ export type LibraryMemberName = 'received' | 'didNotReceive' | 'returns' | 'throws' | 'resolves' | 'rejects' | 'mimicks' From ba03bdcfacb6db10571d09413b4dd73b1adfbead Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:29:56 +0000 Subject: [PATCH 041/106] types: received().optionalProp = undefined compiles (TD-7) The assertion view (`received()` / `didNotReceive()`) was a homomorphic mapping with `-?`, which removes `undefined` from optional properties, and the member type was intersected with `{}`, which drops `undefined` as well on TypeScript >= 4.8. Checking that the code under test cleared an optional property did not compile (T30). - For types without a string index signature the assertion view is mapped over the keys without copying modifiers, so an optional property keeps `undefined`. Optional methods are still asserted as calls (their call signatures come from the member type without null/undefined). Types with a string index signature keep the homomorphic mapping (T:TY-8). - FunctionSubstitute is `unknown` instead of `{}` for a member that is not callable, so `FunctionSubstitute<...> & TValue` is exactly `TValue`. Side effect: `readonly` is no longer copied into the assertion view, so `sub.received().readonlyProp = value` compiles too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/TD-1.T25.null-only-members.ts | 2 ++ .../TD-7.T30.optional-property-assertion.ts | 30 +++++++++++++++++++ src/api/types/FunctionSubstitute.ts | 11 ++++--- src/api/types/Substitute.ts | 25 +++++++++++----- 4 files changed, 56 insertions(+), 12 deletions(-) create mode 100644 spec-types/TD-7.T30.optional-property-assertion.ts diff --git a/spec-types/TD-1.T25.null-only-members.ts b/spec-types/TD-1.T25.null-only-members.ts index 939bedb..02d975a 100644 --- a/spec-types/TD-1.T25.null-only-members.ts +++ b/spec-types/TD-1.T25.null-only-members.ts @@ -28,6 +28,8 @@ members.find(Arg.any()).returns(null) assert>() assert>() assert>() +members.received().nothing = null +members.received().maybeNothing = undefined members.received().find('1') const asMembers: Members = members diff --git a/spec-types/TD-7.T30.optional-property-assertion.ts b/spec-types/TD-7.T30.optional-property-assertion.ts new file mode 100644 index 0000000..932576a --- /dev/null +++ b/spec-types/TD-7.T30.optional-property-assertion.ts @@ -0,0 +1,30 @@ +// TD-7 / T30 In the assertion view an optional property keeps `undefined` in its type, so a check that the code under +// test cleared it compiles: `sub.received().optionalProp = undefined`. +import { Substitute, Arg, received, didNotReceive } from '../src' + +interface Form { + note?: string + count?: number + format?(value: number): string + onSubmit?: (values: string[]) => void + title: string +} +const form = Substitute.for
() +const clear = (f: Form) => { f.note = undefined } +clear(form) + +form.received().note = undefined +form.received().note = 'x' +form.received(1).note = Arg.any() +form.didNotReceive().count = undefined +form[received](1).note = undefined +form[didNotReceive]().count = undefined +// optional methods are still asserted as calls +form.received().format(1) +form.didNotReceive().onSubmit(Arg.any()) +form.received().title = 'x' + +// @ts-expect-error the property keeps its type +form.received().note = 1 +// @ts-expect-error a required property does not accept undefined +form.received().title = undefined diff --git a/src/api/types/FunctionSubstitute.ts b/src/api/types/FunctionSubstitute.ts index cd6c2bb..d1a525c 100644 --- a/src/api/types/FunctionSubstitute.ts +++ b/src/api/types/FunctionSubstitute.ts @@ -63,13 +63,16 @@ type Overloads = [TFunction] extends [Primitive] ? NoOverloads : ] : NoOverloads +// `unknown` (not `{}`) when there is no signature, so that `FunctionSubstitute<...> & TValue` is exactly `TValue` for a +// member that is not callable: `{} & undefined` is `never` (TypeScript >= 4.8), which would drop `undefined` from an +// optional property in the assertion view (TD-7). type PositionalSignature = TOverload extends Overload ? (...args: TOverload['arguments']) => CallResult : - {} + unknown type AllArgumentsSignature = TOverload extends Overload ? (allArguments: AllArguments) => CallResult : - {} + unknown // All positional signatures come before the `Arg.all()` signatures, so a call with a single matcher // (`Arg.any()`, `Arg.is(...)`) resolves against the real parameter lists first (T:TY-10). @@ -85,10 +88,10 @@ type OverloadSignatures /** * The call signatures a member of type `TFunction` has on a substitute, one pair per overload: the overload's own - * parameter list, and a single `Arg.all()` argument. `{}` when `TFunction` is not callable. + * parameter list, and a single `Arg.all()` argument. `unknown` when `TFunction` is not callable. */ export type FunctionSubstitute = - IsNever extends true ? {} : + IsNever extends true ? unknown : IsAny extends true ? (...args: any[]) => CallResult : // Not `[TFunction] extends [(...args: any) => any]`: in its true branch TypeScript would add that signature to TFunction. OverloadSignatures, TView> diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index 6f29781..280d072 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -17,7 +17,7 @@ export type PropertySubstitute = SetupMethods TValue> */ type Members = string extends keyof T ? T : Pick -// All views are mapped with `-?` and expand calls from the member type without `null | undefined`, so optional members +// The views are mapped with `-?` and expand calls from the member type without `null | undefined`, so optional members // (`prop?`, `method?()`) are configured and asserted like required ones (T:TY-7). // // Members whose type is only `null` and/or `undefined` (`error?: undefined`, `ownerDocument: null`) get no setup API: @@ -47,20 +47,29 @@ type SubstituteMembers = { /** The members of a substitute (without the assertion and configuration methods). */ export type ObjectSubstituteTransformation = SubstituteMembers> +// In the assertion view, a member that is not callable keeps its declared type, including `undefined` for an optional +// property (`sub.received().note = undefined`, TD-7). A callable member offers the assertion signatures (calls return +// nothing) on the member type without `null | undefined`. type AssertionMember = FunctionSubstitute, 'assertion'> & TValue -type AssertionMembers = { - [P in keyof T]-?: - P extends 'then' ? never : - P extends 'toJSON' ? never : - AssertionMember -} +type AssertionMemberOf = + P extends 'then' ? never : + P extends 'toJSON' ? never : + AssertionMember + +// For a type with a string index signature, the homomorphic mapping (with `-?`) keeps the named members next to the +// index signature (T:TY-8); `-?` removes `undefined` from optional named members there. +type IndexedAssertionMembers = { [P in keyof T]-?: AssertionMemberOf } + +// Every other type is mapped over its keys without copying the modifiers (the key set is not written as `keyof T`): +// all members are required, and an optional property keeps `undefined` in its type, which `-?` would remove. +type AssertionMembers = { [P in Extract]: AssertionMemberOf } /** * The object returned by `received()` / `didNotReceive()`: calls return nothing, property reads and writes keep the * member type (`sub.received().isEnabled = true`). */ -export type TerminatingObject = AssertionMembers> +export type TerminatingObject = string extends keyof T ? IndexedAssertionMembers : AssertionMembers type ConfigurationMember = FunctionSubstitute, 'configure'> & ConfigurationResult TValue> From a3a927afd8dc77999561a0c60dbb69640f2ae049 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:30:30 +0000 Subject: [PATCH 042/106] types: Arg.all() type-checks after leading arguments (TD-3) D14 lets `Arg.all()` match the rest of the arguments after leading ones (`add(1, Arg.all())`, `log('x', Arg.all())`), but the typings only accepted it as the only argument, unless the remaining parameters were `unknown` or `any` (T27). Each overload now also gets signatures that take its first n parameters followed by `Arg.all()`, for every position n from 1 to 6 at which it has a parameter (required, optional or rest), in all three views. They are written out position by position (TypeScript 3.6 has no variadic tuples), so their parameters are named arg0, arg1, ... `Arg.all()` with something after it, or after the last parameter of a fixed parameter list, is still rejected. The position test uses `A['length']`: TypeScript 4.0 and 4.1 consider `[string, number?]` assignable to `[any?]`, so a tuple pattern would miss optional parameters there. The return types stay inside the signatures, where TypeScript computes them only when a signature is used. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/TD-3.T27.arg-all-trailing.ts | 50 +++++++++++++++++++++++++ src/api/types/FunctionSubstitute.ts | 37 ++++++++++++++---- 2 files changed, 79 insertions(+), 8 deletions(-) create mode 100644 spec-types/TD-3.T27.arg-all-trailing.ts diff --git a/spec-types/TD-3.T27.arg-all-trailing.ts b/spec-types/TD-3.T27.arg-all-trailing.ts new file mode 100644 index 0000000..6639a0d --- /dev/null +++ b/spec-types/TD-3.T27.arg-all-trailing.ts @@ -0,0 +1,50 @@ +// TD-3 / T27 `Arg.all()` type-checks in any trailing position (D14): after leading arguments it matches the rest of +// the arguments. It replaces the parameter at its position (required, optional or rest), up to the 7th parameter. +import { Substitute, Arg, configure, received } from '../src' + +interface Calculator { add(a: number, b: number): number } +interface Logger { + log(message: string, ...details: string[]): void + find(id: string, options?: { deep: boolean }): string + record(a: number, b: string, c: boolean, d: number, e: string, f: number, g: boolean): void +} +interface Store { + get(): string[] + get(key: string): string + set(key: string, value: string): void + set(entries: Record): void +} + +const calculator = Substitute.for() +calculator.add(1, Arg.all()).returns(3) +calculator.add(Arg.any(), Arg.all()).returns(3) +calculator.add(Arg.is(a => a > 0), Arg.all()).mimicks((a, b) => a + b) +calculator.received().add(1, Arg.all()) +calculator.didNotReceive().add(2, Arg.all()) +calculator[received](1).add(1, Arg.all()) +calculator[configure]().add(1, Arg.all()).returns(3) + +const logger = Substitute.for() +logger.received().log('saved', Arg.all()) +logger.log('saved', 'a', Arg.all()).returns() +logger.log('saved', 'a', 'b', 'c', 'd', 'e', Arg.all()).returns() +logger.find('1', Arg.all()).returns('x') +logger.received().find('1', Arg.all()) +logger.record(1, 'b', true, Arg.all()).returns() +logger.record(1, 'b', true, 4, 'e', 6, Arg.all()).returns() + +const store = Substitute.for() +store.set('k', Arg.all()).returns() +store.received().set('k', Arg.all()) +store.get(Arg.all()).returns(['a']) + +// @ts-expect-error the leading arguments keep their types +calculator.add('1', Arg.all()) +// @ts-expect-error nothing may follow Arg.all() +calculator.add(Arg.all(), 2) +// @ts-expect-error Calculator.add has no parameter at that position +calculator.add(1, 2, Arg.all()) +// @ts-expect-error the configured value keeps its type +calculator.add(1, Arg.all()).returns('3') +// @ts-expect-error the leading arguments keep their types +logger.received().log(1, Arg.all()) diff --git a/src/api/types/FunctionSubstitute.ts b/src/api/types/FunctionSubstitute.ts index d1a525c..485d33b 100644 --- a/src/api/types/FunctionSubstitute.ts +++ b/src/api/types/FunctionSubstitute.ts @@ -70,10 +70,30 @@ type PositionalSignature = TOverload ex (...args: TOverload['arguments']) => CallResult : unknown -type AllArgumentsSignature = TOverload extends Overload ? - (allArguments: AllArguments) => CallResult : +// The `Arg.all()` signatures of an overload: +// - a single `Arg.all()` argument: `add(Arg.all())`; +// - `Arg.all()` after leading arguments (D14, TD-3): `add(1, Arg.all())`, `log('x', Arg.all())`. For every position `n` +// from 1 to 6 at which the overload has a parameter (required, optional or rest), a signature takes the first `n` +// parameters of the overload followed by `Arg.all()`. They are written out position by position because +// TypeScript 3.6 has no variadic tuple types, so their parameters are named `arg0`, `arg1`, ... +// The overload has a parameter at position `n` when one of its possible argument counts (`A['length']`: a number +// literal, a union of them with optional parameters, or `number` with a rest parameter) is greater than `n`. The +// nesting stops at the first position the overload does not have. (`A extends [any?]` would be shorter, but +// TypeScript 4.0 and 4.1 consider `[string, number?]` assignable to `[any?]`.) +// (The return types are written inside each signature, where TypeScript only computes them when the signature is used.) +type AllArgumentsSignatures = TOverload extends Overload ? + ((allArguments: AllArguments) => CallResult) & + TrailingAllArgumentsSignatures : unknown +type TrailingAllArgumentsSignatures = [Exclude] extends [never] ? unknown : + ((arg0: A[0], allArguments: AllArguments) => CallResult) & ([Exclude] extends [never] ? unknown : + ((arg0: A[0], arg1: A[1], allArguments: AllArguments) => CallResult) & ([Exclude] extends [never] ? unknown : + ((arg0: A[0], arg1: A[1], arg2: A[2], allArguments: AllArguments) => CallResult) & ([Exclude] extends [never] ? unknown : + ((arg0: A[0], arg1: A[1], arg2: A[2], arg3: A[3], allArguments: AllArguments) => CallResult) & ([Exclude] extends [never] ? unknown : + ((arg0: A[0], arg1: A[1], arg2: A[2], arg3: A[3], arg4: A[4], allArguments: AllArguments) => CallResult) & ([Exclude] extends [never] ? unknown : + ((arg0: A[0], arg1: A[1], arg2: A[2], arg3: A[3], arg4: A[4], arg5: A[5], allArguments: AllArguments) => CallResult)))))) + // All positional signatures come before the `Arg.all()` signatures, so a call with a single matcher // (`Arg.any()`, `Arg.is(...)`) resolves against the real parameter lists first (T:TY-10). type OverloadSignatures = @@ -81,14 +101,15 @@ type OverloadSignatures PositionalSignature & PositionalSignature & PositionalSignature & PositionalSignature & PositionalSignature & PositionalSignature & - AllArgumentsSignature & AllArgumentsSignature & - AllArgumentsSignature & AllArgumentsSignature & - AllArgumentsSignature & AllArgumentsSignature & - AllArgumentsSignature & AllArgumentsSignature + AllArgumentsSignatures & AllArgumentsSignatures & + AllArgumentsSignatures & AllArgumentsSignatures & + AllArgumentsSignatures & AllArgumentsSignatures & + AllArgumentsSignatures & AllArgumentsSignatures /** - * The call signatures a member of type `TFunction` has on a substitute, one pair per overload: the overload's own - * parameter list, and a single `Arg.all()` argument. `unknown` when `TFunction` is not callable. + * The call signatures a member of type `TFunction` has on a substitute: per overload, the overload's own parameter list, + * a single `Arg.all()` argument, and the leading parameters followed by `Arg.all()`. `unknown` when `TFunction` is not + * callable. */ export type FunctionSubstitute = IsNever extends true ? unknown : From 061e314020101da96ef3ae68ca393e4003217111 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:30:53 +0000 Subject: [PATCH 043/106] fix(configure): D31 nested setups through a configured or mimicked member A nested configure() setup through a member or a call that already answers with a value goes to that value when it is a substitute (a configured return value, or the mimicked instance's value), as in NSubstitute; for a real value it is a SubstituteException usage error. Nested setups are never silently ignored and never silently replace the earlier setup (ENG2-11). A mimicked member whose value is a substitute now reads as that substitute. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 66 +++++++++++++++++++++++++ src/internals/Engine.ts | 74 ++++++++++++++++++++++++++-- src/internals/SubstituteState.ts | 5 ++ 3 files changed, 141 insertions(+), 4 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index 46c895c..e3c235b 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -425,6 +425,72 @@ test('ENG2-7 (D28) a substitute is not a jest asymmetric matcher unless asymmetr matcher.received(1).asymmetricMatch(42) }) +test('ENG2-11 (D31) nested configure() setups through a configured or mimicked member go to its substitute, or fail', t => { + // a property configured to return a substitute: the nested setup goes to that substitute + const app = Substitute.for() + const config = Substitute.for() + config.port.returns(80) + app.config.returns(config) + app[configure]().config.port.returns(1) + t.is(app.config, config) + t.is(app.config.port, 1) + + // a call configured to return a substitute: the earlier setups of that substitute are kept + const container = Substitute.for() + const repository = Substitute.for() + repository.find(2).returns('two') + container.getRepo().returns(repository) + container[configure]().getRepo().find(1).returns('one') + t.is(container.getRepo(), repository) + t.is(container.getRepo().find(1), 'one') + t.is(container.getRepo().find(2), 'two') + // ... also when a matcher setup answers the call, and for a function substitute that is called + const lookup = Substitute.for() + lookup.get(Arg.any()).returns(repository) + lookup[configure]().get(5).find(3).returns('three') + t.is(lookup.get(5), repository) + t.is(repository.find(3), 'three') + const callback = Substitute.for() + const factory = Substitute.for() + factory.make().returns(callback) + factory[configure]().make()(7).returns('seven') + t.is(callback(7), 'seven') + + // mimicked: a substitute value gets the setup, a real value is a usage error + const mimicked = Substitute.for() + mimicked[mimick]({ config, settings: { port: 80 } }) + mimicked[configure]().config.host.returns('example.org') + t.is(mimicked.config, config) + t.is(mimicked.config.host, 'example.org') + const mimickedError = t.throws(() => mimicked[configure]().settings.port.returns(1), { instanceOf: SubstituteException }) + t.true(plain(mimickedError.message).startsWith( + 'Cannot configure @Substitute.settings.port: settings is mimicked with { port: 80 }, which is not a substitute, ' + + 'and members of a real value cannot be configured.')) + t.is(mimicked.settings.port, 80) + + // configured real values are a usage error, and nothing is replaced + const real = Substitute.for() + real.options.returns({ retries: 3 }) + real.load().returns([1]) + real.connection.throws(new Error('down')) + t.throws(() => real[configure]().options.retries.returns(5), { instanceOf: SubstituteException, message: /options returns \{ retries: 3 \}, which is not a substitute/ }) + t.throws(() => real[configure]().load().length.returns(5), { instanceOf: SubstituteException, message: /Cannot configure @Substitute\.load\(\)\.length: load\(\) returns \[ 1 \]/ }) + t.throws(() => real[configure]().connection.isOpen.returns(true), { instanceOf: SubstituteException, message: /connection is configured with throws\(\)/ }) + t.deepEqual(real.options, { retries: 3 }) + t.deepEqual(real.load(), [1]) + + // members that do not answer with a value yet keep working as before + const fresh = Substitute.for() + fresh[configure]().config.port.returns(1) + fresh[configure]().getRepo(Arg.any()).find(1).returns('one') + t.is(fresh.config.port, 1) + t.is(fresh.getRepo(9).find(1), 'one') + const partial = Substitute.for() + partial[mimick]({ load: () => 'real' }) + partial[configure]().config.port.returns(2) + t.is(partial.config.port, 2) +}) + test('ENG2-12 (D32) methods read from the value of a member configured as property and method run on that value', t => { const sizes = Substitute.for() sizes.size(Arg.any()).returns(10) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 05836c1..402a029 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -1,6 +1,6 @@ import { inspect, InspectOptions, types } from 'util' -import { isSubstituteProxy, substituteMarker } from '../shared' +import { constants, isSubstituteProxy, substituteMarker } from '../shared' import { ArgumentHashes, AutoEntry, Substitution, SubstituteState } from './SubstituteState' import { CallRecord, currentSequence, pairReadings, retract } from './CallRecord' import { CallSite, Frame, sameExpression } from './CallSite' @@ -481,7 +481,8 @@ const realGet = (state: SubstituteState, key: PropertyKey, chainCandidate: CallR const delegate = hasMember(mimicked.instance, key) || !(isStringAssertionKey(key) || state.hasCallSubstitutions(key) || state.hasConfiguredPropertyEntry(key)) const value = delegate ? mimicked.instance[key] : undefined - if (delegate && typeof value !== 'function') { + // a substitute value records and resolves its own calls (D31: nested setups through the member go to it) + if (delegate && (typeof value !== 'function' || isSubstituteProxy(value))) { linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) return value } @@ -745,6 +746,47 @@ const createConfigureProxy = (state: SubstituteState): any => { }) } +/* + * D31: a nested setup through a member or a call (`sub[configure]().config.port.returns(1)`) that already answers + * with a value (a configured return value, or the mimicked instance's value) goes to that value when it is a + * substitute, as in NSubstitute. Members of a real value cannot be configured: that is a usage error, so that the + * nested setup is never silently ignored and never silently replaces the earlier setup. + */ + +/** The configure view of a substitute value: of this copy of the library directly, of another copy through its symbol. */ +const configureViewOf = (value: any): any => { + if (Object.getPrototypeOf(value) === faceTargetPrototype) { + const face = value[INTERNAL] as Face | undefined + if (face !== undefined) return createConfigureProxy(faceState(face)) + } + return value[constants.CONTEXT.configure.symbol]() +} + +const nestedOfRealValueError = (path: string, member: string, reason: string, start: Function) => SubstituteException.generic( + `Cannot configure ${path}: ${member} ${reason}, which is not a substitute, and members of a real value cannot be ` + + `configured. Configure ${member} to return a substitute (e.g. Substitute.for()) and configure that one, ` + + `or configure what ${member} returns as a whole.`, + start +) + +/** The configure view to forward a nested setup to, or undefined when the member or call does not answer yet. */ +const forwardNestedSetup = ( + path: string, member: string, substitution: Substitution | undefined, mimicked: { value: unknown } | undefined, start: Function +): any => { + if (substitution !== undefined && substitution.method !== 'auto') { + if (substitution.method !== 'returns') + throw nestedOfRealValueError(path, member, `is configured with ${substitution.method}()`, start) + const value = substitution.peekValue() + if (isSubstituteProxy(value)) return configureViewOf(value) + throw nestedOfRealValueError(path, member, `returns ${formatValue(value, false)}`, start) + } + if (mimicked !== undefined) { + if (isSubstituteProxy(mimicked.value)) return configureViewOf(mimicked.value) + throw nestedOfRealValueError(path, member, `is mimicked with ${formatValue(mimicked.value, false)}`, start) + } + return undefined +} + const configureMember = (state: SubstituteState, key: PropertyKey): any => { const context = contextMethodOf(key) if (context !== undefined) return contextFunction(context, () => state, undefined) @@ -756,6 +798,15 @@ const configureMember = (state: SubstituteState, key: PropertyKey): any => { if (method !== undefined) return function substitution(...values: any[]) { state.setPropertySubstitution(key, method, values) } + // D31: through a member that answers with a value already + const substitution = state.propertySubstitution(key) + const instance = state.mimicked?.instance + const mimickedValue = substitution === undefined && instance !== undefined && hasMember(instance, key) ? instance[key] : undefined + // a real method of a mimicked instance reads as a handle (see realGet), so nested setups configure that handle + const mimicked = mimickedValue !== undefined && (typeof mimickedValue !== 'function' || isSubstituteProxy(mimickedValue)) + ? { value: mimickedValue } : undefined + const forwarded = forwardNestedSetup(`${state.memberPath(key)}.${keyToString(property)}`, keyToString(key), substitution, mimicked, get) + if (forwarded !== undefined) return forwarded[property] // D26: call/apply/bind are members here like any other: setups through them configure the member reading return configureMember(state.propertyEntry(key).state, property) }, @@ -777,6 +828,21 @@ const nestedEntry = (state: SubstituteState, key: PropertyKey, specification: Re return entry } +/** + * Where a nested setup through a call goes (D31): the substitute that the call already returns, or the + * auto-substitute registered for the specification. For an argument list without matchers, the substitution that + * answers that call now counts; for one with matchers, the substitution configured with the same specification. + */ +const nestedSetupTarget = (state: SubstituteState, key: PropertyKey, specification: RecordedArguments, property: PropertyKey | undefined, start: Function): any => { + const answering = specification.argumentsClass === 'plain' + ? state.findCallSubstitution(key, new ArgumentHashes(specification.value!)) + : state.callSubstitutionFor(key, specification) + const call = `${memberLabel(key)}${formatArguments(specification.value, false)}` + const path = `${state.memberPath(key)}${formatArguments(specification.value, false)}${property === undefined ? '(...)' : `.${keyToString(property)}`}` + const forwarded = forwardNestedSetup(path, call, answering, undefined, start) + return forwarded !== undefined ? forwarded : createConfigureProxy(nestedEntry(state, key, specification).state) +} + /** * A call in a setup: `.returns(...)` configures it, anything else configures the auto-substitute it returns. * @@ -797,7 +863,7 @@ const configureCall = (state: SubstituteState, key: PropertyKey, specification: state.addCallSubstitution(key, specification, method, values) } if (stringAssertion) return assertionMember(state, property, assertionCount(get), get) - return configureMember(nestedEntry(state, key, specification).state, property) + return nestedSetupTarget(state, key, specification, property, get)[property] }, set: function set(_target: unknown, property: PropertyKey, value: unknown) { if (!stringAssertion) throw configureSetError(set) @@ -805,7 +871,7 @@ const configureCall = (state: SubstituteState, key: PropertyKey, specification: return true }, apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { - return configureCall(nestedEntry(state, key, specification).state, SELF, RecordedArguments.forSpecification(args)) + return nestedSetupTarget(state, key, specification, undefined, apply)(...args) } }) } diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index 6daab60..e80952d 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -82,6 +82,11 @@ export class Substitution { return this.args?.rank ?? 0 } + /** The value the next use would give, without using it. */ + public peekValue(): any { + return this.values.length === 0 ? undefined : this.values[this._next] + } + /** The values are used in order and the last one keeps being used (NSubstitute semantics). */ public nextValue(): any { const values = this.values From a61403688ed7be3e6593e5dcf149bddeda75945e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:31:21 +0000 Subject: [PATCH 044/106] types: Arg.any('function'/'object') fit typed parameters, standalone Arg.is (TD-5, TD-6) - Arg.any('function') was typed `Argument & Function` and Arg.any('object') `Argument & object`, which are not assignable to a callback parameter such as `(value: number) => void` or to an object parameter such as `{ id: string }` (T28). 'function' is now typed as any function or constructor (its `matches` still accepts any `Function`), and 'object' as `any`, like Arg.any(): no type is assignable to every object type. - `const negative = Arg.is((x: number) => x < 0)` did not compile on TypeScript 3.6 and 3.7, which cannot infer the type through `ExtractFirstArg` from the predicate (T29). Arg.is gets a second overload that takes the type from the predicate's parameter; contextual typing in argument position is unchanged (the first overload is tried first). No runtime change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .../TD-5.T28.arg-any-function-object.ts | 28 +++++++++++++++++++ spec-types/TD-6.T29.arg-is-standalone.ts | 27 ++++++++++++++++++ src/api/Arg.ts | 16 +++++++++-- 3 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 spec-types/TD-5.T28.arg-any-function-object.ts create mode 100644 spec-types/TD-6.T29.arg-is-standalone.ts diff --git a/spec-types/TD-5.T28.arg-any-function-object.ts b/spec-types/TD-5.T28.arg-any-function-object.ts new file mode 100644 index 0000000..09f2a87 --- /dev/null +++ b/spec-types/TD-5.T28.arg-any-function-object.ts @@ -0,0 +1,28 @@ +// TD-5 / T28 `Arg.any('function')` is assignable to typed function (and constructor) parameters, `Arg.any('object')` to +// typed object parameters. +import { Substitute, Arg, configure } from '../src' + +class Widget { name = 'w' } +interface Bus { + subscribe(handler: (value: number) => void): () => void + once(event: string, handler?: (value: string) => boolean): void + save(item: { id: string }): void + saveAll(items: { id: string }[], options: Partial<{ force: boolean }>): number + register(type: new () => Widget): void + send(payload: object, callback: Function): void +} + +const bus = Substitute.for() +bus.subscribe(Arg.any('function')).returns(() => { }) +bus.received().subscribe(Arg.any('function')) +bus.once('saved', Arg.any('function')) +bus.received().save(Arg.any('object')) +bus.saveAll(Arg.any('array'), Arg.any('object')).returns(1) +bus.register(Arg.any('function')) +bus.send(Arg.any('object'), Arg.any('function')) +bus[configure]().subscribe(Arg.any.not('function')).returns(() => { }) + +interface Calculator { add(a: number, b: number): number } +const calculator = Substitute.for() +// @ts-expect-error a function matcher does not fit a number parameter +calculator.add(Arg.any('function'), 1) diff --git a/spec-types/TD-6.T29.arg-is-standalone.ts b/spec-types/TD-6.T29.arg-is-standalone.ts new file mode 100644 index 0000000..9741711 --- /dev/null +++ b/spec-types/TD-6.T29.arg-is-standalone.ts @@ -0,0 +1,27 @@ +// TD-6 / T29 A matcher created on its own from an annotated predicate (README "Matching specific arguments") takes its +// type from the predicate. spec-types/min-ts/consumer.ts checks the same pattern with TypeScript 3.6. +import { Substitute, Arg } from '../src' +import { assert, Equals, expectType } from './helpers' + +interface Calculator { + add(a: number, b: number): number + divide(a: number, b: number): number +} +const calculator = Substitute.for() + +const negative = Arg.is((x: number) => x < 0) +calculator.divide(negative, negative).returns(1) +calculator.received().divide(negative, Arg.any()) +expectType(negative) + +const notZero = Arg.is.not((x: number) => x === 0) +calculator.divide(1, notZero).returns(2) + +const explicit = Arg.is(x => x > 0) +calculator.add(explicit, 1) + +// in argument position the predicate's parameter type still comes from the parameter +calculator.add(Arg.is(a => { assert>(); return a > 1 }), Arg.any()).returns(1) + +// @ts-expect-error a string matcher does not fit a number parameter +calculator.divide(Arg.is((x: string) => x === ''), 1) diff --git a/src/api/Arg.ts b/src/api/Arg.ts index 581ab77..52b29c8 100644 --- a/src/api/Arg.ts +++ b/src/api/Arg.ts @@ -35,7 +35,17 @@ const isFunction = (predicate: PredicateFunction>, options throw new TypeError(`Arg.is expects a predicate function, but received ${describeInvalidPredicate(predicate)}.`) return new Argument(`Arg.is{${describePredicate(predicate)}}`, predicate, options) } -type Is = (predicate: PredicateFunction>) => ReturnArg> +type Is = { + (predicate: PredicateFunction>): ReturnArg> + // Infers the type from an annotated predicate when the matcher is created on its own, which TypeScript 3.6 and 3.7 + // cannot do through `ExtractFirstArg` above (TD-6). + (predicate: (arg: T) => boolean): ReturnArg +} + +// 'function' and 'object' are mostly used for callback and object parameters, so they must be assignable to them (TD-5): +// 'function' is typed as any function or constructor (its `matches` still accepts any `Function`), 'object' as `any` +// (no type is assignable to every object type). +type AnyFunction = Argument & ((...args: any[]) => any) & (new (...args: any[]) => any) type MapAnyReturn = T extends 'any' ? ReturnArg : T extends 'string' ? @@ -44,8 +54,8 @@ ReturnArg : T extends 'boolean' ? ReturnArg : T extends 'symbol' ? ReturnArg : T extends 'undefined' ? ReturnArg : T extends 'object' ? -ReturnArg : T extends 'function' ? -ReturnArg : T extends 'array' ? +ReturnArg : T extends 'function' ? +AnyFunction : T extends 'array' ? ReturnArg : any type AnyType = 'string' | 'number' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'array' | 'any' From 6fafdffa0529530b226302f911f26bd36901e562 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:31:21 +0000 Subject: [PATCH 045/106] test(types): cover the round-3 typing fixes with the minimum TypeScript version spec-types/min-ts/consumer.ts (checked against the built typings with TypeScript 3.6 by `npm run test:types:min-ts`) now also uses: setups and string assertions in generic code (TD-2), members typed only null/undefined (TD-1), Arg.all() after leading arguments (TD-3), Arg.any('function') / Arg.any('object') on typed parameters (TD-5), matchers created on their own from an annotated predicate (TD-6, which only failed on 3.6 and 3.7) and `received().optionalProp = undefined` (TD-7). The TD-8 fixture needs template literal types and lib.dom, so it stays in spec-types/ only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/min-ts/consumer.ts | 53 ++++++++++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/spec-types/min-ts/consumer.ts b/spec-types/min-ts/consumer.ts index 523d19f..91df0be 100644 --- a/spec-types/min-ts/consumer.ts +++ b/spec-types/min-ts/consumer.ts @@ -92,6 +92,57 @@ function once(sub: SubstituteOf) { } once(calculator).add(1, 2) +// TD-2 / T26: setups and string assertions in generic code +interface Repo { get(id: string): T; find(id: string): T | undefined; count: number } +function stubRepo(repo: SubstituteOf>, value: T) { + repo.count.returns(1) + repo.get(Arg.any()).returns(value) + repo.find('a').returns(undefined) + repo[configure]().get('b').returns(value) + repo.received().get('a') + repo.didNotReceive().find('b') +} +stubRepo(Substitute.for>(), 'value') +function expectNoCalls(sub: SubstituteOf) { + return sub.didNotReceive() +} +expectNoCalls(calculator).add(1, 2) + +// TD-1 / T25: members typed only null / undefined +interface Ok { data: string; error?: undefined; nothing: null } +const ok = Substitute.for() +ok.data.returns('x') +const nothing: null = ok.nothing +const asOk: Ok = ok + +// TD-3 / T27: Arg.all() after leading arguments +interface Logger { + log(message: string, ...details: string[]): void + find(id: string, options?: { deep: boolean }): string +} +const logger = Substitute.for() +calculator.add(1, Arg.all()).returns(3) +calculator.received().add(1, Arg.all()) +logger.received().log('saved', Arg.all()) +logger.find('1', Arg.all()).returns('x') + +// TD-5 / T28: Arg.any('function') / Arg.any('object') on typed parameters +interface Bus { subscribe(handler: (value: number) => void): () => void; save(item: { id: string }): void } +const bus = Substitute.for() +bus.subscribe(Arg.any('function')).returns(() => undefined) +bus.received().save(Arg.any('object')) + +// TD-6 / T29: a matcher created on its own from an annotated predicate +const negative = Arg.is((x: number) => x < 0) +calculator.divide(negative, negative).returns(1) +const notZero = Arg.is.not((x: number) => x === 0) +calculator.divide(1, notZero).returns(2) + +// TD-7 / T30: clearing an optional property, checked in the assertion view +interface Form { note?: string } +const form = Substitute.for() +form.received().note = undefined + try { calculator.received().add(9, 9) } catch (error) { @@ -100,4 +151,4 @@ try { } } -export { asCalculator } +export { asCalculator, nothing, asOk } From 976b4cf18f2984a108cfae2ee57482b22a1915da Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:32:16 +0000 Subject: [PATCH 046/106] docs(types): documentation comments on the whole public API (TD-10) Editors showed no documentation for Substitute.for, Arg.*, .returns() and the other setup methods, nor for most of the exported symbols, although the changelog said the typings carry documentation comments (T32). Documented, in the built typings: - Substitute.for and SubstituteOf; - Arg (an explicit, documented `ArgMatchers` type), Arg.any / Arg.is / Arg.all, their call signatures, and `.not`; - the setup methods in both forms: .returns / .throws / .mimicks / .resolves / .rejects and [returns] / ... (the string forms are split into one type per method, so each carries its own comment), plus the exported symbols returns, throws, resolves, rejects, mimicks; - received / didNotReceive (string and symbol forms, and the exported symbols), configure, mimick and clearReceivedCalls; - SubstituteException was already documented. spec-types/TD-10.T32.jsdoc.js asks the TypeScript language service for the quick info of each of them in a consumer of dist/ and fails when one has no documentation. `npm run test:types:min-ts` runs it after the minimum-TypeScript check, so CI covers it once that script runs in CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/TD-10.T32.jsdoc.js | 115 +++++++++++++++++++++++++++++ spec-types/min-ts/check.js | 12 +++ src/api/Arg.ts | 52 ++++++++++++- src/api/Substitute.ts | 10 +++ src/api/types/Substitute.ts | 5 +- src/api/types/SubstituteMethods.ts | 52 +++++++++++-- src/api/types/SubstitutionLevel.ts | 72 ++++++++++++++---- 7 files changed, 292 insertions(+), 26 deletions(-) create mode 100644 spec-types/TD-10.T32.jsdoc.js diff --git a/spec-types/TD-10.T32.jsdoc.js b/spec-types/TD-10.T32.jsdoc.js new file mode 100644 index 0000000..5b35bb6 --- /dev/null +++ b/spec-types/TD-10.T32.jsdoc.js @@ -0,0 +1,115 @@ +#!/usr/bin/env node +// TD-10 / T32 The public API carries documentation comments that editors show (quick info), in the BUILT package +// typings (dist/*.d.ts). Each `/*@name*/` marker in the consumer below sits right before an identifier; the check asks +// the TypeScript language service for the quick info at that identifier and fails when it has no documentation. +// +// npm run build && node spec-types/TD-10.T32.jsdoc.js +// +// `npm run test:types:min-ts` runs it too (see spec-types/min-ts/check.js). The consumer only exists in memory. +'use strict' +const fs = require('fs') +const path = require('path') +const ts = require('typescript') + +const root = path.resolve(__dirname, '..') +if (!fs.existsSync(path.join(root, 'dist', 'index.d.ts'))) { + console.error('The package typings (dist/index.d.ts) were not found: run `npm run build` first.') + process.exit(1) +} + +const consumerPath = path.join(__dirname, '__jsdoc-consumer__.ts') +const consumer = ` +import { + Substitute, Arg, SubstituteOf, SubstituteException, + received, didNotReceive, mimick, clearReceivedCalls, configure, returns, throws, resolves, rejects, mimicks +} from '../dist' + +interface Calculator { + add(a: number, b: number): number + load(): Promise +} +const calculator = Substitute./*@Substitute.for*/for() +const asSubstitute: /*@SubstituteOf*/SubstituteOf = calculator + +calculator.add(/*@Arg*/Arg.any(), 2) +calculator.add(Arg./*@Arg.any*/any('number'), Arg.any./*@Arg.any.not*/not('number')) +calculator.add(Arg./*@Arg.is*/is(x => x > 0), Arg.is./*@Arg.is.not*/not(x => x === 0)) +calculator.add(Arg./*@Arg.all*/all()) + +calculator.add(1, 2)./*@returns()*/returns(3) +calculator.add(1, 2)./*@throws()*/throws(new Error()) +calculator.add(1, 2)./*@mimicks()*/mimicks((a, b) => a + b) +calculator.load()./*@resolves()*/resolves(1) +calculator.load()./*@rejects()*/rejects(new Error()) +calculator.add(1, 2)[/*@[returns]*/returns](3) +calculator.add(1, 2)[/*@[throws]*/throws](new Error()) +calculator.add(1, 2)[/*@[mimicks]*/mimicks]((a, b) => a + b) +calculator.load()[/*@[resolves]*/resolves](1) +calculator.load()[/*@[rejects]*/rejects](new Error()) + +calculator./*@received()*/received(1).add(1, 2) +calculator./*@didNotReceive()*/didNotReceive().add(1, 2) +calculator[/*@[received]*/received]().add(1, 2) +calculator[/*@[didNotReceive]*/didNotReceive]().add(1, 2) +calculator[/*@[configure]*/configure]().add(1, 2).returns(3) +calculator[/*@[mimick]*/mimick]({ add: (a, b) => a + b, load: async () => 1 }) +calculator[/*@[clearReceivedCalls]*/clearReceivedCalls]() + +const error = new /*@SubstituteException*/SubstituteException('message') +export { asSubstitute, error } +` + +const compilerOptions = { + module: ts.ModuleKind.CommonJS, + moduleResolution: ts.ModuleResolutionKind.NodeJs, + target: ts.ScriptTarget.ES2018, + lib: ['lib.es2018.d.ts'], + strict: true, + noEmit: true, + types: [] +} +const host = { + getScriptFileNames: () => [consumerPath], + getScriptVersion: () => '1', + getScriptSnapshot: fileName => { + const text = fileName === consumerPath ? consumer : (fs.existsSync(fileName) ? fs.readFileSync(fileName, 'utf8') : undefined) + return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text) + }, + getCurrentDirectory: () => __dirname, + getCompilationSettings: () => compilerOptions, + getDefaultLibFileName: options => ts.getDefaultLibFilePath(options), + fileExists: fileName => fileName === consumerPath || fs.existsSync(fileName), + readFile: fileName => fileName === consumerPath ? consumer : fs.readFileSync(fileName, 'utf8'), + readDirectory: ts.sys.readDirectory, + directoryExists: ts.sys.directoryExists, + getDirectories: ts.sys.getDirectories +} +const service = ts.createLanguageService(host, ts.createDocumentRegistry()) + +let failed = false +const diagnostics = service.getSemanticDiagnostics(consumerPath).concat(service.getSyntacticDiagnostics(consumerPath)) +for (const diagnostic of diagnostics) { + failed = true + console.log(`FAIL the consumer does not compile: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`) +} + +const marker = /\/\*@(.+?)\*\//g +let match +let count = 0 +while ((match = marker.exec(consumer)) !== null) { + count++ + const name = match[1] + const info = service.getQuickInfoAtPosition(consumerPath, match.index + match[0].length) + const documentation = info ? ts.displayPartsToString(info.documentation).trim() : '' + if (documentation === '') { + failed = true + console.log(`FAIL ${name}: no documentation comment`) + } else { + console.log(`ok ${name}: ${documentation.split('\n')[0].slice(0, 90)}`) + } +} +if (count === 0) { + failed = true + console.log('FAIL no markers found') +} +process.exit(failed ? 1 : 0) diff --git a/spec-types/min-ts/check.js b/spec-types/min-ts/check.js index ea05ac3..a15e996 100644 --- a/spec-types/min-ts/check.js +++ b/spec-types/min-ts/check.js @@ -6,6 +6,9 @@ // node spec-types/min-ts/check.js 3.9 4.0 4.4 # after `npm run build`: check other versions // // The consumer is compiled with `strict`, without @types/node and with skipLibCheck both off and on. +// +// Afterwards it runs spec-types/TD-10.T32.jsdoc.js, which checks (with the project's own TypeScript) that the public +// API in the same built typings carries documentation comments. 'use strict' const { spawnSync } = require('child_process') const fs = require('fs') @@ -75,4 +78,13 @@ try { if (fs.rmSync) fs.rmSync(workDirectory, { recursive: true, force: true }) else fs.rmdirSync(workDirectory, { recursive: true }) } + +const documentation = spawnSync(process.execPath, [path.join(__dirname, '..', 'TD-10.T32.jsdoc.js')], { cwd: root, encoding: 'utf8' }) +const documented = documentation.status === 0 +failed = failed || !documented +console.log(`${documented ? 'ok ' : 'FAIL'} documentation comments of the public API (spec-types/TD-10.T32.jsdoc.js)`) +if (!documented) { + const report = `${documentation.stdout || ''}${documentation.stderr || ''}`.split('\n').filter(line => !line.startsWith('ok')) + console.log(report.join('\n').trim().replace(/^/gm, ' ')) +} process.exit(failed ? 1 : 0) diff --git a/src/api/Arg.ts b/src/api/Arg.ts index 52b29c8..a253469 100644 --- a/src/api/Arg.ts +++ b/src/api/Arg.ts @@ -1,7 +1,13 @@ import { inspect } from 'util' import { Argument, AllArguments, ArgumentOptions, PredicateFunction, isSubstituteProxy } from '../shared' -type Inversable = T & { not: T } +type Inversable = T & { + /** + * The inverse matcher: it matches the arguments the matcher itself rejects, e.g. `Arg.is.not(x => x === 0)` or + * `Arg.any.not('string')`. A predicate that throws matches in neither form. + */ + not: T +} type ExtractFirstArg = T extends AllArguments ? TArgs[0] : T type ReturnArg = Argument & T const createInversable = (target: (arg: TArg, opt?: ArgumentOptions) => TReturn): Inversable<(arg: TArg) => TReturn> => { @@ -36,7 +42,16 @@ const isFunction = (predicate: PredicateFunction>, options return new Argument(`Arg.is{${describePredicate(predicate)}}`, predicate, options) } type Is = { + /** + * Matches an argument for which `predicate` returns a truthy value: `calculator.add(Arg.is(x => x > 10), 2)`. + * The predicate's parameter type is taken from the parameter the matcher is passed to. A predicate that throws counts + * as a non-match. + */ (predicate: PredicateFunction>): ReturnArg> + /** + * Matches an argument for which `predicate` returns a truthy value: `const negative = Arg.is((x: number) => x < 0)`. + * A predicate that throws counts as a non-match. + */ // Infers the type from an annotated predicate when the matcher is created on its own, which TypeScript 3.6 and 3.7 // cannot do through `ExtractFirstArg` above (TD-6). (predicate: (arg: T) => boolean): ReturnArg @@ -59,7 +74,14 @@ AnyFunction : T extends 'array' ? ReturnArg : any type AnyType = 'string' | 'number' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'array' | 'any' -type Any = (type?: T) => MapAnyReturn +type Any = { + /** + * Matches any argument (`Arg.any()`), or any argument of the given type: 'string', 'number', 'boolean', 'symbol', + * 'undefined', 'object' (non-null objects, arrays and substitutes), 'function' (functions, classes and substitutes), + * 'array' or 'any'. + */ + (type?: T): MapAnyReturn +} const createAnyPredicate = (type: string): PredicateFunction => { switch (type) { @@ -94,7 +116,31 @@ const anyFunction = (type: AnyType = 'any', options?: ArgumentOptions) => { return new Argument(description, anyPredicateFor(type), options) } -export const Arg = { +type ArgMatchers = { + /** + * Matches all arguments. As the only argument it matches any argument list: `calculator.add(Arg.all())`. After + * leading arguments it matches the rest of the arguments, including none: `logger.log('saved', Arg.all())` matches + * `log('saved')` and `log('saved', 1, 2)`. Nothing may follow it. + */ + all: () => AllArguments + /** + * Matches an argument for which the predicate returns a truthy value: `calculator.add(Arg.is(x => x > 10), 2)`. + * `Arg.is.not(predicate)` matches where it returns a falsy value. A predicate that throws matches in neither form. + */ + is: Inversable + /** + * Matches any argument (`Arg.any()`), or any argument of a type (`Arg.any('string')`): 'string', 'number', + * 'boolean', 'symbol', 'undefined', 'object' (non-null objects, arrays and substitutes), 'function' (functions, + * classes and substitutes), 'array' or 'any'. `Arg.any.not('string')` matches every argument that is not a string. + */ + any: Inversable +} + +/** + * Argument matchers for setups and assertions: `Arg.any()`, `Arg.is(predicate)`, `Arg.all()` and their `.not` forms. + * A call whose arguments contain a matcher is always a setup or an assertion, never a real call. + */ +export const Arg: ArgMatchers = { all: (): AllArguments => new AllArguments(), is: createInversable(isFunction) as Inversable, any: createInversable(anyFunction) as Inversable diff --git a/src/api/Substitute.ts b/src/api/Substitute.ts index 96208be..758fa15 100644 --- a/src/api/Substitute.ts +++ b/src/api/Substitute.ts @@ -1,9 +1,19 @@ import { ObjectSubstitute } from './types' import { createSubstitute } from '../internals' +/** + * The type of a substitute for `T`: every member of `T` with the setup API (`.returns`, `.throws`, `.mimicks`, and + * `.resolves` / `.rejects` for promises), plus `received` / `didNotReceive` and the symbol API (`[received]`, + * `[didNotReceive]`, `[configure]`, `[mimick]`, `[clearReceivedCalls]`). It is assignable to `T`. + */ export type SubstituteOf = ObjectSubstitute & T export class Substitute { + /** + * Creates a substitute for `T` (an interface, a class or any other type): `const calculator = Substitute.for()`. + * Configure it with `calculator.add(1, 2).returns(3)`, pass it to the code under test as a `T`, and check the calls + * with `calculator.received().add(1, 2)`. Members that were not configured return a substitute of their own. + */ public static for(): SubstituteOf { return createSubstitute() as SubstituteOf } diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index 280d072..f43261f 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -32,7 +32,8 @@ type Members = string extends keyof T ? T : Pick // (`await sub` resolves to the substitute itself); the typings make `then` `never`. `toJSON` is answered by the // substitute itself (it serializes the substitute): it keeps its declared type on the substitute (through `& T`) but // has no setup API, and it cannot be configured or asserted. -// Symbol.toPrimitive and util.inspect.custom are special-cased at runtime as well but are not reflected here. +// The other keys the runtime special-cases (Symbol.toPrimitive, util.inspect.custom, the well-known symbols, ...) are +// not reflected here. type SubstituteMember = FunctionSubstitute, 'substitute'> & PropertySubstitute @@ -44,7 +45,7 @@ type SubstituteMembers = { SubstituteMember } -/** The members of a substitute (without the assertion and configuration methods). */ +/** The members of a substitute (without the assertion and configuration methods), each with its setup API. */ export type ObjectSubstituteTransformation = SubstituteMembers> // In the assertion view, a member that is not callable keeps its declared type, including `undefined` for an optional diff --git a/src/api/types/SubstituteMethods.ts b/src/api/types/SubstituteMethods.ts index 249037b..f3e6342 100644 --- a/src/api/types/SubstituteMethods.ts +++ b/src/api/types/SubstituteMethods.ts @@ -2,32 +2,72 @@ import { constants } from '../../shared' import { ConfigureView, TerminatingObject } from './Substitute' import { HasAnyMember, LibraryMemberName } from './Utilities' +/** + * Starts an assertion: `sub[received]()` (1 or more times) or `sub[received](n)` (exactly `n` times), followed by the + * member access, call or property set to check, e.g. `calculator[received](2).add(1, Arg.any())`. + * The symbol form always works, also when the substituted type has its own member called `received`, and in generic + * code. + */ export const received: typeof constants.CONTEXT.received.symbol = constants.CONTEXT.received.symbol +/** + * Starts an assertion that the following member access, call or property set never happened: + * `sub[didNotReceive]().add(1, 2)`. Same as `sub[received](0)`. + */ export const didNotReceive: typeof constants.CONTEXT.didNotReceive.symbol = constants.CONTEXT.didNotReceive.symbol +/** + * Makes a substitute delegate to a real instance: `sub[mimick](instance)`. Every member access, call or set without a + * matching substitution goes to `instance`; calls are still recorded for assertions. Symbol-only: a string `mimick` is + * always an ordinary member of the substituted type. + */ export const mimick: typeof constants.CONTEXT.mimick.symbol = constants.CONTEXT.mimick.symbol +/** + * Clears the calls received so far by a substitute (and its auto-substitutes): `sub[clearReceivedCalls]()`. The + * configured substitutions are kept. + */ export const clearReceivedCalls: typeof constants.CONTEXT.clearReceivedCalls.symbol = constants.CONTEXT.clearReceivedCalls.symbol +/** + * Gives a view of a substitute in which every member access or call is a setup, never a real call: + * `sub[configure]().add(1, 3).returns(1337)`. Use it to re-configure a call whose literal arguments already match an + * existing substitution (a plain `sub.add(1, 3)` would return the configured value instead). + */ export const configure: typeof constants.CONTEXT.configure.symbol = constants.CONTEXT.configure.symbol /** * The symbol API is always available, also on `SubstituteOf` for a generic `T` (T:TY-3). */ type SymbolSubstituteMethods = { - /** Asserts that the following member access, call or set happened `amount` times (1 or more when omitted). */ + /** + * Asserts that the following member access, call or set happened `amount` times (1 or more when omitted). + * Throws a `SubstituteException` when it did not. `amount` must be a non-negative integer. + */ [received](amount?: number): TerminatingObject /** Asserts that the following member access, call or set never happened. Same as `[received](0)`. */ [didNotReceive](): TerminatingObject - /** Delegates every member access, call or set without a matching substitution to `instance`. */ + /** + * Delegates every member access, call or set without a matching substitution to `instance`. Calls are still + * recorded, and explicit substitutions take precedence. + */ [mimick](instance: T): void - /** Clears the received calls of this substitute; configured substitutions are kept. */ + /** Clears the received calls of this substitute (and its auto-substitutes); configured substitutions are kept. */ [clearReceivedCalls](): void - /** A view of the substitute where every member access or call is a setup (`sub[configure]().add(1, 2).returns(3)`). */ + /** + * A view of the substitute where every member access or call is a setup, never a real call: + * `sub[configure]().add(1, 2).returns(3)`. + */ [configure](): ConfigureView } type StringSubstituteMethods = { - /** Asserts that the following member access, call or set happened `amount` times (1 or more when omitted). */ + /** + * Asserts that the following member access, call or set happened `amount` times (1 or more when omitted). + * Throws a `SubstituteException` when it did not. `amount` must be a non-negative integer. + * `sub[received]()` is the symbol form. + */ received(amount?: number): TerminatingObject - /** Asserts that the following member access, call or set never happened. Same as `received(0)`. */ + /** + * Asserts that the following member access, call or set never happened. Same as `received(0)`. + * `sub[didNotReceive]()` is the symbol form. + */ didNotReceive(): TerminatingObject } diff --git a/src/api/types/SubstitutionLevel.ts b/src/api/types/SubstitutionLevel.ts index 68596a8..6f3b6a3 100644 --- a/src/api/types/SubstitutionLevel.ts +++ b/src/api/types/SubstitutionLevel.ts @@ -1,10 +1,18 @@ import { constants } from '../../shared' import { HasMember, LibraryMemberName, Primitive } from './Utilities' +/** + * Symbol form of `.returns(...)`: `sub.add(1, 2)[returns](3)`. Always available, also where the value has its own member + * called `returns`. + */ export const returns: typeof constants.CONTEXT.returns.symbol = constants.CONTEXT.returns.symbol +/** Symbol form of `.throws(...)`: `sub.divide(1, 0)[throws](new Error())`. */ export const throws: typeof constants.CONTEXT.throws.symbol = constants.CONTEXT.throws.symbol +/** Symbol form of `.resolves(...)`, offered on members that return a promise: `sub.load()[resolves](value)`. */ export const resolves: typeof constants.CONTEXT.resolves.symbol = constants.CONTEXT.resolves.symbol +/** Symbol form of `.rejects(...)`, offered on members that return a promise: `sub.load()[rejects](new Error())`. */ export const rejects: typeof constants.CONTEXT.rejects.symbol = constants.CONTEXT.rejects.symbol +/** Symbol form of `.mimicks(...)`: `sub.add(Arg.all())[mimicks]((a, b) => a + b)`. */ export const mimicks: typeof constants.CONTEXT.mimicks.symbol = constants.CONTEXT.mimicks.symbol type OneArgumentRequiredFunction = (requiredInput: TArgs, ...restInputs: TArgs[]) => TReturnType @@ -22,22 +30,56 @@ type IsPromise = [NonNullable] extends [never] ? false [NonNullable] extends [Promise] ? true : false type SymbolSetupMethods = { + /** + * Configures the value(s) to return. With several values, the calls return them in order and then keep returning + * the last one. + */ [returns]: ReturnsFunction + /** Configures the error(s) to throw, in order; the last one keeps being thrown. */ [throws]: ThrowsFunction + /** + * Configures implementation(s) to run instead. They receive the call's arguments and their result is returned; with + * several implementations, the calls use them in order and then keep using the last one. + */ [mimicks]: MimicksFunction } & (IsPromise extends true ? { + /** Configures the value(s) the returned promise resolves to, in order; the last one is repeated. */ [resolves]: ResolvesFunction> + /** Configures the reason(s) the returned promise rejects with, in order; the last one is repeated. */ [rejects]: RejectsFunction } : {}) -type StringSetupMethods = { +type StringReturns = { + /** + * Configures the value(s) to return. With several values, the calls return them in order and then keep returning + * the last one. `[returns]` is the symbol form. + */ returns: ReturnsFunction +} +type StringThrows = { + /** Configures the error(s) to throw, in order; the last one keeps being thrown. `[throws]` is the symbol form. */ throws: ThrowsFunction +} +type StringMimicks = { + /** + * Configures implementation(s) to run instead. They receive the call's arguments and their result is returned; with + * several implementations, the calls use them in order and then keep using the last one. `[mimicks]` is the symbol + * form. + */ mimicks: MimicksFunction -} & (IsPromise extends true ? { - resolves: ResolvesFunction> +} +type StringResolves = { + /** Configures the value(s) the returned promise resolves to, in order; the last one is repeated. `[resolves]` is the symbol form. */ + resolves: ResolvesFunction +} +type StringRejects = { + /** Configures the reason(s) the returned promise rejects with, in order; the last one is repeated. `[rejects]` is the symbol form. */ rejects: RejectsFunction -} : {}) +} + +type StringSetupMethods = + StringReturns & StringThrows & StringMimicks & + (IsPromise extends true ? StringResolves> & StringRejects : {}) // The string form of a setup method is offered only when the value it is accessed on has no member with that name. // Otherwise `value.returns` would be the value's own member (the symbol form `value[returns]` always works). @@ -46,18 +88,18 @@ type StringSetupMethods = { // constraint `{}`, which has no conflicting member: in generic code all string forms are offered (TD-2, T26). The method // type itself is computed from the whole value type, so a union return type does not split the method (T:TY-1). type StringForm = TCheck extends unknown ? - (HasMember extends true ? {} : { [P in TName]: TMethod }) : + (HasMember extends true ? {} : TMethod) : never type CheckedStringSetupMethods = // Primitives (and unions of literals, however large) have no conflicting member: skip the per-member check (TD-8). [NonNullable] extends [Primitive] ? StringSetupMethods : - StringForm & {}, 'returns', ReturnsFunction> & - StringForm & {}, 'throws', ThrowsFunction> & - StringForm & {}, 'mimicks', MimicksFunction> & + StringForm & {}, 'returns', StringReturns> & + StringForm & {}, 'throws', StringThrows> & + StringForm & {}, 'mimicks', StringMimicks> & (IsPromise extends true ? ( - StringForm & {}, 'resolves', ResolvesFunction>> & - StringForm & {}, 'rejects', RejectsFunction> + StringForm & {}, 'resolves', StringResolves>> & + StringForm & {}, 'rejects', StringRejects> ) : {}) /** @@ -76,11 +118,11 @@ export type UncheckedSetupMethods = /** * The type of a call on a substitute: the returned value intersected with the setup API. * `null` and `undefined` cannot carry the setup API, so they are dropped from the value part (T:TY-9), while the - * setup methods still accept them. When nothing is left (`null`, `undefined` or `never`), only the setup API remains. - * For `never` (a member that always throws) `returns` accepts no value (T:TY-12), so only `throws` and `mimicks` can be - * used. - * There is deliberately no separate branch for `never`: for a type parameter (generic code) the check cannot be - * decided, and TypeScript then only offers the members that all branches have (TD-2, T26). + * setup methods still accept them. When nothing is left (`null`, `undefined`, `void`-like or `never`), only the setup + * API remains. For `never` (a member that always throws) `returns` accepts no value (T:TY-12), so only `throws` and + * `mimicks` can be used. + * There is deliberately no separate branch for `never`: for a return type that is a type parameter (generic code) the + * check cannot be decided, and TypeScript then only offers the members that all branches have (TD-2, T26). */ export type SubstitutionResult = [NonNullable] extends [never] ? UncheckedSetupMethods : From 13a257d4145951dd611afd613eee8e5eb58eeb44 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:34:43 +0000 Subject: [PATCH 047/106] fix(arguments): the nested-matcher scan runs no getters and survives revoked proxies Looking for matchers nested in the arguments of a real call read the values of accessor properties (a second getter run per call) and crashed on a revoked proxy (Array.isArray throws). It now reads data properties only and treats a container it cannot inspect as holding no matcher. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 13 +++++++++++++ src/internals/RecordedArguments.ts | 25 +++++++++++++++++++------ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index e3c235b..72dd41b 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -352,6 +352,19 @@ test('ENG2-5 (D27) Arg matchers nested in plain objects and arrays match deeply, literal.put(new Map([['k', Arg.any()]])) literal.received(2).put(Arg.all()) + // looking for nested matchers runs no getters of the arguments, and survives revoked proxies + let getterReads = 0 + const lazy = {} + Object.defineProperty(lazy, 'value', { enumerable: true, get() { getterReads++; return 1 } }) + const scanned = Substitute.for() + scanned.take(lazy) + scanned.take(lazy) + t.true(getterReads <= 1, `${getterReads} getter reads`) + const { proxy: revoked, revoke } = Proxy.revocable({}, {}) + revoke() + t.notThrows(() => scanned.take(revoked)) + t.throws(() => scanned.received(2).take(revoked), { instanceOf: SubstituteException }) + // cycles end, in the specification and in the actual arguments const cyclicSpecification: any = { name: Arg.any() } cyclicSpecification.self = cyclicSpecification diff --git a/src/internals/RecordedArguments.ts b/src/internals/RecordedArguments.ts index aae88b8..7de9143 100644 --- a/src/internals/RecordedArguments.ts +++ b/src/internals/RecordedArguments.ts @@ -34,9 +34,13 @@ const literalEquals = (expected: unknown, actual: unknown): boolean => { /** Arrays, and objects whose prototype is Object.prototype or null: the only values that may hold nested matchers. */ const isPlainContainer = (value: unknown): value is object => { if (typeof value !== 'object' || value === null || isArgumentMatcher(value)) return false - if (Array.isArray(value)) return true - const prototype = Object.getPrototypeOf(value) - return prototype === Object.prototype || prototype === null + try { + if (Array.isArray(value)) return true + const prototype = Object.getPrototypeOf(value) + return prototype === Object.prototype || prototype === null + } catch { + return false // a revoked proxy + } } /** The own enumerable string and symbol keys of a plain object (the keys deep strict equality compares). */ @@ -52,15 +56,24 @@ const containerEntries = (container: object): Array<[PropertyKey, unknown]> => A ? Array.from({ length: container.length }, (_, index): [PropertyKey, unknown] => [index, container[index]]) : ownEnumerableKeys(container).map((key): [PropertyKey, unknown] => [key, (container as any)[key]]) -/** Whether some value inside a plain container satisfies the predicate, without allocating per item. */ +/** The value of an own data property; getters are not run (a matcher behind a getter is not looked for). */ +const dataValue = (object: object, key: PropertyKey): unknown => { + const descriptor = Object.getOwnPropertyDescriptor(object, key) + return descriptor !== undefined && 'value' in descriptor ? descriptor.value : undefined +} + +/** + * Whether some value inside a plain container satisfies the predicate. Used on the arguments of every call, so it + * allocates nothing per item and runs no getters of the code under test's objects. + */ const someItem = (container: object, predicate: (item: unknown) => boolean): boolean => { if (Array.isArray(container)) { for (let index = 0; index < container.length; index++) if (predicate(container[index])) return true return false } - for (const key of Object.keys(container)) if (predicate((container as any)[key])) return true + for (const key of Object.keys(container)) if (predicate(dataValue(container, key))) return true for (const symbol of Object.getOwnPropertySymbols(container)) - if (Object.prototype.propertyIsEnumerable.call(container, symbol) && predicate((container as any)[symbol])) return true + if (Object.prototype.propertyIsEnumerable.call(container, symbol) && predicate(dataValue(container, symbol))) return true return false } From 326a8de4159646148678016ccda747d48ddfd08b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:38:23 +0000 Subject: [PATCH 048/106] feat(assertions): direct-call assertions through the string forms and on member handles D26 lists x.received()(1) among the assertions that count the direct-call reading. The string received(n) / didNotReceive() followed by an invocation is now an assertion of a direct call (D11 already made it one when followed by a member access), instead of a silent call of a member named received. A direct-call assertion on a member handle, sub.method[received]()(1), checks the calls of the member on its parent, where invoking the handle records them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 9 +++++++++ src/internals/Engine.ts | 23 ++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index 72dd41b..69b281f 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -200,6 +200,12 @@ test('ENG2-3 (D26) call/apply/bind on a function substitute or a call result beh t.notThrows(() => listener[received](1)('saved')) t.notThrows(() => listener[received](1).apply(undefined, ['saved']), 'the member reading counts it too') t.is(inspect(listener).split('\n')[2], " ('saved') via .apply(undefined, [ 'saved' ])", 'shown once') + // the string forms followed by an invocation assert a direct call as well (D11 extended by D26) + const before = inspect(listener) + t.notThrows(() => listener.received(1)('saved')) + t.throws(() => listener.didNotReceive()('saved'), { instanceOf: SubstituteException }) + t.throws(() => listener.received(Arg.any())('saved'), { instanceOf: SubstituteException, message: /Expected count/ }) + t.is(inspect(listener), before, 'and they are not recorded') const callback = Substitute.for() callback(1).returns(5) @@ -254,6 +260,9 @@ test('ENG2-4 (D26) members named call/apply/bind keep their member reading', t = // ... and the direct reading counts them as well (bind only when the bound function is invoked) t.notThrows(() => shop.received(1).rpc(1)) t.notThrows(() => shop.received(1).discount()) + t.notThrows(() => shop.rpc.received(1)(1), 'invoking a member handle is a call of the member') + t.notThrows(() => shop.rpc[received](1)(1)) + t.throws(() => shop.rpc[received](1)(2), { instanceOf: SubstituteException }) t.notThrows(() => shop.received(1).socket, 'socket was only read: the bind call is a call of its member bind') t.is(inspect(shop), "@Substitute {\n received:\n discount() via .apply({ total: 10 })\n socket\n rpc(1) via .call('getUser', 1)\n}") const message = messageOf(() => shop.received(2).rpc(1)) diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 402a029..903ee75 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -259,6 +259,12 @@ const faceApply = (face: Face, thisArg: unknown, args: any[], stackStart: Functi const self = { thisArg, explicit: false } if (!(face instanceof AutoEntry)) return invoke(face, SELF, args, stackStart, undefined, undefined, self) if (face.kind === 'get') return invoke(face.parent, face.key, args, stackStart, TAKE_PENDING_READ, undefined, self) + // D11 / D26: `fn.received(n)` followed by an invocation asserts a direct call, like a member access after it does + if (isStringAssertionKey(face.key)) { + const assertion = resolveStringAssertion(face, continuedChain(face.adjacentHandOut(), frameAt(stackStart)), stackStart) + assertDirectCall(assertion.state, args, assertion.count, stackStart) + return undefined + } return invoke(face.state, SELF, args, stackStart, undefined, face.adjacentHandOut(), self) } @@ -680,12 +686,23 @@ const createAssertionProxy = (state: SubstituteState, count: ExpectedCount): any return true }, apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { - assertCall(state, SELF, args, count, apply) + assertDirectCall(state, args, count, apply) return undefined } }) } +/** + * An assertion that a substitute was invoked directly: `fn[received]()(1)`. A member handle (`sub.method`) is never + * invoked on its own: invoking it is a call of the member, recorded on the parent, so that is what is checked + * (`sub.method[received]()(1)` is `sub[received]().method(1)`, D26). + */ +const assertDirectCall = (state: SubstituteState, args: any[], count: ExpectedCount, stackStart: Function): void => { + const owner = state.owner + if (owner !== undefined && owner.kind === 'get') assertCall(owner.parent, owner.key, args, count, stackStart) + else assertCall(state, SELF, args, count, stackStart) +} + /** `sub.received(n).member`: a property assertion now, or a method assertion if it is invoked. */ const assertionMember = (state: SubstituteState, key: PropertyKey, count: ExpectedCount, stackStart: Function): any => { const deferred = assertPropertyRead(state, key, count, stackStart) @@ -871,6 +888,10 @@ const configureCall = (state: SubstituteState, key: PropertyKey, specification: return true }, apply: function apply(_target: unknown, _thisArg: unknown, args: any[]) { + if (stringAssertion) { + assertDirectCall(state, args, assertionCount(apply), apply) + return undefined + } return nestedSetupTarget(state, key, specification, undefined, apply)(...args) } }) From 99cc83fa88ac15fce9e50b8828ed1b27236dafbf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:39:08 +0000 Subject: [PATCH 049/106] fix(engine): call/apply/bind on a substitute mimicking an object without them read like the object D12: a substitute that mimicks a plain object without a member call, apply or bind reads that member as the object does (undefined) instead of offering the D26 helper. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3.test.ts | 5 +++++ src/internals/Engine.ts | 11 ++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/spec/regression/fixes/round3.test.ts b/spec/regression/fixes/round3.test.ts index 69b281f..a9697cd 100644 --- a/spec/regression/fixes/round3.test.ts +++ b/spec/regression/fixes/round3.test.ts @@ -294,6 +294,11 @@ test('ENG2-4 (D26) members named call/apply/bind keep their member reading', t = const property = Substitute.for() property[configure]().call.returns('configured') t.is(property.call, 'configured') + // a substitute that mimicks an object without such a member reads it like the object does (D12) + const plainObject = Substitute.for() + plainObject[mimick]({ name: 'x' }) + t.is(plainObject.call, undefined) + t.is(plainObject.bind, undefined) }) test('ENG2-5 (D27) Arg matchers nested in plain objects and arrays match deeply, and make the call a setup', t => { diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 903ee75..5aee0b9 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -230,9 +230,14 @@ const faceGet = (face: Face, property: PropertyKey, stackStart: Function): any = } } - // D26: call/apply/bind, unless the member with that name is configured as a property - if (isFunctionHelperKey(property) && memberStateOf(face)?.propertySubstitution(property) === undefined) - return dualHelper(face, property, chainHead()) + // D26: call/apply/bind, unless the member with that name is configured as a property, or the substitute mimicks + // an instance that has no such member (then it reads like on the instance, D12) + if (isFunctionHelperKey(property)) { + const memberState = memberStateOf(face) + const instance = memberState?.mimicked?.instance + if (memberState?.propertySubstitution(property) === undefined && (instance === undefined || hasMember(instance, property))) + return dualHelper(face, property, chainHead()) + } const context = contextMethodOf(property) if (context !== undefined) return contextFunction(context, () => faceState(face), chainHead()) From 8dbec02be4d308bf79c90dd6144ff716365cb534 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:51:20 +0000 Subject: [PATCH 050/106] fix(packaging): make the ES module entry independent of CommonJS interop (F1) dist/index.mjs did `import cjs from './index.js'`. Because dist/index.js sets __esModule and exports.default, Rollup's commonjs plugin, Vite SSR and vitest with inlined dependencies resolved `cjs` to the Substitute class, so every export of the package was undefined there. The generated wrapper now imports both the default and the namespace of the CommonJS build, uses whichever one is the complete exports object, and throws a clear error at import time if neither is. Checks: - packaging test that runs the wrapper against simulated Node.js, webpack-like and __esModule-interop views of the CommonJS build; - compatibility-checks/test/bundlers.ts bundles the packed package with Rollup + @rollup/plugin-commonjs, webpack, esbuild (cjs and esm) and a Vite SSR build with ssr.noExternal, and runs vitest with server.deps.inline; - a vitest-inline runner in the test runner compatibility checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CONTRIBUTING.md | 26 +- compatibility-checks/bundlers/entry.mjs | 32 + compatibility-checks/package-lock.json | 1211 ++++++++++++++++- compatibility-checks/package.json | 11 +- .../vitest-inline/exports.test.ts | 25 + .../test-runners/vitest-inline/index.spec.ts | 7 + compatibility-checks/test/bundlers.ts | 153 +++ compatibility-checks/test/index.ts | 4 +- compatibility-checks/vitest.inline.config.mts | 15 + packaging/build-esm.js | 24 +- packaging/package.test.js | 66 + 11 files changed, 1521 insertions(+), 53 deletions(-) create mode 100644 compatibility-checks/bundlers/entry.mjs create mode 100644 compatibility-checks/test-runners/vitest-inline/exports.test.ts create mode 100644 compatibility-checks/test-runners/vitest-inline/index.spec.ts create mode 100644 compatibility-checks/test/bundlers.ts create mode 100644 compatibility-checks/vitest.inline.config.mts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 92e66ee..c09ee4e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,7 +29,7 @@ npm ci | `src/` | The library source (TypeScript). `src/index.ts` is the public entry point. | | `spec/` | The runtime specs, run with [ava](https://github.com/avajs/ava). | | `packaging/` | Packaging checks (run as part of `npm test`), the ES module wrapper generator and the smoke tests. | -| `compatibility-checks/` | A separate npm project that checks the packed package with ava, jest, mocha, node:test and vitest. | +| `compatibility-checks/` | A separate npm project that checks the packed package with ava, jest, mocha, node:test and vitest, and bundles it with Rollup, webpack, esbuild and Vite. | | `dist/` | Build output that gets published (generated, not committed). | | `dist-spec/` | Compiled specs used by `npm test` (generated, not committed). | @@ -43,7 +43,12 @@ This compiles `src/` into `dist/` with `tsc` (CommonJS plus `.d.ts` typings) and `packaging/build-esm.js`, which generates the native ES module entry point next to it: - `dist/index.mjs` re-exports every export of `dist/index.js`, plus the default export. It wraps the CommonJS - build instead of being a second copy, so CommonJS and ESM consumers share one module instance. + build instead of being a second copy, so CommonJS and ESM consumers share one module instance. Tools disagree + about what a default import of a CommonJS module that sets `__esModule` is: Node.js, webpack and esbuild give + `module.exports`, while Rollup's commonjs plugin, Vite SSR and vitest with inlined dependencies give + `exports.default`. The wrapper therefore imports both the default and the namespace of `dist/index.js`, uses + whichever one holds the complete exports, and throws at import time if neither does. A packaging test simulates + each of these interop shapes, and the compatibility checks bundle the package with the real tools. - `dist/index.d.mts` holds the matching typings for TypeScript's `node16`, `nodenext` and `bundler` resolution. The `exports` map in `package.json` sends `import` to the ES module entry and everything else (`require`, older @@ -87,9 +92,18 @@ Type-level tests check the public typings with the TypeScript compiler. CI runs ### Compatibility checks -`compatibility-checks/` is a separate npm project with its own dependencies. It verifies that every supported -test runner (ava, jest, mocha, node:test and vitest) reports a failing Substitute assertion, including one that -is thrown after the test function has returned. It runs against the packed package, not against `src/`: +`compatibility-checks/` is a separate npm project with its own dependencies. It runs against the packed package, +not against `src/`, and checks two things: + +- `test/index.ts`: every supported test runner (ava, jest, mocha, node:test, vitest, and vitest with the package + inlined through `vitest.inline.config.mts`) reports a failing Substitute assertion, including one that is thrown + after the test function has returned. +- `test/bundlers.ts`: `bundlers/entry.mjs` is bundled with Rollup and `@rollup/plugin-commonjs`, webpack, esbuild + (CommonJS and ES module output) and a Vite SSR build with `ssr.noExternal`, and each bundle is run with Node.js. + The default, named and namespace imports must be the real exports. vitest with `server.deps.inline` runs + `test-runners/vitest-inline/exports.test.ts`, which checks the same. + +Run them with: ```sh cd compatibility-checks @@ -103,7 +117,7 @@ nor `package-lock.json` of the compatibility checks changes. From the repository does the same once the compatibility check dependencies are installed. To try a single runner by hand after `npm run install:local`, use `npm run validate:` (`ava`, `jest`, -`mocha`, `nodejs` or `vitest`). Each of them is expected to fail with exactly one failing test. +`mocha`, `nodejs`, `vitest` or `vitest-inline`). Each of them is expected to fail with exactly one failing test. ## Continuous integration diff --git a/compatibility-checks/bundlers/entry.mjs b/compatibility-checks/bundlers/entry.mjs new file mode 100644 index 0000000..32b47be --- /dev/null +++ b/compatibility-checks/bundlers/entry.mjs @@ -0,0 +1,32 @@ +// F1: test/bundlers.ts bundles this file with each bundler and runs the bundle with Node.js. It reports what the +// default, named and namespace imports of the package are inside the bundle, and whether the library works there. +import Substitute, { Substitute as NamedSubstitute, Arg, received, SubstituteException } from '@fluffy-spoon/substitute' +import * as namespace from '@fluffy-spoon/substitute' + +const report = { + defaultImport: typeof Substitute, + defaultIsNamedSubstitute: Substitute === NamedSubstitute, + namespaceDefaultIsSubstitute: namespace.default === Substitute, + arg: typeof Arg, + received: typeof received, + substituteException: typeof SubstituteException, + namespaceKeys: Object.keys(namespace).sort(), + undefinedNamespaceValues: Object.keys(namespace).filter(name => namespace[name] === undefined).sort() +} + +try { + const calculator = NamedSubstitute.for() + calculator.add(1, Arg.any()).returns(3) + report.returns = calculator.add(1, 2) + calculator[received](1).add(1, 2) + try { + calculator.received(2).add(1, 2) + report.failingAssertion = 'did not throw' + } catch (error) { + report.failingAssertion = error instanceof SubstituteException ? 'SubstituteException' : String(error) + } +} catch (error) { + report.error = String((error && error.stack) || error) +} + +console.log(JSON.stringify(report)) diff --git a/compatibility-checks/package-lock.json b/compatibility-checks/package-lock.json index 3fdb331..9c54193 100644 --- a/compatibility-checks/package-lock.json +++ b/compatibility-checks/package-lock.json @@ -9,16 +9,22 @@ "version": "0.0.0", "license": "MIT", "devDependencies": { + "@rollup/plugin-commonjs": "^29.0.3", + "@rollup/plugin-node-resolve": "^16.0.3", "@types/mocha": "^10.0.10", "@types/node": "^22.20.5", "ansi-regex": "^6.0.1", "ava": "^6.4.1", + "esbuild": "^0.28.2", "jest": "^30.5.2", "mocha": "^12.0.3", + "rollup": "^4.68.4", "ts-jest": "^29.4.15", "tsx": "^4.23.15", "typescript": "^5.9.3", - "vitest": "^5.1.0" + "vite": "^8.3.8", + "vitest": "^5.1.0", + "webpack": "^5.112.2" }, "engines": { "node": ">=22.12" @@ -575,7 +581,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" @@ -588,7 +593,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -600,7 +604,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -1892,6 +1895,17 @@ "node": ">=6.0.0" } }, + "node_modules/@jridgewell/source-map": { + "version": "0.3.11", + "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz", + "integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.25" + } + }, "node_modules/@jridgewell/sourcemap-codec": { "version": "1.6.0", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", @@ -1939,7 +1953,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@tybys/wasm-util": "^0.10.3" }, @@ -1999,7 +2012,6 @@ "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/oxc-project" } @@ -2328,7 +2340,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2346,7 +2357,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2364,7 +2374,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2382,7 +2391,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2400,7 +2408,6 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2418,7 +2425,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2436,7 +2442,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2454,7 +2459,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2472,7 +2476,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2490,7 +2493,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2508,7 +2510,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2526,7 +2527,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2544,7 +2544,6 @@ "os": [ "openharmony" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2559,7 +2558,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@emnapi/core": "2.0.0-beta.2", "@emnapi/runtime": "2.0.0-beta.2", @@ -2582,7 +2580,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2600,7 +2597,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -2610,8 +2606,69 @@ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", "dev": true, + "license": "MIT" + }, + "node_modules/@rollup/plugin-commonjs": { + "version": "29.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-29.0.3.tgz", + "integrity": "sha512-ZaOxZceP7SOUW7Lqw5IRVweSQYWaeIPnXIGLiB690EBA3FGJTO40EEr2L5yZplJWsgTCogILRSpcAe7+U0Otdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "commondir": "^1.0.1", + "estree-walker": "^2.0.2", + "fdir": "^6.2.0", + "is-reference": "1.2.1", + "magic-string": "^0.30.3", + "picomatch": "^4.0.2" + }, + "engines": { + "node": ">=16.0.0 || 14 >= 14.17" + }, + "peerDependencies": { + "rollup": "^2.68.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } + }, + "node_modules/@rollup/plugin-commonjs/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, "license": "MIT", - "peer": true + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@rollup/plugin-node-resolve": { + "version": "16.0.3", + "resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-16.0.3.tgz", + "integrity": "sha512-lUYM3UBGuM93CnMPG1YocWu7X802BrNF3jW2zny5gQyLQgRFJhV1Sq0Zi74+dh/6NBx1DxFC4b4GXg9wUCG5Qg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rollup/pluginutils": "^5.0.1", + "@types/resolve": "1.20.2", + "deepmerge": "^4.2.2", + "is-module": "^1.0.0", + "resolve": "^1.22.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "rollup": "^2.78.0||^3.0.0||^4.0.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + } + } }, "node_modules/@rollup/pluginutils": { "version": "5.5.1", @@ -2636,6 +2693,370 @@ } } }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.4.tgz", + "integrity": "sha512-8AfICPTDNFpsRltDrWzlX3iVEwHubamhXc10bjOJRCl4eZXj+BE25uCVMYzFpbcqfuxSfrt4VkSVL5QqiHoVDQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.4.tgz", + "integrity": "sha512-Vs4CxDXeCrCVNZ9jPnicohYT7aX7cxLzjMepkno/7f1zFhC80OUsKHM03BJsusLfYnjKrUe7D8vPvQNdD+rjCg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.4.tgz", + "integrity": "sha512-EEytXPqw9k5OIyx1Cou+Xg8XhTwtWW31WIGq1cWTpX05ek6STIprxJ5wY6cOEZAk5sjXM/mE2/JohNhtUiPukg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.4.tgz", + "integrity": "sha512-eRYMGvFdL3TKnaXlacxifKMltpLxehT0XghbV5pPfzJUNCc+psia9rg/scZZPfeDK+VKpSZx9VoMz236yeYEaQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.4.tgz", + "integrity": "sha512-w+E1P+Ul1PgoAiH22tcONSEyx+3VjUcSIZeqr1QSOSC5vvawduMVtgD1ZtfQsPHkpTN/VJekrgN3JL2+YKhaDQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.4.tgz", + "integrity": "sha512-nukgdVNAx7X07qu8nZjJwuCRW/yDjLIio83yXhKUkuUUXTlmEGjVRN+XxrzxnkhiTRfHnqC/OYAga3t7vMQkAw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.4.tgz", + "integrity": "sha512-o5vn+twqv2XwxEpseC76YCNXpCXoRlPmr+ZYpSnmlxbFh5kdHysap9V93cS1hzAXtK6xuXa5kdtS+/8rkUfs4Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.4.tgz", + "integrity": "sha512-b2w9laiL8oWofYqGF+ABzin9wNMPxzHRD21EIPJ5A0iniq19d3flE4UP7uZKl1gj+d3Kv/bt1htVUSzI0bE1TQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.4.tgz", + "integrity": "sha512-Ao858LxFnvGrn4qbin3rr+LmEhOrF9pQKgzEnT14f9KjOpytd5smOuj7OOtkejJ7YVb5cBdPpYdT1zjwNcNq9g==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.4.tgz", + "integrity": "sha512-B78SoWLJeAleSOIDFZ+twb+7DoBla0g73LrdkxlkNwicAsrLfHeYX+NcPlOmxZ3Z8vKVvj0J/kmIMzEaqbQNGg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.4.tgz", + "integrity": "sha512-IK0JVhVLGer5AlmgU0eMbfuldxO1wNACZBwyq+ot9UW899hhkWPcO3k0eIrNlqmuWrySvMtzr7GK9xkbNekOTQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.4.tgz", + "integrity": "sha512-6MoYXMYy+6eqtVesSNehfsS3LY4A0P8MpHfhcnMkVsWVhaLv0vvuCj2EGkanchIoyHxAmxY+aR3ankaTkokC2A==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.4.tgz", + "integrity": "sha512-mo+MC3fHiG4EOdtp7uGSvBv/4hKpqxhV16QGpXn2D0mTBBiOW6hGIOXUK7nck8THlURRWjYdtUPvvJfxHKZ/2w==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.4.tgz", + "integrity": "sha512-uBRu6ztHsmoW/10bPsOVbhW8ie4Puw6+CQD/XLRGqr3ugv6pRNm3b4vebiwouhCgkjJ/ItJdqHKJ3mVhpr/wQA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.4.tgz", + "integrity": "sha512-XNY+QlYWmhqzeiMdOKjziVnx6aP5cXSxbk4rDqbb+MH2IcNiIZWX1wPRfAVV6ntiM17XHJJ2WUNcxnglDNH69A==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.4.tgz", + "integrity": "sha512-agahuMApMIOQgJMNEaJNtQRD+iUllqAvkF/V7WutWaBLTSeMgFd0urEo6m1scFmG0Cd+2zIPvnu2SWcKeuSB1Q==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.4.tgz", + "integrity": "sha512-1N+ysuGmcw/PAC4E5/vpotbjC7zHBMqOMJ+kdjkuvVGbj4Mkzu1/cNI4IMaU27VP6MWded1fQAU9ME2m/JmiUA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.4.tgz", + "integrity": "sha512-ZO0fVys5Rtut3W0FcpKl/T/CTuTgaujErjanLJHVSmqhWaXnPr1u1VAinHPb8ash+cHA8yMX4QnRbmXhrrXfAg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.4.tgz", + "integrity": "sha512-a4T4Ji3Is/TCh4rUuV6ehDdSMp3hxLH/v7mP4VT0kVB90Hfr9GUHVAiJhiJ3iy+tJ4qpvIG4haP+HpivOyWYpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.4.tgz", + "integrity": "sha512-I4FcDk1+t2w7/JwKakDbhOKvtP07Q8Y/jqaTTdgVklmfqTqmTwtIk254iSP4iCgXgQWThKm8CN67mDzPGDnpqw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.4.tgz", + "integrity": "sha512-kpekXvZs3E/21ps5tUiPbQggi4C8bCx4jBl2eAIaVTerC7eDLWJunZ6nRw3/K4r20E5Z5f1bmbrfSS6H8GRv+A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.4.tgz", + "integrity": "sha512-mrnM4nr22FidljIL4vGK1htFcxPNCjLK/g2LQvgpBbq8pKL/zHY1czntTDbtYjoaYWVFu+XX0P2r2h/7zwWlIw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.4.tgz", + "integrity": "sha512-xKF6HKrBdrb3jpGFlGAGtNF6nMu/TGdnVO38durZTMQUaduIqH/aDIjyi7SXmXNDUXTfTMUEIGVwPQ5FuMhCLQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.4.tgz", + "integrity": "sha512-uu45X0jgiXEab6vcoWuPQLqhBPKUCZkXc+gv0oTI78mhn5DnQC2WGvNJ/s6Cnc68PvB/8vAtlE2dIHrpx/wySw==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.4.tgz", + "integrity": "sha512-+sVn72CSCbAemlPieSHWpBsJR5vkWH/xQM0Px0loHUhscMNl3CuH0UwTHuzCIaamlv+ZTi1V44jEKQ45FUaNwg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.4.tgz", + "integrity": "sha512-/eMzhxPPUGd5vjHdaNtvxHbblmoe+DyvPnJkZ4uQrDlVq9PQSd8br4pWwamycwRcLoNEzXwFy2mzcGoZTYqU5A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@sinclair/typebox": { "version": "0.34.52", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", @@ -2683,7 +3104,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "tslib": "^2.4.0" } @@ -2782,6 +3202,13 @@ "@types/istanbul-lib-report": "*" } }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/mocha": { "version": "10.0.10", "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.10.tgz", @@ -2799,6 +3226,13 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/resolve": { + "version": "1.20.2", + "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz", + "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/stack-utils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", @@ -3278,6 +3712,181 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/@webassemblyjs/ast": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ast/-/ast-1.14.1.tgz", + "integrity": "sha512-nuBEDgQfm1ccRp/8bCQrx1frohyufl4JlbMMZ4P1wpeOfDhF6FQkxZJ1b/e+PLwr6X1Nhw6OLme5usuBWYBvuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/helper-numbers": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2" + } + }, + "node_modules/@webassemblyjs/floating-point-hex-parser": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/floating-point-hex-parser/-/floating-point-hex-parser-1.13.2.tgz", + "integrity": "sha512-6oXyTOzbKxGH4steLbLNOu71Oj+C8Lg34n6CqRvqfS2O71BxY6ByfMDRhBytzknj9yGUPVJ1qIKhRlAwO1AovA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-api-error": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-api-error/-/helper-api-error-1.13.2.tgz", + "integrity": "sha512-U56GMYxy4ZQCbDZd6JuvvNV/WFildOjsaWD3Tzzvmw/mas3cXzRJPMjP83JqEsgSbyrmaGjBfDtV7KDXV9UzFQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-buffer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-buffer/-/helper-buffer-1.14.1.tgz", + "integrity": "sha512-jyH7wtcHiKssDtFPRB+iQdxlDf96m0E39yb0k5uJVhFGleZFoNw1c4aeIcVUPPbXUVJ94wwnMOAqUHyzoEPVMA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-numbers": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-numbers/-/helper-numbers-1.13.2.tgz", + "integrity": "sha512-FE8aCmS5Q6eQYcV3gI35O4J789wlQA+7JrqTTpJqn5emA4U2hvwJmvFRC0HODS+3Ye6WioDklgd6scJ3+PLnEA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/floating-point-hex-parser": "1.13.2", + "@webassemblyjs/helper-api-error": "1.13.2", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/helper-wasm-bytecode": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-bytecode/-/helper-wasm-bytecode-1.13.2.tgz", + "integrity": "sha512-3QbLKy93F0EAIXLh0ogEVR6rOubA9AoZ+WRYhNbFyuB70j3dRdwH9g+qXhLAO0kiYGlg3TxDV+I4rQTr/YNXkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/helper-wasm-section": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/helper-wasm-section/-/helper-wasm-section-1.14.1.tgz", + "integrity": "sha512-ds5mXEqTJ6oxRoqjhWDU83OgzAYjwsCV8Lo/N+oRsNDmx/ZDpqalmrtgOMkHwxsG0iI//3BwWAErYRHtgn0dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/wasm-gen": "1.14.1" + } + }, + "node_modules/@webassemblyjs/ieee754": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/ieee754/-/ieee754-1.13.2.tgz", + "integrity": "sha512-4LtOzh58S/5lX4ITKxnAK2USuNEvpdVV9AlgGQb8rJDHaLeHciwG4zlGr0j/SNWlr7x3vO1lDEsuePvtcDNCkw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@xtuc/ieee754": "^1.2.0" + } + }, + "node_modules/@webassemblyjs/leb128": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/leb128/-/leb128-1.13.2.tgz", + "integrity": "sha512-Lde1oNoIdzVzdkNEAWZ1dZ5orIbff80YPdHx20mrHwHrVNNTjNr8E3xz9BdpcGqRQbAEa+fkrCb+fRFTl/6sQw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@webassemblyjs/utf8": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/@webassemblyjs/utf8/-/utf8-1.13.2.tgz", + "integrity": "sha512-3NQWGjKTASY1xV5m7Hr0iPeXD9+RDobLll3T9d2AO+g3my8xy5peVyjSag4I50mR1bBSN/Ct12lo+R9tJk0NZQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@webassemblyjs/wasm-edit": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-edit/-/wasm-edit-1.14.1.tgz", + "integrity": "sha512-RNJUIQH/J8iA/1NzlE4N7KtyZNHi3w7at7hDjvRNm5rcUXa00z1vRz3glZoULfJ5mpvYhLybmVcwcjGrC1pRrQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/helper-wasm-section": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-opt": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1", + "@webassemblyjs/wast-printer": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-gen": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-gen/-/wasm-gen-1.14.1.tgz", + "integrity": "sha512-AmomSIjP8ZbfGQhumkNvgC33AY7qtMCXnN6bL2u2Js4gVCg8fp735aEiMSBbDR7UQIj90n4wKAFUSEd0QN2Ukg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wasm-opt": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-opt/-/wasm-opt-1.14.1.tgz", + "integrity": "sha512-PTcKLUNvBqnY2U6E5bdOQcSM+oVP/PmrDY9NzowJjislEjwP/C4an2303MCVS2Mg9d3AJpIGdUFIQQWbPds0Sw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-buffer": "1.14.1", + "@webassemblyjs/wasm-gen": "1.14.1", + "@webassemblyjs/wasm-parser": "1.14.1" + } + }, + "node_modules/@webassemblyjs/wasm-parser": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wasm-parser/-/wasm-parser-1.14.1.tgz", + "integrity": "sha512-JLBl+KZ0R5qB7mCnud/yyX08jWFw5MsoalJ1pQ4EdFlgj9VdXKGuENGsiCIjegI1W7p91rUlcB/LB5yRJKNTcQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@webassemblyjs/helper-api-error": "1.13.2", + "@webassemblyjs/helper-wasm-bytecode": "1.13.2", + "@webassemblyjs/ieee754": "1.13.2", + "@webassemblyjs/leb128": "1.13.2", + "@webassemblyjs/utf8": "1.13.2" + } + }, + "node_modules/@webassemblyjs/wast-printer": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@webassemblyjs/wast-printer/-/wast-printer-1.14.1.tgz", + "integrity": "sha512-kPSSXE6De1XOR820C90RIo2ogvZG+c3KiHzqUoO/F34Y2shGzesfqv7o57xrxovZJH/MetF5UjroJ/R/3isoiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@webassemblyjs/ast": "1.14.1", + "@xtuc/long": "4.2.2" + } + }, + "node_modules/@xtuc/ieee754": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@xtuc/ieee754/-/ieee754-1.2.0.tgz", + "integrity": "sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==", + "dev": true, + "license": "BSD-3-Clause" + }, + "node_modules/@xtuc/long": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@xtuc/long/-/long-4.2.2.tgz", + "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/abbrev": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-3.0.1.tgz", @@ -3334,6 +3943,54 @@ "node": ">= 14" } }, + "node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ajv-formats": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^8.0.0" + }, + "peerDependencies": { + "ajv": "^8.0.0" + }, + "peerDependenciesMeta": { + "ajv": { + "optional": true + } + } + }, + "node_modules/ajv-keywords": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-5.1.0.tgz", + "integrity": "sha512-YCS/JNFAUyr5vAuhk1DWm1CBxRHW9LbJ2ozWeemrIqpbsqKjHVxYPyi5GC0rjZIT5JxJ3virVTS8wk4i/Z+krw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3" + }, + "peerDependencies": { + "ajv": "^8.8.2" + } + }, "node_modules/ansi-escapes": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", @@ -3810,6 +4467,13 @@ "node-int64": "^0.4.0" } }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", + "dev": true, + "license": "MIT" + }, "node_modules/callsites": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-4.2.0.tgz", @@ -3926,6 +4590,16 @@ "node": ">=18" } }, + "node_modules/chrome-trace-event": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.4.tgz", + "integrity": "sha512-rNjApaLzuwaOTjCiT8lSDdGN1APCiqkChLMJxJPWLunPAt5fy8xgU9/jNOchV84wfIxrA0lRQB7oCT8jrn/wrQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0" + } + }, "node_modules/chunkd": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/chunkd/-/chunkd-2.0.1.tgz", @@ -4086,12 +4760,26 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, + "node_modules/commander": { + "version": "2.20.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", + "integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==", + "dev": true, + "license": "MIT" + }, "node_modules/common-path-prefix": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/common-path-prefix/-/common-path-prefix-3.0.0.tgz", "integrity": "sha512-QE33hToZseCH3jS0qN96O/bSh3kaw/h+Tq7ngyY9eWDUnTlTNUyqfqvCXioLe5Na5jFsL78ra/wuBU4iuEgd4w==", "dev": true }, + "node_modules/commondir": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz", + "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==", + "dev": true, + "license": "MIT" + }, "node_modules/concordance": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/concordance/-/concordance-5.0.4.tgz", @@ -4282,6 +4970,20 @@ "dev": true, "license": "MIT" }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/error-ex": { "version": "1.3.4", "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", @@ -4292,6 +4994,16 @@ "is-arrayish": "^0.2.1" } }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -4392,6 +5104,16 @@ "node": ">=0.10.0" } }, + "node_modules/events": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", + "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.x" + } + }, "node_modules/execa": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", @@ -4453,6 +5175,13 @@ "node": ">=12.0.0" } }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, "node_modules/fast-diff": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/fast-diff/-/fast-diff-1.3.0.tgz", @@ -4482,6 +5211,23 @@ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", "dev": true }, + "node_modules/fast-uri": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fastq": { "version": "1.20.3", "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", @@ -4625,6 +5371,16 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -4768,6 +5524,19 @@ "node": ">=8" } }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/html-escaper": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", @@ -4876,6 +5645,22 @@ "dev": true, "license": "MIT" }, + "node_modules/is-core-module": { + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -4919,6 +5704,13 @@ "node": ">=0.10.0" } }, + "node_modules/is-module": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz", + "integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==", + "dev": true, + "license": "MIT" + }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -4958,6 +5750,16 @@ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "dev": true }, + "node_modules/is-reference": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-1.2.1.tgz", + "integrity": "sha512-U82MsXXiFIrjCK4otLT+o2NA2Cd2g5MLoOVXUZjIOhLurrRxpEXzI8O0KZHr3IjLvlAH1kTPYSuqer5T9ZVBKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, "node_modules/is-stream": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", @@ -6400,6 +7202,13 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -6428,7 +7237,6 @@ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", - "peer": true, "dependencies": { "detect-libc": "^2.0.3" }, @@ -6466,7 +7274,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6488,7 +7295,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6510,7 +7316,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6532,7 +7337,6 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6554,7 +7358,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6576,7 +7379,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6598,7 +7400,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6620,7 +7421,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6642,7 +7442,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6664,7 +7463,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6686,7 +7484,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -6869,6 +7666,16 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/mimic-function": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", @@ -6908,6 +7715,93 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minimizer-webpack-plugin": { + "version": "5.14.0", + "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.14.0.tgz", + "integrity": "sha512-PnvQXCJxhgH2ZVVO7Lj0sM6q8L1XGxnUvd8wVQIRwi8khMCLq5wg0Ngxe44bcuZL2FSN81RdVE7YHEVzTKsQDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "jest-worker": "^27.4.5", + "schema-utils": "^4.6.0", + "terser": "^5.51.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@minify-html/node": { + "optional": true + }, + "@napi-rs/image": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "@swc/html": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "cssnano": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "html-minifier-terser": { + "optional": true + }, + "imagemin": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "postcss": { + "optional": true + }, + "sharp": { + "optional": true + }, + "svgo": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, + "node_modules/minimizer-webpack-plugin/node_modules/jest-worker": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz", + "integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "merge-stream": "^2.0.0", + "supports-color": "^8.0.0" + }, + "engines": { + "node": ">= 10.13.0" + } + }, "node_modules/minipass": { "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", @@ -7046,7 +7940,6 @@ } ], "license": "MIT", - "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -7368,6 +8261,13 @@ "node": ">=8" } }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, "node_modules/path-scurry": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", @@ -7477,7 +8377,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", @@ -7594,6 +8493,38 @@ "node": ">=0.10.0" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.18.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/resolve-cwd": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", @@ -7632,7 +8563,6 @@ "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" @@ -7662,6 +8592,52 @@ "@rolldown/binding-win32-x64-msvc": "1.2.19" } }, + "node_modules/rollup": { + "version": "4.68.4", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.4.tgz", + "integrity": "sha512-5acdO1/M9urvHQuZVkoOt8JWQH6XxCnFnox1qodE39qkXaML67S2E7MhHDgx3pQYycM1A5dRJwahYMDLO9a3Yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.4", + "@rollup/rollup-android-arm64": "4.68.4", + "@rollup/rollup-android-x64": "4.68.4", + "@rollup/rollup-darwin-arm64": "4.68.4", + "@rollup/rollup-darwin-x64": "4.68.4", + "@rollup/rollup-freebsd-arm64": "4.68.4", + "@rollup/rollup-freebsd-x64": "4.68.4", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.4", + "@rollup/rollup-linux-arm-musleabihf": "4.68.4", + "@rollup/rollup-linux-arm64-gnu": "4.68.4", + "@rollup/rollup-linux-arm64-musl": "4.68.4", + "@rollup/rollup-linux-loong64-gnu": "4.68.4", + "@rollup/rollup-linux-loong64-musl": "4.68.4", + "@rollup/rollup-linux-ppc64-gnu": "4.68.4", + "@rollup/rollup-linux-ppc64-musl": "4.68.4", + "@rollup/rollup-linux-riscv64-gnu": "4.68.4", + "@rollup/rollup-linux-riscv64-musl": "4.68.4", + "@rollup/rollup-linux-s390x-gnu": "4.68.4", + "@rollup/rollup-linux-x64-gnu": "4.68.4", + "@rollup/rollup-linux-x64-musl": "4.68.4", + "@rollup/rollup-openbsd-x64": "4.68.4", + "@rollup/rollup-openharmony-arm64": "4.68.4", + "@rollup/rollup-win32-arm64-msvc": "4.68.4", + "@rollup/rollup-win32-ia32-msvc": "4.68.4", + "@rollup/rollup-win32-x64-gnu": "4.68.4", + "@rollup/rollup-win32-x64-msvc": "4.68.4", + "fsevents": "~2.3.2" + } + }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -7686,6 +8662,37 @@ "queue-microtask": "^1.2.2" } }, + "node_modules/schema-utils": { + "version": "4.8.3", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.8.3.tgz", + "integrity": "sha512-qIfo3f+lRNqnMPgpXSKvUhsT3pY5U+ppmgGr4j8LanFP3W/Ze+xj8DY/dPb5qVu3m6qFIMyMWKVRLNKxrNhxWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", + "ajv-keywords": "^5.1.0" + }, + "bin": { + "schema-utils": "bin/schema-utils.js" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.0.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + } + } + }, "node_modules/semver": { "version": "7.8.6", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", @@ -7809,11 +8816,21 @@ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", - "peer": true, "engines": { "node": ">=0.10.0" } }, + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, "node_modules/sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -8064,6 +9081,19 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/synckit": { "version": "0.11.13", "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz", @@ -8080,6 +9110,20 @@ "url": "https://opencollective.com/synckit" } }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, "node_modules/tar": { "version": "7.5.23", "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.23.tgz", @@ -8116,6 +9160,25 @@ "node": ">=14.16" } }, + "node_modules/terser": { + "version": "5.51.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", + "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@jridgewell/source-map": "^0.3.3", + "acorn": "^8.15.0", + "commander": "^2.20.0", + "source-map-support": "~0.5.20" + }, + "bin": { + "terser": "bin/terser" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/test-exclude": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz", @@ -8348,8 +9411,7 @@ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "dev": true, "license": "0BSD", - "optional": true, - "peer": true + "optional": true }, "node_modules/tsx": { "version": "4.23.15", @@ -8528,7 +9590,6 @@ "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", @@ -8684,6 +9745,19 @@ } } }, + "node_modules/watchpack": { + "version": "2.6.4", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.6.4.tgz", + "integrity": "sha512-5H3Tce2GfzWbcr9VnSqyak2whFaONw4BdmI5BDnMXold4qSlCFd64XaMQESRh2vkDKmdUkv6rUo17UvZ9f9nXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.2" + }, + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", @@ -8691,6 +9765,57 @@ "dev": true, "license": "BSD-2-Clause" }, + "node_modules/webpack": { + "version": "5.112.2", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.112.2.tgz", + "integrity": "sha512-B2tp1LI9D8GVpPDqprdt12ukTkXXahj9MzqSWJq4faSPgOUM7CdZaGAB6HrL/8E6UwbBpdj4vzWDbKoFnVoU6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.8", + "@types/json-schema": "^7.0.15", + "@webassemblyjs/ast": "^1.14.1", + "@webassemblyjs/wasm-edit": "^1.14.1", + "@webassemblyjs/wasm-parser": "^1.14.1", + "browserslist": "^4.28.1", + "chrome-trace-event": "^1.0.2", + "enhanced-resolve": "^5.26.0", + "es-module-lexer": "^2.1.0", + "events": "^3.2.0", + "graceful-fs": "^4.2.11", + "mime-db": "^1.54.0", + "minimizer-webpack-plugin": "^5.13.0", + "schema-utils": "^4.8.1", + "tapable": "^2.3.0", + "watchpack": "^2.6.3", + "webpack-sources": "^3.6.0" + }, + "bin": { + "webpack": "bin/webpack.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependenciesMeta": { + "webpack-cli": { + "optional": true + } + } + }, + "node_modules/webpack-sources": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.7.0.tgz", + "integrity": "sha512-PdUhbCycwEgiS1hB/FBDksWKg/ashAIuJKqwdbPn8/dFVgU5LxQiBvG0js6VRRIzPujMrStYCczywp82P0KWng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/well-known-symbols": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/well-known-symbols/-/well-known-symbols-2.0.0.tgz", diff --git a/compatibility-checks/package.json b/compatibility-checks/package.json index 075dfd1..8dee019 100644 --- a/compatibility-checks/package.json +++ b/compatibility-checks/package.json @@ -22,20 +22,27 @@ "validate:mocha": "mocha --require tsx/cjs test-runners/mocha/**.ts", "validate:nodejs": "node --require tsx/cjs --test ./test-runners/nodejs/*.ts", "validate:vitest": "vitest run ./test-runners/vitest/*.ts", + "validate:vitest-inline": "vitest run --config vitest.inline.config.mts ./test-runners/vitest-inline/index.spec.ts", "pretest": "npm run install:local", - "test": "node --require tsx/cjs --test test/index.ts" + "test": "node --require tsx/cjs --test test/index.ts test/bundlers.ts" }, "devDependencies": { + "@rollup/plugin-commonjs": "^29.0.3", + "@rollup/plugin-node-resolve": "^16.0.3", "@types/mocha": "^10.0.10", "@types/node": "^22.20.5", "ansi-regex": "^6.0.1", "ava": "^6.4.1", + "esbuild": "^0.28.2", "jest": "^30.5.2", "mocha": "^12.0.3", + "rollup": "^4.68.4", "ts-jest": "^29.4.15", "tsx": "^4.23.15", "typescript": "^5.9.3", - "vitest": "^5.1.0" + "vite": "^8.3.8", + "vitest": "^5.1.0", + "webpack": "^5.112.2" }, "volta": { "node": "24.22.3" diff --git a/compatibility-checks/test-runners/vitest-inline/exports.test.ts b/compatibility-checks/test-runners/vitest-inline/exports.test.ts new file mode 100644 index 0000000..9743df3 --- /dev/null +++ b/compatibility-checks/test-runners/vitest-inline/exports.test.ts @@ -0,0 +1,25 @@ +import { createRequire } from 'node:module' +import { expect, test } from 'vitest' +import Substitute, { Arg, Substitute as NamedSubstitute, SubstituteException, received } from '@fluffy-spoon/substitute' +import * as namespace from '@fluffy-spoon/substitute' + +// F1: run by test/bundlers.ts with vitest.inline.config.mts, and expected to pass. +const exportNames = Object.keys(createRequire(__filename)('@fluffy-spoon/substitute')).sort() + +test('F1 default, named and namespace imports are the real exports when vitest inlines the package', () => { + expect(typeof Substitute.for).toBe('function') + expect(Substitute).toBe(NamedSubstitute) + expect(typeof Arg.any).toBe('function') + expect(typeof received).toBe('symbol') + expect(typeof SubstituteException).toBe('function') + expect(Object.keys(namespace).sort()).toEqual(exportNames) + expect(Object.keys(namespace).filter(name => (namespace as Record)[name] === undefined)).toEqual([]) +}) + +test('F1 the inlined package works', () => { + const calculator = Substitute.for<{ add(a: number, b: number): number }>() + calculator.add(1, Arg.any()).returns(3) + expect(calculator.add(1, 2)).toBe(3) + calculator[received](1).add(1, 2) + expect(() => calculator.received(2).add(1, 2)).toThrow(SubstituteException) +}) diff --git a/compatibility-checks/test-runners/vitest-inline/index.spec.ts b/compatibility-checks/test-runners/vitest-inline/index.spec.ts new file mode 100644 index 0000000..17bac6c --- /dev/null +++ b/compatibility-checks/test-runners/vitest-inline/index.spec.ts @@ -0,0 +1,7 @@ +import { test } from 'vitest' +import { ambiguousPropertyTypeAssertion } from '../_common' + +// The shared scenario, with the package inlined by vitest (vitest.inline.config.mts). +test('can substitute callable interfaces', () => { + ambiguousPropertyTypeAssertion() +}) diff --git a/compatibility-checks/test/bundlers.ts b/compatibility-checks/test/bundlers.ts new file mode 100644 index 0000000..8332aaa --- /dev/null +++ b/compatibility-checks/test/bundlers.ts @@ -0,0 +1,153 @@ +// F1: the package's ES module entry (dist/index.mjs) wraps its CommonJS build. Bundlers and test runners that +// transform the package themselves turn that CommonJS build into an ES module in different ways (the __esModule +// interop), and once got only undefined exports. These checks bundle bundlers/entry.mjs with each of them, run the +// bundle with Node.js and check that the default, named and namespace imports are the real exports. +// +// Like test/index.ts, they run against the packed package that `npm run install:local` installed. +import * as test from 'node:test' +import * as assert from 'node:assert' +import { execFile } from 'node:child_process' +import * as fs from 'node:fs' +import { builtinModules } from 'node:module' +import * as os from 'node:os' +import * as path from 'node:path' +import commonjs from '@rollup/plugin-commonjs' +import { nodeResolve } from '@rollup/plugin-node-resolve' +import * as esbuild from 'esbuild' +import { rollup } from 'rollup' +import webpack from 'webpack' +import { testRunnerEnvironment } from './environment' + +const here = path.resolve(__dirname, '..') +const entry = path.join(here, 'bundlers', 'entry.mjs') +const exportNames = Object.keys(require('@fluffy-spoon/substitute')).sort() +const nodeBuiltins = [...builtinModules, ...builtinModules.map(name => `node:${name}`)] + +const run = (command: string, args: string[], cwd: string) => new Promise<{ status: number, output: string }>(resolve => { + execFile(command, args, { cwd, encoding: 'utf8', env: testRunnerEnvironment() }, (error, stdout, stderr) => { + resolve({ status: error ? (typeof error.code === 'number' ? error.code : 1) : 0, output: stdout + stderr }) + }) +}) + +type Bundler = { + name: string + /** Bundles `entry` into `outDir` and returns the path of the bundle. */ + bundle: (outDir: string) => Promise +} + +const bundlers: Bundler[] = [ + { + name: 'rollup with @rollup/plugin-commonjs', + bundle: async outDir => { + const file = path.join(outDir, 'rollup.mjs') + const build = await rollup({ + input: entry, + external: nodeBuiltins, + onwarn: warning => { throw new Error(`rollup warning: ${warning.message}`) }, + plugins: [nodeResolve({ preferBuiltins: true }), commonjs()] + }) + await build.write({ file, format: 'es' }) + await build.close() + return file + } + }, + { + name: 'webpack', + bundle: outDir => new Promise((resolve, reject) => { + webpack({ + mode: 'none', + target: 'node', + context: here, + entry, + output: { path: outDir, filename: 'webpack.cjs' } + }, (error, stats) => { + if (error) return reject(error) + if (stats === undefined || stats.hasErrors() || stats.hasWarnings()) { + return reject(new Error(`webpack: ${stats && stats.toString('errors-warnings')}`)) + } + resolve(path.join(outDir, 'webpack.cjs')) + }) + }) + }, + { + name: 'esbuild (CommonJS output)', + bundle: async outDir => { + const outfile = path.join(outDir, 'esbuild.cjs') + await esbuild.build({ entryPoints: [entry], bundle: true, platform: 'node', format: 'cjs', outfile, logLevel: 'silent' }) + return outfile + } + }, + { + name: 'esbuild (ES module output)', + bundle: async outDir => { + const outfile = path.join(outDir, 'esbuild.mjs') + await esbuild.build({ + entryPoints: [entry], + bundle: true, + platform: 'node', + format: 'esm', + outfile, + logLevel: 'silent', + // esbuild's ES module output cannot require() Node.js built-ins (the library requires 'util') without this. + banner: { js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);" } + }) + return outfile + } + }, + { + name: 'Vite SSR build with ssr.noExternal', + bundle: async outDir => { + const { build } = await import('vite') + await build({ + configFile: false, + root: here, + logLevel: 'silent', + ssr: { noExternal: true }, + build: { ssr: entry, outDir, emptyOutDir: false, write: true } + }) + const [file] = fs.readdirSync(outDir).filter(name => /^entry\.m?js$/.test(name)) + assert.ok(file, `vite wrote ${fs.readdirSync(outDir).join(', ')}`) + return path.join(outDir, file) + } + } +] + +test.describe('F1 bundled ES module imports are the real exports', () => { + const outDirs: string[] = [] + test.after(() => { + for (const outDir of outDirs) fs.rmSync(outDir, { recursive: true, force: true }) + }) + + for (const bundler of bundlers) { + test.it(`F1 ${bundler.name}: default, named and namespace imports are the real exports`, async () => { + const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'substitute-bundle-')) + outDirs.push(outDir) + const bundle = await bundler.bundle(outDir) + const result = await run(process.execPath, [bundle], outDir) + assert.strictEqual(result.status, 0, result.output) + const report = JSON.parse(result.output.trim().split('\n').pop() as string) + assert.deepStrictEqual(report, { + defaultImport: 'function', + defaultIsNamedSubstitute: true, + namespaceDefaultIsSubstitute: true, + arg: 'object', + received: 'symbol', + substituteException: 'function', + namespaceKeys: exportNames, + undefinedNamespaceValues: [], + returns: 3, + failingAssertion: 'SubstituteException' + }, `${bundler.name}: ${result.output}`) + }) + } + + test.it('F1 vitest with server.deps.inline: default, named and namespace imports are the real exports', async () => { + const vitestPackage = require.resolve('vitest/package.json', { paths: [here] }) + const vitest = path.join(path.dirname(vitestPackage), require(vitestPackage).bin.vitest) + const result = await run(process.execPath, [ + vitest, 'run', '--config', 'vitest.inline.config.mts', 'test-runners/vitest-inline/exports.test.ts' + ], here) + assert.strictEqual(result.status, 0, result.output) + assert.match(result.output, /Tests\s+2 passed/, result.output) + }) +}) diff --git a/compatibility-checks/test/index.ts b/compatibility-checks/test/index.ts index 54476e2..0a0851b 100644 --- a/compatibility-checks/test/index.ts +++ b/compatibility-checks/test/index.ts @@ -32,7 +32,9 @@ test.describe('Verifies test runner compatibility', () => { { name: 'mocha', failureAcknowledgementTexts: ['1 failing'], failureLocationText: 'can substitute callable interfaces:' }, // G:CI-2: this check used to pass vacuously or fail, because the nested `node --test` inherited NODE_TEST_CONTEXT. { name: 'nodejs', failureAcknowledgementTexts: ['fail 1'], failureLocationText: 'test-runners/nodejs/index.ts' }, - { name: 'vitest', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest/index.spec.ts' } + { name: 'vitest', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest/index.spec.ts' }, + // F1: vitest with the package inlined (vitest.inline.config.mts), so that Vite, not Node.js, loads its ES module entry. + { name: 'vitest-inline', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest-inline/index.spec.ts' } ] testRunners.forEach(testRunner => { diff --git a/compatibility-checks/vitest.inline.config.mts b/compatibility-checks/vitest.inline.config.mts new file mode 100644 index 0000000..2232847 --- /dev/null +++ b/compatibility-checks/vitest.inline.config.mts @@ -0,0 +1,15 @@ +import { defineConfig } from 'vitest/config' + +// F1: with inlined dependencies, vitest transforms @fluffy-spoon/substitute itself instead of letting Node.js load it. +// Vite then applies the __esModule interop to the CommonJS build that the package's ES module entry wraps, which +// once made every export of the package undefined. `server.deps.inline: true` and `ssr.noExternal` behave the same. +// Used by `npm run validate:vitest-inline` and by test/bundlers.ts. +export default defineConfig({ + test: { + server: { + deps: { + inline: ['@fluffy-spoon/substitute'] + } + } + } +}) diff --git a/packaging/build-esm.js b/packaging/build-esm.js index ebbba63..aa20d05 100644 --- a/packaging/build-esm.js +++ b/packaging/build-esm.js @@ -9,6 +9,15 @@ // `export const` bindings (instead of `export * from './index.js'`) also work on Node versions that // cannot detect the named exports of a CommonJS module. // +// The wrapper must not depend on how the importer turns a CommonJS module into an ES module (F1). dist/index.js +// sets `__esModule` and `exports.default`, and tools disagree about what `import cjs from './index.js'` then is: +// - Node.js, webpack, esbuild and Rolldown (Vite 8 builds) give module.exports, which has every export; +// - Rollup's commonjs plugin, Vite SSR and vitest with inlined dependencies (server.deps.inline, ssr.noExternal) +// apply the __esModule interop and give exports.default, the Substitute class. Their namespace import +// (`import * as`) has the named exports instead. +// So the wrapper imports both, uses whichever one is the complete exports object, and fails loudly at import +// time if neither is (instead of exporting undefined values). +// // Runs as part of `npm run build`, after tsc. const fs = require('fs') @@ -36,10 +45,23 @@ if (defaultName === undefined) { } const header = '// Generated by packaging/build-esm.js during `npm run build`. Do not edit.' +const packageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, '..', 'package.json'), 'utf8')) +const bugsUrl = packageJson.bugs && packageJson.bugs.url +if (typeof bugsUrl !== 'string') throw new Error('package.json has no bugs.url') +const interopFailure = `${packageJson.name}: the ES module entry could not read the exports of its CommonJS build (dist/index.js). ` + + `Please report this at ${bugsUrl} and name the bundler or test runner you use. As a workaround, load the package with require().` const mjs = [ header, - "import cjs from './index.js';", + "import cjsDefault, * as cjsNamespace from './index.js';", + '', + '// The complete exports of dist/index.js: its default export is also its named export ' + JSON.stringify(defaultName) + '.', + `const isCompleteExports = value => value != null && value.${defaultName} !== undefined && value.default === value.${defaultName};`, + '// Node.js and most bundlers give module.exports as the default import; tools that apply the __esModule interop', + '// give exports.default instead, and the named exports through the namespace. See packaging/build-esm.js.', + 'const cjs = isCompleteExports(cjsDefault) ? cjsDefault : isCompleteExports(cjsNamespace) ? cjsNamespace : undefined;', + `if (cjs === undefined) throw new Error(${JSON.stringify(interopFailure)});`, + '', ...names.map(name => `export const ${name} = cjs.${name};`), 'export default cjs.default;', '' diff --git a/packaging/package.test.js b/packaging/package.test.js index 233c25d..2357b69 100644 --- a/packaging/package.test.js +++ b/packaging/package.test.js @@ -74,6 +74,72 @@ test('DOCS:ESM CommonJS require, deep imports and package.json still work with t t.regex(runNode(state.consumer, ['deep-imports.mjs']), /ESM deep import smoke test passed/) }) +// F1: tools that bundle or transform the package turn dist/index.js (CommonJS, with __esModule and exports.default) +// into an ES module in different ways. Each shape below is what one family of tools makes of it for the +// `import ... from './index.js'` in dist/index.mjs. compatibility-checks/test/bundlers.ts checks the real tools. +const commonJsViews = [ + { name: 'Node.js 12.17 to 14.12 (module.exports, no named exports)', defaultExport: 'real', namedExports: false }, + { name: 'Node.js 14.13+, webpack, esbuild and Rolldown (module.exports and the named exports)', defaultExport: 'real', namedExports: true }, + { name: 'the __esModule interop of Rollup\'s commonjs plugin, Vite SSR and vitest inlining (exports.default and the named exports)', defaultExport: 'real.default', namedExports: true } +] + +const simulateCommonJsView = (directory, cjsEntry, names, { defaultExport, namedExports }) => { + fs.mkdirSync(directory) + fs.writeFileSync(path.join(directory, 'package.json'), JSON.stringify({ type: 'module' })) + fs.copyFileSync(path.join(state.consumer, 'node_modules', '@fluffy-spoon', 'substitute', 'dist', 'index.mjs'), path.join(directory, 'index.mjs')) + fs.writeFileSync(path.join(directory, 'index.js'), [ + "import { createRequire } from 'module'", + `const real = createRequire(import.meta.url)(${JSON.stringify(cjsEntry)})`, + `export default ${defaultExport}`, + ...(namedExports ? names.filter(name => name !== 'default').map(name => `export const ${name} = real.${name}`) : []), + '' + ].join('\n')) + fs.writeFileSync(path.join(directory, 'check.mjs'), [ + "import assert from 'assert'", + "import { createRequire } from 'module'", + "import Substitute, * as namespace from './index.mjs'", + `const real = createRequire(import.meta.url)(${JSON.stringify(cjsEntry)})`, + "assert.strictEqual(Substitute, real.default, 'the default import is the Substitute class')", + "assert.deepStrictEqual(Object.keys(namespace).sort(), Object.keys(real).sort(), 'the same export names')", + "for (const name of Object.keys(real)) assert.strictEqual(namespace[name], real[name], name)", + "console.log('ok')", + '' + ].join('\n')) +} + +test('F1 the ES module entry gives the real exports whichever CommonJS interop the importer applies', t => { + const cjsEntry = path.join(state.consumer, 'node_modules', '@fluffy-spoon', 'substitute', 'dist', 'index.js') + const names = Object.keys(require(cjsEntry)) + commonJsViews.forEach((view, index) => { + const directory = path.join(state.consumer, `interop-${index}`) + simulateCommonJsView(directory, cjsEntry, names, view) + const result = spawnSync(process.execPath, ['check.mjs'], { cwd: directory, encoding: 'utf8', env: childEnvironment() }) + t.is(result.status, 0, `${view.name}: ${result.stdout}${result.stderr}`) + }) + + // A view that has neither shape fails loudly at import time instead of exporting undefined values. + const directory = path.join(state.consumer, 'interop-unusable') + simulateCommonJsView(directory, cjsEntry, names, { defaultExport: '{}', namedExports: false }) + const result = spawnSync(process.execPath, ['check.mjs'], { cwd: directory, encoding: 'utf8', env: childEnvironment() }) + t.not(result.status, 0) + t.regex(result.stderr, /could not read the exports of its CommonJS build/) +}) + +test('F1 the compatibility checks bundle the packed package and run vitest with the package inlined', t => { + const compatibility = JSON.parse(fs.readFileSync(path.join(root, 'compatibility-checks', 'package.json'), 'utf8')) + t.regex(compatibility.scripts.test, /\btest\/bundlers\.ts\b/, 'npm test in compatibility-checks runs test/bundlers.ts') + for (const dependency of ['rollup', '@rollup/plugin-commonjs', '@rollup/plugin-node-resolve', 'webpack', 'esbuild', 'vite', 'vitest']) { + t.truthy(compatibility.devDependencies[dependency], `compatibility-checks depends on ${dependency}`) + } + const bundlers = fs.readFileSync(path.join(root, 'compatibility-checks', 'test', 'bundlers.ts'), 'utf8') + t.regex(bundlers, /commonjs\(\)/, 'a bundle is built with @rollup/plugin-commonjs') + t.regex(bundlers, /vitest\.inline\.config\.mts/, 'vitest runs with the inline config') + const inlineConfig = fs.readFileSync(path.join(root, 'compatibility-checks', 'vitest.inline.config.mts'), 'utf8') + t.regex(inlineConfig, /inline:\s*\['@fluffy-spoon\/substitute'\]/) + t.regex(compatibility.scripts['validate:vitest-inline'], /--config vitest\.inline\.config\.mts/) + t.regex(fs.readFileSync(path.join(root, 'compatibility-checks', 'test', 'index.ts'), 'utf8'), /name: 'vitest-inline'/) +}) + const typeScriptConsumer = [ "import Substitute, { Arg, Substitute as Named } from '@fluffy-spoon/substitute'", "import { Arg as DeepArg } from '@fluffy-spoon/substitute/dist/api/Arg'", From 88bc60d147b8d5321fdcbdf71748544bc1e6ac2c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:56:24 +0000 Subject: [PATCH 051/106] fix(packaging): give exports["."] a CommonJS fallback for Node.js 13.0/13.1 (F2) Node.js 13.0 and 13.1 read "exports" but not conditions, so require() of the package failed there although engines.node is >=10. exports["."] is now [conditions, "./dist/index.js"]: everything that understands conditions still uses them, and those two versions take the CommonJS entry. engines.node stays >=10. The minimum-node CI job now also smoke-tests the packed package on 13.0.0 (require) and on 13.7.0 (require and import, the oldest 13.x with the import condition). A packaging test checks the fallback and those CI steps. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .github/workflows/nodejs.yml | 25 +++++++++++++++++++++++++ CONTRIBUTING.md | 17 +++++++++++++---- package.json | 21 ++++++++++++--------- packaging/package.test.js | 23 +++++++++++++++++++++++ packaging/smoke/deep-imports.js | 3 ++- 5 files changed, 75 insertions(+), 14 deletions(-) diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index bbb028a..e156f25 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -16,6 +16,12 @@ env: MINIMUM_NODE_VERSION: '10.0.0' # The oldest Node.js version with native ES module support, for the ESM entry point (dist/index.mjs). MINIMUM_ESM_NODE_VERSION: '12.17.0' + # F2: Node.js 13.0 and 13.1 read "exports" but not its conditions. They load the package through the array fallback + # in exports["."] (the CommonJS entry); without it, require() fails there. + EXPORTS_FALLBACK_NODE_VERSION: '13.0.0' + # Node.js 13.2 to 13.6 have ES modules but not the "import" condition, so 13.7 is the oldest 13.x release on which + # the ES module entry works. + MINIMUM_ESM_NODE_13_VERSION: '13.7.0' jobs: test: @@ -119,3 +125,22 @@ jobs: node --version node require.js node import.mjs + - name: Use Node.js ${{ env.EXPORTS_FALLBACK_NODE_VERSION }} + uses: actions/setup-node@v5 + with: + node-version: ${{ env.EXPORTS_FALLBACK_NODE_VERSION }} + - name: CommonJS smoke test on Node ${{ env.EXPORTS_FALLBACK_NODE_VERSION }} (exports without conditions) + working-directory: ${{ runner.temp }}/consumer + run: | + node --version + node require.js + - name: Use Node.js ${{ env.MINIMUM_ESM_NODE_13_VERSION }} + uses: actions/setup-node@v5 + with: + node-version: ${{ env.MINIMUM_ESM_NODE_13_VERSION }} + - name: CommonJS and ES module smoke test on Node ${{ env.MINIMUM_ESM_NODE_13_VERSION }} + working-directory: ${{ runner.temp }}/consumer + run: | + node --version + node require.js + node import.mjs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c09ee4e..b5e4dda 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,7 +52,14 @@ This compiles `src/` into `dist/` with `tsc` (CommonJS plus `.d.ts` typings) and - `dist/index.d.mts` holds the matching typings for TypeScript's `node16`, `nodenext` and `bundler` resolution. The `exports` map in `package.json` sends `import` to the ES module entry and everything else (`require`, older -resolvers) to the CommonJS entry. `main` and `types` are kept for resolvers that do not read `exports`. Deep +resolvers) to the CommonJS entry. `exports["."]` is an array: the conditions object comes first, and the plain +CommonJS entry `./dist/index.js` follows as a fallback for Node.js 13.0 and 13.1, which read `exports` but do not +understand conditions (without the fallback, `require` fails there). `main` and `types` are kept for resolvers that +do not read `exports`. + +The package supports Node.js 10 and newer with `require`. The ES module entry needs Node.js 12.17 or newer on 12.x, +or 13.7 or newer (13.2 to 13.6 have ES modules but not the `import` condition, so `import` gets the CommonJS entry +and named imports fail there). Deep imports of compiled files (`@fluffy-spoon/substitute/dist/...`, with or without `.js`) stay available through the `./dist/*` subpaths, but they are not public API. @@ -127,9 +134,11 @@ To try a single runner by hand after `npm run install:local`, use `npm run valid Node.js LTS line (22, 24 and 26). - **compatibility**: the compatibility checks against the packed package on the same Node.js versions. - **minimum-node**: packs the package and smoke-tests it (`packaging/smoke/`) on the oldest supported Node.js - version (`MINIMUM_NODE_VERSION`, which must equal `engines.node`) and on the oldest version with native ES - modules (`MINIMUM_ESM_NODE_VERSION`). If a change needs a newer Node.js, raise `engines.node` and - `MINIMUM_NODE_VERSION` together; a packaging test checks that they match. + version (`MINIMUM_NODE_VERSION`, which must equal `engines.node`), on the oldest version with native ES + modules (`MINIMUM_ESM_NODE_VERSION`, 12.17.0), on 13.0.0 (`EXPORTS_FALLBACK_NODE_VERSION`, which only loads the + package through the `exports["."]` fallback) and on 13.7.0 (`MINIMUM_ESM_NODE_13_VERSION`, the oldest 13.x with + the `import` condition). If a change needs a newer Node.js, raise `engines.node` and `MINIMUM_NODE_VERSION` + together; a packaging test checks that they match. `.github/workflows/codeql-analysis.yml` runs CodeQL on pushes and pull requests to `master` and weekly. diff --git a/package.json b/package.json index d0dccf4..d353fdd 100644 --- a/package.json +++ b/package.json @@ -45,16 +45,19 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "exports": { - ".": { - "import": { - "types": "./dist/index.d.mts", - "default": "./dist/index.mjs" + ".": [ + { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "default": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } }, - "default": { - "types": "./dist/index.d.ts", - "default": "./dist/index.js" - } - }, + "./dist/index.js" + ], "./package.json": "./package.json", "./dist/*.js": "./dist/*.js", "./dist/*.mjs": "./dist/*.mjs", diff --git a/packaging/package.test.js b/packaging/package.test.js index 2357b69..ad2aae5 100644 --- a/packaging/package.test.js +++ b/packaging/package.test.js @@ -198,6 +198,29 @@ test('G:PK-2 engines.node is the minimum Node version that CI smoke-tests the pa t.regex(ciWorkflow, /node\s+require\.js/, 'that job runs the CommonJS smoke test') }) +test('F2 exports["."] falls back to the CommonJS entry for Node.js versions without conditional exports (13.0, 13.1)', t => { + const entry = packageJson.exports['.'] + t.true(Array.isArray(entry), 'exports["."] is a fallback array') + t.is(entry.length, 2) + const [conditions, fallback] = entry + t.deepEqual(conditions, { + import: { types: './dist/index.d.mts', default: './dist/index.mjs' }, + default: { types: './dist/index.d.ts', default: './dist/index.js' } + }, 'the conditions come first, so every Node.js version and tool that understands them uses them') + t.is(fallback, packageJson.main, 'the fallback is the CommonJS entry') + t.is(packageJson.engines.node, '>=10', 'engines.node stays >=10') + + // The packed package resolves like before on this Node.js version. + const resolved = runNode(state.consumer, ['-p', "require.resolve('@fluffy-spoon/substitute')"]).trim() + t.is(resolved, path.join(state.consumer, 'node_modules', '@fluffy-spoon', 'substitute', 'dist', 'index.js')) + + // CI smoke-tests the fallback on Node.js 13.0.0, and the ES module entry on 13.7.0, the oldest 13.x it supports. + t.regex(ciWorkflow, /EXPORTS_FALLBACK_NODE_VERSION:\s*'13\.0\.0'/) + t.regex(ciWorkflow, /MINIMUM_ESM_NODE_13_VERSION:\s*'13\.7\.0'/) + t.regex(ciWorkflow, /node-version:\s*\$\{\{\s*env\.EXPORTS_FALLBACK_NODE_VERSION\s*\}\}[\s\S]*?node require\.js/) + t.regex(ciWorkflow, /node-version:\s*\$\{\{\s*env\.MINIMUM_ESM_NODE_13_VERSION\s*\}\}[\s\S]*?node require\.js\s*\n\s*node import\.mjs/) +}) + test('G:CI-1 the release workflow only publishes to registries it can authenticate against', t => { const owner = /github\.com\/([^/]+)\//.exec(packageJson.repository.url)[1].toLowerCase() const scope = packageJson.name.split('/')[0] diff --git a/packaging/smoke/deep-imports.js b/packaging/smoke/deep-imports.js index 3cc5920..6562e3e 100644 --- a/packaging/smoke/deep-imports.js +++ b/packaging/smoke/deep-imports.js @@ -1,6 +1,7 @@ 'use strict' // Deep imports of compiled files under dist/ are not public API, but the "exports" map keeps them working -// (Node versions with subpath pattern trailer support, i.e. 14.19+ and 16.10+, and versions without "exports" support). +// (Node versions with subpath pattern trailer support, i.e. 14.19+ and 16.9+, and versions without "exports" support, +// i.e. older than 12.17; on 12.17 to 12.22, all of 13.x, 14.0 to 14.18 and 16.0 to 16.8 they fail). // Run from a directory whose node_modules contains the extracted package tarball: // node deep-imports.js var assert = require('assert') From a227cbec64dd721e6cb1000c7d65058a6ea05c9f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 13:57:33 +0000 Subject: [PATCH 052/106] ci: check the oldest supported TypeScript in CI and document every check (F4, TD-12) The README promises TypeScript 3.6 or newer, but no workflow ran test:types:min-ts. A new types-min-ts job runs it on the development Node.js version; the publish workflow runs the whole CI workflow, so it gates releases too. CONTRIBUTING.md now lists spec-types/ and spec-docs/ in the project layout, explains how to run test:types:min-ts and test:docs locally (pointing to spec-docs/README.md), lists test:docs in the test job and describes the new job. Packaging tests keep the job and the documentation in step with the workflow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .github/workflows/nodejs.yml | 20 +++++++++++++++ CONTRIBUTING.md | 49 ++++++++++++++++++++++++++++++------ packaging/package.test.js | 37 +++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index e156f25..602962c 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -53,6 +53,26 @@ jobs: - name: Check the code examples in the documentation run: npm run test:docs + # F4: README, MIGRATION and CHANGELOG promise TypeScript 3.6 or newer. Type-checks the built typings with exactly that + # version (spec-types/min-ts/check.js installs it on the fly with npx), so a .d.ts change that needs newer + # TypeScript fails CI and is never published. + types-min-ts: + name: Typings on the oldest supported TypeScript + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + show-progress: false + - name: Use the development Node.js version + uses: actions/setup-node@v5 + with: + node-version-file: package.json + cache: npm + - name: Install dependencies + run: npm ci + - name: Build and type-check the typings with the oldest supported TypeScript + run: npm run test:types:min-ts + compatibility: name: Test runner compatibility on Node ${{ matrix.node-version }} runs-on: ubuntu-latest diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b5e4dda..2e675f0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,6 +28,8 @@ npm ci | --- | --- | | `src/` | The library source (TypeScript). `src/index.ts` is the public entry point. | | `spec/` | The runtime specs, run with [ava](https://github.com/avajs/ava). | +| `spec-types/` | Type-level tests of the public typings (`npm run test:types`), and `spec-types/min-ts/`, which checks the built typings with the oldest supported TypeScript (`npm run test:types:min-ts`). | +| `spec-docs/` | The documentation check (`npm run test:docs`): it type-checks and runs the code examples of the README, MIGRATION and CHANGELOG. See [spec-docs/README.md](spec-docs/README.md). | | `packaging/` | Packaging checks (run as part of `npm test`), the ES module wrapper generator and the smoke tests. | | `compatibility-checks/` | A separate npm project that checks the packed package with ava, jest, mocha, node:test and vitest, and bundles it with Rollup, webpack, esbuild and Vite. | | `dist/` | Build output that gets published (generated, not committed). | @@ -59,9 +61,12 @@ do not read `exports`. The package supports Node.js 10 and newer with `require`. The ES module entry needs Node.js 12.17 or newer on 12.x, or 13.7 or newer (13.2 to 13.6 have ES modules but not the `import` condition, so `import` gets the CommonJS entry -and named imports fail there). Deep -imports of compiled files (`@fluffy-spoon/substitute/dist/...`, with or without `.js`) stay available through -the `./dist/*` subpaths, but they are not public API. +and named imports fail there). + +Deep imports of compiled files (`@fluffy-spoon/substitute/dist/...`, with or without `.js`) stay available through +the `./dist/*` subpaths, but they are not public API. They need subpath patterns with trailers (Node.js 14.19 or +newer, or 16.9 or newer) or a Node.js version that ignores `exports` (older than 12.17); on 12.17 to 12.22, all +of 13.x, 14.0 to 14.18 and 16.0 to 16.8 they fail. ## Test @@ -94,8 +99,36 @@ npm run build:spec && npx ava spec/regression/returns.spec.ts --match '*order*' npm run test:types ``` -Type-level tests check the public typings with the TypeScript compiler. CI runs them with -`npm run test:types --if-present`. +Type-level tests in `spec-types/` check the public typings with the TypeScript compiler of this repository +(`spec-types/` with `strict`, `spec-types/loose/` without). CI runs them with `npm run test:types --if-present`. + +### Oldest supported TypeScript + +```sh +npm run test:types:min-ts +``` + +The README promises TypeScript 3.6 or newer. This builds `dist/` and type-checks `spec-types/min-ts/consumer.ts` +against the built typings (resolved through `package.json` like an installed copy) with TypeScript 3.6, with +`skipLibCheck` off and on. TypeScript 3.6 is installed on the fly with `npx`, so this needs access to the npm +registry. To check other versions after `npm run build`, pass them explicitly: +`node spec-types/min-ts/check.js 3.9 4.0 4.4`. Keep `consumer.ts` to code that TypeScript 3.6 can parse (no +`@ts-expect-error`, for example). If a change makes the typings need a newer TypeScript, that is a breaking change: +raise `MINIMUM_TYPESCRIPT_VERSION` in `spec-types/min-ts/check.js` and the documented minimum together. + +### Documentation examples + +```sh +npm run test:docs +``` + +This builds `dist/` and checks every code example in `README.md`, `MIGRATION.md` and `CHANGELOG.md`: TypeScript +examples are type-checked against the built package and run, JavaScript examples are run, and their +`// prints ...` and `// throws ...` comments must hold. Relative links and `#anchors` must resolve. It then runs a +self-test against deliberately broken fixtures. A change to the library's behaviour or typings that breaks a +documented example fails this check, so update the example in the same change. How to write checked examples, +and the directives that mark blocks (`compile-only`, `esm`, `skip`, ...), are described in +[spec-docs/README.md](spec-docs/README.md). ### Compatibility checks @@ -130,8 +163,10 @@ To try a single runner by hand after `npm run install:local`, use `npm run valid `.github/workflows/nodejs.yml` runs on every push and pull request: -- **test**: `npm ci`, `npm run build`, `npm test` and `npm run test:types --if-present` on every supported - Node.js LTS line (22, 24 and 26). +- **test**: `npm ci`, `npm run build`, `npm test`, `npm run test:types --if-present` and `npm run test:docs` on + every supported Node.js LTS line (22, 24 and 26). +- **types-min-ts**: `npm run test:types:min-ts`, the built typings with the oldest supported TypeScript (3.6), on + the development Node.js version. - **compatibility**: the compatibility checks against the packed package on the same Node.js versions. - **minimum-node**: packs the package and smoke-tests it (`packaging/smoke/`) on the oldest supported Node.js version (`MINIMUM_NODE_VERSION`, which must equal `engines.node`), on the oldest version with native ES diff --git a/packaging/package.test.js b/packaging/package.test.js index ad2aae5..aa8c1ef 100644 --- a/packaging/package.test.js +++ b/packaging/package.test.js @@ -308,6 +308,43 @@ test('CI:matrix CI tests every supported Node LTS line and runs the type tests', t.regex(ciWorkflow, /pull_request/) }) +/** The body of a job in a workflow file: everything from ` :` up to the next job. */ +const workflowJob = (workflow, job) => { + const match = new RegExp(`\\n ${job}:\\n([\\s\\S]*?)(?=\\n [\\w-]+:\\n|$)`).exec(workflow) + return match ? match[1] : undefined +} + +test('F4 CI (and so the release gate) type-checks the built typings with the oldest supported TypeScript', t => { + t.regex(packageJson.scripts['test:types:min-ts'], /^npm run build && node spec-types\/min-ts\/check\.js$/) + t.regex(readText('spec-types/min-ts/check.js'), /MINIMUM_TYPESCRIPT_VERSION = '3\.6'/) + const job = workflowJob(ciWorkflow, 'types-min-ts') + t.truthy(job, 'nodejs.yml has a types-min-ts job') + t.regex(job, /run:\s*npm ci\b/) + t.regex(job, /run:\s*npm run test:types:min-ts\s*$/m) + t.notRegex(job, /\bif:/, 'the job always runs') + // The publish workflow runs the whole CI workflow, this job included, before it publishes. + t.regex(publishWorkflow, /uses:\s*\.\/\.github\/workflows\/nodejs\.yml/) + t.regex(workflowJob(publishWorkflow, 'publish-npm'), /needs:\s*ci\b/) +}) + +test('TD-12 CONTRIBUTING.md documents every CI check, including test:docs and test:types:min-ts', t => { + const contributing = readText('CONTRIBUTING.md') + for (const command of ['npm run test:docs', 'npm run test:types:min-ts', 'npm run test:types']) { + t.true(contributing.includes(command), `CONTRIBUTING.md shows how to run ${command}`) + } + for (const directory of ['spec-types/', 'spec-docs/']) { + t.regex(contributing, new RegExp(`\\| \`${directory}\` \\|`), `the project layout lists ${directory}`) + } + t.true(contributing.includes('spec-docs/README.md'), 'CONTRIBUTING.md points to the docs check documentation') + const ci = contributing.slice(contributing.indexOf('## Continuous integration'), contributing.indexOf('## Releasing')) + for (const [, job] of ciWorkflow.matchAll(/\n ([\w-]+):\n\s+name:/g)) { + t.true(ci.includes(`**${job}**`), `the Continuous integration section describes the ${job} job`) + } + for (const [, command] of workflowJob(ciWorkflow, 'test').matchAll(/run:\s*(npm [^\n]+)/g)) { + t.true(ci.includes(command.replace(' --if-present', '')), `the Continuous integration section mentions ${command}`) + } +}) + test('DOCS:CONTRIBUTING CONTRIBUTING.md (linked from the README) exists and documents the release process', t => { const contributing = readText('CONTRIBUTING.md') for (const topic of ['npm test', 'test:types', 'compatibility-checks', 'release']) { From 160619b164eeaced667abfbcf269a6f484adfec2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:00:27 +0000 Subject: [PATCH 053/106] test(compat): check substitutes inside jest matchers (P28, ENG2-7) jest treats any value with a callable asymmetricMatch member as an asymmetric matcher. An unconfigured member of a substitute is a callable auto-substitute, so a non-matching expect(fn).toHaveBeenCalledWith(sub) passed and expect(42).toEqual(sub) threw jest's internal "Unexpected return from a matcher function" error. test-runners/jest-matchers is a jest suite that must pass: those assertions must fail with jest's normal assertion error (matcherResult.pass === false), while comparisons with the same substitute still pass. test/index.ts runs it through `npm run validate:jest-matchers`; @jest/globals is now a direct devDependency for its imports. The engine change that makes it pass (D28: unconfigured asymmetricMatch reads as undefined) is not on this branch, so this check fails here until that change is merged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CONTRIBUTING.md | 6 +- compatibility-checks/package-lock.json | 1 + compatibility-checks/package.json | 2 + .../test-runners/jest-matchers/index.spec.ts | 63 +++++++++++++++++++ compatibility-checks/test/index.ts | 13 ++++ packaging/package.test.js | 11 ++++ 6 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 compatibility-checks/test-runners/jest-matchers/index.spec.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e675f0..2393903 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -137,7 +137,10 @@ not against `src/`, and checks two things: - `test/index.ts`: every supported test runner (ava, jest, mocha, node:test, vitest, and vitest with the package inlined through `vitest.inline.config.mts`) reports a failing Substitute assertion, including one that is thrown - after the test function has returned. + after the test function has returned. It also runs `test-runners/jest-matchers/` (`npm run validate:jest-matchers`), + which must pass: substitutes used inside jest matchers compare by identity, so a non-matching + `expect(fn).toHaveBeenCalledWith(substitute)` fails and `expect(42).toEqual(substitute)` fails with jest's normal + assertion error. - `test/bundlers.ts`: `bundlers/entry.mjs` is bundled with Rollup and `@rollup/plugin-commonjs`, webpack, esbuild (CommonJS and ES module output) and a Vite SSR build with `ssr.noExternal`, and each bundle is run with Node.js. The default, named and namespace imports must be the real exports. vitest with `server.deps.inline` runs @@ -158,6 +161,7 @@ does the same once the compatibility check dependencies are installed. To try a single runner by hand after `npm run install:local`, use `npm run validate:` (`ava`, `jest`, `mocha`, `nodejs`, `vitest` or `vitest-inline`). Each of them is expected to fail with exactly one failing test. +`npm run validate:jest-matchers` is the exception: it is expected to pass. ## Continuous integration diff --git a/compatibility-checks/package-lock.json b/compatibility-checks/package-lock.json index 9c54193..7e46b92 100644 --- a/compatibility-checks/package-lock.json +++ b/compatibility-checks/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "license": "MIT", "devDependencies": { + "@jest/globals": "^30.5.2", "@rollup/plugin-commonjs": "^29.0.3", "@rollup/plugin-node-resolve": "^16.0.3", "@types/mocha": "^10.0.10", diff --git a/compatibility-checks/package.json b/compatibility-checks/package.json index 8dee019..8d0b9d5 100644 --- a/compatibility-checks/package.json +++ b/compatibility-checks/package.json @@ -19,6 +19,7 @@ "install:local": "node scripts/install-local-build.js", "validate:ava": "ava test-runners/ava/**.ts", "validate:jest": "jest test-runners/jest/**.ts", + "validate:jest-matchers": "jest test-runners/jest-matchers/**.ts", "validate:mocha": "mocha --require tsx/cjs test-runners/mocha/**.ts", "validate:nodejs": "node --require tsx/cjs --test ./test-runners/nodejs/*.ts", "validate:vitest": "vitest run ./test-runners/vitest/*.ts", @@ -27,6 +28,7 @@ "test": "node --require tsx/cjs --test test/index.ts test/bundlers.ts" }, "devDependencies": { + "@jest/globals": "^30.5.2", "@rollup/plugin-commonjs": "^29.0.3", "@rollup/plugin-node-resolve": "^16.0.3", "@types/mocha": "^10.0.10", diff --git a/compatibility-checks/test-runners/jest-matchers/index.spec.ts b/compatibility-checks/test-runners/jest-matchers/index.spec.ts new file mode 100644 index 0000000..02d2398 --- /dev/null +++ b/compatibility-checks/test-runners/jest-matchers/index.spec.ts @@ -0,0 +1,63 @@ +import { describe, expect, jest, test } from '@jest/globals' +import Substitute from '@fluffy-spoon/substitute' + +// P28 (ENG2-7): jest treats any value whose `asymmetricMatch` member is a function as an asymmetric matcher (like +// expect.any()) and asks it whether it matches. An unconfigured member of a substitute is an auto-substitute, which is +// a function that returns a truthy value, so every comparison with a substitute "matched": a non-matching +// toHaveBeenCalledWith(substitute) passed, and toEqual(substitute) threw an internal matcher error. A substitute must +// compare like any other value: by identity. +// +// Unlike the other runners, this suite is expected to pass. test/index.ts runs it with `npm run validate:jest-matchers`. + +interface Logger { + info(message: string): void +} + +/** Runs a jest assertion that must fail, and returns its error. */ +const failureOf = (assertion: () => void): Error => { + try { + assertion() + } catch (error) { + return error as Error + } + throw new Error('The assertion passed, but it should have failed: jest treated the substitute as a matcher.') +} + +/** jest's own assertion error (JestAssertionError with pass: false), not an internal error of a matcher. */ +const expectAssertionFailure = (error: Error, matcherName: string) => { + expect(error.message).not.toMatch(/Unexpected return from a matcher function/) + expect(error.message).toContain(matcherName) + expect((error as Error & { matcherResult?: { pass: boolean } }).matcherResult).toEqual(expect.objectContaining({ pass: false })) +} + +describe('P28 jest matchers compare a substitute by identity', () => { + test('a non-matching expect(fn).toHaveBeenCalledWith(substitute) fails', () => { + const logger = Substitute.for() + const fn = jest.fn() + fn('unrelated') + expectAssertionFailure(failureOf(() => expect(fn).toHaveBeenCalledWith(logger)), 'toHaveBeenCalledWith') + }) + + test('expect(42).toEqual(substitute) fails with a normal assertion error', () => { + const logger = Substitute.for() + expectAssertionFailure(failureOf(() => expect(42).toEqual(logger)), 'toEqual') + }) + + test('a non-matching toContainEqual(substitute) and toEqual between two substitutes fail', () => { + const logger = Substitute.for() + const otherLogger = Substitute.for() + expectAssertionFailure(failureOf(() => expect([1, 2]).toContainEqual(logger)), 'toContainEqual') + expectAssertionFailure(failureOf(() => expect({ logger: 'oops' }).toEqual({ logger })), 'toEqual') + expectAssertionFailure(failureOf(() => expect(otherLogger).toEqual(logger)), 'toEqual') + }) + + test('the same substitute still matches', () => { + const logger = Substitute.for() + const fn = jest.fn() + fn(logger) + expect(fn).toHaveBeenCalledWith(logger) + expect(logger).toEqual(logger) + expect({ logger }).toEqual({ logger }) + expect([1, logger]).toContainEqual(logger) + }) +}) diff --git a/compatibility-checks/test/index.ts b/compatibility-checks/test/index.ts index 0a0851b..8f4cf3d 100644 --- a/compatibility-checks/test/index.ts +++ b/compatibility-checks/test/index.ts @@ -37,6 +37,19 @@ test.describe('Verifies test runner compatibility', () => { { name: 'vitest-inline', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest-inline/index.spec.ts' } ] + // P28 (ENG2-7): jest's matchers must compare a substitute like any other value. Unlike the runs above, this suite + // (test-runners/jest-matchers) must pass. + test.describe('jest matchers', () => { + test.it('P28 a non-matching toHaveBeenCalledWith(substitute) and toEqual(substitute) fail with normal assertion errors', () => { + try { + execSync('npm run validate:jest-matchers', { env: testRunnerEnvironment(), stdio: 'pipe' }) + } catch (error) { + // @ts-expect-error + assert.fail(`The jest matcher checks failed:\n${error.stdout.toString()}${error.stderr.toString()}`) + } + }) + }) + testRunners.forEach(testRunner => { test.describe(testRunner.name, () => { test.it('reports the Substitute exception', () => { diff --git a/packaging/package.test.js b/packaging/package.test.js index aa8c1ef..c39dcaf 100644 --- a/packaging/package.test.js +++ b/packaging/package.test.js @@ -140,6 +140,17 @@ test('F1 the compatibility checks bundle the packed package and run vitest with t.regex(fs.readFileSync(path.join(root, 'compatibility-checks', 'test', 'index.ts'), 'utf8'), /name: 'vitest-inline'/) }) +test('P28 the compatibility checks use substitutes inside jest matchers', t => { + const compatibility = JSON.parse(fs.readFileSync(path.join(root, 'compatibility-checks', 'package.json'), 'utf8')) + t.is(compatibility.scripts['validate:jest-matchers'], 'jest test-runners/jest-matchers/**.ts') + const harness = fs.readFileSync(path.join(root, 'compatibility-checks', 'test', 'index.ts'), 'utf8') + t.regex(harness, /execSync\('npm run validate:jest-matchers'/, 'test/index.ts runs the jest matcher suite and expects it to pass') + const suite = fs.readFileSync(path.join(root, 'compatibility-checks', 'test-runners', 'jest-matchers', 'index.spec.ts'), 'utf8') + t.regex(suite, /expect\(fn\)\.toHaveBeenCalledWith\(logger\)/) + t.regex(suite, /expect\(42\)\.toEqual\(logger\)/) + t.regex(suite, /Unexpected return from a matcher function/) +}) + const typeScriptConsumer = [ "import Substitute, { Arg, Substitute as Named } from '@fluffy-spoon/substitute'", "import { Arg as DeepArg } from '@fluffy-spoon/substitute/dist/api/Arg'", From 190428c2cdeec931c6f4856f920bed0274525ea3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:06:46 +0000 Subject: [PATCH 054/106] docs(contributing): test:types:min-ts also checks the documentation comments fix/r3-types made spec-types/min-ts/check.js run the TD-10 JSDoc check after the TypeScript 3.6 check, while fix/r3-packaging documented test:types:min-ts and the types-min-ts CI job as the TypeScript 3.6 check only. Mention the JSDoc check in both places. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CONTRIBUTING.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2393903..4a20f2a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -115,6 +115,9 @@ registry. To check other versions after `npm run build`, pass them explicitly: `node spec-types/min-ts/check.js 3.9 4.0 4.4`. Keep `consumer.ts` to code that TypeScript 3.6 can parse (no `@ts-expect-error`, for example). If a change makes the typings need a newer TypeScript, that is a breaking change: raise `MINIMUM_TYPESCRIPT_VERSION` in `spec-types/min-ts/check.js` and the documented minimum together. +Afterwards the same script runs `spec-types/TD-10.T32.jsdoc.js`, which uses the TypeScript of this repository to +check that the public API in the built typings carries documentation comments (editor quick info). It fails when +one of them is missing. ### Documentation examples @@ -169,8 +172,8 @@ To try a single runner by hand after `npm run install:local`, use `npm run valid - **test**: `npm ci`, `npm run build`, `npm test`, `npm run test:types --if-present` and `npm run test:docs` on every supported Node.js LTS line (22, 24 and 26). -- **types-min-ts**: `npm run test:types:min-ts`, the built typings with the oldest supported TypeScript (3.6), on - the development Node.js version. +- **types-min-ts**: `npm run test:types:min-ts`, the built typings with the oldest supported TypeScript (3.6) and + the documentation comments of the public API, on the development Node.js version. - **compatibility**: the compatibility checks against the packed package on the same Node.js versions. - **minimum-node**: packs the package and smoke-tests it (`packaging/smoke/`) on the oldest supported Node.js version (`MINIMUM_NODE_VERSION`, which must equal `engines.node`), on the oldest version with native ES From d588449f25a6a1e47049de3ae9f5e7b8c51fbf0b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:25:29 +0000 Subject: [PATCH 055/106] docs: document the round-3 behaviour and correct the migration notes README: - Node.js ranges for the ES module entry (12.17+ on 12.x, 13.7+ on 13.x, 14+), bundler support and the esbuild ESM banner (F1, F2). - Matchers inside objects and arrays (D27), how literal arguments are compared, including #private fields and invalid dates (D29), and mutating setup arguments (amended D15/D35). - What .returns() does on a call that already answers with a primitive, a plain object, a substitute or an auto-substitute (V2-4, ENG2-15), and nested configure() setups that forward to a substitute or fail (D31). - Which reads and calls lead to a setup or check: the same-file, same-function rule, stored handles, callbacks and the stackTraceLimit fallback (D25). - call, apply and bind: both meanings, how they are recorded and printed, and the JavaScript direct-call checks x.received(n)(...) (D26, D11 extension). - Members used as a property and as a method (D32), `this` in mimicks(), the never-used-member message and the read-without-call hint (TD-11, D36), deferred reports for didNotReceive().m and fake timers (D33, D34), the full list of protocol members (D28), generic helpers (T26), new typing limitations (T25-T31), jest matchers (P28) and a performance section (D30, D35). MIGRATION: - Drop claims about bugs 2.0.0-beta.4 never had, and add the breaking changes: JavaScript string checks of members called returns & co. are now setups, null-only members lose .returns(), Arg.any('object') is any (TD-4). - 1.x deep imports were under dist/src/; list the removed beta internals and the Node.js versions on which deep imports work (TD-9, F3). - New sections for checks that fail later, argument comparison, `this` in mimicks() and protocol members; nested matchers, call/apply/bind and setup-chain reads under the existing sections. CHANGELOG: - List only changes relative to 2.0.0-beta.4: remove the fixes for bugs that only existed on unreleased master, add the round-3 additions, changes and fixes, and qualify the message and JSDoc entries (TD-4, TD-10, TD-11). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- CHANGELOG.md | 54 +++++--- MIGRATION.md | 98 ++++++++++++-- README.md | 376 +++++++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 469 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53be49b..73dc4e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,29 +8,40 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis ### Added - Symbols for the library's methods, exported from the package root: `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. They always mean the library's method, so they handle members with the same names, and they work when two copies of the package are installed. -- `sub[configure]()`: a view of a substitute in which every call and property read is a setup. Use it to change a call that is already configured, or to configure a mimicked substitute. +- `sub[configure]()`: a view of a substitute in which every call and property read is a setup. Use it to change a call that is already configured, or to configure a mimicked substitute. A setup through a member or call that answers with a substitute goes to that substitute; through one that answers with a real value, it throws a `SubstituteException`. - `sub[mimick](instance)`: hands everything that is not configured to a real instance. Calls are still recorded, and setups still win. - `sub[clearReceivedCalls]()`: forgets the received calls of a substitute and its auto-substitutes, and keeps the setups. - `SubstituteException` is exported from the package root, for `instanceof` checks. - Auto-substitutes are cached, so nested setups and checks work at runtime: `app.getCalculator().add(1, 2).returns(99)` and `app.logger.received().info('hi')`. -- `Arg.all()` after other arguments matches the rest of the arguments, including none: `log('x', Arg.all())`. -- A native ES module entry point and an `exports` map, with typings for the `node16`, `nodenext` and `bundler` module resolutions. The ES module entry point shares one copy of the library with CommonJS. +- `Arg.all()` after other arguments matches the rest of the arguments, including none: `log('x', Arg.all())`. In TypeScript, this type-checks after up to 6 other arguments. +- Matchers inside plain objects and arrays, at any depth: `repository.save({ id: Arg.any(), name: 'bob' }).returns('saved')`. `Arg.all()` as the last item of an array matches the remaining items. +- A native ES module entry point and an `exports` map, with typings for the `node16`, `nodenext` and `bundler` module resolutions. The ES module entry point shares one copy of the library with CommonJS. It is checked on every change with Node.js, Rollup with `@rollup/plugin-commonjs`, webpack, esbuild, a Vite SSR build with `ssr.noExternal` and vitest with `server.deps.inline`. - `console.log`, `util.inspect` and `String()` show a substitute's setups and received calls. -- The public typings carry documentation comments for editors. -- A [migration guide](MIGRATION.md), this changelog and [contributing guidelines](CONTRIBUTING.md). The README examples are type-checked and run in CI. +- The public typings carry documentation comments for editors: `Substitute.for`, `SubstituteOf`, `Arg` and its matchers, the setup methods, the checks and the symbols. +- A [migration guide](MIGRATION.md), this changelog and [contributing guidelines](CONTRIBUTING.md). The README examples are type-checked and run in CI, and the oldest supported TypeScript version is checked there, too. ### Changed - When several setups match a call, the most specific one wins: literal arguments, then matchers, then `Arg.all()` alone. Among setups of the same kind, the most recent one wins, and configuring the same call again replaces it. (The README said that the first matching setup wins.) -- A call with an argument matcher (`Arg.any`, `Arg.is`, `Arg.all`, also with `.not`) is always a setup or a check. It is never recorded as a received call and never runs an existing setup. +- A call with an argument matcher (`Arg.any`, `Arg.is`, `Arg.all`, also with `.not`, also inside an object or array) is always a setup or a check. It is never recorded as a received call and never runs an existing setup. +- The reads and calls that lead up to a setup or a check in the same expression, like `app.getCalculator()` in `app.getCalculator().add(1, 2).returns(99)`, are not recorded as received calls. Calls that the code under test made are kept, also when the test then configures or checks the value they returned. - Reading a method without calling it is no longer a call; method checks count invocations only. -- `received(count)` throws a `SubstituteException` unless the count is a non-negative integer (or left out). `received(0)` is the same as `didNotReceive()`. +- `.call()`, `.apply()` and `.bind()` on a substitute value also count as a call of a member called `call`, `apply` or `bind`, and a setup written through them configures that member. Failure messages and `String(sub)` show such a call once, as in `rpc(1) via .call('getUser', 1)`. +- A `mimicks()` function and a mimicked function get the `this` of the call: the substitute for `sub.method(...)`, and the first argument of `.call()` and `.apply()`. +- **JavaScript:** `sub.received(count)` or `sub.didNotReceive()` followed by `.returns()`, `.throws()`, `.resolves()`, `.rejects()` or `.mimicks()` configures a member of your own called `received` or `didNotReceive`. In 2.0.0-beta.4 and 1.x it was a check of a member called `returns` (and so on), so such checks now pass silently. Use the symbols: `sub[received](1).returns(5)`. +- **JavaScript:** `sub.received(count)` or `sub.didNotReceive()` followed directly by a call, like `listener.received(1)('saved')`, checks a call of the substitute itself. +- `received(count)` throws a `SubstituteException` unless the count is a non-negative integer (or left out). In 2.0.0-beta.4 an invalid count threw a plain `Error`, and in 1.x it was reported as a call count mismatch. `received(0)` is the same as `didNotReceive()`. - `Arg.any('object')` matches objects, arrays and substitutes, but no longer `null`. `Arg.any('function')` matches substitutes, and `Arg.any('array')` uses `Array.isArray`. - `Arg.is()` throws a `TypeError` right away when it is not given a function. A predicate that throws counts as a non-match, and the failure message says so. -- Failure messages say what kind of call was expected (method calls, property reads or property assignments), with the expected arguments and the path of nested substitutes. They list at most 50 received calls. They contain ANSI colours only when the output is a terminal, and honour `NO_COLOR`, `FORCE_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb`. -- Failed checks throw right away. Only a property-style check on a member that was called as a method can be reported later, on `process.nextTick` (see the README). -- TypeScript: on a type with a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, only the symbol forms `sub[received]()` and `sub[didNotReceive]()` are offered. `.returns()` and the other setup methods are offered unless the configured value has its own member with that name. +- An argument object that is changed after it was used in a setup only matches that setup when the same object is passed again; a new object equal to the changed one no longer does. +- `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.isConcatSpreadable`, `Symbol.match`, `Symbol.matchAll`, `Symbol.replace`, `Symbol.search`, `Symbol.split`, `Symbol.species`, `Symbol.toStringTag`, `Symbol.unscopables`, `util.promisify.custom` and `asymmetricMatch` read as `undefined` unless they are configured, and these reads are not recorded. So a substitute is no longer iterable: `[...sub]` and `for...of` throw a `TypeError` (2.0.0-beta.4 iterated it as empty). +- A substitute no longer exposes internal fields: `Object.keys(sub)` is empty, and `Reflect.ownKeys(sub)` lists only `length` and `name`. +- Failure messages say what kind of call was expected: method calls, property reads, property assignments, or "property reads or method calls" when that is not known. They show the path of nested substitutes, and list at most 50 received calls. When the checked member was never used at all, the message cannot name the expected arguments; once the method has been called, it does. A method that was only read, never called, gets a hint that reading is not calling. Messages contain ANSI colours only when the output is a terminal, and honour `NO_COLOR`, `FORCE_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb`. +- Failed checks throw right away. Only a property-style check (`sub.received(2).member` or `sub.didNotReceive().member`, not followed by a call) on a member that was called as a method can be reported later, on `process.nextTick` (see the README). Such a report uses the `process.nextTick` that the library found when it was loaded. +- TypeScript: on a type with a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, only the symbol forms `sub[received]()` and `sub[didNotReceive]()` are offered. In generic code, the type parameter's constraint decides; an unconstrained `SubstituteOf` offers the string forms. `.returns()` and the other setup methods are offered unless the configured value has its own member with that name. - TypeScript: a member called `then` is typed `never`, because substitutes are never thenables. -- The minimum TypeScript version is 3.6 (2.0.0-beta.4 needed 3.8). The package runs on Node.js 10 and newer with CommonJS, and 12.17 and newer as an ES module. +- TypeScript: members typed only `null` or `undefined` keep their plain type and have no setup API (configure them through `sub[configure]()`). +- TypeScript: `Arg.any('function')` is typed as any function or class, so it fits typed callback parameters. `Arg.any('object')` is typed `any`. +- The minimum TypeScript version is 3.6 (2.0.0-beta.4 needed 3.8). The package runs on Node.js 10 and newer with CommonJS. As an ES module, it needs Node.js 12.17 or newer on 12.x, 13.7 or newer on 13.x, or 14 or newer. - Releases are published to npm with provenance: stable versions as `latest`, prereleases as `beta`. ### Fixed @@ -38,26 +49,27 @@ The first stable release of version 2 (there was no 2.0.0 release). It is publis - Checking a configured property ran its setup: it threw the configured error, used up values of a `returns()` sequence, ran `mimicks()` again or left an unhandled rejection. - Calls through a stored or destructured method reference, or a callback, were recorded only once. - Merely reading a method (for example to register it as a callback) satisfied `received().method(...)`. -- `.call()`, `.apply()` and `.bind()` on a configured method returned a proxy instead of the configured value. -- Checks on members called `returns`, `throws`, `resolves`, `rejects` or `mimicks` passed silently. -- `received(count)` with a negative, fractional or `NaN` count passed silently. -- A setup on the substitute leaked into nested members with the same name. Nested checks were checked against the root members, and code under test that read a nested member called `received` threw. +- `.call()`, `.apply()` and `.bind()` on a configured method, on a function substitute, on the result of a call or on a nested member returned a proxy instead of the configured value, so a function substitute called through a helper like `once(fn)`, which calls `fn.apply(this, args)`, did not return its configured value. +- A setup on the substitute leaked into nested members with the same name, and nested checks (`app.logger.received().info('hi')`) passed whatever had been called. +- `sub.didNotReceive().method` without the call parentheses passed silently when the method had been called. It is now reported (see above). - `Arg.all()` after other arguments ignored those arguments. -- Every call scanned all earlier calls, which made large tests slow. 10,000 calls now take well under a second. +- Every call scanned all earlier calls, which made large tests slow. 10,000 calls now take well under a second, also with arguments such as nested objects, long arrays, `Buffer`s or long strings. - A failed check overflowed the stack when substitutes referred to each other through their arguments, and threw a `TypeError` with `Error.stackTraceLimit = 0`. - An exception thrown by an `Arg.is()` predicate escaped into the code under test. -- Failure messages for methods said "property calls" and left out the expected arguments. -- The symbol API did not work across two copies of the package. -- TypeScript: `mimicks()` on methods that return a union (including `boolean`); `received()` in generic helpers over `SubstituteOf`; a member called `returns` removing `.returns()` from all properties; optional members; named members next to an index signature; overloads without parameters; methods with more than 5 overloads; `.throws()` on methods returning `never`; `(...args: unknown[])` methods; a private member called `received` turning the substitute type into `never`. +- Failure messages said "property calls" when the library could not know whether a method or a property was checked. +- A check reported on `process.nextTick` was lost when a test had installed fake timers that fake `process.nextTick`. +- `[].concat(sub)` dropped the substitute, `value instanceof sub.SomeClass` was always `true`, `'text'.startsWith(sub.prefix)` threw, and `util.promisify(sub.method)` did not call the substitute. +- jest took every substitute for an asymmetric matcher: `expect(fn).toHaveBeenCalledWith(sub)` and `toContainEqual(sub)` passed whatever the values were, and a failing `toEqual(sub)` threw jest's internal "Unexpected return from a matcher function" error. +- TypeScript: optional members; named members next to an index signature; overloads without parameters; methods with more than 5 overloads; `.throws()` on methods returning `never`; `(...args: unknown[])` methods; a private member called `received` turning the substitute type into `never`; types with a very large union of string literals, such as lib.dom's `HTMLInputElement`, failing with "Expression produces a union type that is too complex to represent". - Under native ES modules, the default import was the CommonJS module object, so `Substitute.for` was not a function. - The package could not be loaded on Node.js versions before 14.18. -- A manual `npm publish` after `npm test` could publish a package without its entry point. `package-lock.json` had an outdated version. +- A manual `npm publish` after `npm test` could publish a package without its entry point. ### Removed - `Substitute.disableFor()`. Call members with conflicting names directly, and use the symbols for the library's methods. - `sub.clearSubstitute(clearType)` and the `ClearType` export. Use `sub[clearReceivedCalls]()`, or create a new substitute to drop setups. - The string `sub.mimick(instance)`. Use `sub[mimick](instance)`; `mimick` is now an ordinary member name. -- The 2.0.0-beta deep import paths (`dist/Substitute`, `dist/Arguments`, `dist/SubstituteException`, ...). Import from the package root. Directory deep imports (`.../dist/api`) no longer resolve on Node.js versions that read `exports`. +- The deep import paths of 1.x (`dist/src/...`) and of the 2.0.0 betas (`dist/Substitute`, `dist/Arguments`, `dist/SubstituteException`, and internals such as `dist/SubstituteNode`, `dist/Recorder` and `dist/RecordsSet`). Import from the package root. Directory deep imports (`.../dist/api`) no longer resolve on Node.js versions that read `exports`. - The GitHub Packages publishing job, which could not publish the `@fluffy-spoon` scope. ## [2.0.0-beta.4] - 2024-03-21 diff --git a/MIGRATION.md b/MIGRATION.md index ff2a780..020e40f 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -7,7 +7,7 @@ Each section says which versions it applies to. Code marked "Before" is for the - [Requirements](#requirements) - [Removed APIs](#removed-apis): [`Substitute.disableFor`](#substitutedisablefor), [`clearSubstitute` and `ClearType`](#clearsubstitute-and-cleartype), [string `mimick(instance)`](#the-string-mimickinstance) - [Names that conflict with the library: the symbol API](#names-that-conflict-with-the-library-the-symbol-api) -- [Behaviour changes](#behaviour-changes): [sequences](#sequences-repeat-the-last-value), [auto-substitutes](#auto-substitutes-and-nested-checks), [matcher calls](#calls-with-argument-matchers-are-setups), [match order](#match-order), [re-configuring](#re-configuring-a-call), [what counts as a call](#what-counts-as-a-call), [checks](#checks-never-run-setups), [`received(count)`](#receivedcount-is-validated), [matchers](#matchers), [messages](#messages) +- [Behaviour changes](#behaviour-changes): [sequences](#sequences-repeat-the-last-value), [auto-substitutes](#auto-substitutes-and-nested-checks), [matcher calls](#calls-with-argument-matchers-are-setups), [match order](#match-order), [re-configuring](#re-configuring-a-call), [what counts as a call](#what-counts-as-a-call), [checks](#checks-never-run-setups), [`received(count)`](#receivedcount-is-validated), [checks that fail later](#checks-that-fail-later), [matchers](#matchers), [argument comparison](#how-arguments-are-compared), [`this` in `mimicks()`](#this-in-mimicks), [protocol members](#protocol-members-read-as-undefined), [messages](#messages) - [Imports and packaging](#imports-and-packaging) - [TypeScript](#typescript) @@ -40,7 +40,8 @@ Prereleases are still published under the `beta` tag. ## Requirements *Applies to: everyone.* -* Node.js 10 or newer for CommonJS, and 12.17 or newer for the native ES module entry point. +* Node.js 10 or newer for CommonJS (`require`). +* For the native ES module entry point (`import`): Node.js 12.17 or newer on 12.x, 13.7 or newer on 13.x, or 14 or newer. On 13.2 to 13.6, `import` gets the CommonJS entry and named imports fail; use `require` there. * TypeScript 3.6 or newer. The 1.x README said TypeScript 3.0; 2.0.0-beta.4 needed 3.8. * `strict` mode, including `strictNullChecks`, is supported. The 1.x README told you to turn `strictNullChecks` off; that is no longer needed. @@ -162,7 +163,9 @@ The package exports symbols for its methods: `received`, `didNotReceive`, `clear * `clearReceivedCalls`, `mimick` and `configure` exist **only** as symbols. * In TypeScript, if a type has a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, its substitute offers only `sub[received]()` and `sub[didNotReceive]()`. Code that used the string forms on such a type no longer compiles. -* `.returns()`, `.throws()`, `.mimicks()`, `.resolves()` and `.rejects()` are not offered on a value that has its own member with that name. Use `[returns]` and so on there. (In 2.0.0-beta.4, a member called `returns` on the substituted interface removed `.returns()` from all of its properties; that is fixed.) +* `.returns()`, `.throws()`, `.mimicks()`, `.resolves()` and `.rejects()` are not offered on a value that has its own member with that name. Use `[returns]` and so on there. +* **In JavaScript, a string check of a member called `returns`, `throws`, `resolves`, `rejects` or `mimicks` is now a setup, and passes silently.** In 1.x and the betas, `sub.received(1).returns(5)` was a check of a member called `returns`. Now `sub.received(1)` followed by `.returns(...)` configures a member of your own called `received` (see [Names that conflict with the library](README.md#in-javascript)). Search your tests for `received(...).returns(`, `.throws(`, `.resolves(`, `.rejects(` and `.mimicks(`, and use the symbol: `sub[received](1).returns(5)`. +* In generic code, the type parameter's constraint decides: an unconstrained `SubstituteOf` offers `sub.received()` and `sub.didNotReceive()`, as in 2.0.0-beta.4, while for `T extends Account`, where `Account` has a member with one of these names, only the symbols are offered. ```typescript @@ -174,6 +177,8 @@ calculator[received](1).add(1, 2) calculator[didNotReceive]().subtract(Arg.all()) ``` +`call`, `apply` and `bind` on a substitute value now mean both the function's own method and a member of your own with that name; see [What counts as a call](#what-counts-as-a-call). + ## Behaviour changes ### Sequences repeat the last value *Applies to: 1.x.* @@ -228,6 +233,8 @@ calculator.subtract(Arg.any(), 2) calculator.didNotReceive().subtract(Arg.all()) ``` +This also holds for matchers inside plain objects and arrays, which are new: `repository.save({ id: Arg.any(), name: 'bob' }).returns('saved')` is a setup, and it matches `save({ id: 1, name: 'bob' })`. Before, a matcher inside an object was compared as a value, so such a call was a received call and never matched anything. Matchers inside class instances, `Map`s and `Set`s are still compared as values. See [Matchers inside objects and arrays](README.md#matchers-inside-objects-and-arrays). + ### Match order *Applies to: 1.x and the betas.* @@ -244,7 +251,7 @@ console.log(calculator.add(5, 0)) // prints 1 ### Re-configuring a call *Applies to: 1.x and the betas.* -A call whose literal arguments match an existing setup returns the configured value, so `calculator.add(1, 2).returns(5)` after `calculator.add(1, 2).returns(4)` fails (a number has no `.returns`). Use the new `sub[configure]()` view, in which every call is a setup: +A call whose literal arguments match an existing setup returns the configured value, so `calculator.add(1, 2).returns(5)` after `calculator.add(1, 2).returns(4)` fails (a number has no `.returns`). If the configured value is a substitute, `.returns(5)` is silently recorded as a call of that substitute's member `returns`, and nothing is configured. Use the new `sub[configure]()` view, in which every call is a setup: ```typescript @@ -263,8 +270,9 @@ console.log(calculator.add(1, 3)) // prints 1337 *Applies to: 1.x and the betas.* * Reading a method without calling it is not a call. Before, merely reading a method (for example to register it as an event handler) satisfied `received().method(...)`. -* `.call()`, `.apply()` and `.bind()` on a method return the configured value and are recorded like a direct call. Before, `.call()` and `.apply()` returned a proxy. +* `.call()`, `.apply()` and `.bind()` on a method, a function substitute, the result of a call or a nested member return the configured value and count as a direct call, and a mimicked function or a `mimicks()` function gets their first argument as `this`. Before, they returned a proxy (in 1.x, `.bind()` on a method already worked). They also count as a call of a member called `call`, `apply` or `bind`, and a setup such as `client.rpc.call('getUser', 1).returns(user)` configures that member. See [`call`, `apply` and `bind`](README.md#call-apply-and-bind). * Every call through a stored or destructured reference, or a callback, is recorded. In the betas, each such call overwrote the previous one (1.x was not affected). +* The reads and calls that lead up to a setup or a check in the same expression, like `app.getCalculator()` in `app.getCalculator().add(1, 2).returns(99)`, are not recorded. Before, they were received calls, so `app.didNotReceive().getCalculator()` failed after that setup. Calls that the code under test made are kept: see [Which calls lead to a setup or a check](README.md#which-calls-lead-to-a-setup-or-a-check) for how the library tells them apart. ```typescript @@ -301,6 +309,13 @@ calculator.received(0).add(1, 2) calculator.received(1.5).add(1, 2) // throws SubstituteException: Expected count has to be a non-negative integer ``` +### Checks that fail later +*Applies to: 1.x and the betas.* + +`sub.didNotReceive().member` or `sub.received(0).member` without parentheses, on a member that was called as a method, passed silently before. Now its failure is reported on `process.nextTick`, because the parentheses were probably forgotten: `Expected to receive 0 property reads or method calls matching add, but received 1 method call. add was called 1 time as a method; to assert calls, invoke it: sub.didNotReceive().add(...)`. Add the call: `sub.didNotReceive().add(1, 2)`, or `.add(Arg.all())`. See [Assertions that fail later](README.md#assertions-that-fail-later). + +Reports on `process.nextTick` use the `process.nextTick` that the library found when it was loaded, so fake timers installed later in a test no longer hold them back. + ### Matchers *Applies to: 1.x and the betas.* @@ -309,10 +324,58 @@ calculator.received(1.5).add(1, 2) // throws SubstituteException: Expected count * `Arg.is()` with something other than a function throws a `TypeError` right away. A predicate that throws counts as a non-match instead of crashing the code under test. * Substitutes passed as arguments are compared by identity, and are never compared or printed member by member. In the betas, a failed check overflowed the stack when substitutes referred to each other through their arguments. +### How arguments are compared +*Applies to: 1.x and the betas.* + +Literal arguments are compared with deep strict equality (`util.isDeepStrictEqual`), as before: own enumerable properties and prototypes. `#private` fields and other internal state are invisible to it, so all instances of a class that keeps its state only in `#private` fields are equal to each other. Use the same instance, or `Arg.is()`, for such classes (see [How arguments are compared](README.md#how-arguments-are-compared)). + +What changed: an argument object that you change after using it in a setup only matches that setup when the same object is passed again. Before, a new object equal to the changed one matched as well. Create the setup with the object as the code under test will pass it, or with a matcher. + + +```typescript +interface Repository { + save(user: { name: string }): string +} + +const repository = Substitute.for() +const user = { name: 'ann' } +repository.save(user).returns('saved') +user.name = 'bob' + +console.log(repository.save(user)) // prints saved +console.log(repository.save({ name: 'bob' }) === 'saved') // prints false +``` + +### `this` in `mimicks()` +*Applies to: 1.x and the betas.* + +A `mimicks()` function is called with the `this` of the call, like a method: the substitute for `sub.method(...)`, the first argument of `.call()` and `.apply()`, and `undefined` for a property read. Before, it was `undefined` (in 2.0.0-beta.4) or the library's own proxy (in 1.x). An implementation that relied on that, or that needs a `this` of its own, should be an arrow function or a bound method. + +### Protocol members read as `undefined` +*Applies to: 1.x and the betas.* + +`Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.isConcatSpreadable`, `Symbol.match`, `Symbol.matchAll`, `Symbol.replace`, `Symbol.search`, `Symbol.split`, `Symbol.species`, `Symbol.toStringTag`, `Symbol.unscopables`, `util.promisify.custom` and `asymmetricMatch` read as `undefined` on a substitute unless they are configured, and the reads are not recorded (see [Special members](README.md#special-members)). Before, they returned auto-substitutes. So: + +* `[].concat(sub)` keeps the substitute as one element (it was dropped), `value instanceof sub.SomeClass` is `false` (it was `true`), `'text'.startsWith(sub.prefix)` no longer throws, and `util.promisify(sub.readFile)` calls the substitute. +* jest no longer takes a substitute for an asymmetric matcher. Before, `expect(fn).toHaveBeenCalledWith(sub)` and `expect(list).toContainEqual(sub)` passed whatever the arguments or items were, and a failing `expect(value).toEqual(sub)` threw jest's internal "Unexpected return from a matcher function" error. Now they compare the substitute by identity, so tests that passed only because of this fail. +* **A substitute is not iterable.** `[...sub]`, `for...of`, `for await...of` and `Promise.all(sub)` on a substitute that is not configured throw a `TypeError`. In the betas they treated it as empty; in 1.x they threw a different `TypeError`. Configure the iterator, or mimick an array: + +```js +const { Substitute, configure, mimick } = require('@fluffy-spoon/substitute') + +const items = Substitute.for() +items[configure]()[Symbol.iterator]().mimicks(() => ['a', 'b'][Symbol.iterator]()) +console.log([...items]) // prints [ 'a', 'b' ] + +const list = Substitute.for() +list[mimick](['a', 'b']) +console.log(list.length) // prints 2 +``` + ### Messages *Applies to: 1.x and the betas.* -The wording of `SubstituteException` messages changed, for example "Expected to receive 2 method calls matching add(1, 2), but received 1.", followed by the calls that were received (at most 50). Tests that compare message texts need updating. Messages contain ANSI colours only when the output is a terminal (`NO_COLOR`, `NODE_DISABLE_COLORS`, `TERM=dumb` and `FORCE_COLOR` are honoured). In the betas, messages always contained them; 1.x messages had no colours. +The wording of `SubstituteException` messages changed, for example "Expected to receive 2 method calls matching add(1, 2), but received 1.", followed by the calls that were received (at most 50). Tests that compare message texts need updating. When the kind of call is not known, messages say "property reads or method calls" instead of "property calls". A check of a member that was never used at all fails when it reads the member, so its message cannot name the expected arguments ("... matching add, but received none."); once the method has been called, the message names them. Messages contain ANSI colours only when the output is a terminal (`NO_COLOR`, `NODE_DISABLE_COLORS`, `TERM=dumb` and `FORCE_COLOR` are honoured). In the betas, messages always contained them; 1.x messages had no colours. `SubstituteException` is now exported from the package root: `import { SubstituteException } from '@fluffy-spoon/substitute'`. @@ -330,14 +393,14 @@ calculator.add(Arg.any(), 2).returns(3) console.log(calculator.add(1, 2)) // prints 3 ``` -**Deep imports moved.** package.json now has an `exports` map. The public entry point is the package root; import everything from there: +**Deep imports moved.** package.json now has an `exports` map. The public entry point is the package root; import everything from there. 1.x had its files under `dist/src/`, the betas directly under `dist/`: | Before | After | |---|---| -| `@fluffy-spoon/substitute/dist/Substitute` (`Substitute`, `SubstituteOf`) | `@fluffy-spoon/substitute` | -| `@fluffy-spoon/substitute/dist/Arguments` (`Arg`) | `@fluffy-spoon/substitute` | -| `@fluffy-spoon/substitute/dist/SubstituteException` (betas), `.../dist/SubstituteBase` (1.x) | `import { SubstituteException } from '@fluffy-spoon/substitute'` | -| `@fluffy-spoon/substitute/dist/Transformations` (`ObjectSubstitute`, ...) | `SubstituteOf` from `@fluffy-spoon/substitute` | +| `@fluffy-spoon/substitute/dist/src/Substitute` (1.x), `.../dist/Substitute` (betas): `Substitute`, `SubstituteOf` | `@fluffy-spoon/substitute` | +| `@fluffy-spoon/substitute/dist/src/Arguments` (1.x), `.../dist/Arguments` (betas): `Arg` | `@fluffy-spoon/substitute` | +| `@fluffy-spoon/substitute/dist/src/SubstituteBase` (1.x), `.../dist/SubstituteException` (betas): `SubstituteException` | `import { SubstituteException } from '@fluffy-spoon/substitute'` | +| `@fluffy-spoon/substitute/dist/src/Transformations` (1.x), `.../dist/Transformations` (betas): `ObjectSubstitute`, ... | `SubstituteOf` from `@fluffy-spoon/substitute` | ```typescript @@ -351,7 +414,11 @@ try { } ``` -The compiled files now live under `dist/api`, `dist/internals` and `dist/shared`. They can still be imported as `@fluffy-spoon/substitute/dist/` (with or without `.js`), but they are not public API and can change in any release. Directory imports such as `@fluffy-spoon/substitute/dist/api` no longer resolve on Node.js versions that read `exports`. +The other files were internals and are gone without a replacement: in 1.x `dist/src/Context`, `dist/src/Utilities` and `dist/src/states/...`; in the betas `dist/SubstituteNode`, `dist/SubstituteNodeBase`, `dist/Recorder`, `dist/RecordsSet`, `dist/RecordedArguments`, `dist/Types` and `dist/Utilities` (`dist/utilities/...` in 2.0.0-beta.4). Development builds made from the repository after 2.0.0-beta.4 had them under `dist/internals/` (`dist/internals/SubstituteNode`, `dist/internals/Recorder`, `dist/internals/RecordsSet`, ...); those are gone, too. + +The compiled files of 2.0.1 live under `dist/api`, `dist/internals` and `dist/shared`. They are not public API and can change in any release. They can be imported as `@fluffy-spoon/substitute/dist/`, with or without `.js`, on Node.js 14.19 or newer on 14.x, 16.9 or newer on 16.x, any later version, and versions older than 12.17 (which ignore `exports`). On 12.17 to 12.19, 13.x and 14.0 to 14.12, deep imports fail; on 12.20 to 12.22, 14.13 to 14.18 and 16.0 to 16.8, only the form without `.js` works. Directory imports such as `@fluffy-spoon/substitute/dist/api` no longer resolve on Node.js versions that read `exports`. + +**`require` works on every Node.js version from 10 on, and `import` needs 12.17 or newer on 12.x, 13.7 or newer on 13.x, or 14 or newer** (see [Requirements](#requirements)). ## TypeScript *Applies to: 1.x and the betas.* @@ -359,7 +426,10 @@ The compiled files now live under `dist/api`, `dist/internals` and `dist/shared` The typings were reworked. Most code compiles unchanged, but: * The [symbol rules](#names-that-conflict-with-the-library-the-symbol-api) above: string checks are not offered on types with conflicting member names, and `mimick(instance)` is symbol only. -* The symbol API is available on every substitute, also on `SubstituteOf` for a generic `T` (in the betas, generic helpers could not call `received()`). +* The symbol API is available on every substitute, also on `SubstituteOf` for a generic `T`. In generic code, the string forms `sub.received()` and `sub.didNotReceive()` are offered for a type parameter without a constraint, as in the betas. With a constraint, the constraint decides: if it has a member called `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`, only the symbols are offered. Calls that return the type parameter keep `.returns()` and the other setup methods. * A member called `then` is typed `never`: substitutes are never thenables. -* Now supported: `mimicks()` on methods that return a union (including `boolean`), optional members, named members next to an index signature, overloads without parameters, up to 8 overloads, `(...args: unknown[])` methods, and `.throws()` on methods that return `never`. +* Members typed only `null` or `undefined` (`error?: undefined`, `ownerDocument: null`) keep their plain type and no longer have `.returns()` and the other setup methods. Configure them through `sub[configure]()`. +* In generic code, a property typed as the type parameter itself (`current: T`) has no setup API; use `sub[configure]().current.returns(value)`. +* `Arg.any('function')` is typed as any function or class, so it fits typed callback parameters. `Arg.any('object')` is typed `any`, like `Arg.any()` (it was `object`). +* Now supported: optional members (also `sub.received().optionalProperty = undefined`), named members next to an index signature, overloads without parameters, up to 8 overloads, `(...args: unknown[])` methods, `.throws()` on methods that return `never`, `Arg.all()` after other arguments (after up to 6 of them), and types with very large unions of string literals, such as lib.dom's `HTMLInputElement`. * See [Typing limitations](README.md#typing-limitations) for what TypeScript cannot express. diff --git a/README.md b/README.md index 04b1148..92eefa0 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,12 @@ # Table of contents - [Installing](#installing) · [Requirements](#requirements) · [Importing](#importing) -- [Usage](#usage): [creating a substitute](#creating-a-substitute), [return values](#setting-return-values), [promises](#working-with-promises), [exceptions](#throwing-exceptions), [mimicking](#mimicking-an-implementation) -- [Argument matchers](#argument-matchers) and [match order](#match-order) -- [Re-configuring a call](#re-configuring-a-call-configure) · [Partial mocks](#partial-mocks) · [Auto-substitutes](#auto-substitutes-and-nested-members) +- [Usage](#usage): [creating a substitute](#creating-a-substitute), [return values](#setting-return-values), [promises](#working-with-promises), [exceptions](#throwing-exceptions), [mimicking](#mimicking-an-implementation), [members that are a property and a method](#members-used-as-a-property-and-as-a-method) +- [Argument matchers](#argument-matchers), [inside objects and arrays](#matchers-inside-objects-and-arrays), [how arguments are compared](#how-arguments-are-compared) and [match order](#match-order) +- [Re-configuring a call](#re-configuring-a-call-configure) · [Partial mocks](#partial-mocks) · [Auto-substitutes](#auto-substitutes-and-nested-members) and [which calls lead to a setup](#which-calls-lead-to-a-setup-or-a-check) - [Verifying calls](#verifying-calls): [counts](#received-and-didnotreceive), [properties](#properties), [what counts as a call](#what-counts-as-a-call), [clearing](#clearing-received-calls), [SubstituteException](#substituteexception), [deferred failures](#assertions-that-fail-later) -- [Names that conflict with the library](#names-that-conflict-with-the-library) and [the symbol API](#the-symbol-api) -- [Special members](#special-members) · [Typing limitations](#typing-limitations) · [Test runners](#test-runners) +- [Names that conflict with the library](#names-that-conflict-with-the-library), [`call`, `apply` and `bind`](#call-apply-and-bind) and [the symbol API](#the-symbol-api) +- [Special members](#special-members) · [Typing limitations](#typing-limitations) · [Test runners](#test-runners) · [Performance](#performance) # Installing ```sh @@ -26,7 +26,8 @@ npm install @fluffy-spoon/substitute --save-dev This README describes version 2. Until 2.0.1, `npm install` installed 1.208.0 (the `latest` tag). If you depend on version 1, pin it with `npm install @fluffy-spoon/substitute@1 --save-dev`; its README is at the [v1.208.0 tag](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking/tree/v1.208.0#readme). # Requirements -* Node.js 10 or newer for CommonJS (`require`), and Node.js 12.17 or newer for the ES module entry point (`import`). +* Node.js 10 or newer for CommonJS (`require`). +* For the ES module entry point (`import`): Node.js 12.17 or newer on 12.x, 13.7 or newer on 13.x, or 14 or newer. Node.js 10.x, 12.0 to 12.16 and 13.0 to 13.1 have no ES modules without a flag, and 13.2 to 13.6 do not pick the package's ES module entry, so named imports fail there; use `require` on those versions. * TypeScript 3.6 or newer, if you use TypeScript. `strict` mode, including `strictNullChecks`, is supported. * Any test runner. ava, jest, mocha, node:test and vitest are tested on every change (see [Test runners](#test-runners)). @@ -60,7 +61,9 @@ console.log(calculator.add(1, 2)) // prints 3 calculator[received](1).add(1, 2) ``` -The ES module entry point wraps the CommonJS build, so both share one copy of the library. Everything is exported from the package root: `Substitute`, `Arg`, `SubstituteException`, the type `SubstituteOf`, and the symbols `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. Paths inside the package (`@fluffy-spoon/substitute/dist/...`) are not public API and can change in any release. +The ES module entry point wraps the CommonJS build, so both share one copy of the library. Bundlers give the same exports: on every change, the package is bundled with Rollup and `@rollup/plugin-commonjs`, webpack, esbuild and a Vite SSR build with `ssr.noExternal`, and run in vitest with `server.deps.inline`. For esbuild's ES module output for Node.js (`format: 'esm'`, `platform: 'node'`), add the usual banner `import { createRequire } from 'module'; const require = createRequire(import.meta.url);`, because the library loads Node.js' `util` module with `require`. If a tool cannot hand the CommonJS exports to the ES module entry, `import` throws right away with an error that says so; use `require()` with that tool. + +Everything is exported from the package root: `Substitute`, `Arg`, `SubstituteException`, the type `SubstituteOf`, and the symbols `received`, `didNotReceive`, `clearReceivedCalls`, `mimick`, `configure`, `returns`, `throws`, `resolves`, `rejects` and `mimicks`. Paths inside the package (`@fluffy-spoon/substitute/dist/...`) are not public API and can change in any release. # Usage The examples in this README use this interface: @@ -198,7 +201,25 @@ enabled = true console.log(calculator.isEnabled) // prints true ``` -The function is not called with the substitute as `this`. Pass an arrow function or a bound method if the implementation needs `this`. +The function is called with the `this` of the call, like a method: the substitute for `calculator.add(2, 3)`, the first argument of `.call()` and `.apply()`, and `undefined` for a property read or a call through a destructured reference. If the implementation needs `this` to be something else, for example the real instance of a method you pass in, pass an arrow function or a bound method (`realCalculator.add.bind(realCalculator)`). + +## Members used as a property and as a method +A member can be configured both as a method and as a property, for example a member of a callable interface. Calls are answered by the method setups and reads by the property setup. Configure the method first. Once the property answers with a value, `stats.size(...)` is a call of that value, so configure the method through [`configure`](#re-configuring-a-call-configure) then: `stats[configure]().size(Arg.any()).returns(10)`. + +```js +const { Substitute, Arg } = require('@fluffy-spoon/substitute') + +const stats = Substitute.for() +stats.size(Arg.any()).returns(10) +stats.size.returns(3) + +console.log(stats.size('files')) // prints 10 +console.log(stats.size.toFixed(1)) // prints 3.0 +console.log(stats.size.valueOf() + 1) // prints 4 +console.log(stats.size === 3) // prints false +``` + +Because such a member must stay callable, reading it gives a function that stands in for the configured value. Reading a member of it reads that member of the value, and methods read from it run on the value, like `stats.size.toFixed(1)`. If the value is a substitute, it records and answers its own calls. The stand-in itself is not the value, so compare or compute with it through its members, for example `valueOf()`. # Argument matchers There are several ways of matching arguments. They work the same when you set up calls and when you verify them, and they also work for property assignments (`calculator.received().isEnabled = Arg.any()`). @@ -297,24 +318,104 @@ After other arguments, `Arg.all()` matches the rest of the arguments, which can import { Substitute, Arg } from '@fluffy-spoon/substitute' interface Logger { - log(message: string, ...details: unknown[]): void + log(message: string, ...details: string[]): void } const logger = Substitute.for() logger.log('saved') -logger.log('saved', 42, 'extra') -logger.log('deleted', 7) +logger.log('saved', 'id 42', 'extra') +logger.log('deleted', 'id 7') logger.received(2).log('saved', Arg.all()) logger.received(1).log('deleted', Arg.all()) logger.received(3).log(Arg.all()) ``` +## Matchers inside objects and arrays +Matchers also work inside plain objects and arrays, at any depth. An object with a matcher matches an argument with the same keys (in any order), and an array with a matcher matches an array of the same length. Each nested matcher matches by its own rule, and every other value must be [equal](#how-arguments-are-compared). Like any call with a matcher, such a call is a setup or a check, never a received call, and in the [match order](#match-order) it ranks with the other matcher setups. + +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' + +interface User { + id: number + name: string + roles: string[] +} + +interface Repository { + save(user: User): string +} + +const repository = Substitute.for() +repository.save({ id: Arg.any(), name: 'bob', roles: [Arg.is(role => role.startsWith('admin'))] }).returns('saved') + +console.log(repository.save({ id: 1, name: 'bob', roles: ['admin:all'] })) // prints saved +console.log(repository.save({ name: 'bob', roles: ['admin:read'], id: 2 })) // prints saved +// another name, or a second role, does not match +repository.save({ id: 3, name: 'ann', roles: ['admin:all'] }) +repository.save({ id: 4, name: 'bob', roles: ['admin:all', 'user'] }) + +repository.received(2).save({ id: Arg.any(), name: 'bob', roles: [Arg.any()] }) +repository.received(4).save(Arg.all()) +repository.didNotReceive().save({ id: Arg.any(), name: 'bob', roles: [] }) +``` + +* `Arg.all()` as the last item of an array matches the remaining items, also none: `['level', Arg.all()]` matches `['level']` and `['level', 1, 2]`. Anywhere else in an array it is a `SubstituteException`. As the value of a key, `Arg.all()` matches any value, but the key must be there. (In TypeScript, `Arg.all()` inside an object or array does not type-check; use `Arg.any()` for a single value.) +* Only plain objects (created with `{ }` or `Object.create(null)`) and arrays are searched for matchers, and an object with matchers only matches an argument with the same prototype: `{ id: Arg.any() }` does not match a class instance. A matcher inside a class instance, a `Map` or a `Set` is not looked for: it is compared as a value, so such a setup never matches, and the call is an ordinary call. Matchers behind getters are not looked for either. Use `Arg.is()` for the whole argument in these cases. +* `String(sub)` shows nested matchers, for example `save({ id: Arg.any{any}, name: 'bob' }) => returns('saved')`. + +## How arguments are compared +Arguments that are not matchers are compared with deep strict equality, the rule of `assert.deepStrictEqual` (`util.isDeepStrictEqual`). Objects and arrays are equal when they have the same prototype and their own enumerable properties (with string or symbol keys) are equal. `NaN` equals `NaN`, but `0` and `-0` are different, and an invalid `Date` equals nothing, not even another invalid `Date`. Substitutes are compared by identity and never member by member. + +Deep strict equality cannot see `#private` fields or other internal state. So all instances of a class that keeps its state only in `#private` fields are equal to each other. For such classes, pass the same instance, or match with `Arg.is()`: + +```typescript +import { Substitute, Arg } from '@fluffy-spoon/substitute' + +class Money { + #cents: number + constructor(cents: number) { this.#cents = cents } + get cents() { return this.#cents } +} + +interface Bank { + pay(amount: Money): string +} + +const bank = Substitute.for() +bank.pay(new Money(100)).returns('paid') +// all Money instances are equal to each other +console.log(bank.pay(new Money(5))) // prints paid + +const checkedBank = Substitute.for() +checkedBank.pay(Arg.is(amount => amount.cents === 100)).returns('paid') +console.log(checkedBank.pay(new Money(5)) === 'paid') // prints false +console.log(checkedBank.pay(new Money(100))) // prints paid +``` + +Changing an object after you used it as an argument of a setup is not supported. The setup still matches when the code under test passes that same object again, but not a new object that equals it, before or after the change: + +```js +const { Substitute } = require('@fluffy-spoon/substitute') + +const repository = Substitute.for() +const user = { name: 'ann' } +repository.save(user).returns('saved') +user.name = 'bob' + +console.log(repository.save(user)) // prints saved +console.log(repository.save({ name: 'bob' }) === 'saved') // prints false +console.log(repository.save({ name: 'ann' }) === 'saved') // prints false +``` + +Received calls keep the argument objects themselves, so a check compares an argument as it is at the time of the check. If the code under test changes an object after passing it, check its new value. + ## Match order When several setups match a call, the most specific one wins: 1. a setup whose arguments are all literal values, -2. then a setup with at least one `Arg.any()` / `Arg.is()` matcher (or literals followed by `Arg.all()`), +2. then a setup with at least one `Arg.any()` / `Arg.is()` matcher, also inside an object or array (or literals followed by `Arg.all()`), 3. then a setup with `Arg.all()` as its only argument. Among setups of the same kind, the one configured last wins, so a later setup overrides an earlier one. @@ -337,7 +438,11 @@ console.log(calculator.add(200, 3)) // prints 100 ``` ## Re-configuring a call (configure) -Outside of a setup, a call whose literal arguments match an existing setup is a real call: it returns the configured value. A primitive value like `10` has no `.returns()`, so you cannot configure such a call again by writing it out. (If the configured value is an object or a substitute, `.returns()` would even configure that object instead.) +Outside of a setup, a call whose literal arguments match an existing setup is a real call: it returns the configured value. So writing the call out again does not configure it again, and what `.returns()` does then depends on the configured value: + +* A primitive like `10`, a plain object or an array has no `.returns()`, so you get a `TypeError`. +* A substitute that you created with `Substitute.for()` has a member called `returns`, like every other name. `.returns(x)` is recorded as a call of that member, and nothing is configured. Nothing fails, and TypeScript does not catch it either. +* An auto-substitute (an unconfigured member of a substitute) is configured itself: `.returns(x)` configures that member, not the call. Use `sub[configure]()` instead. It gives a view of the substitute in which every call and property read is a setup: it never runs an existing setup and is never recorded as a received call. @@ -361,6 +466,29 @@ console.log(calculator.isEnabled) // prints false Calls with argument matchers are always setups (see [What counts as a call](#what-counts-as-a-call)), so a catch-all setup *after* a specific one needs no `configure`. In TypeScript, the `configure` view only offers the setup methods. +A setup in the `configure` view can go through a member or a call that already answers with a value. If that value is a substitute, the setup goes to that substitute, which keeps its other setups. If it is a real value (a plain object, an array, a primitive), or the member is configured with `throws()`, `resolves()`, `rejects()` or `mimicks()`, its members cannot be configured, and the setup throws a `SubstituteException` that says so. Nothing is replaced in that case. Members and calls that do not answer with a value yet are configured as usual. + +```js +const { Substitute, configure } = require('@fluffy-spoon/substitute') + +const repository = Substitute.for() +repository.find(2).returns('two') + +const container = Substitute.for() +container.getRepository().returns(repository) + +// getRepository() answers with a substitute, so the setup goes to that substitute +container[configure]().getRepository().find(1).returns('one') +console.log(container.getRepository() === repository) // prints true +console.log(repository.find(1)) // prints one +console.log(repository.find(2)) // prints two + +container.settings.returns({ port: 80 }) +container[configure]().settings.port.returns(1) // throws SubstituteException: settings returns { port: 80 }, which is not a substitute +``` + +For a call without matchers, the setup that answers the call counts, also a matcher setup: after `lookup.get(Arg.any()).returns(repository)`, `lookup[configure]().get(5).find(3).returns('three')` configures `repository.find(3)`. + # Partial mocks With partial mocks you always start with a true substitute where everything is mocked, and then opt out of substitutions in certain scenarios: per call with `mimicks()`, or for a whole instance with `[mimick]()`. The examples use this implementation: @@ -398,7 +526,7 @@ console.log(calculator.divide(10, 2)) // prints 5 console.log(calculator.divide(10, 5)) // prints 1338 ``` -`sub[mimick](instance)` hands everything that is not configured to a real instance: property reads return the instance's values, method calls run the instance's methods (with `this` being the instance), and assignments write to the instance. Members that the instance does not have read as `undefined`. Setups still win, and every call is recorded, so you can verify it. Because real calls are passed on to the instance, configure a mimicked substitute through [`[configure]()`](#re-configuring-a-call-configure). +`sub[mimick](instance)` hands everything that is not configured to a real instance: property reads return the instance's values, method calls run the instance's methods (with `this` being the instance, unless you pass another one with `.call()` or `.apply()`), and assignments write to the instance. If the instance is a function, calling the substitute calls it, with the `this` of the call. Members that the instance does not have read as `undefined`. Setups still win, and every call is recorded, so you can verify it. Because real calls are passed on to the instance, configure a mimicked substitute through [`[configure]()`](#re-configuring-a-call-configure). ```typescript @@ -420,6 +548,8 @@ calculator.received().add(2, 3) calculator.received().isEnabled = false ``` +In the `configure` view, a setup through a member of the instance whose value is a substitute goes to that substitute, and from then on the member reads as that substitute. The members of a real value of the instance cannot be configured: with `sub[mimick]({ settings: { port: 80 } })`, `sub[configure]().settings.port.returns(1)` throws a `SubstituteException`. Configure the whole member instead: `sub[configure]().settings.returns({ port: 1 })`. A setup through a method of the instance, like `sub[configure]().load().size.returns(1)`, does not run the real method. It creates a setup for `load()`, which from then on answers that call instead of the instance. + The string `mimick` is not part of the API (any more): `sub.mimick(...)` is an ordinary member, like every name except the [conflicting names](#names-that-conflict-with-the-library). # Auto-substitutes and nested members @@ -442,7 +572,7 @@ app.logger.received().info('started') app.logger.didNotReceive().info('stopped') ``` -Setups and calls never leak between members: `app.add(1, 2).returns(99)` does not configure `app.getCalculator().add(1, 2)`, and the other way round. The calls in a setup or an assertion (`app.getCalculator()` above) are not recorded as received calls. +Setups and calls never leak between members: `app.add(1, 2).returns(99)` does not configure `app.getCalculator().add(1, 2)`, and the other way round. **Typing limitation:** in TypeScript, nested auto-substitutes are typed as plain values, not as substitutes, so `app.getCalculator().add(1, 2).returns(99)` and `app.logger.received()` do not compile. They do work at runtime (in JavaScript, or through a cast). In TypeScript, configure the member to return a substitute you create yourself; that is fully typed: @@ -469,6 +599,34 @@ app.logger.info('started') logger.received().info('started') ``` +## Which calls lead to a setup or a check +The reads and calls that lead up to a setup or a check in the same expression, like `app.getCalculator()` in `app.getCalculator().add(1, 2).returns(99)`, are part of that setup or check, so they are not recorded as received calls. A value that the code under test got from a substitute keeps the call that returned it, though, so you can configure or check that value and still verify how the code under test got it: + +```js +const { Substitute } = require('@fluffy-spoon/substitute') + +// the code under test +function openConnection(driver) { + return driver.connect('db://test') +} + +const driver = Substitute.for() +const connection = openConnection(driver) +connection.isOpen.returns(true) + +console.log(connection.isOpen) // prints true +driver.received(1).connect('db://test') +driver.didNotReceive().connect('db://test') // throws SubstituteException +``` + +The library tells the two apart by where they happen: the reads and calls before a setup or a check are left out only when they were made in the same file and the same function as the setup or check. (It compares the first stack frame outside the library: the position of the enclosing function, or on Node.js before 14.18 its name.) So: + +* A chain written over several lines, or in a helper function of your own, is one setup or check. +* A handle that you store and use in the same function is part of the setup: after `const logger = app.logger` and `logger.level.returns(3)`, the read of `app.logger` is not recorded. +* A handle that you get in one function and use in another one keeps the reads that produced it. For example, after `const click = app.handlers.click` in a test, `t.notThrows(() => click.received(1).fire())` runs the check in a callback, so the reads of `handlers` and `click` stay recorded, and `app.didNotReceive().handlers` would fail. +* Calls that the code under test makes in its own functions are kept. +* Without stack frames (`Error.stackTraceLimit = 0`), only position decides: a setup or check right after the call that returned its value, with no other use of a substitute in between, leaves that call out. + # Verifying calls ## received and didNotReceive `received()` checks that a call was received at least once, `received(count)` that it was received exactly `count` times, and `didNotReceive()` that it was never received. A failed check throws a [`SubstituteException`](#substituteexception). @@ -513,6 +671,27 @@ All property or method calls to @Substitute.add received so far: called at Object. (test/calculator.test.ts:2:12) ``` +When the member was never used at all, the check fails as soon as it reads the member, before the arguments are known, so the message cannot name them: `Expected to receive 1 or more property reads or method calls matching add, but received none.` Once the method has been called, the message names the expected arguments, as above. + +A method that was read but never called fails a method check right away with the reads listed, and a hint: + + +```typescript +// the code under test registers a handler, which never fires +const handler = calculator.subtract +calculator.received(2).subtract(5, 1) // throws SubstituteException +``` + + +```text +SubstituteException: Call count mismatch in @Substitute.subtract: +Expected to receive 2 property reads or method calls matching subtract, but received 1 property read and no method calls. +All property or method calls to @Substitute.subtract received so far: +› ✘ @Substitute.subtract + called at Object. (test/calculator.test.ts:2:28) +@Substitute.subtract was read 1 time without being called; reading a method does not count as calling it. +``` + The message contains ANSI colours only when the output is a terminal. `NO_COLOR`, `NODE_DISABLE_COLORS` and `TERM=dumb` turn colours off, and `FORCE_COLOR` turns them on. ## Properties @@ -532,12 +711,14 @@ calculator.received(1).isEnabled = Arg.any() calculator.didNotReceive().isEnabled = false ``` -In TypeScript, assigning a property on the substitute itself (`calculator.isEnabled = true`) does not compile, see [Typing limitations](#typing-limitations). The code under test assigns through its own type, like `toggle` above. +In TypeScript, assigning a property on the substitute itself (`calculator.isEnabled = true`) does not compile, see [Typing limitations](#typing-limitations). The code under test assigns through its own type, like `toggle` above. In a check, read-only properties can be assigned, and optional properties accept `undefined` (`form.received().note = undefined`). ## What counts as a call -* Every invocation is a call of its own, also through a stored or destructured reference, a callback, or `.call()` / `.apply()` / `.bind()`. +* Every invocation is a call of its own, also through a stored or destructured reference or a callback. +* `.call()`, `.apply()` and `.bind()` work on a method, a function substitute and every other substitute value as on a function: `calculator.subtract.call(undefined, 5, 1)` returns what `calculator.subtract(5, 1)` is configured to return, and counts as a call `subtract(5, 1)`. It counts as a call of a member called `call` as well; see [`call`, `apply` and `bind`](#call-apply-and-bind). * Reading a method without calling it, for example to register it as an event handler that never fires, is not a call. Method checks (`received().subtract(...)`, also with `Arg.all()`) only count invocations. -* A call with an argument matcher (`Arg.any()`, `Arg.is()`, `Arg.all()`, also with `.not`) is a setup or a check, never a received call. It does not run an existing setup either. +* A call with an argument matcher (`Arg.any()`, `Arg.is()`, `Arg.all()`, also with `.not`, also [inside an object or array](#matchers-inside-objects-and-arrays)) is a setup or a check, never a received call. It does not run an existing setup either. +* The reads and calls that lead up to a setup or a check in the same expression are not recorded; see [Which calls lead to a setup or a check](#which-calls-lead-to-a-setup-or-a-check). * Checks never run setups or mimicked implementations, and are never recorded themselves. Checking a property configured with `throws()` does not throw, and checking a property configured with a sequence does not use up a value. @@ -549,6 +730,10 @@ calculator.received(3).add(Arg.all()) const handler = calculator.subtract calculator.received().subtract(Arg.all()) // throws SubstituteException +calculator.subtract(5, 1).returns(4) +console.log(calculator.subtract.call(undefined, 5, 1)) // prints 4 +calculator.received(1).subtract(5, 1) + calculator.divide(Arg.any(), 2) // a setup without a value, not a call calculator.didNotReceive().divide(Arg.all()) ``` @@ -556,7 +741,7 @@ calculator.didNotReceive().divide(Arg.all()) **Known issue in 2.0.1:** `didNotReceive().subtract(...)` (or `received(0)`) on a method that has been read but never called fails, because the library decides at `.subtract` whether you check a property read or a method call. If the code under test registers a method without calling it, clear the received calls after that (see below) before you check that it was not called. ## Clearing received calls -`sub[clearReceivedCalls]()` forgets the received calls of a substitute and of its auto-substitutes. Setups are kept, including the position in a sequence of return values. To start over completely, create a new substitute. +`sub[clearReceivedCalls]()` forgets the received calls of a substitute and of its auto-substitutes. Setups are kept, including the position in a sequence of return values, and so are the auto-substitutes (`app.logger` stays the same object). To start over completely, create a new substitute. ```typescript @@ -585,7 +770,12 @@ try { ``` ## Assertions that fail later -Checks throw right away, with one exception. In a property-style check, `sub.received(count).member` that is not followed by a call, on a member that has been called as a method, the library cannot know yet whether you are about to call it (`sub.received(2).member(...)`). If the property check fails, the failure is reported on `process.nextTick`, and it is cancelled if you call the member. Such a failure escapes `try`/`catch` and `t.throws()`. Test runners report it as an uncaught exception in the running test. +Checks throw right away, with one exception: a property-style check, `sub.received(count).member` or `sub.didNotReceive().member` that is not followed by a call, on a member that has been called as a method. The library cannot know yet whether you are about to call it (`sub.received(2).member(...)`), so it reports the failure on `process.nextTick`, and cancels the report if you call the member. There are two cases: + +* The property check fails, as in `calculator.received(2).add` below. +* `didNotReceive().member` or `received(0).member` on a member that was only called, never read: it would pass as a property check, but the parentheses were probably forgotten. The report says so: `Expected to receive 0 property reads or method calls matching add, but received 1 method call. add was called 1 time as a method; to assert calls, invoke it: sub.didNotReceive().add(...)`. + +Such a failure escapes `try`/`catch` and `t.throws()`. Test runners report it as an uncaught exception in the running test. ```typescript @@ -598,14 +788,26 @@ calculator.add(3, 4) calculator.received(2).add ``` + +```typescript +calculator.add(1, 2) + +// the parentheses are missing: reported later, on process.nextTick +calculator.didNotReceive().add +``` + To avoid this, check methods with a call (`calculator.received(2).add(1, 2)`, or `.add(Arg.all())`). Those are decided right away. +The report is scheduled with the `process.nextTick` that the library found when it was loaded, so fake timers that are installed later, such as `jest.useFakeTimers()` in a test or `@sinonjs/fake-timers` faking `nextTick`, do not hold it back. Fake timers that replace `process.nextTick` before the library is loaded, for example jest's `fakeTimers: { enableGlobally: true }` configuration or a setup file that installs them before the library is imported, can delay the report until the fake clock runs. + # Names that conflict with the library -A substituted type may have members with the same names as the library's methods: `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`. Each of them has a symbol (exported from the package) that always means the library method. +A substituted type may have members with the same names as the library's methods: `received`, `didNotReceive`, `returns`, `throws`, `resolves`, `rejects` or `mimicks`. Each of them has a symbol (exported from the package) that always means the library method. Members called `call`, `apply` or `bind` need care too, because every function has them; see [`call`, `apply` and `bind`](#call-apply-and-bind). ## In TypeScript If the substituted type has a member with one of these names, `sub.received()` and `sub.didNotReceive()` are not offered, because they would be ambiguous. Use the symbols `sub[received]()` and `sub[didNotReceive]()`; they are always available. +In generic code, the type parameter's constraint decides. A type parameter without a constraint gets the string forms: `sub.received()` and `sub.didNotReceive()` are offered on `SubstituteOf`, and the setup methods on calls that return `T`. For `T extends Account`, where `Account` has a member called `returns`, only the symbols are offered, as for `Account` itself. + ```typescript import { Substitute, Arg, received } from '@fluffy-spoon/substitute' @@ -653,6 +855,31 @@ console.log(shop.find('1').total()) // prints 42 At runtime, `.returns`, `.throws`, `.resolves`, `.rejects` and `.mimicks` on a member or call that is *not* configured always mean the setup methods. So if the code under test uses a member with one of these names on a value it gets from a substitute, configure that value first, as `shop.find('1')` above. + +```typescript +import { Substitute, SubstituteOf, Arg } from '@fluffy-spoon/substitute' + +interface Repository { + get(id: string): T +} + +function stubGet(repository: SubstituteOf>, value: T) { + repository.get(Arg.any()).returns(value) +} + +function receivedOnce(sub: SubstituteOf) { + return sub.received(1) +} +``` + + +```typescript +const users = Substitute.for>() +stubGet(users, 'ann') +console.log(users.get('1')) // prints ann +receivedOnce(users).get('1') +``` + `clearReceivedCalls`, `mimick` and `configure` exist only as symbols, so members with those names never conflict. ## In JavaScript @@ -660,6 +887,7 @@ Without types, the library decides by how a name is used: * `sub.received(...)` and `sub.didNotReceive()` are checks when they are called and followed by a member, like `sub.received(2).add(1, 2)`. Followed by `.returns()`, `.throws()`, `.resolves()`, `.rejects()` or `.mimicks()`, they configure a member of your own called `received` or `didNotReceive`. * `sub.received` that is not called is an ordinary member, so the code under test can read a property called `received`. +* `sub.received(count)` or `sub.didNotReceive()` followed directly by a call checks a call of the substitute itself: `listener.received(1)('saved')` checks that the function substitute `listener` was called with `'saved'`. On a member, `sub.method.received(1)(5)` checks the calls `sub.method(5)`. * The symbols `sub[received]()` and `sub[didNotReceive]()` are always checks. Use them to check members called `returns`, `throws`, `resolves`, `rejects` or `mimicks`. ```js @@ -674,6 +902,46 @@ builder.returns(5) // the code under test calls its own `returns` method builder[received]().returns(5) ``` +## call, apply and bind +Every function has `call`, `apply` and `bind`, and a substituted object can have members with these names of its own, like the `call(method, ...args)` of an RPC client or the `bind(port)` of a socket. On every substitute value that can be called (a substitute, a member like `sub.method`, the result of a call, a nested auto-substitute), `x.call`, `x.apply` and `x.bind` therefore give a helper that handles both meanings: + +* If a setup for a member called `call`, `apply` or `bind` matches the arguments as they are, it answers. Such a setup comes from `x.call('getUser', 1).returns(user)`, from the `configure` view, or from a mimicked instance with such a member. +* Otherwise the helper works like the function's own `call`, `apply` and `bind`: it returns what `x(...arguments)` is configured to return, and a mimicked function or a `mimicks()` function gets the first argument as `this`. + +Either way, the invocation is recorded once and counts in both meanings: as a call of the member (`x.received().call('getUser', 1)`) and as a direct call of `x` (`x[received]()(1)`, or `sub.received().method(1)` when `x` is `sub.method`). `String(sub)` and failure messages show it once, for example `rpc(1) via .call('getUser', 1)`. A setup written through `call`, `apply` or `bind` only configures the member: `client.rpc.call('getUser', 1).returns(user)` does not answer `client.rpc.call('deleteUser', 1)` or `client.rpc(1)`. + +```js +const { Substitute, received } = require('@fluffy-spoon/substitute') + +// an RPC client with a member called call +const client = Substitute.for() +client.rpc.call('getUser', 1).returns({ name: 'ann' }) +console.log(client.rpc.call('getUser', 1)) // prints { name: 'ann' } +client.rpc.received(1).call('getUser', 1) +// the same invocation, read as rpc(1) with 'getUser' as this +client.received(1).rpc(1) + +// a function substitute that a helper calls through apply() +const once = fn => { + let done = false + return function (...args) { + if (!done) { + done = true + return fn.apply(this, args) + } + } +} +const listener = Substitute.for() +listener('saved').returns('ack') +console.log(once(listener)('saved')) // prints ack +listener[received](1)('saved') +``` + +* `x.bind(thisArg, ...arguments)` itself only counts as a call of a member called `bind`. Calling the function it returns is a direct call of `x`, with the bound arguments first. `.returns()` on the result of `x.bind(...)` configures the member `bind`. +* `x.apply(thisArg, value)` with a primitive `value` only has the member meaning, because a function's `apply` would throw. +* A member `call`, `apply` or `bind` configured as a property (`sub[configure]().call.returns(value)`) reads as that value. A substitute that mimicks an object without such a member reads it as `undefined`, like the object. +* In the `configure` view, `call`, `apply` and `bind` are ordinary members. + # The symbol API All of these are exported from the package root. @@ -705,6 +973,37 @@ async function load() { return calculator } load().then(loaded => console.log(loaded === calculator)) // prints true ``` +JavaScript, Node.js and test libraries read some members to find out what a value is. Unless you configure them, these read as `undefined` on every substitute and auto-substitute, and the reads are not recorded: + +* `Symbol.iterator`, `Symbol.asyncIterator`, `Symbol.hasInstance`, `Symbol.isConcatSpreadable`, `Symbol.match`, `Symbol.matchAll`, `Symbol.replace`, `Symbol.search`, `Symbol.split`, `Symbol.species`, `Symbol.toStringTag` and `Symbol.unscopables`, +* `util.promisify.custom` (`Symbol.for('nodejs.util.promisify.custom')`), +* `asymmetricMatch`, which jest reads to find asymmetric matchers. + +So `[].concat(sub)` keeps the substitute as one element, `value instanceof sub.SomeClass` is `false`, `'text'.startsWith(sub.prefix)` works, `util.promisify(sub.readFile)` calls the substitute (so a `mimicks()` setup that calls the callback works), `Object.prototype.toString.call(sub)` is `'[object Function]'`, and jest's `toEqual(sub)` and `toHaveBeenCalledWith(sub)` compare a substitute by identity, like any other function. A substitute is not iterable: `[...sub]`, `for...of`, `for await...of` and `Promise.all(sub)` throw a `TypeError`. + +Unlike `then`, these members can be configured, through the `configure` view or by mimicking an instance that has them. The plain `sub[Symbol.iterator]().returns(...)` does not work, because the read gives `undefined`. + +```js +const { Substitute, configure, mimick } = require('@fluffy-spoon/substitute') + +const empty = Substitute.for() +console.log([].concat(empty).length) // prints 1 +const spread = () => [...empty] +spread() // throws TypeError + +const numbers = Substitute.for() +numbers[configure]()[Symbol.iterator]().mimicks(() => [1, 2][Symbol.iterator]()) +console.log([...numbers]) // prints [ 1, 2 ] + +const letters = Substitute.for() +letters[mimick](['a', 'b']) +console.log([...letters]) // prints [ 'a', 'b' ] + +const tagged = Substitute.for() +tagged[configure]()[Symbol.toStringTag].returns('Tagged') +console.log(Object.prototype.toString.call(tagged)) // prints [object Tagged] +``` + # Typing limitations TypeScript cannot express a few things about substitutes: @@ -713,12 +1012,18 @@ TypeScript cannot express a few things about substitutes: * **A generic method called with explicit type arguments** (`store.get('answer')`) has no setup API. Call it without type arguments. * **Overloads whose parameters have literal types** (`on(event: 'data', ...)`) resolve to the interface's own declaration when you call them directly. Configure them with `sub[configure]().on('data', ...)`. * **More than 8 overloads:** only the last 8 have the setup API. -* **A property typed `never`** cannot be configured. +* **A property typed `never`** cannot be configured. On a method that returns `never`, `.returns()` only accepts `never`; use `.throws()`. +* **Members typed only `null` or `undefined`** (`error?: undefined`, `ownerDocument: null`) keep their plain type and have no setup API. Configure them through `sub[configure]()`. +* **Generic code:** a property whose type is the type parameter itself (`current: T`, also `current?: T` or `T | undefined`) has no setup API; configure it with `sub[configure]().current.returns(value)`. Properties of types like `T[]` or `Promise`, and calls that return `T`, are fine. The result of a call on the substitute (`box.get('a')`) is not assignable to `T` in generic code; read it through the plain interface type, or cast it. +* **A union of object types whose variants declare each other's members as `?: undefined`**, like `{ ok: true, data: string, error?: undefined } | { ok: false, data?: undefined, error: Error }`, turns `Substitute.for<...>()` into `never`. Substitute one variant (`Substitute.for()`) instead. Other unions, such as `Cat | Dog`, work. +* **`Arg.all()` after other arguments** type-checks after up to 6 of them. It does not type-check with arguments after it (which is an error at runtime, too), after the last parameter of a fixed parameter list (`add(1, 2, Arg.all())`), or inside an object or array. Editors show the signatures that accept it with parameters named `arg0`, `arg1`, and so on. +* **`Arg.any('object')`** is typed `any`, like `Arg.any()`, so the compiler does not check it against the parameter. `Arg.any('function')` is typed as any function or class. +* **Optional properties of a type with a string index signature** do not accept `undefined` in a check (`sub.received().note = undefined`). Without an index signature, they do. * **Nested auto-substitutes** are not typed as substitutes, see [Auto-substitutes](#auto-substitutes-and-nested-members). ```typescript -import { configure } from '@fluffy-spoon/substitute' +import { configure, SubstituteOf } from '@fluffy-spoon/substitute' // @ts-expect-error the property's type carries the setup API calculator.isEnabled = true @@ -749,10 +1054,28 @@ interface Socket { const socket = Substitute.for() socket[configure]().on('data', Arg.any()).returns(socket) console.log(socket.on('data', () => { }) === socket) // prints true + +interface Box { + current: T + items: T[] + get(key: string): T +} +function stubBox(box: SubstituteOf>, value: T) { + box.get(Arg.any()).returns(value) + box.items.returns([value]) + // @ts-expect-error a property typed as the type parameter itself has no setup API + box.current.returns(value) + box[configure]().current.returns(value) +} +const box = Substitute.for>() +stubBox(box, 7) +console.log(box.current) // prints 7 ``` # Test runners -Checks throw a `SubstituteException`, so they work with any test runner: a failed check fails the test, and you can expect one with your runner's `throws` assertion. ava, jest, mocha, node:test and vitest are tested on every change, including a check that [fails later](#assertions-that-fail-later), which each of them reports as a failure. +Checks throw a `SubstituteException`, so they work with any test runner: a failed check fails the test, and you can expect one with your runner's `throws` assertion. ava, jest, mocha, node:test and vitest (also with the package inlined through `server.deps.inline`) are tested on every change, including a check that [fails later](#assertions-that-fail-later), which each of them reports as a failure. Fake timers that a test installs do not hold back such a report; see [Assertions that fail later](#assertions-that-fail-later) for fake timers that are installed before the library is loaded. + +Substitutes can be passed to your runner's own assertions: jest's `toEqual(sub)`, `toContainEqual(sub)` and `toHaveBeenCalledWith(sub)` compare substitutes by identity: a substitute only equals itself (see [Special members](#special-members)). ```typescript import { test } from 'node:test' @@ -788,6 +1111,11 @@ test('adds the numbers', t => { }) ``` +# Performance +Finding the setup and the auto-substitute for a call does not scan earlier calls, and takes about the same time whatever the shape of the arguments: nested objects, long arrays, `Buffer`s and typed arrays, long strings, `Map`s, `Set`s or `Date`s. Measured on Node.js 22, 10,000 calls with nested-object arguments take about 0.1 to 0.2 seconds, and so do 4,000 setups with object arguments plus 4,000 matching calls. + +Each received call is kept until [`[clearReceivedCalls]()`](#clearing-received-calls), at about 300 bytes per call (measured on Node.js 22, 64-bit). A distinct unconfigured call also keeps its auto-substitute, about 200 bytes more, for as long as the substitute lives, so that the same call always returns the same auto-substitute; `[clearReceivedCalls]()` keeps those. Symbols passed as arguments are not kept alive by the library once the substitute is gone. + # Benefits over other mocking libraries - Easier-to-understand fluent syntax. - No need to cast to `any` in certain places (for instance, when overriding read-only properties) due to the `myProperty.returns(...)` syntax. From 6cb1c229e77b7891a4c6353465b492cf41e41fa9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:23:24 +0000 Subject: [PATCH 056/106] test(hashing): do not pin Node.js's own isDeepStrictEqual rules; follow them in the README Node.js 24 changed util.isDeepStrictEqual: two invalid Dates are now equal, and two cyclic objects whose cycles have a different shape are no longer equal. The hashing test asserted the Node.js 22 behaviour, so npm test failed on the Node.js 24 and 26 CI entries. It now only checks that the hash agrees with whatever the running Node.js decides, and the README says the library follows the running version. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- README.md | 2 +- spec/regression/fixes/round3-hashing.test.ts | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 92eefa0..a2e98ad 100644 --- a/README.md +++ b/README.md @@ -366,7 +366,7 @@ repository.didNotReceive().save({ id: Arg.any(), name: 'bob', roles: [] }) * `String(sub)` shows nested matchers, for example `save({ id: Arg.any{any}, name: 'bob' }) => returns('saved')`. ## How arguments are compared -Arguments that are not matchers are compared with deep strict equality, the rule of `assert.deepStrictEqual` (`util.isDeepStrictEqual`). Objects and arrays are equal when they have the same prototype and their own enumerable properties (with string or symbol keys) are equal. `NaN` equals `NaN`, but `0` and `-0` are different, and an invalid `Date` equals nothing, not even another invalid `Date`. Substitutes are compared by identity and never member by member. +Arguments that are not matchers are compared with deep strict equality, the rule of `assert.deepStrictEqual` (`util.isDeepStrictEqual`). Objects and arrays are equal when they have the same prototype and their own enumerable properties (with string or symbol keys) are equal. `NaN` equals `NaN`, but `0` and `-0` are different. Where Node.js changed the rule, the library follows the running version: two invalid `Date`s are different up to Node.js 22 and equal from Node.js 24 on, and two cyclic objects whose cycles have a different shape are equal up to Node.js 22 and different from Node.js 24 on. Substitutes are compared by identity and never member by member. Deep strict equality cannot see `#private` fields or other internal state. So all instances of a class that keeps its state only in `#private` fields are equal to each other. For such classes, pass the same instance, or match with `Arg.is()`: diff --git a/spec/regression/fixes/round3-hashing.test.ts b/spec/regression/fixes/round3-hashing.test.ts index 37af1ce..5c5aa81 100644 --- a/spec/regression/fixes/round3-hashing.test.ts +++ b/spec/regression/fixes/round3-hashing.test.ts @@ -154,7 +154,11 @@ test('ENG2-2 (D35) the structural hash: special values, and values that cannot b same(new Map([[{ k: 1 }, 'a']]), new Map([[{ k: 1 }, 'a']]), 'Map object keys') same(new Set([1, { a: 2 }]), new Set([{ a: 2 }, 1]), 'Set order') same(new Date(5), new Date(5), 'Dates') - t.false(isDeepStrictEqual(new Date(NaN), new Date(NaN)), 'invalid Dates are never equal') + // Node.js changed this in 24: two invalid Dates are unequal up to Node.js 22 and equal from 24 on. The hash only + // has to agree with whatever the running Node.js decides. + if (isDeepStrictEqual(new Date(NaN), new Date(NaN))) { + t.is(structuralHash(new Date(NaN)), structuralHash(new Date('nope')), 'invalid Dates, where Node.js finds them equal') + } same(/x/gi, new RegExp('x', 'gi'), 'RegExps') same(Buffer.from('abc'), Buffer.from('abc'), 'Buffers') same(new Float64Array([-0, NaN]), new Float64Array([-0, NaN]), 'typed arrays') @@ -182,7 +186,7 @@ test('ENG2-2 (D35) the structural hash: special values, and values that cannot b cyclic.self = cyclic const longer: any = { name: 'a', self: { name: 'a' } } longer.self.self = longer - t.true(isDeepStrictEqual(cyclic, longer)) + // Node.js up to 22 finds these two equal, Node.js 24 and later do not; the hash must agree in both cases t.is(structuralHash(cyclic), FALLBACK_HASH) t.is(structuralHash(longer), FALLBACK_HASH) const throwing = { get value(): never { throw new Error('getter') } } From 3fd35c2ef00e087885dce1f9611c8c5d5a4cd00f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:52:39 +0000 Subject: [PATCH 057/106] fix(hashing): bound the cost of the structural hash per argument (E3) Arguments with a cycle all got FALLBACK_HASH, and native errors (whose name and message are not enumerable) all got one hash, so unconfigured calls with them compared against every earlier call (R3-ADV-2, R3-1). Long strings, shared-subtree objects and very long arrays were hashed in full. The hash now has a budget of objects per argument, shared evenly among the values each object hashes, and a depth limit: deeper objects give a constant tag, so cycles simply end there. Long arrays, strings and byte arrays are sampled by position; wide objects and large Maps and Sets contribute every entry shallowly. No limit depends on key or entry order. Native errors mix in the name, message, cause and errors that the running Node.js compares, decided once at load. FALLBACK_HASH stays for values that cannot be read. The search for matchers nested in arguments (D27) is bounded the same way. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round3-hashing.test.ts | 10 +- spec/regression/fixes/round4-hashing.test.ts | 352 +++++++++++++++++++ src/internals/RecordedArguments.ts | 48 ++- src/internals/utilities/ArgumentHash.ts | 296 ++++++++++------ 4 files changed, 584 insertions(+), 122 deletions(-) create mode 100644 spec/regression/fixes/round4-hashing.test.ts diff --git a/spec/regression/fixes/round3-hashing.test.ts b/spec/regression/fixes/round3-hashing.test.ts index 5c5aa81..02f4ade 100644 --- a/spec/regression/fixes/round3-hashing.test.ts +++ b/spec/regression/fixes/round3-hashing.test.ts @@ -186,9 +186,10 @@ test('ENG2-2 (D35) the structural hash: special values, and values that cannot b cyclic.self = cyclic const longer: any = { name: 'a', self: { name: 'a' } } longer.self.self = longer - // Node.js up to 22 finds these two equal, Node.js 24 and later do not; the hash must agree in both cases - t.is(structuralHash(cyclic), FALLBACK_HASH) - t.is(structuralHash(longer), FALLBACK_HASH) + // Node.js up to 22 finds these two equal, Node.js 24 and later do not; the hash must agree in both cases. + // Round 4 (E3): cycles end at the depth limit instead of giving FALLBACK_HASH, and both unroll to the same tree. + t.not(structuralHash(cyclic), FALLBACK_HASH) + t.is(structuralHash(cyclic), structuralHash(longer)) const throwing = { get value(): never { throw new Error('getter') } } t.is(structuralHash(throwing), FALLBACK_HASH) t.is(hashArguments([1, throwing]), FALLBACK_HASH) @@ -197,7 +198,8 @@ test('ENG2-2 (D35) the structural hash: special values, and values that cannot b t.is(structuralHash(proxy), FALLBACK_HASH) const wide: any[] = [] for (let index = 0; index < 20; index++) wide.push(wide.length === 0 ? {} : [wide[index - 1], wide[index - 1]]) - t.is(structuralHash(wide[19]), FALLBACK_HASH, 'more nested objects than the limit (through shared references)') + // round 4 (E3): more nested objects than the budget (through shared references) are cut, not given FALLBACK_HASH + t.not(structuralHash(wide[19]), FALLBACK_HASH, 'more nested objects than the budget (through shared references)') // substitutes and functions by identity, never traversed const substitute = Substitute.for() diff --git a/spec/regression/fixes/round4-hashing.test.ts b/spec/regression/fixes/round4-hashing.test.ts new file mode 100644 index 0000000..17374f7 --- /dev/null +++ b/spec/regression/fixes/round4-hashing.test.ts @@ -0,0 +1,352 @@ +import test, { ExecutionContext } from 'ava' +import { isDeepStrictEqual, types } from 'util' + +import { Substitute, Arg } from '../../../src' +import { FALLBACK_HASH, hashArguments, structuralHash } from '../../../src/internals/utilities/ArgumentHash' +import { RecordedArguments } from '../../../src/internals/RecordedArguments' + +// Round 4, E3 (R3-ADV-2, R3-1): the structural hash costs a bounded amount per argument, whatever its size or shape, +// and it still never separates values that the RUNNING Node.js finds deep strictly equal. Only that agreement is +// asserted: Node.js itself changed its rules (invalid Dates and cycles of a different shape, errors' cause). + +/** A small deterministic PRNG (mulberry32), so that a failure can be reproduced. */ +const random = (seed: number) => () => { + seed = (seed + 0x6d2b79f5) | 0 + let t = Math.imul(seed ^ (seed >>> 15), 1 | seed) + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 +} +type Next = () => number + +class Point { constructor(public x: unknown, public y: unknown) { } } + +const Aggregate = (globalThis as any).AggregateError as (new (errors: unknown[], message: string) => Error) | undefined +const sharedSymbols = [Symbol('a'), Symbol.for('registered')] +const sharedFunctions = [() => 1, Substitute.for()] +const middle = (char: string, half: number) => 'm'.repeat(half) + char + 'm'.repeat(half) + +/** Builds an object with these entries, in a random insertion order. */ +const objectOf = (next: Next, entries: Array<[PropertyKey, unknown]>): Record => { + const result: Record = {} + for (const [key, value] of shuffle(next, entries)) result[key as any] = value + return result +} + +const shuffle = (next: Next, items: T[]): T[] => { + for (let index = items.length - 1; index > 0; index--) { + const other = Math.floor(next() * (index + 1)) + ;[items[index], items[other]] = [items[other], items[index]] + } + return items +} + +/** + * Values from small domains, so that independently generated values are often deep strictly equal: with keys inserted + * in other orders, cycles of other shapes, other identities. + */ +const generate = (next: Next, depth: number): unknown => { + const pick = (items: readonly T[]): T => items[Math.floor(next() * items.length)] + const leaf = () => pick<() => unknown>([ + () => undefined, () => null, () => next() < 0.5, () => pick([0, -0, 1, NaN, 1.5]), + () => pick(['', 'a', 'b']), + // long strings that differ only in the middle, hashed in full and sampled + () => middle(pick(['a', 'b']), 1500), () => middle(pick(['a', 'b']), 6000), + () => pick(sharedSymbols), () => pick(sharedFunctions), + // invalid Dates: Node.js 24 and later find two of them equal, earlier versions do not + () => new Date(pick([0, 1, NaN])), + // errors: the same or another message, other classes, extra properties, a cause + () => new (pick([Error, TypeError]))(pick(['a', 'b'])), + () => Object.assign(new Error(pick(['a', 'b'])), { code: pick([1, 2]) }), + () => new (Error as any)('a', { cause: pick([1, 2, undefined]) }), + () => Aggregate === undefined ? new Error('a') : new Aggregate([pick([1, 2])], 'a'), + () => Buffer.from(pick(['', 'ab'])) + ])() + if (depth <= 0 || next() < 0.3) return leaf() + const size = Math.floor(next() * 3) + const child = () => generate(next, depth - 1) + return pick<() => unknown>([ + () => Array.from({ length: size }, child), + () => objectOf(next, Array.from({ length: size }, (_, index): [PropertyKey, unknown] => [pick(['a', 'b', 'c']) + index, child()])), + () => objectOf(next, [[pick(sharedSymbols), child()], ['plain', size]]), + () => new Point(child(), child()), + () => new Map(shuffle(next, Array.from({ length: size }, (_, index): [unknown, unknown] => [index % 2 === 0 ? index : { key: index }, child()]))), + () => new Set(shuffle(next, Array.from({ length: size }, child))), + // cycles of several shapes: a self reference, a child-to-parent back-reference, a cycle through two objects + () => { const node: any = objectOf(next, [['name', pick(['a', 'b'])]]); node.self = node; return node }, + () => { const node: any = { name: pick(['a', 'b']) }; node.self = { name: node.name, self: node }; return node }, + () => { const parent: any = objectOf(next, [['id', pick([1, 2])], ['children', [] as unknown[]]]); parent.children.push(objectOf(next, [['parent', parent], ['value', child()]])); return parent }, + () => { const list: any[] = [pick([1, 2])]; list.push(list); return list }, + // wide and long values, sampled or hashed shallowly + () => Array.from({ length: 300 }, (_, index) => (index === 150 ? child() : index)), + () => objectOf(next, Array.from({ length: 300 }, (_, index): [PropertyKey, unknown] => [`k${index}`, index === 7 ? child() : index])), + () => new Map(shuffle(next, Array.from({ length: 300 }, (_, index): [unknown, unknown] => [index === 0 ? { key: pick([1, 2]) } : index, index === 1 ? child() : index]))), + () => new Set(shuffle(next, Array.from({ length: 300 }, (_, index) => (index === 0 ? child() : index)))) + ])() +} + +/** A deep strictly equal copy with other identities, other key orders and other Map/Set insertion orders. */ +const copy = (next: Next, value: unknown, seen = new Map()): unknown => { + if (typeof value !== 'object' || value === null) return value + if (seen.has(value)) return seen.get(value) + if (Array.isArray(value)) { + const result: unknown[] = new Array(value.length) + seen.set(value, result) + for (const key of Object.keys(value)) (result as any)[key] = copy(next, (value as any)[key], seen) + return result + } + if (Buffer.isBuffer(value)) return Buffer.from(value) + if (value instanceof Date) return new Date(value.getTime()) + if (value instanceof Map) { + const result = new Map() + seen.set(value, result) + for (const [k, v] of shuffle(next, [...value])) result.set(copy(next, k, seen), copy(next, v, seen)) + return result + } + if (value instanceof Set) { + const result = new Set() + seen.set(value, result) + for (const item of shuffle(next, [...value])) result.add(copy(next, item, seen)) + return result + } + // a native error of the same class, with the same own properties (cause, errors, extras), but another stack + const result = types.isNativeError(value) + ? Object.setPrototypeOf(new Error((value as Error).message), Object.getPrototypeOf(value)) + : Object.create(Object.getPrototypeOf(value)) + seen.set(value, result) + for (const key of shuffle(next, Reflect.ownKeys(value))) { + if (key === 'stack') continue + const descriptor = Object.getOwnPropertyDescriptor(value, key)! + Object.defineProperty(result, key, { ...descriptor, value: copy(next, descriptor.value, seen) }) + } + return result +} + +/** + * isDeepStrictEqual, or false when it throws: Node.js 22 can throw a TypeError on some Sets that hold null and + * objects. The library treats such a comparison as unequal as well (see RecordedArguments). + */ +const deepStrictEqual = (a: unknown, b: unknown): boolean => { + try { + return isDeepStrictEqual(a, b) + } catch { + return false + } +} + +const hashesAgree = (t: ExecutionContext, a: unknown, b: unknown, message: string): boolean => { + if (!deepStrictEqual(a, b)) return false + if (structuralHash(a) !== structuralHash(b) || hashArguments([a, 1]) !== hashArguments([b, 1])) t.fail(`equal values hash differently: ${message}`) + return true +} + +test('R3-ADV-2 / R3-1 (E3) the bounded hash agrees with the running Node.js isDeepStrictEqual (property test)', t => { + const next = random(20261117) + const values: unknown[] = [] + let equalPairs = 0 + for (let index = 0; index < 3000; index++) { + const value = generate(next, 4) + values.push(value) + const twin = copy(next, value) + // a copy is equal unless Node.js finds the value unequal to itself (an invalid Date up to Node.js 22) + if (hashesAgree(t, value, twin, `copy ${index}`)) equalPairs++ + t.not(structuralHash(value), FALLBACK_HASH, 'every generated value can be hashed (cycles included)') + } + + let unequal = 0 + let collisions = 0 + for (let index = 0; index < 30000; index++) { + const a = values[Math.floor(next() * values.length)] + const b = values[Math.floor(next() * values.length)] + if (hashesAgree(t, a, b, `pair ${index}`)) equalPairs++ + else { + unequal++ + if (structuralHash(a) === structuralHash(b)) collisions++ + } + } + t.true(equalPairs > 3000, `${equalPairs} equal pairs`) + t.true(unequal > 1000) + // only values that differ in what the hash leaves out collide: prototypes, holes, deep or sampled parts, ... + t.true(collisions / unequal < 0.1, `${collisions} collisions in ${unequal} unequal pairs`) +}) + +test('R3-ADV-2 / R3-1 (E3) cycles, errors, invalid Dates, long strings and key orders, value by value', t => { + const agree = (a: unknown, b: unknown, message: string) => { + hashesAgree(t, a, b, message) + t.not(structuralHash(a), FALLBACK_HASH, message) + } + const differ = (a: unknown, b: unknown, message: string) => { + t.false(deepStrictEqual(a, b), message) + t.not(structuralHash(a), structuralHash(b), message) + } + + // cycles of different shapes unroll to the same tree, so they hash the same whatever Node.js decides about them + const cyclic: any = { name: 'a' } + cyclic.self = cyclic + const longer: any = { name: 'a', self: { name: 'a' } } + longer.self.self = longer + t.is(structuralHash(cyclic), structuralHash(longer)) + agree(cyclic, longer, 'cycles of a different shape') + const parent: any = { id: 1, children: [] } + parent.children.push({ parent }) + const otherParent: any = { children: [], id: 1 } + otherParent.children.push({ parent: otherParent }) + agree(parent, otherParent, 'a child-to-parent back-reference') + differ(parent, { id: 2, children: [{ parent }] }, 'back-references with other ids') + + // invalid Dates: equal from Node.js 24 on, never equal before; the hash agrees in both cases + agree(new Date(NaN), new Date('nope'), 'invalid Dates') + + // errors: name and message (and cause, errors where the running Node.js compares them) + agree(new Error('a'), new Error('a'), 'errors with the same message') + differ(new Error('request 1 failed'), new Error('request 2 failed'), 'errors with other messages') + differ(new TypeError('a'), new RangeError('a'), 'errors of other classes') + agree(Object.assign(new Error('a'), { code: 1 }), Object.assign(new Error('a'), { code: 1 }), 'errors with extra properties') + differ(Object.assign(new Error('a'), { code: 1 }), Object.assign(new Error('a'), { code: 2 }), 'errors with other extra properties') + agree(new (Error as any)('a', { cause: { id: 1 } }), new (Error as any)('a', { cause: { id: 1 } }), 'errors with a cause') + agree(new (Error as any)('a', { cause: undefined }), new Error('a'), 'a cause of undefined') + if (!deepStrictEqual(new (Error as any)('a', { cause: 1 }), new (Error as any)('a', { cause: 2 }))) + differ(new (Error as any)('a', { cause: 1 }), new (Error as any)('a', { cause: 2 }), 'errors with other causes') + + // long strings that differ only in the middle: hashed in full up to 4096 characters, sampled beyond + agree(middle('a', 1500), middle('a', 1500), 'long strings') + differ(middle('a', 1500), middle('b', 1500), 'long strings that differ in the middle') + agree(middle('a', 600000), middle('a', 600000), 'very long strings') + agree(Buffer.alloc(1 << 20, 1), Buffer.alloc(1 << 20, 1), 'large Buffers') + + // the same keys inserted in other orders, at every depth; wide objects, large Maps and Sets in any order + agree({ a: 1, b: { c: [1, { d: 2, e: 3 }] } }, { b: { c: [1, { e: 3, d: 2 }] }, a: 1 }, 'key order at every depth') + const keys = Array.from({ length: 400 }, (_, index) => `key${index}`) + const wide = (order: string[]) => Object.fromEntries(order.map(key => [key, { value: key }])) + agree(wide(keys), wide([...keys].reverse()), 'wide objects in other key orders') + agree(new Map(keys.map(key => [key, key])), new Map([...keys].reverse().map(key => [key, key])), 'large Maps') + agree(new Set(keys), new Set([...keys].reverse()), 'large Sets') + agree(new Map(keys.map(key => [{ key }, 1])), new Map([...keys].reverse().map(key => [{ key }, 1])), 'large Maps with object keys') + + // values deeper and larger than the limits are cut, not given FALLBACK_HASH + let chain: any = { leaf: 1 } + for (let index = 0; index < 100; index++) chain = { next: chain } + t.not(structuralHash(chain), FALLBACK_HASH) + let dag: any = { leaf: 1 } + for (let index = 0; index < 40; index++) dag = { a: dag, b: dag } + t.not(structuralHash(dag), FALLBACK_HASH) + + // only values that cannot be read give FALLBACK_HASH + t.is(structuralHash({ get value(): never { throw new Error('getter') } }), FALLBACK_HASH) + const { proxy, revoke } = Proxy.revocable({}, {}) + revoke() + t.is(structuralHash(proxy), FALLBACK_HASH) +}) + +const millisecondsOf = (run: () => void) => { + const start = process.hrtime.bigint() + run() + return Number(process.hrtime.bigint() - start) / 1e6 +} +const bestOfThree = (run: () => void) => { + run() // warm up + return Math.min(millisecondsOf(run), millisecondsOf(run), millisecondsOf(run)) +} + +test('R3-1 (E3) 10k unconfigured calls with Error arguments, cb(err, null) and back-references finish well under 1s', t => { + const cases: Array<[string, () => void]> = [ + ['logger.error(new Error(message_i))', () => { + const logger = Substitute.for() + for (let index = 0; index < 10_000; index++) logger.error(new Error(`request ${index} failed`)) + }], + ['cb(new TypeError(message_i), null)', () => { + const callback = Substitute.for() + for (let index = 0; index < 10_000; index++) callback(new TypeError(`bad ${index}`), null) + }], + ['visit(node_i) with a child-to-parent back-reference', () => { + const visitor = Substitute.for() + for (let index = 0; index < 10_000; index++) { + const node: any = { id: index, children: [] } + node.children.push({ parent: node }) + visitor.visit(node) + } + }], + ['f({ err: new Error(message_i) })', () => { + const substitute = Substitute.for() + for (let index = 0; index < 10_000; index++) substitute.f({ err: new Error(`e${index}`) }) + }] + ] + for (const [name, run] of cases) { + const elapsed = bestOfThree(run) + t.true(elapsed < 1000, `${name}: ${elapsed} ms`) + } + + // the cache still finds equal arguments + const logger = Substitute.for() + t.is(logger.error(new Error('x')), logger.error(new Error('x'))) + t.not(logger.error(new Error('x')), logger.error(new Error('y'))) + const node: any = { id: 1, children: [] } + node.children.push({ parent: node }) + const same: any = { id: 1, children: [] } + same.children.push({ parent: same }) + if (deepStrictEqual(node, same)) t.is(logger.visit(node), logger.visit(same)) + logger.received(3).error(new Error('x')) +}) + +test('R3-ADV-2 (E3) cyclic setups, 1 MB strings, deep DAGs and 150k-element arrays finish well under 1s', t => { + const cases: Array<[string, () => void]> = [ + ['2000 cyclic setups and 2000 matching calls', () => { + const repository = Substitute.for() + for (let index = 0; index < 2000; index++) { + const entity: any = { id: index } + entity.self = entity + repository.save(entity).returns(index) + } + for (let index = 0; index < 2000; index++) { + const entity: any = { id: index } + entity.self = entity + if (repository.save(entity) !== index) throw new Error(`save(${index})`) + } + }], + ['200 calls with distinct 1 MB strings', () => { + const log = Substitute.for() + const payload = 'x'.repeat(1 << 20) + for (let index = 0; index < 200; index++) log.write(index + payload) + }], + ['50 calls with a deep DAG of shared subtrees', () => { + const store = Substitute.for() + for (let index = 0; index < 50; index++) { + let dag: any = { leaf: index } + for (let level = 0; level < 25; level++) dag = { a: dag, b: dag } + store.put(dag) + } + }] + ] + for (const [name, run] of cases) { + const elapsed = bestOfThree(run) + t.true(elapsed < 1000, `${name}: ${elapsed} ms`) + } + + // 20 calls with 150k-element arrays (the arrays are created beforehand: only the calls are timed) + const arrays = Array.from({ length: 20 }, (_, index) => { + const items = Array.from({ length: 150_000 }, (_, item) => ({ item })) + items[149_999] = { item: -index } + return items + }) + const elapsed = bestOfThree(() => { + const sink = Substitute.for() + for (const items of arrays) sink.consume(items) + }) + t.true(elapsed < 1000, `20 calls with 150k-element arrays: ${elapsed} ms`) +}) + +test('R3-ADV-2 (E3) the search for nested matchers is bounded as well, and still finds them in ordinary arguments', t => { + const items = Array.from({ length: 150_000 }, (_, item) => ({ item })) + const elapsed = bestOfThree(() => { + for (let index = 0; index < 20; index++) RecordedArguments.containsMatchers([items]) + }) + t.true(elapsed < 100, `${elapsed} ms`) + + const repository = Substitute.for() + repository.save({ user: { id: Arg.any(), roles: [Arg.any('string'), 'admin'] } }).returns('saved') + t.is(repository.save({ user: { id: 1, roles: ['x', 'admin'] } }), 'saved') + const wide = Object.fromEntries(Array.from({ length: 200 }, (_, index) => [`k${index}`, index === 199 ? Arg.any() : index])) + repository.update(wide).returns('updated') + t.is(repository.update({ ...wide, k199: 'anything' }), 'updated') + repository.received(1).save(Arg.all()) + repository.received(1).update(Arg.all()) +}) diff --git a/src/internals/RecordedArguments.ts b/src/internals/RecordedArguments.ts index 7de9143..cefe699 100644 --- a/src/internals/RecordedArguments.ts +++ b/src/internals/RecordedArguments.ts @@ -62,34 +62,50 @@ const dataValue = (object: object, key: PropertyKey): unknown => { return descriptor !== undefined && 'value' in descriptor ? descriptor.value : undefined } -/** - * Whether some value inside a plain container satisfies the predicate. Used on the arguments of every call, so it - * allocates nothing per item and runs no getters of the code under test's objects. +/* + * E3: the search for nested matchers runs on the arguments of every call, so its cost is bounded like the structural + * hash's (see ArgumentHash): each argument has a budget of SCAN_BUDGET containers, a container shares the rest of its + * budget evenly among its items, and containers without a share, nested more than MAX_SCAN_DEPTH levels deep (so + * cycles end), or with more than MAX_SCANNED_ITEMS items or keys are not searched. Matchers there are not recognised, + * and the value is compared literally. Items without a share are still checked for being a matcher themselves. */ -const someItem = (container: object, predicate: (item: unknown) => boolean): boolean => { +const SCAN_BUDGET = 1024 +const MAX_SCAN_DEPTH = 32 +const MAX_SCANNED_ITEMS = 1024 + +const holdsMatcherItem = (item: unknown, budget: number, depth: number): boolean => + isArgumentMatcher(item) || (budget > 0 && depth < MAX_SCAN_DEPTH && isPlainContainer(item) && holdsMatcher(item, budget, depth + 1)) + +/** Whether a plain container holds a matcher (see above). It runs no getters of the code under test's objects. */ +const holdsMatcher = (container: object, budget: number, depth: number): boolean => { if (Array.isArray(container)) { - for (let index = 0; index < container.length; index++) if (predicate(container[index])) return true + const length = container.length + if (length > MAX_SCANNED_ITEMS) return false + const share = Math.floor((budget - 1) / length) + for (let index = 0; index < length; index++) if (holdsMatcherItem(container[index], share, depth)) return true return false } - for (const key of Object.keys(container)) if (predicate(dataValue(container, key))) return true - for (const symbol of Object.getOwnPropertySymbols(container)) - if (Object.prototype.propertyIsEnumerable.call(container, symbol) && predicate(dataValue(container, symbol))) return true + const keys = Object.keys(container) + const symbols = Object.getOwnPropertySymbols(container) + const count = keys.length + symbols.length + if (count > MAX_SCANNED_ITEMS) return false + const share = Math.floor((budget - 1) / count) + for (let index = 0; index < keys.length; index++) if (holdsMatcherItem(dataValue(container, keys[index]), share, depth)) return true + for (let index = 0; index < symbols.length; index++) { + const symbol = symbols[index] + if (Object.prototype.propertyIsEnumerable.call(container, symbol) && holdsMatcherItem(dataValue(container, symbol), share, depth)) return true + } return false } -const holdsMatcher = (container: object, visited: Set): boolean => { - visited.add(container) - return someItem(container, item => isArgumentMatcher(item) || (isPlainContainer(item) && !visited.has(item) && holdsMatcher(item, visited))) -} - /** - * Whether a value has a matcher nested in a plain object or array (D27), at any depth. Every container is visited - * once, so cycles end. A container that cannot be read (a throwing getter) holds no matcher. + * Whether a value has a matcher nested in a plain object or array (D27), within the bounds above. A container that + * cannot be read (a throwing getter) holds no matcher. */ const containsNestedMatcher = (value: unknown): boolean => { if (!isPlainContainer(value)) return false try { - return holdsMatcher(value, new Set()) + return holdsMatcher(value, SCAN_BUDGET, 0) } catch { return false } diff --git a/src/internals/utilities/ArgumentHash.ts b/src/internals/utilities/ArgumentHash.ts index 9cf52fb..85e606c 100644 --- a/src/internals/utilities/ArgumentHash.ts +++ b/src/internals/utilities/ArgumentHash.ts @@ -1,22 +1,32 @@ -import { types } from 'util' +import { isDeepStrictEqual, types } from 'util' /** - * Structural hashes of argument lists (D35). They let the auto-substitute cache and the index of literal + * Structural hashes of argument lists (D35, E3). They let the auto-substitute cache and the index of literal * substitutions find the candidates for a call in O(1) expected time, whatever the shape of the arguments, instead of * comparing the call against every earlier argument list. * - * Contract: argument lists that are deep strictly equal (util.isDeepStrictEqual, element by element) always get the - * same structural hash. Unequal lists may share a hash (callers confirm every candidate with live deep equality), - * so the hash only looks at what deep strict equality compares, and may leave things out: + * Contract: argument lists that the running Node.js finds deep strictly equal (util.isDeepStrictEqual, element by + * element) always get the same structural hash. Unequal lists may share a hash (callers confirm every candidate with + * live deep equality), so the hash only looks at what deep strict equality compares, and may leave things out: * - primitives by value (NaN as one value, symbols by their description), functions (substitutes included) by * identity: they are never traversed; - * - arrays element by element (a hole counts as undefined), plain objects and class instances by their own - * enumerable string and symbol keys and values, in any key order (prototypes are left out); + * - arrays by their length and their items (a hole counts as undefined), plain objects and class instances by their + * own enumerable string and symbol keys and values, in any key order (prototypes are left out); * - Maps and Sets by their entries, in any order; Dates, RegExps and boxed primitives by their value; typed arrays, - * DataViews and ArrayBuffers by their bytes. - * Arguments that cannot be hashed give the constant FALLBACK_HASH: a cycle (a value deep strictly equal to a cyclic - * value is cyclic as well), more than MAX_OBJECTS nested objects (deep strictly equal values have the same number), - * or anything that throws while it is read, such as a throwing getter or a revoked proxy. + * DataViews and ArrayBuffers by their bytes; native errors also by the name, message, cause and errors that the + * running Node.js compares (found out once, when the library is loaded). + * + * E3: the cost per argument is bounded, whatever its size, so that every call costs about the same: + * - each argument has a budget of BUDGET objects. An object takes one and shares the rest evenly among the values it + * hashes, and an object without a share, or nested more than MAX_DEPTH levels deep, gives a constant tag. Cycles + * simply end there (deep strictly equal values unroll to the same tree, whatever the shape of their cycles); + * - long arrays are sampled by position (their length, the first and the last items and items at a fixed stride), + * long strings and byte arrays likewise; the samples depend only on the length; + * - objects with many keys, and large Maps and Sets, contribute every key, but only shallowly (primitives by value, + * objects by a constant tag). + * No limit depends on the order of keys or of Map and Set entries, as deep strictly equal values may differ in it. + * Arguments that cannot be read give the constant FALLBACK_HASH: anything that throws while it is read, such as a + * throwing getter or a revoked proxy. * * The identity hash counts objects by identity (and is undefined when there are no objects among the arguments, as * the structural hash is exact then). It finds the entry recorded for the same objects again after they were mutated. @@ -36,19 +46,26 @@ const idOf = (value: object): number => { return id } -const MAX_OBJECTS = 100_000 -/** The depth from which the ancestors of the current value are also kept in a Set (cycle detection stays O(1)). */ -const ANCESTOR_SET_DEPTH = 16 - -/** Thrown to stop hashing; the arguments then get FALLBACK_HASH. Not an Error, so that no stack trace is captured. */ -const CANNOT_HASH = { reason: 'cannot hash' } +/** How many objects of one argument are hashed at most. */ +const BUDGET = 1024 +/** How many levels of nested objects are hashed at most. */ +const MAX_DEPTH = 32 +/** Arrays with more items are sampled: the first and last SAMPLED_ITEMS / 4 items, and SAMPLED_ITEMS / 2 strided ones. */ +const SAMPLED_ITEMS = 256 +/** Objects with more keys, and Maps and Sets with more entries, are hashed shallowly. */ +const MAX_ENTRIES = 256 +/** Objects with more keys, and Maps and Sets with more entries, are hashed by their size only. */ +const MAX_SCANNED_ENTRIES = 65536 +/** Strings and byte arrays that are longer are sampled, like arrays. */ +const SAMPLED_UNITS = 4096 // tags that keep the kinds of values apart const enum Tag { Undefined = 0x1b873593, Null = 0x2e5c4a1d, True = 0x5a9e1d27, False = 0x3c6ef372, Number = 0x7f4a7c15, NaN = 0x6c078965, String = 0x0bad5eed, BigInt = 0x4cf5ad43, Symbol = 0x1f83d9ab, Function = 0x5be0cd19, Array = 0x6a09e667, Object = 0x3c6ef373, Map = 0x510e527f, Set = 0x9b05688c, Date = 0x1f83d9ac, - RegExp = 0x5be0cd1a, Bytes = 0x428a2f98, Boxed = 0x71374491, Identity = 0x2a5c4e2b, Arguments = 0x0f1bbcdc + RegExp = 0x5be0cd1a, Bytes = 0x428a2f98, Boxed = 0x71374491, Identity = 0x2a5c4e2b, Arguments = 0x0f1bbcdc, + Cut = 0x24b6f2d1, Key = 0x63a1b5c7, Error = 0x1d8e4e27, Wide = 0x3a8f05c5 } const mix = (hash: number, value: number): number => { @@ -64,9 +81,28 @@ const spread = (value: number): number => { return Math.imul(h, 0xc2b2ae35) | 0 } +/** + * The positions of a sequence of `length` units that are hashed: all of them up to `samples`, otherwise the first and + * last quarter of `samples` and half of them at a fixed stride in between. They depend only on the length. + */ +const sampledPosition = (length: number, samples: number, index: number): number => { + if (length <= samples) return index + const edge = samples >>> 2 + if (index < edge) return index + if (index >= samples - edge) return length - (samples - index) + const strided = samples - 2 * edge + return edge + Math.floor((index - edge + 0.5) * (length - 2 * edge) / strided) +} + const hashString = (text: string, seed: number): number => { - let h = mix(seed, text.length) - for (let index = 0; index < text.length; index++) h = Math.imul(h ^ text.charCodeAt(index), 0x01000193) + const length = text.length + let h = mix(seed, length) + if (length <= SAMPLED_UNITS) { + for (let index = 0; index < length; index++) h = Math.imul(h ^ text.charCodeAt(index), 0x01000193) + } else { + for (let index = 0; index < SAMPLED_UNITS; index++) + h = Math.imul(h ^ text.charCodeAt(sampledPosition(length, SAMPLED_UNITS, index)), 0x01000193) + } return mix(h, 0) } @@ -80,8 +116,13 @@ const hashNumber = (value: number): number => { } const hashBytes = (bytes: Uint8Array): number => { - let h = mix(Tag.Bytes, bytes.length) - for (let index = 0; index < bytes.length; index++) h = Math.imul(h ^ bytes[index], 0x01000193) + const length = bytes.length + let h = mix(Tag.Bytes, length) + if (length <= SAMPLED_UNITS) { + for (let index = 0; index < length; index++) h = Math.imul(h ^ bytes[index], 0x01000193) + } else { + for (let index = 0; index < SAMPLED_UNITS; index++) h = Math.imul(h ^ bytes[sampledPosition(length, SAMPLED_UNITS, index)], 0x01000193) + } return mix(h, 0) } @@ -102,108 +143,159 @@ const hashPrimitive = (value: unknown): number => { return Tag.Null } -/** One structural hashing run over an argument list. */ -class StructuralHasher { - private _objects = 0 - private readonly _ancestors: object[] = [] - private _ancestorSet?: Set +/** Primitives by value, functions by identity, objects by a constant tag. */ +const shallowHash = (value: unknown): number => { + if (typeof value === 'function') return mix(Tag.Function, idOf(value)) + if (typeof value !== 'object' || value === null) return hashPrimitive(value) + return Tag.Cut +} - public hash(value: unknown): number { - if (typeof value === 'function') return mix(Tag.Function, idOf(value)) - if (typeof value !== 'object' || value === null) return hashPrimitive(value) - return this.hashObject(value) +/** + * E3: what deep strict equality compares on native errors besides their own enumerable properties. It changed between + * Node.js versions (name since 12, cause and errors since 20 or 22), so it is found out once. A part is only hashed when + * errors that differ in it alone are unequal, so that the hash never separates errors the running Node.js finds equal. + */ +const errorParts = ((): { name: boolean, message: boolean, cause: boolean, errors: boolean } => { + const unequal = (create: () => [unknown, unknown]): boolean => { + try { + const [a, b] = create() + return !isDeepStrictEqual(a, b) + } catch { + return false + } } - - private enter(object: object): void { - if (++this._objects > MAX_OBJECTS) throw CANNOT_HASH - const set = this._ancestorSet - if (set !== undefined) { - if (set.has(object)) throw CANNOT_HASH - set.add(object) - } else if (this._ancestors.indexOf(object) !== -1) throw CANNOT_HASH - this._ancestors.push(object) - if (set === undefined && this._ancestors.length > ANCESTOR_SET_DEPTH) this._ancestorSet = new Set(this._ancestors) + const named = (name: string) => { + const error = new Error('x') + Object.defineProperty(error, 'name', { value: name, enumerable: false, configurable: true, writable: true }) + return error } + const withCause = (...cause: unknown[]) => new (Error as any)('x', ...cause.map(value => ({ cause: value }))) as Error + const Aggregate = (globalThis as any).AggregateError as (new (errors: unknown[], message: string) => Error) | undefined + const withoutErrors = () => { + const error = new Aggregate!([1], 'x') + delete (error as any).errors + return error + } + return { + name: unequal(() => [named('A'), named('B')]), + message: unequal(() => [new Error('a'), new Error('b')]), + cause: unequal(() => [withCause(1), withCause(2)]) && unequal(() => [withCause(1), withCause()]), + errors: Aggregate !== undefined && unequal(() => [new Aggregate([1], 'x'), new Aggregate([2], 'x')]) && + unequal(() => [new Aggregate([1], 'x'), withoutErrors()]) + } +})() + +/** Each child's share of an object's budget. */ +const share = (budget: number, children: number): number => children === 0 ? 0 : Math.floor((budget - 1) / children) + +/** The own enumerable string and symbol keys (the keys deep strict equality compares). */ +const ownEnumerableKeys = (object: object): PropertyKey[] => { + const keys: PropertyKey[] = Object.keys(object) + const symbols = Object.getOwnPropertySymbols(object) + for (let index = 0; index < symbols.length; index++) + if (Object.prototype.propertyIsEnumerable.call(object, symbols[index])) keys.push(symbols[index]) + return keys +} + +const hashKey = (key: PropertyKey): number => typeof key === 'symbol' ? hashPrimitive(key) : hashString(key as string, Tag.Key) - private exit(object: object): void { - this._ancestors.pop() - this._ancestorSet?.delete(object) +/** The hash of one value with a budget of objects (see above). */ +const hashValue = (value: unknown, budget: number, depth: number): number => { + if (typeof value === 'function') return mix(Tag.Function, idOf(value)) + if (typeof value !== 'object' || value === null) return hashPrimitive(value) + if (budget <= 0 || depth >= MAX_DEPTH) return Tag.Cut + return hashObject(value, budget, depth + 1) +} + +const hashObject = (object: object, budget: number, depth: number): number => { + if (Array.isArray(object)) { + const length = object.length + const count = length <= SAMPLED_ITEMS ? length : SAMPLED_ITEMS + const childBudget = share(budget, count) + let h = mix(Tag.Array, length) + for (let index = 0; index < count; index++) h = mix(h, hashValue(object[sampledPosition(length, SAMPLED_ITEMS, index)], childBudget, depth)) + return h + } + if (ArrayBuffer.isView(object)) return hashBytes(new Uint8Array(object.buffer, object.byteOffset, object.byteLength)) + if (types.isAnyArrayBuffer(object)) return hashBytes(new Uint8Array(object as ArrayBuffer)) + if (types.isDate(object)) return mix(Tag.Date, hashNumber(Date.prototype.getTime.call(object))) + if (types.isRegExp(object)) { + const regExp = object as RegExp + return mix(hashString(regExp.source, Tag.RegExp), hashString(regExp.flags, Tag.RegExp)) } + if (types.isMap(object)) return hashMap(object as Map, budget, depth) + if (types.isSet(object)) return hashSet(object as Set, budget, depth) + if (types.isNumberObject(object)) return mix(Tag.Boxed, hashNumber(Number.prototype.valueOf.call(object))) + if (types.isStringObject(object)) return mix(Tag.Boxed, hashString(String.prototype.valueOf.call(object), Tag.String)) + if (types.isBooleanObject(object)) return mix(Tag.Boxed, Boolean.prototype.valueOf.call(object) ? Tag.True : Tag.False) + if (types.isSymbolObject(object)) return mix(Tag.Boxed, hashString(Symbol.prototype.toString.call(object), Tag.Symbol)) + if (isBigIntObject(object)) return mix(Tag.Boxed, hashString(String(object), Tag.BigInt)) - private hashObject(object: object): number { - this.enter(object) - try { - return this.hashContents(object) - } finally { - this.exit(object) - } + // own enumerable string and symbol keys, in any order + const keys = ownEnumerableKeys(object) + const count = keys.length + const error = types.isNativeError(object) ? object as Error & { cause?: unknown, errors?: unknown } : undefined + let h = mix(types.isArgumentsObject(object) ? Tag.Arguments : error !== undefined ? Tag.Error : Tag.Object, count) + if (count > MAX_SCANNED_ENTRIES) return mix(h, Tag.Wide) + const errorChildren = error === undefined ? 0 : (errorParts.cause ? 1 : 0) + (errorParts.errors ? 1 : 0) + // wide objects: every key and its value, shallowly + const childBudget = count > MAX_ENTRIES ? 0 : share(budget, count + errorChildren) + let sum = 0 + for (let index = 0; index < count; index++) { + const key = keys[index] + sum = (sum + spread(mix(hashKey(key), hashValue((object as any)[key], childBudget, depth)))) | 0 } + h = mix(h, sum) + if (error !== undefined) { + // deep strict equality compares these with ===, or like the other properties (cause, errors) + if (errorParts.name) h = mix(h, shallowHash(error.name)) + if (errorParts.message) h = mix(h, shallowHash(error.message)) + if (errorParts.cause) h = mix(h, hashValue(error.cause, childBudget, depth)) + if (errorParts.errors) h = mix(h, hashValue(error.errors, childBudget, depth)) + } + return h +} - private hashContents(object: object): number { - if (Array.isArray(object)) { - let h = mix(Tag.Array, object.length) - for (let index = 0; index < object.length; index++) h = mix(h, this.hash(object[index])) - return h - } - if (ArrayBuffer.isView(object)) return hashBytes(new Uint8Array(object.buffer, object.byteOffset, object.byteLength)) - if (types.isAnyArrayBuffer(object)) return hashBytes(new Uint8Array(object as ArrayBuffer)) - if (types.isDate(object)) return mix(Tag.Date, hashNumber(Date.prototype.getTime.call(object))) - if (types.isRegExp(object)) { - const regExp = object as RegExp - return mix(hashString(regExp.source, Tag.RegExp), hashString(regExp.flags, Tag.RegExp)) - } - if (types.isMap(object)) { - let sum = 0 - for (const [key, value] of object as Map) sum = (sum + spread(mix(this.hash(key), this.hash(value)))) | 0 - return mix(mix(Tag.Map, (object as Map).size), sum) - } - if (types.isSet(object)) { - let sum = 0 - for (const value of object as Set) sum = (sum + spread(this.hash(value))) | 0 - return mix(mix(Tag.Set, (object as Set).size), sum) - } - if (types.isNumberObject(object)) return mix(Tag.Boxed, hashNumber(Number.prototype.valueOf.call(object))) - if (types.isStringObject(object)) return mix(Tag.Boxed, hashString(String.prototype.valueOf.call(object), Tag.String)) - if (types.isBooleanObject(object)) return mix(Tag.Boxed, Boolean.prototype.valueOf.call(object) ? Tag.True : Tag.False) - if (types.isSymbolObject(object)) return mix(Tag.Boxed, hashString(Symbol.prototype.toString.call(object), Tag.Symbol)) - if (isBigIntObject(object)) return mix(Tag.Boxed, hashString(String(object), Tag.BigInt)) - - // own enumerable string and symbol keys, in any order - const keys = Object.keys(object) - let sum = 0 - for (const key of keys) sum = (sum + spread(mix(hashString(key, Tag.Object), this.hash((object as any)[key])))) | 0 - let count = keys.length - for (const symbol of Object.getOwnPropertySymbols(object)) { - if (!Object.prototype.propertyIsEnumerable.call(object, symbol)) continue - count++ - sum = (sum + spread(mix(hashPrimitive(symbol), this.hash((object as any)[symbol])))) | 0 - } - return mix(mix(types.isArgumentsObject(object) ? Tag.Arguments : Tag.Object, count), sum) +/** Map entries in any order. Large Maps contribute every entry, shallowly (objects among them by a constant tag). */ +const hashMap = (map: Map, budget: number, depth: number): number => { + const size = map.size + const h = mix(Tag.Map, size) + if (size > MAX_SCANNED_ENTRIES) return mix(h, Tag.Wide) + let sum = 0 + if (size > MAX_ENTRIES) { + for (const [key, value] of map) sum = (sum + spread(mix(shallowHash(key), shallowHash(value)))) | 0 + } else { + const childBudget = share(budget, 2 * size) + for (const [key, value] of map) sum = (sum + spread(mix(hashValue(key, childBudget, depth), hashValue(value, childBudget, depth)))) | 0 } + return mix(h, sum) +} + +/** Set members in any order, like Map entries. */ +const hashSet = (set: Set, budget: number, depth: number): number => { + const size = set.size + const h = mix(Tag.Set, size) + if (size > MAX_SCANNED_ENTRIES) return mix(h, Tag.Wide) + const childBudget = size > MAX_ENTRIES ? 0 : share(budget, size) + let sum = 0 + for (const value of set) sum = (sum + spread(hashValue(value, childBudget, depth))) | 0 + return mix(h, sum) } /** The hash of one value (see above). Exported for the tests of the contract. */ export const structuralHash = (value: unknown): number => { try { - return new StructuralHasher().hash(value) + return hashValue(value, BUDGET, 0) } catch { return FALLBACK_HASH } } -/** The structural hash of an argument list (see above). */ +/** The structural hash of an argument list (see above). Each argument has a budget of its own. */ export const hashArguments = (args: readonly unknown[]): number => { - // the common cases need no hasher: no arguments, and primitives only let h = mix(Tag.Array, args.length) - let hasher: StructuralHasher | undefined try { - for (let index = 0; index < args.length; index++) { - const value = args[index] - if (typeof value === 'object' && value !== null) { - if (hasher === undefined) hasher = new StructuralHasher() - h = mix(h, hasher.hash(value)) - } else h = mix(h, typeof value === 'function' ? mix(Tag.Function, idOf(value)) : hashPrimitive(value)) - } + for (let index = 0; index < args.length; index++) h = mix(h, hashValue(args[index], BUDGET, 0)) } catch { return FALLBACK_HASH } From 1f6f0402cf25d6867d94ca2ec76c03df6f9d7c51 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:54:13 +0000 Subject: [PATCH 058/106] fix(protocol keys): use the runtime's util.promisify.custom and util.inspect.custom (E7) On Node.js 10.0 to 12.16.1 and 13.0 to 13.11, util.promisify.custom is a symbol of its own, not Symbol.for('nodejs.util.promisify.custom'), so util.promisify(sub.method) still found an auto-substitute there and bypassed the configured call (R3-2). The runtime's key is now a protocol key as well. Matchers also print through the runtime's util.inspect.custom, which differs from the registered symbol on Node.js 10.0 to 10.11. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round4.test.ts | 53 ++++++++++++++++++++++++++++ src/internals/Constants.ts | 5 ++- src/shared/Arguments.ts | 14 ++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 spec/regression/fixes/round4.test.ts diff --git a/spec/regression/fixes/round4.test.ts b/spec/regression/fixes/round4.test.ts new file mode 100644 index 0000000..1e2a6b5 --- /dev/null +++ b/spec/regression/fixes/round4.test.ts @@ -0,0 +1,53 @@ +import test from 'ava' +import { spawnSync } from 'child_process' +import * as path from 'path' + +// Round 4: the runtime findings of the round-3 verification (R3-*), decided in the fix spec as E1-E7. + +const library = path.resolve(__dirname, '../../../src/index.js') + +/** Runs a script with the library in a child process, and returns what it prints as JSON. */ +const runScript = (script: string, options: { args?: string[], env?: Record } = {}): any => { + const result = spawnSync(process.execPath, [...(options.args ?? []), '-e', script], { + encoding: 'utf8', + env: { ...process.env, NO_COLOR: '1', ...options.env } + }) + if (result.status !== 0) throw new Error(`exit code ${result.status}: ${result.stderr}`) + return JSON.parse(result.stdout) +} + +test('R3-2 (E7) the runtime\'s own util.promisify.custom and util.inspect.custom are used, also where they are not the registered symbols', t => { + // Node.js 10.0 to 12.16.1 and 13.0 to 13.11 have a util.promisify.custom of their own (Node.js 10.0 to 10.11 the + // same for util.inspect.custom), not Symbol.for('nodejs.util.promisify.custom'). This child process makes the + // running Node.js look like that before it loads the library. + const result = runScript(` + const util = require('util') + const promisifyCustom = util.promisify.custom = Symbol('util.promisify.custom') + const inspectCustom = util.inspect.custom = Symbol('util.inspect.custom') + const { Substitute, Arg } = require(${JSON.stringify(library)}) + + // util.promisify of those versions: the function under the custom key, if there is one, or a wrapper + const promisify = original => typeof original[promisifyCustom] === 'function' ? original[promisifyCustom] + : (...args) => new Promise((resolve, reject) => original(...args, (error, value) => error ? reject(error) : resolve(value))) + + const fs = Substitute.for() + fs.readFile(Arg.any(), Arg.any()).mimicks((file, done) => done(null, 'contents of ' + file)) + const loaded = promisify(fs.readFile)('/etc/app.json') + const custom = typeof fs.readFile[promisifyCustom] + let recorded = false + try { fs.readFile.didNotReceive()[promisifyCustom] } catch (error) { recorded = true } + const matcher = Arg.is(() => true) + Promise.resolve(loaded).then(contents => console.log(JSON.stringify({ + contents: typeof contents === 'string' ? contents : typeof contents, + custom, + recorded, + printed: typeof matcher[inspectCustom] === 'function' ? matcher[inspectCustom]() : 'not printable' + }))) + `) + t.deepEqual(result, { + contents: 'contents of /etc/app.json', + custom: 'undefined', + recorded: false, + printed: 'Arg.is{() => true}' + }) +}) diff --git a/src/internals/Constants.ts b/src/internals/Constants.ts index 80c00bb..431b557 100644 --- a/src/internals/Constants.ts +++ b/src/internals/Constants.ts @@ -1,4 +1,4 @@ -import { inspect } from 'util' +import { inspect, promisify } from 'util' import { constants as sharedConstants, substituteMarker } from '../shared' const CONTEXT = sharedConstants.CONTEXT @@ -68,7 +68,10 @@ const protocolKeys = new Set([ // asyncIterator and matchAll are looked up by name because older runtimes do not have them ...['iterator', 'asyncIterator', 'hasInstance', 'isConcatSpreadable', 'match', 'matchAll', 'replace', 'search', 'split', 'species', 'toStringTag', 'unscopables'].map(name => wellKnownSymbols[name]), + // E7: the registered form, and the running runtime's own key, which is another symbol on Node.js 10.0 to 12.16.1 + // and 13.0 to 13.11 (util.promisify reads that one there) Symbol.for('nodejs.util.promisify.custom'), + (promisify as { custom?: symbol }).custom, 'asymmetricMatch' ].filter(key => key !== undefined) as PropertyKey[]) diff --git a/src/shared/Arguments.ts b/src/shared/Arguments.ts index 796bc08..321d48b 100644 --- a/src/shared/Arguments.ts +++ b/src/shared/Arguments.ts @@ -1,3 +1,5 @@ +import { inspect } from 'util' + export type PredicateFunction = (arg: T) => boolean export type ArgumentOptions = { inverseMatch?: boolean @@ -37,6 +39,18 @@ class BaseArgument { } } +// E7: util.inspect looks for the runtime's own util.inspect.custom, which is another symbol than the registered one on +// Node.js 10.0 to 10.11; without it, failure messages would print matchers as raw objects there. +const registeredInspectCustom = Symbol.for('nodejs.util.inspect.custom') +const runtimeInspectCustom = (inspect as { custom?: symbol }).custom +if (runtimeInspectCustom !== undefined && runtimeInspectCustom !== registeredInspectCustom) { + Object.defineProperty(BaseArgument.prototype, runtimeInspectCustom, { + value: (BaseArgument.prototype as any)[registeredInspectCustom], + writable: true, + configurable: true + }) +} + export class Argument extends BaseArgument { private readonly _type = 'SingleArgument'; get type(): 'SingleArgument' { From 7e819964db97deac2220b3e42539328d9e6a996b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:57:32 +0000 Subject: [PATCH 059/106] types: setups and checks through a type parameter's constraint (T33, R3TD-1) In generic code such as `function stub(s: SubstituteOf)` or `class Fixture { sub = Substitute.for() }`, the typings now resolve the members through the constraint: - `s.total.returns(1)`, `s.add(1, 2).returns(3)`, `s.add(Arg.all())`, `s.load('a').resolves(1)` and the configure view type-check, and the configured values are checked against the constraint's member types; - `s.received().total = 1` compiles again (a round-3 regression), and so does `s.received().limit = undefined` for an optional member. How: every decision the typings make per member (only null/undefined? callable? index signature?) is a "kind" that TypeScript resolves through the constraint in generic code (distributive conditional types over the kind, with an `any` branch for the case generic code must not take), and the assertion view picks between `FunctionSubstitute & T[P]` and `T[P]` with an indexed access, which TypeScript checks against the constraint on assignment. FunctionSubstitute distributes over the member type, after ruling out primitives without distributing over large literal unions (TD-8). Member types are read from `T` itself, not from `Pick`. As a side effect, a property typed as an unconstrained type parameter (`current: T`) now has the setup API in generic code (the round-3 limitation in TD-2.V2-2.T26.generic-code.ts is lifted). Members typed `any` stay `any` in every view. On TypeScript 3.6 to 3.8, members whose type includes null or undefined still have no setup API in generic code. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/R3TD-1.T33.constrained-generics.ts | 85 +++++++++++++++++++ spec-types/TD-2.V2-2.T26.generic-code.ts | 10 ++- src/api/types/FunctionSubstitute.ts | 42 +++++++-- src/api/types/Substitute.ts | 54 +++++++----- src/api/types/Utilities.ts | 33 +++++++ 5 files changed, 195 insertions(+), 29 deletions(-) create mode 100644 spec-types/R3TD-1.T33.constrained-generics.ts diff --git a/spec-types/R3TD-1.T33.constrained-generics.ts b/spec-types/R3TD-1.T33.constrained-generics.ts new file mode 100644 index 0000000..f6109a4 --- /dev/null +++ b/spec-types/R3TD-1.T33.constrained-generics.ts @@ -0,0 +1,85 @@ +// R3TD-1 / T33 SubstituteOf for a constrained type parameter (`T extends Calculator`): setups, checks and the +// configure view work through the constraint, as for a SubstituteOf. The values they take are checked +// against the constraint's member types. +// (On TypeScript 3.6 to 3.8, members whose type includes null or undefined, such as `name` and `limit` below, have no +// setup API in generic code; spec-types/min-ts/consumer.ts checks the rest with TypeScript 3.6.) +import { Substitute, SubstituteOf, Arg, configure, received, didNotReceive, returns, mimicks } from '../src' + +interface Calculator { + add(a: number, b: number): number + load(id: string): Promise + total: number + name: string | null + limit?: number +} + +export function stub(s: SubstituteOf) { + s.total.returns(1) + s.total.returns(1, 2) + s.total[returns](3) + s.add(1, 2).returns(3) + s.add(Arg.any(), Arg.is(b => b > 0)).returns(4) + s.add(1, Arg.all()).returns(5) + s.add(Arg.all()).mimicks((a, b) => a + b) + s.add(1, 2)[mimicks]((a, b) => a - b) + s.load('a').resolves(1) + s.load('a').rejects(new Error()) + s.name.returns('x') + s.name.returns(null) + s.limit.returns(10) + s[configure]().total.returns(1) + s[configure]().add(1, 2).returns(3) + s[configure]().load(Arg.any()).resolves(2) + + s.received().add(1, 2) + s.received(2).add(1, Arg.all()) + s.didNotReceive().add(Arg.all()) + s.received().total = 1 + s.received(1).total = Arg.any() + s.didNotReceive().name = null + s.received().limit = undefined + s[received](1).total = 2 + s[didNotReceive]().add(1, 2) + const total: number = s.received().total + + // @ts-expect-error the configured value has the member's type + s.total.returns('1') + // @ts-expect-error the configured value has the member's type + s.add(1, 2).returns('3') + // @ts-expect-error the arguments keep their types + s.add('1', 2) + // @ts-expect-error the arguments keep their types in the assertion view + s.received().add('1', 2) + // @ts-expect-error a property check keeps the member's type + s.received().total = '1' + // @ts-expect-error a required property does not accept undefined + s.received().total = undefined + // @ts-expect-error the configure view checks the value too + s[configure]().total.returns('1') + // @ts-expect-error resolves() is only offered for promises + s.add(1, 2).resolves(3) + // @ts-expect-error not a member of the constraint + s.subtract(1, 2) + return total +} + +export class Fixture { + sub = Substitute.for() + arrange() { + this.sub.add(1, 2).returns(3) + this.sub.total.returns(10) + this.sub[configure]().add(Arg.all()).returns(0) + } + verify() { + this.sub.received().add(1, 2) + this.sub.received().total = 10 + } +} + +interface ScientificCalculator extends Calculator { sqrt(x: number): number } +const fixture = new Fixture() +fixture.arrange() +fixture.sub.sqrt(4).returns(2) +fixture.verify() +stub(Substitute.for()) +stub(fixture.sub) diff --git a/spec-types/TD-2.V2-2.T26.generic-code.ts b/spec-types/TD-2.V2-2.T26.generic-code.ts index 10c144e..b1f5121 100644 --- a/spec-types/TD-2.V2-2.T26.generic-code.ts +++ b/spec-types/TD-2.V2-2.T26.generic-code.ts @@ -3,9 +3,9 @@ // calls that return the type parameter, as in 2.0.0-beta.4. // - `sub.received()` / `sub.didNotReceive()` are offered on SubstituteOf for an unconstrained T: the D11 conflict rule // applies only where it can be decided (concrete types, or a constraint; see T-TY-03.G-RG-3.generic-helpers.ts). -// - Limitation: a PROPERTY whose type is the type parameter itself (`current: T`) has no setup API on the substitute -// (TypeScript cannot tell it apart from a member that can only be null or undefined, see TD-1.T25.null-only-members.ts). -// Configure it through the configure view: `repo[configure]().current.returns(value)`. +// - A PROPERTY whose type is the type parameter itself (`current: T`) has the setup API as well (round 4, T33; it had +// none in round 3, when `repo[configure]().current.returns(value)` was the way around it). For a concrete type, a +// member that can only be null or undefined still has none (TD-1.T25.null-only-members.ts). import { Substitute, SubstituteOf, Arg, configure, received, didNotReceive, returns, throws } from '../src' interface Repo { @@ -45,8 +45,10 @@ export function stubRepo(repo: SubstituteOf>, value: T) { repo.get('a').returns(1) // @ts-expect-error resolves() is only offered for promises repo.get('a').resolves(value) - // @ts-expect-error limitation: a property typed as the type parameter itself; use repo[configure]().current + // @ts-expect-error the configured value must be a T + repo.current.returns(1) repo.current.returns(value) + repo.current.mimicks(() => value) } // The G:RG-3 / V2-2 helpers diff --git a/src/api/types/FunctionSubstitute.ts b/src/api/types/FunctionSubstitute.ts index 485d33b..68e38fa 100644 --- a/src/api/types/FunctionSubstitute.ts +++ b/src/api/types/FunctionSubstitute.ts @@ -1,6 +1,6 @@ import { AllArguments } from '../../shared' import { ConfigurationResult, SubstitutionResult } from './SubstitutionLevel' -import { Equals, IsAny, IsNever, Primitive } from './Utilities' +import { Equals, IsAny, ObjectKind, Primitive } from './Utilities' /** * What a call returns in each view of a substitute: @@ -106,13 +106,43 @@ type OverloadSignatures AllArgumentsSignatures & AllArgumentsSignatures & AllArgumentsSignatures & AllArgumentsSignatures +// The signatures of one non-primitive type. (Not `[TFunction] extends [(...args: any) => any]`: in its true branch +// TypeScript would add that signature to TFunction.) +type SignaturesOf = OverloadSignatures, TView> + +// Distributive over `TFunction`, so that in generic code (a member type such as `T['add']` with `T extends Calculator`) +// TypeScript computes the signatures from the constraint (`Calculator['add']`) when the member is called (T33). +type EachSignatures = TFunction extends unknown ? SignaturesOf : never + +// Primitives, `never` and `any` are ruled out without distributing over a (possibly very large) union of literals +// (TD-8). Their branch is `any` for `any` (a member typed `any` stays `any`) and `never` otherwise: in generic code +// TypeScript cannot decide the check and uses the union of both branches, where `never` drops out, and an `any` branch +// is left out as well (see `ObjectKind`). +type GuardedSignatures = + [TFunction] extends [Primitive] ? (IsAny extends true ? any : never) : + EachSignatures + +type FunctionSubstituteOf = + TKind extends 'object' ? GuardedSignatures : unknown + /** * The call signatures a member of type `TFunction` has on a substitute: per overload, the overload's own parameter list, * a single `Arg.all()` argument, and the leading parameters followed by `Arg.all()`. `unknown` when `TFunction` is not - * callable. + * callable, `any` when it is `any`. + * In generic code the signatures are computed from the constraint of the member type, so that + * `sub.add(1, 2).returns(3)` type-checks on a `SubstituteOf` with `T extends Calculator` (T33). */ export type FunctionSubstitute = - IsNever extends true ? unknown : - IsAny extends true ? (...args: any[]) => CallResult : - // Not `[TFunction] extends [(...args: any) => any]`: in its true branch TypeScript would add that signature to TFunction. - OverloadSignatures, TView> + FunctionSubstituteOf, TFunction, TView> + +// The assertion view of a callable member also checks the call arguments; for a property it is only the property's +// type. `'call'` or `'plain'` per non-primitive member of the union (see `AssertionMember`). +type EachCallKind = TFunction extends (...args: any[]) => any ? 'call' : 'plain' +type GuardedCallKind = [TFunction] extends [Primitive] ? never : EachCallKind + +/** + * `'call'` when `TFunction` (a member type without `null | undefined`) is callable, otherwise `'plain'`. In generic + * code it is decided by the member's constraint. + */ +export type CallKind = CallKindOf, TFunction> +type CallKindOf = TKind extends 'object' ? GuardedCallKind : 'plain' diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index f43261f..f7ad559 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -1,5 +1,6 @@ import { ConfigurationResult, SetupMethods } from './SubstitutionLevel' -import { FunctionSubstitute } from './FunctionSubstitute' +import { CallKind, FunctionSubstitute } from './FunctionSubstitute' +import { IndexKind, ValueKind } from './Utilities' /** * The setup API of a member read on a substitute (`sub.isEnabled.returns(true)`). The value itself is not part of it: @@ -9,13 +10,18 @@ import { FunctionSubstitute } from './FunctionSubstitute' export type PropertySubstitute = SetupMethods TValue> /** - * The object type whose members the views below map. + * The object type whose keys the views below map. * A type with a string index signature is mapped directly: a homomorphic mapping over it keeps the named members next to * the index signature (T:TY-8), whereas `keyof T` is just `string | number`. Any other type is first turned into a plain * object type with the same members, so that primitives (`Substitute.for()`) and arrays are mapped member by - * member too (a homomorphic mapping would return a primitive unchanged and only map the elements of an array). + * member too (a homomorphic mapping would return a primitive unchanged and only map the elements of an array), and so + * that a union (`Cat | Dog`) is mapped as one object type with the members its variants have in common. + * The member types are read from `T` itself (`Member`), not from this object type: in generic code `T['total']` + * accepts the values of the constraint's member type, `Pick['total']` does not (T33). */ -type Members = string extends keyof T ? T : Pick +type Members = { indexed: T, plain: Pick }[IndexKind] + +type Member = T[P & keyof T] // The views are mapped with `-?` and expand calls from the member type without `null | undefined`, so optional members // (`prop?`, `method?()`) are configured and asserted like required ones (T:TY-7). @@ -23,10 +29,8 @@ type Members = string extends keyof T ? T : Pick // Members whose type is only `null` and/or `undefined` (`error?: undefined`, `ownerDocument: null`) get no setup API: // there is nothing to configure, and an object type intersected with `null` would reduce the whole substitute to // `never` (TD-1, T25). They are `unknown` here, so that `SubstituteOf` gives them their plain type from `T`. -// For a property whose type is an unresolved type parameter (`current: T` in generic code), TypeScript cannot decide -// this check and only keeps what both branches have, i.e. nothing: such a property has no setup API in generic code. -// It is configured through `sub[configure]().current`. (Calls are not affected: their results never meet `T`'s own -// property types, so they keep the setup API in both branches; see `SubstitutionResult`.) +// In generic code that check cannot be decided, and the member gets the setup API (`ValueKind`): a property whose type +// is the type parameter itself (`current: T`) can be configured there as well (T26, T33). // // Special members (T:TY-16, D20). At runtime a substitute never exposes `then`, so that it is not a thenable // (`await sub` resolves to the substitute itself); the typings make `then` `never`. `toJSON` is answered by the @@ -37,21 +41,33 @@ type Members = string extends keyof T ? T : Pick type SubstituteMember = FunctionSubstitute, 'substitute'> & PropertySubstitute -type SubstituteMembers = { - [P in keyof T]-?: +// For a concrete `any` kind (a member that is only null/undefined) this is `SubstituteMember | unknown`, which +// is `unknown`. +type SubstituteMemberOf = TKind extends 'value' ? SubstituteMember : unknown + +type SubstituteMembers = { + [P in keyof TMembers]-?: P extends 'then' ? never : P extends 'toJSON' ? unknown : - [NonNullable] extends [never] ? unknown : - SubstituteMember + SubstituteMemberOf>, Member> } /** The members of a substitute (without the assertion and configuration methods), each with its setup API. */ -export type ObjectSubstituteTransformation = SubstituteMembers> +export type ObjectSubstituteTransformation = SubstituteMembers, T> // In the assertion view, a member that is not callable keeps its declared type, including `undefined` for an optional // property (`sub.received().note = undefined`, TD-7). A callable member offers the assertion signatures (calls return // nothing) on the member type without `null | undefined`. -type AssertionMember = FunctionSubstitute, 'assertion'> & TValue +// The choice is an indexed access rather than a conditional type: in generic code TypeScript checks a value assigned +// to it against the member type of the constraint (`sub.received().total = 1` with `T extends Calculator`, T33), which +// it never does for a conditional type. +type AssertionMember = { + call: FunctionSubstitute, 'assertion'> & TValue + plain: TValue +}[AssertionKind, TValue>] + +// For a concrete `any` kind (a member that is only null/undefined) this is `CallKind | 'plain'`, i.e. `'plain'`. +type AssertionKind = TKind extends 'value' ? CallKind> : 'plain' type AssertionMemberOf = P extends 'then' ? never : @@ -70,16 +86,16 @@ type AssertionMembers = { [P in Extract]: AssertionMemb * The object returned by `received()` / `didNotReceive()`: calls return nothing, property reads and writes keep the * member type (`sub.received().isEnabled = true`). */ -export type TerminatingObject = string extends keyof T ? IndexedAssertionMembers : AssertionMembers +export type TerminatingObject = { indexed: IndexedAssertionMembers, plain: AssertionMembers }[IndexKind] type ConfigurationMember = FunctionSubstitute, 'configure'> & ConfigurationResult TValue> -type ConfigurationMembers = { - [P in keyof T]-?: +type ConfigurationMembers = { + [P in keyof TMembers]-?: P extends 'then' ? never : P extends 'toJSON' ? never : - ConfigurationMember + ConfigurationMember> } /** @@ -87,4 +103,4 @@ type ConfigurationMembers = { * setup API. The string forms (`.returns`, `.throws`, ...) are always offered here: the configured value is never * returned from this view, so there is nothing for them to conflict with. */ -export type ConfigureView = ConfigurationMembers> +export type ConfigureView = ConfigurationMembers, T> diff --git a/src/api/types/Utilities.ts b/src/api/types/Utilities.ts index 8f527a0..b8eb4ad 100644 --- a/src/api/types/Utilities.ts +++ b/src/api/types/Utilities.ts @@ -14,6 +14,39 @@ export type IsAny = 0 extends (1 & T) ? true : false */ export type Primitive = string | number | boolean | bigint | symbol +// Kinds: generic code +// ------------------- +// In generic code (`SubstituteOf` with `T extends Calculator`) a member type such as `T['total']` is a type +// parameter, and TypeScript cannot decide a conditional type on it. When such a deferred conditional type is used (a +// property of it is read, it is called, ...), TypeScript resolves it through its constraint: +// - a conditional type whose checked type is a naked type parameter (distributive) is computed with the constraint +// of the checked type, e.g. `T['total']` becomes `number`; +// - any other conditional type stands for the union of its two branches, except that a branch of type `any` is left +// out. +// The typings use both rules to decide in generic code what they decide for concrete types (T33). A "kind" is a +// conditional type that gives `any` for the case generic code should not take, and a string literal otherwise; a +// distributive conditional type over the kind then picks the type. For a concrete `any` kind, that conditional type +// gives the union of both branches. + +/** + * `any` for primitives (also `never` and `any` themselves), `'object'` for any other type. In generic code it is + * `'object'`. + */ +export type ObjectKind = [T] extends [Primitive] ? any : 'object' + +/** + * `any` for a type that is only `null` and/or `undefined` (or `never`), `'value'` otherwise. In generic code it is + * `'value'`. + */ +export type ValueKind = [NonNullable] extends [never] ? any : 'value' + +/** + * `'indexed'` for a type with a string index signature, `'plain'` otherwise. In generic code it is decided by the + * constraint of the type parameter (`'plain'` for an unconstrained one). + */ +export type IndexKind = IndexKindOf +type IndexKindOf = T extends unknown ? (string extends keyof T ? 'indexed' : 'plain') : never + /** The names the library uses: these are the names whose presence in a type the typings check. */ export type LibraryMemberName = 'received' | 'didNotReceive' | 'returns' | 'throws' | 'resolves' | 'rejects' | 'mimicks' From d3525fff071749e2d36a00fab78c1e8c04ce3f66 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:58:11 +0000 Subject: [PATCH 060/106] types: substitutes of function types are configured and checked through their calls (T37, R3TD-6, R3-3) `Substitute.for()` with `type Listener = (event: string) => string` (or an interface with call signatures) now types its calls like a member's: - `listener('saved').returns('ack')`, `listener(Arg.all()).mimicks(...)`, `load(1).resolves(...)` for a function returning a promise; - `listener.received(1)('saved')`, `listener.didNotReceive()(Arg.any())`, `listener[received](1)('saved')`, `listener[didNotReceive]()(...)`; - `listener[configure]()('saved').returns('ack')`. The arguments and configured values keep their types, overloads are handled as for members, and the members of a callable interface work as before. The call signatures with the setup API come before `T`'s own in SubstituteOf. Types without call signatures get none. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .../R3TD-6.R3-3.T37.function-substitutes.ts | 108 ++++++++++++++++++ src/api/Substitute.ts | 8 +- src/api/types/Substitute.ts | 12 +- src/api/types/index.ts | 9 +- 4 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 spec-types/R3TD-6.R3-3.T37.function-substitutes.ts diff --git a/spec-types/R3TD-6.R3-3.T37.function-substitutes.ts b/spec-types/R3TD-6.R3-3.T37.function-substitutes.ts new file mode 100644 index 0000000..62acdcd --- /dev/null +++ b/spec-types/R3TD-6.R3-3.T37.function-substitutes.ts @@ -0,0 +1,108 @@ +// R3TD-6 / R3-3 / T37 A substitute of a function type, or of an interface with call signatures, is called like the +// function: each call has the setup API (`listener('saved').returns('ack')`), and the assertion and configure views +// are callable too (`listener.received(1)('saved')`, `listener[received](1)('saved')`, +// `listener[configure]()('saved').returns('ack')`). +import { Substitute, SubstituteOf, Arg, received, didNotReceive, configure, mimick, returns, throws } from '../src' +import { assert, Equals, expectType } from './helpers' + +type Listener = (event: string) => string +const listener = Substitute.for() +listener('saved').returns('ack') +listener('saved').returns('ack', 'again') +listener(Arg.any()).returns('any') +listener(Arg.is(event => event.length > 3)).throws(new Error()) +listener(Arg.all()).mimicks(event => event.toUpperCase()) +listener('saved')[returns]('ack') +listener('saved')[throws](new Error()) +listener.received(1)('saved') +listener.received()(Arg.any()) +listener.didNotReceive()('deleted') +listener.didNotReceive()(Arg.all()) +listener[received](1)('saved') +listener[didNotReceive]()(Arg.is(event => event === '')) +listener[configure]()('saved').returns('ack') +listener[configure]()(Arg.all()).mimicks(event => event) +listener[mimick](event => event) +const asListener: Listener = listener +const answer: string = listener('saved') +expectType>(listener) + +// @ts-expect-error the configured value keeps the return type +listener('saved').returns(1) +// @ts-expect-error the arguments keep their types +listener(1) +// @ts-expect-error the arguments keep their types in the assertion view +listener.received(1)(1) +// @ts-expect-error the arguments keep their types in the assertion view +listener[received](1)(1) +// @ts-expect-error the arguments keep their types in the configure view +listener[configure]()(1).returns('x') +// @ts-expect-error a call in the assertion view returns nothing +listener.received(1)('saved').returns('x') +// @ts-expect-error the configure view only offers the setup API, not the value +const configured: string = listener[configure]()('saved') +// @ts-expect-error the call has a parameter +listener.received(1)() + +// Overloads, a promise and void +interface Format { + (value: number): string + (value: string, radix: number): number +} +const format = Substitute.for() +format(1).returns('1') +format('10', 2).returns(2) +format.received()('10', 2) +format[configure]()(Arg.all()).returns('x') +// @ts-expect-error the overload taking a number returns a string +format(1).returns(1) +// @ts-expect-error no overload takes a string alone +format('10') + +type Load = (id: number) => Promise +const load = Substitute.for() +load(1).resolves('one') +load(Arg.any()).rejects(new Error()) +// @ts-expect-error the promise resolves to a string +load(1).resolves(1) + +type Notify = () => void +const notify = Substitute.for() +notify().returns() +notify.received(2)() + +// An interface with a call signature and members +interface Counter { + (step: number): number + count: number + reset(): void +} +const counter = Substitute.for() +counter(1).returns(2) +counter.count.returns(5) +counter.reset().returns() +counter.received()(1) +counter.received().reset() +counter.received().count = 3 +counter[configure]()(2).returns(4) +counter[configure]().count.returns(6) +const asCounter: Counter = counter +// @ts-expect-error the call returns a number +counter(1).returns('2') + +// A function type as a member keeps working as before +interface Emitter { listener: Listener } +const emitter = Substitute.for() +emitter.listener('saved').returns('ack') +emitter.received().listener('saved') + +// Types that are not callable get no call signatures +interface Calculator { add(a: number, b: number): number } +const calculator = Substitute.for() +// @ts-expect-error a Calculator is not callable +calculator(1) +// @ts-expect-error not callable in the assertion view either +calculator.received()(1) +assert>() + +export { asListener, asCounter, configured } diff --git a/src/api/Substitute.ts b/src/api/Substitute.ts index 758fa15..3fd61b5 100644 --- a/src/api/Substitute.ts +++ b/src/api/Substitute.ts @@ -4,15 +4,19 @@ import { createSubstitute } from '../internals' /** * The type of a substitute for `T`: every member of `T` with the setup API (`.returns`, `.throws`, `.mimicks`, and * `.resolves` / `.rejects` for promises), plus `received` / `didNotReceive` and the symbol API (`[received]`, - * `[didNotReceive]`, `[configure]`, `[mimick]`, `[clearReceivedCalls]`). It is assignable to `T`. + * `[didNotReceive]`, `[configure]`, `[mimick]`, `[clearReceivedCalls]`). When `T` is a function type, calls of the + * substitute itself have the setup API too (`listener('saved').returns('ack')`). It is assignable to `T`. */ export type SubstituteOf = ObjectSubstitute & T export class Substitute { /** - * Creates a substitute for `T` (an interface, a class or any other type): `const calculator = Substitute.for()`. + * Creates a substitute for `T` (an interface, a class, a function type or any other type): + * `const calculator = Substitute.for()`. * Configure it with `calculator.add(1, 2).returns(3)`, pass it to the code under test as a `T`, and check the calls * with `calculator.received().add(1, 2)`. Members that were not configured return a substitute of their own. + * A substitute of a function type is configured and checked through its calls: `listener('saved').returns('ack')`, + * `listener.received(1)('saved')`. */ public static for(): SubstituteOf { return createSubstitute() as SubstituteOf diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index f7ad559..3d9dcf8 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -84,9 +84,12 @@ type AssertionMembers = { [P in Extract]: AssertionMemb /** * The object returned by `received()` / `didNotReceive()`: calls return nothing, property reads and writes keep the - * member type (`sub.received().isEnabled = true`). + * member type (`sub.received().isEnabled = true`). A substitute of a function type is callable here as well + * (`listener.received(1)('saved')`, T37). */ -export type TerminatingObject = { indexed: IndexedAssertionMembers, plain: AssertionMembers }[IndexKind] +export type TerminatingObject = + { indexed: IndexedAssertionMembers, plain: AssertionMembers }[IndexKind] & + FunctionSubstitute, 'assertion'> type ConfigurationMember = FunctionSubstitute, 'configure'> & ConfigurationResult TValue> @@ -101,6 +104,7 @@ type ConfigurationMembers = { /** * The object returned by `sub[configure]()`. Member reads and calls on it are always setups, so they only expose the * setup API. The string forms (`.returns`, `.throws`, ...) are always offered here: the configured value is never - * returned from this view, so there is nothing for them to conflict with. + * returned from this view, so there is nothing for them to conflict with. A substitute of a function type is callable + * here as well (`listener[configure]()('saved').returns('ack')`, T37). */ -export type ConfigureView = ConfigurationMembers, T> +export type ConfigureView = ConfigurationMembers, T> & FunctionSubstitute, 'configure'> diff --git a/src/api/types/index.ts b/src/api/types/index.ts index db14535..cd1cc9a 100644 --- a/src/api/types/index.ts +++ b/src/api/types/index.ts @@ -1,8 +1,13 @@ import { ObjectSubstituteTransformation } from './Substitute' import { ObjectSubstituteMethods } from './SubstituteMethods' +import { FunctionSubstitute } from './FunctionSubstitute' -export type ObjectSubstitute = - ObjectSubstituteMethods & +// A substitute of a function type (or of an interface with call signatures) is called like the function, and each call +// has the setup API (`listener('saved').returns('ack')`, T37). These signatures come before `T`'s own in +// `SubstituteOf`, so a call resolves against them first. +export type ObjectSubstitute = + FunctionSubstitute, 'substitute'> & + ObjectSubstituteMethods & ObjectSubstituteTransformation export { received, didNotReceive, clearReceivedCalls, mimick, configure } from './SubstituteMethods' From 13418c161325e5c4539190d85f00c6fa8c6f3f10 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:04:40 +0000 Subject: [PATCH 061/106] types: unions whose variants declare null-only members no longer reduce to never (T36, R3TD-4) `Substitute.for<{ data: string[]; error: null } | { data: null; error: Error }>()` and the `?: undefined` XOR form were `never` on TypeScript 3.9 and newer: the substitute's setup API for `data` met `null` in one variant and `error` met `null` in the other, and TypeScript drops a variant whose literal-typed member reduces to never. ObjectSubstitute now adds, for a union T only, one patch per variant that declares such a member as `never` itself. TypeScript keeps a variant when one of the intersected types declares the member `never`, so every variant is kept and still assignable to its variant of T. The member reads as the setup API intersected with the other variants' types, and `.returns(...)` takes the type the variants have in common: `result.data.returns(['a'])`, `result.data.returns(null)`, `result.error.returns(null)`. A union in which only some variants declare such a member keeps all its variants now (`load.status.returns('idle')` still compiles, `load.data` is still `string` with the setup API). A member that is null-only in every variant keeps its plain type (T25). Unions without such members (Cat | Dog), non-union types and generic code are unchanged (the patch is `unknown` there). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .../R3TD-4.T36.null-only-union-variants.ts | 76 +++++++++++++++++++ src/api/types/Substitute.ts | 27 +++++++ src/api/types/index.ts | 7 +- 3 files changed, 108 insertions(+), 2 deletions(-) create mode 100644 spec-types/R3TD-4.T36.null-only-union-variants.ts diff --git a/spec-types/R3TD-4.T36.null-only-union-variants.ts b/spec-types/R3TD-4.T36.null-only-union-variants.ts new file mode 100644 index 0000000..65b8956 --- /dev/null +++ b/spec-types/R3TD-4.T36.null-only-union-variants.ts @@ -0,0 +1,76 @@ +// R3TD-4 / T36 A union whose variants declare members as only null/undefined (`{ data: T; error: null } | +// { data: null; error: E }`, and the `?: undefined` "XOR" form) does not reduce Substitute.for<...>() to `never`. +// Such a member reads as the setup API intersected with the other variants' types, and `.returns(...)` takes the type +// the variants have in common (`string[] | null`). Unions without such members (Cat | Dog) are unchanged. +import { Substitute, SubstituteOf, configure, received } from '../src' +import { assert, Equals, expectType } from './helpers' + +// PostgREST / Supabase style +type QueryResult = { data: string[]; error: null } | { data: null; error: Error } +const result = Substitute.for() +result.data.returns(['a']) +result.data.returns(null) +result.error.returns(null) +result.error.returns(new Error('x')) +result[configure]().data.returns(['b']) +result.received().data +result.received().error = null +result[received](1).data = ['a'] +const asResult: QueryResult = result +const data: string[] = result.data +// @ts-expect-error the configured value has the members' common type +result.data.returns('a') +// @ts-expect-error the assertion view keeps the members' common type +result.received().error = 'x' + +// The XOR form, which compiled with 2.0.0-beta.4 +type Outcome = { ok: true; value: string; error?: undefined } | { ok: false; value?: undefined; error: Error } +const outcome = Substitute.for() +outcome.ok.returns(true) +outcome.value.returns('x') +outcome.value.returns(undefined) +outcome.error.returns(new Error()) +outcome.received().value = undefined +const asOutcome: Outcome = outcome +// @ts-expect-error `ok` is a boolean +outcome.ok.returns('yes') + +// Only some variants declare the member as null +type Load = { status: 'idle'; data: null } | { status: 'done'; data: string } +const load = Substitute.for() +load.status.returns('idle') +load.status.returns('done') +load.data.returns('x') +load.data.returns(null) +const asLoad: Load = load +// @ts-expect-error `status` is 'idle' | 'done' +load.status.returns('loading') + +// A member that is only null/undefined in every variant keeps its plain type (T25) +type Both = { kind: 'a'; a: number; gone: null } | { kind: 'b'; b: number; gone: null } +const both = Substitute.for() +both.kind.returns('a') +assert>() +const asBoth: Both = both + +// Unions without such members +interface Cat { kind: 'cat'; name: string; meow(): string } +interface Dog { kind: 'dog'; name: string; bark(times: number): string } +const pet = Substitute.for() +pet.kind.returns('cat') +pet.name.returns('Rex') +pet.received().name +const asPet: Cat | Dog = pet +expectType>(pet) +// @ts-expect-error not a member of every variant +pet.meow() +// @ts-expect-error `kind` is 'cat' | 'dog' +pet.kind.returns('cow') + +// In generic code nothing changes +export function generic(sub: SubstituteOf) { + sub.received().data + return sub +} + +export { asResult, asOutcome, asLoad, asBoth, asPet, data } diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index 3d9dcf8..596c124 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -55,6 +55,33 @@ type SubstituteMembers = { /** The members of a substitute (without the assertion and configuration methods), each with its setup API. */ export type ObjectSubstituteTransformation = SubstituteMembers, T> +// Unions whose variants declare a member as only null/undefined (T36, R3TD-4): +// { data: string[]; error: null } | { data: null; error: Error } +// { ok: true; value: string; error?: undefined } | { ok: false; value?: undefined; error: Error } +// The members above are mapped from the members the variants have in common, so `data` has the setup API of +// `string[] | null`. `SubstituteOf` intersects them with `T`, i.e. with each variant, and in the variant where +// `data` is `null` the setup API meets `null`. That gives `never`, and TypeScript drops a variant that has a `never` +// member which is `null` or a literal in one of the intersected types. When every variant has such a member, the whole +// substitute became `never`. +// The patch below gives such a member the type `never` itself in that variant. TypeScript keeps a variant in which one +// of the intersected types declares the member as `never`, so every variant is kept. The member then reads as the +// setup API intersected with the other variants' types (`result.data` is `string[]` with `.returns(...)`), and each +// variant of the substitute is still assignable to that variant of `T`. + +// The members that are only null/undefined in `TVariant` but not in every variant of `T`. +type VariantNullKeys = { + [P in keyof TVariant]-?: + [NonNullable] extends [never] ? (P extends keyof T ? ([NonNullable] extends [never] ? never : P) : never) : + never +}[keyof TVariant] + +// `unknown` for a type that is not a union (and in generic code, where the check cannot be decided). +type VariantPatch = [T] extends [TVariant] ? unknown : { [P in VariantNullKeys]: never } + +/** For a union `T`, a union of one patch per variant (see above); `unknown` for any other type. */ +export type UnionVariantPatch = UnionVariantPatchOf +type UnionVariantPatchOf = TVariant extends unknown ? VariantPatch : never + // In the assertion view, a member that is not callable keeps its declared type, including `undefined` for an optional // property (`sub.received().note = undefined`, TD-7). A callable member offers the assertion signatures (calls return // nothing) on the member type without `null | undefined`. diff --git a/src/api/types/index.ts b/src/api/types/index.ts index cd1cc9a..c50c501 100644 --- a/src/api/types/index.ts +++ b/src/api/types/index.ts @@ -1,14 +1,17 @@ -import { ObjectSubstituteTransformation } from './Substitute' +import { ObjectSubstituteTransformation, UnionVariantPatch } from './Substitute' import { ObjectSubstituteMethods } from './SubstituteMethods' import { FunctionSubstitute } from './FunctionSubstitute' // A substitute of a function type (or of an interface with call signatures) is called like the function, and each call // has the setup API (`listener('saved').returns('ack')`, T37). These signatures come before `T`'s own in // `SubstituteOf`, so a call resolves against them first. +// `UnionVariantPatch` keeps a union whose variants declare members as only null/undefined from reducing to `never` +// once `SubstituteOf` intersects this with `T` (T36); it is `unknown` for any other type. export type ObjectSubstitute = FunctionSubstitute, 'substitute'> & ObjectSubstituteMethods & - ObjectSubstituteTransformation + ObjectSubstituteTransformation & + UnionVariantPatch export { received, didNotReceive, clearReceivedCalls, mimick, configure } from './SubstituteMethods' export { returns, throws, resolves, rejects, mimicks } from './SubstitutionLevel' From 471c08faf41bc06583b99f62f3f8ebfb9a9141ce Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:06:35 +0000 Subject: [PATCH 062/106] test(types): pin the optional-callback limitation of the assertion view (T34, R3TD-2) `widget.received().onChange = undefined` for `onChange?: (value: string) => void` cannot compile under strictNullChecks on TypeScript 3.6 to 5.9 without breaking `widget.received().onChange('x')`: TypeScript gives a mapped property one type for reads and writes, and a type that accepts `undefined` cannot be called without a "possibly undefined" error. The fixture pins the limitation (string and symbol forms) and checks the two ways around it, which the runtime treats as a set to `undefined`: `(widget.received() as Widget).onChange = undefined` and `widget.received().onChange = Arg.any.not('function')`. It also checks that calls of optional callbacks are asserted as calls, and the same in generic code over a constraint (which fails at 6cb1c22 and passes since T33). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .../R3TD-2.T34.optional-callback-assertion.ts | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 spec-types/R3TD-2.T34.optional-callback-assertion.ts diff --git a/spec-types/R3TD-2.T34.optional-callback-assertion.ts b/spec-types/R3TD-2.T34.optional-callback-assertion.ts new file mode 100644 index 0000000..eccf7f2 --- /dev/null +++ b/spec-types/R3TD-2.T34.optional-callback-assertion.ts @@ -0,0 +1,47 @@ +// R3TD-2 / T34 Checking that the code under test cleared an OPTIONAL FUNCTION-TYPED property. +// Limitation (TypeScript 3.6 to 5.9 with strictNullChecks): `widget.received().onChange = undefined` does not compile. +// In the assertion view `onChange` is callable (`widget.received().onChange('x')` checks a call), and TypeScript uses +// one type for reading and writing such a property: a type that accepts `undefined` cannot be called without a +// "possibly undefined" error. Optional properties that are not functions accept `undefined` (TD-7.T30). +// Ways around it, all checked at runtime the same way (a property set to `undefined`): +// (widget.received() as Widget).onChange = undefined +// widget.received().onChange = Arg.any.not('function') (a set to any value that is not a function) +import { Substitute, SubstituteOf, Arg, received, didNotReceive } from '../src' + +interface Widget { + note?: string + onChange?: (value: string) => void + onClose?(): void +} +const widget = Substitute.for() +const detach = (w: Widget) => { w.note = undefined; w.onChange = undefined } +detach(widget) + +widget.received().note = undefined +// calls of optional callbacks are checked as calls +widget.received().onChange('x') +widget.received().onChange(Arg.all()) +widget.didNotReceive().onClose() +widget[received](1).onChange(Arg.any()) + +// @ts-expect-error limitation: an optional function-typed property does not accept undefined in the assertion view +widget.received().onChange = undefined +// @ts-expect-error limitation, also in the symbol form +widget[received](1).onChange = undefined + +// the ways around it +;(widget.received() as Widget).onChange = undefined +;(widget[received](1) as Widget).onChange = undefined +;(widget.didNotReceive() as Widget).onChange = undefined +;(widget[didNotReceive]() as Widget).onChange = undefined +widget.received().onChange = Arg.any.not('function') + +// @ts-expect-error the cast keeps the property's type +;(widget.received() as Widget).onChange = 'x' + +// The same in generic code over a constraint (T33) +export function cleared(sub: SubstituteOf) { + sub.received().note = undefined + sub.received().onChange('x') + ;(sub.received() as Widget).onChange = undefined +} From 289a39dc2e73fc9e3d64aae2d35e44109edd736e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:09:42 +0000 Subject: [PATCH 063/106] fix(call sites): format "called at" normally, read frames from a separate capture, never change Error.prepareStackTrace (E1, E2, E4, E5) E4 (R3-ADV-3): a received call keeps one captured stack, which V8 and Node.js format as usual when a message shows it, so source maps (node --enable-source-maps, jest with ts-jest, vitest vm pools) and stack-trace packages apply. The structured frames that D25 compares are read from a separate capture, taken when an operation hands out a proxy; only the latest one is kept, so received calls carry no second stack. E5 (R3-ADV-4): reading structured call sites saves the full property descriptor of Error.prepareStackTrace, defines a data property for that moment and restores the exact descriptor. A non-configurable accessor (the stack-chain package on Node.js < 21) is never touched: there are no structured frames then, and adjacency decides. E1 (R3-ADV-1): a method read that is invoked later (a method reference handed to the code under test) takes the call site of the invocation. Only `sub.method(...)`, invoked right after the read on the substitute it was read from, keeps the read's call site. E2 (R3-ADV-6): adjacency alone decides only when neither operation has a frame. Async frames that V8 appends to a promise job's stack are not frames of the operation, so a call made from a promise job stays recorded when the test then configures what it returned. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/regression/fixes/round4.test.ts | 205 +++++++++++++++++++++++++++ src/internals/CallRecord.ts | 41 ++---- src/internals/CallSite.ts | 166 ++++++++++++++-------- src/internals/Engine.ts | 72 ++++++---- src/internals/SubstituteState.ts | 7 +- 5 files changed, 373 insertions(+), 118 deletions(-) diff --git a/spec/regression/fixes/round4.test.ts b/spec/regression/fixes/round4.test.ts index 1e2a6b5..2cb268b 100644 --- a/spec/regression/fixes/round4.test.ts +++ b/spec/regression/fixes/round4.test.ts @@ -1,11 +1,216 @@ import test from 'ava' import { spawnSync } from 'child_process' +import * as fs from 'fs' +import * as os from 'os' import * as path from 'path' +import { inspect } from 'util' + +import { Substitute, didNotReceive, received } from '../../../src' +import { SubstituteException } from '../../../src/internals/SubstituteException' // Round 4: the runtime findings of the round-3 verification (R3-*), decided in the fix spec as E1-E7. const library = path.resolve(__dirname, '../../../src/index.js') +const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') + +const messageOf = (assertion: () => unknown): string => { + try { + assertion() + } catch (error) { + if (!(error instanceof SubstituteException)) throw error + return plain(error.message) + } + throw new Error('expected the assertion to fail') +} + +// ---- code under test for E1 and E2, in functions of its own (as in a module under test) ---- + +class UserService { + constructor(private readonly fetchUser: (id: number) => any) { } + load(id: number) { return this.fetchUser(id) } +} + +function openWith(connect: (url: string) => any) { + return connect('db://x') +} + +const loadUser = (getUser: (id: number) => any, id: number) => Promise.resolve(id).then(getUser) + +test('R3-ADV-1 (E1) a method reference that the code under test invokes later is a call made where it is invoked', t => { + const api = Substitute.for() + const service = new UserService(api.getUser) // the test passes a method reference + const user = service.load(1) // the code under test calls api.getUser(1) + user.name.returns('ann') // the test configures the value it got back + t.is(user.name, 'ann') + t.notThrows(() => api.received(1).getUser(1)) + t.throws(() => api.didNotReceive().getUser(1), { instanceOf: SubstituteException }) + // the call site of the call is the invocation in UserService.load, not the read in the test + const message = messageOf(() => api.received(2).getUser(1)) + t.regex(message, /› ✔ @Substitute\.getUser\(1\)\n {4}called at UserService\.load /) + + const driver = Substitute.for() + const connection = openWith(driver.connect) + connection.isOpen.returns(true) + t.true(connection.isOpen) + t.notThrows(() => driver.received(1).connect('db://x')) + t.throws(() => driver.didNotReceive().connect('db://x'), { instanceOf: SubstituteException }) + t.regex(messageOf(() => driver.received(2).connect('db://x')), /called at openWith /) + + // a method read and invoked in one expression is still one expression: a setup retracts all of it + const app = Substitute.for() + app.getCalc().add(1, 2).returns(3) + app.logger.child('x').info.returns(undefined) + t.is(inspect(app), '@Substitute {\n}') + t.is(app.getCalc().add(1, 2), 3) + // and a method reference invoked in the test, with another `this`, is a call as well + const getCalc = app.getCalc + getCalc().add(5, 5).returns(10) + t.is(app.getCalc().add(5, 5), 10) +}) + +test('R3-ADV-6 (E2) a call made from a promise job stays recorded when the test then configures what it returned', async t => { + const getUser = Substitute.for() + const user = await loadUser(getUser, 1) // getUser(1) is invoked by a promise job: no frame of its own + user.name.returns('ann') + t.is(user.name, 'ann') + t.notThrows(() => getUser[received](1)(1)) + t.throws(() => getUser[didNotReceive]()(1), { instanceOf: SubstituteException }) + + // the same for a method of a substitute + const api = Substitute.for() + const loaded: any = await Promise.resolve(2).then(api.fetch) + loaded.status.returns(200) + t.notThrows(() => api.received(1).fetch(2)) +}) + +test('R3-ADV-6 (E2) adjacency alone decides only when neither operation has a frame', t => { + const result = runScript(` + const { Substitute } = require(${JSON.stringify(library)}) + const { inspect } = require('util') + function getConnection(driver) { return driver.connect('db://x') } + Error.stackTraceLimit = 0 + const driver = Substitute.for() + const connection = getConnection(driver) + connection.isOpen.returns(true) + const app = Substitute.for() + app.getCalc().add(1, 2).returns(99) + console.log(JSON.stringify({ driver: inspect(driver), app: inspect(app), result: app.getCalc().add(1, 2) })) + `) + // without frames, a setup right after the call that returned the value retracts that call (the round-2 rule) + t.deepEqual(result, { driver: '@Substitute {\n}', app: '@Substitute {\n}', result: 99 }) +}) + +/** Compiles a TypeScript file with a source map into a new directory, and returns the path of the JavaScript file. */ +const compileWithSourceMap = (source: string): string => { + const typescript = require('typescript') + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'substitute-source-map-')) + const { outputText, sourceMapText } = typescript.transpileModule(source, { + fileName: 'checkout.ts', + compilerOptions: { module: typescript.ModuleKind.CommonJS, target: typescript.ScriptTarget.ES2019, sourceMap: true } + }) + fs.writeFileSync(path.join(directory, 'checkout.ts'), source) + fs.writeFileSync(path.join(directory, 'checkout.js'), outputText) + fs.writeFileSync(path.join(directory, 'checkout.js.map'), sourceMapText) + return path.join(directory, 'checkout.js') +} + +test('R3-ADV-3 (E4) "called at" lines keep source maps, also where Error.prepareStackTrace is not set (as in jest)', t => { + const source = [ + `import { Substitute } from ${JSON.stringify(library)}`, + '', + '// types and blank lines that are not in the JavaScript output, so that the lines differ', + 'interface Metrics {', + ' increment(name: string): void', + ' child: Metrics', + '}', + '', + 'type Unused = { a: string, b: string }', + '', + "if (process.env.WITHOUT_PREPARE_STACK_TRACE) delete (Error as any).prepareStackTrace", + 'const metrics = Substitute.for()', + "metrics.increment('x')", + "metrics.child.increment('y')", + 'const messages: string[] = []', + "try { metrics.received(2).increment('x') } catch (error: any) { messages.push(error.message) }", + 'try { metrics.received(2).child } catch (error: any) { messages.push(error.message) }', + 'console.log(JSON.stringify(messages))' + ].join('\n') + const lines = source.split('\n') + const lineOf = (text: string) => lines.indexOf(text) + 1 + const script = compileWithSourceMap(source) + for (const withoutPrepareStackTrace of [false, true]) { + const result = spawnSync(process.execPath, ['--enable-source-maps', script], { + encoding: 'utf8', + env: { ...process.env, NO_COLOR: '1', ...(withoutPrepareStackTrace ? { WITHOUT_PREPARE_STACK_TRACE: '1' } : {}) } + }) + t.is(result.status, 0, result.stderr) + const [increment, child] = JSON.parse(result.stdout) as string[] + const calledAt = (message: string) => message.split('\n').filter(line => line.includes('called at')) + t.deepEqual(calledAt(increment).map(line => /checkout\.(ts|js):(\d+)/.exec(line)?.slice(1).join(':')), [`ts:${lineOf("metrics.increment('x')")}`], + `the call site maps to the TypeScript line (${withoutPrepareStackTrace ? 'without' : 'with'} Error.prepareStackTrace)`) + // a nested read whose structured call site was read for the chain (D25) keeps its text as well + t.deepEqual(calledAt(child).map(line => /checkout\.(ts|js):(\d+)/.exec(line)?.slice(1).join(':')), [`ts:${lineOf("metrics.child.increment('y')")}`]) + } +}) + +test('R3-ADV-4 (E5) reading call sites never changes Error.prepareStackTrace for the process', t => { + const scenario = ` + const { Substitute } = require(${JSON.stringify(library)}) + const { inspect } = require('util') + const descriptor = () => { const d = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace'); return d && { ...d } } + const before = descriptor() + // setups and checks that read structured call sites (D25 chains), and a failure message + const app = Substitute.for() + app.getCalc().add(1, 2).returns(3) + app.logger.info('x') + app.logger.received(1).info('x') + function getConnection(driver) { return driver.connect('db://x') } + const driver = Substitute.for() + getConnection(driver).isOpen.returns(true) + let message = '' + try { app.logger.received(2).info('x') } catch (error) { message = error.message } + const after = descriptor() + let syntaxError + try { JSON.parse('{') } catch (error) { syntaxError = error } + console.log(JSON.stringify({ + unchanged: JSON.stringify(Object.keys(before || {})) === JSON.stringify(Object.keys(after || {})) && + (before === undefined ? after === undefined : Object.keys(before).every(key => before[key] === after[key])), + stackIsText: typeof new Error('y').stack === 'string' && typeof syntaxError.stack === 'string', + calledAt: message.includes('called at'), + setupRecordedNothing: inspect(app) === '@Substitute {\\n received:\\n logger\\n}', + codeUnderTestCallKept: (() => { try { driver.received(1).connect('db://x'); return true } catch { return false } })(), + result: app.getCalc().add(1, 2) + })) + ` + const formatter = `(error, frames) => 'formatted ' + error + frames.map(frame => '\\n at ' + frame).join('')` + // stack-chain installs an accessor whose setter stores the formatter and whose getter returns its own wrapper, with + // Object.defineProperty and no attributes: non-configurable where Node.js has no Error.prepareStackTrace of its own + // (before 21), configurable where it has one + const accessor = (attributes: string) => ` + let current = ${formatter} + const installed = (error, frames) => current(error, frames) + Object.defineProperty(Error, 'prepareStackTrace', { ${attributes} get: () => installed, set: value => { current = value } })` + const setups: Record = { + 'an accessor as stack-chain installs it': accessor(''), + 'a non-configurable accessor': `delete Error.prepareStackTrace; ${accessor('configurable: false,')}`, + 'a configurable accessor': accessor('configurable: true,'), + // source-map-support: a data property + 'a data property (source-map-support)': `Error.prepareStackTrace = ${formatter}`, + 'a non-configurable data property': `Object.defineProperty(Error, 'prepareStackTrace', { value: ${formatter}, writable: true, configurable: false })`, + 'no property at all': `delete Error.prepareStackTrace` + } + for (const [name, setup] of Object.entries(setups)) { + const result = runScript(setup + scenario) + // a non-configurable accessor cannot be swapped for a moment: then there are no structured frames, and adjacency + // decides (E2), which also retracts the call that the code under test made right before the setup + const withFrames = !name.startsWith('a non-configurable accessor') + t.deepEqual(result, { + unchanged: true, stackIsText: true, calledAt: true, setupRecordedNothing: true, codeUnderTestCallKept: withFrames, result: 3 + }, name) + } +}) + /** Runs a script with the library in a child process, and returns what it prints as JSON. */ const runScript = (script: string, options: { args?: string[], env?: Record } = {}): any => { const result = spawnSync(process.execPath, [...(options.args ?? []), '-e', script], { diff --git a/src/internals/CallRecord.ts b/src/internals/CallRecord.ts index a2745d9..6566a93 100644 --- a/src/internals/CallRecord.ts +++ b/src/internals/CallRecord.ts @@ -1,4 +1,4 @@ -import { CallSite, Frame, StackHolder, captureStack } from './CallSite' +import { StackHolder, captureStack, forgetHandOutFrame, stackText } from './CallSite' export type RecordKind = 'get' | 'set' | 'call' @@ -19,8 +19,8 @@ const nextSequence = (): number => ++sequence export class CallRecord { public seq: number public retracted = false - /** The captured stack, wrapped in a CallSite (D30: only when it is needed). */ - private _site: StackHolder | CallSite + /** The captured stack (its call site), formatted as text only when a message shows it (E4). */ + private _stack: StackHolder /** * D26: an invocation through `x.call(...)` / `x.apply(...)` is recorded once, with two readings: a call of x's * member `call` / `apply` with the raw arguments, and a direct call of x. Each reading is a record of its own @@ -40,40 +40,27 @@ export class CallRecord { public chainPrevious?: CallRecord ) { this.seq = nextSequence() - this._site = captureStack(stackStart) - } - - private get site(): CallSite { - const site = this._site - if (site instanceof CallSite) return site - const wrapped = new CallSite(site) - this._site = wrapped - return wrapped + this._stack = captureStack(stackStart) } /** The call site as a stack trace text, for messages. */ public get stack(): string | undefined { - try { - return this.site.stack - } catch { - return undefined - } - } - - /** The first frame outside the library (D25), or null when there is none. */ - public get frame(): Frame | null { - return this.site.frame + return stackText(this._stack) } /** - * Turns a property read into an invocation. When the invocation directly follows the read (the usual - * `sub.method(...)`), the read already captured the right call site. + * Turns a property read into an invocation. E1: the invocation is a call made where it is invoked, which is not + * always where the method was read (a method reference handed to the code under test, `new Service(api.getUser)`, + * is invoked later, elsewhere), so it takes the call site of the invocation, unless the caller knows that the read + * and the invocation are the same expression (`sub.method(...)`). */ - public convertToCall(args: any[], stackStart: Function): void { - const directlyInvoked = this.seq === currentSequence() + public convertToCall(args: any[], stackStart: Function, sameExpressionAsRead = false): void { this.kind = 'call' this.args = args - if (!directlyInvoked) this._site = captureStack(stackStart) + if (!sameExpressionAsRead) { + this._stack = captureStack(stackStart) + forgetHandOutFrame(this) + } this.seq = nextSequence() } } diff --git a/src/internals/CallSite.ts b/src/internals/CallSite.ts index f30eb8e..c049218 100644 --- a/src/internals/CallSite.ts +++ b/src/internals/CallSite.ts @@ -1,12 +1,15 @@ /** * Call sites of operations on substitutes: the first stack frame outside the library. * - * Every received call keeps its call site, to show it in assertion messages. Collecting a stack trace is cheap; it - * is the formatting into text that costs, so V8 does it lazily, when `stack` is first read. The engine also needs to - * know, now and then, whether two operations come from the same expression in a test (D25). For that it reads the - * structured call site (file and enclosing function) of a captured stack, once, by formatting it with a - * prepareStackTrace that returns the V8 call sites. The text is then produced from those call sites when a message - * needs it. + * Every received call keeps a captured stack trace (only its call site), to show it in assertion messages. Capturing + * is cheap; it is the formatting into text that costs, so V8 does it lazily, when `stack` is first read, and then + * formats it like any other stack trace: Error.prepareStackTrace, source maps (node --enable-source-maps, jest, + * vitest) and stack-trace packages all apply (E4). + * + * The engine also needs to know, now and then, whether two operations come from the same expression in a test (D25): + * whether their first frames outside the library are in the same file and the same enclosing function. For that it + * reads the structured call sites of a SEPARATE capture, with a prepareStackTrace that returns the V8 call sites. That + * capture is never used for text. Reading it changes Error.prepareStackTrace only for that moment (E5). */ type V8CallSite = { @@ -14,7 +17,7 @@ type V8CallSite = { getFunctionName(): string | null getEnclosingLineNumber?(): number | null getEnclosingColumnNumber?(): number | null - toString(): string + isAsync?(): boolean } /** A captured stack trace: V8 installs a lazily formatted `stack` property on it. */ @@ -45,35 +48,74 @@ export const captureStack = (stackStart: Function): StackHolder => { return holder } +/** The stack trace of a holder as text, formatted the usual way (undefined if it is not text). */ +export const stackText = (holder: StackHolder): string | undefined => { + try { + const stack = holder.stack + return typeof stack === 'string' ? stack : undefined + } catch { + return undefined + } +} + +const PREPARE_STACK_TRACE = 'prepareStackTrace' const returnCallSites = (_error: unknown, callSites: unknown) => callSites -/** Reads the stack of a holder with a prepareStackTrace that returns the V8 call sites (undefined if it cannot). */ -const readCallSites = (holder: StackHolder): { callSites?: V8CallSite[], text?: unknown } => { - const errorConstructor = Error as { prepareStackTrace?: unknown } - const prepare = errorConstructor.prepareStackTrace - let replaced = false +/** + * E5: the descriptor that puts returnCallSites in place of Error.prepareStackTrace for a moment, or undefined when that + * is not possible without changing the property for good: a non-configurable accessor (as the stack-chain package + * installs) or a non-configurable, non-writable value, or an Error that cannot be extended. + */ +const temporaryDescriptor = (original: PropertyDescriptor | undefined): PropertyDescriptor | undefined => { + if (original === undefined || original.configurable === true) + return { value: returnCallSites, writable: true, configurable: true, enumerable: original?.enumerable === true } + if ('value' in original && original.writable === true) return { value: returnCallSites } + return undefined +} + +/** + * Reads the structured call sites of a holder (undefined if it cannot). Error.prepareStackTrace is replaced by a data + * property only while the holder's stack is formatted, and the exact property descriptor is put back afterwards, so + * that the process's stack formatting never changes (E5). + */ +const readCallSites = (holder: StackHolder): V8CallSite[] | undefined => { + const errorConstructor = Error as unknown as Record + let original: PropertyDescriptor | undefined try { - errorConstructor.prepareStackTrace = returnCallSites - replaced = errorConstructor.prepareStackTrace === returnCallSites - } catch { /* a frozen Error: no structured call sites */ } + original = Object.getOwnPropertyDescriptor(errorConstructor, PREPARE_STACK_TRACE) + } catch { + return undefined + } + const temporary = temporaryDescriptor(original) + if (temporary === undefined) return undefined + try { + Object.defineProperty(errorConstructor, PREPARE_STACK_TRACE, temporary) + } catch { + return undefined + } let value: unknown try { value = holder.stack } catch { value = undefined } finally { - if (replaced) { - try { - errorConstructor.prepareStackTrace = prepare - } catch { /* it was writable a moment ago */ } - } + try { + if (original === undefined) delete errorConstructor[PREPARE_STACK_TRACE] + else Object.defineProperty(errorConstructor, PREPARE_STACK_TRACE, original) + } catch { /* it could be redefined a moment ago */ } } - return Array.isArray(value) ? { callSites: value as V8CallSite[] } : { text: value } + return Array.isArray(value) ? value as V8CallSite[] : undefined } +/** + * The frame of a call site. An async frame is no frame of the operation: V8 appends the async functions that await the + * current promise job to its stack (async stack traces), so a call made from a promise job, which has no frame of its + * own, would otherwise look like a call made by the test function that awaits it (E2). + */ const frameOf = (callSite: V8CallSite | undefined): Frame | null => { if (callSite === undefined) return null try { + if (typeof callSite.isAsync === 'function' && callSite.isAsync()) return null const line = typeof callSite.getEnclosingLineNumber === 'function' ? callSite.getEnclosingLineNumber() : null const column = typeof callSite.getEnclosingColumnNumber === 'function' ? callSite.getEnclosingColumnNumber() : null const enclosing = typeof line === 'number' && typeof column === 'number' ? `${line}:${column}` : callSite.getFunctionName() @@ -83,53 +125,57 @@ const frameOf = (callSite: V8CallSite | undefined): Frame | null => { } } -const formatCallSites = (holder: StackHolder, callSites: V8CallSite[]): string => { - const prepare = (Error as { prepareStackTrace?: unknown }).prepareStackTrace - if (typeof prepare === 'function') { - try { - const formatted = prepare.call(Error, holder, callSites) - if (typeof formatted === 'string') return formatted - } catch { /* fall back to the default format */ } - } - return ['Error', ...callSites.map(callSite => ` at ${String(callSite)}`)].join('\n') +/** The first frame outside the library of a capture made for that purpose, or null when there is none. */ +const frameOfCapture = (holder: StackHolder): Frame | null => { + const callSites = readCallSites(holder) + return callSites === undefined ? null : frameOf(callSites[0]) } -/** The call site of one operation. The structured frame and the text are both worked out lazily. */ -export class CallSite { - // undefined: not read yet; null: not available (no frame, or not a V8 runtime) - private _frame?: Frame | null = undefined - private _callSites?: V8CallSite[] = undefined - private _text?: string = undefined +/** The first frame outside the library of the current operation (the trap function is the stack start). */ +export const currentFrame = (stackStart: Function): Frame | null => frameOfCapture(captureStack(stackStart)) - constructor(private readonly _holder: StackHolder) { } +/* + * The frame of the operation that last handed out a proxy (or a deferred read). D25 only ever compares the frame of the + * operation that handed out the proxy that the current operation uses, when that was the most recent operation of all, + * so one capture is kept, for the latest hand-out only: the received calls do not carry a second stack each (D30). + */ +const handOut: { owner: object | undefined, capture: StackHolder | undefined, frame: Frame | null | undefined } = + { owner: undefined, capture: undefined, frame: undefined } - public static capture(stackStart: Function): CallSite { - return new CallSite(captureStack(stackStart)) - } +/** + * Captures the frame of the current operation, which hands out a proxy for `owner` (a received call). The capture of + * the same owner is kept: a method read and invoked in one expression (`sub.method(...)`) hands out twice. + */ +export const captureHandOutFrame = (owner: object, stackStart: Function): void => { + if (handOut.owner === owner) return + handOut.owner = owner + handOut.capture = captureStack(stackStart) + handOut.frame = undefined +} - /** The first frame outside the library, or null when there is none (e.g. Error.stackTraceLimit = 0). */ - public get frame(): Frame | null { - if (this._frame === undefined) { - const { callSites, text } = readCallSites(this._holder) - this._callSites = callSites - if (typeof text === 'string') this._text = text - this._frame = callSites === undefined ? null : frameOf(callSites[0]) - } - return this._frame - } +/** Forgets the capture of `owner`: its operation turned out to be another one (a method read invoked elsewhere). */ +export const forgetHandOutFrame = (owner: object): void => { + if (handOut.owner !== owner) return + handOut.owner = undefined + handOut.capture = undefined + handOut.frame = undefined +} - /** The stack trace as text (only the call site), for messages. */ - public get stack(): string | undefined { - if (this._frame === undefined) void this.frame // the call sites are read once, for the frame and the text - if (this._text !== undefined) return this._text - if (this._callSites === undefined) return undefined - return this._text = formatCallSites(this._holder, this._callSites) - } +/** The frame of the operation that handed out a proxy for `owner`, if it was the latest hand-out; otherwise null. */ +export const handOutFrame = (owner: object): Frame | null => { + if (handOut.owner !== owner || handOut.capture === undefined) return null + if (handOut.frame === undefined) handOut.frame = frameOfCapture(handOut.capture) + return handOut.frame } /** * D25: whether two operations belong to the same expression: their call sites are in the same file and the same - * enclosing function. When a call site is not available, only adjacency counts (the caller has checked it). + * enclosing function. E2: only when neither of them has a call site (stack traces are off, or structured call sites + * cannot be read) does adjacency alone decide (the caller has checked it). When exactly one of them has a call site, + * they are not the same expression: an expression in a test always has one. A call made from a promise job or + * another callback of the runtime has none. */ -export const sameExpression = (a: Frame | null, b: Frame | null): boolean => - a === null || b === null || (a.file === b.file && a.enclosing === b.enclosing) +export const sameExpression = (a: Frame | null, b: Frame | null): boolean => { + if (a === null || b === null) return a === b + return a.file === b.file && a.enclosing === b.enclosing +} diff --git a/src/internals/Engine.ts b/src/internals/Engine.ts index 5aee0b9..f4775de 100644 --- a/src/internals/Engine.ts +++ b/src/internals/Engine.ts @@ -3,7 +3,7 @@ import { inspect, InspectOptions, types } from 'util' import { constants, isSubstituteProxy, substituteMarker } from '../shared' import { ArgumentHashes, AutoEntry, Substitution, SubstituteState } from './SubstituteState' import { CallRecord, currentSequence, pairReadings, retract } from './CallRecord' -import { CallSite, Frame, sameExpression } from './CallSite' +import { Frame, captureHandOutFrame, currentFrame, handOutFrame, sameExpression } from './CallSite' import { RecordedArguments } from './RecordedArguments' import { SubstituteException } from './SubstituteException' import { assertCall, assertPropertyRead, assertSet, settle, validateExpectedCount, ExpectedCount } from './Assertions' @@ -108,13 +108,19 @@ const colorsOf = (options?: InspectOptions) => options?.colors === true // ---- substitutes and auto-substitutes --------------------------------------------------------- -export const createSubstitute = (): any => createFaceProxy(new SubstituteState()) +export const createSubstitute = (): any => { + const state = new SubstituteState() + return state.proxy = createFaceProxy(state) +} const entryProxy = (entry: AutoEntry): any => { if (entry.proxy === undefined) entry.proxy = createFaceProxy(entry) return entry.proxy } +/** The proxy of a substitute (undefined for an auto-substitute whose proxy was never handed out). */ +const proxyOf = (state: SubstituteState): any => state.owner === undefined ? state.proxy : state.owner.proxy + const faceState = (face: Face): SubstituteState => face instanceof AutoEntry ? face.state : face /* @@ -123,23 +129,22 @@ const faceState = (face: Face): SubstituteState => face instanceof AutoEntry ? f * continues the expression of the operation that handed out its proxy when that operation was the last one of * all (adjacency) and both come from the same function in the same file (their first stack frames outside the * library). So a value that the code under test got from a substitute, and returned, does not take the code under - * test's call with it when the test configures or checks that value. Without stack frames (Error.stackTraceLimit - * = 0), adjacency alone decides. + * test's call with it when the test configures or checks that value. Only when neither operation has a stack frame + * (Error.stackTraceLimit = 0, or structured call sites cannot be read) does adjacency alone decide (E2). */ /** The frame of the current operation, read only when it is needed (the trap function is the stack start). */ -const frameAt = (stackStart: Function) => (): Frame | null => CallSite.capture(stackStart).frame +const frameAt = (stackStart: Function) => (): Frame | null => currentFrame(stackStart) /** The candidate (an adjacent hand-out) if the current operation continues its expression. */ const continuedChain = (candidate: CallRecord | undefined, current: () => Frame | null): CallRecord | undefined => { if (candidate === undefined) return undefined - const head = candidate.frame - return head === null || sameExpression(head, current()) ? candidate : undefined + return sameExpression(handOutFrame(candidate), current()) ? candidate : undefined } /** Links a new record to the candidate if it continues the candidate's expression. */ -const linkChain = (record: CallRecord, candidate: CallRecord | undefined): CallRecord => { - if (continuedChain(candidate, () => record.frame) !== undefined) record.chainPrevious = candidate +const linkChain = (record: CallRecord, candidate: CallRecord | undefined, stackStart: Function): CallRecord => { + if (continuedChain(candidate, frameAt(stackStart)) !== undefined) record.chainPrevious = candidate return record } @@ -293,10 +298,10 @@ const NOT_CONFIGURED: unique symbol = Symbol('not configured') * arguments, or when a mimicked instance has such a member of its own (a function's call/apply/bind inherited from * Function.prototype is the direct reading itself, recorded as such). */ -const memberReadingAnswer = (state: SubstituteState, helper: FunctionHelperKey, rawArgs: any[], hashes: ArgumentHashes, record: CallRecord, thisArg: unknown): any => { +const memberReadingAnswer = (state: SubstituteState, helper: FunctionHelperKey, rawArgs: any[], hashes: ArgumentHashes, record: CallRecord, thisArg: unknown, stackStart: Function): any => { const substitution = state.findCallSubstitution(helper, hashes) if (substitution !== undefined) { - if (substitution.method === 'auto') substitution.entry!.handOut(record) + if (substitution.method === 'auto') substitution.entry!.handOut(record, stackStart) return execute(substitution, rawArgs, thisArg) } const instance = state.mimicked?.instance @@ -357,14 +362,14 @@ const dualHelper = (face: Face, helper: FunctionHelperKey, chainHead: CallRecord if (directRecord !== undefined) pairReadings(memberRecord, directRecord) const hashes = new ArgumentHashes(rawArgs) - const answer = memberReadingAnswer(memberState, helper, rawArgs, hashes, memberRecord, thisArg) + const answer = memberReadingAnswer(memberState, helper, rawArgs, hashes, memberRecord, thisArg, stackStart) if (answer !== NOT_CONFIGURED) return answer if (directRecord !== undefined) { - const directAnswer = configuredAnswer(direct.state, direct.key, directArgs!, new ArgumentHashes(directArgs!), directRecord, { thisArg, explicit: true }) + const directAnswer = configuredAnswer(direct.state, direct.key, directArgs!, new ArgumentHashes(directArgs!), directRecord, { thisArg, explicit: true }, stackStart) if (directAnswer !== NOT_CONFIGURED) return directAnswer } const entry = memberState.callEntry(helper, hashes) - entry.handOut(memberRecord) + entry.handOut(memberRecord, stackStart) return entryProxy(entry) } @@ -389,10 +394,10 @@ const dualHelper = (face: Face, helper: FunctionHelperKey, chainHead: CallRecord const memberRecord = memberState.addRecord('call', 'bind', rawArgs, bind) memberRecord.chainPrevious = chainHead const hashes = new ArgumentHashes(rawArgs) - const answer = memberReadingAnswer(memberState, 'bind', rawArgs, hashes, memberRecord, thisArg) + const answer = memberReadingAnswer(memberState, 'bind', rawArgs, hashes, memberRecord, thisArg, bind) if (answer !== NOT_CONFIGURED) return answer const entry = memberState.callEntry('bind', hashes) - entry.handOut(memberRecord) + entry.handOut(memberRecord, bind) return createBoundProxy(face, entry, thisArg, boundArgs) } } @@ -479,9 +484,12 @@ const realGet = (state: SubstituteState, key: PropertyKey, chainCandidate: CallR const substitution = state.propertySubstitution(key) if (substitution !== undefined) { - const record = linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) + const record = linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate, stackStart) // Configured both as a property and as a method: whether this read is a property read is only known later. - if (state.hasCallSubstitutions(key)) return deferredRead(state, key, record, substitution) + if (state.hasCallSubstitutions(key)) { + captureHandOutFrame(record, stackStart) + return deferredRead(state, key, record, substitution) + } return execute(substitution) } @@ -494,21 +502,21 @@ const realGet = (state: SubstituteState, key: PropertyKey, chainCandidate: CallR const value = delegate ? mimicked.instance[key] : undefined // a substitute value records and resolves its own calls (D31: nested setups through the member go to it) if (delegate && (typeof value !== 'function' || isSubstituteProxy(value))) { - linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) + linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate, stackStart) return value } } - const record = linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate) + const record = linkChain(state.addRecord('get', key, undefined, stackStart), chainCandidate, stackStart) state.addPendingRead(record) const entry = state.propertyEntry(key) - entry.handOut(record) + entry.handOut(record, stackStart) return entryProxy(entry) } /** A real property assignment by the code under test. */ const realSet = (state: SubstituteState, key: PropertyKey, value: unknown, chainCandidate: CallRecord | undefined, stackStart: Function): void => { - linkChain(state.addRecord('set', key, [value], stackStart), chainCandidate) + linkChain(state.addRecord('set', key, [value], stackStart), chainCandidate, stackStart) if (state.mimicked !== undefined) state.mimicked.instance[key] = value } @@ -529,11 +537,15 @@ const invoke = (state: SubstituteState, key: PropertyKey, args: any[], stackStar let record: CallRecord if (read !== undefined && read.kind === 'get' && !read.retracted) { - read.convertToCall(args, stackStart) + // E1: the read keeps its call site only for `sub.method(...)`: the method was read right before, from the + // substitute it is invoked on. A method reference invoked later (with another `this`) is a call made elsewhere. + const sameExpression = readSource === TAKE_PENDING_READ && read.seq === currentSequence() && + self.thisArg !== undefined && self.thisArg === proxyOf(state) + read.convertToCall(args, stackStart, sameExpression) record = read - } else record = linkChain(state.addRecord('call', key, args, stackStart), chainCandidate) + } else record = linkChain(state.addRecord('call', key, args, stackStart), chainCandidate, stackStart) - return resolveCall(state, key, args, record, self) + return resolveCall(state, key, args, record, self, stackStart) } /** @@ -544,10 +556,10 @@ type Self = { thisArg: unknown, explicit: boolean } const NO_SELF: Self = { thisArg: undefined, explicit: false } /** The configured answer to a call: a matching substitution, or the mimicked instance. NOT_CONFIGURED otherwise. */ -const configuredAnswer = (state: SubstituteState, key: PropertyKey, args: any[], hashes: ArgumentHashes, record: CallRecord, self: Self): any => { +const configuredAnswer = (state: SubstituteState, key: PropertyKey, args: any[], hashes: ArgumentHashes, record: CallRecord, self: Self, stackStart: Function): any => { const substitution = state.findCallSubstitution(key, hashes) if (substitution !== undefined) { - if (substitution.method === 'auto') substitution.entry!.handOut(record) + if (substitution.method === 'auto') substitution.entry!.handOut(record, stackStart) return execute(substitution, args, self.thisArg) } @@ -564,12 +576,12 @@ const configuredAnswer = (state: SubstituteState, key: PropertyKey, args: any[], return NOT_CONFIGURED } -const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], record: CallRecord, self: Self): any => { +const resolveCall = (state: SubstituteState, key: PropertyKey, args: any[], record: CallRecord, self: Self, stackStart: Function): any => { const hashes = new ArgumentHashes(args) - const answer = configuredAnswer(state, key, args, hashes, record, self) + const answer = configuredAnswer(state, key, args, hashes, record, self, stackStart) if (answer !== NOT_CONFIGURED) return answer const entry = state.callEntry(key, hashes) - entry.handOut(record) + entry.handOut(record, stackStart) return entryProxy(entry) } diff --git a/src/internals/SubstituteState.ts b/src/internals/SubstituteState.ts index e80952d..c9e9c30 100644 --- a/src/internals/SubstituteState.ts +++ b/src/internals/SubstituteState.ts @@ -1,6 +1,7 @@ import { inspect } from 'util' import { CallRecord, RecordKind, currentSequence } from './CallRecord' +import { captureHandOutFrame } from './CallSite' import { RecordedArguments } from './RecordedArguments' import { SELF, SubstitutionMethod, keyToString } from './Constants' import { hashArguments, identityHashArguments } from './utilities' @@ -142,9 +143,11 @@ export class AutoEntry { return this._state } - public handOut(record: CallRecord): void { + /** Notes that the operation of `record` hands out this entry's proxy (`stackStart`: the trap of that operation). */ + public handOut(record: CallRecord, stackStart: Function): void { this._handedOutBy = record this._handedOutAt = currentSequence() + captureHandOutFrame(record, stackStart) } /** @@ -286,6 +289,8 @@ export class SubstituteState { private readonly _specificationEntries = new Map() public mimicked?: { instance: any } + /** The proxy of a substitute created with Substitute.for() (an auto-substitute's proxy is its owner's). */ + public proxy?: any constructor(public readonly owner?: AutoEntry) { } From 3cc28fdf7f1493d3c145c49c039b53de12302cad Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:11:15 +0000 Subject: [PATCH 064/106] fix(assertions): throw deferred reports from a microtask (E6) Deferred reports (D9, D33) were thrown from process.nextTick. Under jest, an exception thrown there (or from setImmediate, or an unhandled rejection) crashes the jest process: in band nothing is reported, with workers the whole file fails after the retries (R3-ADV-5). An exception thrown from queueMicrotask is reported as the running test's failure, and the next tests still run. The library captures the real queueMicrotask when it is loaded (process.nextTick on Node.js 10, which has none), so fake timers installed later cannot delay or swallow a report. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec/helpers/deferredReports.ts | 7 ++-- spec/regression/fixes/round4.test.ts | 55 +++++++++++++++++++++++----- src/internals/Assertions.ts | 15 ++++++-- 3 files changed, 62 insertions(+), 15 deletions(-) diff --git a/spec/helpers/deferredReports.ts b/spec/helpers/deferredReports.ts index 2ba0749..ec5c60b 100644 --- a/spec/helpers/deferredReports.ts +++ b/spec/helpers/deferredReports.ts @@ -1,10 +1,11 @@ import { deferredReports } from '../../src/internals/Assertions' /** - * Runs the library's deferred reports (D9, D33) on demand instead of on process.nextTick. + * Runs the library's deferred reports (D9, D33) on demand instead of on a microtask. * - * Since D34 the library captures the real process.nextTick when it is loaded, so fake timers installed by a test - * no longer intercept the reports. The tests use this stand-in, which has the same shape as the fake clock they + * Since D34 the library captures the real scheduler when it is loaded (since E6 queueMicrotask, process.nextTick + * where there is none), so fake timers installed by a test no longer intercept the reports. Every report goes + * through `deferredReports.schedule`, which this stand-in replaces. It has the same shape as the fake clock the tests * used before: `tick()` runs the reports scheduled so far and rethrows the first one that throws. */ export const interceptDeferredReports = () => { diff --git a/spec/regression/fixes/round4.test.ts b/spec/regression/fixes/round4.test.ts index 2cb268b..1472750 100644 --- a/spec/regression/fixes/round4.test.ts +++ b/spec/regression/fixes/round4.test.ts @@ -12,6 +12,16 @@ import { SubstituteException } from '../../../src/internals/SubstituteException' const library = path.resolve(__dirname, '../../../src/index.js') +/** Runs a script with the library in a child process, and returns what it prints as JSON. */ +const runScript = (script: string, options: { args?: string[], env?: Record } = {}): any => { + const result = spawnSync(process.execPath, [...(options.args ?? []), '-e', script], { + encoding: 'utf8', + env: { ...process.env, NO_COLOR: '1', ...options.env } + }) + if (result.status !== 0) throw new Error(`exit code ${result.status}: ${result.stderr}`) + return JSON.parse(result.stdout) +} + const plain = (text: string) => text.replace(/\x1b\[\d+m/g, '') const messageOf = (assertion: () => unknown): string => { @@ -211,15 +221,42 @@ test('R3-ADV-4 (E5) reading call sites never changes Error.prepareStackTrace for } }) -/** Runs a script with the library in a child process, and returns what it prints as JSON. */ -const runScript = (script: string, options: { args?: string[], env?: Record } = {}): any => { - const result = spawnSync(process.execPath, [...(options.args ?? []), '-e', script], { - encoding: 'utf8', - env: { ...process.env, NO_COLOR: '1', ...options.env } - }) - if (result.status !== 0) throw new Error(`exit code ${result.status}: ${result.stderr}`) - return JSON.parse(result.stdout) -} +test('R3-ADV-5 (E6) deferred reports are thrown from a microtask, also when fake timers replace it later', t => { + const script = (setup: string) => ` + const { Substitute } = require(${JSON.stringify(library)}) + ${setup} + const order = [] + process.on('uncaughtException', error => order.push('report: ' + error.constructor.name)) + process.nextTick(() => order.push('nextTick')) + Promise.resolve().then(() => order.push('promise job before')) + const calculator = Substitute.for() + calculator.add(1, 2) + calculator.add(3, 4) + calculator.received(1).add // D9: decided once it is known that add is not invoked + Promise.resolve().then(() => order.push('promise job after')) + setImmediate(() => console.log(JSON.stringify(order))) + ` + // a microtask runs with the promise jobs, in order, after the queued nextTick callbacks + const expected = ['nextTick', 'promise job before', 'report: SubstituteException', 'promise job after'] + t.deepEqual(runScript(script('')), expected) + // fake timers installed after the library was loaded cannot delay or swallow the report (D34) + const fakeTimers = require.resolve('@sinonjs/fake-timers') + const withFakeTimers = runScript(script(` + const clock = require(${JSON.stringify(fakeTimers)}).install({ toFake: ['queueMicrotask', 'nextTick', 'setTimeout'] }) + `)) + t.true(withFakeTimers.includes('report: SubstituteException'), JSON.stringify(withFakeTimers)) + + // plain Node.js: the report is an uncaught exception, printed, and the process exits with code 1 + const result = spawnSync(process.execPath, ['-e', ` + const { Substitute } = require(${JSON.stringify(library)}) + const logger = Substitute.for() + logger.error('disk full') + logger.didNotReceive().error // D33: the parentheses were forgotten + `], { encoding: 'utf8', env: { ...process.env, NO_COLOR: '1' } }) + t.is(result.status, 1) + t.regex(result.stderr, /SubstituteException: Call count mismatch in @Substitute\.error:/) + t.regex(result.stderr, /to assert calls, invoke it: sub\.didNotReceive\(\)\.error\(\.\.\.\)/) +}) test('R3-2 (E7) the runtime\'s own util.promisify.custom and util.inspect.custom are used, also where they are not the registered symbols', t => { // Node.js 10.0 to 12.16.1 and 13.0 to 13.11 have a util.promisify.custom of their own (Node.js 10.0 to 10.11 the diff --git a/src/internals/Assertions.ts b/src/internals/Assertions.ts index 3b569f3..d259b37 100644 --- a/src/internals/Assertions.ts +++ b/src/internals/Assertions.ts @@ -119,10 +119,19 @@ type Schedule = (callback: () => void) => void /** * D34: the scheduler of deferred reports is captured when the library is loaded, so that fake timers installed - * later (jest.useFakeTimers(), @sinonjs/fake-timers faking nextTick) cannot swallow a report. Fake timers that are - * installed before the library is loaded can still delay it. + * later (jest.useFakeTimers(), @sinonjs/fake-timers faking queueMicrotask and nextTick) cannot swallow a report. Fake + * timers that are installed before the library is loaded can still delay it. + * + * E6: a report is thrown from a microtask (queueMicrotask). Test runners attribute an exception thrown there to the + * running test: jest reports it as that test's failure and runs the next tests, where an exception thrown from + * process.nextTick or setImmediate, or an unhandled rejection, crashes the jest process. Node.js 10 has no + * queueMicrotask; there the report falls back to process.nextTick. */ const captureSchedule = (): Schedule => { + if (typeof queueMicrotask === 'function') { + const microtask = queueMicrotask + return callback => { microtask(callback) } + } if (typeof process !== 'undefined' && process !== null && typeof process.nextTick === 'function') { const nextTick = process.nextTick return callback => { nextTick.call(process, callback) } @@ -160,7 +169,7 @@ export const settle = (deferred: DeferredAssertion | undefined): void => { * - The only deferred case (D9): the property-style form fails, the member has been invoked, the count is * finite, and either a method assertion with that count could still pass or the member has only ever * been invoked (never read as a property), so the access is most likely the start of a method assertion - * whose message needs the arguments. The failure is scheduled on process.nextTick and cancelled as soon + * whose message needs the arguments. The failure is scheduled on a microtask (E6) and cancelled as soon * as the member is invoked; only a property-style assertion that is never invoked reports it there. * For a member that was only invoked, the report says so and shows the method assertion to write instead. * - D33: a property-style `didNotReceive().m` / `received(0).m` on a member that was only invoked holds as a From 3ef3428df8bbc32240eaa0bb0bcb48c44291856f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:13:53 +0000 Subject: [PATCH 065/106] types: Arg.is.not / Arg.any.not document the inverse at the call site (T35, R3TD-3) `.not` reused the call signatures of `Arg.is` / `Arg.any` (`Inversable = T & { not: T }`), so editors showed "Matches an argument for which predicate returns a truthy value" when hovering `Arg.is.not(...)`. `Arg.is.not` and `Arg.any.not` now have their own call-signature types (IsNot, AnyNot) with the same parameters and return types and documentation that starts with "The inverse of `Arg.is`" / "The inverse of `Arg.any`". The `not` properties carry the same kind of documentation for references that are not called. spec-types/TD-10.T32.jsdoc.js now also checks what the documentation says: at `.not(...)` call sites, on a standalone `Arg.is.not((x: number) => ...)`, on `Arg.any.not()` and on an uncalled `.not` it must describe the inverse (and say "falsy" / "NOT of the given type"), and at `Arg.is(...)` / `Arg.any(...)` it must not. The check fails on the 6cb1c22 build. Runtime code is unchanged: dist/api/Arg.js is byte-identical. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/TD-10.T32.jsdoc.js | 21 ++++++++++++++ src/api/Arg.ts | 53 +++++++++++++++++++++++++++-------- 2 files changed, 63 insertions(+), 11 deletions(-) diff --git a/spec-types/TD-10.T32.jsdoc.js b/spec-types/TD-10.T32.jsdoc.js index 5b35bb6..929c0f6 100644 --- a/spec-types/TD-10.T32.jsdoc.js +++ b/spec-types/TD-10.T32.jsdoc.js @@ -2,6 +2,8 @@ // TD-10 / T32 The public API carries documentation comments that editors show (quick info), in the BUILT package // typings (dist/*.d.ts). Each `/*@name*/` marker in the consumer below sits right before an identifier; the check asks // the TypeScript language service for the quick info at that identifier and fails when it has no documentation. +// R3TD-3 / T35 At an `Arg.is.not(...)` / `Arg.any.not(...)` call site (and on `.not` itself) the documentation +// describes the inverse matcher, and at `Arg.is(...)` / `Arg.any(...)` it does not (see `expectations` below). // // npm run build && node spec-types/TD-10.T32.jsdoc.js // @@ -35,6 +37,10 @@ calculator.add(/*@Arg*/Arg.any(), 2) calculator.add(Arg./*@Arg.any*/any('number'), Arg.any./*@Arg.any.not*/not('number')) calculator.add(Arg./*@Arg.is*/is(x => x > 0), Arg.is./*@Arg.is.not*/not(x => x === 0)) calculator.add(Arg./*@Arg.all*/all()) +const notZero = Arg.is./*@Arg.is.not (standalone)*/not((x: number) => x === 0) +const isNot = Arg.is./*@Arg.is.not (not called)*/not +const anyNot = Arg.any./*@Arg.any.not (not called)*/not +calculator.add(Arg.any./*@Arg.any.not (no type)*/not(), notZero) calculator.add(1, 2)./*@returns()*/returns(3) calculator.add(1, 2)./*@throws()*/throws(new Error()) @@ -93,6 +99,15 @@ for (const diagnostic of diagnostics) { console.log(`FAIL the consumer does not compile: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`) } +// R3TD-3 / T35 What the documentation must (or must not) say at some markers: [marker name pattern, text pattern, +// whether the text must be present, what is checked]. +const expectations = [ + [/^Arg\.(is|any)\.not\b/, /^The inverse of `Arg\.(is|any)`/, true, 'describes the inverse matcher'], + [/^Arg\.is\.not\b/, /falsy/i, true, 'says that the predicate returns a falsy value'], + [/^Arg\.any\.not\b/, /\bNOT of the given type\b/, true, 'says that the argument is not of the type'], + [/^Arg\.(is|any)$/, /\binverse\b/i, false, 'describes the matcher itself, not its inverse'] +] + const marker = /\/\*@(.+?)\*\//g let match let count = 0 @@ -104,6 +119,12 @@ while ((match = marker.exec(consumer)) !== null) { if (documentation === '') { failed = true console.log(`FAIL ${name}: no documentation comment`) + continue + } + const wrong = expectations.filter(([names, text, present]) => names.test(name) && text.test(documentation) !== present) + if (wrong.length > 0) { + failed = true + for (const [, , , what] of wrong) console.log(`FAIL ${name}: the documentation ${what}: ${documentation.split('\n')[0]}`) } else { console.log(`ok ${name}: ${documentation.split('\n')[0].slice(0, 90)}`) } diff --git a/src/api/Arg.ts b/src/api/Arg.ts index a253469..a922418 100644 --- a/src/api/Arg.ts +++ b/src/api/Arg.ts @@ -1,13 +1,9 @@ import { inspect } from 'util' import { Argument, AllArguments, ArgumentOptions, PredicateFunction, isSubstituteProxy } from '../shared' -type Inversable = T & { - /** - * The inverse matcher: it matches the arguments the matcher itself rejects, e.g. `Arg.is.not(x => x === 0)` or - * `Arg.any.not('string')`. A predicate that throws matches in neither form. - */ - not: T -} +// The shape `createInversable` builds at runtime. The public types (`Is`, `Any`) give `.not` its own call signatures +// with their own documentation, so that editors describe the inverse at `Arg.is.not(...)` (T35). +type Inversable = T & { not: T } type ExtractFirstArg = T extends AllArguments ? TArgs[0] : T type ReturnArg = Argument & T const createInversable = (target: (arg: TArg, opt?: ArgumentOptions) => TReturn): Inversable<(arg: TArg) => TReturn> => { @@ -55,6 +51,26 @@ type Is = { // Infers the type from an annotated predicate when the matcher is created on its own, which TypeScript 3.6 and 3.7 // cannot do through `ExtractFirstArg` above (TD-6). (predicate: (arg: T) => boolean): ReturnArg + /** + * The inverse of `Arg.is`: `Arg.is.not(predicate)` matches an argument for which `predicate` returns a falsy value, + * e.g. `calculator.divide(1, Arg.is.not(x => x === 0))`. A predicate that throws matches in neither form. + */ + not: IsNot +} + +type IsNot = { + /** + * The inverse of `Arg.is`: matches an argument for which `predicate` returns a FALSY value (it does not match where + * `Arg.is(predicate)` matches): `calculator.divide(1, Arg.is.not(x => x === 0))`. The predicate's parameter type is + * taken from the parameter the matcher is passed to. A predicate that throws matches in neither form. + */ + (predicate: PredicateFunction>): ReturnArg> + /** + * The inverse of `Arg.is`: matches an argument for which `predicate` returns a FALSY value (it does not match where + * `Arg.is(predicate)` matches): `const notZero = Arg.is.not((x: number) => x === 0)`. A predicate that throws + * matches in neither form. + */ + (predicate: (arg: T) => boolean): ReturnArg } // 'function' and 'object' are mostly used for callback and object parameters, so they must be assignable to them (TD-5): @@ -81,6 +97,21 @@ type Any = { * 'array' or 'any'. */ (type?: T): MapAnyReturn + /** + * The inverse of `Arg.any`: `Arg.any.not(type)` matches every argument that is NOT of the given type, e.g. + * `Arg.any.not('string')` matches every argument that is not a string. + */ + not: AnyNot +} + +type AnyNot = { + /** + * The inverse of `Arg.any`: matches every argument that is NOT of the given type (it does not match where + * `Arg.any(type)` matches): `Arg.any.not('string')` matches every argument that is not a string, and + * `Arg.any.not()` matches nothing. Types: 'string', 'number', 'boolean', 'symbol', 'undefined', 'object' (non-null + * objects, arrays and substitutes), 'function' (functions, classes and substitutes), 'array' or 'any'. + */ + (type?: T): MapAnyReturn } const createAnyPredicate = (type: string): PredicateFunction => { @@ -127,13 +158,13 @@ type ArgMatchers = { * Matches an argument for which the predicate returns a truthy value: `calculator.add(Arg.is(x => x > 10), 2)`. * `Arg.is.not(predicate)` matches where it returns a falsy value. A predicate that throws matches in neither form. */ - is: Inversable + is: Is /** * Matches any argument (`Arg.any()`), or any argument of a type (`Arg.any('string')`): 'string', 'number', * 'boolean', 'symbol', 'undefined', 'object' (non-null objects, arrays and substitutes), 'function' (functions, * classes and substitutes), 'array' or 'any'. `Arg.any.not('string')` matches every argument that is not a string. */ - any: Inversable + any: Any } /** @@ -142,6 +173,6 @@ type ArgMatchers = { */ export const Arg: ArgMatchers = { all: (): AllArguments => new AllArguments(), - is: createInversable(isFunction) as Inversable, - any: createInversable(anyFunction) as Inversable + is: createInversable(isFunction) as unknown as Is, + any: createInversable(anyFunction) as unknown as Any } From c8bf6471af2aadec157258138a17a790ce02514f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:14:27 +0000 Subject: [PATCH 066/106] types: Arg.any('undefined') only fits parameters that accept undefined (T38, R3TD-7) `Arg.any('undefined')` was typed `Argument & undefined`, which is `never` and therefore fit every parameter (`calculator.add(Arg.any('undefined'), 2)` compiled). Its type is now taken from where it is used: a second, inferred type parameter picks up the parameter (or property) type it is passed to; that type is used when it accepts `undefined`, and `undefined` otherwise, which is a compile error there. On its own (`const m = Arg.any('undefined')`) it is `undefined`. A type assertion to a matcher type (`>Arg.any('undefined')`, as spec/regression does) still compiles. Without strictNullChecks it fits every parameter, as `undefined` does. `Arg.any.not('undefined')` matches every defined value and is typed `any`, so it still fits any parameter. The other `Arg.any.not(type)` types are unchanged. Checked with TypeScript 3.6 to 5.9; runtime code is unchanged (dist/api/Arg.js is byte-identical). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/R3TD-7.T38.arg-any-undefined.ts | 66 ++++++++++++++++++++++ spec-types/loose/non-strict.ts | 2 + src/api/Arg.ts | 19 +++++-- 3 files changed, 83 insertions(+), 4 deletions(-) create mode 100644 spec-types/R3TD-7.T38.arg-any-undefined.ts diff --git a/spec-types/R3TD-7.T38.arg-any-undefined.ts b/spec-types/R3TD-7.T38.arg-any-undefined.ts new file mode 100644 index 0000000..64dc2e7 --- /dev/null +++ b/spec-types/R3TD-7.T38.arg-any-undefined.ts @@ -0,0 +1,66 @@ +// R3TD-7 / T38 `Arg.any('undefined')` fits only parameters (and properties) that accept `undefined`. It used to be +// typed `never`, which fits every parameter. Its type is taken from where it is used: the parameter type when that +// accepts `undefined`, otherwise `undefined` (a compile error there). On its own it is `undefined`. +// `Arg.any.not('undefined')` matches every defined value and still fits any parameter. +import { Substitute, SubstituteOf, Arg, configure, received } from '../src' +import { Argument } from '../src/shared' +import { assert, Equals } from './helpers' + +interface Calculator { + add(a: number, b: number): number + find(id?: string): string + maybe(value: number | undefined): number + anything(value: unknown): void + save(item: { id: string }): void + note?: string + title: string +} +const calculator = Substitute.for() + +calculator.find(Arg.any('undefined')).returns('none') +calculator.maybe(Arg.any('undefined')).returns(0) +calculator.anything(Arg.any('undefined')) +calculator.received().find(Arg.any('undefined')) +calculator.didNotReceive().maybe(Arg.any('undefined')) +calculator[received](1).anything(Arg.any('undefined')) +calculator[configure]().find(Arg.any('undefined')).returns('none') +calculator.received().note = Arg.any('undefined') + +// @ts-expect-error a number parameter does not accept undefined +calculator.add(Arg.any('undefined'), 2).returns(3) +// @ts-expect-error nor in the assertion view +calculator.received().add(1, Arg.any('undefined')) +// @ts-expect-error nor in the configure view +calculator[configure]().add(Arg.any('undefined'), 2).returns(3) +// @ts-expect-error an object parameter does not accept undefined +calculator.save(Arg.any('undefined')) +// @ts-expect-error a required property does not accept undefined +calculator.received().title = Arg.any('undefined') + +// on its own +const missing = Arg.any('undefined') +assert>() +calculator.find(missing) +// @ts-expect-error a number parameter does not accept undefined +calculator.add(missing, 2) + +// as a matcher object (spec/regression/Arguments.spec.ts does this) +const matches: boolean = (>Arg.any('undefined')).matches(undefined) + +// the inverse fits any parameter +calculator.add(Arg.any.not('undefined'), 2).returns(3) +calculator.save(Arg.any.not('undefined')) +calculator.received().title = Arg.any.not('undefined') +// the other types are unchanged (`Arg.any.not('number')` is typed like `Arg.any('number')`) +calculator.add(Arg.any('number'), Arg.any.not('number')) +// @ts-expect-error a string matcher does not fit a number parameter +calculator.add(Arg.any('string'), 2) + +// generic code over a constraint (T33) +export function stub(sub: SubstituteOf) { + sub.find(Arg.any('undefined')).returns('none') + // @ts-expect-error a number parameter does not accept undefined + sub.add(Arg.any('undefined'), 2) +} + +export { matches } diff --git a/spec-types/loose/non-strict.ts b/spec-types/loose/non-strict.ts index 0ab9ecf..ba6fe48 100644 --- a/spec-types/loose/non-strict.ts +++ b/spec-types/loose/non-strict.ts @@ -26,6 +26,8 @@ calculator.received(2).isEnabled = true calculator[received]().add(1, 2) calculator[configure]().add(1, 2).returns(3) calculator[mimick]({} as Calculator) +// without strictNullChecks every parameter accepts undefined, so Arg.any('undefined') fits everywhere (T38) +calculator.add(Arg.any('undefined'), 2).returns(3) const asCalculator: Calculator = calculator // overloads, including one without parameters diff --git a/src/api/Arg.ts b/src/api/Arg.ts index a922418..126e478 100644 --- a/src/api/Arg.ts +++ b/src/api/Arg.ts @@ -78,17 +78,28 @@ type IsNot = { // (no type is assignable to every object type). type AnyFunction = Argument & ((...args: any[]) => any) & (new (...args: any[]) => any) -type MapAnyReturn = T extends 'any' ? +// 'undefined' fits only parameters that accept `undefined` (T38). (`Argument & undefined` is `never`, which +// fits every parameter.) The type is taken from where the matcher is used: `TContext` is inferred from the parameter (or +// property) type it is passed to. That type is used when it accepts `undefined`, and `undefined` otherwise, which is +// then a compile error. Without such a type (`const m = Arg.any('undefined')`) it is `undefined`. A type assertion to a +// matcher type (`>Arg.any('undefined')`) keeps working. +type UndefinedArg = undefined extends TContext ? TContext : TContext extends Argument ? TContext : undefined + +type MapAnyReturn = T extends 'any' ? ReturnArg : T extends 'string' ? ReturnArg : T extends 'number' ? ReturnArg : T extends 'boolean' ? ReturnArg : T extends 'symbol' ? ReturnArg : T extends 'undefined' ? -ReturnArg : T extends 'object' ? +UndefinedArg : T extends 'object' ? ReturnArg : T extends 'function' ? AnyFunction : T extends 'array' ? ReturnArg : any +// `Arg.any.not('undefined')` matches every defined value, so it fits any parameter. The other types keep the type of +// the matcher without `.not`. +type MapAnyNotReturn = T extends 'undefined' ? ReturnArg : MapAnyReturn + type AnyType = 'string' | 'number' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | 'array' | 'any' type Any = { /** @@ -96,7 +107,7 @@ type Any = { * 'undefined', 'object' (non-null objects, arrays and substitutes), 'function' (functions, classes and substitutes), * 'array' or 'any'. */ - (type?: T): MapAnyReturn + (type?: T): MapAnyReturn /** * The inverse of `Arg.any`: `Arg.any.not(type)` matches every argument that is NOT of the given type, e.g. * `Arg.any.not('string')` matches every argument that is not a string. @@ -111,7 +122,7 @@ type AnyNot = { * `Arg.any.not()` matches nothing. Types: 'string', 'number', 'boolean', 'symbol', 'undefined', 'object' (non-null * objects, arrays and substitutes), 'function' (functions, classes and substitutes), 'array' or 'any'. */ - (type?: T): MapAnyReturn + (type?: T): MapAnyNotReturn } const createAnyPredicate = (type: string): PredicateFunction => { From 04f24b66afa1c93d3501103c7435ffa5f3aa132d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:15:10 +0000 Subject: [PATCH 067/106] test(types): check the round-4 typing patterns with TypeScript 3.6 (T33-T38) spec-types/min-ts/consumer.ts (type-checked against the built typings by `npm run test:types:min-ts`) now also covers: setups, checks and the configure view through a type parameter's constraint (members that cannot be null or undefined), a fixture class over `T extends Counter`, substitutes of function types, a union whose variants declare members as only null, the ways around the optional-callback limitation, and Arg.any('undefined') / Arg.any.not('undefined') / Arg.is.not. It fails on the 6cb1c22 build with TypeScript 3.6 and passes with TypeScript 3.6, 3.7, 3.8, 3.9, 4.0, 4.1, 4.5, 4.7, 4.8, 4.9, 5.0, 5.4 and 5.9. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/min-ts/consumer.ts | 57 ++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/spec-types/min-ts/consumer.ts b/spec-types/min-ts/consumer.ts index 91df0be..0fcc6cb 100644 --- a/spec-types/min-ts/consumer.ts +++ b/spec-types/min-ts/consumer.ts @@ -143,6 +143,61 @@ interface Form { note?: string } const form = Substitute.for() form.received().note = undefined +// R3TD-1 / T33: setups and checks through a type parameter's constraint (members that cannot be null or undefined; +// nullable members need TypeScript 3.9 in generic code) +interface Counter { add(a: number, b: number): number; total: number; load(): Promise } +function stubCounter(sub: SubstituteOf) { + sub.total.returns(1) + sub.add(1, 2).returns(3) + sub.add(Arg.all()).mimicks((a, b) => a + b) + sub.load().resolves(1) + sub[configure]().total.returns(2) + sub[configure]().add(1, Arg.all()).returns(4) + sub.received().add(1, 2) + sub.received().total = 1 + sub[didNotReceive]().add(Arg.any(), 2) +} +class CounterFixture { + sub = Substitute.for() + arrange() { this.sub.add(1, 2).returns(3) } +} +stubCounter(Substitute.for()) +new CounterFixture().arrange() + +// R3TD-6 / R3-3 / T37: substitutes of function types +type Listener = (event: string) => string +const listener = Substitute.for() +listener('saved').returns('ack') +listener(Arg.all()).mimicks(event => event) +listener.received(1)('saved') +listener.didNotReceive()(Arg.any()) +listener[received](1)('saved') +listener[configure]()('saved').returns('ack') +const asListener: Listener = listener + +// R3TD-4 / T36: unions whose variants declare members as only null +type QueryResult = { data: string[]; error: null } | { data: null; error: Error } +const queryResult = Substitute.for() +queryResult.data.returns(['a']) +queryResult.error.returns(null) +const asQueryResult: QueryResult = queryResult + +// R3TD-2 / T34: the ways around the optional-callback limitation +interface Widget { onChange?: (value: string) => void } +const widget = Substitute.for() +widget.received().onChange('x') +;(widget.received() as Widget).onChange = undefined +widget.received().onChange = Arg.any.not('function') + +// R3TD-3 / T35 and R3TD-7 / T38: Arg.any / Arg.is and their .not forms +interface Finder { find(id?: string): string; count(value: number): number } +const finder = Substitute.for() +finder.find(Arg.any('undefined')).returns('none') +finder.count(Arg.any.not('undefined')).returns(0) +finder.count(Arg.is.not(value => value > 0)).returns(1) +finder.count(Arg.any.not('number')).returns(2) +const missing: undefined = Arg.any('undefined') + try { calculator.received().add(9, 9) } catch (error) { @@ -151,4 +206,4 @@ try { } } -export { asCalculator, nothing, asOk } +export { asCalculator, nothing, asOk, asListener, asQueryResult, missing } From 472b24bafa6773bf4095acdc86ceb0ccac11cd9d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:17:34 +0000 Subject: [PATCH 068/106] test(compatibility): require jest's own report of the deferred failure (R3-ADV-5, E6) The jest check accepted "type: 'CallCountMismatch'", which is part of Node.js's fatal-exception dump, so it passed when jest crashed. The jest fixture now has a passing test before and after the failing one, and the check requires jest's report: the failure of that test with "Tests: 1 failed, 2 passed, 3 total". jest 30 on Node.js 22 cannot attribute an exception thrown from a microtask to the running test (Node.js 22 loses the AsyncLocalStorage store there), so on Node.js 22 the check also accepts jest's "Test suite failed to run" for the file, with "Tests: 3 passed, 3 total". Every runner's output must be free of a Node.js crash, and jest's and vitest's "called at" lines must name the TypeScript source lines (E4). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- .../test-runners/_common/index.ts | 4 +- .../test-runners/jest/index.spec.ts | 11 ++++ compatibility-checks/test/index.ts | 56 +++++++++++++++++-- 3 files changed, 64 insertions(+), 7 deletions(-) diff --git a/compatibility-checks/test-runners/_common/index.ts b/compatibility-checks/test-runners/_common/index.ts index eb0dbb7..deec9d3 100644 --- a/compatibility-checks/test-runners/_common/index.ts +++ b/compatibility-checks/test-runners/_common/index.ts @@ -16,8 +16,8 @@ export const ambiguousPropertyTypeAssertion = () => { lib.subSection.returns({ subMethod: () => 'subSection as property' } as AmbiguousSection) // Three calls, then a property-style assertion with a finite count that a method assertion could still - // satisfy. The member is never invoked afterwards, so the failure can only be reported on process.nextTick, - // after the test function has returned. Every test runner must still attribute it to the test. + // satisfy. The member is never invoked afterwards, so the failure can only be reported on a microtask (E6), + // after the test function has returned. Every test runner must still report it as a failure. lib.subSection() lib.subSection() lib.subSection() diff --git a/compatibility-checks/test-runners/jest/index.spec.ts b/compatibility-checks/test-runners/jest/index.spec.ts index 6ddcfea..ac1ca87 100644 --- a/compatibility-checks/test-runners/jest/index.spec.ts +++ b/compatibility-checks/test-runners/jest/index.spec.ts @@ -1,5 +1,16 @@ +import { expect, test } from '@jest/globals' import { ambiguousPropertyTypeAssertion } from '../_common' +// R3-ADV-5 (E6): the tests around the failing one must still run and be reported, so that a crash of the jest +// process (which loses them) cannot pass for the failure of one test. +test('passes before the failing test', () => { + expect(1).toBe(1) +}) + test('can substitute callable interfaces', () => { ambiguousPropertyTypeAssertion() }) + +test('passes after the failing test', () => { + expect(1).toBe(1) +}) diff --git a/compatibility-checks/test/index.ts b/compatibility-checks/test/index.ts index 8f4cf3d..ca553fa 100644 --- a/compatibility-checks/test/index.ts +++ b/compatibility-checks/test/index.ts @@ -1,17 +1,48 @@ import * as test from 'node:test' import * as assert from 'node:assert' import { execSync } from 'node:child_process' +import { readFileSync } from 'node:fs' +import * as path from 'node:path' import { testRunnerEnvironment } from './environment' type TestRunner = { name: string /** * One of these must appear in the runner's output. The shared scenario fails with a SubstituteException that is - * thrown either synchronously (a failed test) or on process.nextTick after the test returned (an uncaught exception), - * depending on whether the library can decide the assertion right away, so both reports are accepted. + * thrown on a microtask after the test returned (E6), which each runner reports in its own way. */ failureAcknowledgementTexts: string[] failureLocationText: string + /** E4: the "called at" lines of the message point at the TypeScript source (the runner applies source maps). */ + mapsCallSites?: boolean + /** Further checks of the runner's output. */ + verify?: (output: string) => void +} + +const nodeMajorVersion = Number(process.versions.node.split('.')[0]) + +/** The lines of the shared scenario that call the substitute, as the "called at" lines must name them. */ +const scenarioCallLines = readFileSync(path.join(__dirname, '../test-runners/_common/index.ts'), 'utf8') + .split('\n') + .flatMap((line, index) => line.trim() === 'lib.subSection()' ? [index + 1] : []) + +/** + * R3-ADV-5 (E6): jest must report the failure as the failure of the test, and run and report the other tests of the + * file. When a deferred report was thrown from process.nextTick, jest crashed instead: Node.js printed the exception as + * fatal and no summary followed (in band), or the file failed after the worker retries; that must fail this check. + * jest 30 finds the running test through AsyncLocalStorage, whose store Node.js 22 loses for an exception thrown from + * a microtask. On Node.js 22 jest 30 therefore reports the failure for the file ("Test suite failed to run"), and the + * other tests of the file still run and pass. + */ +const verifyJest = (output: string) => { + assert.ok(!/^Node\.js v\d/m.test(output), `The jest process crashed: ${output}`) + const testFailure = output.includes('● can substitute callable interfaces') && /Tests:\s+1 failed, 2 passed, 3 total/.test(output) + const fileFailure = output.includes('● Test suite failed to run') && /Tests:\s+3 passed, 3 total/.test(output) + // the "Tests:" summary counts the other two tests of the file, which passed + assert.ok( + testFailure || (nodeMajorVersion < 24 && fileFailure), + `jest did not report the failure of the test "can substitute callable interfaces" next to the 2 passing tests: ${output}` + ) } test.describe('Verifies test runner compatibility', () => { @@ -28,13 +59,19 @@ test.describe('Verifies test runner compatibility', () => { const testRunners: TestRunner[] = [ { name: 'ava', failureAcknowledgementTexts: ['1 uncaught exception', '1 test failed'], failureLocationText: 'test-runners/ava/index.ts' }, - { name: 'jest', failureAcknowledgementTexts: ['Tests: 1 failed', "type: 'CallCountMismatch'"], failureLocationText: 'test-runners/jest/index.spec.ts' }, + { + name: 'jest', + failureAcknowledgementTexts: ['Tests:'], + failureLocationText: 'test-runners/jest/index.spec.ts', + mapsCallSites: true, + verify: verifyJest + }, { name: 'mocha', failureAcknowledgementTexts: ['1 failing'], failureLocationText: 'can substitute callable interfaces:' }, // G:CI-2: this check used to pass vacuously or fail, because the nested `node --test` inherited NODE_TEST_CONTEXT. { name: 'nodejs', failureAcknowledgementTexts: ['fail 1'], failureLocationText: 'test-runners/nodejs/index.ts' }, - { name: 'vitest', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest/index.spec.ts' }, + { name: 'vitest', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest/index.spec.ts', mapsCallSites: true }, // F1: vitest with the package inlined (vitest.inline.config.mts), so that Vite, not Node.js, loads its ES module entry. - { name: 'vitest-inline', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest-inline/index.spec.ts' } + { name: 'vitest-inline', failureAcknowledgementTexts: ['1 error', '1 failed'], failureLocationText: 'test-runners/vitest-inline/index.spec.ts', mapsCallSites: true } ] // P28 (ENG2-7): jest's matchers must compare a substitute like any other value. Unlike the runs above, this suite @@ -66,6 +103,15 @@ test.describe('Verifies test runner compatibility', () => { result.includes('SubstituteException') && result.includes('Call count mismatch'), `Could not find the expected exception message in the output: ${result}` ) + // R3-ADV-5: a test runner that crashes does not report the failure of a test + assert.ok(!/^Node\.js v\d/m.test(result), `The test runner process crashed: ${result}`) + if (testRunner.mapsCallSites) { + // R3-ADV-3 (E4): source maps apply to the "called at" lines (they once showed the compiled position) + assert.equal(scenarioCallLines.length, 3) + for (const line of scenarioCallLines) + assert.ok(result.includes(`_common/index.ts:${line}:`), `No "called at" line names test-runners/_common/index.ts:${line}: ${result}`) + } + testRunner.verify?.(result) }) }) }) From 88aa9faf533007430d7f8445705776b81cdb2cb5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:20:49 +0000 Subject: [PATCH 069/106] fix(hashing): load on Node.js 10, which has no globalThis The feature check for AggregateError read globalThis, which Node.js 10 does not have, so requiring the package threw a ReferenceError there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- src/internals/utilities/ArgumentHash.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/internals/utilities/ArgumentHash.ts b/src/internals/utilities/ArgumentHash.ts index 85e606c..9558734 100644 --- a/src/internals/utilities/ArgumentHash.ts +++ b/src/internals/utilities/ArgumentHash.ts @@ -170,7 +170,9 @@ const errorParts = ((): { name: boolean, message: boolean, cause: boolean, error return error } const withCause = (...cause: unknown[]) => new (Error as any)('x', ...cause.map(value => ({ cause: value }))) as Error - const Aggregate = (globalThis as any).AggregateError as (new (errors: unknown[], message: string) => Error) | undefined + // Node.js 10 has neither globalThis nor AggregateError + const globalObject: any = typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : undefined + const Aggregate = globalObject?.AggregateError as (new (errors: unknown[], message: string) => Error) | undefined const withoutErrors = () => { const error = new Aggregate!([1], 'x') delete (error as any).errors From 82f32369c18b061786ad20530fefd80a817408f1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:31:11 +0000 Subject: [PATCH 070/106] perf(types): read member types with Extract instead of intersecting with keyof T `T[P & keyof T]` intersects each key with the whole key union of `T`, which distributes over hundreds of keys for lib.dom types every time a member type is computed (TypeScript computes every member of a substitute on the first member access). `T[Extract]` is a single lookup, and in generic code it still resolves to the constraint's member type on assignment. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- src/api/types/Substitute.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/api/types/Substitute.ts b/src/api/types/Substitute.ts index 596c124..5fbd797 100644 --- a/src/api/types/Substitute.ts +++ b/src/api/types/Substitute.ts @@ -21,7 +21,9 @@ export type PropertySubstitute = SetupMethods TValue> */ type Members = { indexed: T, plain: Pick }[IndexKind] -type Member = T[P & keyof T] +// `Extract`, not `P & keyof T`: intersecting a key with a large key union (lib.dom's Document has hundreds of members) +// distributes over the whole union each time a member type is computed. +type Member = T[Extract] // The views are mapped with `-?` and expand calls from the member type without `null | undefined`, so optional members // (`prop?`, `method?()`) are configured and asserted like required ones (T:TY-7). From e8bb73e7f4da20b770598a7e947e59619c2a1062 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:31:47 +0000 Subject: [PATCH 071/106] perf(hashing): sample long strings in three plain loops Hashing a string longer than 4096 characters computed every sampled position through sampledPosition, which made 10k calls with 5000-character strings slower than hashing them in full before. The prefix, the strided samples and the suffix now have loops of their own (the same positions). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- src/internals/utilities/ArgumentHash.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/internals/utilities/ArgumentHash.ts b/src/internals/utilities/ArgumentHash.ts index 9558734..1679952 100644 --- a/src/internals/utilities/ArgumentHash.ts +++ b/src/internals/utilities/ArgumentHash.ts @@ -90,8 +90,19 @@ const sampledPosition = (length: number, samples: number, index: number): number const edge = samples >>> 2 if (index < edge) return index if (index >= samples - edge) return length - (samples - index) - const strided = samples - 2 * edge - return edge + Math.floor((index - edge + 0.5) * (length - 2 * edge) / strided) + return edge + Math.floor((index - edge + 0.5) * (length - 2 * edge) / (samples - 2 * edge)) +} + +/** hashString for a string longer than SAMPLED_UNITS: the positions of sampledPosition, in three loops. */ +const hashSampledString = (text: string, h: number): number => { + const length = text.length + const edge = SAMPLED_UNITS >>> 2 + const strided = SAMPLED_UNITS - 2 * edge + const span = length - 2 * edge + for (let index = 0; index < edge; index++) h = Math.imul(h ^ text.charCodeAt(index), 0x01000193) + for (let index = 0; index < strided; index++) h = Math.imul(h ^ text.charCodeAt(edge + Math.floor((index + 0.5) * span / strided)), 0x01000193) + for (let index = length - edge; index < length; index++) h = Math.imul(h ^ text.charCodeAt(index), 0x01000193) + return h } const hashString = (text: string, seed: number): number => { @@ -99,10 +110,7 @@ const hashString = (text: string, seed: number): number => { let h = mix(seed, length) if (length <= SAMPLED_UNITS) { for (let index = 0; index < length; index++) h = Math.imul(h ^ text.charCodeAt(index), 0x01000193) - } else { - for (let index = 0; index < SAMPLED_UNITS; index++) - h = Math.imul(h ^ text.charCodeAt(sampledPosition(length, SAMPLED_UNITS, index)), 0x01000193) - } + } else h = hashSampledString(text, h) return mix(h, 0) } From c0ca6ca839250aaceca9e8d77045b6fef9b17894 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:32:30 +0000 Subject: [PATCH 072/106] test(types): pin two assertion-view limitations found while checking T33/T34 Both are pre-existing (they fail the same way at 6cb1c22) and are recorded with the way around them, which is checked on TypeScript 3.9 to 5.9: - assigning a plain function to a callable member in the assertion view (`button.received().onClick = handler`): the member's type there also has the `Arg.all()` call signatures. Use `(button.received() as Button).onClick = handler`. - in generic code, checking a set of a property typed as the type parameter itself (`current: T`): use `(holder.received() as Holder).current = value`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt --- spec-types/limitations.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/spec-types/limitations.ts b/spec-types/limitations.ts index c52010d..a08e2b7 100644 --- a/spec-types/limitations.ts +++ b/spec-types/limitations.ts @@ -1,6 +1,6 @@ // Documented limitations of the typings (TypeScript cannot express these). Each `@ts-expect-error` line shows the // limitation, the line after it a way around it. -import { Substitute, Arg, configure } from '../src' +import { Substitute, SubstituteOf, Arg, configure } from '../src' // T:TY-6 Assigning a property directly on a substitute: the property's type carries the setup API (`.returns`, ...), // and TypeScript uses the same type for reads and writes of a mapped property. @@ -39,4 +39,21 @@ const events = Substitute.for() events.on('data', Arg.any()).returns(events) events[configure]().on('data', Arg.any()).returns(events) +// Assigning a function to a callable member in the assertion view: the member's type there also carries the +// `Arg.all()` call signatures, which a plain function does not have. Check the set through the type itself. +interface Button { onClick?: (event: string) => void } +const button = Substitute.for