@ultimat3/testing 30.9.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 (148) 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 +30 -51
  56. package/src/exercise.ts +12 -6
  57. package/src/factories.ts +192 -179
  58. package/src/factory-api.ts +131 -0
  59. package/src/factory-associations.ts +67 -0
  60. package/src/factory-errors.ts +38 -0
  61. package/src/factory-lint.ts +92 -0
  62. package/src/factory-persist.ts +74 -16
  63. package/src/factory-pipeline.ts +191 -0
  64. package/src/factory-registry.ts +2 -1
  65. package/src/factory-types.ts +131 -0
  66. package/src/failure-store-conformance.ts +137 -0
  67. package/src/fixture-jobs.ts +27 -11
  68. package/src/fixture-mail.ts +7 -7
  69. package/src/fixture-seed.ts +111 -0
  70. package/src/fixture-statements.ts +68 -52
  71. package/src/framework-fixtures.ts +1 -1
  72. package/src/idempotency-store-conformance.ts +186 -0
  73. package/src/idempotency-store-replay-conformance.ts +140 -0
  74. package/src/idempotency-store-tx-conformance.ts +132 -0
  75. package/src/idempotency-store-world-conformance.ts +82 -0
  76. package/src/identity-provider-conformance.ts +144 -0
  77. package/src/image-transform-conformance.ts +89 -0
  78. package/src/index.ts +68 -157
  79. package/src/isr-store-conformance.ts +113 -0
  80. package/src/job-sim-effects.ts +19 -31
  81. package/src/job-sim-world.ts +6 -15
  82. package/src/lease-store-conformance.ts +195 -0
  83. package/src/mail-driver-conformance.ts +108 -0
  84. package/src/matcher-doubles.ts +104 -0
  85. package/src/matcher-stub.ts +78 -0
  86. package/src/matcher-surface.ts +21 -0
  87. package/src/matchers.ts +19 -1
  88. package/src/mcp-confirmation-store-conformance.ts +262 -0
  89. package/src/meter-store-conformance.ts +135 -0
  90. package/src/notify-digest-conformance.ts +133 -0
  91. package/src/notify-inbox-conformance.ts +130 -0
  92. package/src/notify-ledger-conformance.ts +134 -0
  93. package/src/notify-preference-conformance.ts +49 -0
  94. package/src/notify-stores-conformance.ts +73 -0
  95. package/src/outbox-store-conformance-claims.ts +112 -0
  96. package/src/outbox-store-conformance-subject.ts +65 -0
  97. package/src/outbox-store-conformance.ts +71 -0
  98. package/src/per-test-reset.ts +55 -20
  99. package/src/preload.ts +4 -2
  100. package/src/purge-conformance.ts +79 -0
  101. package/src/push-device-conformance.ts +124 -0
  102. package/src/push-subscription-conformance.ts +123 -0
  103. package/src/quiet-logs.ts +4 -4
  104. package/src/rate-limit-store-conformance.ts +178 -0
  105. package/src/registry-leak-error.ts +8 -1
  106. package/src/scrape-driver-conformance-frame-checks.ts +97 -0
  107. package/src/scrape-driver-conformance-page-checks.ts +114 -0
  108. package/src/scrape-driver-conformance-site.ts +84 -0
  109. package/src/scrape-driver-conformance.ts +34 -0
  110. package/src/search-index-conformance-list.ts +76 -0
  111. package/src/search-index-conformance-support.ts +69 -0
  112. package/src/search-index-conformance-versions.ts +66 -0
  113. package/src/search-index-conformance.ts +126 -0
  114. package/src/secret-source-conformance.ts +91 -0
  115. package/src/seed-factories.ts +57 -0
  116. package/src/seed-writer.ts +8 -19
  117. package/src/semantic-cache-factory-conformance.ts +86 -0
  118. package/src/sms-transport-conformance.ts +102 -0
  119. package/src/step-store-conformance.ts +171 -0
  120. package/src/storage-conformance-read-checks.ts +132 -0
  121. package/src/storage-conformance-shape.ts +121 -0
  122. package/src/storage-conformance-stream-checks.ts +226 -0
  123. package/src/storage-conformance.ts +34 -0
  124. package/src/stub-action.ts +24 -0
  125. package/src/stub-errors.ts +86 -0
  126. package/src/stub-job.ts +30 -0
  127. package/src/stub-query.ts +25 -0
  128. package/src/stub-script.ts +76 -0
  129. package/src/stub-stack.ts +29 -0
  130. package/src/stub.ts +73 -0
  131. package/src/swap-adapter.ts +135 -0
  132. package/src/test-scope.ts +96 -0
  133. package/src/test-types.ts +1 -1
  134. package/src/totp-replay-guard-conformance.ts +76 -0
  135. package/src/transport-conformance.ts +179 -0
  136. package/src/upload-scanner-conformance.ts +112 -0
  137. package/src/vector-store-conformance-checks.ts +174 -0
  138. package/src/vector-store-conformance.ts +21 -0
  139. package/src/cdp-connection.ts +0 -291
  140. package/src/cdp-errors.ts +0 -179
  141. package/src/cdp-launch-attempt.ts +0 -224
  142. package/src/cdp-launch-candidates.ts +0 -62
  143. package/src/cdp-launch-profile.ts +0 -106
  144. package/src/cdp-launch-reap.ts +0 -68
  145. package/src/cdp-launch-wire.ts +0 -171
  146. package/src/cdp-launch.ts +0 -175
  147. package/src/cdp-pipe.ts +0 -77
  148. package/src/cdp-wire-watch.ts +0 -113
