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61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
  searchOpenStaxBooks,
  fetchOpenStaxPageContent,
  fetchOpenStaxSources,
  extractSearchTerms,
  generatePageSlugs,
} from "../openstax";

// Mock global fetch
const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);

beforeEach(() => {
  vi.clearAllMocks();
});

// --- Test data ---

const mockBookSearchResponse = {
  meta: { total_count: 3 },
  items: [
    {
      id: 603,
      meta: {
        slug: "college-physics-2e",
        type: "books.Book",
        detail_url: "https://openstax.org/apps/cms/api/v2/pages/603/",
        html_url: "https://openstax.org/details/books/college-physics-2e",
        first_published_at: "2022-06-24T11:12:49.206000-05:00",
        locale: "en",
      },
      title: "College Physics 2e",
    },
    {
      id: 415,
      meta: {
        slug: "physics",
        type: "books.Book",
        detail_url: "https://openstax.org/apps/cms/api/v2/pages/415/",
        html_url: "https://openstax.org/details/books/physics",
        first_published_at: "2020-03-26T17:09:27.082000-05:00",
        locale: "en",
      },
      title: "Physics",
    },
  ],
};

const mockPageHtml = `
<!DOCTYPE html>
<html>
<head><title>1.1 Newton's Laws of Motion - College Physics 2e | OpenStax</title></head>
<body>
<nav>Skip to content</nav>
<header>Header content</header>
<div class="main-content">
  <h1>Newton's Laws of Motion</h1>
  <p>Newton's first law states that a body at rest remains at rest, or, if in motion,
  remains in motion at a constant velocity unless acted on by a net external force.
  This is also known as the law of inertia.</p>
  <p>Newton's second law of motion is closely related to the first law. It states that
  the acceleration of an object depends directly upon the net force acting upon the object,
  and inversely upon the mass of the object. As the force acting upon an object is increased,
  the acceleration of the object is increased. As the mass of an object is increased,
  the acceleration of the object is decreased.</p>
  <p>Newton's third law states that for every action there is an equal and opposite reaction.
  In other words, if object A exerts a force on object B, then object B also exerts an equal
  and opposite force on object A.</p>
  <div class="teacher-support">Teacher Support: This section covers Newton's laws.</div>
</div>
<footer>Citation/Attribution This book may not be used in the training of large language models.</footer>
</body>
</html>`;

const mockEmptyPageHtml = `
<!DOCTYPE html>
<html>
<head><title>Empty Page | OpenStax</title></head>
<body><div>Short.</div></body>
</html>`;

// --- searchOpenStaxBooks ---

describe("searchOpenStaxBooks", () => {
  it("returns parsed book search results", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => mockBookSearchResponse,
    });

    const results = await searchOpenStaxBooks("physics");
    expect(results).toHaveLength(2);
    expect(results[0]).toEqual({
      id: 603,
      title: "College Physics 2e",
      slug: "college-physics-2e",
      url: "https://openstax.org/details/books/college-physics-2e",
    });
  });

  it("returns empty array when no results", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });

    const results = await searchOpenStaxBooks("xyznonexistent");
    expect(results).toEqual([]);
  });

  it("throws on non-OK response", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: false,
      status: 500,
      statusText: "Internal Server Error",
    });

    await expect(searchOpenStaxBooks("physics")).rejects.toThrow("OpenStax book search failed");
  });

  it("passes correct query params to CMS API", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });

    await searchOpenStaxBooks("quantum mechanics", 5);

    const calledUrl = mockFetch.mock.calls[0][0] as string;
    expect(calledUrl).toContain("type=books.Book");
    expect(calledUrl).toContain("search=quantum+mechanics");
    expect(calledUrl).toContain("limit=5");
    expect(calledUrl).toContain("format=json");
  });

  it("uses User-Agent header", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });

    await searchOpenStaxBooks("test");
    const options = mockFetch.mock.calls[0][1] as { headers: Record<string, string> };
    expect(options.headers["User-Agent"]).toContain("RotNot");
  });

  it("generates fallback URL when html_url is missing", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({
        meta: { total_count: 1 },
        items: [
          {
            id: 1,
            title: "Test Book",
            meta: { slug: "test-book", html_url: null, type: "books.Book", detail_url: "", first_published_at: "", locale: "en" },
          },
        ],
      }),
    });

    const results = await searchOpenStaxBooks("test");
    expect(results[0].url).toBe("https://openstax.org/details/books/test-book");
  });
});

// --- fetchOpenStaxPageContent ---

describe("fetchOpenStaxPageContent", () => {
  it("extracts title and content from a valid page", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const result = await fetchOpenStaxPageContent("college-physics-2e", "1-1-newtons-laws-of-motion");
    expect(result).not.toBeNull();
    expect(result!.title).toBe("1.1 Newton's Laws of Motion");
    expect(result!.url).toBe("https://openstax.org/books/college-physics-2e/pages/1-1-newtons-laws-of-motion");
    expect(result!.content).toContain("Newton's first law states");
    expect(result!.content).toContain("law of inertia");
    expect(result!.content).toContain("third law states");
  });

  it("strips LLM training restriction notice", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const result = await fetchOpenStaxPageContent("college-physics-2e", "1-1-newtons-laws");
    expect(result!.content).not.toContain("training of large language models");
  });

  it("strips Citation/Attribution section", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const result = await fetchOpenStaxPageContent("college-physics-2e", "test");
    expect(result!.content).not.toContain("Citation/Attribution");
  });

  it("returns null for non-OK responses", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: false,
      status: 404,
      statusText: "Not Found",
    });

    const result = await fetchOpenStaxPageContent("nonexistent-book", "nonexistent-page");
    expect(result).toBeNull();
  });

  it("returns null for pages with too little content", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockEmptyPageHtml,
    });

    const result = await fetchOpenStaxPageContent("test-book", "empty-page");
    expect(result).toBeNull();
  });

  it("truncates content exceeding maxChars", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const result = await fetchOpenStaxPageContent("college-physics-2e", "test", 200);
    expect(result).not.toBeNull();
    expect(result!.content.length).toBeLessThanOrEqual(201); // 200 + "…"
    expect(result!.content).toMatch(/…$/);
  });

  it("constructs correct URL from book and page slugs", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    await fetchOpenStaxPageContent("biology-2e", "3-1-dna-replication");
    const calledUrl = mockFetch.mock.calls[0][0] as string;
    expect(calledUrl).toBe("https://openstax.org/books/biology-2e/pages/3-1-dna-replication");
  });

  it("strips nav, header, and footer elements", async () => {
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const result = await fetchOpenStaxPageContent("test", "test");
    expect(result!.content).not.toContain("Skip to content");
    expect(result!.content).not.toContain("Header content");
  });
});

