Skip to content

Fix 2.0.1 release blockers: engine bugs, typings, packaging/CI and docs - #282

Draft
ffMathy wants to merge 450 commits into
masterfrom
ccr-f7030c4e-rhdc1v
Draft

ffMathy wants to merge 450 commits into
masterfrom
ccr-f7030c4e-rhdc1v

Conversation

@ffMathy

@ffMathy ffMathy commented Nov 16, 2026 •

Copy link
Copy Markdown
Owner

This PR fixes the problems found in an audit of the unreleased 2.0.1 on master, before it is published. It covers the runtime engine, the typings, packaging/CI and the docs. CHANGELOG.md lists every user-visible change, and MIGRATION.md explains how to upgrade from 1.x and from the betas.

The work has gone through seventeen rounds so far. Each round fixed the open findings in separate branches, merged them, updated the docs, and then:

  • re-ran every earlier repro on Node.js 22, 24 and 26;
  • ran adversarial reviews of the engine, the typings and docs, and packaging;
  • had a "fresh-eyes" reviewer write realistic test suites as a new user would.

Findings per round went 23 → 36 → 28 → 21 → 22 → 15 → 13 → 15 → 20 → 21 → 22. The count has stopped falling: each round's new realistic test suites find older problems with libraries and tools not tried before, and each round's fixes add a few new ones. In round 17 the new suites covered Next.js route handlers with tRPC and Drizzle, an LLM client wrapper, and a cron worker run under tsx. Round 17's 22 findings come down to 20 distinct problems. 8 of them come from round 17's own changes, and 2 of those are medium. An eighteenth round is in progress (see "Open items").

What changed

Engine (src/internals/, rewritten around per-substitute state)

  • Setups and checks
    • Overlapping setups work. The most specific setup wins, and among equally specific ones the most recent.
    • Checks never run setups, and calls with matchers are never recorded as received calls.
    • A check with nothing after it, such as next.didNotReceive(), is reported as a usage error instead of passing silently.
  • Which calls are recorded
    • Every call is recorded, also through stored or destructured method references, callbacks, .call/.apply/.bind, Reflect.apply and new.
    • The reads that lead up to a setup in the same expression are not recorded. This is decided by call site, and the README states the exact rule.
  • Auto-substitutes are cached, so nested setups and checks work.
  • Checks through a call with matchers, such as api.load(Arg.any()).received(1).save(), count the calls on what the matching received calls returned: auto-substitutes, configured, mimicked and fluent substitutes, and substitutes of another copy of the library, also two or more steps below the call. When a matching call was answered by something that is not a substitute (a plain value, resolves(), throws(), a bound function), the check is a usage error instead of passing silently. These checks never change what later calls return. A helper that opens such a check and returns it (const sentTo = room => io.to(room).received(1)) works like the inline form.
  • Shared substitutes: after a nested setup through a call with matchers (io.to(Arg.any()).emit(Arg.all()).returns(true)), every matching call returns the same substitute, as in NSubstitute. A check through a concrete call (io.to('room-b').received(1).emit(…), also written with .call()/.apply()) then counts only what came through that call: all of the substitute's calls, none, or a usage error when only some of its calls came through it. Failure messages show the concrete call (to('room-a')) instead of the matcher.
  • .call()/.apply() wrappers (retry, once, memoize, jest.fn, vi.fn, sinon.spy) get the same answer as the direct call, including the same auto-substitute. A method that is really named call and takes a primitive first argument (rpc.call('getUser', 1), redis.call('get', 'k')) keeps a separate answer per first argument.
  • New API: sub[configure](), sub[mimick](instance), sub[clearReceivedCalls](), matchers nested inside objects and arrays, Arg.all() after leading arguments, and an exported SubstituteException.
  • Matchers of test runners: jest/vitest asymmetric matchers (expect.any(…), expect.objectContaining(…), …) and sinon.match(…) work as matchers in setups and checks, also nested, and print with their own text at any depth. Arg matchers work inside them (expect.objectContaining({ topic: Arg.any('string') })) and in jest's and vitest's own equality (expect(value).toEqual({ id: Arg.any() })). Values that cannot be inspected or listed, such as revoked proxies, are never taken for matchers and match by identity.
  • mimick:
    • A mimicked method that returns its own instance (return this) keeps a fluent chain on the substitute, so the rest of the chain is recorded.
    • Wrapping a member of a mimicked substitute (obj.m = wrap(obj.m), as instrumentation does, or jest.spyOn(sub, 'm')) works. Calls still go through the setups and are recorded once.
  • Arguments
    • An omitted trailing argument matches undefined, Arg.any() and Arg.any('undefined').
    • An Arg.is() predicate or a runner matcher that reads a substitute argument leaves no trace: its reads are not recorded and use up no returns() values. Calls made from a callback that a predicate runs are recorded.
    • JavaScript mistakes get clear usage errors: an unknown Arg.any type, Arg.any passed without calling it, an async Arg.is predicate, mimicks with a non-function.
  • Failure messages
    • Checks throw synchronously whenever the outcome is known. The rare later report is thrown from a microtask, which jest attributes to the right test.
    • Messages show the substitute path and keep source-mapped "called at" lines.
    • A check that misses a call made further down an unconfigured fluent chain (reply.code(404).send(…)) says where the call was made and how to set up or check the chain.
    • Arguments print two levels deep. They print deeper, at the least depth that shows the difference, when the expected and received calls would otherwise look the same. This also works next to matchers, inside Maps and Sets (whose order does not count as a difference), on arrays with named properties, with keys in another order, and with two copies of the library. Size is bounded (a DOM event no longer prints megabytes), and errors print compactly. When the expected and received calls still print alike (function identity, private state), the message says so.
  • Performance
    • 10k calls take well under a second for every argument shape we tested: nested, cyclic, errors, 1 MB strings, 150k-item arrays, a million errors, wide objects, Maps and Sets, shared tables, URLs.
    • The per-call hot path is about as fast as before these fixes.
    • The speed tests run serially, with limits scaled to machine load.
    • Dropped substitutes are released, also after many calls answered by a shared substitute.
  • Robustness
    • Works with Error.stackTraceLimit = 0, and with a read-only or frozen Error.
    • A debugger that pauses on caught exceptions stops once per throws() answer, at the configured throw.
    • Works with custom Error.prepareStackTrace formatters and with fake timers.
    • Works after Object.setPrototypeOf(sub, …), with classes that extend a substitute (new.target, .call/.apply/.bind on them), with wrappers that copy a substitute's prototype or bind it natively (mem, p-memoize, onetime, Function.prototype.bind), and with two copies of the library loaded.
    • A substitute can be frozen, can take defineProperty, and answers in. util.callbackify(sub.method) works.
  • Protocol members: then, Symbol.iterator, Symbol.hasInstance, util.promisify.custom, util.inspect.custom, jest's asymmetricMatch/_isMockFunction, sinon-chai's spy probe and DOM handleEvent behave sensibly. jest and vitest snapshots and diffs of substitutes are readable.

