@skyphusion/create-prism 0.1.0 → 0.175.6

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 +5 -3
  2. package/index.js +4 -2
  3. package/package.json +1 -1
  4. package/template/CONTRIBUTING.md +6 -2
  5. package/template/README.md +45 -33
  6. package/template/docs/legal/README.md +1 -0
  7. package/template/migrations/0002_auth_public_mode.sql +32 -0
  8. package/template/package.json +6 -6
  9. package/template/public/app.js +44 -16
  10. package/template/public/index.html +47 -4
  11. package/template/src/auth-kdf.ts +7 -4
  12. package/template/src/auth.ts +11 -2
  13. package/template/src/control-plane.ts +254 -0
  14. package/template/src/env.ts +15 -0
  15. package/template/src/gateway-credentials.ts +23 -4
  16. package/template/src/health-schema.ts +4 -0
  17. package/template/src/index.ts +65 -3982
  18. package/template/src/longrun-params.ts +4 -2
  19. package/template/src/models.ts +65 -19
  20. package/template/src/output-extract.ts +58 -8
  21. package/template/src/parsers/openai-sse.ts +43 -14
  22. package/template/src/providers/anthropic.ts +105 -0
  23. package/template/src/providers/openai-image.ts +66 -0
  24. package/template/src/providers/openai.ts +79 -13
  25. package/template/src/providers/xai.ts +91 -0
  26. package/template/src/proxied-image-params.ts +29 -16
  27. package/template/src/routes/artifacts.ts +51 -0
  28. package/template/src/routes/chat.ts +1709 -0
  29. package/template/src/routes/conversations.ts +212 -0
  30. package/template/src/routes/documents.ts +262 -0
  31. package/template/src/routes/health.ts +105 -0
  32. package/template/src/routes/history.ts +92 -0
  33. package/template/src/routes/prefs.ts +95 -0
  34. package/template/src/routes/projects.ts +574 -0
  35. package/template/src/routes/rag.ts +657 -0
  36. package/template/src/routes/shared.ts +226 -0
  37. package/template/src/routes/workflow.ts +304 -0
  38. package/template/src/user-prefs.ts +10 -0
  39. package/template/src/zip.ts +7 -0
  40. package/template/tests/anthropic-binding.test.ts +181 -0
  41. package/template/tests/control-plane.test.ts +112 -0
  42. package/template/tests/gateway-credentials.test.ts +37 -0
  43. package/template/tests/longrun-params.test.ts +19 -0
  44. package/template/tests/openai-image.test.ts +47 -0
  45. package/template/tests/openai-responses.test.ts +78 -0
  46. package/template/tests/openai-sse.test.ts +28 -0
  47. package/template/tests/output-extract.test.ts +75 -1
  48. package/template/tests/proxied-image-params.test.ts +16 -7
  49. package/template/tests/sprint1-catalog.test.ts +27 -0
  50. package/template/tests/sprint2-catalog.test.ts +51 -0
  51. package/template/tests/sprint3-catalog.test.ts +29 -0
  52. package/template/tests/xai-binding.test.ts +127 -0
  53. package/template/tests-integration/worker.test.ts +9 -2
  54. package/template/wrangler.example.toml +19 -7
