@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,149 @@
1
+ // Tests for interpretAnthropicSSEFrame (v0.18.1). Behavior preserved from
2
+ // the inline implementation in callAnthropicStream pre-extraction.
3
+
4
+ import { describe, it, expect } from "vitest";
5
+ import { interpretAnthropicSSEFrame } from "../src/parsers/anthropic-sse";
6
+
7
+ describe("interpretAnthropicSSEFrame", () => {
8
+ describe("message_start", () => {
9
+ it("yields a usage event from initial message_start", () => {
10
+ const data = {
11
+ type: "message_start",
12
+ message: {
13
+ id: "msg_01",
14
+ role: "assistant",
15
+ usage: { input_tokens: 100, output_tokens: 1 },
16
+ },
17
+ };
18
+ expect(interpretAnthropicSSEFrame(data)).toEqual([
19
+ { type: "usage", in_: 100, out_: 1 },
20
+ ]);
21
+ });
22
+
23
+ it("yields no event if message_start has no usage", () => {
24
+ const data = { type: "message_start", message: { id: "msg_01", role: "assistant" } };
25
+ expect(interpretAnthropicSSEFrame(data)).toEqual([]);
26
+ });
27
+ });
28
+
29
+ describe("content_block_delta", () => {
30
+ it("yields a text event for a text_delta", () => {
31
+ const data = {
32
+ type: "content_block_delta",
33
+ index: 0,
34
+ delta: { type: "text_delta", text: "Hello" },
35
+ };
36
+ expect(interpretAnthropicSSEFrame(data)).toEqual([
37
+ { type: "text", text: "Hello" },
38
+ ]);
39
+ });
40
+
41
+ it("ignores non-text-delta types (e.g. tool-use input_json_delta)", () => {
42
+ const data = {
43
+ type: "content_block_delta",
44
+ index: 0,
45
+ delta: { type: "input_json_delta", partial_json: '{"x":1}' },
46
+ };
47
+ expect(interpretAnthropicSSEFrame(data)).toEqual([]);
48
+ });
49
+
50
+ it("ignores delta with no text field", () => {
51
+ const data = {
52
+ type: "content_block_delta",
53
+ index: 0,
54
+ delta: { type: "text_delta" },
55
+ };
56
+ expect(interpretAnthropicSSEFrame(data)).toEqual([]);
57
+ });
58
+ });
59
+
60
+ describe("message_delta", () => {
61
+ it("yields a usage event with final output_tokens count", () => {
62
+ const data = {
63
+ type: "message_delta",
64
+ delta: { stop_reason: "end_turn" },
65
+ usage: { input_tokens: 100, output_tokens: 42 },
66
+ };
67
+ expect(interpretAnthropicSSEFrame(data)).toEqual([
68
+ { type: "usage", in_: 100, out_: 42 },
69
+ ]);
70
+ });
71
+
72
+ it("yields no event if message_delta has no usage", () => {
73
+ const data = { type: "message_delta", delta: { stop_reason: "end_turn" } };
74
+ expect(interpretAnthropicSSEFrame(data)).toEqual([]);
75
+ });
76
+
77
+ it("returns null for missing token fields in usage", () => {
78
+ const data = { type: "message_delta", usage: { output_tokens: 42 } };
79
+ expect(interpretAnthropicSSEFrame(data)).toEqual([
80
+ { type: "usage", in_: null, out_: 42 },
81
+ ]);
82
+ });
83
+ });
84
+
85
+ describe("ignored event types", () => {
86
+ it("ignores content_block_start", () => {
87
+ const data = {
88
+ type: "content_block_start",
89
+ index: 0,
90
+ content_block: { type: "text", text: "" },
91
+ };
92
+ expect(interpretAnthropicSSEFrame(data)).toEqual([]);
93
+ });
94
+
95
+ it("ignores content_block_stop", () => {
96
+ expect(interpretAnthropicSSEFrame({ type: "content_block_stop", index: 0 })).toEqual([]);
97
+ });
98
+
99
+ it("ignores message_stop", () => {
100
+ expect(interpretAnthropicSSEFrame({ type: "message_stop" })).toEqual([]);
101
+ });
102
+
103
+ it("ignores ping events", () => {
104
+ expect(interpretAnthropicSSEFrame({ type: "ping" })).toEqual([]);
105
+ });
106
+
107
+ it("ignores unknown event types", () => {
108
+ expect(interpretAnthropicSSEFrame({ type: "some_future_event", extra: 1 })).toEqual([]);
109
+ });
110
+
111
+ it("ignores frames with no type field", () => {
112
+ expect(interpretAnthropicSSEFrame({ random: "junk" })).toEqual([]);
113
+ });
114
+ });
115
+
116
+ describe("realistic conversation sequence", () => {
117
+ // Walks a typical turn: message_start -> content_block_start ->
118
+ // content_block_delta x N -> content_block_stop -> message_delta -> message_stop
119
+ it("yields exactly the events callers need from a full turn sequence", () => {
120
+ const frames: Array<{ type: string; [key: string]: unknown }> = [
121
+ {
122
+ type: "message_start",
123
+ message: { id: "msg_01", role: "assistant", usage: { input_tokens: 50, output_tokens: 1 } },
124
+ },
125
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
126
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "The " } },
127
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "quick " } },
128
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "fox." } },
129
+ { type: "content_block_stop", index: 0 },
130
+ {
131
+ type: "message_delta",
132
+ delta: { stop_reason: "end_turn" },
133
+ usage: { input_tokens: 50, output_tokens: 8 },
134
+ },
135
+ { type: "message_stop" },
136
+ ];
137
+
138
+ const allEvents = frames.flatMap((f) => interpretAnthropicSSEFrame(f));
139
+
140
+ expect(allEvents).toEqual([
141
+ { type: "usage", in_: 50, out_: 1 },
142
+ { type: "text", text: "The " },
143
+ { type: "text", text: "quick " },
144
+ { type: "text", text: "fox." },
145
+ { type: "usage", in_: 50, out_: 8 },
146
+ ]);
147
+ });
148
+ });
149
+ });
@@ -0,0 +1,59 @@
1
+ // Pure-logic tests for password hashing (v0.167.0, issue #80).
2
+
3
+ import { describe, expect, it } from "vitest";
4
+ import {
5
+ hashPassword,
6
+ verifyPassword,
7
+ parsePhc,
8
+ constantTimeEqual,
9
+ PBKDF2_ITERATIONS,
10
+ } from "../src/auth-kdf";
11
+
12
+ describe("hashPassword / verifyPassword", () => {
13
+ it("round-trips the correct password", async () => {
14
+ const stored = await hashPassword("correct horse battery staple");
15
+ expect(await verifyPassword("correct horse battery staple", stored)).toBe(true);
16
+ });
17
+
18
+ it("rejects a wrong password", async () => {
19
+ const stored = await hashPassword("correct horse battery staple");
20
+ expect(await verifyPassword("Correct Horse Battery Staple", stored)).toBe(false);
21
+ expect(await verifyPassword("", stored)).toBe(false);
22
+ });
23
+
24
+ it("produces a PHC string with the expected algo, hash, and iteration count", async () => {
25
+ const stored = await hashPassword("hunter2hunter2");
26
+ const parsed = parsePhc(stored);
27
+ expect(stored.startsWith(`pbkdf2$sha256$${PBKDF2_ITERATIONS}$`)).toBe(true);
28
+ expect(parsed).not.toBeNull();
29
+ expect(parsed!.iterations).toBe(PBKDF2_ITERATIONS);
30
+ expect(parsed!.salt.length).toBe(16);
31
+ expect(parsed!.hash.length).toBe(32);
32
+ });
33
+
34
+ it("salts per call: same password yields different stored hashes", async () => {
35
+ const a = await hashPassword("samepassword123");
36
+ const b = await hashPassword("samepassword123");
37
+ expect(a).not.toBe(b);
38
+ expect(await verifyPassword("samepassword123", a)).toBe(true);
39
+ expect(await verifyPassword("samepassword123", b)).toBe(true);
40
+ });
41
+
42
+ it("fails closed on a malformed stored value", async () => {
43
+ expect(await verifyPassword("x", "not-a-phc-string")).toBe(false);
44
+ expect(await verifyPassword("x", "pbkdf2$sha256$notnum$AA==$AA==")).toBe(false);
45
+ expect(await verifyPassword("x", "argon2$sha256$1$AA==$AA==")).toBe(false);
46
+ expect(parsePhc("a$b$c")).toBeNull();
47
+ });
48
+ });
49
+
50
+ describe("constantTimeEqual", () => {
51
+ it("true only for identical byte arrays", () => {
52
+ expect(constantTimeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3]))).toBe(true);
53
+ expect(constantTimeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 4]))).toBe(false);
54
+ });
55
+
56
+ it("false for different lengths", () => {
57
+ expect(constantTimeEqual(new Uint8Array([1, 2]), new Uint8Array([1, 2, 3]))).toBe(false);
58
+ });
59
+ });
@@ -0,0 +1,97 @@
1
+ // Pure-logic tests for auth validation, user-id shape, and session cookies
2
+ // (v0.167.0, issue #80).
3
+
4
+ import { describe, expect, it } from "vitest";
5
+ import { validateUsername, validatePassword, generateUserId, DUMMY_PASSWORD_HASH } from "../src/auth";
6
+ import { parsePhc, PBKDF2_ITERATIONS } from "../src/auth-kdf";
7
+ import {
8
+ SESSION_COOKIE,
9
+ buildSessionCookie,
10
+ clearSessionCookie,
11
+ parseSessionCookie,
12
+ generateSessionToken,
13
+ } from "../src/session";
14
+
15
+ describe("validateUsername", () => {
16
+ it("accepts valid handles", () => {
17
+ for (const u of ["abc", "user_1", "a-b-c", "Rollins42"]) {
18
+ expect(validateUsername(u)).toBeNull();
19
+ }
20
+ });
21
+ it("rejects invalid handles", () => {
22
+ expect(validateUsername("ab")).not.toBeNull(); // too short
23
+ expect(validateUsername("a".repeat(33))).not.toBeNull(); // too long
24
+ expect(validateUsername("has space")).not.toBeNull();
25
+ expect(validateUsername("bad!char")).not.toBeNull();
26
+ expect(validateUsername("has.dot")).not.toBeNull(); // dot not in charset
27
+ expect(validateUsername(123)).not.toBeNull();
28
+ expect(validateUsername(undefined)).not.toBeNull();
29
+ });
30
+ });
31
+
32
+ describe("validatePassword", () => {
33
+ it("accepts 10..1024 char passwords", () => {
34
+ expect(validatePassword("1234567890")).toBeNull();
35
+ expect(validatePassword("a".repeat(1024))).toBeNull();
36
+ });
37
+ it("rejects too short / too long / non-string", () => {
38
+ expect(validatePassword("123456789")).not.toBeNull(); // 9 chars
39
+ expect(validatePassword("a".repeat(1025))).not.toBeNull();
40
+ expect(validatePassword(1234567890)).not.toBeNull();
41
+ });
42
+ });
43
+
44
+ describe("generateUserId", () => {
45
+ it("has the usr_ + 24 hex shape and is unique per call", () => {
46
+ const a = generateUserId();
47
+ const b = generateUserId();
48
+ expect(a).toMatch(/^usr_[0-9a-f]{24}$/);
49
+ expect(a).not.toBe(b);
50
+ });
51
+ });
52
+
53
+ describe("session cookie helpers", () => {
54
+ it("builds a __Host- cookie with the required attributes", () => {
55
+ const c = buildSessionCookie("tok123", 3600);
56
+ expect(c.startsWith(`${SESSION_COOKIE}=tok123;`)).toBe(true);
57
+ expect(c).toContain("Path=/");
58
+ expect(c).toContain("HttpOnly");
59
+ expect(c).toContain("Secure");
60
+ expect(c).toContain("SameSite=Lax");
61
+ expect(c).toContain("Max-Age=3600");
62
+ });
63
+
64
+ it("clear cookie expires immediately", () => {
65
+ expect(clearSessionCookie()).toContain("Max-Age=0");
66
+ });
67
+
68
+ it("parses our cookie out of a multi-cookie header, ignoring others", () => {
69
+ const req = new Request("https://prism.test/", {
70
+ headers: { cookie: `other=1; ${SESSION_COOKIE}=abc.def; theme=dark` },
71
+ });
72
+ expect(parseSessionCookie(req)).toBe("abc.def");
73
+ });
74
+
75
+ it("returns null when the cookie is absent", () => {
76
+ const req = new Request("https://prism.test/", { headers: { cookie: "other=1" } });
77
+ expect(parseSessionCookie(req)).toBeNull();
78
+ expect(parseSessionCookie(new Request("https://prism.test/"))).toBeNull();
79
+ });
80
+
81
+ it("generates a url-safe opaque token", () => {
82
+ const t = generateSessionToken();
83
+ expect(t).toMatch(/^[A-Za-z0-9_-]+$/);
84
+ expect(t.length).toBeGreaterThan(20);
85
+ });
86
+ });
87
+
88
+ describe("login timing oracle guard", () => {
89
+ it("the unknown-username dummy hash costs the same iterations as a real hash", () => {
90
+ const parsed = parsePhc(DUMMY_PASSWORD_HASH);
91
+ expect(parsed).not.toBeNull();
92
+ // Parity with the real KDF cost is what closes the enumeration side channel.
93
+ expect(parsed!.iterations).toBe(PBKDF2_ITERATIONS);
94
+ expect(parsed!.salt.length).toBe(16);
95
+ expect(parsed!.hash.length).toBe(32);
96
+ });
97
+ });
@@ -0,0 +1,217 @@
1
+ // Tests for chunkText (v0.19.4), the recursive character text splitter
2
+ // used by the RAG ingestion pipeline.
3
+ //
4
+ // Verifies the contract: respect separator hierarchy, return ordered chunks,
5
+ // preserve source text under concatenation (modulo overlap and whitespace
6
+ // trimming), and degrade gracefully on inputs with no useful boundaries.
7
+
8
+ import { describe, it, expect } from "vitest";
9
+ import { chunkText } from "../src/chunking";
10
+
11
+ const TARGET = 500;
12
+
13
+ describe("chunkText", () => {
14
+ describe("edge cases", () => {
15
+ it("returns empty array for empty input", () => {
16
+ expect(chunkText("")).toEqual([]);
17
+ });
18
+
19
+ it("returns single chunk for text under target size", () => {
20
+ const text = "Short paragraph that fits in one chunk.";
21
+ expect(chunkText(text)).toEqual([text]);
22
+ });
23
+
24
+ it("returns single chunk for text exactly at target size", () => {
25
+ const text = "a".repeat(TARGET);
26
+ const chunks = chunkText(text);
27
+ expect(chunks).toHaveLength(1);
28
+ expect(chunks[0]).toBe(text);
29
+ });
30
+ });
31
+
32
+ describe("paragraph boundaries (highest priority)", () => {
33
+ it("breaks on paragraph boundaries when text exceeds target", () => {
34
+ const para1 = "First paragraph. ".repeat(20); // ~340 chars
35
+ const para2 = "Second paragraph. ".repeat(20); // ~360 chars
36
+ const para3 = "Third paragraph. ".repeat(20); // ~340 chars
37
+ const text = `${para1}\n\n${para2}\n\n${para3}`;
38
+ const chunks = chunkText(text);
39
+
40
+ // Should produce multiple chunks broken at paragraph boundaries.
41
+ expect(chunks.length).toBeGreaterThanOrEqual(2);
42
+ // No chunk should contain text from a paragraph that the chunker
43
+ // shouldn't have split: paragraph boundary trumps mid-paragraph.
44
+ for (const chunk of chunks) {
45
+ // Each chunk's text should be reconstructible from the source
46
+ // (modulo trimming). Don't assert exact equality on counts since
47
+ // greedy merge may combine paragraph 1 + 2 if they fit.
48
+ expect(chunk.length).toBeGreaterThan(0);
49
+ }
50
+ });
51
+
52
+ it("respects ALL paragraph breaks, not just ones late in the window", () => {
53
+ // The old fixed-window chunker only looked at the last 1/3 of the
54
+ // 500-char window for break points. A paragraph break at char 50
55
+ // would have been ignored. The new chunker should respect it.
56
+ const short = "Tiny paragraph.";
57
+ const long = "Long second paragraph. ".repeat(40); // ~920 chars
58
+ const text = `${short}\n\n${long}`;
59
+ const chunks = chunkText(text);
60
+
61
+ // The short paragraph should appear at the start of the first chunk
62
+ // (possibly combined with the early part of the long paragraph if
63
+ // they fit under target).
64
+ expect(chunks[0]).toContain("Tiny paragraph.");
65
+ });
66
+ });
67
+
68
+ describe("fallback separator hierarchy", () => {
69
+ it("falls back to line breaks when no paragraph breaks present", () => {
70
+ // 20 lines, each ~50 chars, no double newlines.
71
+ const lines = Array(20).fill(0).map((_, i) => `Line ${i}: ${"x".repeat(40)}`);
72
+ const text = lines.join("\n");
73
+ const chunks = chunkText(text);
74
+
75
+ expect(chunks.length).toBeGreaterThanOrEqual(2);
76
+ for (const chunk of chunks) {
77
+ expect(chunk.length).toBeLessThanOrEqual(TARGET + CHUNK_OVERLAP_BUFFER);
78
+ }
79
+ });
80
+
81
+ it("falls back to sentence boundaries when no line breaks present", () => {
82
+ // Long run-on prose with periods, no newlines.
83
+ const sentence = "This is a sentence of moderate length about something. ";
84
+ const text = sentence.repeat(20); // ~1100 chars
85
+ const chunks = chunkText(text);
86
+
87
+ expect(chunks.length).toBeGreaterThanOrEqual(2);
88
+ // Each chunk should end at a sentence boundary (modulo final trim).
89
+ for (let i = 0; i < chunks.length - 1; i++) {
90
+ // Not all chunks will end with a period if the merge boundary
91
+ // happens to fall elsewhere, but most should.
92
+ expect(chunks[i].length).toBeLessThanOrEqual(TARGET + CHUNK_OVERLAP_BUFFER);
93
+ }
94
+ });
95
+
96
+ it("falls back to word boundaries when no sentence boundaries present", () => {
97
+ // A long run of words separated only by spaces, no punctuation.
98
+ const text = Array(200).fill("word").join(" "); // ~1000 chars
99
+ const chunks = chunkText(text);
100
+
101
+ expect(chunks.length).toBeGreaterThanOrEqual(2);
102
+ for (const chunk of chunks) {
103
+ expect(chunk.length).toBeLessThanOrEqual(TARGET + CHUNK_OVERLAP_BUFFER);
104
+ }
105
+ });
106
+
107
+ it("hard-splits when no separator at all is present", () => {
108
+ // A single long word, no spaces or punctuation.
109
+ const text = "a".repeat(1500);
110
+ const chunks = chunkText(text);
111
+
112
+ expect(chunks.length).toBeGreaterThanOrEqual(3); // Should split into 3+ chunks
113
+ // Concat without overlap should reconstruct the source (or close to it
114
+ // given overlap may carry some chars). Just check total content.
115
+ const totalChars = chunks.reduce((n, c) => n + c.length, 0);
116
+ expect(totalChars).toBeGreaterThanOrEqual(1500); // overlap may add chars
117
+ });
118
+ });
119
+
120
+ describe("overlap behavior", () => {
121
+ it("includes tail-overlap from previous chunk in next chunk", () => {
122
+ // Build a text long enough to force multiple chunks. Use distinctive
123
+ // ending content so we can verify it appears at the start of the next.
124
+ const head = "alpha ".repeat(40); // ~240 chars
125
+ const tail = "DISTINCTIVE_MARKER omega ".repeat(20); // ~500 chars
126
+ const text = `${head}${tail}`;
127
+ const chunks = chunkText(text);
128
+
129
+ // If multiple chunks, the start of chunk 2+ should contain content
130
+ // from the end of chunk 1.
131
+ if (chunks.length >= 2) {
132
+ // Overlap is 50 chars. Some marker text should bleed forward.
133
+ // Don't assert the exact overlap content; just verify the overlap
134
+ // mechanism produces chunks with reasonable length.
135
+ for (const chunk of chunks) {
136
+ expect(chunk.length).toBeGreaterThan(0);
137
+ expect(chunk.length).toBeLessThanOrEqual(TARGET + CHUNK_OVERLAP_BUFFER);
138
+ }
139
+ }
140
+ });
141
+ });
142
+
143
+ describe("realistic content", () => {
144
+ it("chunks a realistic multi-paragraph passage cleanly", () => {
145
+ const text = [
146
+ "The Northern Realms stretch from the frozen coast to the southern foothills.",
147
+ "Three great cities dot the landscape: Korvath in the north, Lyrian in the center, and Threehaven by the southern pass.",
148
+ "",
149
+ "Each city pays tribute to the High King, though their relationships with the crown vary considerably.",
150
+ "Korvath is the most loyal, having been founded by the royal line during the Frost Wars.",
151
+ "Lyrian, by contrast, considers itself an independent merchant republic that merely tolerates royal authority.",
152
+ "Threehaven is somewhere in between - loyal in word, autonomous in deed.",
153
+ "",
154
+ "Beyond the cities lie the hinterlands.",
155
+ "Small villages, scattered farms, and the great forests where the old gods are still remembered.",
156
+ ].join("\n");
157
+
158
+ const chunks = chunkText(text);
159
+ // Should split cleanly somewhere, but the whole text is short enough
160
+ // it might fit in one chunk too. Just verify it doesn't crash and
161
+ // produces non-empty output.
162
+ expect(chunks.length).toBeGreaterThanOrEqual(1);
163
+ for (const chunk of chunks) {
164
+ expect(chunk.length).toBeGreaterThan(0);
165
+ }
166
+ });
167
+
168
+ it("handles markdown-like content with mixed headers and prose", () => {
169
+ const text = [
170
+ "# Chapter 1: The Beginning",
171
+ "",
172
+ "It was a dark and stormy night when Lyra first arrived at the inn.",
173
+ "The bartender looked up briefly before returning to polishing his glasses.",
174
+ "She took a seat near the window and waited.",
175
+ "",
176
+ "## Section 1.1",
177
+ "",
178
+ "The room was small but warm, and the fire crackled steadily.",
179
+ "Outside, the rain hammered against the windows.",
180
+ "Lyra had been traveling for three days without proper shelter, and the warmth was almost overwhelming.",
181
+ "",
182
+ "She thought of the journey ahead.",
183
+ "The mountains lay another week's ride to the north.",
184
+ "Beyond them, the answers she sought - or so she hoped.",
185
+ ].join("\n");
186
+
187
+ const chunks = chunkText(text);
188
+ expect(chunks.length).toBeGreaterThanOrEqual(1);
189
+ // Verify no chunk is wildly oversized.
190
+ for (const chunk of chunks) {
191
+ expect(chunk.length).toBeLessThanOrEqual(TARGET + CHUNK_OVERLAP_BUFFER);
192
+ }
193
+ });
194
+ });
195
+
196
+ describe("size constraints", () => {
197
+ it("no chunk significantly exceeds target size on prose input", () => {
198
+ // Wikipedia-style prose paragraph repeated to force chunking.
199
+ const para = "The library was founded in 1923 by a consortium of merchants and scholars who believed that knowledge should be accessible to all citizens of the republic. Its initial collection numbered some twelve thousand volumes, gathered from estates across the region. The original building, designed by the architect Marcus Veridian, still stands at the corner of Third and Maple, though it has been substantially expanded over the centuries.";
200
+ const text = `${para}\n\n${para}\n\n${para}\n\n${para}`; // ~1880 chars
201
+
202
+ const chunks = chunkText(text);
203
+ expect(chunks.length).toBeGreaterThanOrEqual(2);
204
+ for (const chunk of chunks) {
205
+ // Allow target + overlap as the loose upper bound; greedy merge
206
+ // can produce chunks slightly over target when overlap is added.
207
+ expect(chunk.length).toBeLessThanOrEqual(TARGET + CHUNK_OVERLAP_BUFFER);
208
+ }
209
+ });
210
+ });
211
+ });
212
+
213
+ // Allow chunks to be slightly larger than target when overlap is included
214
+ // or when the recursive splitter produced a fragment between TARGET/2 and
215
+ // TARGET that gets combined with overlap. The chunker is "soft target"
216
+ // rather than "hard cap".
217
+ const CHUNK_OVERLAP_BUFFER = 100;