Typings

  • Fixed:
    • optional members and index signatures, also through a generic constraint;
    • overloads, including literal-typed parameters;
    • unions, including members whose signatures differ between variants;
    • function-type, callable-interface and constructor-type substitutes;
    • constrained generic code and generic methods (arity checked, no any leaks), including emit('event', Arg.all()) on typed event emitters;
    • Arg.is contextual types, predicates that return any non-promise value (Arg.is(user => user.name)), and Arg.any('undefined' | 'bigint');
    • Arg.all()-only setups on overloaded methods (pool.query(Arg.all()).resolves(…) with @types/pg). .mimicks() after them takes a function that fits each overload, as assigning to the method would, so it may leave out trailing parameters (TypeORM save/remove, pg query, fs/promises readFile);
    • methods whose last overload no argument fits once its type parameters are replaced by their constraints, such as hono's c.get('user') with an empty ContextVariableMap;
    • .resolves() for maybe-promise returns, and not for promise-like subtypes with extra members;
    • sub[mimick](instance) takes a partial instance of an object type, also for SubstituteOf<T | undefined> in generic code;
    • check views survive declaration emit (declaration: true), also for types with symbol-keyed members (iterables, EventEmitter, streams);
    • editor docs on .not.
  • No loosening: every "must not compile" line found in any round is pinned with @ts-expect-error and checked on TypeScript 3.6 to 7.0.
  • CI: type-level tests run with npm run test:types, plus a TypeScript 3.6 minimum check.
  • Documented: the remaining typing limitations in README "Typing limitations": old-TypeScript gaps, the type-check cost of very large unions on TS < 4.9, Arg.any('string') for string-literal unions (with workarounds), Arg.any() on methods whose overloads are all generic with constrained type parameters such as TypeORM Repository.save (with workarounds), type-parameter defaults such as pino's child(), and the per-event limits of http.Server/net.Socket typings.

Packaging and CI

  • An exports map and an ES module entry that shares one copy of the library with CommonJS. It is checked with Node and with Rollup, Vite, webpack, esbuild and Rolldown, in ESM and CommonJS output. The directories that emitted declarations import (dist/shared, dist/api, dist/api/types) resolve under node16, nodenext and bundler.
  • A prepack build, and engines verified down to Node 10.
  • CI on Node 22/24/26, plus minimum-Node and TypeScript 3.6 jobs.
  • Compatibility checks (36) for ava, jest 29/30 (CJS, ESM, ts-jest, babel-jest), mocha (also async tests), node:test and vitest (all pools), including snapshots, module mocks and runner matchers, all run against the packed package.
  • The publish workflow sets the latest/beta dist-tag and provenance, and runs after CI.

