Production RAG, line by line · pagesOf() extracts the text with pdf.js; the change handler posts it · stage 2 of 6
Upload handler
When the visitor picks one or more PDFs, the page reads each file locally with pdf.js. It calls getTextContent page by page and joins each page's text items into plain text. It then posts the file name, the PDF's page count and the text of the non-empty pages as JSON to /api/demo/files. The PDF's bytes never leave the browser. The page processes the files one at a time, in the order of the input's FileList.
demo.html42 / 42 lines on this page explainedlines 256-297 of 505; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own
Import pdf.js once, point it at its worker In the browser
WhatThe first call imports the ES module build of pdf.js from cdnjs; ??= skips the import on later calls. workerSrc names the matching pdf.worker module, where pdf.js parses the document.
WhyParsing a PDF is CPU-heavy, so pdf.js runs it in a Web Worker and the page stays responsive. The library and its worker must be the same version, so both URLs are built from the one PDFJS base URL.
PDFJS = https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.10.38pdf.min.mjs and pdf.worker.min.mjs
WhatThe File is read into an ArrayBuffer and passed to getDocument as a Uint8Array. The loading task's promise resolves to the parsed document. An empty pages array is created.
WhyThe browser reads the PDF's bytes from disk through the File API, and pdf.js parses them locally. Only the name, the page count and each page's text go to the demo Worker, as the page's retention notice promises.
for (let n = 1; n <= pdf.numPages; n++) {const content = await (await pdf.getPage(n)).getTextContent();
Every page, in order In the browser
WhatFor n from 1 to numPages, the page is loaded and getTextContent returns its text items. Each item is a run of text with its position, a str and a hasEOL flag.
WhyPages are read one after another, so only one page's text content is built at a time. Page numbers start at 1, as in a PDF viewer, so a citation's page number opens the right page (#page=N).
const text = content.items.map((item) => item.str + (item.hasEOL ? "\n" : " ")).join("") .replace(/[ \t]+/g, " ").replace(/ *\n */g, "\n").trim(); pages.push({ page: n, text }); }
Items to plain text In the browser
WhatEach item's str is followed by a newline when pdf.js marks the end of a line (hasEOL), and by a space otherwise. Runs of spaces and tabs become one space, spaces around a newline are dropped, and the page text is trimmed. Every page is pushed as { page: n, text }, including empty ones; the return filters those out.
WhyKeeping the PDF's line breaks as \n lets the chunker (INGEST 4) recognise a sentence end at a line end (".\n"). Folding whitespace keeps the character count close to the visible text, and that count is what the demo account's 500,000-character limit measures.
The page count, and only pages with text In the browser
WhatReturns page_count, the PDF's own number of pages, and pages, with every empty page filtered out.
WhyEmpty pages (scans with no text layer, blank pages) are not sent. At INGEST 1 the Worker works out from page_count which pages had no text and lists them as skipped, so the visitor still sees them.
$("pdfs").addEventListener("change", async (event) => {const input = event.target;const status = $("upload-status");for (const file of [...input.files]) { status.textContent = `Reading ${file.name}…`;
One file at a time In the browser
WhatWhen the file input changes, the handler copies its FileList into an array and walks it with an awaited for…of loop. The status line, an aria-live region, names the file being read.
WhySequential uploads parse one PDF at a time and keep one request in flight, and the Worker's limit checks (INGEST 3) apply in FileList order. pagesOf never calls pdf.destroy(), so earlier documents stay loaded in the pdf.js worker for the life of the tab.
The status line while the page posts a three-page sample PDF's text to the Worker. The browser has already extracted the text, and the file list shows nothing new until the Worker replies. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
// Only the file name, its page count and each page's text: the file itself stays here.const response = awaitfetch("/api/demo/files", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: file.name, page_count, pages }), });
POST the text In the browser
WhatA same-origin fetch POSTs JSON with the file's name, page_count and the pages array of { page, text }. The browser attaches the HttpOnly demo cookie itself; the script never reads it.
WhyThe demo cookie, which holds the visitor's access key, is the only thing that identifies their demo account, and the site's Pages Function sends the key on as X-Demo-Key. The page makes no size check of its own. The Worker refuses an upload that would exceed the demo account's limits of 5 PDFs, 300 pages or 500,000 characters (INGEST 3, LIMITS in demo/src/app.ts).
const body = await response.json().catch(() => ({}));if (!response.ok) { status.textContent = body.error || `${file.name} could not be added.`; continue; }
A refusal is shown, and the next file goes on In the browser
WhatThe reply is parsed as JSON, and an unparseable body reads as {}. On a non-2xx status, the Worker's error message, or a generic one, goes in the status line, and continue moves to the next file.
WhyThe page shows whatever error the reply carries. The Worker's 400, 409, 413 and 500 messages are written for the visitor ("x.pdf is already uploaded.", or which limit was passed). A 401 shows its bare "signed out", and a reply with no error falls back to "<name> could not be added."
WhatAn object URL for the File is stored in opened under the file's name. listFile draws the file's row from the reply, and the status line says the file was added. showConnect may then reveal the Use it from Claude Code box, now that the demo account has a file.
WhyThe object URL lets a cited source's name open the visitor's own PDF at the cited page for the life of the tab, though the PDF was never uploaded.
The page after the Worker replies. listFile draws the new row with its page count and its remove button, and the status line says the file was added. At the pinned commit, the Worker writes the chunks' vectors before it sends this reply. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
} catch { status.textContent = `${file.name} could not be read as a PDF.`; }
Any exception In the browser
WhatAny error thrown in the try shows "<name> could not be read as a PDF." The causes are pdf.js failing to parse the file, a PDF that needs a password (none is supplied), or the fetch rejecting on a network failure.
WhyOne catch covers both the extraction and the POST, so a network failure gets the same message as an unreadable file. Either way, the loop goes on to the next file.
WhatAfter the last file, the input's value is reset to the empty string.
WhyA file input fires change only when its value changes. Clearing it lets the visitor choose the same file again, for example after removing it or after a failed upload.