app/lib/speculation.mjs
44 lines and 4 functions in DrDustinEdwards/dustinedwards-info, at commit 1590ba4 on 2026-10-24. This file on GitHub.
Functions
| Function | Lines | Complexity | Covered | CRAP | Mutation |
|---|---|---|---|---|---|
| buildSpeculationRules | 32 to 53 | 1 | 100% | OkCRAP 1 | Ok100% |
| not | 34 to 34 | 1 | 100% | OkCRAP 1 | Ok100% |
| <anonymous:39> | 39 to 39 | 1 | 100% | OkCRAP 1 | Ok100% |
| <anonymous:41> | 41 to 41 | 1 | 100% | OkCRAP 1 | Ok100% |
Imports
It imports app/lib/json-ld.mjs. Imported by app/components/site-speculation.tsx, workers/csp.mjs.
Source
/**
* A document rule, not a URL list: it derives from the links on the page, so it cannot go stale.
*/
import { jsonLd } from "./json-ld.mjs";
const EXCLUDED_PREFIXES = ["/admin", "/lab", "/api", "/media"];
// `/search/ask` is billed: speculating it would spend model tokens on a click nobody made.
const EXCLUDED_PATHS = ["/login", "/theme", "/search/ask"];
const EXCLUDED_SUFFIXES = [".md", ".xml", ".json", ".txt"];
/**
* Not `immediate`: a cookie-carrying reader bypasses the cache, so immediate cost 4 to 5 extra
* origin document requests per page load. Chrome caps moderate speculations in flight.
*/
const DOCUMENT_EAGERNESS = "moderate";
/**
* Not `prerender`: moderate starts on pointerdown, and activating a prerender that has not painted
* swaps in a blank frame (measured in Chrome 151). Prefetch keeps paint holding and stays credentialed.
*/
export const DOCUMENT_ACTION = "prefetch";
/**
* @param {object} args
* @param {string} args.pathname the page the rules are being rendered on
* @returns {string} the JSON payload for the speculationrules script, escaped by `jsonLd` so no
* `</script` or `<!--` can appear whatever the pathname. The Worker hashes this same string.
*/
export function buildSpeculationRules({ pathname }) {
/** @param {string} pattern */
const not = (pattern) => ({ not: { href_matches: pattern } });
// The positive clause is a pathname pattern, which makes the rule same-origin by construction.
const conditions = [
{ href_matches: "/*" },
...EXCLUDED_PREFIXES.flatMap((prefix) => [not(prefix), not(`${prefix}/*`)]),
...EXCLUDED_PATHS.map(not),
...EXCLUDED_SUFFIXES.map((suffix) => not(`/*${suffix}`)),
/*
* A URLPattern `search` component, not a pathname glob: the glob spelling silently excludes
* every link on the page.
*/
{ not: { href_matches: { search: "(.+)" } } },
not(pathname),
];
return jsonLd({
[DOCUMENT_ACTION]: [{ where: { and: conditions }, eagerness: DOCUMENT_EAGERNESS }],
});
}