@ultimat3/testing 30.8.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CLAUDE.md +49 -62
  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 +41 -11
  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-input.ts +22 -9
  55. package/src/exercise-override-line.ts +98 -0
  56. package/src/exercise-report.ts +30 -51
  57. package/src/exercise-sweeps.ts +3 -1
  58. package/src/exercise.ts +38 -19
  59. package/src/factories.ts +192 -179
  60. package/src/factory-api.ts +131 -0
  61. package/src/factory-associations.ts +67 -0
  62. package/src/factory-errors.ts +38 -0
  63. package/src/factory-lint.ts +92 -0
  64. package/src/factory-persist.ts +74 -16
  65. package/src/factory-pipeline.ts +191 -0
  66. package/src/factory-registry.ts +2 -1
  67. package/src/factory-types.ts +131 -0
  68. package/src/failure-store-conformance.ts +137 -0
  69. package/src/fixture-jobs.ts +50 -15
  70. package/src/fixture-mail.ts +7 -7
  71. package/src/fixture-seed.ts +111 -0
  72. package/src/fixture-statements.ts +68 -52
  73. package/src/framework-fixtures.ts +1 -1
  74. package/src/idempotency-store-conformance.ts +186 -0
  75. package/src/idempotency-store-replay-conformance.ts +140 -0
  76. package/src/idempotency-store-tx-conformance.ts +132 -0
  77. package/src/idempotency-store-world-conformance.ts +82 -0
  78. package/src/identity-provider-conformance.ts +144 -0
  79. package/src/image-transform-conformance.ts +89 -0
  80. package/src/index.ts +68 -157
  81. package/src/isr-store-conformance.ts +113 -0
  82. package/src/job-sim-effects.ts +19 -31
  83. package/src/job-sim-world.ts +6 -15
  84. package/src/lease-store-conformance.ts +195 -0
  85. package/src/mail-driver-conformance.ts +108 -0
  86. package/src/matcher-doubles.ts +104 -0
  87. package/src/matcher-stub.ts +78 -0
  88. package/src/matcher-surface.ts +21 -0
  89. package/src/matchers.ts +19 -1
  90. package/src/mcp-confirmation-store-conformance.ts +262 -0
  91. package/src/meter-store-conformance.ts +135 -0
  92. package/src/notify-digest-conformance.ts +133 -0
  93. package/src/notify-inbox-conformance.ts +130 -0
  94. package/src/notify-ledger-conformance.ts +134 -0
  95. package/src/notify-preference-conformance.ts +49 -0
  96. package/src/notify-stores-conformance.ts +73 -0
  97. package/src/outbox-store-conformance-claims.ts +112 -0
  98. package/src/outbox-store-conformance-subject.ts +65 -0
  99. package/src/outbox-store-conformance.ts +71 -0
  100. package/src/per-test-reset.ts +55 -20
  101. package/src/plan-oracle.ts +10 -3
  102. package/src/plan-sweep.ts +37 -12
  103. package/src/preload.ts +4 -2
  104. package/src/purge-conformance.ts +79 -0
  105. package/src/push-device-conformance.ts +124 -0
  106. package/src/push-subscription-conformance.ts +123 -0
  107. package/src/quiet-logs.ts +4 -4
  108. package/src/rate-limit-store-conformance.ts +178 -0
  109. package/src/registry-leak-error.ts +8 -1
  110. package/src/scale-sweep-run.ts +3 -1
  111. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  112. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  113. package/src/scrape-driver-conformance-site.ts +84 -0
  114. package/src/scrape-driver-conformance.ts +34 -0
  115. package/src/sealed-dns-resolver.ts +56 -0
  116. package/src/sealed-dns.ts +63 -64
  117. package/src/sealed-network.ts +13 -12
  118. package/src/sealed-node-sockets.ts +63 -0
  119. package/src/sealed-sockets.ts +13 -8
  120. package/src/sealed-udp.ts +118 -0
  121. package/src/search-index-conformance-list.ts +76 -0
  122. package/src/search-index-conformance-support.ts +69 -0
  123. package/src/search-index-conformance-versions.ts +66 -0
  124. package/src/search-index-conformance.ts +126 -0
  125. package/src/secret-source-conformance.ts +91 -0
  126. package/src/seed-factories.ts +57 -0
  127. package/src/seed-writer.ts +8 -19
  128. package/src/semantic-cache-factory-conformance.ts +86 -0
  129. package/src/sms-transport-conformance.ts +102 -0
  130. package/src/step-store-conformance.ts +171 -0
  131. package/src/storage-conformance-read-checks.ts +132 -0
  132. package/src/storage-conformance-shape.ts +121 -0
  133. package/src/storage-conformance-stream-checks.ts +226 -0
  134. package/src/storage-conformance.ts +34 -0
  135. package/src/stub-action.ts +24 -0
  136. package/src/stub-errors.ts +86 -0
  137. package/src/stub-job.ts +30 -0
  138. package/src/stub-query.ts +25 -0
  139. package/src/stub-script.ts +76 -0
  140. package/src/stub-stack.ts +29 -0
  141. package/src/stub.ts +73 -0
  142. package/src/swap-adapter.ts +135 -0
  143. package/src/test-scope.ts +96 -0
  144. package/src/test-types.ts +1 -1
  145. package/src/totp-replay-guard-conformance.ts +76 -0
  146. package/src/transport-conformance.ts +179 -0
  147. package/src/upload-scanner-conformance.ts +112 -0
  148. package/src/vector-store-conformance-checks.ts +174 -0
  149. package/src/vector-store-conformance.ts +21 -0
  150. package/src/cdp-connection.ts +0 -291
  151. package/src/cdp-errors.ts +0 -179
  152. package/src/cdp-launch-attempt.ts +0 -224
  153. package/src/cdp-launch-candidates.ts +0 -62
  154. package/src/cdp-launch-profile.ts +0 -106
  155. package/src/cdp-launch-reap.ts +0 -68
  156. package/src/cdp-launch-wire.ts +0 -171
  157. package/src/cdp-launch.ts +0 -175
  158. package/src/cdp-pipe.ts +0 -77
  159. package/src/cdp-wire-watch.ts +0 -113
