@skyphusion/create-prism 1.0.4 → 1.3.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 (45) hide show
  1. package/README.md +10 -8
  2. package/index.js +3 -2
  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 +79 -52
  7. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +5 -2
  8. package/template/docs/legal/INSTANCE-PRIVACY.md +128 -27
  9. package/template/migrations/0005_auth_attempts_retention.sql +23 -0
  10. package/template/package.json +6 -6
  11. package/template/public/app.js +21 -8
  12. package/template/public/index.html +23 -9
  13. package/template/public/styles.css +45 -7
  14. package/template/public/url-safety.js +6 -6
  15. package/template/schema.sql +6 -0
  16. package/template/src/ai-binding.ts +125 -3
  17. package/template/src/auth.ts +6 -0
  18. package/template/src/env.ts +38 -10
  19. package/template/src/gateway-credentials.ts +118 -22
  20. package/template/src/index.ts +2 -0
  21. package/template/src/providers/anthropic.ts +4 -4
  22. package/template/src/providers/openai-image.ts +10 -0
  23. package/template/src/providers/xai.ts +4 -4
  24. package/template/src/rate-limit.ts +26 -0
  25. package/template/src/routes/chat.ts +18 -9
  26. package/template/src/routes/prefs.ts +46 -5
  27. package/template/src/routes/rag.ts +135 -61
  28. package/template/src/routes/shared.ts +27 -11
  29. package/template/src/routes/workflow.ts +2 -5
  30. package/template/src/skyphusion-search.ts +108 -0
  31. package/template/src/user-prefs.ts +16 -3
  32. package/template/src/version.ts +1 -1
  33. package/template/tests/ai-binding-rest.test.ts +154 -0
  34. package/template/tests/csp.test.ts +11 -6
  35. package/template/tests/gateway-credentials.test.ts +101 -3
  36. package/template/tests/openai-image.test.ts +21 -1
  37. package/template/tests/rag-metadata-filter.test.ts +135 -0
  38. package/template/tests/skip-link.test.ts +164 -0
  39. package/template/tests/skyphusion-search.test.ts +144 -0
  40. package/template/tests/vectorize-backfill-metadata.test.ts +166 -0
  41. package/template/tests-integration/auth.test.ts +346 -2
  42. package/template/tests-integration/pdf-extract.test.ts +71 -0
  43. package/template/wrangler.example.toml +26 -11
  44. package/template/src/searxng.ts +0 -75
  45. package/template/tests/searxng.test.ts +0 -51
