@ultimat3/testing 30.9.0 → 31.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CLAUDE.md +46 -55
  2. package/README.md +179 -39
  3. package/package.json +23 -17
  4. package/src/ai-conformance-answer.ts +67 -0
  5. package/src/ai-gateway-conformance.ts +105 -0
  6. package/src/ai-provider-conformance.ts +69 -0
  7. package/src/ai-provider-transport-conformance.ts +170 -0
  8. package/src/audit-sink-conformance.ts +204 -0
  9. package/src/auth-adapter-conformance-credentials.ts +124 -0
  10. package/src/auth-adapter-conformance-mfa.ts +70 -0
  11. package/src/auth-adapter-conformance-passkeys.ts +133 -0
  12. package/src/auth-adapter-conformance-sessions.ts +115 -0
  13. package/src/auth-adapter-conformance-support.ts +71 -0
  14. package/src/auth-adapter-conformance-users.ts +128 -0
  15. package/src/auth-adapter-conformance.ts +34 -0
  16. package/src/auth-limiter-factory-conformance.ts +224 -0
  17. package/src/auth-server-store-conformance-records.ts +69 -0
  18. package/src/auth-server-store-conformance.ts +208 -0
  19. package/src/cache-tier-conformance-checks.ts +142 -0
  20. package/src/cache-tier-conformance.ts +24 -0
  21. package/src/cassette-format.ts +8 -13
  22. package/src/cassette-record.ts +1 -1
  23. package/src/cdp-browser.ts +10 -11
  24. package/src/cdp-e2e-page.ts +2 -2
  25. package/src/cdp-e2e-session.ts +2 -2
  26. package/src/cdp-network-probe.ts +1 -1
  27. package/src/cdp-offline-script.ts +2 -2
  28. package/src/clock-conformance.ts +126 -0
  29. package/src/conformance.ts +239 -0
  30. package/src/e2e-browser-handle.ts +1 -2
  31. package/src/e2e-error-codes.ts +17 -16
  32. package/src/e2e-run.ts +4 -3
  33. package/src/embedder-conformance.ts +101 -0
  34. package/src/entity-conformance-aggregates.ts +210 -0
  35. package/src/entity-conformance-batches.ts +216 -0
  36. package/src/entity-conformance-bulk.ts +379 -0
  37. package/src/entity-conformance-checks.ts +27 -0
  38. package/src/entity-conformance-entities.ts +52 -0
  39. package/src/entity-conformance-locks.ts +286 -0
  40. package/src/entity-conformance-matrix.ts +397 -0
  41. package/src/entity-conformance-reads.ts +241 -0
  42. package/src/entity-conformance-support.ts +56 -0
  43. package/src/entity-conformance-tenancy.ts +296 -0
  44. package/src/entity-conformance-values.ts +305 -0
  45. package/src/entity-conformance-versions.ts +60 -0
  46. package/src/entity-conformance-writes.ts +348 -0
  47. package/src/entity-driver-conformance.ts +103 -0
  48. package/src/error-groups-store-conformance.ts +198 -0
  49. package/src/error-reporter-conformance.ts +119 -0
  50. package/src/errors.ts +20 -2
  51. package/src/event-bus-conformance.ts +161 -0
  52. package/src/exercise-drift-hint.ts +4 -1
  53. package/src/exercise-judge.ts +5 -3
  54. package/src/exercise-override-line.ts +98 -0
  55. package/src/exercise-report.ts +138 -115
  56. package/src/exercise-room-mail.ts +40 -0
  57. package/src/exercise.ts +33 -29
  58. package/src/factories.ts +192 -179
  59. package/src/factory-api.ts +131 -0
  60. package/src/factory-associations.ts +67 -0
  61. package/src/factory-errors.ts +38 -0
  62. package/src/factory-lint.ts +92 -0
  63. package/src/factory-persist.ts +74 -16
  64. package/src/factory-pipeline.ts +191 -0
  65. package/src/factory-registry.ts +2 -1
  66. package/src/factory-types.ts +131 -0
  67. package/src/failure-store-conformance.ts +137 -0
  68. package/src/fixture-jobs.ts +27 -11
  69. package/src/fixture-mail.ts +7 -7
  70. package/src/fixture-seed.ts +111 -0
  71. package/src/fixture-statements.ts +68 -52
  72. package/src/framework-fixtures.ts +1 -1
  73. package/src/idempotency-store-conformance.ts +186 -0
  74. package/src/idempotency-store-replay-conformance.ts +140 -0
  75. package/src/idempotency-store-tx-conformance.ts +132 -0
  76. package/src/idempotency-store-world-conformance.ts +82 -0
  77. package/src/identity-provider-conformance.ts +144 -0
  78. package/src/image-transform-conformance.ts +89 -0
  79. package/src/index.ts +68 -157
  80. package/src/isr-store-conformance.ts +113 -0
  81. package/src/job-sim-effects.ts +19 -31
  82. package/src/job-sim-world.ts +6 -15
  83. package/src/lease-store-conformance.ts +195 -0
  84. package/src/mail-driver-conformance.ts +108 -0
  85. package/src/matcher-doubles.ts +104 -0
  86. package/src/matcher-stub.ts +78 -0
  87. package/src/matcher-surface.ts +21 -0
  88. package/src/matchers.ts +19 -1
  89. package/src/mcp-confirmation-store-conformance.ts +262 -0
  90. package/src/meter-store-conformance.ts +135 -0
  91. package/src/notify-digest-conformance.ts +133 -0
  92. package/src/notify-inbox-conformance.ts +130 -0
  93. package/src/notify-ledger-conformance.ts +134 -0
  94. package/src/notify-preference-conformance.ts +49 -0
  95. package/src/notify-stores-conformance.ts +73 -0
  96. package/src/outbox-store-conformance-claims.ts +112 -0
  97. package/src/outbox-store-conformance-subject.ts +65 -0
  98. package/src/outbox-store-conformance.ts +71 -0
  99. package/src/per-test-reset.ts +55 -20
  100. package/src/preload.ts +4 -2
  101. package/src/purge-conformance.ts +79 -0
  102. package/src/push-device-conformance.ts +124 -0
  103. package/src/push-subscription-conformance.ts +123 -0
  104. package/src/quiet-logs.ts +4 -4
  105. package/src/rate-limit-store-conformance.ts +178 -0
  106. package/src/registry-leak-error.ts +8 -1
  107. package/src/scale-sweep-run.ts +6 -9
  108. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  109. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  110. package/src/scrape-driver-conformance-site.ts +84 -0
  111. package/src/scrape-driver-conformance.ts +34 -0
  112. package/src/sealed-network.ts +20 -2
  113. package/src/search-index-conformance-list.ts +76 -0
  114. package/src/search-index-conformance-support.ts +69 -0
  115. package/src/search-index-conformance-versions.ts +66 -0
  116. package/src/search-index-conformance.ts +126 -0
  117. package/src/secret-source-conformance.ts +91 -0
  118. package/src/seed-factories.ts +57 -0
  119. package/src/seed-writer.ts +8 -19
  120. package/src/semantic-cache-factory-conformance.ts +86 -0
  121. package/src/sms-transport-conformance.ts +102 -0
  122. package/src/step-store-conformance.ts +171 -0
  123. package/src/storage-conformance-read-checks.ts +132 -0
  124. package/src/storage-conformance-shape.ts +121 -0
  125. package/src/storage-conformance-stream-checks.ts +226 -0
  126. package/src/storage-conformance.ts +34 -0
  127. package/src/stub-action.ts +24 -0
  128. package/src/stub-errors.ts +86 -0
  129. package/src/stub-job.ts +30 -0
  130. package/src/stub-query.ts +25 -0
  131. package/src/stub-script.ts +76 -0
  132. package/src/stub-stack.ts +29 -0
  133. package/src/stub.ts +73 -0
  134. package/src/swap-adapter.ts +135 -0
  135. package/src/test-scope.ts +96 -0
  136. package/src/test-types.ts +1 -1
  137. package/src/totp-replay-guard-conformance.ts +76 -0
  138. package/src/transport-conformance.ts +179 -0
  139. package/src/upload-scanner-conformance.ts +112 -0
  140. package/src/vector-store-conformance-checks.ts +174 -0
  141. package/src/vector-store-conformance.ts +21 -0
  142. package/src/cdp-connection.ts +0 -291
  143. package/src/cdp-errors.ts +0 -179
  144. package/src/cdp-launch-attempt.ts +0 -224
  145. package/src/cdp-launch-candidates.ts +0 -62
  146. package/src/cdp-launch-profile.ts +0 -106
  147. package/src/cdp-launch-reap.ts +0 -68
  148. package/src/cdp-launch-wire.ts +0 -171
  149. package/src/cdp-launch.ts +0 -175
  150. package/src/cdp-pipe.ts +0 -77
  151. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,25 @@