// --- extractSearchTerms ---

describe("extractSearchTerms", () => {
  it("removes stop words and returns key terms", () => {
    expect(extractSearchTerms("How a hash table works")).toBe("hash table");
  });

  it("handles possessives and special characters", () => {
    expect(extractSearchTerms("Newton's three laws of motion")).toBe("newton's laws motion");
  });

  it("limits to 4 terms", () => {
    const result = extractSearchTerms("The economic factors behind the fall of the Roman Empire and its consequences");
    const terms = result.split(" ");
    expect(terms.length).toBeLessThanOrEqual(4);
  });

  it("filters single-character words", () => {
    expect(extractSearchTerms("What is a B-tree")).toBe("b-tree");
  });

  it("handles empty input", () => {
    expect(extractSearchTerms("")).toBe("");
  });

  it("handles all stop words", () => {
    expect(extractSearchTerms("how the a an")).toBe("");
  });
});

// --- generatePageSlugs ---

describe("generatePageSlugs", () => {
  it("generates slug from full topic name", () => {
    const slugs = generatePageSlugs("Newton's three laws of motion");
    expect(slugs).toContain("newtons-three-laws-of-motion");
  });

  it("generates key-term slug variant", () => {
    const slugs = generatePageSlugs("How a hash table works");
    expect(slugs).toContain("hash-table");
  });

  it("generates shorter word-prefix variants", () => {
    const slugs = generatePageSlugs("How public-key cryptography works");
    // Should include shorter variants from the first few significant words
    expect(slugs.some((s) => s.split("-").length <= 3)).toBe(true);
  });

  it("deduplicates slugs", () => {
    const slugs = generatePageSlugs("Hash table");
    const unique = new Set(slugs);
    expect(slugs.length).toBe(unique.size);
  });

  it("strips special characters", () => {
    const slugs = generatePageSlugs("Euler's identity & why it connects five constants");
    for (const slug of slugs) {
      expect(slug).not.toMatch(/[&']/);
    }
  });
});

// --- fetchOpenStaxSources ---

describe("fetchOpenStaxSources", () => {
  it("returns sections from domain-mapped books on successful page fetch", async () => {
    // First call: CMS search (search terms from topic)
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });
    // Second call: page content fetch for first domain book + first slug
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const results = await fetchOpenStaxSources("Newton's three laws of motion", "Physics", 1);
    expect(results).toHaveLength(1);
    expect(results[0].bookSlug).toBe("college-physics-2e");
    expect(results[0].excerpt).toContain("Newton");
    expect(results[0].url).toContain("openstax.org/books/college-physics-2e/pages/");
  });

  it("returns empty array when no domain books and no search results", async () => {
    // CMS search returns nothing
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });

    const results = await fetchOpenStaxSources("Some unknown topic", "UnknownDomain");
    expect(results).toEqual([]);
  });

  it("falls back to CMS search when domain has no mapped books", async () => {
    // CMS search
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => mockBookSearchResponse,
    });
    // Page fetch for first search result book + first slug
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const results = await fetchOpenStaxSources("Newton's laws", undefined, 1);
    expect(results.length).toBeGreaterThanOrEqual(0);
  });

  it("handles CMS search failures gracefully", async () => {
    // CMS search fails
    mockFetch.mockResolvedValueOnce({
      ok: false,
      status: 500,
      statusText: "Error",
    });
    // Still tries domain-mapped books; page fetch works
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const results = await fetchOpenStaxSources("Newton's laws", "Physics", 1);
    // Should still work since domain books are available
    expect(results.length).toBeGreaterThanOrEqual(0);
  });

  it("skips books where page content is too short", async () => {
    // CMS search
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });
    // First book, first slug → empty page
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockEmptyPageHtml,
    });
    // First book, second slug → empty page
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockEmptyPageHtml,
    });
    // First book, third slug → empty page
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockEmptyPageHtml,
    });
    // Second book, first slug → good page
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const results = await fetchOpenStaxSources("Newton's laws", "Physics", 1);
    expect(results.length).toBeLessThanOrEqual(1);
  });

  it("respects maxResults limit", async () => {
    // CMS search
    mockFetch.mockResolvedValueOnce({
      ok: true,
      json: async () => ({ meta: { total_count: 0 }, items: [] }),
    });
    // Page fetches — 2 books succeed
    mockFetch.mockResolvedValueOnce({
      ok: true,
      text: async () => mockPageHtml,
    });

    const results = await fetchOpenStaxSources("Newton's laws", "Physics", 1);
    expect(results.length).toBeLessThanOrEqual(1);
  });
});