@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,91 @@
1
+ // The `secretSource` port's contract as shared examples: `behavesLike(secretSourceConformance, ()
2
+ // => subject)`. A source cannot be handed a key through the port, so the subject arranges one — the
3
+ // env var, a key file, a KMS fake's own table — and the suite asks for it back through `masterKey`
4
+ // only.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { SecretSource, SecretSourceContext } from '@ultimat3/core/adapter';
8
+ import type { SharedExamples } from './shared-examples';
9
+ import { sharedExamples } from './shared-examples';
10
+
11
+ type Maybe<T> = T | Promise<T>;
12
+
13
+ /** A source plus the two worlds it is asked in: one holding `hex`, one holding nothing. */
14
+ export interface SecretSourceSubject {
15
+ readonly source: SecretSource;
16
+ /** A context this source answers `hex` for. A fresh one per call — two calls, two places. */
17
+ holding(hex: string): Maybe<SecretSourceContext>;
18
+ /** A context this source has no key for. */
19
+ empty(): Maybe<SecretSourceContext>;
20
+ }
21
+
22
+ export interface SecretSourceCheck {
23
+ readonly name: string;
24
+ run(subject: SecretSourceSubject): Promise<void>;
25
+ }
26
+
27
+ let minted = 0;
28
+ /** 64 hex chars, distinct per call: the AES-256 key shape `x secrets init` writes. */
29
+ const keyHex = (): string => {
30
+ minted += 1;
31
+ return `${process.pid.toString(16)}${minted.toString(16)}`.padStart(64, 'a');
32
+ };
33
+
34
+ /** The answer, or the failure itself — "absent" must never be a throw or a rejection. */
35
+ const asked = async (source: SecretSource, context: SecretSourceContext): Promise<unknown> => {
36
+ try {
37
+ return await source.masterKey(context);
38
+ } catch (error) {
39
+ return { threw: error };
40
+ }
41
+ };
42
+
43
+ export const SECRET_SOURCE_CHECKS: readonly SecretSourceCheck[] = [
44
+ {
45
+ name: 'a place holding no key answers undefined — never a throw, never a rejection',
46
+ async run({ source, empty }) {
47
+ expect(await asked(source, await empty())).toBeUndefined();
48
+ },
49
+ },
50
+ {
51
+ name: 'a place holding a key answers exactly that key, twice in a row',
52
+ async run({ source, holding }) {
53
+ const hex = keyHex();
54
+ const context = await holding(hex);
55
+ expect((await source.masterKey(context))?.hex).toBe(hex);
56
+ expect((await source.masterKey(context))?.hex).toBe(hex);
57
+ },
58
+ },
59
+ {
60
+ name: 'the answer names its source and where it was read — and the place never carries the key',
61
+ async run({ source, holding }) {
62
+ const hex = keyHex();
63
+ const ref = await source.masterKey(await holding(hex));
64
+ expect(source.name.length).toBeGreaterThan(0);
65
+ expect(ref?.source.length ?? 0).toBeGreaterThan(0);
66
+ expect(ref?.at.length ?? 0).toBeGreaterThan(0);
67
+ expect(ref?.at).not.toContain(hex);
68
+ expect(ref?.source).not.toContain(hex);
69
+ },
70
+ },
71
+ {
72
+ name: 'two places holding two keys answer each its own — nothing is kept across contexts',
73
+ async run({ source, holding }) {
74
+ const [first, second] = [keyHex(), keyHex()];
75
+ const [one, two] = [await holding(first), await holding(second)];
76
+ expect((await source.masterKey(one))?.hex).toBe(first);
77
+ expect((await source.masterKey(two))?.hex).toBe(second);
78
+ },
79
+ },
80
+ ];
81
+
82
+ export const secretSourceConformance: SharedExamples<SecretSourceSubject> = sharedExamples(
83
+ 'a secret source',
84
+ (subject) => {
85
+ for (const check of SECRET_SOURCE_CHECKS) {
86
+ test(check.name, async () => {
87
+ await check.run(subject());
88
+ });
89
+ }
90
+ },
91
+ );
@@ -0,0 +1,57 @@
1
+ // `factorySeed(name, body)`: a named seed whose rows come from factories — `defineSeed`'s own run
2
+ // (tier, dry run, metrics, `x db seed`), with every `create()` in the body written through the
3
+ // seed's idempotent insert. Every factory sequence restarts first, so a replay draws the same ids
4
+ // and writes nothing new. `@ultimat3/entity` loads on `run()`, never on import.
5
+
6
+ import type { Seed, SeedContext, SeedInit, SeedRun } from '@ultimat3/entity';
7
+ import { FactoryNotPersistedError } from './errors';
8
+ import { resetFactorySequences } from './factories';
9
+ import { isEntity, type Persister, swapPersister } from './factory-persist';
10
+
11
+ /**
12
+ * A `create()` inside a seed: the seed's `insert` — `on conflict do nothing` by primary key, counted
13
+ * in its metrics, rolled back by a dry run. It answers the row as WRITTEN (`$parse`d): a seed reads
14
+ * nothing back, so a replay's skipped row answers what this run would have written.
15
+ */
16
+ const seedPersister = (context: SeedContext): Persister => ({
17
+ async insert(entity, row) {
18
+ if (!isEntity(entity)) throw new FactoryNotPersistedError({ table: entity.$table });
19
+ const parsed = entity.$parse(row) as object;
20
+ await context.insert(entity, [parsed as Parameters<SeedContext['insert']>[1][number]]);
21
+ return parsed;
22
+ },
23
+ });
24
+
25
+ /**
26
+ * `export const demo = factorySeed('demo', async ({ id }) => { await posts.create({ comments: 2,
27
+ * org: await orgs.create({ id: id('org:acme') }) }) })` — then `x db seed demo`, or
28
+ * `demo.run({ driver })` from a test. Same name, same rows, every run.
29
+ */
30
+ export function factorySeed(
31
+ name: string,
32
+ build: (context: SeedContext) => Promise<void>,
33
+ init: SeedInit = {},
34
+ ): Seed {
35
+ const tier = init.tier ?? 'dev';
36
+ return {
37
+ name,
38
+ tier,
39
+ run: async (options = {}): Promise<SeedRun> => {
40
+ const { defineSeed } = await import('@ultimat3/entity');
41
+ const seed = defineSeed(
42
+ name,
43
+ async (context) => {
44
+ resetFactorySequences();
45
+ const previous = swapPersister(seedPersister(context));
46
+ try {
47
+ await build(context);
48
+ } finally {
49
+ swapPersister(previous);
50
+ }
51
+ },
52
+ { tier },
53
+ );
54
+ return seed.run(options);
55
+ },
56
+ };
57
+ }
@@ -6,6 +6,7 @@
6
6
  // `@ultimat3/entity` loads on the first write, never on import: this module is on the barrel, and