@@ -0,0 +1,144 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import type { Env } from "../src/env";
3
+ import { searchWeb } from "../src/routes/rag";
4
+ import { mapSearchChunks } from "../src/skyphusion-search";
5
+
6
+ const RPC_ERRORS = [
7
+ "empty_question",
8
+ "question_too_long",
9
+ "rate_limited",
10
+ "search_unavailable",
11
+ ] as const;
12
+
13
+ const WIKI_HIT = {
14
+ query: {
15
+ search: [{ title: "Ada Lovelace", snippet: "Mathematician", pageid: 42 }],
16
+ },
17
+ };
18
+
19
+ const CHUNK = {
20
+ text: " prism workers ",
21
+ score: 0.42,
22
+ item: {
23
+ key: "prism/README.md.txt",
24
+ metadata: { repo: "prism", path: "README.md" },
25
+ },
26
+ };
27
+
28
+ function wikiResponse(): Response {
29
+ return new Response(JSON.stringify(WIKI_HIT), {
30
+ status: 200,
31
+ headers: { "content-type": "application/json" },
32
+ });
33
+ }
34
+
35
+ function installWikipediaFetch() {
36
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
37
+ const url = typeof input === "string"
38
+ ? input
39
+ : input instanceof URL
40
+ ? input.toString()
41
+ : input.url;
42
+ if (!url.includes("https://en.wikipedia.org/w/api.php")) {
43
+ throw new Error(`unexpected global fetch: ${url}`);
44
+ }
45
+ return wikiResponse();
46
+ });
47
+ vi.stubGlobal("fetch", fetchMock);
48
+ return fetchMock;
49
+ }
50
+
51
+ function binding(search: (question: string) => Promise<{ chunks: unknown[] }>): Env {
52
+ return { SEARCH: { search } } as unknown as Env;
53
+ }
54
+
55
+ afterEach(() => {
56
+ vi.unstubAllGlobals();
57
+ vi.restoreAllMocks();
58
+ });
59
+
60
+ describe("mapSearchChunks", () => {
61
+ it("maps a chunk to a github blob link", () => {
62
+ expect(mapSearchChunks([CHUNK], 5)).toEqual([{
63
+ title: "prism/README.md",
64
+ url: "https://github.com/skyphusion-labs/prism/blob/main/README.md",
65
+ snippet: "prism workers",
66
+ score: 0.42,
67
+ }]);
68
+ });
69
+
70
+ it("drops a chunk whose path is not a safe corpus path", () => {
71
+ expect(mapSearchChunks([{
72
+ text: "nope",
73
+ item: { key: "prism/../etc/passwd", metadata: { repo: "prism", path: "../etc/passwd" } },
74
+ }], 5)).toEqual([]);
75
+ });
76
+ });
77
+
78
+ describe("searchWeb sources", () => {
79
+ it("binding returns hits", async () => {
80
+ const wiki = installWikipediaFetch();
81
+ const search = vi.fn(async (_question: string) => ({ chunks: [CHUNK] }));
82
+ const out = await searchWeb(binding(search), "prism workers");
83
+ expect(search).toHaveBeenCalledTimes(1);
84
+ expect(search.mock.calls[0]).toEqual(["prism workers"]);
85
+ expect(out.error).toBeNull();
86
+ expect(out.sources.web).toEqual({ status: "ok", count: 1 });
87
+ expect(out.sources.wikipedia.status).toBe("ok");
88
+ expect(out.sources.wikipedia.count).toBe(1);
89
+ expect(out.results.map((r) => r.source)).toEqual(["skyphusion-search", "wikipedia"]);
90
+ expect(out.results[0]).toMatchObject({
91
+ title: "prism/README.md",
92
+ url: "https://github.com/skyphusion-labs/prism/blob/main/README.md",
93
+ snippet: "prism workers",
94
+ });
95
+ expect(out.results[1]).toMatchObject({
96
+ title: "Ada Lovelace",
97
+ url: "https://en.wikipedia.org/?curid=42",
98
+ });
99
+ expect(wiki).toHaveBeenCalled();
100
+ });
101
+
102
+ it.each(RPC_ERRORS)("%s: web source failed, Wikipedia still answers", async (code) => {
103
+ const wiki = installWikipediaFetch();
104
+ const search = vi.fn(async () => {
105
+ throw new Error(code);
106
+ });
107
+ const out = await searchWeb(binding(search), "prism workers");
108
+ expect(search).toHaveBeenCalledTimes(1);
109
+ expect(out.sources.web).toEqual({ status: "failed", count: 0, error: code });
110
+ expect(out.error).toBe(code);
111
+ expect(out.sources.wikipedia).toEqual({ status: "ok", count: 1 });
112
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
113
+ expect(wiki).toHaveBeenCalled();
114
+ });
115
+
116
+ it("a thrown binding is failed and does not clear Wikipedia", async () => {
117
+ installWikipediaFetch();
118
+ const env = binding(async () => {
119
+ throw new Error("binding down");
120
+ });
121
+ const out = await searchWeb(env, "prism workers");
122
+ expect(out.sources.web).toEqual({ status: "failed", count: 0, error: "binding down" });
123
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
124
+ });
125
+
126
+ it("binding absent is not a failure and not zero hits", async () => {
127
+ const wiki = installWikipediaFetch();
128
+ const out = await searchWeb({} as Env, "prism workers");
129
+ expect(out.sources.web).toEqual({ status: "absent", count: 0 });
130
+ expect(out.error).toBeNull();
131
+ expect(out.sources.wikipedia).toEqual({ status: "ok", count: 1 });
132
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
133
+ expect(wiki).toHaveBeenCalled();
134
+ });
135
+
136
+ it("an empty chunks array is zero hits, not a failure", async () => {
137
+ installWikipediaFetch();
138
+ const env = binding(async () => ({ chunks: [] }));
139
+ const out = await searchWeb(env, "prism workers");
140
+ expect(out.sources.web).toEqual({ status: "ok", count: 0 });
141
+ expect(out.error).toBeNull();
142
+ expect(out.results.map((r) => r.source)).toEqual(["wikipedia"]);
143
+ });
144
+ });
@@ -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
+ });