@skyphusion/create-prism 0.1.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 (100) hide show
  1. package/LICENSE +235 -0
  2. package/NOTICE +3 -0
  3. package/README.md +114 -0
  4. package/index.js +195 -0
  5. package/package.json +44 -0
  6. package/template/CONTRIBUTING.md +80 -0
  7. package/template/LICENSE +235 -0
  8. package/template/MIGRATIONS.md +197 -0
  9. package/template/NOTICE +3 -0
  10. package/template/README.md +875 -0
  11. package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
  12. package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
  13. package/template/docs/legal/README.md +11 -0
  14. package/template/docs/screenshot-desktop.jpg +0 -0
  15. package/template/docs/screenshot-mobile.jpg +0 -0
  16. package/template/gitignore +23 -0
  17. package/template/migrate-v0.164.0.sql +6 -0
  18. package/template/migrate-v0.167.0.sql +44 -0
  19. package/template/migrate-v0.20.0.sql +40 -0
  20. package/template/migrate-v0.20.2.sql +19 -0
  21. package/template/migrate-v0.20.3.sql +36 -0
  22. package/template/migrations/0001_init.sql +134 -0
  23. package/template/package.json +32 -0
  24. package/template/public/app.js +2778 -0
  25. package/template/public/apple-touch-icon.png +0 -0
  26. package/template/public/favicon-16.png +0 -0
  27. package/template/public/favicon-32.png +0 -0
  28. package/template/public/favicon.svg +5 -0
  29. package/template/public/icon-192.png +0 -0
  30. package/template/public/icon-512.png +0 -0
  31. package/template/public/index.html +329 -0
  32. package/template/public/manifest.webmanifest +14 -0
  33. package/template/public/streaming-client.js +207 -0
  34. package/template/public/stt.html +68 -0
  35. package/template/public/stt.js +16 -0
  36. package/template/public/styles.css +2068 -0
  37. package/template/public/voice-widget.js +195 -0
  38. package/template/schema.sql +283 -0
  39. package/template/src/ai-binding.ts +33 -0
  40. package/template/src/auth-kdf.ts +106 -0
  41. package/template/src/auth.ts +315 -0
  42. package/template/src/chunking.ts +161 -0
  43. package/template/src/discord.ts +353 -0
  44. package/template/src/env.ts +55 -0
  45. package/template/src/gateway-credentials.ts +97 -0
  46. package/template/src/health-schema.ts +25 -0
  47. package/template/src/index.ts +4180 -0
  48. package/template/src/longrun-params.ts +135 -0
  49. package/template/src/models.ts +214 -0
  50. package/template/src/output-extract.ts +128 -0
  51. package/template/src/parsers/anthropic-sse.ts +56 -0
  52. package/template/src/parsers/gemini-sse.ts +62 -0
  53. package/template/src/parsers/openai-sse.ts +60 -0
  54. package/template/src/parsers/sse-framer.ts +39 -0
  55. package/template/src/parsers/types.ts +16 -0
  56. package/template/src/parsers/workers-ai-sse.ts +43 -0
  57. package/template/src/parsers/xai-sse.ts +40 -0
  58. package/template/src/providers/anthropic.ts +208 -0
  59. package/template/src/providers/google.ts +150 -0
  60. package/template/src/providers/openai.ts +69 -0
  61. package/template/src/providers/workers-ai.ts +83 -0
  62. package/template/src/providers/xai.ts +159 -0
  63. package/template/src/proxied-image-params.ts +43 -0
  64. package/template/src/rate-limit.ts +77 -0
  65. package/template/src/searxng.ts +75 -0
  66. package/template/src/session.ts +114 -0
  67. package/template/src/stt-session.ts +206 -0
  68. package/template/src/stt-util.ts +19 -0
  69. package/template/src/types.ts +56 -0
  70. package/template/src/user-prefs.ts +63 -0
  71. package/template/src/utils.ts +73 -0
  72. package/template/src/zip.ts +137 -0
  73. package/template/tests/anthropic-sse.test.ts +149 -0
  74. package/template/tests/auth-kdf.test.ts +59 -0
  75. package/template/tests/auth-unit.test.ts +97 -0
  76. package/template/tests/chunking.test.ts +217 -0
  77. package/template/tests/discord.test.ts +184 -0
  78. package/template/tests/gateway-credentials.test.ts +65 -0
  79. package/template/tests/gemini-sse.test.ts +75 -0
  80. package/template/tests/google-gemini.test.ts +65 -0
  81. package/template/tests/health-schema.test.ts +35 -0
  82. package/template/tests/longrun-params.test.ts +128 -0
  83. package/template/tests/openai-sse.test.ts +71 -0
  84. package/template/tests/output-extract.test.ts +171 -0
  85. package/template/tests/proxied-image-params.test.ts +51 -0
  86. package/template/tests/rate-limit.test.ts +45 -0
  87. package/template/tests/searxng.test.ts +51 -0
  88. package/template/tests/sse-framer.test.ts +113 -0
  89. package/template/tests/stt-session.test.ts +35 -0
  90. package/template/tests/utils.test.ts +39 -0
  91. package/template/tests/workers-ai-sse.test.ts +67 -0
  92. package/template/tests/xai-sse.test.ts +60 -0
  93. package/template/tests/zip.test.ts +145 -0
  94. package/template/tests-integration/auth.test.ts +371 -0
  95. package/template/tests-integration/worker.test.ts +322 -0
  96. package/template/tsconfig.json +18 -0
  97. package/template/vitest.config.ts +18 -0
  98. package/template/vitest.node.config.ts +19 -0
  99. package/template/vitest.workers.config.ts +47 -0
  100. package/template/wrangler.example.toml +151 -0