7
7
  // the barrel stays entity-free.
8
8
 
9
+ import { fingerprint } from '@ultimat3/core';
9
10
  import type { DbClient, SqlFragment } from '@ultimat3/db';
10
11
  import { identifier, join, sql } from '@ultimat3/db';
11
12
  import type { Driver, EntityCore, Repo } from '@ultimat3/entity';
@@ -14,25 +15,13 @@ import type { SeedRow, SeedUpdate, SeedWriter } from './seed-graph-plan';
14
15
 
15
16
  type SeedRepo = Repo<Record<string, unknown>>;
16
17
 
17
- /** Stable text for one row: keys sorted, an instant as ISO, bytes as hex — never insertion order. */
18
- const stable = (value: unknown): unknown => {
19
- if (value instanceof Date) return value.toISOString();
20
- if (value instanceof Uint8Array) {
21
- return Array.from(value, (byte) => byte.toString(16).padStart(2, '0')).join('');
22
- }
23
- if (typeof value === 'bigint') return value.toString();
24
- if (Array.isArray(value)) return value.map(stable);
25
- if (typeof value !== 'object' || value === null) return value;
26
- const record = value as Record<string, unknown>;
27
- return Object.fromEntries(
28
- Object.keys(record)
29
- .sort()
30
- .map((key) => [key, stable(record[key])]),
31
- );
32
- };
33
-
34
- const digestRow = (row: unknown): string =>
35
- new Bun.CryptoHasher('md5').update(JSON.stringify(stable(row))).digest('hex');
18
+ /**
19
+ * One row's digest: core's `fingerprint`, over `canonicalJson` — the framework's one INJECTIVE
20
+ * form: keys sorted, and a date, bytes and a bigint each tagged. A private copy rendered bytes as
21
+ * bare hex, one digest with the text holding that hex — a hash form must never fold two values
22
+ * onto one string, and a second hasher is where the next copy drifts.
23
+ */
24
+ export const digestRow = (row: unknown): string => fingerprint(row);
36
25
 
