Files
openclaude/tests
NikhilandGitHub 650fae952d fix(sdk): make stub-leak detection TDZ-safe + defer to next microtask (#1287) (#1398)
* fix(sdk): make stub-leak detection TDZ-safe + defer to next microtask (#1287)

`bun run scripts/start-grpc.ts` crashed at startup with:

    ReferenceError: Cannot access 'QueryEngine' before initialization.
        at detectStubLeaks (src/entrypoints/sdk/index.ts:29:33)
        at src/entrypoints/sdk/index.ts:47:1

The detector ran at module-load time and read each critical import
directly. When the start script's circular-import chain reached the SDK
barrel before `QueryEngine.js` had finished initializing its own export
bindings, the QueryEngine reference at line 29 hit the temporal dead
zone and threw. Stub-leak detection is meant to catch `__stub: true`
markers from the esbuild plugin — TDZ is a different bug class (an
uninitialized binding can't carry `__stub`), so the detector should
treat the access failure as 'nothing to check here' rather than
crashing the entire SDK entry.

Two changes:

1. Wrap each import read in safelyAccess(() => binding) so a TDZ
   ReferenceError on one returns undefined and the loop continues.
   Real stub markers still surface as the explicit SDK init error.
2. Defer detectStubLeaks() from module-load to queueMicrotask, so
   every same-tick init in the circular chain (start-grpc.ts → SDK
   index → QueryEngine → ... → SDK index) completes before we read
   bindings. Microtask runs before any actual SDK usage, so a real
   stub leak still surfaces well before the first query() call.

Tests (3): SDK barrel imports without throwing, anti-regression on
real __stub: true bindings, TDZ-shaped access returns undefined.

* test(sdk): exercise the real stub-leak detector with stubbed fixtures (#1287)

The regression test asserted only that a local object literal had
__stub === true and re-implemented safelyAccess inline, so it never ran
the real detector: removing queueMicrotask(detectStubLeaks), dropping the
loop, or swallowing the __stub case would all still pass.

Split the detection primitives (safelyAccess + the critical-import scan)
into src/entrypoints/sdk/stubLeakDetection.ts and have the SDK entry point
import them. The test now feeds stub-shaped fixtures through the real
checkCriticalImportsForStubs / safelyAccess and asserts: a real
__stub: true binding throws the explicit SDK init error; non-stub modules
pass; a TDZ ReferenceError is tolerated (skipped) without crashing; a stub
behind a skipped TDZ access is still caught; and the SDK barrel import
never throws on its own load. Detector runtime behavior is unchanged.
2026-06-17 10:55:53 +08:00
..