@@ -0,0 +1,315 @@
1
+ // First-party auth plane for the public deployment (v0.167.0, issue #80).
2
+ //
3
+ // Two deployment modes, selected by env.AUTH_MODE:
4
+ // - "access" (default when unset): Cloudflare Access sits in front and the
5
+ // worker trusts Cf-Access-Authenticated-User-Email. This is the private
6
+ // self-host path and preserves all pre-v0.167.0 behavior.
7
+ // - "public": no Access. Visitors sign up with username + password; identity
8
+ // comes from an httpOnly session cookie. Gateway credentials are per-user
9
+ // only (fail closed), so visitor inference never bills the host.
10
+ //
11
+ // Identity is derived in exactly one place, resolveIdentity(), which both read
12
+ // sites call (src/index.ts getUserEmail and src/stt-session.ts), so the two can
13
+ // never diverge. The returned string is the ownership key written to every
14
+ // user_email-keyed row and R2 customMetadata; in public mode it is the opaque
15
+ // users.id, in access mode the Access email, in local dev "anonymous".
16
+
17
+ import type { Env } from "./env";
18
+ import { hashPassword, verifyPassword, PBKDF2_ITERATIONS } from "./auth-kdf";
19
+ import {
20
+ SESSION_COOKIE,
21
+ buildSessionCookie,
22
+ clearSessionCookie,
23
+ createSession,
24
+ deleteAllUserSessions,
25
+ deleteSession,
26
+ lookupSession,
27
+ parseSessionCookie,
28
+ } from "./session";
29
+ import { checkRateLimit, resetRateLimit } from "./rate-limit";
30
+
31
+ export type AuthMode = "public" | "access";
32
+
33
+ export function authMode(env: Env): AuthMode {
34
+ return env.AUTH_MODE === "public" ? "public" : "access";
35
+ }
36
+
37
+ const ANON = "anonymous";
38
+
39
+ // Per-request memo so the boot gate and the handler that follows resolve the
40
+ // session at most once against D1. Keyed by the Request object, which the
41
+ // router threads unchanged into every handler.
42
+ const identityMemo = new WeakMap<Request, string | null>();
43
+
44
+ // The single identity derivation. Returns the ownership key, or null when the
45
+ // request is unauthenticated in public mode (no/invalid session). Access mode
46
+ // never returns null: an absent header falls back to the anonymous local-dev
47
+ // identity, exactly as before.
48
+ export async function resolveIdentity(request: Request, env: Env): Promise<string | null> {
49
+ if (identityMemo.has(request)) return identityMemo.get(request) ?? null;
50
+
51
+ let result: string | null;
52
+ if (authMode(env) === "access") {
53
+ result = request.headers.get("cf-access-authenticated-user-email") ?? ANON;
54
+ } else {
55
+ const token = parseSessionCookie(request);
56
+ result = token ? await lookupSession(env.DB, token) : null;
57
+ }
58
+ identityMemo.set(request, result);
59
+ return result;
60
+ }
61
+
62
+ // ---------- validation ----------
63
+
64
+ const USERNAME_RE = /^[a-zA-Z0-9_-]{3,32}$/;
65
+ const PASSWORD_MIN = 10;
66
+ const PASSWORD_MAX = 1024;
67
+
68
+ export function validateUsername(username: unknown): string | null {
69
+ if (typeof username !== "string") return "Username is required.";
70
+ const trimmed = username.trim();
71
+ if (!USERNAME_RE.test(trimmed)) {
72
+ return "Username must be 3-32 characters: letters, digits, dash, underscore.";
73
+ }
74
+ return null;
75
+ }
76
+
77
+ export function validatePassword(password: unknown): string | null {
78
+ if (typeof password !== "string") return "Password is required.";
79
+ if (password.length < PASSWORD_MIN) return `Password must be at least ${PASSWORD_MIN} characters.`;
80
+ if (password.length > PASSWORD_MAX) return `Password must be at most ${PASSWORD_MAX} characters.`;
81
+ return null;
82
+ }
83
+
84
+ // Opaque stable user id: "usr_" + 24 lowercase hex (12 random bytes).
85
+ export function generateUserId(): string {
86
+ const bytes = crypto.getRandomValues(new Uint8Array(12));
87
+ let hex = "";
88
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
89
+ return `usr_${hex}`;
90
+ }
91
+
92
+ function json(body: unknown, init: ResponseInit = {}): Response {
93
+ const headers = new Headers(init.headers);
94
+ headers.set("content-type", "application/json; charset=utf-8");
95
+ return new Response(JSON.stringify(body), { ...init, headers });
96
+ }
97
+
98
+ function clientIp(request: Request): string {
99
+ return request.headers.get("cf-connecting-ip") ?? "unknown";
100
+ }
101
+
102
+ // ---------- rate-limit budgets ----------
103
+
104
+ const LOGIN_LIMIT = 5;
105
+ const LOGIN_WINDOW = 15 * 60; // 15 minutes per ip+username
106
+ const SIGNUP_LIMIT = 10;
107
+ const SIGNUP_WINDOW = 60 * 60; // 10 signups per hour per ip
108
+
109
+ // Throwaway verify target for unknown usernames. Its iteration count MUST equal
110
+ // PBKDF2_ITERATIONS so that an unknown-username login costs the same wall-clock
111
+ // as a real one; otherwise the fast (low-iteration) path is a username-
112
+ // enumeration timing oracle. Built from the constant so the two can never
113
+ // drift. The salt/hash bytes are arbitrary; the compare always fails.
114
+ export const DUMMY_PASSWORD_HASH =
115
+ `pbkdf2$sha256$${PBKDF2_ITERATIONS}$AAAAAAAAAAAAAAAAAAAAAA==$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=`;
116
+
117
+ // ---------- routes ----------
118
+
119
+ // POST /api/auth/signup {username, password}. Public mode only. Creates the
120
+ // account, opens a session, sets the cookie. Email is deferred from v0.167.0:
121
+ // the column exists for forward-compat but the route does not accept it.
122
+ export async function handleSignup(request: Request, env: Env): Promise<Response> {
123
+ if (authMode(env) !== "public") {
124
+ return json({ error: "Signup is disabled on this deployment." }, { status: 403 });
125
+ }
126
+ let body: { username?: unknown; password?: unknown };
127
+ try {
128
+ body = await request.json();
129
+ } catch {
130
+ return json({ error: "Invalid JSON" }, { status: 400 });
131
+ }
132
+ const uErr = validateUsername(body.username);
133
+ if (uErr) return json({ error: uErr }, { status: 400 });
134
+ const pErr = validatePassword(body.password);
135
+ if (pErr) return json({ error: pErr }, { status: 400 });
136
+
137
+ const ip = clientIp(request);
138
+ if (!(await checkRateLimit(env.DB, `signup:${ip}`, SIGNUP_LIMIT, SIGNUP_WINDOW))) {
139
+ return json({ error: "Too many signups from this network. Try again later." }, { status: 429 });
140
+ }
141
+
142
+ const username = (body.username as string).trim();
143
+ const usernameLc = username.toLowerCase();
144
+ const existing = await env.DB.prepare(`SELECT id FROM users WHERE username_lc = ?`)
145
+ .bind(usernameLc)
146
+ .first<{ id: string }>();
147
+ if (existing) return json({ error: "That username is taken." }, { status: 409 });
148
+
149
+ const id = generateUserId();
150
+ const passwordHash = await hashPassword(body.password as string);
151
+ await env.DB.prepare(
152
+ `INSERT INTO users (id, username, username_lc, password_hash) VALUES (?, ?, ?, ?)`,
153
+ )
154
+ .bind(id, username, usernameLc, passwordHash)
155
+ .run();
156
+
157
+ const token = await createSession(env.DB, id);
158
+ return json(
159
+ { user: { username } },
160
+ { status: 201, headers: { "set-cookie": buildSessionCookie(token) } },
161
+ );
162
+ }
163
+
164
+ // POST /api/auth/login {username, password}. Public mode only.
165
+ export async function handleLogin(request: Request, env: Env): Promise<Response> {
166
+ if (authMode(env) !== "public") {
167
+ return json({ error: "Login is disabled on this deployment." }, { status: 403 });
168
+ }
169
+ let body: { username?: unknown; password?: unknown };
170
+ try {
171
+ body = await request.json();
172
+ } catch {
173
+ return json({ error: "Invalid JSON" }, { status: 400 });
174
+ }
175
+ if (typeof body.username !== "string" || typeof body.password !== "string") {
176
+ return json({ error: "Username and password are required." }, { status: 400 });
177
+ }
178
+
179
+ const ip = clientIp(request);
180
+ const usernameLc = body.username.trim().toLowerCase();
181
+ const bucketKey = `login:${ip}:${usernameLc}`;
182
+ // Pre-verify check throttles a login flood (before the 600k-iter KDF cost).
183
+ if (!(await checkRateLimit(env.DB, bucketKey, LOGIN_LIMIT, LOGIN_WINDOW))) {
184
+ return json({ error: "Too many login attempts. Try again later." }, { status: 429 });
185
+ }
186
+
187
+ const row = await env.DB.prepare(
188
+ `SELECT id, username, password_hash FROM users WHERE username_lc = ?`,
189
+ )
190
+ .bind(usernameLc)
191
+ .first<{ id: string; username: string; password_hash: string }>();
192
+
193
+ // Verify against the stored hash, or the equal-cost dummy when the user is
194
+ // unknown, so a missing account and a wrong password take the same time and
195
+ // return the same generic error (no username enumeration).
196
+ const storedHash = row?.password_hash ?? DUMMY_PASSWORD_HASH;
197
+ const ok = await verifyPassword(body.password, storedHash);
198
+ if (!row || !ok) {
199
+ return json({ error: "Invalid username or password." }, { status: 401 });
200
+ }
201
+
202
+ // Success: clear the failed-attempt tally so successful logins never count
203
+ // toward the cap (the limiter targets failed floods, per the design).
204
+ await resetRateLimit(env.DB, bucketKey);
205
+
206
+ const token = await createSession(env.DB, row.id);
207
+ return json(
208
+ { user: { username: row.username } },
209
+ { headers: { "set-cookie": buildSessionCookie(token) } },
210
+ );
211
+ }
212
+
213
+ // POST /api/auth/logout. Drops the current session and clears the cookie.
214
+ // A no-op (still 200) when there is no session.
215
+ export async function handleLogout(request: Request, env: Env): Promise<Response> {
216
+ const token = parseSessionCookie(request);
217
+ if (token) await deleteSession(env.DB, token);
218
+ return json({ ok: true }, { headers: { "set-cookie": clearSessionCookie() } });
219
+ }
220
+
221
+ // DELETE /api/account {password}. Session-authed, re-verifies the password,
222
+ // then cascades every owned artifact and row before dropping the account and
223
+ // clearing the cookie. Public mode only (access-mode identities are external).
224
+ export async function handleAccountDelete(request: Request, env: Env): Promise<Response> {
225
+ if (authMode(env) !== "public") {
226
+ return json({ error: "Account deletion is only available on the public deployment." }, { status: 403 });
227
+ }
228
+ const id = await resolveIdentity(request, env);
229
+ if (!id) return json({ error: "Authentication required.", code: "unauthenticated" }, { status: 401 });
230
+
231
+ let body: { password?: unknown };
232
+ try {
233
+ body = await request.json();
234
+ } catch {
235
+ return json({ error: "Invalid JSON" }, { status: 400 });
236
+ }
237
+ if (typeof body.password !== "string") {
238
+ return json({ error: "Password confirmation is required." }, { status: 400 });
239
+ }
240
+ const row = await env.DB.prepare(`SELECT password_hash FROM users WHERE id = ?`)
241
+ .bind(id)
242
+ .first<{ password_hash: string }>();
243
+ if (!row || !(await verifyPassword(body.password, row.password_hash))) {
244
+ return json({ error: "Password confirmation failed." }, { status: 403 });
245
+ }
246
+
247
+ await cascadeDeleteUserData(env, id);
248
+ return json({ ok: true }, { headers: { "set-cookie": clearSessionCookie() } });
249
+ }
250
+
251
+ // Full account cascade. D1 has no FK enforcement, so ownership is unwound in
252
+ // application code. R2 keys are not user-prefixed, so every owned key is
253
+ // enumerated from the user's D1 rows (never an R2 list). R2 + Vectorize deletes
254
+ // are best-effort; the D1 rows are removed in a single batch so the account
255
+ // vanishes atomically even if an external delete lags.
256
+ export async function cascadeDeleteUserData(env: Env, userId: string): Promise<void> {
257
+ // 1. R2 objects referenced by this user's chats (generated output +
258
+ // by-reference attachments) and documents (uploaded source bytes).
259
+ const r2Keys = new Set<string>();
260
+ const chatRows = await env.DB.prepare(
261
+ `SELECT output_artifact, attachments FROM chats WHERE user_email = ?`,
262
+ )
263
+ .bind(userId)
264
+ .all<{ output_artifact: string | null; attachments: string | null }>();
265
+ for (const c of chatRows.results ?? []) {
266
+ if (c.output_artifact) {
267
+ try {
268
+ const art = JSON.parse(c.output_artifact) as { key?: string };
269
+ if (art?.key) r2Keys.add(art.key);
270
+ } catch { /* ignore malformed */ }
271
+ }
272
+ if (c.attachments) {
273
+ try {
274
+ const atts = JSON.parse(c.attachments) as Array<{ key?: string }>;
275
+ if (Array.isArray(atts)) for (const a of atts) if (a?.key) r2Keys.add(a.key);
276
+ } catch { /* ignore malformed */ }
277
+ }
278
+ }
279
+ const docRows = await env.DB.prepare(`SELECT r2_key FROM documents WHERE user_email = ?`)
280
+ .bind(userId)
281
+ .all<{ r2_key: string }>();
282
+ for (const d of docRows.results ?? []) if (d.r2_key) r2Keys.add(d.r2_key);
283
+ for (const key of r2Keys) {
284
+ try { await env.R2.delete(key); } catch { /* best effort */ }
285
+ }
286
+
287
+ // 2. Vectorize embeddings for this user's RAG chunks.
288
+ const vecRows = await env.DB.prepare(`SELECT vector_id FROM chunks WHERE user_email = ?`)
289
+ .bind(userId)
290
+ .all<{ vector_id: string }>();
291
+ const vectorIds = (vecRows.results ?? []).map((r) => r.vector_id).filter(Boolean);
292
+ if (vectorIds.length) {
293
+ try { await env.VEC.deleteByIds(vectorIds); } catch { /* best effort */ }
294
+ }
295
+
296
+ // 3. Every D1 row keyed to this identity, in one batch. project_documents
297
+ // carries no user_email, so it is scoped through the user's project ids.
298
+ await env.DB.batch([
299
+ env.DB.prepare(
300
+ `DELETE FROM project_documents WHERE project_id IN (SELECT id FROM projects WHERE user_email = ?)`,
301
+ ).bind(userId),
302
+ env.DB.prepare(`DELETE FROM project_messages WHERE user_email = ?`).bind(userId),
303
+ env.DB.prepare(`DELETE FROM chunks WHERE user_email = ?`).bind(userId),
304
+ env.DB.prepare(`DELETE FROM documents WHERE user_email = ?`).bind(userId),
305
+ env.DB.prepare(`DELETE FROM projects WHERE user_email = ?`).bind(userId),
306
+ env.DB.prepare(`DELETE FROM chats WHERE user_email = ?`).bind(userId),
307
+ env.DB.prepare(`DELETE FROM user_prefs WHERE user_email = ?`).bind(userId),
308
+ env.DB.prepare(`DELETE FROM sessions WHERE user_id = ?`).bind(userId),
309
+ env.DB.prepare(`DELETE FROM users WHERE id = ?`).bind(userId),
310
+ ]);
311
+ // Defensive: ensure no session survives the batch (belt-and-suspenders).
312
+ await deleteAllUserSessions(env.DB, userId);
313
+ }
314
+
315
+ export { SESSION_COOKIE };
@@ -0,0 +1,161 @@
1
+ // Text chunking for RAG ingestion (v0.19.4).
2
+ //
3
+ // Extracted and rewritten from the fixed-window chunker in src/index.ts.
4
+ // The previous implementation used a 500-char window with break-point
5
+ // search restricted to the last 1/3 of the window: if a paragraph break
6
+ // appeared earlier than that, the chunker ignored it and forced a chunk
7
+ // that spanned the paragraph. For fiction, worldbuilding, and Discord
8
+ // message corpora (v0.20.x), this produced chunks that broke mid-thought
9
+ // even when clean semantic boundaries existed.
10
+ //
11
+ // The new chunker uses recursive separator splitting (the LangChain
12
+ // `RecursiveCharacterTextSplitter` shape). A separator hierarchy is tried
13
+ // in priority order; for each separator, the text is split and any piece
14
+ // still too large is recursively split using the next-priority separator.
15
+ // Adjacent fragments are then greedily merged back up to the target size
16
+ // with optional tail-overlap.
17
+ //
18
+ // Result: chunks respect ALL paragraph breaks (not just ones in the last
19
+ // third of the window), can be smaller than target when a clean boundary
20
+ // makes them so, and degrade gracefully on text with no useful separators.
21
+
22
+ const CHUNK_TARGET_CHARS = 500;
23
+ const CHUNK_OVERLAP_CHARS = 50;
24
+
25
+ // Separator priority hierarchy. Earlier separators are tried first; the
26
+ // chunker prefers paragraph breaks over line breaks over sentence breaks
27
+ // over word breaks. The empty-string separator is the last-resort hard
28
+ // character split.
29
+ const CHUNK_SEPARATORS: readonly string[] = [
30
+ "\n\n", // paragraph breaks (highest priority - never break a paragraph)
31
+ "\n", // line breaks (preserve list items, dialog lines, code lines)
32
+ ". ", // sentence end (period)
33
+ "? ", // sentence end (question)
34
+ "! ", // sentence end (exclamation)
35
+ "; ", // clause break (semicolon - useful for legal prose)
36
+ ", ", // weaker break (comma fallback for run-on text)
37
+ " ", // word break
38
+ "", // last resort: hard character split
39
+ ];
40
+
41
+ /**
42
+ * Split text into chunks targeting CHUNK_TARGET_CHARS each, with tail-overlap
43
+ * between consecutive chunks. Public entry point; replaces the v0.10.x
44
+ * fixed-window chunker.
45
+ *
46
+ * Returns an empty array for empty input. Otherwise returns at least one
47
+ * chunk. Chunks are returned in source order. Each chunk is trimmed of
48
+ * leading/trailing whitespace.
49
+ */
50
+ export function chunkText(text: string): string[] {
51
+ if (!text) return [];
52
+ const fragments = recursiveCharSplit(text, CHUNK_SEPARATORS, CHUNK_TARGET_CHARS);
53
+ return mergeFragments(fragments, CHUNK_TARGET_CHARS, CHUNK_OVERLAP_CHARS);
54
+ }
55
+
56
+ /**
57
+ * Recursively split text using a separator hierarchy until all fragments
58
+ * are at most `targetSize` characters. Tries separators in order; for each
59
+ * separator that appears in the text, splits and re-attaches the separator
60
+ * to the trailing side of each piece (so the split is non-destructive).
61
+ * Pieces still too large after a split are recursively re-split using the
62
+ * next-priority separator.
63
+ *
64
+ * If no separator in the list appears in the text and the text still
65
+ * exceeds targetSize, falls back to a hard character split.
66
+ */
67
+ function recursiveCharSplit(
68
+ text: string,
69
+ separators: readonly string[],
70
+ targetSize: number,
71
+ ): string[] {
72
+ if (text.length <= targetSize) {
73
+ return text ? [text] : [];
74
+ }
75
+
76
+ // Find the first separator that appears in the text. The empty-string
77
+ // separator always matches (it's the hard-split fallback).
78
+ let separator = "";
79
+ let separatorIdx = separators.length;
80
+ for (let i = 0; i < separators.length; i++) {
81
+ const s = separators[i];
82
+ if (s === "" || text.includes(s)) {
83
+ separator = s;
84
+ separatorIdx = i;
85
+ break;
86
+ }
87
+ }
88
+
89
+ // Hard character split as the absolute last resort.
90
+ if (separator === "") {
91
+ const out: string[] = [];
92
+ for (let i = 0; i < text.length; i += targetSize) {
93
+ out.push(text.slice(i, i + targetSize));
94
+ }
95
+ return out;
96
+ }
97
+
98
+ // Split on the chosen separator and re-attach it to the trailing side
99
+ // of each piece (except the last, which has nothing trailing).
100
+ const rawParts = text.split(separator);
101
+ const parts: string[] = [];
102
+ for (let i = 0; i < rawParts.length; i++) {
103
+ const piece = rawParts[i] + (i < rawParts.length - 1 ? separator : "");
104
+ if (piece) parts.push(piece);
105
+ }
106
+
107
+ // Recurse on any piece that's still too large, using the next-priority
108
+ // separators only (the current one already didn't reduce it enough).
109
+ const nextSeps = separators.slice(separatorIdx + 1);
110
+ const out: string[] = [];
111
+ for (const part of parts) {
112
+ if (part.length <= targetSize) {
113
+ out.push(part);
114
+ } else {
115
+ out.push(...recursiveCharSplit(part, nextSeps, targetSize));
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+
121
+ /**
122
+ * Greedily merge adjacent fragments back up to the target size. Adds a
123
+ * tail-overlap from the previous chunk to the next when overlap > 0 and
124
+ * the previous chunk is large enough to carry one.
125
+ *
126
+ * The merge stays under targetSize whenever possible. If a single fragment
127
+ * exceeds targetSize on its own (which happens when recursiveCharSplit
128
+ * had to hard-split), it gets its own chunk regardless.
129
+ */
130
+ function mergeFragments(
131
+ fragments: string[],
132
+ targetSize: number,
133
+ overlap: number,
134
+ ): string[] {
135
+ const out: string[] = [];
136
+ let buffer = "";
137
+
138
+ for (const frag of fragments) {
139
+ if (!buffer) {
140
+ buffer = frag;
141
+ continue;
142
+ }
143
+ if (buffer.length + frag.length <= targetSize) {
144
+ buffer += frag;
145
+ } else {
146
+ const finalized = buffer.trim();
147
+ if (finalized) out.push(finalized);
148
+ // Optional tail-overlap: carry the last `overlap` characters of the
149
+ // previous chunk into the start of the next. Helps RAG retrieval
150
+ // find passages that straddle chunk boundaries.
151
+ if (overlap > 0 && buffer.length > overlap) {
152
+ buffer = buffer.slice(-overlap) + frag;
153
+ } else {
154
+ buffer = frag;
155
+ }
156
+ }
157
+ }
158
+ const finalized = buffer.trim();
159
+ if (finalized) out.push(finalized);
160
+ return out;
161
+ }