Docs

  • README rewrite in which every snippet is type-checked and executed in CI (npm run test:docs, 167 blocks in README, MIGRATION and CHANGELOG).
  • New MIGRATION.md, CHANGELOG.md (closes Update documentation #234) and CONTRIBUTING.md.
  • A prominent warning not to use jest's toHaveBeenCalled*, sinon-chai's spy assertions or sinon.assert.* on substitutes, with a table of received()/didNotReceive() replacements.

Verification at 5c41ddc

  • npm test passes 494 functional tests and 135 timing tests on Node 22, 24 and 26. test:types (including the declaration-emit fixtures), the TypeScript 3.6 check, test:docs (167 blocks), the packaging tests and the 36 compatibility checks also pass on all three.
  • The minimum-Node smoke tests pass on Node 10.0, 12.17, 13.0 and 13.7.
  • The round-17 regression review re-ran all round-16 findings. Round 17 fixed or documented each of them, with two exceptions. A slowdown is only partly fixed; it is listed under "Open items". The TypeORM save(Arg.any()) typing is now a documented limitation with workarounds. The review also re-ran the repro sets of rounds 2 to 16 and the differential fuzzers against 8be3a70 and cd1bf29. Every difference in their output is an intended round-17 change.
  • Under load, npm test passed 5 of 6 runs. The one failure was a timing test at load 20, whose limit is already at its 4× load cap.
  • Memory: after 50,000 calls answered by a shared substitute, dropped substitutes keep 0.29 MB instead of 16.8 MB at 8be3a70. The hot path is within 3% of 8be3a70, and bytes per call are unchanged.

Open items (round 18 in progress)

Round 17's four reviews found 20 distinct problems: 4 medium and 16 low. Round 18 is working on them.

  • Medium
    • Regression from round 17: a check through a call with matchers gets quadratically slower with the number of matching calls that each returned their own substitute. At 20,000 calls it takes 2.8 s instead of 60 ms.
    • Regression from round 17: under tsx, which puts each compiled file on one line, didNotReceive() wrongly passes after a fluent call made earlier in the same test (a map.set(…) set up to return map). An older part: under tsx, a deferred report is swallowed by a later usage error.
    • Older: a check through a concrete call passes wrongly when a later step of the check is a call on a builder that returns itself, such as knex db('orders').where('id', 1).received(1).first(), socket.io io.to('b').to('c') or fastify reply.code(…).header(…).
    • Older: node:test's mock.method(sub, 'm', implementation), or mockImplementation(), on a mimicked substitute bypasses the setups and records no call.
  • Regressions from round 17 (low)
    • A substitute handed out twice in one expression (a cycle) loses the top step, so a check passes that should fail.
    • The last call's arguments stay in memory after its substitute is dropped.
    • Object.defineProperty with default attributes on a mimicked substitute puts the property on the instance, but the substitute then reports no such own property, and a forbidden redefinition succeeds.
    • Calls of a mimicked fluent method (return this, such as EventEmitter on()) cost 1.4–1.7 times as much as before.
    • vi.spyOn on a mimicked member makes the instance's own calls through this count as received calls, as jest.spyOn and plain wrappers already did.
    • Typings: after Arg.all() on overloads, .mimicks() accepts a union of implementations when only one of them fits (strict mode).
    • Still slower than in round 15: Arg.is() predicates that read a closed-over substitute take 1.33–1.43 times as long when a large argument is passed. The target is 1.3; round 16 had made this up to 99 times slower.
  • Other (low): a configured answer that is a revoked function proxy still crashes a check through a call with matchers. The "check that substitute" hint can print arguments that are not code, or that are cut off. After clearing only the owner's received calls, a concrete check still counts calls that came through the cleared call. A helper that returns a check view can only be typed as ReturnType<typeof sub.received>, and the symbol form has no type annotation that compiles.
  • Docs (low): sinon.replace on a mimicked substitute throws for methods of class instances, and does not compile in TypeScript without a cast. vi.spyOn(sub, 'x') throws for a member with no setup. On AWS SDK v3 client.send(), the new advice for Arg.any() on generic overloads is backwards. "Any two Blobs are equal" is wrong, because size and type count.

Worth a look before merging

  • Debugger stops: a debugger set to pause on caught exceptions stops inside the library on chained steps where Error.prepareStackTrace is not a function (Node < 20.20, jest 30, vitest vm* pools). The README gives the skipFiles workaround.
  • Module mocks: a substitute that stands in for a whole module works with jest's CommonJS jest.mock. Other runners need a plain object of substitutes; the README shows the pattern for each runner.
  • Changed arguments: an argument that is changed after a setup holds it matches in a way the README calls unspecified.

Before publishing

  • NPM_PUBLISH_TOKEN must be a valid granular npm token, or trusted publishing must be configured for the package.
  • Publishing the v2.0.1 GitHub release makes 2.x the npm latest. Until now, latest is 1.208.0.

🤖 Generated with Claude Code

https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt

…fixes (E42-E45)

URLs hash by href, promises and weak collections by identity (E42); absolute
time limits are scaled by a measured load factor (E43); values in messages,
printouts and paths are printed within bounds (E44); errors print compactly at
every depth, with their own properties (E45).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Objects that inherit from a substitute are ordinary objects (E46); a matcher
usage error cancels only the report of its own check (E47); a check view that
nothing follows is reported (E48); uncalled matcher functions and async
predicates are usage errors (E49); configured or mimicked toString/valueOf are
used for conversions (E50); a mimicked substitute enumerates like its instance
(E51); substitutes are numbered in messages whose calls print alike (E52);
compatibility checks for module mocks that need a plain object (E53).

Merged without textual conflicts. Paths.ts and SubstituteException.ts carry
both branches' changes: engine A's bounded path arguments and 20,000-character
listing budget, and engine B's root numbering (rootLabel/withRootNumbers,
printsAlike, the numbered rebuild).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Generic methods never take any for arguments their own signature rejects (T54);
resolves()/rejects() only where a native promise fits (T55); callbacks typed with
one union variant's this compile again (T56); a cheaper assertion view of union
members (T57, partly met); returns()/resolves() without a value when undefined
fits (T58); the limitations R8TD-4, R8TD-5 and R8TD-7 are pinned (T59).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…enables, classes extending a substitute, Arg.is and uncalled matchers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…, coercion, mimicked enumeration, bounded printing, module mocks, typing limitations, performance

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…module-mock compatibility suites

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… a plain object

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
E46 decided "the receiver is not the substitute itself" by the prototype
of the receiver, so a substitute whose prototype was replaced
(Object.setPrototypeOf(sub, Repo.prototype), the usual instanceof trick)
answered its own symbol APIs, the substitute marker, toJSON and
Symbol.toPrimitive as if it only inherited from a substitute:
sub[received] and the other symbols were undefined, isSubstituteProxy was
false, String(sub) gave the native function text and JSON dropped it.