37
26
  /** The physical columns of an entity's primary key, in key order. */
38
27
  const keyColumns = (entity: EntityCore): readonly string[] => {
@@ -0,0 +1,86 @@
1
+ // The `semanticCache` port's contract as shared examples:
2
+ // `behavesLike(semanticCacheFactoryConformance, () => (scope) => yours(scope))`. The port is a
3
+ // FACTORY, one cache per scope, because two tenants asking near-identical questions of one shared
4
+ // cache is one tenant reading the other's answer — so scope isolation is the first check.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { SemanticCacheFactory } from '@ultimat3/ai/adapter';
8
+ import { uuidV7 } from '@ultimat3/core';
9
+ import type { SharedExamples } from './shared-examples';
10
+ import { sharedExamples } from './shared-examples';
11
+
12
+ export interface SemanticCacheFactoryCheck {
13
+ readonly name: string;
14
+ run(factory: SemanticCacheFactory): Promise<void>;
15
+ }
16
+
17
+ /** A fresh scope per check, so a durable store's rows from an earlier check never answer. */
18
+ const scope = (label: string): string => `conformance-${label}-${uuidV7()}`;
19
+
20
+ const NORTH = [1, 0, 0] as const;
21
+ const EAST = [0, 1, 0] as const;
22
+
23
+ export const SEMANTIC_CACHE_FACTORY_CHECKS: readonly SemanticCacheFactoryCheck[] = [
24
+ {
25
+ name: 'two scopes are two caches: what one remembers the other never answers',
26
+ async run(factory) {
27
+ const a = factory(scope('a'));
28
+ const b = factory(scope('b'));
29
+ await a.remember('k', NORTH, 'org-a answer');
30
+ expect(await b.lookup(NORTH, 0.9)).toBeUndefined();
31
+ expect((await a.lookup<string>(NORTH, 0.9))?.value).toBe('org-a answer');
32
+ },
33
+ },
34
+ {
35
+ name: 'a remembered embedding answers its own lookup, with its key and a similarity near 1',
36
+ async run(factory) {
37
+ const cache = factory(scope('hit'));
38
+ expect(cache.name.length).toBeGreaterThan(0);
39
+ await cache.remember('the-key', NORTH, { answer: 42 });
40
+ const hit = await cache.lookup<{ answer: number }>(NORTH, 0.9);
41
+ expect(hit?.key).toBe('the-key');
42
+ expect(hit?.value).toEqual({ answer: 42 });
43
+ expect(hit?.similarity).toBeGreaterThan(0.999);
44
+ },
45
+ },
46
+ {
47
+ name: 'below the threshold is a miss, never the nearest entry anyway',
48
+ async run(factory) {
49
+ const cache = factory(scope('miss'));
50
+ await cache.remember('north', NORTH, 'north');
51
+ expect(await cache.lookup(EAST, 0.9)).toBeUndefined();
52
+ },
53
+ },
54
+ {
55
+ name: 'an embedding that is not a number is not a match',
56
+ async run(factory) {
57
+ const cache = factory(scope('nan'));
58
+ await cache.remember('north', NORTH, 'north');
59
+ expect(await cache.lookup([1, Number.NaN, 0], 0.5)).toBeUndefined();
60
+ },
61
+ },
62
+ {
63
+ name: 'invalidateTags drops the tagged entries, names their keys, and keeps the rest',
64
+ async run(factory) {
65
+ const cache = factory(scope('tags'));
66
+ await cache.remember('tagged', NORTH, 'tagged', { tags: [{ entity: 'post', id: '1' }] });
67
+ await cache.remember('kept', EAST, 'kept', { tags: [{ entity: 'post', id: '2' }] });
68
+ expect(await cache.size()).toBe(2);
69
+ expect(await cache.invalidateTags([{ entity: 'post', id: '1' }])).toEqual(['tagged']);
70
+ expect(await cache.lookup(NORTH, 0.9)).toBeUndefined();
71
+ expect((await cache.lookup<string>(EAST, 0.9))?.value).toBe('kept');
72
+ expect(await cache.size()).toBe(1);
73
+ },
74
+ },
75
+ ];
76
+
77
+ export const semanticCacheFactoryConformance: SharedExamples<SemanticCacheFactory> = sharedExamples(
78
+ 'a semantic cache factory',
79
+ (subject) => {
80
+ for (const check of SEMANTIC_CACHE_FACTORY_CHECKS) {
81
+ test(check.name, async () => {
82
+ await check.run(subject());
83
+ });
84
+ }
85
+ },
86
+ );
@@ -0,0 +1,102 @@
1
+ // The `SmsTransport` contract of `@ultimat3/notify` as shared examples, for a provider adapter of
2
+ // your own (Twilio, Vonage, SNS): `behavesLike(smsTransportConformance, () => transport)`. Asked
3
+ // through `send` alone — what a transport answers about a message, never how its wire looks.
4
+
5
+ import { expect, test } from 'bun:test';
6
+ import type { SmsMessage, SmsTransport } from '@ultimat3/notify/adapter';
7
+ import type { SharedExamples } from './shared-examples';
8
+ import { sharedExamples } from './shared-examples';
9
+
10
+ export interface SmsTransportCheck {
11
+ readonly name: string;
12
+ run(transport: SmsTransport): Promise<void>;
13
+ }
14
+
15
+ const TO = '+4915112345678';
16
+ const CONCURRENT_SENDS = 8;
17
+
18
+ /** A rendered message, by hand: the port receives text already in the recipient's language. */
19
+ export const conformanceSms = (overrides: Partial<SmsMessage> = {}): SmsMessage => ({
20
+ to: TO,
21
+ body: 'Your code is 424242',
22
+ idempotencyKey: 'conformance-sms-1',
23
+ ...overrides,
24
+ });
25
+
26
+ const refusedCode = async (run: () => Promise<unknown>): Promise<unknown> => {
27
+ try {
28
+ await run();
29
+ } catch (error) {
30
+ return (error as { code?: unknown }).code;
31
+ }
32
+ return expect.unreachable('expected the transport to refuse');
33
+ };
34
+
35
+ export const SMS_TRANSPORT_CHECKS: readonly SmsTransportCheck[] = [
36
+ {
37
+ name: 'a send resolves a result naming this transport and the number it accepted',
38
+ async run(transport) {
39
+ expect(transport.name.length).toBeGreaterThan(0);
40
+ const result = await transport.send(conformanceSms());
41
+ expect([result.transport, result.to]).toEqual([transport.name, TO]);
42
+ expect(result.id.length).toBeGreaterThan(0);
43
+ },
44
+ },
45
+ {
46
+ // A caller matching a retry to its first send reads this key back.
47
+ name: 'the idempotency key is answered back unchanged, the same on every attempt',
48
+ async run(transport) {
49
+ const message = conformanceSms();
50
+ const first = await transport.send(message);
51
+ const second = await transport.send(message);
52
+ expect([first.idempotencyKey, second.idempotencyKey]).toEqual([
53
+ message.idempotencyKey,
54
+ message.idempotencyKey,
55
+ ]);
56
+ },
57
+ },
58
+ {
59
+ // The id lands in logs and the delivery ledger; the number and the body are a person's.
60
+ name: 'the result id carries neither the number nor the body',
61
+ async run(transport) {
62
+ const message = conformanceSms();
63
+ const result = await transport.send(message);
64
+ for (const leak of [TO, TO.slice(1), message.body]) expect(result.id).not.toContain(leak);
65
+ },
66
+ },
67
+ {
68
+ // A local spelling is a number the provider guesses the country of: a message to a stranger.
69
+ name: 'a number that is not E.164 is refused with X_NOTIFY_SMS_NUMBER_INVALID',
70
+ async run(transport) {
71
+ for (const to of ['015112345678', '+49 151 12345678', '']) {
72
+ expect(await refusedCode(() => transport.send(conformanceSms({ to })))).toBe(
73
+ 'X_NOTIFY_SMS_NUMBER_INVALID',
74
+ );
75
+ }
76
+ },
77
+ },
78
+ {
79
+ name: `${CONCURRENT_SENDS} concurrent sends each answer for their own message`,
80
+ async run(transport) {
81
+ const messages = Array.from({ length: CONCURRENT_SENDS }, (_, index) =>
82
+ conformanceSms({
83
+ to: `+1415555${String(index).padStart(4, '0')}`,
84
+ idempotencyKey: `conformance-sms-${String(index)}`,
85
+ }),
86
+ );
87
+ const results = await Promise.all(messages.map((message) => transport.send(message)));
88
+ expect(results.map((result) => [result.to, result.idempotencyKey])).toEqual(
89
+ messages.map((message) => [message.to, message.idempotencyKey]),
90
+ );
91
+ },
92
+ },
93
+ ];
94
+
95
+ export const smsTransportConformance: SharedExamples<SmsTransport | Promise<SmsTransport>> =
96
+ sharedExamples('an SMS transport', (subject) => {
97
+ for (const check of SMS_TRANSPORT_CHECKS) {
98
+ test(check.name, async () => {
99
+ await check.run(await subject());
100
+ });
101
+ }
102
+ });
@@ -0,0 +1,171 @@
1
+ // The `StepStore` contract of `@ultimat3/jobs` as shared examples: `behavesLike(stepStoreConformance,
2
+ // () => driver)`. The subject is the store AND the queue it is fenced on — a write made under a
3
+ // claim lands only while that claim holds the row, and only a queue row can say so. Any `JobDriver`
4
+ // is one; a store of your own goes in as `memoryJobDriver({ steps: yours })` or inside your driver.
5
+
6
+ import { expect, test } from 'bun:test';
7
+ import type { JobDriver, StepFence, StepRecord } from '@ultimat3/jobs';
8
+ import type { SharedExamples } from './shared-examples';
9
+ import { sharedExamples } from './shared-examples';
10
+
11
+ /** The step store under test and the slice of its queue a fence needs. */
12
+ export type StepStoreSubject = Pick<JobDriver, 'steps' | 'enqueue' | 'claim' | 'ack'>;
13
+
14
+ export interface StepStoreCheck {
15
+ readonly name: string;
16
+ run(subject: StepStoreSubject): Promise<void>;
17
+ }
18
+
19
+ const AT = Date.UTC(2026, 10, 9, 9, 0, 0);
20
+
21
+ let minted = 0;
22
+ const tag = (): string => {
23
+ minted += 1;
24
+ return `${process.pid.toString(36)}-${minted.toString(36)}`;
25
+ };
26
+
27
+ const step = (runId: string, name: string, extra: Partial<StepRecord> = {}): StepRecord => ({
28
+ runId,
29
+ name,
30
+ status: 'completed',
31
+ output: { name },
32
+ startedAt: AT,
33
+ completedAt: AT + 5,
34
+ attempts: 1,
35
+ ...extra,
36
+ });
37
+
38
+ /** A claimed row of a queue of this check's own, and the fence its claim writes under. */
39
+ async function claimed(subject: StepStoreSubject): Promise<{ runId: string; fence: StepFence }> {
40
+ const at = tag();
41
+ const [queue, job] = [`conformance-steps-${at}`, `conformance.steps-${at}`];
42
+ await subject.enqueue({ name: job, queue, input: {}, idempotencyKey: at, maxAttempts: 3 });
43
+ const [row] = await subject.claim({
44
+ queues: [queue],
45
+ limit: 1,
46
+ visibilityTimeoutMs: 30_000,
47
+ workerId: 'conformance-worker',
48
+ });
49
+ if (row === undefined) return expect.unreachable('a row enqueued on its own queue is claimable');
50
+ const fence = { job, jobId: row.id, workerId: row.claimedBy, claim: row.claim };
51
+ return { runId: row.runId, fence };
52
+ }
53
+
54
+ const leaseLost = { code: 'X_JOB_LEASE_LOST' };
55
+
56
+ export const STEP_STORE_CHECKS: readonly StepStoreCheck[] = [
57
+ {
58
+ name: 'a step nobody wrote is undefined, and a run nobody wrote lists nothing',
59
+ async run({ steps }) {
60
+ const runId = crypto.randomUUID();
61
+ expect(await steps.get(runId, 'absent')).toBeUndefined();
62
+ expect(await steps.list(runId)).toEqual([]);
63
+ },
64
+ },
65
+ {
66
+ name: 'every field of a record reads back as it was written',
67
+ async run({ steps }) {
68
+ const runId = crypto.randomUUID();
69
+ const waiting = step(runId, 'wait', {
70
+ status: 'waiting',
71
+ output: { floor: 7 },
72
+ wakeAt: AT + 60_000,
73
+ event: 'paid',
74
+ correlationKey: 'order-1',
75
+ attempts: 2,
76
+ error: 'boom',
77
+ });
78
+ await steps.put(waiting);
79
+ expect(await steps.get(runId, 'wait')).toEqual(waiting);
80
+ expect(await steps.list(runId)).toEqual([waiting]);
81
+ },
82
+ },
83
+ {
84
+ // A live reference replayed a `Date` under one store and a string under another: a step that
85
+ // worked in every test broke on its first retry in production.
86
+ name: 'an output is stored as JSON carries it: a Date as its string, undefined as null',
87
+ async run({ steps }) {
88
+ const runId = crypto.randomUUID();
89
+ const date = new Date(AT);
90
+ const cases: readonly (readonly [string, unknown, unknown])[] = [
91
+ ['date', { at: date }, { at: date.toISOString() }],
92
+ ['undefined', undefined, null],
93
+ ['member', { a: undefined, b: 1 }, { b: 1 }],
94
+ ['map', new Map([['k', 1]]), {}],
95
+ ];
96
+ for (const [name, output] of cases) await steps.put(step(runId, name, { output }));
97
+ for (const [name, , stored] of cases) {
98
+ expect((await steps.get(runId, name))?.output).toEqual(stored);
99
+ }
100
+ },
101
+ },
102
+ {
103
+ name: 'a second put of one (run, name) replaces the first',
104
+ async run({ steps }) {
105
+ const runId = crypto.randomUUID();
106
+ await steps.put(step(runId, 'nap', { status: 'sleeping', output: null, wakeAt: AT + 9 }));
107
+ const done = step(runId, 'nap', { output: 'woke', attempts: 2 });
108
+ await steps.put(done);
109
+ expect(await steps.list(runId)).toEqual([done]);
110
+ },
111
+ },
112
+ {
113
+ name: 'list reads one run in start order; del and clear scope by run',
114
+ async run({ steps }) {
115
+ const [runId, other] = [crypto.randomUUID(), crypto.randomUUID()];
116
+ const [late, early, mid] = [
117
+ step(runId, 'late', { startedAt: AT + 20 }),
118
+ step(runId, 'early', { startedAt: AT }),
119
+ step(runId, 'mid', { startedAt: AT + 10 }),
120
+ ];
121
+ for (const each of [late, early, mid, step(other, 'kept')]) await steps.put(each);
122
+ expect((await steps.list(runId)).map((each) => each.name)).toEqual(['early', 'mid', 'late']);
123
+ await steps.del(runId, 'mid');
124
+ expect((await steps.list(runId)).map((each) => each.name)).toEqual(['early', 'late']);
125
+ await steps.clear(runId);
126
+ expect(await steps.list(runId)).toEqual([]);
127
+ expect((await steps.list(other)).map((each) => each.name)).toEqual(['kept']);
128
+ },
129
+ },
130
+ {
131
+ name: 'a write under a claim that still holds the row lands',
132
+ async run(subject) {
133
+ const { runId, fence } = await claimed(subject);
134
+ await subject.steps.put(step(runId, 'fenced'), fence);
135
+ expect((await subject.steps.get(runId, 'fenced'))?.status).toBe('completed');
136
+ },
137
+ },
138
+ {
139
+ // The in-process abort cannot stop a body in ANOTHER process whose lease lapsed; this can.
140
+ name: 'a write under another claim of the row is X_JOB_LEASE_LOST and writes nothing',
141
+ async run(subject) {
142
+ const { runId, fence } = await claimed(subject);
143
+ const stale = [
144
+ { ...fence, claim: fence.claim + 1 },
145
+ { ...fence, workerId: 'another' },
146
+ ];
147
+ for (const by of stale) {
148
+ await expect(subject.steps.put(step(runId, 'stale'), by)).rejects.toMatchObject(leaseLost);
149
+ }
150
+ expect(await subject.steps.get(runId, 'stale')).toBeUndefined();
151
+ },
152
+ },
153
+ {
154
+ name: 'a write under a claim whose row was settled is X_JOB_LEASE_LOST',
155
+ async run(subject) {
156
+ const { runId, fence } = await claimed(subject);
157
+ expect(await subject.ack(fence.jobId, fence)).toBe(true);
158
+ await expect(subject.steps.put(step(runId, 'late'), fence)).rejects.toMatchObject(leaseLost);
159
+ expect(await subject.steps.get(runId, 'late')).toBeUndefined();
160
+ },
161
+ },
162
+ ];
163
+
164
+ export const stepStoreConformance: SharedExamples<StepStoreSubject | Promise<StepStoreSubject>> =
165
+ sharedExamples('a step store', (subject) => {
166
+ for (const check of STEP_STORE_CHECKS) {
167
+ test(check.name, async () => {
168
+ await check.run(await subject());
169
+ });
170
+ }
171
+ });
@@ -0,0 +1,132 @@
1
+ // The read-and-write half of the `StorageDriver` contract: what every disk — local, memory, s3, and
2
+ // yours — answers through the port alone. Lifted from `storage/src/driver-contract.test.ts` and
3
+ // `driver-parity.test.ts`; a semantic only one disk holds is a test that passes CI and fails deploy.
4
+
5
+ import { expect } from 'bun:test';
6
+ import type { StorageCheck } from './storage-conformance-shape';
7
+ import { bytesOf, drain, refusalOf, scopeOf, streamOf, textOf } from './storage-conformance-shape';
8
+
9
+ export const STORAGE_READ_CHECKS: readonly StorageCheck[] = [
10
+ {
11
+ name: 'put, stat, get and exists describe one object: key, size and type',
12
+ async run({ disk }) {
13
+ const key = `${scopeOf()}a.png`;
14
+ const put = await disk.put(key, bytesOf('12345'), { contentType: 'image/png' });
15
+ const stat = await disk.stat(key);
16
+ const read = await disk.get(key);
17
+ for (const object of [put, stat, read.object]) {
18
+ expect([object?.key, object?.size, object?.contentType]).toEqual([key, 5, 'image/png']);
19
+ }
20
+ expect(textOf(read.bytes)).toBe('12345');
21
+ expect(await disk.exists(key)).toBe(true);
22
+ },
23
+ },
24
+ {
25
+ name: 'an absent key is undefined to stat, false to exists, X_STORAGE_NOT_FOUND to a read',
26
+ async run({ disk }) {
27
+ const scope = scopeOf();
28
+ await disk.put(`${scope}p`, bytesOf('file'));
29
+ await disk.put(`${scope}q/r`, bytesOf('nested'));
30
+ // `p/x` sits under an object and `q` is only a prefix: absent on every disk all the same.
31
+ for (const absent of [`${scope}never`, `${scope}p/x`, `${scope}q`]) {
32
+ expect(await disk.stat(absent)).toBeUndefined();
33
+ expect(await disk.exists(absent)).toBe(false);
34
+ expect(await refusalOf(() => disk.get(absent))).toBe('X_STORAGE_NOT_FOUND');
35
+ expect(await refusalOf(() => disk.stream(absent))).toBe('X_STORAGE_NOT_FOUND');
36
+ expect(await refusalOf(() => disk.streamRange(absent, [0, 1]))).toBe('X_STORAGE_NOT_FOUND');
37
+ }
38
+ expect(textOf((await disk.get(`${scope}q/r`)).bytes)).toBe('nested');
39
+ },
40
+ },
41
+ {
42
+ name: 'a key that climbs out of the disk is X_STORAGE_PATH_UNSAFE before a byte moves',
43
+ async run({ disk }) {
44
+ expect(await refusalOf(() => disk.stat('../escape'))).toBe('X_STORAGE_PATH_UNSAFE');
45
+ expect(await refusalOf(() => disk.get('../escape'))).toBe('X_STORAGE_PATH_UNSAFE');
46
+ expect(await refusalOf(() => disk.put('../escape', bytesOf('x')))).toBe(
47
+ 'X_STORAGE_PATH_UNSAFE',
48
+ );
49
+ },
50
+ },
51
+ {
52
+ name: 'an overwrite moves the etag, and a read pinned to the old one is X_STORAGE_OBJECT_CHANGED',
53
+ async run({ disk }) {
54
+ const key = `${scopeOf()}v.txt`;
55
+ await disk.put(key, bytesOf('first version'), { contentType: 'text/plain' });
56
+ const before = (await disk.stat(key))?.etag ?? '';
57
+ await disk.put(key, bytesOf('second, longer version'), { contentType: 'text/plain' });
58
+ const now = (await disk.stat(key))?.etag ?? '';
59
+ expect(now).not.toBe(before);
60
+ const stale = { etag: before };
61
+ expect(await refusalOf(() => disk.stream(key, stale))).toBe('X_STORAGE_OBJECT_CHANGED');
62
+ expect(await refusalOf(() => disk.streamRange(key, [0, 4], stale))).toBe(
63
+ 'X_STORAGE_OBJECT_CHANGED',
64
+ );
65
+ expect(await drain(await disk.stream(key, { etag: now }))).toBe('second, longer version');
66
+ expect(await drain(await disk.streamRange(key, [0, 5], { etag: now }))).toBe('second');
67
+ },
68
+ },
69
+ {
70
+ name: 'a header value with a line break is X_INVARIANT on put and putStream, and stores nothing',
71
+ async run({ disk }) {
72
+ const key = `${scopeOf()}a`;
73
+ const injected = 'text/html\r\nx-evil: 1';
74
+ for (const options of [{ contentType: injected }, { cacheControl: injected }]) {
75
+ expect(await refusalOf(() => disk.put(key, bytesOf('x'), options))).toBe('X_INVARIANT');
76
+ const streamed = () =>
77
+ disk.putStream(key, streamOf(bytesOf('x')), { maxBytes: 8, ...options });
78
+ expect(await refusalOf(streamed)).toBe('X_INVARIANT');
79
+ }
80
+ expect(await disk.exists(key)).toBe(false);
81
+ },
82
+ },
83
+ {
84
+ name: 'delete of an absent key resolves, and a deleted key reads as absent',
85
+ async run({ disk }) {
86
+ const key = `${scopeOf()}gone.txt`;
87
+ await expect(disk.delete(key)).resolves.toBeUndefined();
88
+ await disk.put(key, bytesOf('x'));
89
+ await disk.delete(key);
90
+ expect(await disk.exists(key)).toBe(false);
91
+ expect(await refusalOf(() => disk.get(key))).toBe('X_STORAGE_NOT_FOUND');
92
+ },
93
+ },
94
+ {
95
+ name: 'metadata and cacheControl put() was told are on the object it answers',
96
+ async run({ disk }) {
97
+ const options = { cacheControl: 'public, max-age=60', metadata: { uploadedBy: 'user-1' } };
98
+ const object = await disk.put(`${scopeOf()}m`, bytesOf('x'), options);
99
+ expect([object.cacheControl, object.metadata]).toEqual([
100
+ 'public, max-age=60',
101
+ { uploadedBy: 'user-1' },
102
+ ]);
103
+ },
104
+ },
105
+ {
106
+ name: 'copy lands the bytes at the destination and leaves the source as it was',
107
+ async run({ disk }) {
108
+ const scope = scopeOf();
109
+ const source = await disk.put(`${scope}src`, bytesOf('copy-me'), {
110
+ contentType: 'text/plain',
111
+ });
112
+ const copied = await disk.copy(`${scope}src`, `${scope}dst`, { ifMatch: source.etag });
113
+ expect([copied.key, copied.size]).toEqual([`${scope}dst`, 7]);
114
+ expect(textOf((await disk.get(`${scope}dst`)).bytes)).toBe('copy-me');
115
+ expect(textOf((await disk.get(`${scope}src`)).bytes)).toBe('copy-me');
116
+ expect(await refusalOf(() => disk.copy(`${scope}none`, `${scope}x`))).toBe(
117
+ 'X_STORAGE_NOT_FOUND',
118
+ );
119
+ },
120
+ },
121
+ {
122
+ name: 'a copy pinned to a revision the source moved past is refused and writes nothing',
123
+ async run({ disk }) {
124
+ const scope = scopeOf();
125
+ const old = await disk.put(`${scope}src`, bytesOf('one'));
126
+ await disk.put(`${scope}src`, bytesOf('two, longer'));
127
+ const stale = () => disk.copy(`${scope}src`, `${scope}dst`, { ifMatch: old.etag });
128
+ expect(await refusalOf(stale)).toBe('X_STORAGE_OBJECT_CHANGED');
129
+ expect(await disk.exists(`${scope}dst`)).toBe(false);
130
+ },
131
+ },
132
+ ];