@@ -0,0 +1,95 @@
1
+ // Per-user AI Gateway preference routes (GET/PATCH /api/prefs). Stores the
2
+ // user gateway slug + Unified Billing token in D1 user_prefs; the token is
3
+ // never echoed back raw (maskSecret). Optional control_plane_key (pcp_) for
4
+ // metered chat via allowlisted play-proxy (URL is never user-set).
5
+
6
+ import type { Env } from "../env";
7
+ import { loadUserPrefs, saveUserPrefs, type UserPrefsJson } from "../user-prefs";
8
+ import { loadGatewayStatus, maskSecret } from "../gateway-credentials";
9
+ import {
10
+ DEFAULT_CONTROL_PLANE_URL,
11
+ looksLikeClientKey,
12
+ resolveControlPlane,
13
+ } from "../control-plane";
14
+ import { json, getUserEmail } from "./shared";
15
+
16
+ function controlPlaneStatus(prefs: UserPrefsJson | null, env: Env) {
17
+ const cp = resolveControlPlane(prefs, env);
18
+ return {
19
+ control_plane_configured: !!cp,
20
+ // Display-only origin (from worker config / default); not editable by the user.
21
+ control_plane_url: cp?.baseUrl ?? DEFAULT_CONTROL_PLANE_URL,
22
+ control_plane_key_set: !!prefs?.control_plane_key?.trim(),
23
+ control_plane_key_preview: maskSecret(prefs?.control_plane_key),
24
+ };
25
+ }
26
+
27
+ export async function handlePrefsGet(request: Request, env: Env): Promise<Response> {
28
+ const userEmail = await getUserEmail(request, env);
29
+ const prefs = await loadUserPrefs(env.DB, userEmail);
30
+ const status = await loadGatewayStatus(env, userEmail);
31
+ return json({
32
+ gateway_id: status.gateway_id,
33
+ cf_aig_token_set: status.cf_aig_token_set,
34
+ cf_aig_token_preview: maskSecret(prefs?.cf_aig_token),
35
+ configured: status.configured || !!resolveControlPlane(prefs, env),
36
+ source: status.source,
37
+ ...controlPlaneStatus(prefs, env),
38
+ });
39
+ }
40
+
41
+ export async function handlePrefsPatch(request: Request, env: Env): Promise<Response> {
42
+ const userEmail = await getUserEmail(request, env);
43
+ let body: {
44
+ gateway_id?: string;
45
+ cf_aig_token?: string;
46
+ clear_cf_aig_token?: boolean;
47
+ control_plane_key?: string;
48
+ clear_control_plane_key?: boolean;
49
+ };
50
+ try {
51
+ body = await request.json();
52
+ } catch {
53
+ return json({ error: "Invalid JSON" }, { status: 400 });
54
+ }
55
+
56
+ const patch: UserPrefsJson = {};
57
+ if (body.gateway_id !== undefined) patch.gateway_id = body.gateway_id;
58
+ if (body.cf_aig_token !== undefined) patch.cf_aig_token = body.cf_aig_token;
59
+ if (body.clear_cf_aig_token) patch.cf_aig_token = "";
60
+ if (body.control_plane_key !== undefined) {
61
+ const k = body.control_plane_key.trim();
62
+ if (k && !looksLikeClientKey(k)) {
63
+ return json(
64
+ {
65
+ error:
66
+ "control_plane_key must be a prism-control-plane client key (pcp_<16 hex>_<43 base64url>).",
67
+ code: "invalid_control_plane_key",
68
+ },
69
+ { status: 400 },
70
+ );
71
+ }
72
+ patch.control_plane_key = k;
73
+ }
74
+ if (body.clear_control_plane_key) patch.control_plane_key = "";
75
+
76
+ if (Object.keys(patch).length === 0) {
77
+ return json(
78
+ {
79
+ error: "Provide gateway_id, cf_aig_token, and/or control_plane_key to update",
80
+ },
81
+ { status: 400 },
82
+ );
83
+ }
84
+
85
+ const merged = await saveUserPrefs(env.DB, userEmail, patch);
86
+ const status = await loadGatewayStatus(env, userEmail);
87
+ return json({
88
+ gateway_id: status.gateway_id,
89
+ cf_aig_token_set: status.cf_aig_token_set,
90
+ cf_aig_token_preview: maskSecret(merged.cf_aig_token),
91
+ configured: status.configured || !!resolveControlPlane(merged, env),
92
+ source: status.source,
93
+ ...controlPlaneStatus(merged, env),
94
+ });
95
+ }
@@ -0,0 +1,574 @@
1
+ // Project routes: CRUD, document membership add/remove, and DiscordChatExporter
2
+ // import into a project. Also owns resolveProjectForChat (the per-project
3
+ // system-prompt fallback + RAG scope resolution) used by the chat routes.
4
+
5
+ import type { Env } from "../env";
6
+ import { parseDataUrl, base64ToBytes } from "../utils";
7
+ import { parseDiscordExport, chunkDiscordMessages } from "../discord";
8
+ import { json, getUserEmail, r2Put, r2DeleteSafe } from "./shared";
9
+ import type { ChatRequest } from "./shared";
10
+ import { embedBatch, DOC_MAX_BYTES, EMBED_BATCH_SIZE } from "./rag";
11
+
12
+ // v0.20.0: project + project_documents join. A project groups documents
13
+ // (and in v0.20.1, conversations) under a shared system_prompt and
14
+ // retrieval scope. Many-to-many membership via project_documents.
15
+ export interface ProjectRow {
16
+ id: number;
17
+ user_email: string;
18
+ name: string;
19
+ slug: string;
20
+ description: string | null;
21
+ system_prompt: string | null;
22
+ created_at: string;
23
+ updated_at: string;
24
+ }
25
+
26
+ // ---------- Projects (v0.20.0) ----------
27
+ //
28
+ // Projects group documents (and in v0.20.1 onward, conversations) under a
29
+ // shared system_prompt and retrieval scope. v0.20.0 endpoints:
30
+ //
31
+ // GET /api/projects list user's projects
32
+ // POST /api/projects create project
33
+ // GET /api/projects/:id get project + members
34
+ // PATCH /api/projects/:id rename / update prompt / desc
35
+ // DELETE /api/projects/:id delete (cascades to memberships)
36
+ // POST /api/projects/:pid/documents/:did add document to project
37
+ // DELETE /api/projects/:pid/documents/:did remove document from project
38
+ // GET /api/documents?project_id=N list docs in project
39
+ //
40
+ // All endpoints scope by user_email; cross-user reads return 404,
41
+ // cross-user writes (e.g. adding another user's doc to your project) are
42
+ // rejected with 400 before touching the DB.
43
+ //
44
+ // Per-project system prompt fallback (handleChat / handleChatStream):
45
+ // when a chat request includes project_id but no per-turn system_prompt,
46
+ // the project's system_prompt is used as default. A per-turn system_prompt
47
+ // always overrides; empty-string system_prompt counts as "set to empty"
48
+ // and disables the fallback (intentional - lets users explicitly clear).
49
+ //
50
+ // Per-project RAG scoping (retrieveContext): when a chat request includes
51
+ // project_id, retrieval joins project_documents and excludes chunks from
52
+ // documents not in that project's membership set. No project_id means
53
+ // "all user's docs" (backward compat).
54
+
55
+ // Generate a URL-safe slug from a display name. Strips non-alphanumeric
56
+ // characters, collapses runs of whitespace and dashes, lowercases, trims.
57
+ // Empty input or all-punctuation input falls back to "project".
58
+ export function slugify(name: string): string {
59
+ const s = name
60
+ .toLowerCase()
61
+ .normalize("NFKD")
62
+ .replace(/[^a-z0-9\s-]+/g, "") // drop punctuation/diacritics
63
+ .trim()
64
+ .replace(/[\s-]+/g, "-") // collapse whitespace runs to single dash
65
+ .replace(/^-+|-+$/g, ""); // trim leading/trailing dashes
66
+ return s || "project";
67
+ }
68
+
69
+ // Find an unused slug for the user. If `base` is unused, returns base.
70
+ // Otherwise appends -2, -3, ... until free. Bounded at 200 attempts;
71
+ // beyond that we throw, which would indicate a degenerate slug or a
72
+ // pathological state.
73
+ export async function findFreeSlug(env: Env, userEmail: string, base: string): Promise<string> {
74
+ let candidate = base;
75
+ let suffix = 2;
76
+ while (suffix < 200) {
77
+ const existing = await env.DB.prepare(
78
+ `SELECT id FROM projects WHERE user_email = ? AND slug = ? LIMIT 1`
79
+ )
80
+ .bind(userEmail, candidate)
81
+ .first();
82
+ if (!existing) return candidate;
83
+ candidate = `${base}-${suffix}`;
84
+ suffix++;
85
+ }
86
+ throw new Error(`Could not allocate slug after 200 attempts (base='${base}')`);
87
+ }
88
+
89
+ // Shared helper used by runChat + runChatStream. Resolves the chat's
90
+ // project_id (if any), looks up the project row scoped to the user, and
91
+ // computes the effective system prompt with project-fallback semantics.
92
+ //
93
+ // Semantics:
94
+ // - body.project_id is undefined or not a positive integer: no project.
95
+ // - body.project_id points to a project not owned by this user: treated
96
+ // same as missing (returns project=null, no fallback). Logged.
97
+ // - body.project_id points to a deleted/unknown project: same as above.
98
+ //
99
+ // - Per-turn body.system_prompt non-empty (after trim) wins outright;
100
+ // the project's system_prompt is ignored.
101
+ // - Per-turn body.system_prompt is undefined or empty/whitespace AND a
102
+ // project is resolved AND that project has a non-null system_prompt:
103
+ // use the project's prompt.
104
+ // - Otherwise: no effective prompt (undefined).
105
+ //
106
+ // The resolved project_id is also returned for retrieveContext scoping.
107
+ export async function resolveProjectForChat(
108
+ env: Env,
109
+ userEmail: string,
110
+ body: ChatRequest,
111
+ ): Promise<{ project: ProjectRow | null; resolvedSystemPrompt: string | undefined; scopedProjectId: number | undefined }> {
112
+ let project: ProjectRow | null = null;
113
+ let scopedProjectId: number | undefined;
114
+
115
+ if (body.project_id !== undefined && Number.isInteger(body.project_id) && body.project_id > 0) {
116
+ project = await env.DB.prepare(
117
+ `SELECT id, user_email, name, slug, description, system_prompt, created_at, updated_at
118
+ FROM projects WHERE id = ? AND user_email = ?`
119
+ )
120
+ .bind(body.project_id, userEmail)
121
+ .first<ProjectRow>();
122
+ if (!project) {
123
+ console.warn(
124
+ `Chat referenced unknown project_id=${body.project_id} for user_email='${userEmail}'; ` +
125
+ `falling back to no-project semantics (no system prompt fallback, no retrieval scoping).`
126
+ );
127
+ } else {
128
+ scopedProjectId = project.id;
129
+ }
130
+ }
131
+
132
+ const reqPrompt = body.system_prompt;
133
+ const hasReqPrompt = reqPrompt !== undefined && reqPrompt.trim() !== "";
134
+ const resolvedSystemPrompt = hasReqPrompt
135
+ ? reqPrompt
136
+ : (project?.system_prompt ?? undefined);
137
+
138
+ return { project, resolvedSystemPrompt, scopedProjectId };
139
+ }
140
+
141
+ export async function handleProjectList(request: Request, env: Env): Promise<Response> {
142
+ const userEmail = await getUserEmail(request, env);
143
+ // LEFT JOIN to count document memberships per project. COUNT(pd.document_id)
144
+ // returns 0 for projects with no members (because of LEFT JOIN), rather
145
+ // than 1 which COUNT(*) would return.
146
+ const rows = await env.DB.prepare(
147
+ `SELECT p.id, p.name, p.slug, p.description, p.system_prompt,
148
+ p.created_at, p.updated_at,
149
+ COUNT(pd.document_id) AS document_count
150
+ FROM projects p
151
+ LEFT JOIN project_documents pd ON pd.project_id = p.id
152
+ WHERE p.user_email = ?
153
+ GROUP BY p.id
154
+ ORDER BY p.created_at DESC`
155
+ )
156
+ .bind(userEmail)
157
+ .all<{
158
+ id: number; name: string; slug: string; description: string | null;
159
+ system_prompt: string | null; created_at: string; updated_at: string;
160
+ document_count: number;
161
+ }>();
162
+ return json({ user: userEmail, projects: rows.results ?? [] });
163
+ }
164
+
165
+ export async function handleProjectGet(request: Request, env: Env, id: number): Promise<Response> {
166
+ const userEmail = await getUserEmail(request, env);
167
+ const proj = await env.DB.prepare(
168
+ `SELECT id, name, slug, description, system_prompt, created_at, updated_at
169
+ FROM projects WHERE id = ? AND user_email = ?`
170
+ )
171
+ .bind(id, userEmail)
172
+ .first<ProjectRow>();
173
+ if (!proj) return json({ error: "Not found" }, { status: 404 });
174
+
175
+ // Include the project's documents (id, filename, chunk_count) so the
176
+ // detail view can render them without a second fetch.
177
+ const docs = await env.DB.prepare(
178
+ `SELECT d.id, d.filename, d.mime, d.size_bytes, d.chunk_count, d.created_at,
179
+ pd.added_at
180
+ FROM project_documents pd
181
+ JOIN documents d ON d.id = pd.document_id
182
+ WHERE pd.project_id = ? AND d.user_email = ?
183
+ ORDER BY pd.added_at DESC`
184
+ )
185
+ .bind(id, userEmail)
186
+ .all<{
187
+ id: number; filename: string; mime: string; size_bytes: number;
188
+ chunk_count: number; created_at: string; added_at: string;
189
+ }>();
190
+
191
+ return json({ project: proj, documents: docs.results ?? [] });
192
+ }
193
+
194
+ export async function handleProjectCreate(request: Request, env: Env): Promise<Response> {
195
+ const userEmail = await getUserEmail(request, env);
196
+ let body: { name?: string; description?: string; system_prompt?: string };
197
+ try {
198
+ body = await request.json();
199
+ } catch {
200
+ return json({ error: "Invalid JSON body" }, { status: 400 });
201
+ }
202
+ const name = (body.name ?? "").trim();
203
+ if (!name) return json({ error: "name is required" }, { status: 400 });
204
+ if (name.length > 200) return json({ error: "name too long (max 200 chars)" }, { status: 400 });
205
+
206
+ const baseSlug = slugify(name);
207
+ const slug = await findFreeSlug(env, userEmail, baseSlug);
208
+
209
+ const description = (body.description ?? "").trim() || null;
210
+ const systemPrompt = (body.system_prompt ?? "").trim() || null;
211
+
212
+ const result = await env.DB.prepare(
213
+ `INSERT INTO projects (user_email, name, slug, description, system_prompt)
214
+ VALUES (?, ?, ?, ?, ?)
215
+ RETURNING id, name, slug, description, system_prompt, created_at, updated_at`
216
+ )
217
+ .bind(userEmail, name, slug, description, systemPrompt)
218
+ .first<ProjectRow>();
219
+
220
+ if (!result) return json({ error: "Insert failed" }, { status: 500 });
221
+ return json({ project: result }, { status: 201 });
222
+ }
223
+
224
+ export async function handleProjectUpdate(request: Request, env: Env, id: number): Promise<Response> {
225
+ const userEmail = await getUserEmail(request, env);
226
+ // Confirm ownership before any write.
227
+ const existing = await env.DB.prepare(
228
+ `SELECT id FROM projects WHERE id = ? AND user_email = ?`
229
+ )
230
+ .bind(id, userEmail)
231
+ .first();
232
+ if (!existing) return json({ error: "Not found" }, { status: 404 });
233
+
234
+ let body: { name?: string; description?: string | null; system_prompt?: string | null };
235
+ try {
236
+ body = await request.json();
237
+ } catch {
238
+ return json({ error: "Invalid JSON body" }, { status: 400 });
239
+ }
240
+
241
+ // Build dynamic UPDATE based on which fields the caller sent. Undefined =
242
+ // "don't touch"; null or empty string = "clear to empty/null". Name has
243
+ // to be a non-empty string if provided.
244
+ const sets: string[] = [];
245
+ const params: Array<string | number | null> = [];
246
+
247
+ if (body.name !== undefined) {
248
+ const n = body.name.trim();
249
+ if (!n) return json({ error: "name cannot be empty" }, { status: 400 });
250
+ if (n.length > 200) return json({ error: "name too long (max 200 chars)" }, { status: 400 });
251
+ sets.push("name = ?");
252
+ params.push(n);
253
+ }
254
+ if (body.description !== undefined) {
255
+ const d = (body.description ?? "").toString().trim() || null;
256
+ sets.push("description = ?");
257
+ params.push(d);
258
+ }
259
+ if (body.system_prompt !== undefined) {
260
+ const sp = (body.system_prompt ?? "").toString().trim() || null;
261
+ sets.push("system_prompt = ?");
262
+ params.push(sp);
263
+ }
264
+
265
+ if (sets.length === 0) {
266
+ return json({ error: "No updatable fields in body" }, { status: 400 });
267
+ }
268
+
269
+ // Slug is intentionally NOT updated on rename. Keeps URLs/storage keys
270
+ // stable. If renames need new slugs, that's a separate explicit op.
271
+ sets.push("updated_at = datetime('now')");
272
+ params.push(id, userEmail);
273
+
274
+ await env.DB.prepare(
275
+ `UPDATE projects SET ${sets.join(", ")} WHERE id = ? AND user_email = ?`
276
+ )
277
+ .bind(...params)
278
+ .run();
279
+
280
+ const updated = await env.DB.prepare(
281
+ `SELECT id, name, slug, description, system_prompt, created_at, updated_at
282
+ FROM projects WHERE id = ? AND user_email = ?`
283
+ )
284
+ .bind(id, userEmail)
285
+ .first<ProjectRow>();
286
+ return json({ project: updated });
287
+ }
288
+
289
+ export async function handleProjectDelete(request: Request, env: Env, id: number): Promise<Response> {
290
+ const userEmail = await getUserEmail(request, env);
291
+ const existing = await env.DB.prepare(
292
+ `SELECT id FROM projects WHERE id = ? AND user_email = ?`
293
+ )
294
+ .bind(id, userEmail)
295
+ .first();
296
+ if (!existing) return json({ error: "Not found" }, { status: 404 });
297
+
298
+ // Cascade: delete memberships first, then the project itself. Documents
299
+ // belonging to the project STAY (they may be in other projects, and even
300
+ // if not, the user uploaded them and may want to keep them outside
301
+ // project organization). v0.20.3: also clear project_messages scoped to
302
+ // this project (raw Discord rows; the documents and their chunks stay).
303
+ await env.DB.batch([
304
+ env.DB.prepare(`DELETE FROM project_documents WHERE project_id = ?`).bind(id),
305
+ env.DB.prepare(`DELETE FROM project_messages WHERE project_id = ?`).bind(id),
306
+ env.DB.prepare(`DELETE FROM projects WHERE id = ? AND user_email = ?`).bind(id, userEmail),
307
+ ]);
308
+ return json({ deleted: id });
309
+ }
310
+
311
+ export async function handleProjectDocAdd(request: Request, env: Env, projectId: number, docId: number): Promise<Response> {
312
+ const userEmail = await getUserEmail(request, env);
313
+ // Confirm both project and document belong to the user. Cross-user
314
+ // attachment is rejected here.
315
+ const proj = await env.DB.prepare(
316
+ `SELECT id FROM projects WHERE id = ? AND user_email = ?`
317
+ )
318
+ .bind(projectId, userEmail)
319
+ .first();
320
+ if (!proj) return json({ error: "Project not found" }, { status: 404 });
321
+
322
+ const doc = await env.DB.prepare(
323
+ `SELECT id FROM documents WHERE id = ? AND user_email = ?`
324
+ )
325
+ .bind(docId, userEmail)
326
+ .first();
327
+ if (!doc) return json({ error: "Document not found" }, { status: 404 });
328
+
329
+ // INSERT OR IGNORE: idempotent membership. Reattaching a doc that's
330
+ // already a member returns 200 without an error (added_at stays at the
331
+ // original value).
332
+ await env.DB.prepare(
333
+ `INSERT OR IGNORE INTO project_documents (project_id, document_id) VALUES (?, ?)`
334
+ )
335
+ .bind(projectId, docId)
336
+ .run();
337
+ return json({ project_id: projectId, document_id: docId, added: true });
338
+ }
339
+
340
+ export async function handleProjectDocRemove(request: Request, env: Env, projectId: number, docId: number): Promise<Response> {
341
+ const userEmail = await getUserEmail(request, env);
342
+ const proj = await env.DB.prepare(
343
+ `SELECT id FROM projects WHERE id = ? AND user_email = ?`
344
+ )
345
+ .bind(projectId, userEmail)
346
+ .first();
347
+ if (!proj) return json({ error: "Project not found" }, { status: 404 });
348
+
349
+ await env.DB.prepare(
350
+ `DELETE FROM project_documents WHERE project_id = ? AND document_id = ?`
351
+ )
352
+ .bind(projectId, docId)
353
+ .run();
354
+ return json({ project_id: projectId, document_id: docId, removed: true });
355
+ }
356
+
357
+ // v0.20.3: import a DiscordChatExporter JSON export into a project.
358
+ //
359
+ // POST /api/projects/:id/import-discord
360
+ // Body: { filename?: string, data: base64, options?: { gapMinutes, includeBots } }
361
+ //
362
+ // Pipeline (mirrors handleDocumentUpload, but for Discord exports):
363
+ // 1. validate project ownership
364
+ // 2. decode + size-check the export bytes
365
+ // 3. parse DCE JSON -> normalized messages (parseDiscordExport)
366
+ // 4. conversation-aware chunk (chunkDiscordMessages)
367
+ // 5. store export bytes in R2
368
+ // 6. insert a documents row for the export file
369
+ // 7. attach the document to the project (project_documents)
370
+ // 8. persist raw messages to project_messages (for future re-chunking)
371
+ // 9. embed chunks, upsert to Vectorize, insert chunk rows with the
372
+ // channel/authors/time metadata columns
373
+ //
374
+ // The chunk embed/store loop is intentionally a near-duplicate of the one in
375
+ // handleDocumentUpload rather than a shared helper: the document path is the
376
+ // higher-traffic code and has no integration tests, so refactoring it to
377
+ // share code carries regression risk disproportionate to ~30 saved lines.
378
+ // Consolidation is a candidate for a later cleanup release once integration
379
+ // tests exist.
380
+ export async function handleDiscordImport(request: Request, env: Env, projectId: number): Promise<Response> {
381
+ const userEmail = await getUserEmail(request, env);
382
+
383
+ const proj = await env.DB.prepare(
384
+ `SELECT id FROM projects WHERE id = ? AND user_email = ?`
385
+ )
386
+ .bind(projectId, userEmail)
387
+ .first();
388
+ if (!proj) return json({ error: "Project not found" }, { status: 404 });
389
+
390
+ let body: { filename?: string; data?: string; options?: { gapMinutes?: number; includeBots?: boolean } };
391
+ try {
392
+ body = await request.json();
393
+ } catch {
394
+ return json({ error: "Invalid JSON body" }, { status: 400 });
395
+ }
396
+ if (!body.data) {
397
+ return json({ error: "Missing export data" }, { status: 400 });
398
+ }
399
+
400
+ const filename = body.filename || "discord-export.json";
401
+
402
+ // Decode base64 (data URL or raw).
403
+ let bytes: Uint8Array;
404
+ try {
405
+ const parsed = body.data.startsWith("data:") ? parseDataUrl(body.data) : null;
406
+ bytes = parsed ? base64ToBytes(parsed.base64) : base64ToBytes(body.data);
407
+ } catch (err) {
408
+ return json({ error: `Bad export data: ${err instanceof Error ? err.message : err}` }, { status: 400 });
409
+ }
410
+ if (bytes.length > DOC_MAX_BYTES) {
411
+ return json({
412
+ error: `Export too large (${bytes.length} bytes, max ${DOC_MAX_BYTES}). Split the export by date range or channel, or wait for presigned upload (v0.20.4).`,
413
+ }, { status: 413 });
414
+ }
415
+
416
+ // Parse the JSON export.
417
+ let exportJson: unknown;
418
+ try {
419
+ exportJson = JSON.parse(new TextDecoder().decode(bytes));
420
+ } catch (err) {
421
+ return json({ error: `Export is not valid JSON: ${err instanceof Error ? err.message : err}` }, { status: 400 });
422
+ }
423
+
424
+ let parsed;
425
+ try {
426
+ parsed = parseDiscordExport(exportJson);
427
+ } catch (err) {
428
+ return json({ error: `Not a recognized DiscordChatExporter export: ${err instanceof Error ? err.message : err}` }, { status: 400 });
429
+ }
430
+ if (parsed.messages.length === 0) {
431
+ return json({
432
+ error: "No usable messages in the export (all were system notifications or empty). Nothing to import.",
433
+ }, { status: 400 });
434
+ }
435
+
436
+ const chunks = chunkDiscordMessages(parsed.messages, {
437
+ gapMinutes: body.options?.gapMinutes,
438
+ includeBots: body.options?.includeBots,
439
+ });
440
+ if (chunks.length === 0) {
441
+ return json({ error: "Parsing produced messages but chunking produced none (check includeBots option)." }, { status: 400 });
442
+ }
443
+
444
+ const totalChars = chunks.reduce((sum, c) => sum + c.text.length, 0);
445
+ const mime = "application/json";
446
+ const r2Key = await r2Put(env, "in", mime, bytes, userEmail);
447
+
448
+ // Insert the documents row for the export file.
449
+ const docInsert = await env.DB.prepare(
450
+ `INSERT INTO documents
451
+ (user_email, filename, mime, r2_key, size_bytes, total_chars, chunk_count)
452
+ VALUES (?, ?, ?, ?, ?, ?, ?)
453
+ RETURNING id, created_at`
454
+ )
455
+ .bind(userEmail, filename, mime, r2Key, bytes.length, totalChars, chunks.length)
456
+ .first<{ id: number; created_at: string }>();
457
+ if (!docInsert) {
458
+ await r2DeleteSafe(env, r2Key);
459
+ return json({ error: "Failed to insert document row" }, { status: 500 });
460
+ }
461
+ const docId = docInsert.id;
462
+
463
+ // Attach the export document to the project so project-scoped retrieval
464
+ // includes it immediately.
465
+ await env.DB.prepare(
466
+ `INSERT OR IGNORE INTO project_documents (project_id, document_id) VALUES (?, ?)`
467
+ )
468
+ .bind(projectId, docId)
469
+ .run();
470
+
471
+ // Persist raw messages for future re-chunking. Batched in groups to stay
472
+ // within D1 statement limits.
473
+ const PM_BATCH = 50;
474
+ for (let i = 0; i < parsed.messages.length; i += PM_BATCH) {
475
+ const slice = parsed.messages.slice(i, i + PM_BATCH);
476
+ const stmts = slice.map((m) =>
477
+ env.DB.prepare(
478
+ `INSERT INTO project_messages
479
+ (project_id, document_id, user_email, message_id, channel, author, author_id, is_bot, sent_at, content)
480
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
481
+ ).bind(projectId, docId, userEmail, m.messageId, m.channel, m.author, m.authorId, m.isBot ? 1 : 0, m.sentAt, m.content)
482
+ );
483
+ await env.DB.batch(stmts);
484
+ }
485
+
486
+ // Embed chunks and upsert to Vectorize. vector_id scheme matches documents:
487
+ // `${userEmail}:${docId}:${chunkIndex}`.
488
+ const vectorIdsWritten: string[] = [];
489
+ const chunkRowsToInsert: {
490
+ chunk_index: number;
491
+ text: string;
492
+ vector_id: string;
493
+ channel: string;
494
+ authors: string;
495
+ sent_at_start: string;
496
+ sent_at_end: string;
497
+ }[] = [];
498
+
499
+ try {
500
+ for (let b = 0; b < chunks.length; b += EMBED_BATCH_SIZE) {
501
+ const batch = chunks.slice(b, b + EMBED_BATCH_SIZE);
502
+ const vectors = await embedBatch(env, userEmail, batch.map((c) => c.text));
503
+ if (vectors.length !== batch.length) {
504
+ throw new Error(`Embedding batch returned ${vectors.length} vectors for ${batch.length} texts`);
505
+ }
506
+ const payload = batch.map((c, i) => {
507
+ const idx = b + i;
508
+ const vid = `${userEmail}:${docId}:${idx}`;
509
+ chunkRowsToInsert.push({
510
+ chunk_index: idx,
511
+ text: c.text,
512
+ vector_id: vid,
513
+ channel: c.channel,
514
+ authors: c.authors.join(", "),
515
+ sent_at_start: c.sentAtStart,
516
+ sent_at_end: c.sentAtEnd,
517
+ });
518
+ vectorIdsWritten.push(vid);
519
+ return {
520
+ id: vid,
521
+ values: vectors[i],
522
+ metadata: {
523
+ user_email: userEmail,
524
+ document_id: docId,
525
+ chunk_index: idx,
526
+ channel: c.channel,
527
+ },
528
+ };
529
+ });
530
+ await env.VEC.upsert(payload);
531
+ }
532
+ } catch (err) {
533
+ // Rollback partial state.
534
+ if (vectorIdsWritten.length) {
535
+ try { await env.VEC.deleteByIds(vectorIdsWritten); } catch { /* swallow */ }
536
+ }
537
+ await env.DB.batch([
538
+ env.DB.prepare(`DELETE FROM project_messages WHERE document_id = ?`).bind(docId),
539
+ env.DB.prepare(`DELETE FROM project_documents WHERE document_id = ?`).bind(docId),
540
+ env.DB.prepare(`DELETE FROM documents WHERE id = ?`).bind(docId),
541
+ ]);
542
+ await r2DeleteSafe(env, r2Key);
543
+ const m = err instanceof Error ? err.message : String(err);
544
+ return json({ error: `Embedding failed: ${m}` }, { status: 502 });
545
+ }
546
+
547
+ // Insert chunk rows with the Discord metadata columns. page/sheet stay NULL.
548
+ if (chunkRowsToInsert.length) {
549
+ for (let i = 0; i < chunkRowsToInsert.length; i += PM_BATCH) {
550
+ const slice = chunkRowsToInsert.slice(i, i + PM_BATCH);
551
+ const stmts = slice.map((c) =>
552
+ env.DB.prepare(
553
+ `INSERT INTO chunks
554
+ (document_id, user_email, chunk_index, text, vector_id, channel, authors, sent_at_start, sent_at_end)
555
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
556
+ ).bind(docId, userEmail, c.chunk_index, c.text, c.vector_id, c.channel, c.authors, c.sent_at_start, c.sent_at_end)
557
+ );
558
+ await env.DB.batch(stmts);
559
+ }
560
+ }
561
+
562
+ return json({
563
+ document_id: docId,
564
+ created_at: docInsert.created_at,
565
+ project_id: projectId,
566
+ filename,
567
+ guild: parsed.guild,
568
+ channel: parsed.channel,
569
+ raw_message_count: parsed.rawCount,
570
+ imported_message_count: parsed.parsedCount,
571
+ chunk_count: chunks.length,
572
+ });
573
+ }
574
+