@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.
- package/CLAUDE.md +46 -55
- package/README.md +179 -39
- package/package.json +23 -17
- package/src/ai-conformance-answer.ts +67 -0
- package/src/ai-gateway-conformance.ts +105 -0
- package/src/ai-provider-conformance.ts +69 -0
- package/src/ai-provider-transport-conformance.ts +170 -0
- package/src/audit-sink-conformance.ts +204 -0
- package/src/auth-adapter-conformance-credentials.ts +124 -0
- package/src/auth-adapter-conformance-mfa.ts +70 -0
- package/src/auth-adapter-conformance-passkeys.ts +133 -0
- package/src/auth-adapter-conformance-sessions.ts +115 -0
- package/src/auth-adapter-conformance-support.ts +71 -0
- package/src/auth-adapter-conformance-users.ts +128 -0
- package/src/auth-adapter-conformance.ts +34 -0
- package/src/auth-limiter-factory-conformance.ts +224 -0
- package/src/auth-server-store-conformance-records.ts +69 -0
- package/src/auth-server-store-conformance.ts +208 -0
- package/src/cache-tier-conformance-checks.ts +142 -0
- package/src/cache-tier-conformance.ts +24 -0
- package/src/cassette-format.ts +8 -13
- package/src/cassette-record.ts +1 -1
- package/src/cdp-browser.ts +10 -11
- package/src/cdp-e2e-page.ts +2 -2
- package/src/cdp-e2e-session.ts +2 -2
- package/src/cdp-network-probe.ts +1 -1
- package/src/cdp-offline-script.ts +2 -2
- package/src/clock-conformance.ts +126 -0
- package/src/conformance.ts +239 -0
- package/src/e2e-browser-handle.ts +1 -2
- package/src/e2e-error-codes.ts +17 -16
- package/src/e2e-run.ts +4 -3
- package/src/embedder-conformance.ts +101 -0
- package/src/entity-conformance-aggregates.ts +210 -0
- package/src/entity-conformance-batches.ts +216 -0
- package/src/entity-conformance-bulk.ts +379 -0
- package/src/entity-conformance-checks.ts +27 -0
- package/src/entity-conformance-entities.ts +52 -0
- package/src/entity-conformance-locks.ts +286 -0
- package/src/entity-conformance-matrix.ts +397 -0
- package/src/entity-conformance-reads.ts +241 -0
- package/src/entity-conformance-support.ts +56 -0
- package/src/entity-conformance-tenancy.ts +296 -0
- package/src/entity-conformance-values.ts +305 -0
- package/src/entity-conformance-versions.ts +60 -0
- package/src/entity-conformance-writes.ts +348 -0
- package/src/entity-driver-conformance.ts +103 -0
- package/src/error-groups-store-conformance.ts +198 -0
- package/src/error-reporter-conformance.ts +119 -0
- package/src/errors.ts +20 -2
- package/src/event-bus-conformance.ts +161 -0
- package/src/exercise-drift-hint.ts +4 -1
- package/src/exercise-judge.ts +5 -3
- package/src/exercise-override-line.ts +98 -0
- package/src/exercise-report.ts +30 -51
- package/src/exercise.ts +12 -6
- package/src/factories.ts +192 -179
- package/src/factory-api.ts +131 -0
- package/src/factory-associations.ts +67 -0
- package/src/factory-errors.ts +38 -0
- package/src/factory-lint.ts +92 -0
- package/src/factory-persist.ts +74 -16
- package/src/factory-pipeline.ts +191 -0
- package/src/factory-registry.ts +2 -1
- package/src/factory-types.ts +131 -0
- package/src/failure-store-conformance.ts +137 -0
- package/src/fixture-jobs.ts +27 -11
- package/src/fixture-mail.ts +7 -7
- package/src/fixture-seed.ts +111 -0
- package/src/fixture-statements.ts +68 -52
- package/src/framework-fixtures.ts +1 -1
- package/src/idempotency-store-conformance.ts +186 -0
- package/src/idempotency-store-replay-conformance.ts +140 -0
- package/src/idempotency-store-tx-conformance.ts +132 -0
- package/src/idempotency-store-world-conformance.ts +82 -0
- package/src/identity-provider-conformance.ts +144 -0
- package/src/image-transform-conformance.ts +89 -0
- package/src/index.ts +68 -157
- package/src/isr-store-conformance.ts +113 -0
- package/src/job-sim-effects.ts +19 -31
- package/src/job-sim-world.ts +6 -15
- package/src/lease-store-conformance.ts +195 -0
- package/src/mail-driver-conformance.ts +108 -0
- package/src/matcher-doubles.ts +104 -0
- package/src/matcher-stub.ts +78 -0
- package/src/matcher-surface.ts +21 -0
- package/src/matchers.ts +19 -1
- package/src/mcp-confirmation-store-conformance.ts +262 -0
- package/src/meter-store-conformance.ts +135 -0
- package/src/notify-digest-conformance.ts +133 -0
- package/src/notify-inbox-conformance.ts +130 -0
- package/src/notify-ledger-conformance.ts +134 -0
- package/src/notify-preference-conformance.ts +49 -0
- package/src/notify-stores-conformance.ts +73 -0
- package/src/outbox-store-conformance-claims.ts +112 -0
- package/src/outbox-store-conformance-subject.ts +65 -0
- package/src/outbox-store-conformance.ts +71 -0
- package/src/per-test-reset.ts +55 -20
- package/src/preload.ts +4 -2
- package/src/purge-conformance.ts +79 -0
- package/src/push-device-conformance.ts +124 -0
- package/src/push-subscription-conformance.ts +123 -0
- package/src/quiet-logs.ts +4 -4
- package/src/rate-limit-store-conformance.ts +178 -0
- package/src/registry-leak-error.ts +8 -1
- package/src/scrape-driver-conformance-frame-checks.ts +97 -0
- package/src/scrape-driver-conformance-page-checks.ts +114 -0
- package/src/scrape-driver-conformance-site.ts +84 -0
- package/src/scrape-driver-conformance.ts +34 -0
- package/src/search-index-conformance-list.ts +76 -0
- package/src/search-index-conformance-support.ts +69 -0
- package/src/search-index-conformance-versions.ts +66 -0
- package/src/search-index-conformance.ts +126 -0
- package/src/secret-source-conformance.ts +91 -0
- package/src/seed-factories.ts +57 -0
- package/src/seed-writer.ts +8 -19
- package/src/semantic-cache-factory-conformance.ts +86 -0
- package/src/sms-transport-conformance.ts +102 -0
- package/src/step-store-conformance.ts +171 -0
- package/src/storage-conformance-read-checks.ts +132 -0
- package/src/storage-conformance-shape.ts +121 -0
- package/src/storage-conformance-stream-checks.ts +226 -0
- package/src/storage-conformance.ts +34 -0
- package/src/stub-action.ts +24 -0
- package/src/stub-errors.ts +86 -0
- package/src/stub-job.ts +30 -0
- package/src/stub-query.ts +25 -0
- package/src/stub-script.ts +76 -0
- package/src/stub-stack.ts +29 -0
- package/src/stub.ts +73 -0
- package/src/swap-adapter.ts +135 -0
- package/src/test-scope.ts +96 -0
- package/src/test-types.ts +1 -1
- package/src/totp-replay-guard-conformance.ts +76 -0
- package/src/transport-conformance.ts +179 -0
- package/src/upload-scanner-conformance.ts +112 -0
- package/src/vector-store-conformance-checks.ts +174 -0
- package/src/vector-store-conformance.ts +21 -0
- package/src/cdp-connection.ts +0 -291
- package/src/cdp-errors.ts +0 -179
- package/src/cdp-launch-attempt.ts +0 -224
- package/src/cdp-launch-candidates.ts +0 -62
- package/src/cdp-launch-profile.ts +0 -106
- package/src/cdp-launch-reap.ts +0 -68
- package/src/cdp-launch-wire.ts +0 -171
- package/src/cdp-launch.ts +0 -175
- package/src/cdp-pipe.ts +0 -77
- package/src/cdp-wire-watch.ts +0 -113
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// The `uploadScanner` port's contract as shared examples: `behavesLike(uploadScannerConformance, ()
|
|
2
|
+
// => scanner)`. Structural over `@ultimat3/storage`'s `UploadScanner`, as the storage suite is over
|
|
3
|
+
// its driver, so this package takes no dependency on storage. Bodies arrive as streams, cut small.
|
|
4
|
+
|
|
5
|
+
import { expect, test } from 'bun:test';
|
|
6
|
+
import type { SharedExamples } from './shared-examples';
|
|
7
|
+
import { sharedExamples } from './shared-examples';
|
|
8
|
+
|
|
9
|
+
/** `@ultimat3/storage`'s `ScanVerdict`, restated structurally. */
|
|
10
|
+
export type ScanVerdictLike =
|
|
11
|
+
| { readonly verdict: 'clean' }
|
|
12
|
+
| { readonly verdict: 'infected'; readonly signature: string }
|
|
13
|
+
| { readonly verdict: 'hold'; readonly reason: string };
|
|
14
|
+
|
|
15
|
+
/** `@ultimat3/storage`'s `UploadScanner`: a ClamAV adapter, a vendor API, the memory reference. */
|
|
16
|
+
export interface UploadScannerLike {
|
|
17
|
+
readonly name: string;
|
|
18
|
+
readonly holds?: boolean | undefined;
|
|
19
|
+
scan(input: {
|
|
20
|
+
readonly key: string;
|
|
21
|
+
readonly pendingKey: string;
|
|
22
|
+
readonly size: number;
|
|
23
|
+
readonly contentType: string;
|
|
24
|
+
readonly body: ReadableStream<Uint8Array>;
|
|
25
|
+
}): Promise<ScanVerdictLike>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface UploadScannerCheck {
|
|
29
|
+
readonly name: string;
|
|
30
|
+
run(scanner: UploadScannerLike): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The EICAR test string, in two halves so this file is no detection itself. */
|
|
34
|
+
export const UPLOAD_SCANNER_EICAR = `${'X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR'}${'-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*'}`;
|
|
35
|
+
|
|
36
|
+
const encode = (text: string): Uint8Array => new TextEncoder().encode(text);
|
|
37
|
+
|
|
38
|
+
/** `bytes` as a stream of `size`-byte chunks — EICAR cut by the transport is still EICAR. */
|
|
39
|
+
function streamOf(bytes: Uint8Array, size: number): ReadableStream<Uint8Array> {
|
|
40
|
+
let at = 0;
|
|
41
|
+
return new ReadableStream({
|
|
42
|
+
pull(controller) {
|
|
43
|
+
if (at >= bytes.byteLength) return controller.close();
|
|
44
|
+
controller.enqueue(bytes.slice(at, at + size));
|
|
45
|
+
at += size;
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const scan = (scanner: UploadScannerLike, bytes: Uint8Array, chunk = 64 * 1024) =>
|
|
51
|
+
scanner.scan({
|
|
52
|
+
key: 'org/conformance/pending/scan/a1-u-1.txt',
|
|
53
|
+
pendingKey: 'org/conformance/pending/u-1.txt',
|
|
54
|
+
size: bytes.byteLength,
|
|
55
|
+
contentType: 'text/plain',
|
|
56
|
+
body: streamOf(bytes, chunk),
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const PLAIN = encode('A plain note: nothing in here is a virus.\n');
|
|
60
|
+
|
|
61
|
+
export const UPLOAD_SCANNER_CHECKS: readonly UploadScannerCheck[] = [
|
|
62
|
+
{
|
|
63
|
+
name: 'has a name, for the refusal it ends up in',
|
|
64
|
+
async run(scanner) {
|
|
65
|
+
expect(scanner.name.length).toBeGreaterThan(0);
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: 'the EICAR test file is infected, with a non-empty signature',
|
|
70
|
+
async run(scanner) {
|
|
71
|
+
const verdict = await scan(scanner, encode(UPLOAD_SCANNER_EICAR));
|
|
72
|
+
expect(verdict.verdict).toBe('infected');
|
|
73
|
+
expect(verdict.verdict === 'infected' ? verdict.signature.length : 0).toBeGreaterThan(0);
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: 'the EICAR test file delivered in 7-byte chunks is still infected',
|
|
78
|
+
async run(scanner) {
|
|
79
|
+
expect((await scan(scanner, encode(UPLOAD_SCANNER_EICAR), 7)).verdict).toBe('infected');
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
name: 'a plain text file is clean',
|
|
84
|
+
async run(scanner) {
|
|
85
|
+
expect(await scan(scanner, PLAIN)).toEqual({ verdict: 'clean' });
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: 'an empty file is clean',
|
|
90
|
+
async run(scanner) {
|
|
91
|
+
expect(await scan(scanner, new Uint8Array())).toEqual({ verdict: 'clean' });
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
name: 'a verdict is about these bytes only: infected, then clean, from one scanner',
|
|
96
|
+
async run(scanner) {
|
|
97
|
+
expect((await scan(scanner, encode(UPLOAD_SCANNER_EICAR))).verdict).toBe('infected');
|
|
98
|
+
expect(await scan(scanner, PLAIN)).toEqual({ verdict: 'clean' });
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
];
|
|
102
|
+
|
|
103
|
+
export const uploadScannerConformance: SharedExamples<UploadScannerLike> = sharedExamples(
|
|
104
|
+
'an upload scanner',
|
|
105
|
+
(subject) => {
|
|
106
|
+
for (const check of UPLOAD_SCANNER_CHECKS) {
|
|
107
|
+
test(check.name, async () => {
|
|
108
|
+
await check.run(subject());
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
);
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// The checks behind `vectorStoreConformance`, one behaviour each, asserted through `VectorStore`
|
|
2
|
+
// alone. Every check binds its own fresh tenant with `scoped()`, so one table shared by the whole
|
|
3
|
+
// suite (pgvector) and one map (memory) both answer as if each check had a store of its own.
|
|
4
|
+
|
|
5
|
+
import { expect } from 'bun:test';
|
|
6
|
+
import type { SearchHit, VectorRecord, VectorStore } from '@ultimat3/ai';
|
|
7
|
+
import { isUltimateError } from '@ultimat3/core';
|
|
8
|
+
|
|
9
|
+
export interface VectorStoreCheck {
|
|
10
|
+
readonly name: string;
|
|
11
|
+
run(store: VectorStore): Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Every subject is built at this width: a pg table's column type is fixed by its DDL. */
|
|
15
|
+
export const VECTOR_CONFORMANCE_DIMENSION = 3;
|
|
16
|
+
|
|
17
|
+
const unit = (...values: number[]): Float32Array => {
|
|
18
|
+
const norm = Math.hypot(...values);
|
|
19
|
+
return Float32Array.from(values.map((value) => value / norm));
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const NORTH = unit(1, 0, 0);
|
|
23
|
+
const CORPUS: readonly VectorRecord[] = [
|
|
24
|
+
{ id: 'a', vector: NORTH, text: 'alpha zirconium manual', metadata: { kind: 'guide' } },
|
|
25
|
+
{
|
|
26
|
+
id: 'b',
|
|
27
|
+
vector: unit(0.9, 0.1, 0),
|
|
28
|
+
text: 'beta guide about vectors',
|
|
29
|
+
metadata: { kind: 'guide' },
|
|
30
|
+
},
|
|
31
|
+
{ id: 'c', vector: unit(0, 1, 0), text: 'gamma error report', metadata: { kind: 'error' } },
|
|
32
|
+
{ id: 'd', vector: unit(0, 0, 1), text: 'delta billing summary' },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
let minted = 0;
|
|
36
|
+
const tenantOf = (): string => {
|
|
37
|
+
minted += 1;
|
|
38
|
+
return `conformance-${Bun.randomUUIDv7()}-${minted.toString(36)}`;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** A fresh tenant's view of `store`, holding `CORPUS`. */
|
|
42
|
+
const seeded = async (store: VectorStore): Promise<VectorStore> => {
|
|
43
|
+
const view = store.scoped({ tenant: tenantOf() });
|
|
44
|
+
await view.upsert(CORPUS);
|
|
45
|
+
return view;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const ids = (hits: readonly SearchHit[]): readonly string[] => hits.map((hit) => hit.id);
|
|
49
|
+
const sortedIds = (hits: readonly SearchHit[]): readonly string[] => [...ids(hits)].sort();
|
|
50
|
+
|
|
51
|
+
const codeOf = async (run: () => unknown): Promise<string> => {
|
|
52
|
+
try {
|
|
53
|
+
await run();
|
|
54
|
+
return 'answered';
|
|
55
|
+
} catch (error) {
|
|
56
|
+
return isUltimateError(error) ? error.code : `not an UltimateError: ${String(error)}`;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export const VECTOR_STORE_CHECKS: readonly VectorStoreCheck[] = [
|
|
61
|
+
{
|
|
62
|
+
name: 'search ranks the nearest vector first, stops at k, and carries text and metadata',
|
|
63
|
+
async run(store) {
|
|
64
|
+
expect(store.dimension).toBe(VECTOR_CONFORMANCE_DIMENSION);
|
|
65
|
+
const hits = await (await seeded(store)).search(NORTH, 2);
|
|
66
|
+
expect(ids(hits)).toEqual(['a', 'b']);
|
|
67
|
+
expect(hits[0]).toMatchObject({
|
|
68
|
+
text: 'alpha zirconium manual',
|
|
69
|
+
metadata: { kind: 'guide' },
|
|
70
|
+
});
|
|
71
|
+
expect(hits[0]?.score ?? 0).toBeGreaterThan(hits[1]?.score ?? 1);
|
|
72
|
+
},
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: 'a row with no metadata answers {}, and an upsert of a known id replaces it',
|
|
76
|
+
async run(store) {
|
|
77
|
+
const view = await seeded(store);
|
|
78
|
+
await view.upsert([{ id: 'd', vector: unit(0, 0, 1), text: 'delta rewritten' }]);
|
|
79
|
+
const hits = await view.search(unit(0, 0, 1), 1);
|
|
80
|
+
expect(hits).toMatchObject([{ id: 'd', text: 'delta rewritten', metadata: {} }]);
|
|
81
|
+
expect(await view.search(NORTH, 10)).toHaveLength(CORPUS.length);
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'a vector of the wrong width is X_VECTOR_DIM_MISMATCH on upsert, search and hybrid',
|
|
86
|
+
async run(store) {
|
|
87
|
+
const view = store.scoped({ tenant: tenantOf() });
|
|
88
|
+
const wide = new Float32Array(VECTOR_CONFORMANCE_DIMENSION + 1);
|
|
89
|
+
const record = { id: 'x', vector: wide, text: 'x' };
|
|
90
|
+
expect([
|
|
91
|
+
await codeOf(() => view.upsert([record])),
|
|
92
|
+
await codeOf(() => view.search(wide, 1)),
|
|
93
|
+
await codeOf(() => view.hybrid({ query: 'x', vector: wide, k: 1 })),
|
|
94
|
+
]).toEqual(['X_VECTOR_DIM_MISMATCH', 'X_VECTOR_DIM_MISMATCH', 'X_VECTOR_DIM_MISMATCH']);
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
name: 'a batch holding one wrong-width record is refused whole: none of it is written',
|
|
99
|
+
async run(store) {
|
|
100
|
+
const view = store.scoped({ tenant: tenantOf() });
|
|
101
|
+
const wide = new Float32Array(VECTOR_CONFORMANCE_DIMENSION + 1);
|
|
102
|
+
const batch = [...CORPUS, { id: 'x', vector: wide, text: 'x' }];
|
|
103
|
+
expect(await codeOf(() => view.upsert(batch))).toBe('X_VECTOR_DIM_MISMATCH');
|
|
104
|
+
expect(await view.search(NORTH, 10)).toEqual([]);
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: 'a metadata filter is an exact match, and a row missing the key is not a match',
|
|
109
|
+
async run(store) {
|
|
110
|
+
const view = await seeded(store);
|
|
111
|
+
expect(sortedIds(await view.search(NORTH, 10, { kind: 'guide' }))).toEqual(['a', 'b']);
|
|
112
|
+
expect(await view.search(NORTH, 10, { kind: 'guid' })).toEqual([]);
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
name: 'two tenants hold the same id as two rows, and neither sees nor deletes the other',
|
|
117
|
+
async run(store) {
|
|
118
|
+
const [one, two] = [await seeded(store), store.scoped({ tenant: tenantOf() })];
|
|
119
|
+
await two.upsert([{ id: 'a', vector: NORTH, text: 'the other tenant' }]);
|
|
120
|
+
await two.delete(['b']);
|
|
121
|
+
expect(ids(await two.search(NORTH, 10))).toEqual(['a']);
|
|
122
|
+
expect((await one.search(NORTH, 1))[0]?.text).toBe('alpha zirconium manual');
|
|
123
|
+
expect(await one.search(NORTH, 10)).toHaveLength(CORPUS.length);
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
name: 'a scope only tightens: another tenant is X_VECTOR_SCOPE_WIDENED, an allow-list hides',
|
|
128
|
+
async run(store) {
|
|
129
|
+
const view = await seeded(store);
|
|
130
|
+
expect(await codeOf(() => view.scoped({ tenant: tenantOf() }))).toBe(
|
|
131
|
+
'X_VECTOR_SCOPE_WIDENED',
|
|
132
|
+
);
|
|
133
|
+
const guides = view.scoped({ allow: { kind: ['guide', 'error'] } }).scoped({
|
|
134
|
+
allow: { kind: ['guide'] },
|
|
135
|
+
});
|
|
136
|
+
expect(sortedIds(await guides.search(NORTH, 10))).toEqual(['a', 'b']);
|
|
137
|
+
await guides.delete(['c', 'd']);
|
|
138
|
+
expect(await view.search(NORTH, 10)).toHaveLength(CORPUS.length);
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
name: 'prune deletes what the filter matches except the kept ids, and nothing else',
|
|
143
|
+
async run(store) {
|
|
144
|
+
const view = await seeded(store);
|
|
145
|
+
await view.prune({ kind: 'guide' }, ['b']);
|
|
146
|
+
expect(sortedIds(await view.search(NORTH, 10))).toEqual(['b', 'c', 'd']);
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
name: 'searchText ranks the document holding a rare exact term first; no match is []',
|
|
151
|
+
async run(store) {
|
|
152
|
+
const view = await seeded(store);
|
|
153
|
+
expect(ids(await view.searchText('zirconium', 3))[0]).toBe('a');
|
|
154
|
+
expect(await view.searchText('xylophonist', 3)).toEqual([]);
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
name: 'hybrid puts the row both rankings lead with first, and stops at k',
|
|
159
|
+
async run(store) {
|
|
160
|
+
const view = await seeded(store);
|
|
161
|
+
const hits = await view.hybrid({ query: 'zirconium', vector: NORTH, k: 2 });
|
|
162
|
+
expect(hits).toHaveLength(2);
|
|
163
|
+
expect(hits[0]?.id).toBe('a');
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
{
|
|
167
|
+
name: 'a k that is not a whole number is refused, never answered with []',
|
|
168
|
+
async run(store) {
|
|
169
|
+
const view = await seeded(store);
|
|
170
|
+
expect(await codeOf(() => view.search(NORTH, Number.NaN))).toBe('X_INVARIANT');
|
|
171
|
+
expect(await codeOf(() => view.searchText('zirconium', 1.5))).toBe('X_INVARIANT');
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// `@ultimat3/ai`'s `VectorStore` contract as shared examples: `behavesLike(vectorStoreConformance,
|
|
2
|
+
// () => store)` runs every check in `vector-store-conformance-checks.ts` against a store of your
|
|
3
|
+
// own — empty or shared, UNBOUND (each check binds its own tenant), `VECTOR_CONFORMANCE_DIMENSION`
|
|
4
|
+
// wide.
|
|
5
|
+
|
|
6
|
+
import { test } from 'bun:test';
|
|
7
|
+
import type { VectorStore } from '@ultimat3/ai';
|
|
8
|
+
import type { SharedExamples } from './shared-examples';
|
|
9
|
+
import { sharedExamples } from './shared-examples';
|
|
10
|
+
import { VECTOR_STORE_CHECKS } from './vector-store-conformance-checks';
|
|
11
|
+
|
|
12
|
+
export const vectorStoreConformance: SharedExamples<VectorStore> = sharedExamples(
|
|
13
|
+
'a vector store',
|
|
14
|
+
(subject) => {
|
|
15
|
+
for (const check of VECTOR_STORE_CHECKS) {
|
|
16
|
+
test(check.name, async () => {
|
|
17
|
+
await check.run(subject());
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
);
|
package/src/cdp-connection.ts
DELETED
|
@@ -1,291 +0,0 @@
|
|
|
1
|
-
// One responsibility: a Chrome DevTools Protocol connection — request framing, response
|
|
2
|
-
// correlation, and the per-call deadline — over a TRANSPORT that moves whole messages. Two exist:
|
|
3
|
-
// the pipe a launched Chrome is driven over (`cdp-pipe.ts`, what the e2e driver uses) and a remote
|
|
4
|
-
// browser's WebSocket (`cdpConnect` below). Launching is `cdp-launch.ts`; the page surface is
|
|
5
|
-
// `cdp-e2e-page.ts`; this file knows nothing about either.
|
|
6
|
-
//
|
|
7
|
-
// **No library, and that is the point rather than an economy.** `packages/scraping/src/cdp-port.ts`
|
|
8
|
-
// declares a ~25-method port because `ScrapePage` is a full scraping surface, and its intended
|
|
9
|
-
// implementation is `puppeteer-core`. `E2eBrowserPage` is FIVE methods, and CDP's wire format is
|
|
10
|
-
// one JSON object with an `id` — so the whole thing an e2e driver needs is this file plus two
|
|
11
|
-
// small ones, on Bun's native `WebSocket`, with no dependency to add to a repo whose first
|
|
12
|
-
// non-negotiable is that Bun's natives replace most of them.
|
|
13
|
-
|
|
14
|
-
import { assert, stringField } from '@ultimat3/core';
|
|
15
|
-
import { CdpCallFailedError, CdpTimeoutError } from './cdp-errors';
|
|
16
|
-
import { wireWatch } from './cdp-wire-watch';
|
|
17
|
-
|
|
18
|
-
/** One CDP result. `unknown` because every payload here is somebody else's JSON. */
|
|
19
|
-
export interface CdpResult {
|
|
20
|
-
readonly result?: Record<string, unknown> | undefined;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface CdpConnection {
|
|
24
|
-
/**
|
|
25
|
-
* Send one command. `sessionId` targets an attached page rather than the browser itself.
|
|
26
|
-
* `deadlineMs` replaces the connection's per-call deadline for THIS call — the launcher's first
|
|
27
|
-
* call is a cold start, not a call, and is the only caller that passes one.
|
|
28
|
-
*/
|
|
29
|
-
send(
|
|
30
|
-
method: string,
|
|
31
|
-
params?: Record<string, unknown>,
|
|
32
|
-
sessionId?: string,
|
|
33
|
-
deadlineMs?: number,
|
|
34
|
-
): Promise<CdpResult>;
|
|
35
|
-
/**
|
|
36
|
-
* Wait for the next occurrence of one CDP **event**, or for the deadline. Answers `true` when the
|
|
37
|
-
* event arrived and `false` when it did not — it never throws, because every caller has a better
|
|
38
|
-
* assertion to fail on than "the event was late".
|
|
39
|
-
*
|
|
40
|
-
* It exists because a command's reply is not always the signal. `Page.navigate`'s reply is
|
|
41
|
-
* DROPPED whenever the navigation swaps the render process — measured on Chrome 150: the page
|
|
42
|
-
* loads, the server is hit, a later `Runtime.evaluate` answers, and the navigate frame never
|
|
43
|
-
* comes back at all. A driver that treated the reply as the completion signal waits out its full
|
|
44
|
-
* deadline on the most ordinary navigation there is.
|
|
45
|
-
*/
|
|
46
|
-
once(method: string, sessionId: string | undefined, timeoutMs: number): Promise<boolean>;
|
|
47
|
-
/**
|
|
48
|
-
* Subscribe to every occurrence of one CDP event, until the returned function is called.
|
|
49
|
-
*
|
|
50
|
-
* `once` cannot express what this is for: a target that attaches AFTER the driver stopped
|
|
51
|
-
* listening is a service worker whose network conditions nobody set, which is an `offline()`
|
|
52
|
-
* that silently does nothing to the one thing serving the page.
|
|
53
|
-
*
|
|
54
|
-
* The listener is also handed the event's `sessionId` (`undefined` for a browser-level event), so
|
|
55
|
-
* a subscriber that owns ONE page can ignore the frames every other attached target sends.
|
|
56
|
-
*/
|
|
57
|
-
on(method: string, listener: CdpEventListener): () => void;
|
|
58
|
-
close(): void;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** One event's params, and the session it arrived on. */
|
|
62
|
-
export type CdpEventListener = (
|
|
63
|
-
params: Record<string, unknown>,
|
|
64
|
-
sessionId: string | undefined,
|
|
65
|
-
) => void;
|
|
66
|
-
|
|
67
|
-
interface Pending {
|
|
68
|
-
readonly resolve: (value: CdpResult) => void;
|
|
69
|
-
readonly reject: (reason: Error) => void;
|
|
70
|
-
readonly timer: ReturnType<typeof setTimeout>;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** A CDP error frame: `{ error: { code, message } }`, both fields somebody else's. */
|
|
74
|
-
const errorText = (frame: Record<string, unknown>): string | undefined => {
|
|
75
|
-
const error = frame['error'];
|
|
76
|
-
if (typeof error !== 'object' || error === null) return undefined;
|
|
77
|
-
const message = (error as Record<string, unknown>)['message'];
|
|
78
|
-
return typeof message === 'string' ? message : 'the browser refused the call';
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* What a connection needs of the wire: whole messages out, whole messages in, and a close. Framing
|
|
83
|
-
* is the transport's — a WebSocket frames per message, the pipe splits on NUL — so correlation and
|
|
84
|
-
* deadlines are written once, over either.
|
|
85
|
-
*/
|
|
86
|
-
export interface CdpTransport {
|
|
87
|
-
send(text: string): void;
|
|
88
|
-
close(): void;
|
|
89
|
-
/** Installed exactly once, by the connection, before the first `send`. */
|
|
90
|
-
listen(handlers: {
|
|
91
|
-
readonly message: (text: string) => void;
|
|
92
|
-
readonly closed: (reason: string) => void;
|
|
93
|
-
}): void;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
export interface CdpConnectionOptions {
|
|
97
|
-
readonly endpoint: string;
|
|
98
|
-
/** Per-call deadline. A CDP call that never answers is a suite that never finishes. */
|
|
99
|
-
readonly timeoutMs: number;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* What went wrong, in the socket's own words when it has any. Bun hands `onerror` an `ErrorEvent`
|
|
104
|
-
* whose `message` is the only place the reason lives — "Failed to connect", "Expected 101 status
|
|
105
|
-
* code" — and a refusal that drops it names the step and not the cause.
|
|
106
|
-
*/
|
|
107
|
-
const failure = (event: unknown, what: string): string => {
|
|
108
|
-
const message = stringField(event, 'message');
|
|
109
|
-
return message === undefined || message === '' ? what : `${what}: ${message}`;
|
|
110
|
-
};
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* A remote browser over its WebSocket url. NOT the e2e driver's wire: measured in the dummy's
|
|
114
|
-
* `offline-feed` suite on Bun 1.4.0, Bun's WebSocket client handed `onmessage` text spliced out of
|
|
115
|
-
* several frames — 64 unparseable frames in one run, one of them the reply to a `Runtime.evaluate`
|
|
116
|
-
* that then waited out its whole deadline. A launched Chrome is driven over `cdp-pipe.ts` instead.
|
|
117
|
-
*/
|
|
118
|
-
export async function cdpConnect(options: CdpConnectionOptions): Promise<CdpConnection> {
|
|
119
|
-
assert(
|
|
120
|
-
options.endpoint.startsWith('ws://') || options.endpoint.startsWith('wss://'),
|
|
121
|
-
`the CDP endpoint is ${options.endpoint === '' ? 'empty' : 'not a WebSocket url'}`,
|
|
122
|
-
'pass the `webSocketDebuggerUrl` Chrome prints on stderr, or the one /json/version answers',
|
|
123
|
-
);
|
|
124
|
-
const socket = new WebSocket(options.endpoint);
|
|
125
|
-
await new Promise<void>((resolve, reject) => {
|
|
126
|
-
// The socket is CLOSED on both failures: a handshake that timed out otherwise kept dialling
|
|
127
|
-
// in the background, holding a descriptor and a pending connection for a caller that gave up.
|
|
128
|
-
const timer = setTimeout(() => {
|
|
129
|
-
socket.close();
|
|
130
|
-
reject(new CdpTimeoutError({ method: 'connect', timeoutMs: options.timeoutMs }));
|
|
131
|
-
}, options.timeoutMs);
|
|
132
|
-
socket.onopen = (): void => {
|
|
133
|
-
clearTimeout(timer);
|
|
134
|
-
resolve();
|
|
135
|
-
};
|
|
136
|
-
// `onerror` is the handshake's only until `listen` below reassigns it: a failure BEFORE open
|
|
137
|
-
// has no pending call to abandon, and rejecting is the only way the caller hears about it.
|
|
138
|
-
socket.onerror = (event: Event): void => {
|
|
139
|
-
clearTimeout(timer);
|
|
140
|
-
socket.close();
|
|
141
|
-
reject(
|
|
142
|
-
new CdpCallFailedError({
|
|
143
|
-
method: 'connect',
|
|
144
|
-
detail: failure(event, 'the browser refused the connection'),
|
|
145
|
-
}),
|
|
146
|
-
);
|
|
147
|
-
};
|
|
148
|
-
});
|
|
149
|
-
|
|
150
|
-
const transport: CdpTransport = {
|
|
151
|
-
send: (text) => socket.send(text),
|
|
152
|
-
close: () => socket.close(),
|
|
153
|
-
listen(handlers) {
|
|
154
|
-
socket.onmessage = (event: MessageEvent): void => {
|
|
155
|
-
handlers.message(typeof event.data === 'string' ? event.data : '');
|
|
156
|
-
};
|
|
157
|
-
socket.onclose = (): void => handlers.closed('the browser closed the CDP connection');
|
|
158
|
-
socket.onerror = (event: Event): void =>
|
|
159
|
-
handlers.closed(failure(event, 'the CDP connection failed'));
|
|
160
|
-
},
|
|
161
|
-
};
|
|
162
|
-
return cdpConnectOver(transport, options.timeoutMs);
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/** A connection over any transport — correlation, deadlines and events, written once. */
|
|
166
|
-
export function cdpConnectOver(transport: CdpTransport, timeoutMs: number): CdpConnection {
|
|
167
|
-
const pending = new Map<number, Pending>();
|
|
168
|
-
const waiters = new Set<(method: string, sessionId: string | undefined) => void>();
|
|
169
|
-
const listeners = new Map<string, Set<CdpEventListener>>();
|
|
170
|
-
let nextId = 0;
|
|
171
|
-
let closed = false;
|
|
172
|
-
// What a call that is never answered reports instead of a bare "did not answer".
|
|
173
|
-
const watch = wireWatch();
|
|
174
|
-
|
|
175
|
-
// Every in-flight call is settled on close. Without this a suite whose browser died waits out
|
|
176
|
-
// one full deadline per call and reports a timeout, where the true fault is a dead browser.
|
|
177
|
-
const abandon = (reason: string): void => {
|
|
178
|
-
closed = true;
|
|
179
|
-
for (const [, one] of pending) {
|
|
180
|
-
clearTimeout(one.timer);
|
|
181
|
-
one.reject(new CdpCallFailedError({ method: 'the connection', detail: reason }));
|
|
182
|
-
}
|
|
183
|
-
pending.clear();
|
|
184
|
-
// A waiter is a "did this happen" question, and on a dead connection the answer is no. Its
|
|
185
|
-
// own timer settles it, so nothing is left hanging; clearing the set only stops a late frame
|
|
186
|
-
// from resolving a waiter whose connection has gone.
|
|
187
|
-
waiters.clear();
|
|
188
|
-
};
|
|
189
|
-
|
|
190
|
-
const message = (raw: string): void => {
|
|
191
|
-
let frame: Record<string, unknown>;
|
|
192
|
-
try {
|
|
193
|
-
frame = JSON.parse(raw) as Record<string, unknown>;
|
|
194
|
-
} catch {
|
|
195
|
-
// An unparseable frame is the browser's, not ours, and there is no call to fail with it:
|
|
196
|
-
// correlation is by `id`, and a frame we cannot read has none. COUNTED, though: the call
|
|
197
|
-
// whose reply it was waits out its deadline, and its timeout says frames were dropped.
|
|
198
|
-
watch.drop();
|
|
199
|
-
return;
|
|
200
|
-
}
|
|
201
|
-
watch.frame(frame);
|
|
202
|
-
const id = frame['id'];
|
|
203
|
-
if (typeof id !== 'number') {
|
|
204
|
-
const method = frame['method'];
|
|
205
|
-
if (typeof method !== 'string') return;
|
|
206
|
-
const on = typeof frame['sessionId'] === 'string' ? frame['sessionId'] : undefined;
|
|
207
|
-
for (const waiter of [...waiters]) waiter(method, on);
|
|
208
|
-
const subscribed = listeners.get(method);
|
|
209
|
-
if (subscribed !== undefined) {
|
|
210
|
-
const params = frame['params'];
|
|
211
|
-
const payload: Record<string, unknown> =
|
|
212
|
-
typeof params === 'object' && params !== null ? (params as Record<string, unknown>) : {};
|
|
213
|
-
// A copy, because a listener may unsubscribe itself while this loop is running.
|
|
214
|
-
for (const listener of [...subscribed]) listener(payload, on);
|
|
215
|
-
}
|
|
216
|
-
return;
|
|
217
|
-
}
|
|
218
|
-
const one = pending.get(id);
|
|
219
|
-
if (one === undefined) return;
|
|
220
|
-
pending.delete(id);
|
|
221
|
-
clearTimeout(one.timer);
|
|
222
|
-
const failed = errorText(frame);
|
|
223
|
-
if (failed !== undefined) {
|
|
224
|
-
one.reject(new CdpCallFailedError({ method: `call ${String(id)}`, detail: failed }));
|
|
225
|
-
return;
|
|
226
|
-
}
|
|
227
|
-
const result = frame['result'];
|
|
228
|
-
one.resolve({
|
|
229
|
-
result:
|
|
230
|
-
typeof result === 'object' && result !== null
|
|
231
|
-
? (result as Record<string, unknown>)
|
|
232
|
-
: undefined,
|
|
233
|
-
});
|
|
234
|
-
};
|
|
235
|
-
transport.listen({ message, closed: abandon });
|
|
236
|
-
|
|
237
|
-
return {
|
|
238
|
-
send(method, params = {}, sessionId, deadlineMs = timeoutMs): Promise<CdpResult> {
|
|
239
|
-
if (closed) {
|
|
240
|
-
return Promise.reject(
|
|
241
|
-
new CdpCallFailedError({ method, detail: 'the CDP connection is already closed' }),
|
|
242
|
-
);
|
|
243
|
-
}
|
|
244
|
-
nextId += 1;
|
|
245
|
-
const id = nextId;
|
|
246
|
-
return new Promise<CdpResult>((resolve, reject) => {
|
|
247
|
-
const sentAt = watch.mark(sessionId);
|
|
248
|
-
const timer = setTimeout(() => {
|
|
249
|
-
pending.delete(id);
|
|
250
|
-
const observed = watch.observe(sentAt, sessionId, !closed);
|
|
251
|
-
reject(new CdpTimeoutError({ method, timeoutMs: deadlineMs, observed }));
|
|
252
|
-
}, deadlineMs);
|
|
253
|
-
pending.set(id, { resolve, reject, timer });
|
|
254
|
-
transport.send(
|
|
255
|
-
JSON.stringify({ id, method, params, ...(sessionId === undefined ? {} : { sessionId }) }),
|
|
256
|
-
);
|
|
257
|
-
});
|
|
258
|
-
},
|
|
259
|
-
once(method, sessionId, timeoutMs): Promise<boolean> {
|
|
260
|
-
if (closed) return Promise.resolve(false);
|
|
261
|
-
return new Promise<boolean>((resolve) => {
|
|
262
|
-
const waiter = (seen: string, on: string | undefined): void => {
|
|
263
|
-
if (seen !== method) return;
|
|
264
|
-
if (sessionId !== undefined && on !== sessionId) return;
|
|
265
|
-
clearTimeout(timer);
|
|
266
|
-
waiters.delete(waiter);
|
|
267
|
-
resolve(true);
|
|
268
|
-
};
|
|
269
|
-
const timer = setTimeout(() => {
|
|
270
|
-
waiters.delete(waiter);
|
|
271
|
-
resolve(false);
|
|
272
|
-
}, timeoutMs);
|
|
273
|
-
waiters.add(waiter);
|
|
274
|
-
});
|
|
275
|
-
},
|
|
276
|
-
on(method, listener): () => void {
|
|
277
|
-
const subscribed = listeners.get(method) ?? new Set();
|
|
278
|
-
subscribed.add(listener);
|
|
279
|
-
listeners.set(method, subscribed);
|
|
280
|
-
return () => {
|
|
281
|
-
subscribed.delete(listener);
|
|
282
|
-
if (subscribed.size === 0) listeners.delete(method);
|
|
283
|
-
};
|
|
284
|
-
},
|
|
285
|
-
close(): void {
|
|
286
|
-
listeners.clear();
|
|
287
|
-
abandon('the driver closed the CDP connection');
|
|
288
|
-
transport.close();
|
|
289
|
-
},
|
|
290
|
-
};
|
|
291
|
-
}
|