@skyphusion/create-prism 1.0.0 → 1.2.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 (54) hide show
  1. package/README.md +7 -4
  2. package/index.js +1 -0
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +18 -3
  5. package/template/MIGRATIONS.md +52 -0
  6. package/template/README.md +50 -16
  7. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
  8. package/template/docs/legal/INSTANCE-PRIVACY.md +127 -27
  9. package/template/migrations/0004_csp_reports.sql +58 -0
  10. package/template/migrations/0005_auth_attempts_retention.sql +23 -0
  11. package/template/package.json +6 -6
  12. package/template/public/app.js +42 -7
  13. package/template/public/index.html +24 -9
  14. package/template/public/stt.css +25 -0
  15. package/template/public/stt.html +1 -21
  16. package/template/public/styles.css +49 -0
  17. package/template/public/url-safety.js +66 -0
  18. package/template/schema.sql +64 -0
  19. package/template/src/ai-binding.ts +125 -3
  20. package/template/src/auth.ts +6 -0
  21. package/template/src/csp.ts +253 -0
  22. package/template/src/env.ts +11 -0
  23. package/template/src/gateway-credentials.ts +118 -22
  24. package/template/src/index.ts +79 -2
  25. package/template/src/providers/anthropic.ts +4 -4
  26. package/template/src/providers/openai-image.ts +10 -0
  27. package/template/src/providers/xai.ts +4 -4
  28. package/template/src/rate-limit.ts +26 -0
  29. package/template/src/routes/chat.ts +29 -16
  30. package/template/src/routes/csp-report.ts +163 -0
  31. package/template/src/routes/health.ts +6 -1
  32. package/template/src/routes/prefs.ts +46 -5
  33. package/template/src/routes/rag.ts +53 -15
  34. package/template/src/routes/shared.ts +22 -9
  35. package/template/src/routes/workflow.ts +2 -5
  36. package/template/src/stt-session.ts +16 -0
  37. package/template/src/user-prefs.ts +16 -3
  38. package/template/src/version.ts +18 -0
  39. package/template/tests/ai-binding-rest.test.ts +154 -0
  40. package/template/tests/csp.test.ts +449 -0
  41. package/template/tests/gateway-credentials.test.ts +101 -3
  42. package/template/tests/openai-image.test.ts +21 -1
  43. package/template/tests/public-url-safety.test.ts +360 -0
  44. package/template/tests/rag-metadata-filter.test.ts +135 -0
  45. package/template/tests/rag-retrieval-diagnostic.test.ts +142 -0
  46. package/template/tests/skip-link.test.ts +164 -0
  47. package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
  48. package/template/tests/version.test.ts +47 -0
  49. package/template/tests-integration/auth.test.ts +346 -2
  50. package/template/tests-integration/csp-report.test.ts +232 -0
  51. package/template/tests-integration/pdf-extract.test.ts +71 -0
  52. package/template/tests-integration/worker.test.ts +154 -0
  53. package/template/vitest.workers.config.ts +19 -4
  54. package/template/wrangler.example.toml +45 -2