@@ -0,0 +1,348 @@
1
+ // Entity conformance · single-row and filtered WRITES: an `undefined` patch value is absent, every
2
+ // key the table keeps is refused when repeated, a transition moves a row keyed by another column,
3
+ // and a column stores only what Postgres stores. Lifted from `entity/src/write-parity.test.ts`.
4
+
5
+ import { expect } from 'bun:test';
6
+ import {
7
+ arrayOf,
8
+ bigint,
9
+ decimal,
10
+ entity,
11
+ enumerated,
12
+ integer,
13
+ invariant,
14
+ json,
15
+ t,
16
+ text,
17
+ timestamp,
18
+ url,
19
+ uuid,
20
+ } from '@ultimat3/entity';
21
+ import { remember } from './entity-conformance-entities';
22
+ import { checkOver, idAt, outcome } from './entity-conformance-support';
23
+ import type { EntityDriverCheck } from './entity-driver-conformance';
24
+
25
+ const notes = remember(
26
+ entity('ec_w_notes', {
27
+ columns: {
28
+ id: uuid().primaryKey(),
29
+ title: text({ max: 40 }),
30
+ body: text({ max: 40 }).nullable(),
31
+ },
32
+ }),
33
+ );
34
+
35
+ /** Soft-deleting: a patch can move a row out of the default read. */
36
+ const stamped = remember(
37
+ entity('ec_w_stamped', {
38
+ columns: {
39
+ id: uuid().primaryKey(),
40
+ title: text({ max: 40 }),
41
+ deletedAt: timestamp().nullable(),
42
+ },
43
+ }),
44
+ );
45
+ const GONE_AT = new Date('2026-01-01T00:00:00.000Z');
46
+
47
+ const tags = remember(
48
+ entity('ec_w_tags', {
49
+ columns: { code: text({ max: 20 }).primaryKey(), slug: text({ max: 20 }) },
50
+ indexes: [{ on: ['slug'], unique: true }],
51
+ }),
52
+ );
53
+
54
+ const STATES = ['draft', 'live', 'archived'] as const;
55
+ const coupons = remember(
56
+ entity('ec_w_coupons', {
57
+ columns: {
58
+ code: text({ max: 20 }).primaryKey(),
59
+ status: enumerated(STATES)
60
+ .transitions({ draft: ['live'], live: ['archived'], archived: [] })
61
+ .default('draft'),
62
+ },
63
+ }),
64
+ );
65
+
66
+ const rates = remember(
67
+ entity('ec_w_rates', {
68
+ columns: {
69
+ id: uuid().primaryKey(),
70
+ rate: decimal({ precision: 8, scale: 2 }),
71
+ loose: decimal().nullable(),
72
+ big: bigint().nullable(),
73
+ },
74
+ }),
75
+ );
76
+
77
+ export const countries = remember(
78
+ entity('ec_w_countries', {
79
+ columns: {
80
+ id: uuid().primaryKey(),
81
+ iso: text({ max: 2 }),
82
+ name: text({ max: 40 }),
83
+ createdAt: timestamp().defaultNow(),
84
+ },
85
+ indexes: [{ on: ['iso'], unique: true }],
86
+ }),
87
+ );
88
+
89
+ const links = remember(
90
+ entity('ec_w_links', {
91
+ columns: { id: uuid().primaryKey(), label: text({ max: 3 }), hits: integer(), href: url() },
92
+ }),
93
+ );
94
+
95
+ /** A unique declared as an INVARIANT, a jsonb to key-test and an array whose elements may be NULL. */
96
+ const docs = remember(
97
+ entity('ec_w_docs', {
98
+ columns: {
99
+ id: uuid().primaryKey(),
100
+ slug: text({ max: 40 }),
101
+ data: json(t.record(t.string)).nullable(),
102
+ marks: arrayOf(text({ max: 20 }).nullable()).nullable(),
103
+ },
104
+ invariants: (c) => [invariant('ec_slug_unique', c.unique(['slug']))],
105
+ }),
106
+ );
107
+
108
+ const ID = idAt(1);
109
+ const UNIQUE = 'X_DB_UNIQUE_VIOLATION';
110
+ const REFUSED = { code: 'X_INVARIANT_VIOLATED' };
111
+
112
+ const undefinedIsAbsent: readonly EntityDriverCheck[] = [
113
+ checkOver({ notes }, 'update keeps a column the patch names as undefined', async (db) => {
114
+ await db.notes.insert({ id: ID, title: 'kept', body: 'kept body' });
115
+ await db.notes.update(ID, { title: 'moved', body: undefined });
116
+ expect(await db.notes.where({ id: ID }).one()).toEqual({
117
+ id: ID,
118
+ title: 'moved',
119
+ body: 'kept body',
120
+ });
121
+ }),
122
+ checkOver({ notes }, 'a patch naming only undefined values changes nothing', async (db) => {
123
+ await db.notes.insert({ id: ID, title: 'kept', body: 'kept body' });
124
+ await outcome(() => db.notes.update(ID, { body: undefined }));
125
+ expect(await db.notes.where({ id: ID }).one()).toEqual({
126
+ id: ID,
127
+ title: 'kept',
128
+ body: 'kept body',
129
+ });
130
+ }),
131
+ checkOver({ notes }, 'updateWhere keeps a column the patch names as undefined', async (db) => {
132
+ await db.notes.insert({ id: ID, title: 'kept', body: 'kept body' });
133
+ await db.notes.updateWhere({ id: ID }, { title: 'moved', body: undefined });
134
+ expect(await db.notes.where({ id: ID }).one()).toEqual({
135
+ id: ID,
136
+ title: 'moved',
137
+ body: 'kept body',
138
+ });
139
+ }),
140
+ ];
141
+
142
+ const keysAreKept: readonly EntityDriverCheck[] = [
143
+ checkOver({ tags }, 'a duplicate primary key is refused, not a silent replace', async (db) => {
144
+ await db.tags.insert({ code: 'a', slug: 'one' });
145
+ expect(await outcome(() => db.tags.insert({ code: 'a', slug: 'two' }))).toEqual({
146
+ code: UNIQUE,
147
+ });
148
+ expect((await db.tags.all()).map((row) => row.slug)).toEqual(['one']);
149
+ }),
150
+ checkOver({ tags }, 'a duplicate unique column is refused', async (db) => {
151
+ await db.tags.insert({ code: 'a', slug: 'one' });
152
+ expect(await outcome(() => db.tags.insert({ code: 'b', slug: 'one' }))).toEqual({
153
+ code: UNIQUE,
154
+ });
155
+ }),
156
+ checkOver({ tags }, 'insertAll with a duplicate inside the batch stores nothing', async (db) => {
157
+ const batch = [
158
+ { code: 'a', slug: 'one' },
159
+ { code: 'a', slug: 'two' },
160
+ ];
161
+ expect(await outcome(() => db.tags.insertAll(batch))).toEqual({ code: UNIQUE });
162
+ expect(await db.tags.all()).toHaveLength(0);
163
+ }),
164
+ checkOver({ tags }, 'a patch moving the primary key leaves one row, not two', async (db) => {
165
+ await db.tags.insert({ code: 'a', slug: 'one' });
166
+ await db.tags.update('a', { code: 'z' });
167
+ expect((await db.tags.all()).map((row) => row.code)).toEqual(['z']);
168
+ }),
169
+ checkOver({ stamped }, 'an update that soft-deletes answers the row it wrote', async (db) => {
170
+ await db.stamped.insert({ id: ID, title: 'gone', deletedAt: null });
171
+ const after = await db.stamped.update(ID, { deletedAt: GONE_AT });
172
+ expect([after.id, after.deletedAt]).toEqual([ID, GONE_AT]);
173
+ expect(await db.stamped.all()).toEqual([]);
174
+ }),
175
+ checkOver(
176
+ { stamped },
177
+ 'an empty patch on a soft-deleted row is X_NOT_FOUND, never the row',
178
+ async (db, { driver }) => {
179
+ await db.stamped.insert({ id: ID, title: 'gone', deletedAt: null });
180
+ await db.stamped.delete(ID);
181
+ const repo = driver.repo(stamped);
182
+ expect(await outcome(() => repo.update(ID, {}))).toEqual({ code: 'X_NOT_FOUND' });
183
+ expect(await outcome(() => repo.update(ID, { title: undefined }))).toEqual({
184
+ code: 'X_NOT_FOUND',
185
+ });
186
+ expect(await outcome(() => repo.update(ID, { title: 'back' }))).toEqual({
187
+ code: 'X_NOT_FOUND',
188
+ });
189
+ },
190
+ ),
191
+ checkOver(
192
+ { notes },
193
+ 'two results taking one primary key are refused; neither row moves',
194
+ async (db) => {
195
+ await db.notes.insert({ id: idAt(1), title: 'one', body: 'same' });
196
+ await db.notes.insert({ id: idAt(2), title: 'two', body: 'same' });
197
+ expect(await outcome(() => db.notes.updateWhere({ body: 'same' }, { id: idAt(3) }))).toEqual({
198
+ code: UNIQUE,
199
+ });
200
+ const kept = (await db.notes.all()).map((row) => [row.id, row.title, row.body]).sort();
201
+ expect(kept).toEqual([
202
+ [idAt(1), 'one', 'same'],
203
+ [idAt(2), 'two', 'same'],
204
+ ]);
205
+ },
206
+ ),
207
+ checkOver(
208
+ { countries },
209
+ 'two results taking one unique value are refused; neither moves',
210
+ async (db) => {
211
+ await db.countries.insert({ id: idAt(1), iso: 'AA', name: 'Same' });
212
+ await db.countries.insert({ id: idAt(2), iso: 'BB', name: 'Same' });
213
+ expect(
214
+ await outcome(() => db.countries.updateWhere({ name: 'Same' }, { iso: 'ZZ' })),
215
+ ).toEqual({
216
+ code: UNIQUE,
217
+ });
218
+ const kept = (await db.countries.all()).map((row) => [row.id, row.iso]).sort();
219
+ expect(kept).toEqual([
220
+ [idAt(1), 'AA'],
221
+ [idAt(2), 'BB'],
222
+ ]);
223
+ },
224
+ ),
225
+ checkOver({ docs }, 'a unique declared as an invariant refuses a second row', async (db) => {
226
+ await db.docs.insert({ id: idAt(1), slug: 'one' });
227
+ expect(await outcome(() => db.docs.insert({ id: idAt(2), slug: 'one' }))).toEqual({
228
+ code: UNIQUE,
229
+ });
230
+ }),
231
+ checkOver(
232
+ { docs },
233
+ "an invariant unique refuses a patch onto another row's value and a batch pair",
234
+ async (db) => {
235
+ await db.docs.insert({ id: idAt(1), slug: 'one' });
236
+ await db.docs.insert({ id: idAt(2), slug: 'two' });
237
+ expect(await outcome(() => db.docs.update(idAt(2), { slug: 'one' }))).toEqual({
238
+ code: UNIQUE,
239
+ });
240
+ const pair = [
241
+ { id: idAt(3), slug: 'three' },
242
+ { id: idAt(4), slug: 'three' },
243
+ ];
244
+ expect(await outcome(() => db.docs.insertAll(pair))).toEqual({ code: UNIQUE });
245
+ expect((await db.docs.all()).map((row) => row.slug).sort()).toEqual(['one', 'two']);
246
+ },
247
+ ),
248
+ ];
249
+
250
+ const transitions: readonly EntityDriverCheck[] = [
251
+ checkOver({ coupons }, 'a transition moves a row keyed by another column', async (db) => {
252
+ await db.coupons.insert({ code: 'SPRING', status: 'draft' });
253
+ const moved = await db.coupons.transition('status', 'SPRING', { from: 'draft', to: 'live' });
254
+ expect(moved).toEqual({ code: 'SPRING', status: 'live' });
255
+ }),
256
+ checkOver({ coupons }, 'a transition handed no id moves no row', async (db) => {
257
+ await db.coupons.insert({ code: 'A', status: 'draft' });
258
+ await db.coupons.insert({ code: 'B', status: 'draft' });
259
+ for (const missing of [undefined, null]) {
260
+ const move = { from: 'draft', to: 'live' } as const;
261
+ const refused = await outcome(() =>
262
+ db.coupons.transition('status', missing as unknown as string, move),
263
+ );
264
+ expect(refused).toEqual({ code: 'X_NOT_FOUND' });
265
+ }
266
+ expect((await db.coupons.all()).map((row) => row.status)).toEqual(['draft', 'draft']);
267
+ }),
268
+ ];
269
+
270
+ const decimals: readonly EntityDriverCheck[] = [
271
+ checkOver({ rates }, 'a decimal reads back as one canonical string at its scale', async (db) => {
272
+ const cases = [
273
+ ['007.5', '7.50'],
274
+ ['2.5', '2.50'],
275
+ ['-0', '0.00'],
276
+ ['-0.00', '0.00'],
277
+ ['12', '12.00'],
278
+ ];
279
+ for (const [index, [given, canonical]] of cases.entries()) {
280
+ const id = idAt(index + 1);
281
+ await db.rates.insert({ id, rate: given as string });
282
+ expect([given, (await db.rates.where({ id }).one())?.rate]).toEqual([given, canonical]);
283
+ }
284
+ }),
285
+ checkOver({ rates }, 'an unbounded decimal and a bigint read back canonical', async (db) => {
286
+ const loose = [
287
+ ['007.50', '7.50'],
288
+ ['-0', '0'],
289
+ ['-000.10', '-0.10'],
290
+ ];
291
+ const bigs = [
292
+ ['007', '7'],
293
+ ['-0', '0'],
294
+ ['-007', '-7'],
295
+ ];
296
+ for (const [index, [given, canonical]] of loose.entries()) {
297
+ const id = idAt(index + 1);
298
+ await db.rates.insert({ id, rate: '1', loose: given as string });
299
+ expect([given, (await db.rates.where({ id }).one())?.loose]).toEqual([given, canonical]);
300
+ }
301
+ for (const [index, [given, canonical]] of bigs.entries()) {
302
+ const id = idAt(index + 11);
303
+ await db.rates.insert({ id, rate: '1', big: given as string });
304
+ expect([given, (await db.rates.where({ id }).one())?.big]).toEqual([given, canonical]);
305
+ }
306
+ }),
307
+ checkOver({ rates }, 'a decimal past its scale or its precision stays refused', async (db) => {
308
+ expect(await outcome(() => db.rates.insert({ id: ID, rate: '1.234' }))).toEqual(REFUSED);
309
+ expect(await outcome(() => db.rates.insert({ id: ID, rate: '1234567.00' }))).toEqual(REFUSED);
310
+ expect(await db.rates.all()).toHaveLength(0);
311
+ }),
312
+ ];
313
+
314
+ const LINK = { id: ID, label: 'abc', hits: 1, href: 'https://a.b' };
315
+
316
+ const columnBounds: readonly EntityDriverCheck[] = [
317
+ checkOver({ links }, 'text past max and an integer outside int4 are refused', async (db) => {
318
+ for (const over of [{ label: 'abcdef' }, { hits: 3_000_000_000 }, { hits: -2_147_483_649 }]) {
319
+ expect([over, await outcome(() => db.links.insert({ ...LINK, ...over }))]).toEqual([
320
+ over,
321
+ REFUSED,
322
+ ]);
323
+ }
324
+ }),
325
+ checkOver({ links }, 'max counts code points, as char_length does', async (db) => {
326
+ await db.links.insert({ ...LINK, label: '👍👍👍' });
327
+ expect((await db.links.where({ id: ID }).one())?.label).toBe('👍👍👍');
328
+ }),
329
+ checkOver(
330
+ { links },
331
+ 'an upper-case url scheme is stored in its canonical lower case',
332
+ async (db) => {
333
+ await db.links.insert({ ...LINK, href: 'HTTPS://a.b/Path' });
334
+ expect((await db.links.where({ id: ID }).one())?.href).toBe('https://a.b/Path');
335
+ },
336
+ ),
337
+ ];
338
+
339
+ export const WRITE_CHECKS: readonly EntityDriverCheck[] = [
340
+ ...undefinedIsAbsent,
341
+ ...keysAreKept,
342
+ ...transitions,
343
+ ...decimals,
344
+ ...columnBounds,
345
+ ];
346
+
347
+ /** Predicates over `docs`, beside the writes because they share its table. */
348
+ export { docs as conformanceDocs };
@@ -0,0 +1,103 @@
1
+ // The entity `Driver` contract as shared examples: `behavesLike(entityDriverConformance, () =>
2
+ // subject)` runs every check against a driver of your own — `memoryDriver()`, `postgresDriver()`, a
3
+ // `defineDriver({ … })` store. Behaviour through the typed handle only, never SQL text: what a
4
+ // caller of `db.<table>` is promised, whichever driver answers.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import { isUltimateError } from '@ultimat3/core';
8
+ import type { Driver, EntityCore } from '@ultimat3/entity';
9
+ import { getEntity, registerEntity } from '@ultimat3/entity';
10
+ import type { DriverCapability } from '@ultimat3/entity/adapter';
11
+ import { ENTITY_DRIVER_CHECKS } from './entity-conformance-checks';
12
+ import { CONFORMANCE_ENTRIES, probe, probes } from './entity-conformance-entities';
13
+ import type { SharedExamples } from './shared-examples';
14
+ import { sharedExamples } from './shared-examples';
15
+
16
+ /** What a driver under test hands the suite. Called once per check. */
17
+ export interface EntityDriverSubject {
18
+ /**
19
+ * A driver over EMPTY tables for `entities`: a SQL store drops and re-creates them from the
20
+ * entities' own migration (`generateMigration`), a memory store builds a fresh driver.
21
+ */
22
+ open(entities: readonly EntityCore[]): Driver | Promise<Driver>;
23
+ /** What the driver declares beyond the five required methods — `DRIVER_CAPABILITIES` for all. */
24
+ readonly capabilities: readonly DriverCapability[];
25
+ /** Whether a reference to a row that does not exist is refused (`X_DB_FOREIGN_KEY_VIOLATION`). */
26
+ readonly foreignKeys: boolean;
27
+ }
28
+
29
+ /** What one check sees: the opened driver, and the subject's declared traits. */
30
+ export interface EntityDriverRun {
31
+ readonly driver: Driver;
32
+ readonly foreignKeys: boolean;
33
+ }
34
+
35
+ export interface EntityDriverCheck {
36
+ readonly name: string;
37
+ /** The tables the check reads and writes; `open` creates exactly these. */
38
+ readonly entities: readonly EntityCore[];
39
+ /** Capabilities the check exercises. Undeclared by the subject: the refusal is the check. */
40
+ readonly needs?: readonly DriverCapability[];
41
+ run(run: EntityDriverRun): Promise<void>;
42
+ }
43
+
44
+ const refusalOf = async (work: () => unknown): Promise<unknown> => {
45
+ try {
46
+ await work();
47
+ } catch (error) {
48
+ return isUltimateError(error) ? [error.code, error.meta?.['capability']] : String(error);
49
+ }
50
+ return 'resolved';
51
+ };
52
+
53
+ /**
54
+ * A capability the subject does not declare is not skipped — it is asserted REFUSED, by name, the
55
+ * way `defineDriver` promises (`X_DRIVER_UNSUPPORTED`, or the typed handle's `X_LOCK_UNSUPPORTED`).
56
+ * So every check is a claim either way, and a driver that half-implements one is found out.
57
+ */
58
+ const assertRefused = async (driver: Driver, capability: DriverCapability): Promise<void> => {
59
+ const answered = await refusalOf(() => probes(driver)[capability]());
60
+ const expected =
61
+ capability === 'lock'
62
+ ? ['X_LOCK_UNSUPPORTED', undefined]
63
+ : ['X_DRIVER_UNSUPPORTED', capability];
64
+ expect({ capability, answered }).toEqual({ capability, answered: expected });
65
+ };
66
+
67
+ /** Put back fixture entities a neighbouring file's `clearRegistry()` took: relations read it. */
68
+ const restoreFixtures = (): void => {
69
+ for (const entry of CONFORMANCE_ENTRIES) {
70
+ if (getEntity(entry.name) === undefined) registerEntity(entry);
71
+ }
72
+ };
73
+
74
+ export const runEntityDriverCheck = async (
75
+ check: EntityDriverCheck,
76
+ subject: EntityDriverSubject,
77
+ ): Promise<void> => {
78
+ restoreFixtures();
79
+ const missing = (check.needs ?? []).filter((need) => !subject.capabilities.includes(need));
80
+ const driver = await subject.open(missing.length > 0 ? [probe] : check.entities);
81
+ if (missing.length > 0) {
82
+ for (const capability of missing) await assertRefused(driver, capability);
83
+ return;
84
+ }
85
+ await check.run({ driver, foreignKeys: subject.foreignKeys });
86
+ };
87
+
88
+ /** Generous: a SQL subject re-creates its tables per check, and one check writes 40,000 rows. */
89
+ const CHECK_TIMEOUT_MS = 60_000;
90
+
91
+ export const entityDriverConformance: SharedExamples<
92
+ EntityDriverSubject | Promise<EntityDriverSubject>
93
+ > = sharedExamples('an entity driver', (subject) => {
94
+ for (const check of ENTITY_DRIVER_CHECKS) {
95
+ test(
96
+ check.name,
97
+ async () => {
98
+ await runEntityDriverCheck(check, await subject());
99
+ },
100
+ CHECK_TIMEOUT_MS,
101
+ );
102
+ }
103
+ });
@@ -0,0 +1,198 @@
1
+ // The `ErrorGroupsStore` contract of `@ultimat3/admin` as shared examples, for a store of your own:
2
+ // `behavesLike(errorGroupsStoreConformance, () => store)`. Structural, because `admin` is this
3
+ // package's tier and a sideways import is refused: an `ErrorGroupsStore` is assignable to the
4
+ // `ErrorGroupsStoreLike` below. Each check writes under its own fingerprint prefix, so a shared table is fine.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { SharedExamples } from './shared-examples';
8
+ import { sharedExamples } from './shared-examples';
9
+
10
+ type Maybe<T> = T | Promise<T>;
11
+
12
+ export type ErrorGroupStatusLike = 'open' | 'resolved' | 'ignored';
13
+
14
+ /** `@ultimat3/admin`'s `ErrorGroupOccurrence`, structurally. */
15
+ export interface ErrorGroupOccurrenceLike {
16
+ readonly fingerprint: string;
17
+ readonly code: string;
18
+ readonly source: string;
19
+ readonly operation: string | null;
20
+ readonly message: string;
21
+ readonly at: Date;
22
+ readonly count: number;
23
+ readonly sample: {
24
+ readonly at: string;
25
+ readonly severity: string;
26
+ readonly title: string;
27
+ readonly cause: string;
28
+ readonly fix: string;
29
+ readonly release: string | null;
30
+ readonly environment: string;
31
+ readonly requestId: string | null;
32
+ readonly traceId: string | null;
33
+ readonly meta: Readonly<Record<string, unknown>> | null;
34
+ readonly stack: string | null;
35
+ };
36
+ }
37
+
38
+ export interface ErrorGroupLike {
39
+ readonly fingerprint: string;
40
+ readonly code: string;
41
+ readonly status: ErrorGroupStatusLike;
42
+ readonly firstSeen: string;
43
+ readonly lastSeen: string;
44
+ readonly count: number;
45
+ readonly sample: ErrorGroupOccurrenceLike['sample'];
46
+ }
47
+
48
+ /** The five members of `@ultimat3/admin`'s `ErrorGroupsStore`, structurally. */
49
+ export interface ErrorGroupsStoreLike {
50
+ record(occurrence: ErrorGroupOccurrenceLike): Promise<{ readonly isNew: boolean }>;
51
+ list(query?: {
52
+ readonly status?: ErrorGroupStatusLike | undefined;
53
+ readonly limit?: number | undefined;
54
+ }): Promise<readonly ErrorGroupLike[]>;
55
+ get(fingerprint: string): Promise<ErrorGroupLike | undefined>;
56
+ setStatus(fingerprint: string, status: ErrorGroupStatusLike): Promise<ErrorGroupLike | undefined>;
57
+ purge(beforeMs: number): Promise<number>;
58
+ }
59
+
60
+ export interface ErrorGroupsStoreCheck {
61
+ readonly name: string;
62
+ run(store: ErrorGroupsStoreLike, prefix: string): Promise<void>;
63
+ }
64
+
65
+ const occurrence = (
66
+ over: Partial<ErrorGroupOccurrenceLike> & { readonly fingerprint: string },
67
+ ): ErrorGroupOccurrenceLike => ({
68
+ code: 'X_INTERNAL',
69
+ source: 'http',
70
+ operation: 'POST /orders',
71
+ message: 'order o_1 is stuck',
72
+ at: new Date('2026-11-06T10:00:00.000Z'),
73
+ count: 1,
74
+ sample: {
75
+ at: '2026-11-06T10:00:00.000Z',
76
+ severity: 'error',
77
+ title: 'an order is stuck',
78
+ cause: 'order o_1 is stuck',
79
+ fix: 'x jobs show orders --json',
80
+ release: 'build-1',
81
+ environment: 'production',
82
+ requestId: 'req-1',
83
+ traceId: null,
84
+ meta: { orderId: 'o_1' },
85
+ stack: null,
86
+ },
87
+ ...over,
88
+ });
89
+
90
+ const RACERS = 5;
91
+
92
+ export const ERROR_GROUPS_STORE_CHECKS: readonly ErrorGroupsStoreCheck[] = [
93
+ {
94
+ name: 'the first occurrence is new, the second is not, and the count adds',
95
+ async run(store, prefix) {
96
+ const fingerprint = `${prefix}a`;
97
+ expect((await store.record(occurrence({ fingerprint }))).isNew).toBe(true);
98
+ const later = new Date('2026-11-06T10:05:00.000Z');
99
+ const second = await store.record(occurrence({ fingerprint, at: later, count: 3 }));
100
+ expect(second.isNew).toBe(false);
101
+ const group = await store.get(fingerprint);
102
+ expect(group).toMatchObject({
103
+ count: 4,
104
+ firstSeen: '2026-11-06T10:00:00.000Z',
105
+ lastSeen: later.toISOString(),
106
+ status: 'open',
107
+ });
108
+ expect(group?.sample.meta).toEqual({ orderId: 'o_1' });
109
+ },
110
+ },
111
+ {
112
+ name: `${RACERS} racing records of one new group: one isNew, every count kept`,
113
+ async run(store, prefix) {
114
+ const fingerprint = `${prefix}race`;
115
+ const answers = await Promise.all(
116
+ Array.from({ length: RACERS }, () => store.record(occurrence({ fingerprint }))),
117
+ );
118
+ expect(answers.filter((answer) => answer.isNew)).toHaveLength(1);
119
+ expect((await store.get(fingerprint))?.count).toBe(RACERS);
120
+ },
121
+ },
122
+ {
123
+ name: 'a late, older occurrence never moves last seen backwards',
124
+ async run(store, prefix) {
125
+ const fingerprint = `${prefix}b`;
126
+ await store.record(occurrence({ fingerprint, at: new Date('2026-11-06T11:00:00.000Z') }));
127
+ await store.record(occurrence({ fingerprint, at: new Date('2026-11-06T09:00:00.000Z') }));
128
+ expect((await store.get(fingerprint))?.lastSeen).toBe('2026-11-06T11:00:00.000Z');
129
+ },
130
+ },
131
+ {
132
+ name: 'resolved re-opens on the next occurrence; ignored stays ignored',
133
+ async run(store, prefix) {
134
+ await store.record(occurrence({ fingerprint: `${prefix}r` }));
135
+ await store.record(occurrence({ fingerprint: `${prefix}i` }));
136
+ expect((await store.setStatus(`${prefix}r`, 'resolved'))?.status).toBe('resolved');
137
+ await store.setStatus(`${prefix}i`, 'ignored');
138
+ await store.record(occurrence({ fingerprint: `${prefix}r` }));
139
+ await store.record(occurrence({ fingerprint: `${prefix}i` }));
140
+ expect((await store.get(`${prefix}r`))?.status).toBe('open');
141
+ expect((await store.get(`${prefix}i`))?.status).toBe('ignored');
142
+ expect(await store.setStatus(`${prefix}missing`, 'resolved')).toBeUndefined();
143
+ },
144
+ },
145
+ {
146
+ name: 'list is newest-seen first, filtered by status, bounded by limit',
147
+ async run(store, prefix) {
148
+ for (const [index, hour] of ['01', '03', '02'].entries()) {
149
+ await store.record(
150
+ occurrence({
151
+ fingerprint: `${prefix}${index}`,
152
+ at: new Date(`2030-01-01T${hour}:00:00.000Z`),
153
+ }),
154
+ );
155
+ }
156
+ await store.setStatus(`${prefix}2`, 'ignored');
157
+ const mine = (await store.list({ limit: 500 })).filter((group) =>
158
+ group.fingerprint.startsWith(prefix),
159
+ );
160
+ expect(mine.map((group) => group.fingerprint)).toEqual([
161
+ `${prefix}1`,
162
+ `${prefix}2`,
163
+ `${prefix}0`,
164
+ ]);
165
+ const ignored = (await store.list({ status: 'ignored' })).filter((group) =>
166
+ group.fingerprint.startsWith(prefix),
167
+ );
168
+ expect(ignored.map((group) => group.fingerprint)).toEqual([`${prefix}2`]);
169
+ expect(await store.list({ limit: 1 })).toHaveLength(1);
170
+ await expect(store.list({ limit: Number.NaN })).rejects.toThrow('limit');
171
+ },
172
+ },
173
+ {
174
+ name: 'purge removes exactly the groups last seen before the bound',
175
+ async run(store, prefix) {
176
+ await store.record(occurrence({ fingerprint: `${prefix}old`, at: new Date('2000-01-01') }));
177
+ await store.record(occurrence({ fingerprint: `${prefix}new`, at: new Date('2099-01-01') }));
178
+ expect(await store.purge(Date.parse('2000-06-01'))).toBeGreaterThanOrEqual(1);
179
+ expect(await store.get(`${prefix}old`)).toBeUndefined();
180
+ expect(await store.get(`${prefix}new`)).toBeDefined();
181
+ },
182
+ },
183
+ ];
184
+
185
+ let minted = 0;
186
+ const prefixOf = (): string => {
187
+ minted += 1;
188
+ return `conformance-${process.pid.toString(36)}-${minted.toString(36)}-`;
189
+ };
190
+
191
+ export const errorGroupsStoreConformance: SharedExamples<Maybe<ErrorGroupsStoreLike>> =
192
+ sharedExamples('an error-groups store', (subject) => {
193
+ for (const check of ERROR_GROUPS_STORE_CHECKS) {
194
+ test(check.name, async () => {
195
+ await check.run(await subject(), prefixOf());
196
+ });
197
+ }
198
+ });