Production RAG, line by line · Forwards to the Worker over the DEMO service binding and returns its response · stage 4 of 6
Pages Function /api/demo/*
The upload and the question both reach one Pages Function, /api/demo/[[path]], which forwards the demo page's four routes. It builds new request headers: X-Demo-Key, the visitor's access key from the demo cookie, and X-Demo-Keep, whether this visitor may be recorded. It forwards the request to the demo Worker through the DEMO service binding, Cloudflare's direct connection from the site's functions to the demo Worker. After an upload or removal, it records an event from the Worker's reply. After a question, it starts recording the event without awaiting it, so the response is not delayed. On every route it returns the Worker's body to the browser unbuffered (the upload event reads only a clone), so a server-sent event stream reaches the page as the Worker writes it. It also deletes the Worker's internal headers from the response. In this repository the event recorder and the consent check are stand-ins. The recorder records nothing, and the consent check always returns false.
functions/api/demo/[[path]].ts76 / 76 lines on this page explainedlines 1-64,68-79 of 79; the rest are on other stage pages
functions/_lib/demo.ts28 / 28 lines on this page explainedevery line of the file
functions/_lib/track.ts27 / 27 lines on this page explainedevery line of the file
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
functions/api/demo/[[path]].ts The Pages Function for /api/demo/*: lines 1–64 (the forwarding, and the upload and removal events) and 68–79 (returning the Worker's response). Lines 65–67, the event recorded when an app is disconnected through /grants, belong to the MCP server's Connected apps.
// The demo page's endpoints: /api/demo/session, /files, /ask and /grants. Forwards each to// the demo Worker (demo/) through the DEMO binding, with the visitor's demo// cookie as X-Demo-Key. Nothing the visitor sends names the demo: the Worker// finds it by the key's hash. X-Demo-Keep tells the Worker whether this visitor may// be recorded (functions/_lib/track.ts): only then are the page text and the questions// kept past the 10-day purge. An upload, a removal, a question and an app disconnected are recorded as events.// A question asked with Accept: text/event-stream is answered as a stream (README.md, step 6), passed// through untouched; its event is handed to waitUntil, not awaited, so no byte waits on D1.
What this Function is Never runs
WhatThe header comment summarises the Function: the four routes it forwards, the demo account found by the access key's hash, X-Demo-Keep, the four events it records, and the ask's stream passed through with its event write given to waitUntil.
WhyIn Cloudflare Pages the [[path]] file name makes this a catch-all route. One Function serves every path under /api/demo/, and params.path holds the matched path segments.
// `grants` is the demo page's Connected apps: the apps allowed to use the demo through its MCP server (README.md, "The MCP server").constROUTES = newSet(["session", "files", "ask", "grants"]);
ROUTES: the four forwarded paths Module load
WhatThe four paths this Function forwards: session, files, ask and grants. grants serves the demo page's Connected apps for the MCP server.
WhyThe set is an allow-list. The Worker also serves /internal/* routes that only the site's own code may call, so a browser must never reach them. A path outside the set is answered 404 before anything is forwarded.
/** Headers the Worker answers the site with, never passed on to the browser. */constINTERNAL = ["X-Demo-Email", "X-Demo-Id", "X-Question-Id", "X-Mcp-Grant"];
INTERNAL: headers the browser never sees Module load
WhatX-Demo-Email, X-Demo-Id, X-Question-Id and X-Mcp-Grant: response headers the Worker sets for the site. Line 76 deletes them before the response reaches the browser.
WhyX-Demo-Email and X-Demo-Id carry the visitor's address and their demo account's id for the event record. X-Question-Id names a recorded question. X-Mcp-Grant is only a flag that triggers the disconnect event at line 66. The browser needs none of them. The upload's reply always sets X-Demo-Id, and sets X-Demo-Email only when the demo account's contact has an address (INGEST 7, about()).
The handler from the route check to the forward, and the upload and removal events. It runs on every call the demo page makes: a session read, an upload, a removal, a question and the Connected apps calls, so its blocks are marked Query time, which covers the request handling the site's functions share.
exportconstonRequest: PagesFunction<Env, "path"> = async ({ request, env, params, waitUntil }) => {// Turn the matched path back into one string and refuse anything that is not one of ours.const path = Array.isArray(params.path) ? params.path.join("/") : String(params.path ?? "");if (!ROUTES.has(path)) returnResponse.json({ error: "not found" }, { status: 404 });
One handler, known routes only Query time
WhatonRequest serves every HTTP method. It joins the catch-all's matched segments back into one path and answers 404 JSON to any path that is not exactly one of ROUTES.
WhyThe check compares the whole joined path, so files/anything is refused too. The Worker is only ever called at /api/<one of the four>.
// Without the binding there is no Worker to forward to.if (env.DEMO === undefined) returnResponse.json({ error: "The demo is not available right now." }, { status: 503 });
No binding, no Worker Query time
WhatIf the DEMO service binding (Cloudflare's direct connection from the site to the demo Worker) is missing, the Function answers 503 with "The demo is not available right now."
WhyThe demo Worker has no public URL (workers_dev = false in demo/wrangler.toml), so the service binding is the only way to reach it.
// Build fresh headers: the visitor's own are not passed on, only their demo key.const headers = newHeaders({ "Content-Type": "application/json" });const key = demoKey(request);if (key !== null) headers.set("X-Demo-Key", key);
Fresh headers, and the access key Query time
WhatThe new headers start with Content-Type: application/json. demoKey returns the demo cookie's key when the key is well-formed, and line 37 sets that key as X-Demo-Key. Without a key no header is set, and the Worker answers 401.
WhyThe visitor's own headers are never forwarded. A browser therefore cannot set X-Demo-Keep or X-Demo-Via itself, and the site's other cookies never reach the Worker. The Worker looks up the visitor's demo account (their row in the demos table) by the SHA-256 hash of this key and by nothing else.
// The page's `Accept: text/event-stream` goes through, so the Worker knows to stream its answer.const accept = request.headers.get("Accept");if (accept !== null) headers.set("Accept", accept);
Accept passes through Query time
WhatThe request's Accept header, if it has one, is copied onto the forwarded request.
WhyThe ask needs this header, because the Worker streams server-sent events only when Accept contains text/event-stream. On an upload the browser's default Accept is forwarded, and upload() ignores it.
// Tell the Worker whether this visitor's text and questions may be kept.const keep = mayRecord(request, env); headers.set("X-Demo-Keep", keep ? "1" : "0");
X-Demo-Keep: may the Worker keep the text? Query time
WhatmayRecord decides whether this visitor may be recorded, and the answer goes to the Worker as X-Demo-Keep: 1 or 0.
WhyOn an upload the Worker archives each page's text in archived_pages only when the header is 1 (INGEST 5). The site makes the decision because it knows the visitor's consent and location; the Worker only reads the header. In this repository mayRecord always returns false, so nothing is archived.
// Send the request on to the Worker's matching route.const answer = await env.DEMO.fetch(`https://demo/api/${path}`, {method: request.method, headers,body: request.method === "GET" || request.method === "HEAD" ? undefined : await request.text(), });
Forward through the service binding Query time
Whatenv.DEMO.fetch sends the request, with its original method and the new headers, to https://demo/api/<path>. For any method other than GET and HEAD, the body is read whole as text and sent on.
WhyA service binding calls the Worker directly, without a public URL. The host in the URL is a placeholder, and the Worker routes on the path and the method. Buffering the upload's JSON body here costs little, because the body holds only the pages' text; the PDF itself never leaves the browser.
// The Worker says whose demo it was, for the events below.const email = answer.headers.get("X-Demo-Email");const demo = answer.headers.get("X-Demo-Id");
Whose account it was Query time
WhatThe Worker's X-Demo-Email and X-Demo-Id response headers are read. Either may be null.
WhyThe site does not know which demo account the cookie's key belongs to. Only the Worker knows, after its hash lookup, and it returns the account's id and address in these headers for the event record.
// Record an upload or a removal, with the file's name and size from the Worker's reply.if (answer.ok && path === "files") {const body = (await answer.clone().json().catch(() => ({}))) as { name?: string; pages?: number; chars?: number };if (request.method === "DELETE") awaitserverEvent(env, request, "demo_remove", { demo, file: body.name }, email);elseawaitserverEvent(env, request, "demo_upload", { demo, file: body.name, pages: body.pages, chars: body.chars }, email); }
The upload and removal events Query time
WhatEvery request reaches this check; only a 2xx reply from /files is recorded. A clone of the response is parsed for name, pages and chars. A DELETE (a removal) is recorded as demo_remove with the file name. Any other method (the upload's POST) is recorded as demo_upload with the name, the page count and the character count. The event is awaited before the response is returned.
Whyclone() leaves the original body unread, so line 75 can still return it to the browser unchanged. Only successful uploads and removals are recorded. In this repository serverEvent is a no-op; on joelstevick.com it writes to the site's analytics database.
Starts recording the question's event without awaiting it, then returns the Worker's response with its body unread. It runs on every call the demo page makes: a session read, an upload, a removal, a question and the Connected apps calls, so its blocks are marked Query time, which covers the request handling the site's functions share.
// The ask's event write starts here but is not awaited (`waitUntil` keeps the function alive// until it ends), so the stream's first byte never waits on a D1 write.const question = answer.headers.get("X-Question-Id");if (path === "ask" && question !== null) waitUntil(serverEvent(env, request, "demo_ask", { demo, question }, email));
Record the question without delaying the response Query time
WhatOn the ask route, when the Worker sent X-Question-Id, the demo_ask event is passed to waitUntil instead of being awaited. Its email argument is the visitor's address from X-Demo-Email. In this repository serverEvent records nothing (functions/_lib/track.ts); a deployment supplies its own analytics.
Whyenv.DEMO.fetch resolves as soon as the Worker returns its headers, while the Worker is still writing the stream's body. Awaiting a D1 write here would delay the stream's first byte. The write starts at once and runs concurrently with the response, and waitUntil keeps the Pages Function alive until it settles. The Worker always sends X-Question-Id on a stream, because the headers go out before the answer is known. On a JSON reply it sends the header only when the questions row was written. A 400, a 401 (signed out), a 429, a 500 from an exception in a JSON ask, and a JSON answer whose row was not written carry no X-Question-Id, so none of them is recorded. Every streamed ask is recorded, and so is every JSON answer, fallback or model failure whose row was written.
// The Worker's body is handed to the browser as it is, a stream included: it is never read or// buffered here, so each event reaches the page as soon as the Worker has written it.const response = newResponse(answer.body, answer);
The body is passed through unread Query time
Whatnew Response(answer.body, answer) builds the reply from the Worker's ReadableStream and copies its status, status text and headers.
WhyThe ask's body is never read, cloned or buffered here, so each event: and data: frame reaches the browser as soon as the Worker writes it. Only a files reply is cloned, at line 60, to record its event. A clone would tee the stream, and a call to .text() would wait for the whole answer, which would defeat streaming. A new Response is needed because the headers of a fetched Response are immutable, and line 76 must delete some of them.
for (const name ofINTERNAL) response.headers.delete(name);return response;};
Delete the internal headers, return Query time
WhatThe four INTERNAL headers are deleted from the copied headers, and the response is returned. Every other header is kept: Content-Type: text/event-stream; charset=utf-8 and Cache-Control: no-store on a streamed ask, Content-Type: application/json on a JSON reply.
WhyThe four headers exist for the site's event records, and the browser has no use for them. The page reads the kept Content-Type to tell a stream from a JSON refusal.
functions/_lib/demo.ts The demo cookie: its name, the format of a valid key, reading the key from a request, checking a value's shape (isDemoKey) and building the Set-Cookie value.
// The demo's cookie: a random key whose SHA-256 the demo Worker stores. Read// here, never sent anywhere but the DEMO binding.
The access key Never runs
WhatThe cookie holds a random key, and the demo Worker stores only its SHA-256 hash.
WhyBecause the demos table holds only the key's SHA-256 hash, a leaked copy of the table cannot sign anyone in. The key itself is stored only in the visitor's cookie and in their /demo?key= link.
WhatThe name of the cookie that holds the visitor's access key.
WhydemoKey and demoCookie both use this one constant, so the name read and the name written cannot drift apart. It is exported, but no other module imports it.
// A key is 43 URL-safe base64 characters (32 random bytes).constFORMAT = /^[A-Za-z0-9_-]{43}$/;
43 URL-safe base64 characters Module load
WhatA key is exactly 43 characters from A–Z, a–z, 0–9, _ and -.
WhyThe Worker mints each key as 32 random bytes in unpadded base64url (randomKey(32), app.ts:138), which is always 43 characters. Any other value cannot be a key the Worker issued, so it is never forwarded.
The access key from the request's demo cookie. It runs on every call the demo page makes, through the /api/demo/* Pages Function, and on the MCP consent page, through functions/_lib/demo-mcp.ts, so it is marked Query time, the value for the request handling every route shares.
for (const part of (request.headers.get("Cookie") ?? "").split(";")) {const [name, ...value] = part.trim().split("=");if (name === COOKIE && FORMAT.test(value.join("="))) return value.join("="); }
Parse the Cookie header Query time
WhatThe Cookie header is split into name=value pairs. The value is re-joined on = in case it contains one. The first cookie named demo whose value matches FORMAT is returned.
WhyA malformed demo cookie is skipped, so a value the Worker could never have issued does not reach its hash lookup.
// Whether a value is shaped like a demo key.exportconst isDemoKey = (key: string | null): key is string => key !== null && FORMAT.test(key);
Key-shaped? Site request
WhatAn arrow function, defined at module load, that returns true when the value is a string matching FORMAT. TypeScript then narrows the value to string.
WhyThe forwarding code does not call it. functions/demo.ts calls it on the ?key= of a /demo link before setting the cookie, so the browser only ever stores a well-formed key.
// The Set-Cookie value that signs this browser in to a demo for 14 days.exportfunctiondemoCookie(key: string): string {return`${COOKIE}=${key}; Path=/; Max-Age=${14 * 86_400}; HttpOnly; Secure; SameSite=Lax`;}
HttpOnly, Secure, SameSite=Lax, 14 days Site request
WhatBuilds demo=<key> with Path=/, a Max-Age of 14 days, HttpOnly, Secure and SameSite=Lax. In this repository its only caller is functions/demo.ts, when it serves a /demo?key= link.
WhyHttpOnly hides the key from page scripts, so a script injected into the page cannot read it. Secure makes the browser send the cookie over HTTPS only. SameSite=Lax withholds it from cross-site subrequests, such as a POST from another site's form. Path=/ sends it with requests to /api/demo/*.
// A stand-in for the site's visitor analytics, which are not part of this repository. On// joelstevick.com this module records visits and events in the site's own D1 database, and// `mayRecord` answers whether this visitor may be recorded (in the EEA, the UK and Switzerland// only after they accept the cookie banner). Here nothing is recorded and no visitor has// consented, so the demo Worker is told X-Demo-Keep: 0 and keeps nothing past its 10-day purge.
A stand-in Never runs
WhatThe comment says the site's own analytics are not in this repository. On joelstevick.com this module records visits and events and answers whether a visitor may be recorded (in the EEA, the UK and Switzerland, only after the visitor accepts the cookie banner). In this repository nothing is recorded and no visitor has consented.
WhyThe forwarding code makes the same calls as on the site, so the public copy runs unchanged. Here the result is X-Demo-Keep: 0 on every request, so the Worker keeps nothing past the 10-day idle purge.
Whether this visitor may be recorded. In this repository, never. It runs on every call the demo page makes and on every request the site forwards to the demo Worker through forwardToDemo (the MCP server, its OAuth endpoints and discovery documents, and the document store), so it is marked Query time, the value for the request handling every route shares.
/** Whether this visitor may be recorded. The site checks consent and location; here, never. */exportfunctionmayRecord(_request: Request, _env: TrackEnv): boolean {returnfalse;}
Always false Query time
WhatIgnores its arguments and returns false.
WhyIts result becomes X-Demo-Keep. With false, the Worker writes no archived_pages rows on upload, and the questions are deleted with the documents after 10 idle days.
Records one server-side event. In this repository, it records nothing. It is called when a /demo?key= link is opened (functions/demo.ts), and on an upload, a removal, a question, a disconnected app and a consent decision, so it is marked Query time, the value for the request handling every route shares.
/** Records one server-side event (an upload, a removal, a question). Here, nothing. */exportasyncfunctionserverEvent(_env: TrackEnv,_request: Request,_type: string,_data: Record<string, unknown> = {},_email?: string | null,): Promise<void> {}
A no-op with the real signature Query time
WhatTakes the env, the request, an event type (demo_upload, demo_remove, demo_ask and others), a data object and an optional email, and resolves at once.
WhyKeeping the real signature lets the forwarding code run unchanged. Awaiting it on an upload costs nothing here; on the site the same call writes the event to the analytics database before the response is returned.