The proxies whose prototype the code under test replaces are now noted in
a setPrototypeOf trap and recognised by identity (a WeakSet, empty unless
that happens), everywhere the library tells its own proxies apart:
inheriting receivers (E46), configured values handed out (E39), the
configure view of a configured value (D31) and new.target (E23/E36).
Objects that merely inherit from a substitute are still ordinary objects.
Assignments by the code under test to such a substitute are recorded again
instead of creating real properties.

R9-ADV-2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
On Node.js 20, util.isDeepStrictEqual, which the library calls to compare
arguments, probes the private kKeyType of KeyObjects on the objects it
compares. For an instance of a class that extends a substitute that read
reached the substitute through the prototype chain, was recorded, and was
answered with a truthy auto-substitute, so Node.js then called equals() on
it as well: the base substitute listed reads and calls nobody made.

A symbol that is neither the library's own nor registered (Symbol.for),
read through an object that only inherits from a substitute, now reads
undefined and records nothing, unless the substitute configures or mimicks
that key. While the library compares arguments, every read that reaches a
substitute through such an object does the same, as while it prints (so
Node.js 20's URL probes href, protocol and auth that follow are not
recorded either). Reads of the substitute itself are unchanged.

The E55 test compares String() of inheriting objects with what the running
V8 gives for any object with a function proxy in its chain (Node.js 20
says [object Function]).

R9V-2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… print alike lines deeper

