All files / app-leaderboard/src/pages speculation.ts

100% Statements 5/5
100% Branches 1/1
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56                      12x                 12x                                   118x             1062x               118x    
/**
 * Speculation Rules for the Leaderboard pages: the browser fetches a page while the pointer rests on (or presses) its
 * link, so the navigation that follows starts from a warm response.
 *
 * `prefetch` only downloads the HTML; `prerender` also runs the page, scripts included, at the cost of more Worker and
 * D1 work per hover. Start with prefetch and switch SPECULATION_ACTION once the load is known to allow it; the client
 * script already holds back its side effects (the share-card upload) until a prerendered page is shown.
 */
export type SpeculationAction = 'prefetch' | 'prerender';
 
/** What the pages ask the browser to do with the links below. */
export const SPECULATION_ACTION: SpeculationAction = 'prefetch';
 
/**
 * Paths under / that must never be fetched ahead:
 * - `ruleset/*` and `lang/*` are GETs that rewrite a cookie and redirect (routes.ts), so a hover alone would switch the
 *   viewer's rules or language;
 * - `settings` depends on the signed-in session and holds the account forms;
 * - `assets/*`, the API reference and the share-card images are not pages to navigate to.
 */
export const SPECULATION_EXCLUDED_PATHS: readonly string[] = [
  '/ruleset/*',
  '/lang/*',
  '/settings',
  '/settings/*',
  '/assets/*',
  '/api-reference',
  '/api/*',
  '/scores/*/card',
  '/players/*/avatar',
];
 
/**
 * The rules as the JSON of a `<script type="speculationrules">`: same-origin links to / and below, less the
 * excluded paths and any link marked `data-no-speculate`. Paths are URL-pattern dictionaries, so any query matches.
 * `<` is escaped so the JSON cannot close its script element.
 */
export function speculationRules(action: SpeculationAction = SPECULATION_ACTION): string {
  const rules = {
    [action]: [
      {
        source: 'document',
        where: {
          and: [
            { or: [{ href_matches: { pathname: '/' } }, { href_matches: { pathname: '/*' } }] },
            ...SPECULATION_EXCLUDED_PATHS.map((pathname) => ({ not: { href_matches: { pathname } } })),
            { not: { selector_matches: '[data-no-speculate]' } },
          ],
        },
        eagerness: 'moderate',
      },
    ],
  };
  return JSON.stringify(rules).replaceAll('<', '\\u003c');
}