{"version":3,"file":"redirect.mjs","names":[],"sources":["../../../src/astro/middleware/redirect.ts"],"sourcesContent":["/**\n * Redirect middleware\n *\n * Intercepts incoming requests and checks for matching redirect rules.\n * Runs after runtime init (needs db) but before setup/auth (should handle\n * ALL routes, including public ones, and should be fast).\n *\n * Skip paths:\n * - /_emdash/* (admin UI, API routes, auth endpoints)\n * - /_image (Astro image optimization)\n * - Static assets (files with extensions)\n *\n * 404 logging happens post-response: if next() returns 404 and the path\n * wasn't already matched by a redirect, log it.\n */\n\nimport { defineMiddleware } from \"astro:middleware\";\n\nimport { RedirectRepository } from \"../../database/repositories/redirect.js\";\nimport { getDb } from \"../../loader.js\";\nimport { loadCachedRedirects, matchCachedPatterns } from \"../../redirects/cache.js\";\nimport { isTerminalStatus } from \"../../redirects/status.js\";\n\n/** Paths that should never be intercepted by redirects */\nconst SKIP_PREFIXES = [\"/_emdash\", \"/_image\"];\n\n/** Static asset extensions -- don't redirect file requests */\nconst ASSET_EXTENSION = /\\.\\w{1,10}$/;\n\ntype RedirectCode = 301 | 302 | 303 | 307 | 308;\n\nfunction isRedirectCode(code: number): code is RedirectCode {\n\treturn code === 301 || code === 302 || code === 303 || code === 307 || code === 308;\n}\n\nexport const onRequest = defineMiddleware(async (context, next) => {\n\tconst { pathname } = context.url;\n\n\t// Skip internal paths and static assets\n\tif (SKIP_PREFIXES.some((prefix) => pathname.startsWith(prefix))) {\n\t\treturn next();\n\t}\n\tif (ASSET_EXTENSION.test(pathname)) {\n\t\treturn next();\n\t}\n\n\t// Public visitors hit the runtime's anonymous fast path, which intentionally\n\t// omits `db` from `locals.emdash` to keep the public render boundary minimal\n\t// (issue #808). Fall back to `getDb()`, which transparently returns the\n\t// per-request scoped db (set in ALS by the runtime middleware) or the\n\t// singleton — same path the loader and template helpers use.\n\tlet db = context.locals.emdash?.db;\n\tif (!db) {\n\t\ttry {\n\t\t\tdb = await getDb();\n\t\t} catch {\n\t\t\treturn next();\n\t\t}\n\t}\n\n\ttry {\n\t\tconst repo = new RedirectRepository(db);\n\n\t\t// One query loads both exact and pattern rules into the cache; warm\n\t\t// requests issue zero queries. Empty-redirect sites cache an empty\n\t\t// Map + array, so the next request returns immediately without probing.\n\t\tconst cached = await loadCachedRedirects(() => repo.findAllEnabled());\n\n\t\t// 1. Exact match (O(1) Map lookup)\n\t\tlet exact = cached.exact.get(pathname);\n\t\tif (!exact && pathname.length > 1) {\n\t\t\tconst alt = pathname.endsWith(\"/\") ? pathname.slice(0, -1) : `${pathname}/`;\n\t\t\texact = cached.exact.get(alt);\n\t\t}\n\t\tif (exact) {\n\t\t\t// Terminal statuses (410 Gone / 451): serve the status directly,\n\t\t\t// with no Location header.\n\t\t\tif (isTerminalStatus(exact.type)) {\n\t\t\t\trepo.recordHit(exact.id).catch(() => {});\n\t\t\t\treturn new Response(null, { status: exact.type });\n\t\t\t}\n\t\t\tconst dest = exact.destination;\n\t\t\tif (dest.startsWith(\"//\") || dest.startsWith(\"/\\\\\")) return next();\n\t\t\trepo.recordHit(exact.id).catch(() => {});\n\t\t\tconst code = isRedirectCode(exact.type) ? exact.type : 301;\n\t\t\treturn context.redirect(dest, code);\n\t\t}\n\n\t\t// 2. Pattern match (compile once, match every request)\n\t\tconst patternMatch = matchCachedPatterns(cached.patterns, pathname);\n\t\tif (patternMatch) {\n\t\t\tconst { redirect, destination } = patternMatch;\n\t\t\t// Terminal statuses (410 Gone / 451): serve the status directly.\n\t\t\tif (isTerminalStatus(redirect.type)) {\n\t\t\t\trepo.recordHit(redirect.id).catch(() => {});\n\t\t\t\treturn new Response(null, { status: redirect.type });\n\t\t\t}\n\t\t\tif (destination.startsWith(\"//\") || destination.startsWith(\"/\\\\\")) return next();\n\t\t\trepo.recordHit(redirect.id).catch(() => {});\n\t\t\tconst code = isRedirectCode(redirect.type) ? redirect.type : 301;\n\t\t\treturn context.redirect(destination, code);\n\t\t}\n\n\t\t// No redirect matched -- proceed and check for 404\n\t\tconst response = await next();\n\n\t\t// Log misses (fire-and-forget) under the path the visitor requested.\n\t\t// Two shapes count as a miss: an unmatched route rendering the error\n\t\t// page with status 404, and a matched route answering a content miss\n\t\t// with a redirect to /404 (the documented template pattern) — there the\n\t\t// missed path exists only on this first pass, before the browser\n\t\t// follows the redirect. The error page itself is never logged: /404\n\t\t// answers 404 by design and carries no path information.\n\t\tconst location = response.headers.get(\"location\");\n\t\tconst missedByRedirect =\n\t\t\tisRedirectCode(response.status) && (location === \"/404\" || location === \"/404/\");\n\t\tconst missedDirectly = response.status === 404 && pathname !== \"/404\" && pathname !== \"/404/\";\n\t\tif (missedDirectly || missedByRedirect) {\n\t\t\tconst referrer = context.request.headers.get(\"referer\") ?? null;\n\t\t\tconst userAgent = context.request.headers.get(\"user-agent\") ?? null;\n\t\t\trepo\n\t\t\t\t.log404({\n\t\t\t\t\tpath: pathname,\n\t\t\t\t\treferrer,\n\t\t\t\t\tuserAgent,\n\t\t\t\t})\n\t\t\t\t.catch(() => {});\n\t\t}\n\n\t\treturn response;\n\t} catch {\n\t\t// If the redirects table doesn't exist yet (pre-migration), skip silently\n\t\treturn next();\n\t}\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,gBAAgB,CAAC,YAAY,UAAU;;AAG7C,MAAM,kBAAkB;AAIxB,SAAS,eAAe,MAAoC;AAC3D,QAAO,SAAS,OAAO,SAAS,OAAO,SAAS,OAAO,SAAS,OAAO,SAAS;;AAGjF,MAAa,YAAY,iBAAiB,OAAO,SAAS,SAAS;CAClE,MAAM,EAAE,aAAa,QAAQ;AAG7B,KAAI,cAAc,MAAM,WAAW,SAAS,WAAW,OAAO,CAAC,CAC9D,QAAO,MAAM;AAEd,KAAI,gBAAgB,KAAK,SAAS,CACjC,QAAO,MAAM;CAQd,IAAI,KAAK,QAAQ,OAAO,QAAQ;AAChC,KAAI,CAAC,GACJ,KAAI;AACH,OAAK,MAAM,OAAO;SACX;AACP,SAAO,MAAM;;AAIf,KAAI;EACH,MAAM,OAAO,IAAI,mBAA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