R9-ADV-1: failure messages and printouts print values two levels deep again
(util.inspect's default), within the E44 bounds. Containers that hold a matcher
are shown at any depth. When the expected call prints like received calls it
does not match, those lines are printed up to four levels deep. What
util.inspect is given holds only the entries that can show before the cut, so
deep values cost no more than small ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Pin the Prisma-style 3-level filter, nested Arg.is and deeper matchers, alike
lines printed deeper (calls and assignments), E52 numbering with deeper lines,
the bounds of deep values, that a value printed only as far as it shows starts
like its full text, and the time of messages with deep and wide values.
round9-hashing's printing test now expects two levels of nesting (E54).

Only the listed calls that a message can show are compared for E52 and E54,
each value of a message is printed once per depth, and the budget margin is
1,000 characters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Primitive arguments were printed up to four times per message (listing size,
alike checks, the message itself). Messages now cost no more than at 4b1fa69.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… its cache in node_modules

R9V-3: assertRatiosWithin (spec/helpers/timing.ts) makes a measurement whose
ratio is over its limit again, up to three measurements, and the smallest ratio
of each kind decides. The families ratio test of round7-hashing, its fresh
batches test and round8's in-probe test use it.

R9V-6: ava.config.js no longer sets cache: false, which made every ava run
leave an empty directory in os.tmpdir(); ava keeps its cache in
node_modules/.cache/ava.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…cache directory

R9V-3: ratio tests check their ratios with assertRatiosWithin, which measures
again when a measurement is over its limit. R9V-6: ava keeps its cache in
node_modules/.cache/ava, so a run leaves only Node.js' module compile cache in
os.tmpdir(), which npm, npx and tsc write themselves (NODE_COMPILE_CACHE or
NODE_DISABLE_COMPILE_CACHE=1 keep it out).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
A check whose matcher argument threw a usage error, such as
listener.received(1)(Arg.any('String')), left a "checked nothing" report
behind as well as the TypeError: the view was followed by a call, but the
call never happened because its arguments threw. The report of a check view
is now the report scheduled last, like the report of a property-style check,
so the matcher's usage error cancels it under the same rule (same line,
same function, after the view).

A dangling string-form check (repo.didNotReceive() as a statement) was not
reported when the same check was completed later in the same tick: calls
with the same arguments hand out the same auto-substitute, and its first use
settled every pending report. Each use now settles one report, the latest
one still pending, so every view that is used settles a report and no view
that is used is reported, while an earlier dangling one still is.

R9V-1, R9-ADV-4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Round 9's dangling-check bookkeeping (E48) made a symbol-form check such as
sub[received](1).f(1) about 1.5x slower than at d5b96ab: every check view
scheduled a microtask of its own, and the property-style half of a check
of a member that was called (deferred until the member is invoked)
captured the whole stack.

- The reports scheduled in one synchronous run (D9, D33, E48) are checked
  by one microtask. It still throws one report per microtask, in the order
  they were scheduled: after throwing one, it checks the rest in a
  microtask of its own.
- A report that comes later carries the frame of the check's line only,
  captured the way the call sites of records are (one frame), as the report
  of a dangling check view already did.
- The short-lived views (checks, configure views, bound functions) share
  one set of traps and inherit their util.inspect hook, instead of a
  handler and a hook of their own per view.

Measured on Node.js 22 (medians of 5 processes, 20,000 checks):
s[received](1).f(1) 0.95x of d5b96ab cold, 1.18x warm (base 1.36x and
1.44x).

R9-ADV-5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
util.inspect reads the inspect.custom hook from the target of a proxy, but
calls it with the proxy itself as `this`. The hook that the views now
inherit from a shared prototype only handled its target, so util.inspect of
a check view, a configure view, a bound function or a member configured both
as a property and as a method printed an empty string. Called with a view,
the hook now asks the view for its printer, as the view's traps answer it.

R9-ADV-5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Node.js 26 shows a proxy as Proxy([Function: bound substitute]) when custom
inspection is off; the test now only requires the target's name there.

R9-ADV-5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…R9FE-1, T60)

The positional signature of a generic method takes `P | TArguments` instead of
`P`, so an argument that is itself a generic call (`Arg.is(sql => ...)`) gets
the parameter type with the type parameters replaced by their constraints as
its contextual type; `P` is still inferred from the arguments. A call whose
matcher arguments fit the method but from which TypeScript cannot infer the
return type (`Config[K]` with a matcher for `K`) takes the return type for the
matchers' value types instead of `any`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…R9TD-2, R9TD-5, T62)

- The own-this signature of a concrete union checks the arguments against
  the variants' parameter lists as declared, so callbacks with the `this`
  types of different variants in one call no longer compile (R9TD-2).
- Its result is what the overloads return whose lists take the arguments
  (or the common return type), instead of `PrefixCallResult`, which was
  `never` on TypeScript 3.6 to 4.1 for calls that omit optional parameters
  (R9TD-1).
- In the assertion view, a member whose type is a union of plain function
  types gets a construct signature, so assigning a function to it does not
  compile, as for other callable members (R9TD-5). The T44 instantiation
  budget still holds (469,989 of 470,000).
- The TS 3.6 consumer gets the R9TD-1 and R9FE-1 must-compile lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…heir own (R9-ADV-3, R9TD-3, T63)

resolves()/rejects() configure a native promise, so they are offered only
where a native promise of the value is a valid value of the member. That now
also holds for subtypes of Promise: ky's ResponsePromise, knex's
QueryBuilder, execa's result and a CancellablePromise no longer offer them
(configure them with returns() and a substitute). A Promise subtype without
members of its own (Prisma's PrismaPromise, which only narrows
Symbol.toStringTag) and one whose own members are optional still do.