@@ -1,35 +1,54 @@
1
1
  // What every test starts from, put back by the preload before each one — the per-TEST half of
2
- // isolation, beside `file-boundary.ts`'s per-file half. Today one thing: the jobs event bus, which
3
- // STORES what it is handed, so an answer one test published resumed the next test's waiting run.
2
+ // isolation, beside `file-boundary.ts`'s per-file half: the jobs event bus, which STORES what it is
3
+ // handed (an answer one test published resumed the next test's waiting run), and the installed
4
+ // rate-limit store, read per request (a bucket one test drained was the next test's 429).
4
5
 
5
6
  import { beforeEach } from 'bun:test';
6
- import type { resetEventBus } from '@ultimat3/jobs';
7
+ import type { clearDefaultRateLimitBuckets } from '@ultimat3/http/adapter';
8
+ import type { freshDefaultEventBus, resetEventBus } from '@ultimat3/jobs/adapter';
9
+ import { onFileBoundary } from './file-boundary';
10
+ import { installTestScope } from './test-scope';
7
11
 
8
12
  let installed = false;
9
13
 
10
14
  /**
11
- * The module that holds the ambient bus, when something in this process has loaded it — and only
12
- * then. A test that never touched `@ultimat3/jobs` has no bus to reset, and loading the package to
13
- * reset one would put the jobs graph into every `packages/core` test.
15
+ * `file` of `pkg`, when something in this process has already loaded it — and only then. A test
16
+ * that never touched the package has nothing to reset, and loading it to reset would put its graph
17
+ * into every `packages/core` test. Resolved once per process: the path does not move.
14
18
  */