@@ -0,0 +1,142 @@
1
+ // The zero-join retrieval diagnostic (skyphusion-labs/fleet-chezmoi#1608).
2
+ //
3
+ // retrieveContext queries Vectorize globally -- no metadata filter, because the
4
+ // tenant scope is the D1 join (see the design note above retrieveContext, which
5
+ // is deliberate: it avoids requiring a Vectorize metadata index). So the raw
6
+ // Vectorize result legitimately contains vector ids belonging to other tenants,
7
+ // and vector ids are minted as `${userEmail}:${docId}:${chunkIndex}`.
8
+ //
9
+ // That makes the zero-join branch the one place where foreign identifiers are
10
+ // in scope next to a string that gets returned to the caller. These assert the
11
+ // split: the operator log keeps the full diagnostic, the client half carries
12
+ // nothing derived from the shared index.
13
+ //
14
+ // Only env.AI / env.VEC / env.DB are stubbed -- the un-stubbable seams.
15
+ // Everything between them is the real shipped retrieveContext.
16
+
17
+ import { describe, it, expect, vi, afterEach } from "vitest";
18
+ import { retrieveContext } from "../src/routes/rag";
19
+ import type { Env } from "../src/env";
20
+
21
+ const CALLER = "alice@example.com";
22
+ const FOREIGN_IDS = [
23
+ "victim@example.com:7:0",
24
+ "usr_0123456789abcdef01234567:12:3",
25
+ "bob@example.com:99:2",
26
+ ];
27
+
28
+ // A caller-visible string must contain none of these substrings. Kept as the
29
+ // identity half of the vector id rather than the whole id, so the assertion
30
+ // still fires if only the identity survives some future re-formatting.
31
+ const FOREIGN_IDENTITIES = ["victim@example.com", "usr_0123456789abcdef01234567", "bob@example.com"];
32
+
33
+ function fakeEnv(): Env {
34
+ return {
35
+ AI: {
36
+ run: async () => ({ shape: [1, 3], data: [[0.1, 0.2, 0.3]] }),
37
+ },
38
+ VEC: {
39
+ query: async () => ({
40
+ matches: FOREIGN_IDS.map((id, i) => ({ id, score: 0.9 - i * 0.01 })),
41
+ }),
42
+ },
43
+ DB: {
44
+ prepare(sql: string) {
45
+ const isPrefs = sql.includes("user_prefs");
46
+ return {
47
+ bind() {
48
+ return {
49
+ // loadUserPrefs -> gateway credentials, so embedBatch proceeds.
50
+ async first() {
51
+ return isPrefs ? { prefs_json: JSON.stringify({ gateway_id: "alice-gw" }) } : null;
52
+ },
53
+ // The tenant-scoped join finds none of the foreign vectors,
54
+ // which is the branch under test.
55
+ async all() {
56
+ return { results: [] };
57
+ },
58
+ };
59
+ },
60
+ };
61
+ },
62
+ },
63
+ } as unknown as Env;
64
+ }
65
+
66
+ afterEach(() => {
67
+ vi.restoreAllMocks();
68
+ });
69
+
70
+ describe("retrieveContext zero-join diagnostic", () => {
71
+ it("returns a caller-visible message carrying no foreign identity", async () => {
72
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
73
+ const { chunks, error } = await retrieveContext(fakeEnv(), CALLER, "quarterly revenue");
74
+
75
+ expect(chunks).toEqual([]);
76
+
77
+ // ORDER IS LOAD-BEARING. Do not swap these two blocks.
78
+ //
79
+ // The disclosure assertion runs FIRST so that it is the assertion that
80
+ // fires when the defect is present. With the pin first, driving the
81
+ // pre-fix code (888e6bb reversed) reddened this test on the pin's
82
+ // `toBe` line and short-circuited, so the loop below never executed:
83
+ // the suite detected the defect, but the assertion that names it had
84
+ // never been shown capable of failing.
85
+ for (const identity of FOREIGN_IDENTITIES) {
86
+ expect(error).not.toContain(identity);
87
+ }
88
+
89
+ // Pin the exact branch SECOND. This is the anti-vacuity control: on any
90
+ // earlier failure path ("embed failed: ...", "vectorize query failed:
91
+ // ...") the loop above passes for free, because those strings are also
92
+ // free of foreign identities and are not the case under test. Running it
93
+ // after preserves that guarantee while leaving the loop reachable.
94
+ expect(error).toBe("No indexed documents matched the query.");
95
+
96
+ // Control: the harness really did feed foreign ids in, so the absence
97
+ // above is a redaction rather than an empty input.
98
+ expect(warn).toHaveBeenCalled();
99
+ const logged = warn.mock.calls.map((c) => c.join(" ")).join("\n");
100
+ for (const identity of FOREIGN_IDENTITIES) {
101
+ expect(logged).toContain(identity);
102
+ }
103
+ });
104
+
105
+ it("keeps the operator diagnostic intact, not deleted", async () => {
106
+ // The diagnostic is the thing that makes a silent retrieval failure
107
+ // debuggable. The fix is a split, not a removal, and this is what would
108
+ // fail if a later cleanup "simplified" the console.warn away.
109
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
110
+ await retrieveContext(fakeEnv(), CALLER, "quarterly revenue");
111
+
112
+ const logged = warn.mock.calls.map((c) => c.join(" ")).join("\n");
113
+ expect(logged).toContain("sample vector_ids=[");
114
+ expect(logged).toContain("D1 join returned 0");
115
+ expect(logged).toContain(CALLER);
116
+ });
117
+
118
+ it("scopes the project-filtered message the same way", async () => {
119
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
120
+ const { error } = await retrieveContext(fakeEnv(), CALLER, "quarterly revenue", 5, 42);
121
+
122
+ // Same ordering rule as above: disclosure assertion first so it is
123
+ // reachable under the defect, branch pin second as the anti-vacuity
124
+ // control.
125
+ for (const identity of FOREIGN_IDENTITIES) {
126
+ expect(error).not.toContain(identity);
127
+ }
128
+ expect(error).toBe("No indexed documents in this project matched the query.");
129
+ expect(warn).toHaveBeenCalled();
130
+ });
131
+
132
+ it("harness control: the fixture really does supply foreign ids", () => {
133
+ // If FOREIGN_IDS were ever emptied, every not-toContain assertion above
134
+ // would pass while testing nothing.
135
+ expect(FOREIGN_IDS.length).toBeGreaterThan(0);
136
+ expect(FOREIGN_IDENTITIES.length).toBe(FOREIGN_IDS.length);
137
+ for (const id of FOREIGN_IDS) {
138
+ expect(id).toContain(":");
139
+ expect(id.split(":")[0]).not.toBe(CALLER);
140
+ }
141
+ });
142
+ });
@@ -0,0 +1,164 @@
1
+ // The skip link, as an artifact check (fleet-chezmoi#1700).
2
+ //
3
+ // WHAT THIS GUARD CAN SEE: the template and the stylesheet. It is a text read,
4
+ // so it proves the rules and attributes are present and self-consistent.
5
+ //
6
+ // WHAT IT STRUCTURALLY CANNOT SEE, stated here rather than in a PR comment: it
7
+ // cannot prove the focused link is VISIBLE. A `:focus` rule with a non-negative
8
+ // `left` can still be painted under something, clipped, or transparent, and no
9
+ // file read would notice. That half was measured against a real browser with a
10
+ // real Tab press (report on the PR) and stays a separate act. What this guard
11
+ // buys is that the measured state cannot silently regress: every field below
12
+ // was in its failing state before #1700, so the suite has been watched going
13
+ // red on the real defect rather than assumed capable of it.
14
+
15
+ import { readFileSync } from "node:fs";
16
+ import { dirname, join } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { describe, expect, it } from "vitest";
19
+
20
+ const pub = (f: string) =>
21
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), "../public/", f), "utf8");
22
+
23
+ // Anything that takes sequential keyboard focus by default, plus an explicit
24
+ // positive tabindex. Deliberately crude: it only has to find the FIRST one.
25
+ const FOCUSABLE = /<(?:a\s[^>]*href|button|input|select|textarea)\b/i;
26
+
27
+ /** The body, so head <link>/<script> can never be mistaken for page content. */
28
+ function body(html: string): string {
29
+ const m = html.match(/<body[^>]*>([\s\S]*)<\/body>/i);
30
+ if (!m) throw new Error("no <body> in index.html");
31
+ return m[1];
32
+ }
33
+
34
+ /** The declaration block of a rule whose selector matches exactly. */
35
+ function rule(css: string, selector: string): string | null {
36
+ const re = new RegExp(
37
+ `(?:^|})\\s*${selector.replace(/[.#*+?^$()|[\]\\]/g, "\\$&")}\\s*\\{([^}]*)\\}`,
38
+ "m",
39
+ );
40
+ const m = css.match(re);
41
+ return m ? m[1] : null;
42
+ }
43
+
44
+ /** The opening tag that carries id="<id>", or null. */
45
+ function tagWithId(html: string, id: string): string | null {
46
+ const m = html.match(new RegExp(`<[a-z][^>]*\\sid="${id}"[^>]*>`, "i"));
47
+ return m ? m[0] : null;
48
+ }
49
+
50
+ describe("control: the matchers discriminate", () => {
51
+ it("FOCUSABLE fires on focusable markup and not on inert markup", () => {
52
+ expect(FOCUSABLE.test('<a href="#x">y</a>')).toBe(true);
53
+ expect(FOCUSABLE.test("<button type=\"button\">y</button>")).toBe(true);
54
+ expect(FOCUSABLE.test('<input id="u">')).toBe(true);
55
+ // The negative half: these must NOT read as a focus stop, or "the skip link
56
+ // is first" would pass on a page where it is not.
57
+ expect(FOCUSABLE.test("<div><span>hello</span><!-- a comment --></div>")).toBe(false);
58
+ expect(FOCUSABLE.test('<a name="anchor">no href</a>')).toBe(false);
59
+ });
60
+
61
+ it("rule() extracts the block it names and not a longhand neighbour", () => {
62
+ const css = ".skip-link { left: -9999px; }\n.skip-link:focus { left: 8px; }\n";
63
+ expect(rule(css, ".skip-link")).toContain("-9999px");
64
+ expect(rule(css, ".skip-link")).not.toContain("8px");
65
+ expect(rule(css, ".skip-link:focus")).toContain("8px");
66
+ expect(rule(css, ".nope")).toBeNull();
67
+ });
68
+
69
+ it("tagWithId finds the tag and reports a missing id as missing", () => {
70
+ expect(tagWithId('<main class="c" id="main-content" tabindex="-1">', "main-content"))
71
+ .toContain("tabindex");
72
+ expect(tagWithId("<main>", "main-content")).toBeNull();
73
+ });
74
+ });
75
+
76
+ describe("the skip link is the first thing a keyboard user reaches", () => {
77
+ it("is the first focusable element in the body", () => {
78
+ const b = body(pub("index.html"));
79
+ const at = b.search(FOCUSABLE);
80
+ expect(at).toBeGreaterThan(-1);
81
+ // The first focus stop in the document is the skip link itself.
82
+ expect(b.slice(at, at + 200)).toContain('class="skip-link"');
83
+ });
84
+
85
+ it("has a non-empty text label, so the focus stop is identifiable", () => {
86
+ const m = pub("index.html").match(/<a class="skip-link"[^>]*>([^<]*)<\/a>/);
87
+ expect(m).not.toBeNull();
88
+ const label = (m as RegExpMatchArray)[1].trim();
89
+ expect(label.length).toBeGreaterThan(0);
90
+ // An `aria-hidden` skip link would be a focus stop with no name at all.
91
+ expect(pub("index.html")).not.toMatch(/<a class="skip-link"[^>]*aria-hidden/);
92
+ });
93
+ });
94
+
95
+ describe("the skip link goes somewhere that exists and is rendered", () => {
96
+ const html = pub("index.html");
97
+ const href = (html.match(/<a class="skip-link"[^>]*href="#([^"]+)"/) || [])[1];
98
+
99
+ it("targets a same-document fragment", () => {
100
+ expect(href).toBeTruthy();
101
+ });
102
+
103
+ it("the target id is present in the document", () => {
104
+ expect(tagWithId(html, href as string)).not.toBeNull();
105
+ });
106
+
107
+ // The defect this one exists for: the link used to point at #auth-screen,
108
+ // which carries `hidden` and is revealed only in public mode with no session.
109
+ // On every signed-in page it therefore aimed focus at a hidden element.
110
+ it("the target is not hidden by default", () => {
111
+ const tag = tagWithId(html, href as string) as string;
112
+ expect(tag).not.toMatch(/\shidden(\s|>|=)/);
113
+ });
114
+
115
+ it("the target accepts programmatic focus", () => {
116
+ const tag = tagWithId(html, href as string) as string;
117
+ expect(tag).toMatch(/tabindex="-1"/);
118
+ });
119
+ });
120
+
121
+ describe("focus moves the link on-screen", () => {
122
+ const css = pub("styles.css");
123
+
124
+ // The #177 / fc#1646 CSP invariant: the offscreen positioning is a stylesheet
125
+ // rule, never an inline style attribute. Enforcing style-src-attr drops the
126
+ // attribute and renders the link on the page.
127
+ it("the offscreen positioning is in the stylesheet", () => {
128
+ const base = rule(css, ".skip-link");
129
+ expect(base).not.toBeNull();
130
+ expect(base as string).toMatch(/position:\s*absolute/);
131
+ expect(base as string).toMatch(/left:\s*-9999px/);
132
+ expect(pub("index.html")).not.toMatch(/<a class="skip-link"[^>]*\sstyle\s*=/);
133
+ });
134
+
135
+ // The whole point of #1700. Before the fix there was NO :focus rule at all,
136
+ // and the element's box was measured still at x = -9999 after .focus().
137
+ it("a :focus rule exists and its left is not offscreen", () => {
138
+ const focused = rule(css, ".skip-link:focus");
139
+ expect(focused).not.toBeNull();
140
+ const left = (focused as string).match(/left:\s*(-?[\d.]+)/);
141
+ expect(left).not.toBeNull();
142
+ expect(Number((left as RegExpMatchArray)[1])).toBeGreaterThanOrEqual(0);
143
+ });
144
+
145
+ it("the revealed link is painted above the auth screen and the sidebar", () => {
146
+ const base = rule(css, ".skip-link") as string;
147
+ const z = base.match(/z-index:\s*(\d+)/);
148
+ expect(z).not.toBeNull();
149
+ // .auth-screen is z-index 100; a reveal underneath it is not a reveal.
150
+ expect(Number((z as RegExpMatchArray)[1])).toBeGreaterThan(100);
151
+ });
152
+ });
153
+
154
+ describe("the auth gate state has no block to bypass", () => {
155
+ // body.auth-active .layout is display:none, so the sidebar and the skip
156
+ // target are both out of the layout. A skip link there would be a focus stop
157
+ // pointing at nothing, which is the defect #1700 fixed, re-introduced.
158
+ it("the skip link leaves the tab order while the auth gate is up", () => {
159
+ const css = pub("styles.css");
160
+ expect(rule(css, "body.auth-active .skip-link")).toMatch(/display:\s*none/);
161
+ // Control: the rule this one depends on is still what makes the shell absent.
162
+ expect(rule(css, "body.auth-active .layout")).toMatch(/display:\s*none/);
163
+ });
164
+ });
@@ -0,0 +1,166 @@
1
+ // scripts/vectorize-backfill-metadata.mjs (skyphusion-labs/fleet-chezmoi#1636): the refusals, the
2
+ // counts, and that it never surfaces an id. The REST client is driven through a recording fetch.
3
+
4
+ import { describe, it, expect } from "vitest";
5
+ import {
6
+ backfill,
7
+ client,
8
+ hasUserEmailIndex,
9
+ parseArgs,
10
+ type BackfillApi,
11
+ type Vec,
12
+ } from "../scripts/vectorize-backfill-metadata.mjs";
13
+
14
+ const IDX = [{ propertyName: "user_email", indexType: "String" }];
15
+ const vec = (id: string, owner: string | null = "usr_a"): Vec => ({
16
+ id,
17
+ values: [0.1, 0.2],
18
+ metadata: owner === null ? { document_id: 1 } : { user_email: owner, document_id: 1 },
19
+ });
20
+
21
+ function fakeApi(over: Partial<BackfillApi> & { stored?: Vec[] } = {}) {
22
+ const stored = over.stored ?? [];
23
+ const calls = { getByIds: [] as string[][], upsert: [] as Vec[][], ids: 0 };
24
+ const api: BackfillApi = {
25
+ metadataIndexes: over.metadataIndexes ?? (async () => IDX),
26
+ vectorIds: async () => [],
27
+ getByIds:
28
+ over.getByIds ??
29
+ (async (_i, ids) => {
30
+ calls.getByIds.push(ids);
31
+ return stored.filter((v) => ids.includes(v.id));
32
+ }),
33
+ upsert:
34
+ over.upsert ??
35
+ (async (_i, vs) => {
36
+ calls.upsert.push(vs);
37
+ }),
38
+ };
39
+ return { api, calls };
40
+ }
41
+
42
+ const run = (api: BackfillApi, ids: string[], extra: Partial<{ dryRun: boolean; batch: number }> = {}) =>
43
+ backfill(api, { index: "ix", d1: "db", dryRun: false, batch: 20, ...extra, idsFrom: async () => ids });
44
+
45
+ describe("refusals: nothing is written", () => {
46
+ it("refuses (2) when there is no user_email metadata index, and never reads the ids", async () => {
47
+ let read = false;
48
+ const { api, calls } = fakeApi({ metadataIndexes: async () => [] });
49
+ const r = await backfill(api, { index: "ix", d1: "db", dryRun: false, batch: 20, idsFrom: async () => ((read = true), ["a"]) });
50
+ expect(r.code).toBe(2);
51
+ expect(r.refusal).toMatch(/create-metadata-index ix --property-name=user_email --type=string/);
52
+ expect(read).toBe(false);
53
+ expect(calls.upsert).toEqual([]);
54
+ });
55
+
56
+ it("refuses when the index exists on user_email but is not a string index", async () => {
57
+ expect(hasUserEmailIndex([{ propertyName: "user_email", indexType: "Number" }])).toBe(false);
58
+ const { api, calls } = fakeApi({ metadataIndexes: async () => [{ propertyName: "user_email", indexType: "Number" }] });
59
+ expect((await run(api, ["a"])).code).toBe(2);
60
+ expect(calls.upsert).toEqual([]);
61
+ });
62
+
63
+ it("refuses when the metadata index list cannot be read", async () => {
64
+ const { api } = fakeApi({ metadataIndexes: async () => { throw new Error("HTTP 403"); } });
65
+ expect((await run(api, ["a"])).code).toBe(2);
66
+ });
67
+
68
+ it("refuses when the D1 ids cannot be read", async () => {
69
+ const { api, calls } = fakeApi();
70
+ const r = await backfill(api, { index: "ix", d1: "db", dryRun: false, batch: 20, idsFrom: async () => { throw new Error("d1"); } });
71
+ expect(r.code).toBe(2);
72
+ expect(calls.upsert).toEqual([]);
73
+ });
74
+ });
75
+
76
+ describe("the backfill", () => {
77
+ it("COMPLETE (0): every D1 id is fetched and written back with the same id, values and metadata", async () => {
78
+ const stored = [vec("a"), vec("b"), vec("c")];
79
+ const { api, calls } = fakeApi({ stored });
80
+ const r = await run(api, ["a", "b", "c"]);
81
+ expect(r).toMatchObject({ code: 0, counts: { d1_ids: 3, fetched: 3, upserted: 3, gaps: 0, missing_metadata: 0 } });
82
+ expect(calls.upsert.flat()).toEqual(stored);
83
+ });
84
+
85
+ it("a D1 id Vectorize cannot return is a GAP (1), never skipped silently; the rest still land", async () => {
86
+ const { api, calls } = fakeApi({ stored: [vec("a"), vec("c")] });
87
+ const r = await run(api, ["a", "b", "c"]);
88
+ expect(r).toMatchObject({ code: 1, counts: { d1_ids: 3, fetched: 2, gaps: 1, upserted: 2 } });
89
+ expect(calls.upsert.flat().map((v) => v.id)).toEqual(["a", "c"]);
90
+ });
91
+
92
+ it("a vector with no user_email metadata is counted (1) and not re-upserted", async () => {
93
+ const { api, calls } = fakeApi({ stored: [vec("a"), vec("b", null)] });
94
+ const r = await run(api, ["a", "b"]);
95
+ expect(r).toMatchObject({ code: 1, counts: { missing_metadata: 1, upserted: 1 } });
96
+ expect(calls.upsert.flat().map((v) => v.id)).toEqual(["a"]);
97
+ });
98
+
99
+ it("--dry-run writes nothing and reports what it would do", async () => {
100
+ const { api, calls } = fakeApi({ stored: [vec("a")] });
101
+ const r = await run(api, ["a"], { dryRun: true });
102
+ expect(r).toMatchObject({ code: 0, counts: { fetched: 1, upserted: 0 } });
103
+ expect(calls.upsert).toEqual([]);
104
+ });
105
+
106
+ it("batches by --batch", async () => {
107
+ const ids = ["a", "b", "c", "d", "e"];
108
+ const { api, calls } = fakeApi({ stored: ids.map((i) => vec(i)) });
109
+ await run(api, ids, { batch: 2 });
110
+ expect(calls.getByIds).toEqual([["a", "b"], ["c", "d"], ["e"]]);
111
+ });
112
+
113
+ it("the result carries counts only: no id, no value, no metadata value", async () => {
114
+ const secretId = "someone@example.com:7:0";
115
+ const { api } = fakeApi({ stored: [vec(secretId, "someone@example.com")] });
116
+ const r = await run(api, [secretId, "missing@example.com:1:0"]);
117
+ const out = JSON.stringify(r);
118
+ expect(out).not.toContain("example.com");
119
+ expect(out).not.toContain("0.1");
120
+ });
121
+ });
122
+
123
+ describe("parseArgs", () => {
124
+ it("requires --index and --d1, and bounds --batch", () => {
125
+ expect(parseArgs(["--index", "ix", "--d1", "db"])).toEqual({ index: "ix", d1: "db", dryRun: false, batch: 20 });
126
+ expect(() => parseArgs(["--d1", "db"])).toThrow(/--index/);
127
+ expect(() => parseArgs(["--index", "ix"])).toThrow(/--d1/);
128
+ expect(() => parseArgs(["--index", "ix", "--d1", "db", "--batch", "0"])).toThrow(/--batch/);
129
+ expect(() => parseArgs(["--index", "ix", "--d1", "db", "--nope"])).toThrow(/unknown/);
130
+ });
131
+ });
132
+
133
+ describe("client: the REST wire shapes", () => {
134
+ function recorder(results: Record<string, unknown>) {
135
+ const seen: { url: string; method?: string; type?: string | null; body?: string }[] = [];
136
+ const fetchImpl = (async (url: string, init: RequestInit = {}) => {
137
+ seen.push({ url, method: init.method, type: new Headers(init.headers).get("content-type"), body: init.body as string });
138
+ const key = Object.keys(results).find((k) => url.endsWith(k))!;
139
+ return new Response(JSON.stringify({ success: true, result: results[key] }), { status: 200 });
140
+ }) as unknown as typeof fetch;
141
+ return { seen, api: client({ token: "t", accountId: "acct", fetchImpl }) };
142
+ }
143
+
144
+ it("reads metadata indexes, D1 ids, get_by_ids, and upserts NDJSON", async () => {
145
+ const { seen, api } = recorder({
146
+ "/metadata_index/list": { metadataIndexes: IDX },
147
+ "/query": [{ results: [{ vector_id: "a" }, { vector_id: "b" }] }],
148
+ "/get_by_ids": [vec("a")],
149
+ "/upsert": { mutationId: "m" },
150
+ });
151
+ expect(await api.metadataIndexes("ix")).toEqual(IDX);
152
+ expect(await api.vectorIds("db")).toEqual(["a", "b"]);
153
+ expect(await api.getByIds("ix", ["a"])).toEqual([vec("a")]);
154
+ await api.upsert("ix", [vec("a"), vec("b")]);
155
+ const up = seen.find((s) => s.url.endsWith("/upsert"))!;
156
+ expect(up.url).toBe("https://api.cloudflare.com/client/v4/accounts/acct/vectorize/v2/indexes/ix/upsert");
157
+ expect(up.type).toBe("application/x-ndjson");
158
+ expect(up.body!.split("\n").map((l) => JSON.parse(l).id)).toEqual(["a", "b"]);
159
+ expect(seen.find((s) => s.url.endsWith("/query"))!.url).toBe("https://api.cloudflare.com/client/v4/accounts/acct/d1/database/db/query");
160
+ });
161
+
162
+ it("throws on a failed call rather than returning an empty answer", async () => {
163
+ const fetchImpl = (async () => new Response(JSON.stringify({ success: false, errors: [] }), { status: 403 })) as unknown as typeof fetch;
164
+ await expect(client({ token: "t", accountId: "a", fetchImpl }).metadataIndexes("ix")).rejects.toThrow(/HTTP 403/);
165
+ });
166
+ });
@@ -0,0 +1,47 @@
1
+ // The version this Worker advertises must equal the version in package.json.
2
+ //
3
+ // THE EXPECTED VALUE IS DERIVED, NEVER TRANSCRIBED. This file reads package.json off disk and
4
+ // parses it; it does not carry a second hand-typed copy of the version string. That distinction
5
+ // is the whole reason this test is worth having. In prism-mcp the advertised version was a
6
+ // literal and the test asserting it carried a transcribed duplicate of the same string, so the
7
+ // assertion only ever proved that someone had typed the same thing twice -- and a correct
8
+ // version bump went red because one copy was updated and the other was not.
9
+ //
10
+ // SCOPE: this file owns "the literal agrees with package.json". Whether the Worker actually PUTS
11
+ // that value on the wire is a separate failure mode, asserted against the real fetch handler in
12
+ // tests-integration/worker.test.ts. Two assertions, two mutations: breaking the literal reddens
13
+ // this file and leaves the integration suite green; removing the field from the /health payload
14
+ // reddens the integration suite and leaves this file green. That pairing is what proves they are
15
+ // two assertions rather than one check wearing two names.
16
+ //
17
+ // This lives in the NODE project (vitest.node.config.ts) rather than the workers one because it
18
+ // reads the filesystem, which workerd has no business doing. The split is load-bearing for the
19
+ // pairing above, not incidental.
20
+
21
+ import { readFileSync } from "node:fs";
22
+ import { dirname, join } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import { describe, expect, it } from "vitest";
25
+ import { VERSION } from "../src/version";
26
+
27
+ // Anchored to THIS FILE, not to process.cwd(): a suite run from a scratch worktree must read the
28
+ // package.json that sits beside the source it is asserting about, not whichever one the working
29
+ // directory happens to point at.
30
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
31
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as { name?: string; version?: string };
32
+
33
+ describe("advertised version", () => {
34
+ // POSITIVE CONTROL, and it runs first on purpose: if package.json moved, was renamed, or
35
+ // stopped parsing, `pkg.version` is undefined and every assertion below would compare against
36
+ // nothing. An undefined expected value makes a drift test fail for a reason that has nothing to
37
+ // do with drift, so name that failure separately rather than letting it wear drift's clothes. A
38
+ // broken reader must not be able to look like either a pass or a version mismatch.
39
+ it("reads a real version out of package.json (control: the reader is not blind)", () => {
40
+ expect(pkg.name).toBe("prism");
41
+ expect(pkg.version).toMatch(/^\d+\.\d+\.\d+/);
42
+ });
43
+
44
+ it("matches package.json, so a release bump cannot leave the wire behind", () => {
45
+ expect(VERSION).toBe(pkg.version);
46
+ });
47
+ });