Existing fixtures changed for this decision: R8TD-2.T55 (CancellablePromise
now must reject resolves()/[rejects]) and T-TY-02 (Deferred's resolves/rejects
members are optional, so the symbol forms are still offered).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…gs (R9FE-3, T64)

Arg.any('string'), 'number', 'boolean', 'symbol' and 'bigint' take the part
of the parameter's type that is of their primitive type, so they fit a union
of string literals, a string or numeric enum, a branded string or a union of
number literals; a parameter without such a part still rejects them, and a
matcher created on its own keeps the primitive type. Arg.any() without a type
gets a signature of its own without type parameters, which keeps the T44
instantiation budget (469,885 of 470,000).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… (R9FE-2, T61)

Setups of overloaded generic methods whose parameters depend on a type
parameter through a conditional type (@types/pg's query(text, values)) cannot
get the setup API: the overloads are seen with `values?: never`, and a check
of the values against the overloads would accept anything, since TypeScript
relates overloads to a signature with `any` for their type parameters. The
fixture pins the limitation and the verified workarounds (values `as never`,
Arg.all()), on TypeScript 3.6 to 7.0.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…rn type (T60, T65)

Instead of a second inference after a failed one (which comparisons of the
substitute's generic signatures with a method's own generic signature reach,
for every generic member of EventEmitter<Events>), the return type is
inferred once from the arguments with matchers replaced by their value types
(function matchers kept). Same results on the spec-types fixtures and the
must-reject corpus; the EventEmitter<Events> perf file needs 39,475
instantiations on TypeScript 5.9 instead of 43,348 (4b1fa69: 36,926).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…rictNullChecks (T64)

Without strictNullChecks `undefined`, the type a matcher gets when no
parameter type is known, is part of every type, so the T64 change gave
`Arg.any('string')` the type `undefined` there and spec/ (which compiles
without strictNullChecks) no longer built. The missing parameter type is
now recognised first. Strict mode is unchanged; the non-strict fixture
covers both forms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…io tests and ava cache)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ngling views, E57 pass-through symbol reads, E58 check cost)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
findEntry gives the mapping that starts last at or before a position, which
can be on an earlier generated line (tsc maps 'log' in '    .log(...)' while V8
puts the read at the dot). Such an entry tells nothing about the line, so the
raw line decides then, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… or check uses it

A record that follows a hand-out of the substitute itself (a mimicked fluent
'return this', map.set(Arg.all()).returns(map)) is linked for later; the E111
line rule is applied when chainPrevious is first read (retraction, routes), so
fluent calls read no stack frames, as at 8be3a70.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ations (R17TD-1)

Without strictFunctionTypes a value typed as a union of implementations is
rejected when one of them does not fit the overloads (as for the member
itself); 5c41ddc and 8be3a70 accepted it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…nts alive

The arguments of the last search are forgotten once the call's matching pass
reads what the search found, and at the end of the synchronous run (one
microtask from the queueMicrotask captured at load), together with the key
listings of wide objects that a call hashing nothing never takes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
tsc and esbuild map the name of a property, and V8 can put a read of a chain at
its dot, which belongs to the mapping before it (the previous line of a chain
over several lines). A mapping that starts one or two characters later is taken
first. Tests and the tsx fixtures cover a chain over lines with the matcher on
the member's line and a check over two lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
findSourceMap turns a path into a file: URL on every call, which cost more than
the lookup (about 2 microseconds); a check through a self-answered concrete call
under tsx, which compares lines on every check, is back within 1.03x of 5c41ddc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…r the pending link

The record of a call that answers the substitute itself carried two fields that the records of
8be3a70 did not (E111's handedOutItself and E126's pending link): 16 bytes more per fluent call
(314 against 298 bytes on Node.js 22), or on every record when the first records of a process were
fluent ones. Now the engine notes the sequence number of the latest hand-out of the substitute itself
(a chain candidate is always the latest operation), and a pending link is the record's ordinary
chain link plus the record's sequence number on its own capture, which has room for it. A read
that is invoked later takes the pending link to the invocation's capture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…'s records in O(1) (R17V-2)

MatchedSubstitutes kept the records it listed as groups and found a
substitute's group by a linear search, so one check over N calls that
each answered its own substitute took O(N^2) (2.5 s at 20,000 calls).
Now nothing is kept per record while one substitute is listed, and a
map from record to substitute once a second one is, as at cd1bf29.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…handed out again in the same expression (R17-ADV-1, R17-ADV-2)

A substitute kept a note of its latest configured hand-out only, so a
route through a self-returning builder (knex where(), socket.io to(),
fastify code()/header()) or a cycle stopped at the last hand-out and
counted every call of the builder: a wrong pass. A substitute now keeps
the notes of every hand-out in the latest expression that handed it
out (one note as a rule, starting over with the next expression), so
the route is matched step by step. A route whose upper part is no
longer known is a usage error, never a check of its lower part.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…e it do not count through the cleared substitute's route (R17-ADV-12)