15
- function loadedEventsModule(): string | undefined {
16
- // Resolved once per process: every test asks, and the answer is a path that does not move.
17
- eventsPath ??= Bun.resolveSync('@ultimat3/jobs', import.meta.dir).replace(
18
- /index\.ts$/,
19
- 'events.ts',
20
- );
21
- return eventsPath in require.cache ? eventsPath : undefined;
19
+ function loaded(pkg: string, file: string): string | undefined {
20
+ const key = `${pkg}/${file}`;
21
+ let path = paths.get(key);
22
+ if (path === undefined) {
23
+ path = Bun.resolveSync(pkg, import.meta.dir).replace(/index\.ts$/, file);
24
+ paths.set(key, path);
25
+ }
26
+ return path in require.cache ? path : undefined;
22
27
  }
23
28
 
24
- let eventsPath: string | undefined;
29
+ const paths = new Map<string, string>();
25
30
 
26
- /** Before each test: a fresh ambient event bus, when the jobs package is loaded at all. */
31
+ /**
32
+ * Before each test: a fresh DEFAULT event bus and the DEFAULT rate-limit buckets emptied — each
33
+ * only when its package is loaded. Already evaluated, so each import answers from the registry, the
34
+ * same instance. Only the defaults: a bus or store installed for the file (`beforeAll`, a booted
35
+ * app's) stays installed, and carries across that file's tests as it would in production.
36
+ */
27
37
  export async function resetPerTestState(): Promise<void> {
28
- const events = loadedEventsModule();
29
- if (events === undefined) return;
30
- // Already evaluated — this import answers from the module registry, the same instance.
31
- const loaded = (await import(events)) as { readonly resetEventBus: typeof resetEventBus };
32
- loaded.resetEventBus();
38
+ const events = loaded('@ultimat3/jobs', 'events.ts');
39
+ if (events !== undefined) {
40
+ const jobs = (await import(events)) as {
41
+ readonly freshDefaultEventBus: typeof freshDefaultEventBus;
42
+ };
43
+ jobs.freshDefaultEventBus();
44
+ }
45
+ const limits = loaded('@ultimat3/http', 'rate-limit-installed.ts');
46
+ if (limits !== undefined) {
47
+ const http = (await import(limits)) as {
48
+ readonly clearDefaultRateLimitBuckets: typeof clearDefaultRateLimitBuckets;
49
+ };
50
+ http.clearDefaultRateLimitBuckets();
51
+ }
33
52
  }
34
53
 
35
54
  /**
@@ -40,4 +59,20 @@ export function installPerTestReset(): void {
40
59
  if (installed) return;
41
60
  installed = true;
42
61
  beforeEach(resetPerTestState);
62
+ // The test doubles' scope rides the same call, so both preloads — the app's and this repo's own
63
+ // `scripts/test-setup.ts` — put every stub and swapped adapter back with no second install line.
64
+ installTestScope();
65
+ // AFTER the scope's own file hook, so a file's swaps are released first: then the whole bus slot
66
+ // goes back to boot state. A frame a file installed and never released — an `afterEach` that
67
+ // "restored" by installing again — would otherwise outlive the file and hand every later test
68
+ // its events, which the per-test fresh DEFAULT bus underneath cannot reach.
69
+ onFileBoundary(resetEventBusAtFileEnd);
70
+ }
71
+
72
+ /** Synchronous, as a file boundary is: the module is already loaded, so `require` answers it. */
73
+ function resetEventBusAtFileEnd(): void {
74
+ const events = loaded('@ultimat3/jobs', 'events.ts');
75
+ if (events === undefined) return;
76
+ const jobs = require(events) as { readonly resetEventBus: typeof resetEventBus };
77
+ jobs.resetEventBus();
43
78
  }
@@ -1,6 +1,6 @@
1
- // The plan oracle: one `explain (format json)` plan, taken with sequential scans, bitmap scans and
2
- // sorts disabled, in; the nodes no index could replace, out. Under those settings the planner picks
3
- // a scan or a sort only when nothing else answers, so the verdict reads the schema, not the rows.
1
+ // The plan oracle: one `explain (format json)` plan, taken with sequential and bitmap scans (and,
2
+ // for a limited sort, sorts) disabled, in; the nodes no index could replace, out. The planner then
3
+ // picks a scan or a sort only when nothing else answers: the verdict reads the schema, not rows.
4
4
  // Pure: JSON in, verdicts out (plan 101, 40-next-query-plans).
5
5
 
6
6
  import { columnsIn } from './plan-conditions';
@@ -89,6 +89,13 @@ export function planRoot(answer: unknown): unknown {
89
89
  return record(first)?.['Plan'] ?? first;
90
90
  }
91
91
 
92
+ /** A `Limit` anywhere in the plan: only beneath one is a sort judged, so only then is one planned. */
93
+ export function planLimited(answer: unknown): boolean {
94
+ const limited = (node: PlanNode): boolean => node.type === 'Limit' || node.children.some(limited);
95
+ const root = nodeOf(planRoot(answer));
96
+ return root !== undefined && limited(root);
97
+ }
98
+
92
99
  /** Every scan beneath `node` (the node itself included), of any table. */
93
100
  const scansBeneath = (node: PlanNode): readonly PlanNode[] => [
94
101
  ...(node.table !== undefined && SCANS.has(node.type) ? [node] : []),
package/src/plan-sweep.ts CHANGED
@@ -1,14 +1,14 @@
1
1
  // The plan sweep: every distinct statement the exercise pass sent whose first relation is an app
2
- // table, planned on the migrated database with sequential scans, bitmap scans and sorts disabled,
3
- // judged by `plan-oracle.ts`, each red node named as the `indexes:` entry that answers it.
4
- // Read-only: `PREPARE` in a read-only transaction whose settings die with it, then `DEALLOCATE`.
2
+ // table, planned on the migrated database with sequential and bitmap scans disabled — and, for a
3
+ // limited read's sort only, sorts too — judged by `plan-oracle.ts`, each red node named as the
4
+ // `indexes:` entry that answers it. Read-only: `PREPARE` in a read-only transaction, `DEALLOCATE`.
5
5
 
6
6
  import { renderThrowable, UltimateError } from '@ultimat3/core';
7
7
  import type { DbClient } from '@ultimat3/db';
8
8
  import { isReservable, raw, sql, withReadTransaction } from '@ultimat3/db';
9
9
  import './errors';
10
- import type { PlanTableColumns } from './plan-oracle';
11
- import { judgePlan } from './plan-oracle';
10
+ import type { PlanTableColumns, PlanVerdict } from './plan-oracle';
11
+ import { judgePlan, planLimited } from './plan-oracle';
12
12
  import type { PlanFinding } from './plan-sweep-fix';
13
13
  import { planFindings } from './plan-sweep-fix';
14
14
  import type { SeedEntity } from './seed-graph-shape';
@@ -47,13 +47,18 @@ export class QueryPlanUnavailableError extends UltimateError {
47
47
  }
48
48
  }
49
49
 
50
- /** The planner's choices the sweep removes: what remains is what the schema can serve. */
51
- const SETTINGS = {
50
+ /**
51
+ * The planner's choices the sweep removes: what remains is what the schema can serve. The access
52
+ * path is judged with sorts allowed — off, an `order by` makes the planner walk whatever index
53
+ * holds the order, whole, instead of the one that keys the read. Only a sort under a `Limit` is
54
+ * judged, so only a limited read is planned again with sorts off, for its sort alone.
55
+ */
56
+ const ACCESS = {
52
57
  enable_seqscan: 'off',
53
58
  enable_bitmapscan: 'off',
54
- enable_sort: 'off',
55
59
  plan_cache_mode: 'force_generic_plan',
56
60
  } as const;
61
+ const SORTS = { ...ACCESS, enable_sort: 'off' } as const;
57
62
  const PREPARED = 'x_plan_sweep';
58
63
  const FIRST_RELATION = /\b(?:from|into|update|join)\s+(?:"?\w+"?\.)?"?([A-Za-z_][\w$]*)"?/i;
59
64
 
@@ -66,7 +71,11 @@ interface Planned {
66
71
  readonly refused?: string;
67
72
  }
68
73
 
69
- async function explain(client: DbClient, statement: string): Promise<Planned> {
74
+ async function explain(
75
+ client: DbClient,
76
+ statement: string,
77
+ settings: typeof ACCESS | typeof SORTS,
78
+ ): Promise<Planned> {
70
79
  const connection = isReservable(client) ? await client.reserve() : undefined;
71
80
  const on = connection ?? client;
72
81
  let prepared = false;
@@ -81,7 +90,7 @@ async function explain(client: DbClient, statement: string): Promise<Planned> {
81
90
  raw(`explain (format json) execute ${PREPARED}${args}`),
82
91
  );
83
92
  },
84
- { settings: SETTINGS, client: on },
93
+ { settings, client: on },
85
94
  );
86
95
  return { plan: rows[0]?.['QUERY PLAN'] };
87
96
  } catch (error) {
@@ -93,6 +102,22 @@ async function explain(client: DbClient, statement: string): Promise<Planned> {
93
102
  }
94
103
  }
95
104
 
105
+ /** One statement's verdicts: its access path planned as is, its limited sort with sorts off. */
106
+ async function judge(
107
+ client: DbClient,
108
+ statement: string,
109
+ tables: PlanTableColumns,
110
+ ): Promise<{ readonly verdicts?: readonly PlanVerdict[]; readonly refused?: string }> {
111
+ const access = await explain(client, statement, ACCESS);
112
+ if (access.refused !== undefined) return { refused: access.refused };
113
+ const read = judgePlan(access.plan, tables).filter((v) => v.code === 'X_QUERY_UNINDEXED');
114
+ if (!planLimited(access.plan)) return { verdicts: read };
115
+ const sorted = await explain(client, statement, SORTS);
116
+ if (sorted.refused !== undefined) return { refused: sorted.refused };
117
+ const sorts = judgePlan(sorted.plan, tables).filter((v) => v.code === 'X_QUERY_SORT_UNSERVED');
118
+ return { verdicts: [...read, ...sorts] };
119
+ }
120
+
96
121
  interface ProofBuilder {
97
122
  planned: number;
98
123
  readonly findings: PlanFinding[];
@@ -132,7 +157,7 @@ export async function sweepPlans(
132
157
  if (entity === undefined) continue;
133
158
  const declared = entity.$describe().scan;
134
159
  const exemptBy = scan ?? declared;
135
- const planned = exemptBy === undefined ? await explain(client, statement) : {};
160
+ const planned = exemptBy === undefined ? await judge(client, statement, judged) : {};
136
161
  for (const name of primitives) {
137
162
  const proof = proofOf(name);
138
163
  proof.planned += 1;
@@ -140,7 +165,7 @@ export async function sweepPlans(
140
165
  else if (planned.refused !== undefined) {
141
166
  proof.unplannable.push({ statement, reason: planned.refused });
142
167
  } else {
143
- proof.findings.push(...planFindings(statement, judgePlan(planned.plan, judged), byTable));
168
+ proof.findings.push(...planFindings(statement, planned.verdicts ?? [], byTable));
144
169
  }
145
170
  }
146
171
  }
package/src/preload.ts CHANGED
@@ -79,10 +79,12 @@ installTabA11yAudit();
79
79
  // the worker answering 503 X_DRAINING for a reason nothing in that file explains. Each file starts
80
80
  // from a live lifecycle, as a file run alone would have it.
81
81
  if (Bun.env[ISOLATED_ENV] !== '1') {
82
- const { forgetHandedOutActionPaths, resetMeterStore } = await import('@ultimat3/action');
82
+ const { forgetHandedOutActionPaths } = await import('@ultimat3/action');
83
83
  onFileBoundary(forgetHandedOutActionPaths);
84
+ // The meter store's reset is its port's, on the `./adapter` subpath (slice 21).
85
+ const { resetMeterStore } = await import('@ultimat3/action/adapter');
84
86
  onFileBoundary(resetMeterStore);
85
- const { resetRateLimitStore } = await import('@ultimat3/http');
87
+ const { resetRateLimitStore } = await import('@ultimat3/http/adapter');
86
88
  onFileBoundary(resetRateLimitStore);
87
89
  const { resetLifecycle } = await import('@ultimat3/core');
88
90
  onFileBoundary(resetLifecycle);
@@ -0,0 +1,79 @@
1
+ // The `PurgeDriver` contract as shared examples: `behavesLike(purgeDriverConformance, () => ({
2
+ // driver, refused }))`. `driver` reaches a CDN that accepts every purge; `refused`, when the driver
3
+ // can be refused at all, the same driver against one that refuses — a purge that cleared nothing
4
+ // must never resolve as one that did, because no later read can tell.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { PurgeDriver } from '@ultimat3/cache';
8
+ import type { UltimateError } from '@ultimat3/core';
9
+ import { isUltimateError } from '@ultimat3/core';
10
+ import type { SharedExamples } from './shared-examples';
11
+ import { sharedExamples } from './shared-examples';
12
+
13
+ export interface PurgeSubject {
14
+ readonly driver: PurgeDriver;
15
+ /** Omitted by a driver no provider can refuse — `noopPurgeDriver`. */
16
+ readonly refused?: PurgeDriver | undefined;
17
+ }
18
+
19
+ export interface PurgeCheck {
20
+ readonly name: string;
21
+ run(subject: PurgeSubject): Promise<void>;
22
+ }
23
+
24
+ /** Past Cloudflare's 30-tag and Fastly's 256-key request caps, so batching is part of the claim. */
25
+ const MANY = Array.from({ length: 300 }, (_, at) => `post:${at}`);
26
+
27
+ /** The coded error a call was refused with, or what happened instead, as a string to compare. */
28
+ async function refusalOf(call: () => Promise<unknown>): Promise<UltimateError | string> {
29
+ try {
30
+ await call();
31
+ } catch (caught) {
32
+ return isUltimateError(caught) ? caught : `not-a-coded-error: ${String(caught)}`;
33
+ }
34
+ return 'resolved';
35
+ }
36
+
37
+ export const PURGE_CHECKS: readonly PurgeCheck[] = [
38
+ {
39
+ name: 'a driver has a name, and an empty purge accepts nothing',
40
+ async run({ driver }) {
41
+ expect(driver.name).toMatch(/^\S+$/);
42
+ expect(await driver.purge([])).toEqual([]);
43
+ },
44
+ },
45
+ {
46
+ name: 'a purge the provider takes whole reports every key, unchanged, across every batch',
47
+ async run({ driver }) {
48
+ const keys = ['post', 'post:1', 'feed', 'org:9f3b-1'];
49
+ expect([...(await driver.purge(keys))].sort()).toEqual([...keys].sort());
50
+ expect([...(await driver.purge(MANY))].sort()).toEqual([...MANY].sort());
51
+ },
52
+ },
53
+ {
54
+ name: 'purgeAll resolves when the provider takes it',
55
+ async run({ driver }) {
56
+ await expect(driver.purgeAll()).resolves.toBeUndefined();
57
+ },
58
+ },
59
+ {
60
+ name: 'a refused purge and a refused purgeAll are X_CACHE_PURGE_FAILED with a fix, never accepted',
61
+ async run({ refused }) {
62
+ if (refused === undefined) return;
63
+ for (const call of [() => refused.purge(['post']), () => refused.purgeAll()]) {
64
+ const refusal = await refusalOf(call);
65
+ expect(typeof refusal === 'string' ? refusal : refusal.code).toBe('X_CACHE_PURGE_FAILED');
66
+ expect(typeof refusal === 'string' ? '' : refusal.fix).not.toBe('');
67
+ }
68
+ },
69
+ },
70
+ ];
71
+
72
+ export const purgeDriverConformance: SharedExamples<PurgeSubject | Promise<PurgeSubject>> =
73
+ sharedExamples('a CDN purge driver', (subject) => {
74
+ for (const check of PURGE_CHECKS) {
75
+ test(check.name, async () => {
76
+ await check.run(await subject());
77
+ });
78
+ }
79
+ });
@@ -0,0 +1,124 @@
1
+ // The `PushDeviceStore` contract of `@ultimat3/notify` as shared examples:
2
+ // `behavesLike(pushDeviceStoreConformance, () => store)`. A device is keyed `(platform, token)`,
3
+ // never by actor; one order by code point; a remove naming an owner reaches only theirs; a
4
+ // bad-token count that survives a re-register. Every check mints its own tokens and actors.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { PushDeviceRecord, PushDeviceStore } from '@ultimat3/notify';
8
+ import type { SharedExamples } from './shared-examples';
9
+ import { sharedExamples } from './shared-examples';
10
+
11
+ export interface PushDeviceStoreCheck {
12
+ readonly name: string;
13
+ run(store: PushDeviceStore): Promise<void>;
14
+ }
15
+
16
+ let minted = 0;
17
+ /** A per-check suffix: eight hex digits, so an APNs token built on it is still hex. */
18
+ const mint = (): string => {
19
+ minted += 1;
20
+ return ((process.pid * 4096 + minted) % 0x1_0000_0000).toString(16).padStart(8, '0');
21
+ };
22
+
23
+ interface Scope {
24
+ readonly ana: string;
25
+ readonly ben: string;
26
+ /** An APNs token: 28 repeats of `pair`, then the check's suffix. */
27
+ ios(pair?: string): string;
28
+ readonly android: string;
29
+ record(overrides?: Partial<PushDeviceRecord>): PushDeviceRecord;
30
+ }
31
+
32
+ const scope = (): Scope => {
33
+ const suffix = mint();
34
+ const ios = (pair = 'ab'): string => `${pair.repeat(28)}${suffix}`;
35
+ const ana = `ana-${suffix}`;
36
+ return {
37
+ ana,
38
+ ben: `ben-${suffix}`,
39
+ ios,
40
+ android: `fcm:${'Z'.repeat(52)}${suffix}`,
41
+ record: (overrides = {}) => ({
42
+ platform: 'ios',
43
+ token: ios(),
44
+ actorId: ana,
45
+ locale: 'es',
46
+ timeZone: 'Europe/Madrid',
47
+ createdAt: Date.parse('2026-11-06T09:00:00Z'),
48
+ ...overrides,
49
+ }),
50
+ };
51
+ };
52
+
53
+ export const PUSH_DEVICE_STORE_CHECKS: readonly PushDeviceStoreCheck[] = [
54
+ {
55
+ name: 'a re-register moves the device and keeps its first createdAt',
56
+ async run(store) {
57
+ const s = scope();
58
+ await store.save(s.record());
59
+ await store.save(s.record({ actorId: s.ben, locale: 'de', createdAt: 0 }));
60
+ expect(await store.listFor(s.ana)).toEqual([]);
61
+ expect(await store.listFor(s.ben)).toEqual([s.record({ actorId: s.ben, locale: 'de' })]);
62
+ },
63
+ },
64
+ {
65
+ name: 'one order, (platform, token) by code point',
66
+ async run(store) {
67
+ const s = scope();
68
+ // Upper case sorts before lower case by code point, and after it in most locales.
69
+ for (const pair of ['cd', 'ab', 'AB']) await store.save(s.record({ token: s.ios(pair) }));
70
+ await store.save(s.record({ platform: 'android', token: s.android }));
71
+ const listed = await store.listFor(s.ana);
72
+ expect(listed.map((d) => `${d.platform}:${d.token.slice(0, 2)}`)).toEqual([
73
+ 'android:fc',
74
+ 'ios:AB',
75
+ 'ios:ab',
76
+ 'ios:cd',
77
+ ]);
78
+ },
79
+ },
80
+ {
81
+ name: 'a remove naming another owner is absent; the sender’s remove reaches anyone',
82
+ async run(store) {
83
+ const s = scope();
84
+ await store.save(s.record());
85
+ expect(await store.remove('ios', s.ios(), s.ben)).toBe(false);
86
+ expect(await store.remove('android', s.ios())).toBe(false);
87
+ expect(await store.remove('ios', s.ios())).toBe(true);
88
+ expect(await store.remove('ios', s.ios())).toBe(false);
89
+ expect(await store.listFor(s.ana)).toEqual([]);
90
+ },
91
+ },
92
+ {
93
+ name: 'bad-token answers count up, survive a re-register, and a clear or a missing row is 0',
94
+ async run(store) {
95
+ const s = scope();
96
+ await store.save(s.record());
97
+ expect(await store.noteBadToken('ios', s.ios())).toBe(1);
98
+ expect(await store.noteBadToken('ios', s.ios())).toBe(2);
99
+ await store.save(s.record({ locale: 'de' }));
100
+ expect(await store.listFor(s.ana)).toEqual([s.record({ locale: 'de', badTokens: 2 })]);
101
+ await store.clearBadToken('ios', s.ios());
102
+ expect(await store.listFor(s.ana)).toEqual([s.record({ locale: 'de' })]);
103
+ expect(await store.noteBadToken('android', s.ios())).toBe(0);
104
+ },
105
+ },
106
+ {
107
+ name: 'a caller’s badTokens on save is ignored: only the store counts',
108
+ async run(store) {
109
+ const s = scope();
110
+ await store.save(s.record({ badTokens: 7 }));
111
+ expect(await store.listFor(s.ana)).toEqual([s.record()]);
112
+ },
113
+ },
114
+ ];
115
+
116
+ export const pushDeviceStoreConformance: SharedExamples<
117
+ PushDeviceStore | Promise<PushDeviceStore>
118
+ > = sharedExamples('a push device store', (subject) => {
119
+ for (const check of PUSH_DEVICE_STORE_CHECKS) {
120
+ test(check.name, async () => {
121
+ await check.run(await subject());
122
+ });
123
+ }
124
+ });
@@ -0,0 +1,123 @@
1
+ // The `PushSubscriptionStore` contract of `@ultimat3/pwa` as shared examples:
2
+ // `behavesLike(pushSubscriptionStoreConformance, () => store)`. A subscription is keyed by its
3
+ // endpoint, never by actor; one order by code point; a remove naming an owner reaches only theirs.
4
+ // Every check mints its own endpoints and actors, so one shared table serves them all.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import { isUltimateError } from '@ultimat3/core';
8
+ import type { PushSubscriptionRecord, PushSubscriptionStore } from '@ultimat3/pwa';
9
+ import type { SharedExamples } from './shared-examples';
10
+ import { sharedExamples } from './shared-examples';
11
+
12
+ export interface PushSubscriptionStoreCheck {
13
+ readonly name: string;
14
+ run(store: PushSubscriptionStore): Promise<void>;
15
+ }
16
+
17
+ const AT = Date.parse('2026-10-08T12:00:00.000Z');
18
+
19
+ let minted = 0;
20
+ interface Scope {
21
+ readonly ana: string;
22
+ readonly ben: string;
23
+ endpoint(path: string): string;
24
+ record(
25
+ path: string,
26
+ actorId: string,
27
+ overrides?: Partial<PushSubscriptionRecord>,
28
+ ): PushSubscriptionRecord;
29
+ }
30
+
31
+ const scope = (): Scope => {
32
+ minted += 1;
33
+ const id = `${process.pid.toString(36)}-${minted.toString(36)}`;
34
+ const endpoint = (path: string): string => `https://push.test/${id}/${path}`;
35
+ return {
36
+ ana: `ana-${id}`,
37
+ ben: `ben-${id}`,
38
+ endpoint,
39
+ record: (path, actorId, overrides = {}) => ({
40
+ endpoint: endpoint(path),
41
+ keys: { p256dh: `p-${path}`, auth: `a-${path}` },
42
+ locale: 'en',
43
+ timeZone: 'Europe/Berlin',
44
+ actorId,
45
+ createdAt: AT,
46
+ expirationTime: null,
47
+ ...overrides,
48
+ }),
49
+ };
50
+ };
51
+
52
+ export const PUSH_SUBSCRIPTION_STORE_CHECKS: readonly PushSubscriptionStoreCheck[] = [
53
+ {
54
+ name: 'one row per endpoint: a re-subscribe hands the device over with its new keys, first createdAt kept',
55
+ async run(store) {
56
+ const s = scope();
57
+ await store.save(s.record('b', s.ana));
58
+ await store.save(s.record('a', s.ana));
59
+ const handed = { locale: 'de', keys: { p256dh: 'p-new', auth: 'a-new' } };
60
+ await store.save(s.record('b', s.ben, { ...handed, createdAt: AT + 5 }));
61
+ expect((await store.listFor(s.ana)).map((row) => row.endpoint)).toEqual([s.endpoint('a')]);
62
+ expect(await store.listFor(s.ben)).toEqual([s.record('b', s.ben, handed)]);
63
+ },
64
+ },
65
+ {
66
+ name: 'one order, the endpoint by code point',
67
+ async run(store) {
68
+ const s = scope();
69
+ for (const path of ['b', 'B', 'a', 'é']) await store.save(s.record(path, s.ana));
70
+ const listed = (await store.listFor(s.ana)).map((row) => row.endpoint.slice(-1));
71
+ expect(listed).toEqual(['B', 'a', 'b', 'é']);
72
+ },
73
+ },
74
+ {
75
+ name: 'an expiration time round-trips as epoch milliseconds',
76
+ async run(store) {
77
+ const s = scope();
78
+ await store.save(s.record('a', s.ana, { expirationTime: AT + 86_400_000 }));
79
+ expect(await store.listFor(s.ana)).toEqual([
80
+ s.record('a', s.ana, { expirationTime: AT + 86_400_000 }),
81
+ ]);
82
+ },
83
+ },
84
+ {
85
+ // `actorId` is `string`, so only untyped code gets here — and the memory store used to accept
86
+ // what the Postgres column refuses. One refusal, one code, nothing written.
87
+ name: 'a subscription with no actor is refused with X_PWA_PUSH_SUBSCRIPTION_INVALID, nothing stored',
88
+ async run(store) {
89
+ const s = scope();
90
+ for (const actorId of [null, '']) {
91
+ const anonymous = s.record('a', actorId as unknown as string);
92
+ const code = await store.save(anonymous).then(
93
+ () => 'stored',
94
+ (error: unknown) => (isUltimateError(error) ? error.code : 'not an UltimateError'),
95
+ );
96
+ expect(code).toBe('X_PWA_PUSH_SUBSCRIPTION_INVALID');
97
+ }
98
+ expect(await store.remove(s.endpoint('a'))).toBe(false);
99
+ },
100
+ },
101
+ {
102
+ name: 'an owner-scoped remove leaves another actor’s device; an unscoped one is the 410',
103
+ async run(store) {
104
+ const s = scope();
105
+ await store.save(s.record('a', s.ana));
106
+ expect(await store.remove(s.endpoint('a'), s.ben)).toBe(false);
107
+ expect(await store.listFor(s.ana)).toHaveLength(1);
108
+ expect(await store.remove(s.endpoint('a'))).toBe(true);
109
+ expect(await store.remove(s.endpoint('a'))).toBe(false);
110
+ expect(await store.listFor(s.ana)).toEqual([]);
111
+ },
112
+ },
113
+ ];
114
+
115
+ export const pushSubscriptionStoreConformance: SharedExamples<
116
+ PushSubscriptionStore | Promise<PushSubscriptionStore>
117
+ > = sharedExamples('a push subscription store', (subject) => {
118
+ for (const check of PUSH_SUBSCRIPTION_STORE_CHECKS) {
119
+ test(check.name, async () => {
120
+ await check.run(await subject());
121
+ });
122
+ }
123
+ });
package/src/quiet-logs.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  // `info` for the one moment core loads, and what the author named decides what is PRINTED.
13
13
  //
14
14
  // A test that asserts on log output hands `structuredLogger({ level, writer })` its own writer, or
15
- // installs its own `setLogSink` and restores the previous one. Never `process.stdout`.
15
+ // installs its own with `installLogSink` and calls the release it returns. Never `process.stdout`.
16
16
 
17
17
  import type { LogLevel } from '@ultimat3/core';
18
18
 
@@ -42,15 +42,15 @@ const routing = logRouting(named);
42
42
  // import and the author's value goes back after it: a child this process spawns inherits what
43
43
  // was named, never the pin. A dynamic import, because a static one is hoisted above this line.
44
44
  if (routing.lines === 'filtered') Bun.env['LOG_LEVEL'] = 'info';
45
- const { setLogSink } = await import('@ultimat3/core');
45
+ const { installLogSink } = await import('@ultimat3/core');
46
46
 
47
47
  if (routing.lines === 'dropped') {
48
- setLogSink(() => undefined);
48
+ installLogSink(() => undefined);
49
49
  } else if (routing.lines === 'filtered') {
50
50
  Bun.env['LOG_LEVEL'] = routing.from;
51
51
  const shown = new Set<LogLevel>(ABOVE_INFO.slice(ABOVE_INFO.indexOf(routing.from)));
52
52
  // Core's own split: `error` and above to stderr, the rest to stdout.
53
- setLogSink((line, level) => {
53
+ installLogSink((line, level) => {
54
54
  if (shown.has(level)) (level === 'warn' ? process.stdout : process.stderr).write(`${line}\n`);
55
55
  });
56
56
  }