1
+ // Single responsibility: put a stub where a query's ROWS come from, through `@ultimat3/query`'s own
2
+ // seam — the actor check, the rate limit, the input parse and the policy still run on every surface
3
+ // (a direct call, `.as()`, HTTP, MCP, a live read), and the stub answers instead of the SQL and the
4
+ // cache. Loaded only when a query is stubbed.
5
+
6
+ import type { Ctx } from '@ultimat3/core';
7
+ import type { AnyQuery } from '@ultimat3/query';
8
+ import type { StubWiring } from './stub-script';
9
+ import { stubStack } from './stub-stack';
10
+ import type { Undo } from './test-scope';
11
+
12
+ /** Stubs stack per target: a test's over a file's hands the file's back (`stub-stack.ts`). */
13
+ const push =
14
+ stubStack<(args: { readonly input: unknown; readonly ctx: Ctx }) => Promise<readonly object[]>>();
15
+
16
+ /** Push `wiring`'s rows over `target`'s reads; the undo pops this stub and no other. */
17
+ export async function stubQueryRows(
18
+ target: AnyQuery,
19
+ wiring: StubWiring<unknown, readonly object[]>,
20
+ ): Promise<Undo> {
21
+ const { overrideRows } = await import('@ultimat3/query/adapter');
22
+ const handle = (args: { readonly input: unknown; readonly ctx: Ctx }) =>
23
+ wiring.answer(args.input, args.ctx.actor);
24
+ return push(target, handle, (top) => overrideRows(target, top));
25
+ }
@@ -0,0 +1,76 @@
1
+ // Single responsibility: what a stubbed body ANSWERS and what it was ASKED — the scripted answers
2
+ // (`returns`, `throws`, played in order, the last repeated) and the call record. Which body is
3
+ // replaced, and how it is put back, is `stub.ts`'s; this module never touches a primitive.
4
+
5
+ import type { Actor, UltimateError } from '@ultimat3/core';
6
+ import type { StandardSchemaV1 } from '@ultimat3/schema';
7
+ import { TestStubUnansweredError } from './stub-errors';
8
+
9
+ /** One call the stubbed body received: the PARSED input it was handed and who was asking. */
10
+ export interface StubCall<I> {
11
+ readonly input: I;
12
+ readonly actor: Actor;
13
+ }
14
+
15
+ /**
16
+ * A primitive whose body answers from a script. `I` is the parsed input its body sees and `O` what
17
+ * its body returns — the output schema still checks every answer, on every surface.
18
+ */
19
+ export interface Stub<I, O> {
20
+ /** The primitive's registered name. */
21
+ readonly name: string;
22
+ /** Every call, oldest first. `expect(stubbed).toHaveBeenCalledWith(input)` reads it. */
23
+ readonly calls: readonly StubCall<I>[];
24
+ /** Answer `values` in order, one per call; the last one answers every call after it. */
25
+ returns(...values: readonly O[]): Stub<I, O>;
26
+ /** The next call — and, if it is the last step scripted, every call after — throws `error`. */
27
+ throws(error: UltimateError): Stub<I, O>;
28
+ }
29
+
30
+ type Step<O> =
31
+ | { readonly kind: 'value'; readonly value: O }
32
+ | { readonly kind: 'throw'; readonly error: UltimateError };
33
+
34
+ /** The half of a stub only this package reads: the body's replacement and the input schema. */
35
+ export interface StubWiring<I, O> {
36
+ readonly stub: Stub<I, O>;
37
+ /** Record the call, then play the next step. */
38
+ answer(input: I, actor: Actor): Promise<O>;
39
+ }
40
+
41
+ const SCHEMAS = new WeakMap<object, StandardSchemaV1>();
42
+
43
+ /** The input schema a stub's expected inputs are parsed by — `toHaveBeenCalledWith`'s check. */
44
+ export function stubInputSchema(value: unknown): StandardSchemaV1 | undefined {
45
+ return typeof value === 'object' && value !== null ? SCHEMAS.get(value) : undefined;
46
+ }
47
+
48
+ /** Build the script and record for one stubbed primitive, named `name`, parsed by `input`. */
49
+ export function stubScript<I, O>(name: string, input: StandardSchemaV1): StubWiring<I, O> {
50
+ const calls: StubCall<I>[] = [];
51
+ const steps: Step<O>[] = [];
52
+ let played = 0;
53
+ const stub: Stub<I, O> = {
54
+ name,
55
+ calls,
56
+ returns(...values) {
57
+ for (const value of values) steps.push({ kind: 'value', value });
58
+ return stub;
59
+ },
60
+ throws(error) {
61
+ steps.push({ kind: 'throw', error });
62
+ return stub;
63
+ },
64
+ };
65
+ SCHEMAS.set(stub, input);
66
+ return {
67
+ stub,
68
+ answer(input, actor) {
69
+ calls.push({ input, actor });
70
+ const step = steps[Math.min(played, steps.length - 1)];
71
+ played += 1;
72
+ if (step === undefined) return Promise.reject(new TestStubUnansweredError(name));
73
+ return step.kind === 'value' ? Promise.resolve(step.value) : Promise.reject(step.error);
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,29 @@
1
+ // Single responsibility: the stubs live on one target, as a stack. A test's stub over a file's
2
+ // stub answers for that test and hands the FILE's stub back when it ends — never the declared body
3
+ // — and a stub undone out of order removes only itself (frames by identity, not by position).
4
+
5
+ import type { Undo } from './test-scope';
6
+
7
+ /** Push `handle` over a target; `apply` puts the top (or, emptied, nothing) in place. */
8
+ export type StubPush<H> = (target: object, handle: H, apply: (top: H | undefined) => void) => Undo;
9
+
10
+ /** One stack per target, for one kind of seam. */
11
+ export function stubStack<H>(): StubPush<H> {
12
+ const stacks = new WeakMap<object, { readonly handle: H }[]>();
13
+ return (target, handle, apply) => {
14
+ const frames = stacks.get(target) ?? [];
15
+ stacks.set(target, frames);
16
+ // A frame per push, so one handle pushed twice is still two frames.
17
+ const frame = { handle };
18
+ frames.push(frame);
19
+ apply(handle);
20
+ let done = false;
21
+ return () => {
22
+ if (done) return;
23
+ done = true;
24
+ const at = frames.indexOf(frame);
25
+ if (at !== -1) frames.splice(at, 1);
26
+ apply(frames.at(-1)?.handle);
27
+ };
28
+ };
29
+ }
package/src/stub.ts ADDED
@@ -0,0 +1,73 @@
1
+ // Single responsibility: `stub(primitive)` — the one test double for an action, an `llm()` (which
2
+ // IS an action), a query or a job. Its body answers from a script; everything around the body stays the
3
+ // real path, and the stub is put back after the test that made it (`test-scope.ts`).
4
+
5
+ import type { Action } from '@ultimat3/action';
6
+ import type { JobHandle } from '@ultimat3/jobs';
7
+ import { isJobHandle } from '@ultimat3/jobs';
8
+ import type { Query } from '@ultimat3/query';
9
+ import type { InferOutput, StandardSchemaV1 } from '@ultimat3/schema';
10
+ import { TestStubTargetUnsupportedError } from './stub-errors';
11
+ import { stubJobBody } from './stub-job';
12
+ import type { Stub, StubWiring } from './stub-script';
13
+ import { stubScript } from './stub-script';
14
+ import type { Undo } from './test-scope';
15
+ import { scopedInstall } from './test-scope';
16
+
17
+ const isCallableObject = (value: unknown): value is object =>
18
+ (typeof value === 'object' || typeof value === 'function') && value !== null;
19
+
20
+ async function install(
21
+ target: unknown,
22
+ wiring: (input: StandardSchemaV1) => StubWiring<unknown, unknown>,
23
+ ): Promise<{ readonly stub: Stub<unknown, unknown>; readonly undo: Undo }> {
24
+ if (isJobHandle(target)) {
25
+ const wired = wiring(target.input);
26
+ return { stub: wired.stub, undo: stubJobBody(target, wired) };
27
+ }
28
+ // Loaded only now: the barrel stays action-free for a tier-0 test importing it for `expect`.
29
+ const { isAction } = await import('@ultimat3/action');
30
+ if (isAction(target)) {
31
+ const { stubActionHandler } = await import('./stub-action');
32
+ const wired = wiring(target.input);
33
+ return { stub: wired.stub, undo: await stubActionHandler(target, wired) };
34
+ }
35
+ const { isQuery } = await import('@ultimat3/query');
36
+ if (isQuery(target)) {
37
+ const { stubQueryRows } = await import('./stub-query');
38
+ const wired = wiring(target.input) as StubWiring<unknown, readonly object[]>;
39
+ return { stub: wired.stub, undo: await stubQueryRows(target, wired) };
40
+ }
41
+ throw new TestStubTargetUnsupportedError(target);
42
+ }
43
+
44
+ /**
45
+ * Replace `target`'s body for this test — inside a test, until it ends; outside one (`beforeAll`,
46
+ * module scope), until its file ends. `returns(...)` / `throws(error)` script the answers;
47
+ * `expect(stubbed).toHaveBeenCalledWith(input)` reads the calls.
48
+ *
49
+ * ```ts
50
+ * const charged = await stub(chargeCard);
51
+ * charged.returns({ chargeId: 'ch_1' });
52
+ * await checkout({ cartId }); // the real action, calling the stubbed one
53
+ * expect(charged).toHaveBeenCalledWith({ cartId, amount });
54
+ * ```
55
+ */
56
+ export function stub<TInput extends StandardSchemaV1, TOutput extends StandardSchemaV1>(
57
+ target: Action<TInput, TOutput>,
58
+ ): Promise<Stub<InferOutput<TInput>, InferOutput<TOutput>>>;
59
+ export function stub<TInput extends StandardSchemaV1, TRow extends object, TSingle extends boolean>(
60
+ target: Query<TInput, TRow, TSingle>,
61
+ ): Promise<Stub<InferOutput<TInput>, readonly TRow[]>>;
62
+ export function stub<I>(target: JobHandle<I>): Promise<Stub<I, unknown>>;
63
+ export async function stub(target: unknown): Promise<Stub<unknown, unknown>> {
64
+ if (!isCallableObject(target)) throw new TestStubTargetUnsupportedError(target);
65
+ const name = (target as { readonly name?: unknown }).name;
66
+ const label = typeof name === 'string' ? name : '';
67
+ return scopedInstall(`stub(${label})`, async () => {
68
+ // Stubs STACK on a target (`stub-stack.ts`): a second one answers over the first, and its undo
69
+ // hands the first back — a file's stub survives a test's.
70
+ const { stub: made, undo } = await install(target, (input) => stubScript(label, input));
71
+ return { value: made, undo };
72
+ });
73
+ }
@@ -0,0 +1,135 @@
1
+ // Single responsibility: `swapAdapter(port, impl)` — the one way a test replaces an adapter port
2
+ // (`ADAPTER_PORTS`, core's registrar) for itself: installed through the port's own `./adapter`
3
+ // installer, put back after the test (`test-scope.ts`). Every port is either bound here or listed in
4
+ // `UNSWAPPED` with what a test does instead — a new row in core's table is a compile error here.
5
+
6
+ import type { IdempotencyStore, MeterStore } from '@ultimat3/action/adapter';
7
+ import type { Embedder, Gateway, SemanticCacheFactory } from '@ultimat3/ai/adapter';
8
+ import type { AuthLimiterFactory, TotpReplayGuard } from '@ultimat3/auth/adapter';
9
+ import type { AdapterPortName } from '@ultimat3/core';
10
+ import type {
11
+ AuditSink,
12
+ ErrorReporter,
13
+ FailureStore,
14
+ SecretSource,
15
+ SleepClock,
16
+ } from '@ultimat3/core/adapter';
17
+ import type { SearchIndex } from '@ultimat3/entity/adapter';
18
+ import type { RateLimitStore } from '@ultimat3/http/adapter';
19
+ import type { EventBus, JobDriver } from '@ultimat3/jobs/adapter';
20
+ import type { MailDriver } from '@ultimat3/mail/adapter';
21
+ import type { NotifyStores, SmsTransport } from '@ultimat3/notify/adapter';
22
+ import type { Transport } from '@ultimat3/realtime/adapter';
23
+ import type { ScrapeDriver } from '@ultimat3/scraping/adapter';
24
+ import { TestAdapterPortUnswappableError } from './stub-errors';
25
+ import type { Undo } from './test-scope';
26
+ import { scopedInstall } from './test-scope';
27
+
28
+ /** What each process-global port takes. The key is the `ADAPTER_PORTS` row's `port`. */
29
+ export interface SwappableAdapters {
30
+ readonly aiGateway: Gateway;
31
+ readonly auditSink: AuditSink;
32
+ readonly authLimiter: AuthLimiterFactory;
33
+ readonly clock: SleepClock;
34
+ readonly embedder: Embedder;
35
+ readonly errorReporter: ErrorReporter;
36
+ readonly eventBus: EventBus;
37
+ readonly failureStore: FailureStore;
38
+ readonly idempotencyStore: IdempotencyStore;
39
+ readonly jobs: JobDriver;
40
+ readonly mail: MailDriver;
41
+ readonly meterStore: MeterStore;
42
+ readonly notifyStores: NotifyStores;
43
+ readonly rateLimitStore: RateLimitStore;
44
+ readonly scrapeDriver: ScrapeDriver;
45
+ readonly searchIndex: SearchIndex;
46
+ readonly secretSource: SecretSource;
47
+ readonly semanticCache: SemanticCacheFactory;
48
+ readonly smsTransport: SmsTransport;
49
+ readonly totpReplay: TotpReplayGuard;
50
+ readonly transport: Transport;
51
+ }
52
+
53
+ /** The ports `swapAdapter` takes. Every one is a row of `ADAPTER_PORTS`, or this fails to compile. */
54
+ export type SwappablePort = keyof SwappableAdapters & AdapterPortName;
55
+
56
+ type Bindings = { readonly [P in SwappablePort]: (impl: SwappableAdapters[P]) => Promise<Undo> };
57
+
58
+ // Every installer answers its own release, restoring the value it replaced.
59
+ const BINDINGS: Bindings = {
60
+ aiGateway: async (impl) => (await import('@ultimat3/ai/adapter')).installAiGateway(impl),
61
+ auditSink: async (impl) => (await import('@ultimat3/core/adapter')).installAuditSink(impl),
62
+ authLimiter: async (impl) => (await import('@ultimat3/auth/adapter')).installAuthLimiters(impl),
63
+ clock: async (impl) => (await import('@ultimat3/core/adapter')).installClock(impl),
64
+ embedder: async (impl) => (await import('@ultimat3/ai/adapter')).installAiEmbedder(impl),
65
+ errorReporter: async (impl) =>
66
+ (await import('@ultimat3/core/adapter')).installErrorReporter(impl),
67
+ eventBus: async (impl) => (await import('@ultimat3/jobs/adapter')).installEventBus(impl),
68
+ failureStore: async (impl) => (await import('@ultimat3/core/adapter')).installFailureStore(impl),
69
+ idempotencyStore: async (impl) =>
70
+ (await import('@ultimat3/action/adapter')).installIdempotencyStore(impl),
71
+ jobs: async (impl) => (await import('@ultimat3/jobs/adapter')).installJobDriver(impl),
72
+ mail: async (impl) => (await import('@ultimat3/mail/adapter')).installMailDriver(impl),
73
+ meterStore: async (impl) => (await import('@ultimat3/action/adapter')).installMeterStore(impl),
74
+ notifyStores: async (impl) =>
75
+ (await import('@ultimat3/notify/adapter')).installNotifyStores(impl),
76
+ rateLimitStore: async (impl) =>
77
+ (await import('@ultimat3/http/adapter')).installRateLimitStore(impl),
78
+ scrapeDriver: async (impl) =>
79
+ (await import('@ultimat3/scraping/adapter')).installScrapeDriver(impl),
80
+ searchIndex: async (impl) => (await import('@ultimat3/entity/adapter')).installSearchIndex(impl),
81
+ secretSource: async (impl) => (await import('@ultimat3/core/adapter')).installSecretSource(impl),
82
+ semanticCache: async (impl) => (await import('@ultimat3/ai/adapter')).installSemanticCache(impl),
83
+ smsTransport: async (impl) =>
84
+ (await import('@ultimat3/notify/adapter')).installSmsTransport(impl),
85
+ // The slot takes a factory; the port carries one guard, which every call hands back.
86
+ totpReplay: async (impl) =>
87
+ (await import('@ultimat3/auth/adapter')).installTotpReplay(() => impl),
88
+ transport: async (impl) =>
89
+ (await import('@ultimat3/realtime/adapter')).installChannelTransport(impl),
90
+ };
91
+
92
+ /**
93
+ * The ports with no process-global slot a test could borrow, each with what a test does instead.
94
+ * A `Record` over the rest of `AdapterPortName`: a port added to core's table is a compile error
95
+ * until it is bound above or given its instruction here.
96
+ */
97
+ export const UNSWAPPED: Readonly<Record<Exclude<AdapterPortName, SwappablePort>, string>> = {
98
+ authServerStore:
99
+ 'passed to the authorization server when the app builds it: build one over a memory store in the test',
100
+ cacheTiers:
101
+ "registered by the boot from cache.tiers: register the test's tier with @ultimat3/cache's isolateTiers()",
102
+ images:
103
+ 'handed to the image route when the boot mounts it: call the route with your driver in the test',
104
+ isrStore: 'handed to the renderer at boot: pass your store to the render call under test',
105
+ mcpConfirmationStore:
106
+ 'handed to the MCP server when the boot builds it: build the server with your store in the test',
107
+ outboxStore: "the boot's outbox relay takes it: build the relay with your store in the test",
108
+ purge: "handed to the cache's CDN purge at boot: pass your driver to the bust under test",
109
+ pushSubscriptionStore: 'the push fixture owns one: destructure { push } in the test',
110
+ storage: 'disks are built by the boot: build the disk over your driver in the test',
111
+ uploadScanner:
112
+ '@ultimat3/testing takes no dependency on @ultimat3/storage: call installUploadScanner(scanner) from @ultimat3/storage/adapter in the test and run the release it answers in afterEach',
113
+ };
114
+
115
+ const isSwappable = (port: string): port is SwappablePort => Object.hasOwn(BINDINGS, port);
116
+
117
+ /**
118
+ * Replace a port's adapter for this test — inside a test, until it ends; outside one, until the
119
+ * file ends — and hand back `impl`, so the swap and the reference are one line:
120
+ *
121
+ * ```ts
122
+ * const queue = await swapAdapter('jobs', memoryJobDriver());
123
+ * ```
124
+ */
125
+ export async function swapAdapter<P extends SwappablePort>(
126
+ port: P,
127
+ impl: SwappableAdapters[P],
128
+ ): Promise<SwappableAdapters[P]> {
129
+ if (!isSwappable(port)) throw new TestAdapterPortUnswappableError(port, UNSWAPPED);
130
+ const install = BINDINGS[port] as (next: SwappableAdapters[P]) => Promise<Undo>;
131
+ return scopedInstall(`swapAdapter('${port}')`, async () => ({
132
+ value: impl,
133
+ undo: await install(impl),
134
+ }));
135
+ }
@@ -0,0 +1,96 @@
1
+ // Single responsibility: WHEN a test double is put back. A stub or a swapped adapter made inside a
2
+ // test is undone after that test; one made outside any test (a `beforeAll`, module scope) after its
3
+ // FILE. The preload's own hooks do it, so no test file writes an `afterEach` that a skipped block
4
+ // could leave unreached (`X_SKIP_CLEANUP_UNREACHED`'s defect, made impossible rather than refused).
5
+
6
+ import { afterEach, beforeEach } from 'bun:test';
7
+ import { onFileBoundary } from './file-boundary';
8
+ import { TestScopeUninstalledError } from './stub-errors';
9
+
10
+ /** Puts one double back. Synchronous: a file boundary cannot await, and no installer needs to. */
11
+ export type Undo = () => void;
12
+
13
+ let installed = false;
14
+ let inTest = false;
15
+ const testUndos: Undo[] = [];
16
+ const fileUndos: Undo[] = [];
17
+
18
+ /**
19
+ * Last made, first undone — two swaps of one port inside one test unwind to the value the test
20
+ * found. Every undo runs even when one throws; the first throw is what the caller sees.
21
+ */
22
+ function unwind(undos: Undo[]): void {
23
+ let first: { readonly error: unknown } | undefined;
24
+ for (let undo = undos.pop(); undo !== undefined; undo = undos.pop()) {
25
+ try {
26
+ undo();
27
+ } catch (error) {
28
+ first ??= { error };
29
+ }
30
+ }
31
+ if (first !== undefined) throw first.error;
32
+ }
33
+
34
+ /**
35
+ * Hand `undo` to the scope that is open now: the running test's, else the file's. Refused — never
36
+ * silently kept — in a process the testing preload did not set up: nothing would ever run it, and
37
+ * the double would answer for every later file on the worker.
38
+ */
39
+ export function deferRestore(what: string, undo: Undo): void {
40
+ if (!installed) throw new TestScopeUninstalledError(what);
41
+ (inTest ? testUndos : fileUndos).push(undo);
42
+ }
43
+
44
+ /**
45
+ * `deferRestore` for an install that has to AWAIT (a module loaded on first use). The undo is
46
+ * registered first, so a missing preload refuses before anything changes; and when the scope ends
47
+ * while the install is still in flight — a test that timed out on a cold import — the install that
48
+ * lands afterwards is undone the moment it lands, never left to answer for every later test.
49
+ */
50
+ export async function scopedInstall<T>(
51
+ what: string,
52
+ install: () => Promise<{ readonly value: T; readonly undo: Undo }>,
53
+ ): Promise<T> {
54
+ let closed = false;
55
+ let undo: Undo | undefined;
56
+ deferRestore(what, () => {
57
+ closed = true;
58
+ undo?.();
59
+ });
60
+ const installed = await install();
61
+ if (closed) installed.undo();
62
+ else undo = installed.undo;
63
+ return installed.value;
64
+ }
65
+
66
+ /** Whether a double made now is the running test's (`true`) or its file's (`false`). */
67
+ export function inTestScope(): boolean {
68
+ return inTest;
69
+ }
70
+
71
+ /** The test's half, run by the preload's `afterEach`. Exported for this package's own tests. */
72
+ export function endTestScope(): void {
73
+ inTest = false;
74
+ unwind(testUndos);
75
+ }
76
+
77
+ /** The file's half, run at the boundary before the next file — after its tests' halves. */
78
+ export function endFileScope(): void {
79
+ endTestScope();
80
+ unwind(fileUndos);
81
+ }
82
+
83
+ /**
84
+ * Called once per process by both preloads, through `installPerTestReset`. A preload's
85
+ * `beforeEach` runs before a file's own and its `afterEach` after, so a file's `afterEach` still
86
+ * sees its stubs and nothing it made outlives the test.
87
+ */
88
+ export function installTestScope(): void {
89
+ if (installed) return;
90
+ installed = true;
91
+ beforeEach(() => {
92
+ inTest = true;
93
+ });
94
+ afterEach(endTestScope);
95
+ onFileBoundary(endFileScope);
96
+ }
package/src/test-types.ts CHANGED
@@ -155,7 +155,7 @@ export const hasE2eDriver = (): boolean => e2eDriver !== undefined;
155
155
  * Put the seam back. The counterpart `useE2eDriver` shipped without, and the module scope it
156
156
  * writes to is process-global: `bun test` shares one process across files, so a file that installs
157
157
  * a browser and does not undo it hands every later file an `e2eTest` that opens a page nobody
158
- * asked for. Same shape and same reason as `@ultimat3/scraping`'s `resetScrapeDriver()`.
158
+ * asked for. Same shape and same reason as `resetScrapeDriver()` on `@ultimat3/scraping/adapter`.
159
159
  */
160
160
  export const resetE2eDriver = (): void => {
161
161
  e2eDriver = undefined;
@@ -0,0 +1,76 @@
1
+ // The `TotpReplayGuard` contract of `@ultimat3/auth` as shared examples, for a guard of your own:
2
+ // `behavesLike(totpReplayGuardConformance, () => guard)`. One atomic claim per (subject, step): a
3
+ // code is single-use across every replica that shares the guard, and two concurrent completions
4
+ // carrying one code admit exactly one.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { TotpReplayGuard } from '@ultimat3/auth/adapter';
8
+ import type { SharedExamples } from './shared-examples';
9
+ import { sharedExamples } from './shared-examples';
10
+
11
+ export interface TotpReplayGuardCheck {
12
+ readonly name: string;
13
+ run(guard: TotpReplayGuard): Promise<void>;
14
+ }
15
+
16
+ /** A TOTP step is 30 s. `at` and `step` agree, as `verifyTotp` hands them over. */
17
+ const STEP_MS = 30_000;
18
+ const AT = new Date('2031-03-04T05:06:00.000Z');
19
+ const STEP = Math.floor(AT.getTime() / STEP_MS);
20
+ const later = (steps: number): Date => new Date(AT.getTime() + steps * STEP_MS);
21
+ const RACERS = 10;
22
+
23
+ /** A subject no other check, run or process shares — a shared table holds every run's steps. */
24
+ const subjectOf = (label: string): string => `conformance:${label}:${crypto.randomUUID()}`;
25
+
26
+ export const TOTP_REPLAY_GUARD_CHECKS: readonly TotpReplayGuardCheck[] = [
27
+ {
28
+ name: 'the first claim of a step is true, every repeat is false',
29
+ async run(guard) {
30
+ const subject = subjectOf('once');
31
+ expect(await guard.claim(subject, STEP, AT)).toBe(true);
32
+ expect(await guard.claim(subject, STEP, AT)).toBe(false);
33
+ expect(await guard.claim(subject, STEP, later(1))).toBe(false);
34
+ },
35
+ },
36
+ {
37
+ name: 'a step is spent per subject, and a neighbouring step is its own',
38
+ async run(guard) {
39
+ const [ada, grace] = [subjectOf('ada'), subjectOf('grace')];
40
+ expect(await guard.claim(ada, STEP, AT)).toBe(true);
41
+ expect(await guard.claim(grace, STEP, AT)).toBe(true);
42
+ expect(await guard.claim(ada, STEP + 1, AT)).toBe(true);
43
+ expect(await guard.claim(ada, STEP - 1, AT)).toBe(true);
44
+ },
45
+ },
46
+ {
47
+ name: 'a step spent stays spent while the drift window can still offer it',
48
+ async run(guard) {
49
+ const subject = subjectOf('window');
50
+ expect(await guard.claim(subject, STEP, AT)).toBe(true);
51
+ expect(await guard.claim(subject, STEP + 1, later(1))).toBe(true);
52
+ // One step on, `verifyTotp` with the default drift still offers STEP: it must still be spent.
53
+ expect(await guard.claim(subject, STEP, later(1))).toBe(false);
54
+ },
55
+ },
56
+ {
57
+ name: `${RACERS} concurrent claims of one step: exactly one is true`,
58
+ async run(guard) {
59
+ const subject = subjectOf('race');
60
+ const answers = await Promise.all(
61
+ Array.from({ length: RACERS }, () => guard.claim(subject, STEP, AT)),
62
+ );
63
+ expect(answers.filter(Boolean)).toHaveLength(1);
64
+ },
65
+ },
66
+ ];
67
+
68
+ export const totpReplayGuardConformance: SharedExamples<
69
+ TotpReplayGuard | Promise<TotpReplayGuard>
70
+ > = sharedExamples('a TOTP replay guard', (subject) => {
71
+ for (const check of TOTP_REPLAY_GUARD_CHECKS) {
72
+ test(check.name, async () => {
73
+ await check.run(await subject());
74
+ });
75
+ }
76
+ });