Clearing io removed its record io.to('room-a') and the hand-out with it,
but the shared room kept emit('welcome'), and a check through the only
live hand-out, io.to('room-b'), counted it. A substitute now notes when
its received calls were cleared, and a check through a route does not
count, at any step, the calls that the substitutes further down received
before the latest clear of a substitute on the route. A check of such a
substitute itself still counts them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ed is E88's usage error, never a TypeError (R17V-1, R17-ADV-6)

throughCall and throughRead asked what a call answered for its
prototype (instanceof), which throws for a revoked function proxy. The
answers noted are the library's own objects or values that answered
(functions), so a function is no longer asked: a revoked proxy is a
value that is not a substitute, E88's usage error, as for a revoked
object proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…bstitute, new non-configurable keys stay on the substitute, the instance's own this-calls through a spy are its own

E129 (R17-ADV-4): a function that wraps one of this copy's member handles
(node:test's mock.method / mock.fn) is a method of the instance, not a
substitute value: reads give a handle, calls go through the setups and the
recording first, then to the mock. A call that a setup answers is shown to
node's mock through its mockImplementationOnce(), so the mock still counts
every call. sub.m.mock on such a handle is the mock's context.

E130 (R17-ADV-8): Object.defineProperty of a new key without configurable on
a mimicked substitute defines it on the substitute itself (non-configurable,
as on any object), as before E115.

E131 (R17-ADV-10): a call through a member handle whose this is the mimicked
instance, made while a call of this substitute is being delegated, is the
instance's own call: not recorded, not matched against the setups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…nt on its path prints as code

R17-ADV-5: the 'check that substitute' remedy of the fluent-chain hint writes
its path as code only when every argument on it prints as code that gives an
equal value (primitives other than symbols, bigints with n, plain arrays and
objects printed in full). Otherwise it names the substitute as messages print
it, to be reached with the same arguments. The fluent remedy is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…etracted read of the member behind

Each check and setup through repo.find(Arg.any()) read the member first,
and the retracted read stayed among the member's records, which every
later check through a call with matchers went through: the 10,000th
check of a member with 10 calls cost several times the first (at
5c41ddc, 8be3a70 and cd1bf29 alike). The read, the latest record of its
member, is forgotten once retracted, as E110 does for the records of a
check through a concrete call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ved calls were cleared

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
….spyOn and sinon on mimicked substitutes

New fixtures: test-runners/jest-matchers/spies-mimicked-round18.spec.ts
(node:test mock.method with an implementation and mockImplementation(),
jest.spyOn and wrapper this-calls), sinon-mimicked-round18.spec.ts (sinon on
own and prototype methods, and on the instance; R17-ADV-9), and
jest-esm-modules/spies-mimicked-round18.test.mjs (vi.spyOn this-calls).
sinon is a new devDependency of the compatibility checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…f narrows below a shared step too (R17-ADV-1, twice.js C/D)

A call or read answering the substitute it was made on with a setup of
its own (room.self().returns(room), room.me.returns(room)) handed
nothing out (E39), so a check further down (io.to('b').self().received(1)
.emit(...)) lost the route and counted every call of room. Such an
answer now hands the substitute out when the call or read continues an
expression that handed it out, as the shared ones do (E111): without
such a hand-out further up, E39 is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…frozen is a TypeError, not a mock that answers without the setups

On a frozen instance, Object.defineProperty() of a mimicked member falls back to
the substitute itself (E25), where a node:test mock with an implementation
would answer every call without the setups and the recording. mock.method()
now throws a TypeError there that names the remedy (mock.fn(sub.m)); the
restore of such a mock changes nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
A call through a member handle with the mimicked instance as this, made while a
call of the substitute is being delegated, is the instance's own only when the
handle is stale (a spy or wrapper replaced the member it was read from). A
handle of a member nothing replaced, called by a wrapper of another member, is
a call of the substitute, as at 5c41ddc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ches, with five substitutes and one setup matcher

A thousand setups with a thousand different Arg.any() matchers made every later check look at a thousand configured
answers, a cost unrelated to E121 (Node 24 measured 1.86x against the limit of 2). The setups now share one matcher
object, so each replaces the one before; 20,000 checks between the batches make the old growth unmistakable (5c41ddc:
4.4 to 7 times), and the median of five substitutes keeps a pause in one of them from deciding.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… noting their owners in it

A check of N = 1,000 substitutes ran its record listing mostly before it was optimized, and the second loop and the
call per substitute made the first check cost 1.27x to 1.36x of 8be3a70 and cd1bf29 in CPU time. Now 0.99x / 1.04x at
N = 1,000 and 1.14x / 1.18x at N = 3,000 (15 fresh processes each); warm checks cost the same as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…Arg.all() fits only when each one does, T83 export CheckViewOf<T>, the type of a check view

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ere Node.js has a source map (tsx), E126 fluent calls that answer the substitute itself read no frames, E127 the last search for matchers keeps no call's arguments alive

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ach substitute's records in O(1), E122 hand-out notes per expression narrow past self-returning steps and cycles, E123 a clear bounds what counts through the owner's route, E124 revoked proxy answers are E88's usage error

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… link only when a check reads them

fix/r18-checks (E122) notes each configured hand-out of a substitute per expression and, to tell
whether a new hand-out continues the latest expression, reads record.chainPrevious. fix/r18-lines
(E126) made the link of a call right after a hand-out of the substitute itself a pending one that the
chainPrevious getter decides from stack frames. Together, every call of a fluent method (a mimicked
`return this`, res.status(Arg.any()).returns(res), map.set(Arg.all()).returns(map)) read frames again
(round18-lines' E126 frame-count test: 800 reads instead of 0).

A hand-out whose record's link to the latest note's record is still pending (CallRecord.linkPendsTo)
is now noted as continuing that expression for now, marked pending; the notes are settled when they
are read (configuredHandOutOf, i.e. when a check follows its route): the latest pending note that does
not continue the note before it drops the notes before it, as noting it would have done. Results are
those of the eager decision: cf18 0 mismatches over 4 seeds of 400; a differential probe of self steps
over one or several lines (600 cases, 2,400 checks) gives the same outcomes as fix/r18-checks alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…fter the substitute, E130 new non-configurable keys stay on the substitute, E131 the instance's own this-calls through a spied member are its own, E132 the check remedy is code only when its arguments print as code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
…ed routes, and the hint's remedies on E122 routes

Pins two combinations of the round-18 branches that no branch's own tests cover:
- E129 x E122 x E126: with node:test's mock.method on a fluent member of a mimicked substitute,
  the chain stays on the substitute, the next-line check is decided by the line rule, the mock sees
  each call, and a check through io.to(Arg.any()).returns(emitter) narrows exactly as without the
  mock (fix/r18-checks alone, without E129, passed the r2 check wrongly through the mock).
- E132 x E122: the 'check that substitute' remedy below self-returning shared steps, below a shared
  builder, and with a Date on the route (no code, reached with the same arguments) makes the check
  pass when followed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
… and the docs items R17TD-2, R17FE-1, R17FE-3, R17-ADV-9, R17FE-4

README:
- CheckViewOf<T> in the exports list, the generic-helper example and 'Declaration emit' (T83): string and symbol forms,
  unconstrained, constrained and T | undefined, isolatedDeclarations; declarations name import("@fluffy-spoon/substitute").CheckViewOf<...>.
- 'Ignoring all arguments': a union of mimicks() functions fits only when each does (T82, checked); the T81 rule qualified.
- 'Typing limitations': the T81 bullet split into the TypeORM case (the parameter is the type parameter) and the AWS SDK v3
  case (the parameter only contains it, Command invariant under strictFunctionTypes), with a checked AWS-shaped snippet;
  sinon.replace(fs as Fs, ...) in 'Assigning a property'.
- 'How arguments are compared': Blobs of the same size and type are equal whatever their bytes; Files from Node.js 24 on
  also compare name and lastModified (checked Blob snippet, capture of a Blob for its bytes).
- 'Partial mocks': E130 defineProperty defaults, E131 the instance's own this-calls through a wrapped or spied member
  (checked), frozen instances.
- 'Fluent interfaces': E132, the check remedy is code only when its arguments print as code (checked Date example).
- 'Through a call with matchers': E122 self-returning builders and cycles step by step, the new usage error, steps with
  different arguments; E123 clears; E124 revoked proxies (checked examples).
- 'Which calls lead to a setup or a check': E125 lines in transpiled test files (tsx, source maps) and the limitation for
  minified or bundled code without a source map; E126 nuance.
- 'Test runners': vi.spyOn on a member without a setup throws, and the working forms (R17FE-1); node:test mock.method
  with an implementation (E129, checked); sinon on own and prototype methods of mimicked instances and on the instance
  (R17FE-3, R17-ADV-9); frozen instances; tsx.
- 'Performance': checks through a call with matchers (E121), notes of shared and fluent hand-outs, fluent call cost,
  predicates that read a closed-over substitute (E128), release of a last call's arguments (E127).
MIGRATION, CHANGELOG: the same changes in short. CONTRIBUTING: the round-18 compatibility fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KD7sVgSiP9KbiEpaM8wCyt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Update documentation

2 participants