From 1d1ce60ffea5e88bec8d66f53892321033a139fb Mon Sep 17 00:00:00 2001 From: damdug <155848353+damdug@users.noreply.github.com> Date: Tue, 10 Mar 2026 13:44:14 -0700 Subject: [PATCH 1/5] deployment ready --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index f29d986..ed6bd1a 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -3,7 +3,7 @@ name: Deploy to GitHub Pages on: push: branches: - - main + - development jobs: build-and-deploy: From bc18c05c0350e9ac5e4523af08c62471e320ae56 Mon Sep 17 00:00:00 2001 From: damdug <155848353+damdug@users.noreply.github.com> Date: Tue, 10 Mar 2026 15:13:24 -0700 Subject: [PATCH 2/5] deployment ready_X+ --- vercel.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/vercel.json b/vercel.json index ae7aa54..a14319e 100644 --- a/vercel.json +++ b/vercel.json @@ -1,5 +1,4 @@ { "framework": "astro", - "buildCommand": "npm run build", - "outputDirectory": "dist" + "buildCommand": "npm run build" } From a6d0c9767061590ec111b42c3ab9e62e24966d4d Mon Sep 17 00:00:00 2001 From: damdug <155848353+damdug@users.noreply.github.com> Date: Tue, 10 Mar 2026 15:56:57 -0700 Subject: [PATCH 3/5] fix: remove vercel.json to enable zero-config Astro SSR on Vercel --- vercel.json | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 vercel.json diff --git a/vercel.json b/vercel.json deleted file mode 100644 index a14319e..0000000 --- a/vercel.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "framework": "astro", - "buildCommand": "npm run build" -} From 5ab61fb75825f3076ed50b871939b40add3e8d73 Mon Sep 17 00:00:00 2001 From: damdug <155848353+damdug@users.noreply.github.com> Date: Tue, 10 Mar 2026 17:05:32 -0700 Subject: [PATCH 4/5] fix: add required environment block to GitHub Pages workflow --- .github/workflows/deploy.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index ed6bd1a..976e59e 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -8,6 +8,9 @@ on: jobs: build-and-deploy: runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} permissions: contents: read pages: write @@ -33,4 +36,5 @@ jobs: path: ./dist - name: Deploy to GitHub Pages + id: deployment uses: actions/deploy-pages@v4 From e6616765e24643af7bacad6d21221bbd7ceffda6 Mon Sep 17 00:00:00 2001 From: damdug <155848353+damdug@users.noreply.github.com> Date: Tue, 10 Mar 2026 17:17:08 -0700 Subject: [PATCH 5/5] fix: remove tracked .vercel artifacts and standardize package name --- .gitignore | 3 + .../_functions/_@astrojs-ssr-adapter.mjs | 1 - .../_functions/_astro-internal_middleware.mjs | 18 - .../_functions/chunks/BaseLayout_CRo5-Q8Q.mjs | 43 - .../_functions/chunks/SignupForm_DXiTqlCO.mjs | 17 - .../chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs | 1564 --------- .../chunks/_astro_assets_BkxcOWlh.mjs | 852 ----- .../chunks/_astro_content_C1JXYIk2.mjs | 438 --- .../_astro_data-layer-content_BUPw26ki.mjs | 3 - .../astro-designed-error-pages_C_Ez8g0J.mjs | 358 -- .../chunks/astro/server_D2NiA7f1.mjs | 2879 ----------------- .../_functions/chunks/consts_Bd-1c2lz.mjs | 33 - .../chunks/content-assets_DleWbedO.mjs | 3 - .../chunks/content-modules_Dz-S_Wwv.mjs | 3 - .../_functions/chunks/index_BL6Pqka4.mjs | 988 ------ .../_functions/chunks/index_BMBZwZG1.mjs | 2687 --------------- .../chunks/noop-middleware_hVW5dbP7.mjs | 9 - .../_functions/chunks/path_Bl04Vi8h.mjs | 111 - .../_functions/chunks/sharp_BTdjpfI2.mjs | 101 - .vercel/output/_functions/entry.mjs | 52 - .../output/_functions/manifest_BkFuMUuC.mjs | 102 - .vercel/output/_functions/noop-entrypoint.mjs | 3 - .../output/_functions/pages/_image.astro.mjs | 101 - .../output/_functions/pages/about.astro.mjs | 22 - .../_functions/pages/api/subscribe.astro.mjs | 47 - .../_functions/pages/api/verify.astro.mjs | 37 - .../output/_functions/pages/confirm.astro.mjs | 34 - .../output/_functions/pages/contact.astro.mjs | 22 - .vercel/output/_functions/pages/hdk.astro.mjs | 41 - .../output/_functions/pages/index.astro.mjs | 29 - .../output/_functions/pages/notes.astro.mjs | 35 - .../_functions/pages/notes/_slug_.astro.mjs | 1 - .../_functions/pages/one-rule.astro.mjs | 24 - .../_functions/pages/resources.astro.mjs | 1 - .../_functions/pages/work-with-me.astro.mjs | 22 - .vercel/output/_functions/renderers.mjs | 3 - .vercel/output/config.json | 63 - .../functions/_render.func/.vc-config.json | 6 - .../functions/_render.func/package.json | 3 - .../_render.func/src/pages/about.astro | 42 - .../_render.func/src/pages/confirm.astro | 14 - .../_render.func/src/pages/contact.astro | 31 - .../_render.func/src/pages/hdk.astro | 71 - .../_render.func/src/pages/index.astro | 50 - .../_render.func/src/pages/notes/index.astro | 49 - .../_render.func/src/pages/one-rule.astro | 77 - .../_render.func/src/pages/work-with-me.astro | 50 - .../output/static/assets/icons/facebook.svg | 3 - .vercel/output/static/assets/icons/github.svg | 3 - .../output/static/assets/icons/instagram.svg | 3 - .../output/static/assets/icons/linkedin.svg | 3 - .../output/static/assets/icons/twitter-x.svg | 3 - .../output/static/assets/icons/whatsapp.svg | 3 - .vercel/output/static/assets/logo/dune.svg | 6 - .vercel/output/static/favicon.ico | Bin 655 -> 0 bytes .vercel/output/static/favicon.svg | 9 - .../notes/the-next-step-doctrine/index.html | 34 - .../the-non-impedance-principle/index.html | 33 - .../static/notes/the-one-rule/index.html | 32 - .vercel/output/static/resources/index.html | 3 - package.json | 2 +- 61 files changed, 4 insertions(+), 11276 deletions(-) delete mode 100644 .vercel/output/_functions/_@astrojs-ssr-adapter.mjs delete mode 100644 .vercel/output/_functions/_astro-internal_middleware.mjs delete mode 100644 .vercel/output/_functions/chunks/BaseLayout_CRo5-Q8Q.mjs delete mode 100644 .vercel/output/_functions/chunks/SignupForm_DXiTqlCO.mjs delete mode 100644 .vercel/output/_functions/chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs delete mode 100644 .vercel/output/_functions/chunks/_astro_assets_BkxcOWlh.mjs delete mode 100644 .vercel/output/_functions/chunks/_astro_content_C1JXYIk2.mjs delete mode 100644 .vercel/output/_functions/chunks/_astro_data-layer-content_BUPw26ki.mjs delete mode 100644 .vercel/output/_functions/chunks/astro-designed-error-pages_C_Ez8g0J.mjs delete mode 100644 .vercel/output/_functions/chunks/astro/server_D2NiA7f1.mjs delete mode 100644 .vercel/output/_functions/chunks/consts_Bd-1c2lz.mjs delete mode 100644 .vercel/output/_functions/chunks/content-assets_DleWbedO.mjs delete mode 100644 .vercel/output/_functions/chunks/content-modules_Dz-S_Wwv.mjs delete mode 100644 .vercel/output/_functions/chunks/index_BL6Pqka4.mjs delete mode 100644 .vercel/output/_functions/chunks/index_BMBZwZG1.mjs delete mode 100644 .vercel/output/_functions/chunks/noop-middleware_hVW5dbP7.mjs delete mode 100644 .vercel/output/_functions/chunks/path_Bl04Vi8h.mjs delete mode 100644 .vercel/output/_functions/chunks/sharp_BTdjpfI2.mjs delete mode 100644 .vercel/output/_functions/entry.mjs delete mode 100644 .vercel/output/_functions/manifest_BkFuMUuC.mjs delete mode 100644 .vercel/output/_functions/noop-entrypoint.mjs delete mode 100644 .vercel/output/_functions/pages/_image.astro.mjs delete mode 100644 .vercel/output/_functions/pages/about.astro.mjs delete mode 100644 .vercel/output/_functions/pages/api/subscribe.astro.mjs delete mode 100644 .vercel/output/_functions/pages/api/verify.astro.mjs delete mode 100644 .vercel/output/_functions/pages/confirm.astro.mjs delete mode 100644 .vercel/output/_functions/pages/contact.astro.mjs delete mode 100644 .vercel/output/_functions/pages/hdk.astro.mjs delete mode 100644 .vercel/output/_functions/pages/index.astro.mjs delete mode 100644 .vercel/output/_functions/pages/notes.astro.mjs delete mode 100644 .vercel/output/_functions/pages/notes/_slug_.astro.mjs delete mode 100644 .vercel/output/_functions/pages/one-rule.astro.mjs delete mode 100644 .vercel/output/_functions/pages/resources.astro.mjs delete mode 100644 .vercel/output/_functions/pages/work-with-me.astro.mjs delete mode 100644 .vercel/output/_functions/renderers.mjs delete mode 100644 .vercel/output/config.json delete mode 100644 .vercel/output/functions/_render.func/.vc-config.json delete mode 100644 .vercel/output/functions/_render.func/package.json delete mode 100644 .vercel/output/functions/_render.func/src/pages/about.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/confirm.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/contact.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/hdk.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/index.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/notes/index.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/one-rule.astro delete mode 100644 .vercel/output/functions/_render.func/src/pages/work-with-me.astro delete mode 100644 .vercel/output/static/assets/icons/facebook.svg delete mode 100644 .vercel/output/static/assets/icons/github.svg delete mode 100644 .vercel/output/static/assets/icons/instagram.svg delete mode 100644 .vercel/output/static/assets/icons/linkedin.svg delete mode 100644 .vercel/output/static/assets/icons/twitter-x.svg delete mode 100644 .vercel/output/static/assets/icons/whatsapp.svg delete mode 100644 .vercel/output/static/assets/logo/dune.svg delete mode 100644 .vercel/output/static/favicon.ico delete mode 100644 .vercel/output/static/favicon.svg delete mode 100644 .vercel/output/static/notes/the-next-step-doctrine/index.html delete mode 100644 .vercel/output/static/notes/the-non-impedance-principle/index.html delete mode 100644 .vercel/output/static/notes/the-one-rule/index.html delete mode 100644 .vercel/output/static/resources/index.html diff --git a/.gitignore b/.gitignore index 16d54bb..b2be1d6 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,6 @@ pnpm-debug.log* # jetbrains setting folder .idea/ + +# Vercel build artifacts +.vercel/ diff --git a/.vercel/output/_functions/_@astrojs-ssr-adapter.mjs b/.vercel/output/_functions/_@astrojs-ssr-adapter.mjs deleted file mode 100644 index 5e920d9..0000000 --- a/.vercel/output/_functions/_@astrojs-ssr-adapter.mjs +++ /dev/null @@ -1 +0,0 @@ -export { c as createExports, a as start } from './chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs'; diff --git a/.vercel/output/_functions/_astro-internal_middleware.mjs b/.vercel/output/_functions/_astro-internal_middleware.mjs deleted file mode 100644 index d510665..0000000 --- a/.vercel/output/_functions/_astro-internal_middleware.mjs +++ /dev/null @@ -1,18 +0,0 @@ -import { d as defineMiddleware, s as sequence } from './chunks/index_BMBZwZG1.mjs'; -import 'es-module-lexer'; -import './chunks/astro-designed-error-pages_C_Ez8g0J.mjs'; -import 'piccolore'; -import './chunks/astro/server_D2NiA7f1.mjs'; -import 'clsx'; - -const onRequest$1 = defineMiddleware(async (_context, next) => { - return next(); -}); - -const onRequest = sequence( - - onRequest$1 - -); - -export { onRequest }; diff --git a/.vercel/output/_functions/chunks/BaseLayout_CRo5-Q8Q.mjs b/.vercel/output/_functions/chunks/BaseLayout_CRo5-Q8Q.mjs deleted file mode 100644 index 1a5b197..0000000 --- a/.vercel/output/_functions/chunks/BaseLayout_CRo5-Q8Q.mjs +++ /dev/null @@ -1,43 +0,0 @@ -import { b as createAstro, c as createComponent, m as maybeRenderHead, e as addAttribute, a as renderTemplate, r as renderComponent, j as renderHead, d as renderSlot } from './astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import 'clsx'; -/* empty css */ - -const $$Astro$1 = createAstro("https://damdug.com"); -const $$Navigation = createComponent(($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro$1, $$props, $$slots); - Astro2.self = $$Navigation; - const navItems = [ - { href: "/notes", label: "Notes" }, - { href: "/hdk", label: "HDK" }, - { href: "/resources", label: "Resources" }, - { href: "/work-with-me", label: "Work With Me" }, - { href: "/about", label: "About" } - ]; - const current = Astro2.url.pathname; - return renderTemplate`${maybeRenderHead()}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/Navigation.astro", void 0); - -const $$Header = createComponent(($$result, $$props, $$slots) => { - return renderTemplate`${maybeRenderHead()}
-DMG_ ${renderComponent($$result, "Navigation", $$Navigation, {})}
`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/Header.astro", void 0); - -const $$Footer = createComponent(($$result, $$props, $$slots) => { - const year = (/* @__PURE__ */ new Date()).getFullYear(); - return renderTemplate`${maybeRenderHead()}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/Footer.astro", void 0); - -const $$Astro = createAstro("https://damdug.com"); -const $$BaseLayout = createComponent(($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro, $$props, $$slots); - Astro2.self = $$BaseLayout; - const { title, description = "Douglas M. Galloway \u2014 Systems thinker. Builder. Coach." } = Astro2.props; - return renderTemplate` ${title} — DMG${renderHead()} ${renderComponent($$result, "Header", $$Header, {})}
${renderSlot($$result, $$slots["default"])}
${renderComponent($$result, "Footer", $$Footer, {})} `; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/layouts/BaseLayout.astro", void 0); - -export { $$BaseLayout as $ }; diff --git a/.vercel/output/_functions/chunks/SignupForm_DXiTqlCO.mjs b/.vercel/output/_functions/chunks/SignupForm_DXiTqlCO.mjs deleted file mode 100644 index 7185503..0000000 --- a/.vercel/output/_functions/chunks/SignupForm_DXiTqlCO.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import { b as createAstro, c as createComponent, m as maybeRenderHead, a as renderTemplate, e as addAttribute, i as renderScript } from './astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import 'clsx'; - -const $$Astro = createAstro("https://damdug.com"); -const $$SignupForm = createComponent(async ($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro, $$props, $$slots); - Astro2.self = $$SignupForm; - const { - label = "Get access to all resources \u2014 free.", - placeholder = "your@email.com", - buttonText = "Get Access" - } = Astro2.props; - return renderTemplate`${maybeRenderHead()}
${label && renderTemplate`

${label}

`}
${renderScript($$result, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/SignupForm.astro?astro&type=script&index=0&lang.ts")}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/SignupForm.astro", void 0); - -export { $$SignupForm as $ }; diff --git a/.vercel/output/_functions/chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs b/.vercel/output/_functions/chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs deleted file mode 100644 index d6e26ee..0000000 --- a/.vercel/output/_functions/chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs +++ /dev/null @@ -1,1564 +0,0 @@ -import { l as ROUTE_TYPE_HEADER, n as REROUTE_DIRECTIVE_HEADER, D as DEFAULT_404_COMPONENT, A as AstroError, o as ActionNotFoundError, p as clientAddressSymbol, L as LocalsNotAnObject, F as FailedToFindPageMapSSR, q as REROUTABLE_STATUS_CODES, s as responseSentSymbol, t as nodeRequestAbortControllerCleanupSymbol } from './astro/server_D2NiA7f1.mjs'; -import colors from 'piccolore'; -import 'clsx'; -import { D as DEFAULT_404_ROUTE, d as default404Instance, e as ensure404Route } from './astro-designed-error-pages_C_Ez8g0J.mjs'; -import 'es-module-lexer'; -import buffer from 'node:buffer'; -import crypto$1 from 'node:crypto'; -import { Http2ServerResponse } from 'node:http2'; -import { f as fileExtension, j as joinPaths, s as slash, p as prependForwardSlash, a as removeTrailingForwardSlash, b as appendForwardSlash, c as isInternalPath, d as collapseDuplicateTrailingSlashes, h as hasFileExtension } from './path_Bl04Vi8h.mjs'; -import { m as matchPattern } from './index_BL6Pqka4.mjs'; -import { r as requestIs404Or500, i as isRequestServerIsland, n as notFound, a as normalizeTheLocale, b as redirectToFallback, c as redirectToDefaultLocale, e as requestHasLocale, d as defineMiddleware, S as SERVER_ISLAND_COMPONENT, f as SERVER_ISLAND_ROUTE, g as createEndpoint, R as RouteCache, s as sequence, h as findRouteToRewrite, v as validateAndDecodePathname, m as matchRoute, j as RenderContext, P as PERSIST_SYMBOL, k as getSetCookiesFromResponse } from './index_BMBZwZG1.mjs'; -import { N as NOOP_MIDDLEWARE_FN } from './noop-middleware_hVW5dbP7.mjs'; -import '@vercel/routing-utils'; -import 'deterministic-object-hash'; -import nodePath from 'node:path'; - -function createI18nMiddleware(i18n, base, trailingSlash, format) { - if (!i18n) return (_, next) => next(); - const payload = { - ...i18n, - trailingSlash, - base, - format}; - const _redirectToDefaultLocale = redirectToDefaultLocale(payload); - const _noFoundForNonLocaleRoute = notFound(payload); - const _requestHasLocale = requestHasLocale(payload.locales); - const _redirectToFallback = redirectToFallback(payload); - const prefixAlways = (context, response) => { - const url = context.url; - if (url.pathname === base + "/" || url.pathname === base) { - return _redirectToDefaultLocale(context); - } else if (!_requestHasLocale(context)) { - return _noFoundForNonLocaleRoute(context, response); - } - return void 0; - }; - const prefixOtherLocales = (context, response) => { - let pathnameContainsDefaultLocale = false; - const url = context.url; - for (const segment of url.pathname.split("/")) { - if (normalizeTheLocale(segment) === normalizeTheLocale(i18n.defaultLocale)) { - pathnameContainsDefaultLocale = true; - break; - } - } - if (pathnameContainsDefaultLocale) { - const newLocation = url.pathname.replace(`/${i18n.defaultLocale}`, ""); - response.headers.set("Location", newLocation); - return _noFoundForNonLocaleRoute(context); - } - return void 0; - }; - return async (context, next) => { - const response = await next(); - const type = response.headers.get(ROUTE_TYPE_HEADER); - const isReroute = response.headers.get(REROUTE_DIRECTIVE_HEADER); - if (isReroute === "no" && typeof i18n.fallback === "undefined") { - return response; - } - if (type !== "page" && type !== "fallback") { - return response; - } - if (requestIs404Or500(context.request, base)) { - return response; - } - if (isRequestServerIsland(context.request, base)) { - return response; - } - const { currentLocale } = context; - switch (i18n.strategy) { - // NOTE: theoretically, we should never hit this code path - case "manual": { - return response; - } - case "domains-prefix-other-locales": { - if (localeHasntDomain(i18n, currentLocale)) { - const result = prefixOtherLocales(context, response); - if (result) { - return result; - } - } - break; - } - case "pathname-prefix-other-locales": { - const result = prefixOtherLocales(context, response); - if (result) { - return result; - } - break; - } - case "domains-prefix-always-no-redirect": { - if (localeHasntDomain(i18n, currentLocale)) { - const result = _noFoundForNonLocaleRoute(context, response); - if (result) { - return result; - } - } - break; - } - case "pathname-prefix-always-no-redirect": { - const result = _noFoundForNonLocaleRoute(context, response); - if (result) { - return result; - } - break; - } - case "pathname-prefix-always": { - const result = prefixAlways(context, response); - if (result) { - return result; - } - break; - } - case "domains-prefix-always": { - if (localeHasntDomain(i18n, currentLocale)) { - const result = prefixAlways(context, response); - if (result) { - return result; - } - } - break; - } - } - return _redirectToFallback(context, response); - }; -} -function localeHasntDomain(i18n, currentLocale) { - for (const domainLocale of Object.values(i18n.domainLookupTable)) { - if (domainLocale === currentLocale) { - return false; - } - } - return true; -} - -const NOOP_ACTIONS_MOD = { - server: {} -}; - -const FORM_CONTENT_TYPES = [ - "application/x-www-form-urlencoded", - "multipart/form-data", - "text/plain" -]; -const SAFE_METHODS = ["GET", "HEAD", "OPTIONS"]; -function createOriginCheckMiddleware() { - return defineMiddleware((context, next) => { - const { request, url, isPrerendered } = context; - if (isPrerendered) { - return next(); - } - if (SAFE_METHODS.includes(request.method)) { - return next(); - } - const isSameOrigin = request.headers.get("origin") === url.origin; - const hasContentType = request.headers.has("content-type"); - if (hasContentType) { - const formLikeHeader = hasFormLikeHeader(request.headers.get("content-type")); - if (formLikeHeader && !isSameOrigin) { - return new Response(`Cross-site ${request.method} form submissions are forbidden`, { - status: 403 - }); - } - } else { - if (!isSameOrigin) { - return new Response(`Cross-site ${request.method} form submissions are forbidden`, { - status: 403 - }); - } - } - return next(); - }); -} -function hasFormLikeHeader(contentType) { - if (contentType) { - for (const FORM_CONTENT_TYPE of FORM_CONTENT_TYPES) { - if (contentType.toLowerCase().includes(FORM_CONTENT_TYPE)) { - return true; - } - } - } - return false; -} - -function createDefaultRoutes(manifest) { - const root = new URL(manifest.hrefRoot); - return [ - { - instance: default404Instance, - matchesComponent: (filePath) => filePath.href === new URL(DEFAULT_404_COMPONENT, root).href, - route: DEFAULT_404_ROUTE.route, - component: DEFAULT_404_COMPONENT - }, - { - instance: createEndpoint(manifest), - matchesComponent: (filePath) => filePath.href === new URL(SERVER_ISLAND_COMPONENT, root).href, - route: SERVER_ISLAND_ROUTE, - component: SERVER_ISLAND_COMPONENT - } - ]; -} - -class Pipeline { - constructor(logger, manifest, runtimeMode, renderers, resolve, serverLike, streaming, adapterName = manifest.adapterName, clientDirectives = manifest.clientDirectives, inlinedScripts = manifest.inlinedScripts, compressHTML = manifest.compressHTML, i18n = manifest.i18n, middleware = manifest.middleware, routeCache = new RouteCache(logger, runtimeMode), site = manifest.site ? new URL(manifest.site) : void 0, defaultRoutes = createDefaultRoutes(manifest), actions = manifest.actions) { - this.logger = logger; - this.manifest = manifest; - this.runtimeMode = runtimeMode; - this.renderers = renderers; - this.resolve = resolve; - this.serverLike = serverLike; - this.streaming = streaming; - this.adapterName = adapterName; - this.clientDirectives = clientDirectives; - this.inlinedScripts = inlinedScripts; - this.compressHTML = compressHTML; - this.i18n = i18n; - this.middleware = middleware; - this.routeCache = routeCache; - this.site = site; - this.defaultRoutes = defaultRoutes; - this.actions = actions; - this.internalMiddleware = []; - if (i18n?.strategy !== "manual") { - this.internalMiddleware.push( - createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat) - ); - } - } - internalMiddleware; - resolvedMiddleware = void 0; - resolvedActions = void 0; - /** - * Resolves the middleware from the manifest, and returns the `onRequest` function. If `onRequest` isn't there, - * it returns a no-op function - */ - async getMiddleware() { - if (this.resolvedMiddleware) { - return this.resolvedMiddleware; - } else if (this.middleware) { - const middlewareInstance = await this.middleware(); - const onRequest = middlewareInstance.onRequest ?? NOOP_MIDDLEWARE_FN; - const internalMiddlewares = [onRequest]; - if (this.manifest.checkOrigin) { - internalMiddlewares.unshift(createOriginCheckMiddleware()); - } - this.resolvedMiddleware = sequence(...internalMiddlewares); - return this.resolvedMiddleware; - } else { - this.resolvedMiddleware = NOOP_MIDDLEWARE_FN; - return this.resolvedMiddleware; - } - } - setActions(actions) { - this.resolvedActions = actions; - } - async getActions() { - if (this.resolvedActions) { - return this.resolvedActions; - } else if (this.actions) { - return await this.actions(); - } - return NOOP_ACTIONS_MOD; - } - async getAction(path) { - const pathKeys = path.split(".").map((key) => decodeURIComponent(key)); - let { server } = await this.getActions(); - if (!server || !(typeof server === "object")) { - throw new TypeError( - `Expected \`server\` export in actions file to be an object. Received ${typeof server}.` - ); - } - for (const key of pathKeys) { - if (!(key in server)) { - throw new AstroError({ - ...ActionNotFoundError, - message: ActionNotFoundError.message(pathKeys.join(".")) - }); - } - server = server[key]; - } - if (typeof server !== "function") { - throw new TypeError( - `Expected handler for action ${pathKeys.join(".")} to be a function. Received ${typeof server}.` - ); - } - return server; - } -} - -const RedirectComponentInstance = { - default() { - return new Response(null, { - status: 301 - }); - } -}; -const RedirectSinglePageBuiltModule = { - page: () => Promise.resolve(RedirectComponentInstance), - onRequest: (_, next) => next(), - renderers: [] -}; - -const dateTimeFormat = new Intl.DateTimeFormat([], { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - hour12: false -}); -const levels = { - debug: 20, - info: 30, - warn: 40, - error: 50, - silent: 90 -}; -function log(opts, level, label, message, newLine = true) { - const logLevel = opts.level; - const dest = opts.dest; - const event = { - label, - level, - message, - newLine - }; - if (!isLogLevelEnabled(logLevel, level)) { - return; - } - dest.write(event); -} -function isLogLevelEnabled(configuredLogLevel, level) { - return levels[configuredLogLevel] <= levels[level]; -} -function info(opts, label, message, newLine = true) { - return log(opts, "info", label, message, newLine); -} -function warn(opts, label, message, newLine = true) { - return log(opts, "warn", label, message, newLine); -} -function error(opts, label, message, newLine = true) { - return log(opts, "error", label, message, newLine); -} -function debug(...args) { - if ("_astroGlobalDebug" in globalThis) { - globalThis._astroGlobalDebug(...args); - } -} -function getEventPrefix({ level, label }) { - const timestamp = `${dateTimeFormat.format(/* @__PURE__ */ new Date())}`; - const prefix = []; - if (level === "error" || level === "warn") { - prefix.push(colors.bold(timestamp)); - prefix.push(`[${level.toUpperCase()}]`); - } else { - prefix.push(timestamp); - } - if (label) { - prefix.push(`[${label}]`); - } - if (level === "error") { - return colors.red(prefix.join(" ")); - } - if (level === "warn") { - return colors.yellow(prefix.join(" ")); - } - if (prefix.length === 1) { - return colors.dim(prefix[0]); - } - return colors.dim(prefix[0]) + " " + colors.blue(prefix.splice(1).join(" ")); -} -class Logger { - options; - constructor(options) { - this.options = options; - } - info(label, message, newLine = true) { - info(this.options, label, message, newLine); - } - warn(label, message, newLine = true) { - warn(this.options, label, message, newLine); - } - error(label, message, newLine = true) { - error(this.options, label, message, newLine); - } - debug(label, ...messages) { - debug(label, ...messages); - } - level() { - return this.options.level; - } - forkIntegrationLogger(label) { - return new AstroIntegrationLogger(this.options, label); - } -} -class AstroIntegrationLogger { - options; - label; - constructor(logging, label) { - this.options = logging; - this.label = label; - } - /** - * Creates a new logger instance with a new label, but the same log options. - */ - fork(label) { - return new AstroIntegrationLogger(this.options, label); - } - info(message) { - info(this.options, this.label, message); - } - warn(message) { - warn(this.options, this.label, message); - } - error(message) { - error(this.options, this.label, message); - } - debug(message) { - debug(this.label, message); - } -} - -const consoleLogDestination = { - write(event) { - let dest = console.error; - if (levels[event.level] < levels["error"]) { - dest = console.info; - } - if (event.label === "SKIP_FORMAT") { - dest(event.message); - } else { - dest(getEventPrefix(event) + " " + event.message); - } - return true; - } -}; - -function getAssetsPrefix(fileExtension, assetsPrefix) { - let prefix = ""; - if (!assetsPrefix) { - prefix = ""; - } else if (typeof assetsPrefix === "string") { - prefix = assetsPrefix; - } else { - const dotLessFileExtension = fileExtension.slice(1); - prefix = assetsPrefix[dotLessFileExtension] || assetsPrefix.fallback; - } - return prefix; -} - -function createAssetLink(href, base, assetsPrefix, queryParams) { - let url = ""; - if (assetsPrefix) { - const pf = getAssetsPrefix(fileExtension(href), assetsPrefix); - url = joinPaths(pf, slash(href)); - } else if (base) { - url = prependForwardSlash(joinPaths(base, slash(href))); - } else { - url = href; - } - return url; -} -function createStylesheetElement(stylesheet, base, assetsPrefix, queryParams) { - if (stylesheet.type === "inline") { - return { - props: {}, - children: stylesheet.content - }; - } else { - return { - props: { - rel: "stylesheet", - href: createAssetLink(stylesheet.src, base, assetsPrefix) - }, - children: "" - }; - } -} -function createStylesheetElementSet(stylesheets, base, assetsPrefix, queryParams) { - return new Set( - stylesheets.map((s) => createStylesheetElement(s, base, assetsPrefix)) - ); -} -function createModuleScriptElement(script, base, assetsPrefix, queryParams) { - if (script.type === "external") { - return createModuleScriptElementWithSrc(script.value, base, assetsPrefix); - } else { - return { - props: { - type: "module" - }, - children: script.value - }; - } -} -function createModuleScriptElementWithSrc(src, base, assetsPrefix, queryParams) { - return { - props: { - type: "module", - src: createAssetLink(src, base, assetsPrefix) - }, - children: "" - }; -} - -function redirectTemplate({ - status, - absoluteLocation, - relativeLocation, - from -}) { - const delay = status === 302 ? 2 : 0; - return ` -Redirecting to: ${relativeLocation} - - - - - Redirecting ${from ? `from ${from} ` : ""}to ${relativeLocation} -`; -} - -class AppPipeline extends Pipeline { - static create({ - logger, - manifest, - runtimeMode, - renderers, - resolve, - serverLike, - streaming, - defaultRoutes - }) { - const pipeline = new AppPipeline( - logger, - manifest, - runtimeMode, - renderers, - resolve, - serverLike, - streaming, - void 0, - void 0, - void 0, - void 0, - void 0, - void 0, - void 0, - void 0, - defaultRoutes - ); - return pipeline; - } - headElements(routeData) { - const routeInfo = this.manifest.routes.find((route) => route.routeData === routeData); - const links = /* @__PURE__ */ new Set(); - const scripts = /* @__PURE__ */ new Set(); - const styles = createStylesheetElementSet(routeInfo?.styles ?? []); - for (const script of routeInfo?.scripts ?? []) { - if ("stage" in script) { - if (script.stage === "head-inline") { - scripts.add({ - props: {}, - children: script.children - }); - } - } else { - scripts.add(createModuleScriptElement(script)); - } - } - return { links, styles, scripts }; - } - componentMetadata() { - } - async getComponentByRoute(routeData) { - const module = await this.getModuleForRoute(routeData); - return module.page(); - } - async tryRewrite(payload, request) { - const { newUrl, pathname, routeData } = findRouteToRewrite({ - payload, - request, - routes: this.manifest?.routes.map((r) => r.routeData), - trailingSlash: this.manifest.trailingSlash, - buildFormat: this.manifest.buildFormat, - base: this.manifest.base, - outDir: this.serverLike ? this.manifest.buildClientDir : this.manifest.outDir - }); - const componentInstance = await this.getComponentByRoute(routeData); - return { newUrl, pathname, componentInstance, routeData }; - } - async getModuleForRoute(route) { - for (const defaultRoute of this.defaultRoutes) { - if (route.component === defaultRoute.component) { - return { - page: () => Promise.resolve(defaultRoute.instance), - renderers: [] - }; - } - } - if (route.type === "redirect") { - return RedirectSinglePageBuiltModule; - } else { - if (this.manifest.pageMap) { - const importComponentInstance = this.manifest.pageMap.get(route.component); - if (!importComponentInstance) { - throw new Error( - `Unexpectedly unable to find a component instance for route ${route.route}` - ); - } - return await importComponentInstance(); - } else if (this.manifest.pageModule) { - return this.manifest.pageModule; - } - throw new Error( - "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue." - ); - } - } -} - -class App { - #manifest; - #manifestData; - #logger = new Logger({ - dest: consoleLogDestination, - level: "info" - }); - #baseWithoutTrailingSlash; - #pipeline; - #adapterLogger; - constructor(manifest, streaming = true) { - this.#manifest = manifest; - this.#manifestData = { - routes: manifest.routes.map((route) => route.routeData) - }; - ensure404Route(this.#manifestData); - this.#baseWithoutTrailingSlash = removeTrailingForwardSlash(this.#manifest.base); - this.#pipeline = this.#createPipeline(streaming); - this.#adapterLogger = new AstroIntegrationLogger( - this.#logger.options, - this.#manifest.adapterName - ); - } - getAdapterLogger() { - return this.#adapterLogger; - } - getAllowedDomains() { - return this.#manifest.allowedDomains; - } - get manifest() { - return this.#manifest; - } - set manifest(value) { - this.#manifest = value; - } - matchesAllowedDomains(forwardedHost, protocol) { - return App.validateForwardedHost(forwardedHost, this.#manifest.allowedDomains, protocol); - } - static validateForwardedHost(forwardedHost, allowedDomains, protocol) { - if (!allowedDomains || allowedDomains.length === 0) { - return false; - } - try { - const testUrl = new URL(`${protocol || "https"}://${forwardedHost}`); - return allowedDomains.some((pattern) => { - return matchPattern(testUrl, pattern); - }); - } catch { - return false; - } - } - /** - * Validate a hostname by rejecting any with path separators. - * Prevents path injection attacks. Invalid hostnames return undefined. - */ - static sanitizeHost(hostname) { - if (!hostname) return void 0; - if (/[/\\]/.test(hostname)) return void 0; - return hostname; - } - /** - * Validate forwarded headers (proto, host, port) against allowedDomains. - * Returns validated values or undefined for rejected headers. - * Uses strict defaults: http/https only for proto, rejects port if not in allowedDomains. - */ - static validateForwardedHeaders(forwardedProtocol, forwardedHost, forwardedPort, allowedDomains) { - const result = {}; - if (forwardedProtocol) { - if (allowedDomains && allowedDomains.length > 0) { - const hasProtocolPatterns = allowedDomains.some( - (pattern) => pattern.protocol !== void 0 - ); - if (hasProtocolPatterns) { - try { - const testUrl = new URL(`${forwardedProtocol}://example.com`); - const isAllowed = allowedDomains.some((pattern) => matchPattern(testUrl, pattern)); - if (isAllowed) { - result.protocol = forwardedProtocol; - } - } catch { - } - } else if (/^https?$/.test(forwardedProtocol)) { - result.protocol = forwardedProtocol; - } - } else if (/^https?$/.test(forwardedProtocol)) { - result.protocol = forwardedProtocol; - } - } - if (forwardedPort && allowedDomains && allowedDomains.length > 0) { - const hasPortPatterns = allowedDomains.some((pattern) => pattern.port !== void 0); - if (hasPortPatterns) { - const isAllowed = allowedDomains.some((pattern) => pattern.port === forwardedPort); - if (isAllowed) { - result.port = forwardedPort; - } - } - } - if (forwardedHost && forwardedHost.length > 0 && allowedDomains && allowedDomains.length > 0) { - const protoForValidation = result.protocol || "https"; - const sanitized = App.sanitizeHost(forwardedHost); - if (sanitized) { - try { - const hostnameOnly = sanitized.split(":")[0]; - const portFromHost = sanitized.includes(":") ? sanitized.split(":")[1] : void 0; - const portForValidation = result.port || portFromHost; - const hostWithPort = portForValidation ? `${hostnameOnly}:${portForValidation}` : hostnameOnly; - const testUrl = new URL(`${protoForValidation}://${hostWithPort}`); - const isAllowed = allowedDomains.some((pattern) => matchPattern(testUrl, pattern)); - if (isAllowed) { - result.host = sanitized; - } - } catch { - } - } - } - return result; - } - /** - * Creates a pipeline by reading the stored manifest - * - * @param streaming - * @private - */ - #createPipeline(streaming = false) { - return AppPipeline.create({ - logger: this.#logger, - manifest: this.#manifest, - runtimeMode: "production", - renderers: this.#manifest.renderers, - defaultRoutes: createDefaultRoutes(this.#manifest), - resolve: async (specifier) => { - if (!(specifier in this.#manifest.entryModules)) { - throw new Error(`Unable to resolve [${specifier}]`); - } - const bundlePath = this.#manifest.entryModules[specifier]; - if (bundlePath.startsWith("data:") || bundlePath.length === 0) { - return bundlePath; - } else { - return createAssetLink(bundlePath, this.#manifest.base, this.#manifest.assetsPrefix); - } - }, - serverLike: true, - streaming - }); - } - set setManifestData(newManifestData) { - this.#manifestData = newManifestData; - } - removeBase(pathname) { - if (pathname.startsWith(this.#manifest.base)) { - return pathname.slice(this.#baseWithoutTrailingSlash.length + 1); - } - return pathname; - } - /** - * It removes the base from the request URL, prepends it with a forward slash and attempts to decoded it. - * - * If the decoding fails, it logs the error and return the pathname as is. - * @param request - * @private - */ - #getPathnameFromRequest(request) { - const url = new URL(request.url); - const pathname = prependForwardSlash(this.removeBase(url.pathname)); - try { - return validateAndDecodePathname(pathname); - } catch (e) { - this.getAdapterLogger().error(e.toString()); - return pathname; - } - } - /** - * Given a `Request`, it returns the `RouteData` that matches its `pathname`. By default, prerendered - * routes aren't returned, even if they are matched. - * - * When `allowPrerenderedRoutes` is `true`, the function returns matched prerendered routes too. - * @param request - * @param allowPrerenderedRoutes - */ - match(request, allowPrerenderedRoutes = false) { - const url = new URL(request.url); - if (this.#manifest.assets.has(url.pathname)) return void 0; - let pathname = this.#computePathnameFromDomain(request); - if (!pathname) { - pathname = prependForwardSlash(this.removeBase(url.pathname)); - } - try { - pathname = validateAndDecodePathname(pathname); - } catch { - return void 0; - } - let routeData = matchRoute(pathname, this.#manifestData); - if (!routeData) return void 0; - if (allowPrerenderedRoutes) { - return routeData; - } else if (routeData.prerender) { - return void 0; - } - return routeData; - } - #computePathnameFromDomain(request) { - let pathname = void 0; - const url = new URL(request.url); - if (this.#manifest.i18n && (this.#manifest.i18n.strategy === "domains-prefix-always" || this.#manifest.i18n.strategy === "domains-prefix-other-locales" || this.#manifest.i18n.strategy === "domains-prefix-always-no-redirect")) { - const validated = App.validateForwardedHeaders( - request.headers.get("X-Forwarded-Proto") ?? void 0, - request.headers.get("X-Forwarded-Host") ?? void 0, - request.headers.get("X-Forwarded-Port") ?? void 0, - this.#manifest.allowedDomains - ); - let protocol = validated.protocol ? validated.protocol + ":" : url.protocol; - let host = validated.host ?? request.headers.get("Host"); - if (host && protocol) { - host = host.split(":")[0]; - try { - let locale; - const hostAsUrl = new URL(`${protocol}//${host}`); - for (const [domainKey, localeValue] of Object.entries( - this.#manifest.i18n.domainLookupTable - )) { - const domainKeyAsUrl = new URL(domainKey); - if (hostAsUrl.host === domainKeyAsUrl.host && hostAsUrl.protocol === domainKeyAsUrl.protocol) { - locale = localeValue; - break; - } - } - if (locale) { - pathname = prependForwardSlash( - joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname)) - ); - if (url.pathname.endsWith("/")) { - pathname = appendForwardSlash(pathname); - } - } - } catch (e) { - this.#logger.error( - "router", - `Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.` - ); - this.#logger.error("router", `Error: ${e}`); - } - } - } - return pathname; - } - #redirectTrailingSlash(pathname) { - const { trailingSlash } = this.#manifest; - if (pathname === "/" || isInternalPath(pathname)) { - return pathname; - } - const path = collapseDuplicateTrailingSlashes(pathname, trailingSlash !== "never"); - if (path !== pathname) { - return path; - } - if (trailingSlash === "ignore") { - return pathname; - } - if (trailingSlash === "always" && !hasFileExtension(pathname)) { - return appendForwardSlash(pathname); - } - if (trailingSlash === "never") { - return removeTrailingForwardSlash(pathname); - } - return pathname; - } - async render(request, renderOptions) { - let routeData; - let locals; - let clientAddress; - let addCookieHeader; - const url = new URL(request.url); - const redirect = this.#redirectTrailingSlash(url.pathname); - const prerenderedErrorPageFetch = renderOptions?.prerenderedErrorPageFetch ?? fetch; - if (redirect !== url.pathname) { - const status = request.method === "GET" ? 301 : 308; - return new Response( - redirectTemplate({ - status, - relativeLocation: url.pathname, - absoluteLocation: redirect, - from: request.url - }), - { - status, - headers: { - location: redirect + url.search - } - } - ); - } - addCookieHeader = renderOptions?.addCookieHeader; - clientAddress = renderOptions?.clientAddress ?? Reflect.get(request, clientAddressSymbol); - routeData = renderOptions?.routeData; - locals = renderOptions?.locals; - if (routeData) { - this.#logger.debug( - "router", - "The adapter " + this.#manifest.adapterName + " provided a custom RouteData for ", - request.url - ); - this.#logger.debug("router", "RouteData:\n" + routeData); - } - if (locals) { - if (typeof locals !== "object") { - const error = new AstroError(LocalsNotAnObject); - this.#logger.error(null, error.stack); - return this.#renderError(request, { - status: 500, - error, - clientAddress, - prerenderedErrorPageFetch - }); - } - } - if (!routeData) { - routeData = this.match(request); - this.#logger.debug("router", "Astro matched the following route for " + request.url); - this.#logger.debug("router", "RouteData:\n" + routeData); - } - if (!routeData) { - routeData = this.#manifestData.routes.find( - (route) => route.component === "404.astro" || route.component === DEFAULT_404_COMPONENT - ); - } - if (!routeData) { - this.#logger.debug("router", "Astro hasn't found routes that match " + request.url); - this.#logger.debug("router", "Here's the available routes:\n", this.#manifestData); - return this.#renderError(request, { - locals, - status: 404, - clientAddress, - prerenderedErrorPageFetch - }); - } - const pathname = this.#getPathnameFromRequest(request); - const defaultStatus = this.#getDefaultStatusCode(routeData, pathname); - let response; - let session; - try { - const mod = await this.#pipeline.getModuleForRoute(routeData); - if (!mod || typeof mod.page !== "function") { - throw new AstroError({ - ...FailedToFindPageMapSSR, - message: `The module for route "${routeData.route}" does not have a valid page function. This may occur when using static output mode with an SSR adapter.` - }); - } - const renderContext = await RenderContext.create({ - pipeline: this.#pipeline, - locals, - pathname, - request, - routeData, - status: defaultStatus, - clientAddress - }); - session = renderContext.session; - response = await renderContext.render(await mod.page()); - } catch (err) { - this.#logger.error("router", "Error while trying to render the route " + routeData.route); - this.#logger.error(null, err.stack || err.message || String(err)); - return this.#renderError(request, { - locals, - status: 500, - error: err, - clientAddress, - prerenderedErrorPageFetch - }); - } finally { - await session?.[PERSIST_SYMBOL](); - } - if (REROUTABLE_STATUS_CODES.includes(response.status) && // If the body isn't null, that means the user sets the 404 status - // but uses the current route to handle the 404 - response.body === null && response.headers.get(REROUTE_DIRECTIVE_HEADER) !== "no") { - return this.#renderError(request, { - locals, - response, - status: response.status, - // We don't have an error to report here. Passing null means we pass nothing intentionally - // while undefined means there's no error - error: response.status === 500 ? null : void 0, - clientAddress, - prerenderedErrorPageFetch - }); - } - if (response.headers.has(REROUTE_DIRECTIVE_HEADER)) { - response.headers.delete(REROUTE_DIRECTIVE_HEADER); - } - if (addCookieHeader) { - for (const setCookieHeaderValue of App.getSetCookieFromResponse(response)) { - response.headers.append("set-cookie", setCookieHeaderValue); - } - } - Reflect.set(response, responseSentSymbol, true); - return response; - } - setCookieHeaders(response) { - return getSetCookiesFromResponse(response); - } - /** - * Reads all the cookies written by `Astro.cookie.set()` onto the passed response. - * For example, - * ```ts - * for (const cookie_ of App.getSetCookieFromResponse(response)) { - * const cookie: string = cookie_ - * } - * ``` - * @param response The response to read cookies from. - * @returns An iterator that yields key-value pairs as equal-sign-separated strings. - */ - static getSetCookieFromResponse = getSetCookiesFromResponse; - /** - * If it is a known error code, try sending the according page (e.g. 404.astro / 500.astro). - * This also handles pre-rendered /404 or /500 routes - */ - async #renderError(request, { - locals, - status, - response: originalResponse, - skipMiddleware = false, - error, - clientAddress, - prerenderedErrorPageFetch - }) { - const errorRoutePath = `/${status}${this.#manifest.trailingSlash === "always" ? "/" : ""}`; - const errorRouteData = matchRoute(errorRoutePath, this.#manifestData); - const url = new URL(request.url); - if (errorRouteData) { - if (errorRouteData.prerender) { - const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? ".html" : ""; - const statusURL = new URL( - `${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`, - url - ); - if (statusURL.toString() !== request.url) { - const response2 = await prerenderedErrorPageFetch(statusURL.toString()); - const override = { status, removeContentEncodingHeaders: true }; - return this.#mergeResponses(response2, originalResponse, override); - } - } - const mod = await this.#pipeline.getModuleForRoute(errorRouteData); - if (!mod || typeof mod.page !== "function") { - const response2 = this.#mergeResponses(new Response(null, { status }), originalResponse); - Reflect.set(response2, responseSentSymbol, true); - return response2; - } - let session; - try { - const renderContext = await RenderContext.create({ - locals, - pipeline: this.#pipeline, - middleware: skipMiddleware ? NOOP_MIDDLEWARE_FN : void 0, - pathname: this.#getPathnameFromRequest(request), - request, - routeData: errorRouteData, - status, - props: { error }, - clientAddress - }); - session = renderContext.session; - const response2 = await renderContext.render(await mod.page()); - return this.#mergeResponses(response2, originalResponse); - } catch { - if (skipMiddleware === false) { - return this.#renderError(request, { - locals, - status, - response: originalResponse, - skipMiddleware: true, - clientAddress, - prerenderedErrorPageFetch - }); - } - } finally { - await session?.[PERSIST_SYMBOL](); - } - } - const response = this.#mergeResponses(new Response(null, { status }), originalResponse); - Reflect.set(response, responseSentSymbol, true); - return response; - } - #mergeResponses(newResponse, originalResponse, override) { - let newResponseHeaders = newResponse.headers; - if (override?.removeContentEncodingHeaders) { - newResponseHeaders = new Headers(newResponseHeaders); - newResponseHeaders.delete("Content-Encoding"); - newResponseHeaders.delete("Content-Length"); - } - if (!originalResponse) { - if (override !== void 0) { - return new Response(newResponse.body, { - status: override.status, - statusText: newResponse.statusText, - headers: newResponseHeaders - }); - } - return newResponse; - } - const status = override?.status ? override.status : originalResponse.status === 200 ? newResponse.status : originalResponse.status; - try { - originalResponse.headers.delete("Content-type"); - } catch { - } - const mergedHeaders = new Map([ - ...Array.from(newResponseHeaders), - ...Array.from(originalResponse.headers) - ]); - const newHeaders = new Headers(); - for (const [name, value] of mergedHeaders) { - newHeaders.set(name, value); - } - return new Response(newResponse.body, { - status, - statusText: status === 200 ? newResponse.statusText : originalResponse.statusText, - // If you're looking at here for possible bugs, it means that it's not a bug. - // With the middleware, users can meddle with headers, and we should pass to the 404/500. - // If users see something weird, it's because they are setting some headers they should not. - // - // Although, we don't want it to replace the content-type, because the error page must return `text/html` - headers: newHeaders - }); - } - #getDefaultStatusCode(routeData, pathname) { - if (!routeData.pattern.test(pathname)) { - for (const fallbackRoute of routeData.fallbackRoutes) { - if (fallbackRoute.pattern.test(pathname)) { - return 302; - } - } - } - const route = removeTrailingForwardSlash(routeData.route); - if (route.endsWith("/404")) return 404; - if (route.endsWith("/500")) return 500; - return 200; - } -} - -const createOutgoingHttpHeaders = (headers) => { - if (!headers) { - return void 0; - } - const nodeHeaders = Object.fromEntries(headers.entries()); - if (Object.keys(nodeHeaders).length === 0) { - return void 0; - } - if (headers.has("set-cookie")) { - const cookieHeaders = headers.getSetCookie(); - if (cookieHeaders.length > 1) { - nodeHeaders["set-cookie"] = cookieHeaders; - } - } - return nodeHeaders; -}; - -function sanitizeHost(hostname) { - if (!hostname) return void 0; - if (/[/\\]/.test(hostname)) return void 0; - return hostname; -} -function parseHost(host) { - const parts = host.split(":"); - return { - hostname: parts[0], - port: parts[1] - }; -} -function matchesAllowedDomains(hostname, protocol, port, allowedDomains) { - const hostWithPort = port ? `${hostname}:${port}` : hostname; - const urlString = `${protocol}://${hostWithPort}`; - if (!URL.canParse(urlString)) { - return false; - } - const testUrl = new URL(urlString); - return allowedDomains.some((pattern) => matchPattern(testUrl, pattern)); -} -function validateHost(host, protocol, allowedDomains) { - if (!host || host.length === 0) return void 0; - if (!allowedDomains || allowedDomains.length === 0) return void 0; - const sanitized = sanitizeHost(host); - if (!sanitized) return void 0; - const { hostname, port } = parseHost(sanitized); - if (matchesAllowedDomains(hostname, protocol, port, allowedDomains)) { - return sanitized; - } - return void 0; -} -function validateForwardedHeaders(forwardedProtocol, forwardedHost, forwardedPort, allowedDomains) { - const result = {}; - if (forwardedProtocol) { - if (allowedDomains && allowedDomains.length > 0) { - const hasProtocolPatterns = allowedDomains.some((pattern) => pattern.protocol !== void 0); - if (hasProtocolPatterns) { - try { - const testUrl = new URL(`${forwardedProtocol}://example.com`); - const isAllowed = allowedDomains.some( - (pattern) => matchPattern(testUrl, { protocol: pattern.protocol }) - ); - if (isAllowed) { - result.protocol = forwardedProtocol; - } - } catch { - } - } else if (/^https?$/.test(forwardedProtocol)) { - result.protocol = forwardedProtocol; - } - } else if (/^https?$/.test(forwardedProtocol)) { - result.protocol = forwardedProtocol; - } - } - if (forwardedPort && allowedDomains && allowedDomains.length > 0) { - const hasPortPatterns = allowedDomains.some((pattern) => pattern.port !== void 0); - if (hasPortPatterns) { - const isAllowed = allowedDomains.some((pattern) => pattern.port === forwardedPort); - if (isAllowed) { - result.port = forwardedPort; - } - } - } - if (forwardedHost && forwardedHost.length > 0 && allowedDomains && allowedDomains.length > 0) { - const protoForValidation = result.protocol || "https"; - const sanitized = sanitizeHost(forwardedHost); - if (sanitized) { - const { hostname, port: portFromHost } = parseHost(sanitized); - const portForValidation = result.port || portFromHost; - if (matchesAllowedDomains(hostname, protoForValidation, portForValidation, allowedDomains)) { - result.host = sanitized; - } - } - } - return result; -} - -function apply() { - if (!globalThis.crypto) { - Object.defineProperty(globalThis, "crypto", { - value: crypto$1.webcrypto - }); - } - if (!globalThis.File) { - Object.defineProperty(globalThis, "File", { - value: buffer.File - }); - } -} - -class NodeApp extends App { - headersMap = void 0; - setHeadersMap(headers) { - this.headersMap = headers; - } - match(req, allowPrerenderedRoutes = false) { - if (!(req instanceof Request)) { - req = NodeApp.createRequest(req, { - skipBody: true, - allowedDomains: this.manifest.allowedDomains - }); - } - return super.match(req, allowPrerenderedRoutes); - } - render(req, routeDataOrOptions, maybeLocals) { - if (!(req instanceof Request)) { - req = NodeApp.createRequest(req, { - allowedDomains: this.manifest.allowedDomains - }); - } - return super.render(req, routeDataOrOptions, maybeLocals); - } - /** - * Converts a NodeJS IncomingMessage into a web standard Request. - * ```js - * import { NodeApp } from 'astro/app/node'; - * import { createServer } from 'node:http'; - * - * const server = createServer(async (req, res) => { - * const request = NodeApp.createRequest(req); - * const response = await app.render(request); - * await NodeApp.writeResponse(response, res); - * }) - * ``` - */ - static createRequest(req, { - skipBody = false, - allowedDomains = [] - } = {}) { - const controller = new AbortController(); - const isEncrypted = "encrypted" in req.socket && req.socket.encrypted; - const getFirstForwardedValue = (multiValueHeader) => { - return multiValueHeader?.toString()?.split(",").map((e) => e.trim())?.[0]; - }; - const providedProtocol = isEncrypted ? "https" : "http"; - const untrustedHostname = req.headers.host ?? req.headers[":authority"]; - const validated = validateForwardedHeaders( - getFirstForwardedValue(req.headers["x-forwarded-proto"]), - getFirstForwardedValue(req.headers["x-forwarded-host"]), - getFirstForwardedValue(req.headers["x-forwarded-port"]), - allowedDomains - ); - const protocol = validated.protocol ?? providedProtocol; - const validatedHostname = validateHost( - typeof untrustedHostname === "string" ? untrustedHostname : void 0, - protocol, - allowedDomains - ); - const hostname = validated.host ?? validatedHostname ?? "localhost"; - const port = validated.port; - let url; - try { - const hostnamePort = getHostnamePort(hostname, port); - url = new URL(`${protocol}://${hostnamePort}${req.url}`); - } catch { - const hostnamePort = getHostnamePort(hostname, port); - url = new URL(`${protocol}://${hostnamePort}`); - } - const options = { - method: req.method || "GET", - headers: makeRequestHeaders(req), - signal: controller.signal - }; - const bodyAllowed = options.method !== "HEAD" && options.method !== "GET" && skipBody === false; - if (bodyAllowed) { - Object.assign(options, makeRequestBody(req)); - } - const request = new Request(url, options); - const socket = getRequestSocket(req); - if (socket && typeof socket.on === "function") { - const existingCleanup = getAbortControllerCleanup(req); - if (existingCleanup) { - existingCleanup(); - } - let cleanedUp = false; - const removeSocketListener = () => { - if (typeof socket.off === "function") { - socket.off("close", onSocketClose); - } else if (typeof socket.removeListener === "function") { - socket.removeListener("close", onSocketClose); - } - }; - const cleanup = () => { - if (cleanedUp) return; - cleanedUp = true; - removeSocketListener(); - controller.signal.removeEventListener("abort", cleanup); - Reflect.deleteProperty(req, nodeRequestAbortControllerCleanupSymbol); - }; - const onSocketClose = () => { - cleanup(); - if (!controller.signal.aborted) { - controller.abort(); - } - }; - socket.on("close", onSocketClose); - controller.signal.addEventListener("abort", cleanup, { once: true }); - Reflect.set(req, nodeRequestAbortControllerCleanupSymbol, cleanup); - if (socket.destroyed) { - onSocketClose(); - } - } - const forwardedClientIp = getFirstForwardedValue(req.headers["x-forwarded-for"]); - const clientIp = forwardedClientIp || req.socket?.remoteAddress; - if (clientIp) { - Reflect.set(request, clientAddressSymbol, clientIp); - } - return request; - } - /** - * Streams a web-standard Response into a NodeJS Server Response. - * ```js - * import { NodeApp } from 'astro/app/node'; - * import { createServer } from 'node:http'; - * - * const server = createServer(async (req, res) => { - * const request = NodeApp.createRequest(req); - * const response = await app.render(request); - * await NodeApp.writeResponse(response, res); - * }) - * ``` - * @param source WhatWG Response - * @param destination NodeJS ServerResponse - */ - static async writeResponse(source, destination) { - const { status, headers, body, statusText } = source; - if (!(destination instanceof Http2ServerResponse)) { - destination.statusMessage = statusText; - } - destination.writeHead(status, createOutgoingHttpHeaders(headers)); - const cleanupAbortFromDestination = getAbortControllerCleanup( - destination.req ?? void 0 - ); - if (cleanupAbortFromDestination) { - const runCleanup = () => { - cleanupAbortFromDestination(); - if (typeof destination.off === "function") { - destination.off("finish", runCleanup); - destination.off("close", runCleanup); - } else { - destination.removeListener?.("finish", runCleanup); - destination.removeListener?.("close", runCleanup); - } - }; - destination.on("finish", runCleanup); - destination.on("close", runCleanup); - } - if (!body) return destination.end(); - try { - const reader = body.getReader(); - destination.on("close", () => { - reader.cancel().catch((err) => { - console.error( - `There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`, - err - ); - }); - }); - let result = await reader.read(); - while (!result.done) { - destination.write(result.value); - result = await reader.read(); - } - destination.end(); - } catch (err) { - destination.write("Internal server error", () => { - err instanceof Error ? destination.destroy(err) : destination.destroy(); - }); - } - } -} -function getHostnamePort(hostname, port) { - const portInHostname = typeof hostname === "string" && /:\d+$/.test(hostname); - const hostnamePort = portInHostname ? hostname : `${hostname}${port ? `:${port}` : ""}`; - return hostnamePort; -} -function makeRequestHeaders(req) { - const headers = new Headers(); - for (const [name, value] of Object.entries(req.headers)) { - if (value === void 0) { - continue; - } - if (Array.isArray(value)) { - for (const item of value) { - headers.append(name, item); - } - } else { - headers.append(name, value); - } - } - return headers; -} -function makeRequestBody(req) { - if (req.body !== void 0) { - if (typeof req.body === "string" && req.body.length > 0) { - return { body: Buffer.from(req.body) }; - } - if (typeof req.body === "object" && req.body !== null && Object.keys(req.body).length > 0) { - return { body: Buffer.from(JSON.stringify(req.body)) }; - } - if (typeof req.body === "object" && req.body !== null && typeof req.body[Symbol.asyncIterator] !== "undefined") { - return asyncIterableToBodyProps(req.body); - } - } - return asyncIterableToBodyProps(req); -} -function asyncIterableToBodyProps(iterable) { - return { - // Node uses undici for the Request implementation. Undici accepts - // a non-standard async iterable for the body. - // @ts-expect-error - body: iterable, - // The duplex property is required when using a ReadableStream or async - // iterable for the body. The type definitions do not include the duplex - // property because they are not up-to-date. - duplex: "half" - }; -} -function getAbortControllerCleanup(req) { - if (!req) return void 0; - const cleanup = Reflect.get(req, nodeRequestAbortControllerCleanupSymbol); - return typeof cleanup === "function" ? cleanup : void 0; -} -function getRequestSocket(req) { - if (req.socket && typeof req.socket.on === "function") { - return req.socket; - } - const http2Socket = req.stream?.session?.socket; - if (http2Socket && typeof http2Socket.on === "function") { - return http2Socket; - } - return void 0; -} - -apply(); - -nodePath.posix.join; - -const ASTRO_PATH_HEADER = "x-astro-path"; -const ASTRO_PATH_PARAM = "x_astro_path"; -const ASTRO_LOCALS_HEADER = "x-astro-locals"; -const ASTRO_MIDDLEWARE_SECRET_HEADER = "x-astro-middleware-secret"; - -const createExports = (manifest, { - middlewareSecret, - skewProtection -}) => { - const app = new NodeApp(manifest); - const handler = async (req, res) => { - const url = new URL(`https://example.com${req.url}`); - const clientAddress = req.headers["x-forwarded-for"]; - const localsHeader = req.headers[ASTRO_LOCALS_HEADER]; - const middlewareSecretHeader = req.headers[ASTRO_MIDDLEWARE_SECRET_HEADER]; - const realPath = req.headers[ASTRO_PATH_HEADER] ?? url.searchParams.get(ASTRO_PATH_PARAM); - if (typeof realPath === "string") { - req.url = realPath; - } - let locals = {}; - if (localsHeader) { - if (middlewareSecretHeader !== middlewareSecret) { - res.statusCode = 403; - res.end("Forbidden"); - return; - } - locals = typeof localsHeader === "string" ? JSON.parse(localsHeader) : JSON.parse(localsHeader[0]); - } - delete req.headers[ASTRO_MIDDLEWARE_SECRET_HEADER]; - if (skewProtection && process.env.VERCEL_SKEW_PROTECTION_ENABLED === "1") { - req.headers["x-deployment-id"] = process.env.VERCEL_DEPLOYMENT_ID; - } - const webResponse = await app.render(req, { - addCookieHeader: true, - clientAddress, - locals - }); - await NodeApp.writeResponse(webResponse, res); - }; - return { - default: handler - }; -}; -function start() { -} - -const serverEntrypointModule = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - createExports, - start -}, Symbol.toStringTag, { value: 'Module' })); - -export { start as a, createExports as c, serverEntrypointModule as s }; diff --git a/.vercel/output/_functions/chunks/_astro_assets_BkxcOWlh.mjs b/.vercel/output/_functions/chunks/_astro_assets_BkxcOWlh.mjs deleted file mode 100644 index ba7a13d..0000000 --- a/.vercel/output/_functions/chunks/_astro_assets_BkxcOWlh.mjs +++ /dev/null @@ -1,852 +0,0 @@ -import { j as joinPaths, i as isRemotePath } from './path_Bl04Vi8h.mjs'; -import { i as isRemoteAllowed, t as typeHandlers, a as types } from './index_BL6Pqka4.mjs'; -import { A as AstroError, ae as ExpectedImage, af as LocalImageUsedWrongly, ag as MissingImageDimension, ah as UnsupportedImageFormat, ai as IncompatibleDescriptorOptions, aj as UnsupportedImageConversion, ak as toStyleString, al as NoImageMetadata, am as FailedToFetchRemoteImageDimensions, an as RemoteImageNotAllowed, ao as ExpectedImageOptions, ap as ExpectedNotESMImage, aq as InvalidImageService, b as createAstro, c as createComponent, ar as ImageMissingAlt, m as maybeRenderHead, e as addAttribute, as as spreadAttributes, a as renderTemplate, at as ExperimentalFontsNotEnabled, au as FontFamilyNotFound, u as unescapeHTML } from './astro/server_D2NiA7f1.mjs'; -import { D as DEFAULT_OUTPUT_FORMAT, a as VALID_SUPPORTED_FORMATS, b as DEFAULT_HASH_PROPS } from './consts_Bd-1c2lz.mjs'; -import * as mime from 'mrmime'; -import 'clsx'; -import 'piccolore'; - -const DEFAULT_RESOLUTIONS = [ - 640, - // older and lower-end phones - 750, - // iPhone 6-8 - 828, - // iPhone XR/11 - 960, - // older horizontal phones - 1080, - // iPhone 6-8 Plus - 1280, - // 720p - 1668, - // Various iPads - 1920, - // 1080p - 2048, - // QXGA - 2560, - // WQXGA - 3200, - // QHD+ - 3840, - // 4K - 4480, - // 4.5K - 5120, - // 5K - 6016 - // 6K -]; -const LIMITED_RESOLUTIONS = [ - 640, - // older and lower-end phones - 750, - // iPhone 6-8 - 828, - // iPhone XR/11 - 1080, - // iPhone 6-8 Plus - 1280, - // 720p - 1668, - // Various iPads - 2048, - // QXGA - 2560 - // WQXGA -]; -const getWidths = ({ - width, - layout, - breakpoints = DEFAULT_RESOLUTIONS, - originalWidth -}) => { - const smallerThanOriginal = (w) => !originalWidth || w <= originalWidth; - if (layout === "full-width") { - return breakpoints.filter(smallerThanOriginal); - } - if (!width) { - return []; - } - const doubleWidth = width * 2; - const maxSize = originalWidth ? Math.min(doubleWidth, originalWidth) : doubleWidth; - if (layout === "fixed") { - return originalWidth && width > originalWidth ? [originalWidth] : [width, maxSize]; - } - if (layout === "constrained") { - return [ - // Always include the image at 1x and 2x the specified width - width, - doubleWidth, - ...breakpoints - ].filter((w) => w <= maxSize).sort((a, b) => a - b); - } - return []; -}; -const getSizesAttribute = ({ - width, - layout -}) => { - if (!width || !layout) { - return void 0; - } - switch (layout) { - // If screen is wider than the max size then image width is the max size, - // otherwise it's the width of the screen - case "constrained": - return `(min-width: ${width}px) ${width}px, 100vw`; - // Image is always the same width, whatever the size of the screen - case "fixed": - return `${width}px`; - // Image is always the width of the screen - case "full-width": - return `100vw`; - case "none": - default: - return void 0; - } -}; - -function isESMImportedImage(src) { - return typeof src === "object" || typeof src === "function" && "src" in src; -} -function isRemoteImage(src) { - return typeof src === "string"; -} -async function resolveSrc(src) { - if (typeof src === "object" && "then" in src) { - const resource = await src; - return resource.default ?? resource; - } - return src; -} - -function isLocalService(service) { - if (!service) { - return false; - } - return "transform" in service; -} -function parseQuality(quality) { - let result = parseInt(quality); - if (Number.isNaN(result)) { - return quality; - } - return result; -} -const sortNumeric = (a, b) => a - b; -function verifyOptions(options) { - if (!options.src || !isRemoteImage(options.src) && !isESMImportedImage(options.src)) { - throw new AstroError({ - ...ExpectedImage, - message: ExpectedImage.message( - JSON.stringify(options.src), - typeof options.src, - JSON.stringify(options, (_, v) => v === void 0 ? null : v) - ) - }); - } - if (!isESMImportedImage(options.src)) { - if (options.src.startsWith("/@fs/") || !isRemotePath(options.src) && !options.src.startsWith("/")) { - throw new AstroError({ - ...LocalImageUsedWrongly, - message: LocalImageUsedWrongly.message(options.src) - }); - } - let missingDimension; - if (!options.width && !options.height) { - missingDimension = "both"; - } else if (!options.width && options.height) { - missingDimension = "width"; - } else if (options.width && !options.height) { - missingDimension = "height"; - } - if (missingDimension) { - throw new AstroError({ - ...MissingImageDimension, - message: MissingImageDimension.message(missingDimension, options.src) - }); - } - } else { - if (!VALID_SUPPORTED_FORMATS.includes(options.src.format)) { - throw new AstroError({ - ...UnsupportedImageFormat, - message: UnsupportedImageFormat.message( - options.src.format, - options.src.src, - VALID_SUPPORTED_FORMATS - ) - }); - } - if (options.widths && options.densities) { - throw new AstroError(IncompatibleDescriptorOptions); - } - if (options.src.format === "svg" && options.format !== "svg" || options.src.format !== "svg" && options.format === "svg") { - throw new AstroError(UnsupportedImageConversion); - } - } -} -const baseService = { - validateOptions(options) { - if (isESMImportedImage(options.src) && options.src.format === "svg") { - options.format = "svg"; - } - verifyOptions(options); - if (!options.format) { - options.format = DEFAULT_OUTPUT_FORMAT; - } - if (options.width) options.width = Math.round(options.width); - if (options.height) options.height = Math.round(options.height); - if (options.layout && options.width && options.height) { - options.fit ??= "cover"; - delete options.layout; - } - if (options.fit === "none") { - delete options.fit; - } - return options; - }, - getHTMLAttributes(options) { - const { targetWidth, targetHeight } = getTargetDimensions(options); - const { - src, - width, - height, - format, - quality, - densities, - widths, - formats, - layout, - priority, - fit, - position, - background, - ...attributes - } = options; - return { - ...attributes, - width: targetWidth, - height: targetHeight, - loading: attributes.loading ?? "lazy", - decoding: attributes.decoding ?? "async" - }; - }, - getSrcSet(options) { - const { targetWidth, targetHeight } = getTargetDimensions(options); - const aspectRatio = targetWidth / targetHeight; - const { widths, densities } = options; - const targetFormat = options.format ?? DEFAULT_OUTPUT_FORMAT; - let transformedWidths = (widths ?? []).sort(sortNumeric); - let imageWidth = options.width; - let maxWidth = Infinity; - if (isESMImportedImage(options.src)) { - imageWidth = options.src.width; - maxWidth = imageWidth; - if (transformedWidths.length > 0 && transformedWidths.at(-1) > maxWidth) { - transformedWidths = transformedWidths.filter((width) => width <= maxWidth); - transformedWidths.push(maxWidth); - } - } - transformedWidths = Array.from(new Set(transformedWidths)); - const { - width: transformWidth, - height: transformHeight, - ...transformWithoutDimensions - } = options; - let allWidths = []; - if (densities) { - const densityValues = densities.map((density) => { - if (typeof density === "number") { - return density; - } else { - return parseFloat(density); - } - }); - const densityWidths = densityValues.sort(sortNumeric).map((density) => Math.round(targetWidth * density)); - allWidths = densityWidths.map((width, index) => ({ - width, - descriptor: `${densityValues[index]}x` - })); - } else if (transformedWidths.length > 0) { - allWidths = transformedWidths.map((width) => ({ - width, - descriptor: `${width}w` - })); - } - return allWidths.map(({ width, descriptor }) => { - const height = Math.round(width / aspectRatio); - const transform = { ...transformWithoutDimensions, width, height }; - return { - transform, - descriptor, - attributes: { - type: `image/${targetFormat}` - } - }; - }); - }, - getURL(options, imageConfig) { - const searchParams = new URLSearchParams(); - if (isESMImportedImage(options.src)) { - searchParams.append("href", options.src.src); - } else if (isRemoteAllowed(options.src, imageConfig)) { - searchParams.append("href", options.src); - } else { - return options.src; - } - const params = { - w: "width", - h: "height", - q: "quality", - f: "format", - fit: "fit", - position: "position", - background: "background" - }; - Object.entries(params).forEach(([param, key]) => { - options[key] && searchParams.append(param, options[key].toString()); - }); - const imageEndpoint = joinPaths("/", imageConfig.endpoint.route); - let url = `${imageEndpoint}?${searchParams}`; - if (imageConfig.assetQueryParams) { - const assetQueryString = imageConfig.assetQueryParams.toString(); - if (assetQueryString) { - url += "&" + assetQueryString; - } - } - return url; - }, - parseURL(url) { - const params = url.searchParams; - if (!params.has("href")) { - return void 0; - } - const transform = { - src: params.get("href"), - width: params.has("w") ? parseInt(params.get("w")) : void 0, - height: params.has("h") ? parseInt(params.get("h")) : void 0, - format: params.get("f"), - quality: params.get("q"), - fit: params.get("fit"), - position: params.get("position") ?? void 0, - background: params.get("background") ?? void 0 - }; - return transform; - } -}; -function getTargetDimensions(options) { - let targetWidth = options.width; - let targetHeight = options.height; - if (isESMImportedImage(options.src)) { - const aspectRatio = options.src.width / options.src.height; - if (targetHeight && !targetWidth) { - targetWidth = Math.round(targetHeight * aspectRatio); - } else if (targetWidth && !targetHeight) { - targetHeight = Math.round(targetWidth / aspectRatio); - } else if (!targetWidth && !targetHeight) { - targetWidth = options.src.width; - targetHeight = options.src.height; - } - } - return { - targetWidth, - targetHeight - }; -} - -function isImageMetadata(src) { - return src.fsPath && !("fsPath" in src); -} - -const cssFitValues = ["fill", "contain", "cover", "scale-down"]; -function addCSSVarsToStyle(vars, styles) { - const cssVars = Object.entries(vars).filter(([_, value]) => value !== void 0 && value !== false).map(([key, value]) => `--${key}: ${value};`).join(" "); - if (!styles) { - return cssVars; - } - const style = typeof styles === "string" ? styles : toStyleString(styles); - return `${cssVars} ${style}`; -} - -const firstBytes = /* @__PURE__ */ new Map([ - [0, "heif"], - [56, "psd"], - [66, "bmp"], - [68, "dds"], - [71, "gif"], - [73, "tiff"], - [77, "tiff"], - [82, "webp"], - [105, "icns"], - [137, "png"], - [255, "jpg"] -]); -function detector(input) { - const byte = input[0]; - const type = firstBytes.get(byte); - if (type && typeHandlers.get(type).validate(input)) { - return type; - } - return types.find((imageType) => typeHandlers.get(imageType).validate(input)); -} - -function lookup(input) { - const type = detector(input); - if (typeof type !== "undefined") { - const size = typeHandlers.get(type).calculate(input); - if (size !== void 0) { - size.type = size.type ?? type; - return size; - } - } - throw new TypeError("unsupported file type: " + type); -} - -async function imageMetadata(data, src) { - let result; - try { - result = lookup(data); - } catch { - throw new AstroError({ - ...NoImageMetadata, - message: NoImageMetadata.message(src) - }); - } - if (!result.height || !result.width || !result.type) { - throw new AstroError({ - ...NoImageMetadata, - message: NoImageMetadata.message(src) - }); - } - const { width, height, type, orientation } = result; - const isPortrait = (orientation || 0) >= 5; - return { - width: isPortrait ? height : width, - height: isPortrait ? width : height, - format: type, - orientation - }; -} - -async function inferRemoteSize(url, imageConfig) { - if (!URL.canParse(url)) { - throw new AstroError({ - ...FailedToFetchRemoteImageDimensions, - message: FailedToFetchRemoteImageDimensions.message(url) - }); - } - const allowlistConfig = imageConfig ? { - domains: imageConfig.domains ?? [], - remotePatterns: imageConfig.remotePatterns ?? [] - } : void 0; - if (!allowlistConfig) { - const parsedUrl = new URL(url); - if (!["http:", "https:"].includes(parsedUrl.protocol)) { - throw new AstroError({ - ...FailedToFetchRemoteImageDimensions, - message: FailedToFetchRemoteImageDimensions.message(url) - }); - } - } - if (allowlistConfig && !isRemoteAllowed(url, allowlistConfig)) { - throw new AstroError({ - ...RemoteImageNotAllowed, - message: RemoteImageNotAllowed.message(url) - }); - } - const response = await fetch(url, { redirect: "manual" }); - if (response.status >= 300 && response.status < 400) { - throw new AstroError({ - ...FailedToFetchRemoteImageDimensions, - message: FailedToFetchRemoteImageDimensions.message(url) - }); - } - if (!response.body || !response.ok) { - throw new AstroError({ - ...FailedToFetchRemoteImageDimensions, - message: FailedToFetchRemoteImageDimensions.message(url) - }); - } - const reader = response.body.getReader(); - let done, value; - let accumulatedChunks = new Uint8Array(); - while (!done) { - const readResult = await reader.read(); - done = readResult.done; - if (done) break; - if (readResult.value) { - value = readResult.value; - let tmp = new Uint8Array(accumulatedChunks.length + value.length); - tmp.set(accumulatedChunks, 0); - tmp.set(value, accumulatedChunks.length); - accumulatedChunks = tmp; - try { - const dimensions = await imageMetadata(accumulatedChunks, url); - if (dimensions) { - await reader.cancel(); - return dimensions; - } - } catch { - } - } - } - throw new AstroError({ - ...NoImageMetadata, - message: NoImageMetadata.message(url) - }); -} - -const PLACEHOLDER_BASE = "astro://placeholder"; -function createPlaceholderURL(pathOrUrl) { - return new URL(pathOrUrl, PLACEHOLDER_BASE); -} -function stringifyPlaceholderURL(url) { - return url.href.replace(PLACEHOLDER_BASE, ""); -} - -async function getConfiguredImageService() { - if (!globalThis?.astroAsset?.imageService) { - const { default: service } = await import( - // @ts-expect-error - './sharp_BTdjpfI2.mjs' - ).catch((e) => { - const error = new AstroError(InvalidImageService); - error.cause = e; - throw error; - }); - if (!globalThis.astroAsset) globalThis.astroAsset = {}; - globalThis.astroAsset.imageService = service; - return service; - } - return globalThis.astroAsset.imageService; -} -async function getImage$1(options, imageConfig) { - if (!options || typeof options !== "object") { - throw new AstroError({ - ...ExpectedImageOptions, - message: ExpectedImageOptions.message(JSON.stringify(options)) - }); - } - if (typeof options.src === "undefined") { - throw new AstroError({ - ...ExpectedImage, - message: ExpectedImage.message( - options.src, - "undefined", - JSON.stringify(options) - ) - }); - } - if (isImageMetadata(options)) { - throw new AstroError(ExpectedNotESMImage); - } - const service = await getConfiguredImageService(); - const resolvedOptions = { - ...options, - src: await resolveSrc(options.src) - }; - let originalWidth; - let originalHeight; - if (options.inferSize) { - delete resolvedOptions.inferSize; - if (isRemoteImage(resolvedOptions.src) && isRemotePath(resolvedOptions.src)) { - if (!isRemoteAllowed(resolvedOptions.src, imageConfig)) { - throw new AstroError({ - ...RemoteImageNotAllowed, - message: RemoteImageNotAllowed.message(resolvedOptions.src) - }); - } - const result = await inferRemoteSize(resolvedOptions.src, imageConfig); - resolvedOptions.width ??= result.width; - resolvedOptions.height ??= result.height; - originalWidth = result.width; - originalHeight = result.height; - } - } - const originalFilePath = isESMImportedImage(resolvedOptions.src) ? resolvedOptions.src.fsPath : void 0; - const clonedSrc = isESMImportedImage(resolvedOptions.src) ? ( - // @ts-expect-error - clone is a private, hidden prop - resolvedOptions.src.clone ?? resolvedOptions.src - ) : resolvedOptions.src; - if (isESMImportedImage(clonedSrc)) { - originalWidth = clonedSrc.width; - originalHeight = clonedSrc.height; - } - if (originalWidth && originalHeight) { - const aspectRatio = originalWidth / originalHeight; - if (resolvedOptions.height && !resolvedOptions.width) { - resolvedOptions.width = Math.round(resolvedOptions.height * aspectRatio); - } else if (resolvedOptions.width && !resolvedOptions.height) { - resolvedOptions.height = Math.round(resolvedOptions.width / aspectRatio); - } else if (!resolvedOptions.width && !resolvedOptions.height) { - resolvedOptions.width = originalWidth; - resolvedOptions.height = originalHeight; - } - } - resolvedOptions.src = clonedSrc; - const layout = options.layout ?? imageConfig.layout ?? "none"; - if (resolvedOptions.priority) { - resolvedOptions.loading ??= "eager"; - resolvedOptions.decoding ??= "sync"; - resolvedOptions.fetchpriority ??= "high"; - delete resolvedOptions.priority; - } else { - resolvedOptions.loading ??= "lazy"; - resolvedOptions.decoding ??= "async"; - resolvedOptions.fetchpriority ??= "auto"; - } - if (layout !== "none") { - resolvedOptions.widths ||= getWidths({ - width: resolvedOptions.width, - layout, - originalWidth, - breakpoints: imageConfig.breakpoints?.length ? imageConfig.breakpoints : isLocalService(service) ? LIMITED_RESOLUTIONS : DEFAULT_RESOLUTIONS - }); - resolvedOptions.sizes ||= getSizesAttribute({ width: resolvedOptions.width, layout }); - delete resolvedOptions.densities; - resolvedOptions.style = addCSSVarsToStyle( - { - fit: cssFitValues.includes(resolvedOptions.fit ?? "") && resolvedOptions.fit, - pos: resolvedOptions.position - }, - resolvedOptions.style - ); - resolvedOptions["data-astro-image"] = layout; - } - const validatedOptions = service.validateOptions ? await service.validateOptions(resolvedOptions, imageConfig) : resolvedOptions; - const srcSetTransforms = service.getSrcSet ? await service.getSrcSet(validatedOptions, imageConfig) : []; - let imageURL = await service.getURL(validatedOptions, imageConfig); - const matchesValidatedTransform = (transform) => transform.width === validatedOptions.width && transform.height === validatedOptions.height && transform.format === validatedOptions.format; - let srcSets = await Promise.all( - srcSetTransforms.map(async (srcSet) => { - return { - transform: srcSet.transform, - url: matchesValidatedTransform(srcSet.transform) ? imageURL : await service.getURL(srcSet.transform, imageConfig), - descriptor: srcSet.descriptor, - attributes: srcSet.attributes - }; - }) - ); - if (isLocalService(service) && globalThis.astroAsset.addStaticImage && !(isRemoteImage(validatedOptions.src) && imageURL === validatedOptions.src)) { - const propsToHash = service.propertiesToHash ?? DEFAULT_HASH_PROPS; - imageURL = globalThis.astroAsset.addStaticImage( - validatedOptions, - propsToHash, - originalFilePath - ); - srcSets = srcSetTransforms.map((srcSet) => { - return { - transform: srcSet.transform, - url: matchesValidatedTransform(srcSet.transform) ? imageURL : globalThis.astroAsset.addStaticImage(srcSet.transform, propsToHash, originalFilePath), - descriptor: srcSet.descriptor, - attributes: srcSet.attributes - }; - }); - } else if (imageConfig.assetQueryParams) { - const imageURLObj = createPlaceholderURL(imageURL); - imageConfig.assetQueryParams.forEach((value, key) => { - imageURLObj.searchParams.set(key, value); - }); - imageURL = stringifyPlaceholderURL(imageURLObj); - srcSets = srcSets.map((srcSet) => { - const urlObj = createPlaceholderURL(srcSet.url); - imageConfig.assetQueryParams.forEach((value, key) => { - urlObj.searchParams.set(key, value); - }); - return { - ...srcSet, - url: stringifyPlaceholderURL(urlObj) - }; - }); - } - return { - rawOptions: resolvedOptions, - options: validatedOptions, - src: imageURL, - srcSet: { - values: srcSets, - attribute: srcSets.map((srcSet) => `${srcSet.url} ${srcSet.descriptor}`).join(", ") - }, - attributes: service.getHTMLAttributes !== void 0 ? await service.getHTMLAttributes(validatedOptions, imageConfig) : {} - }; -} - -const $$Astro$2 = createAstro("https://damdug.com"); -const $$Image = createComponent(async ($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro$2, $$props, $$slots); - Astro2.self = $$Image; - const props = Astro2.props; - if (props.alt === void 0 || props.alt === null) { - throw new AstroError(ImageMissingAlt); - } - if (typeof props.width === "string") { - props.width = parseInt(props.width); - } - if (typeof props.height === "string") { - props.height = parseInt(props.height); - } - const layout = props.layout ?? imageConfig.layout ?? "none"; - if (layout !== "none") { - props.layout ??= imageConfig.layout; - props.fit ??= imageConfig.objectFit ?? "cover"; - props.position ??= imageConfig.objectPosition ?? "center"; - } - const image = await getImage(props); - const additionalAttributes = {}; - if (image.srcSet.values.length > 0) { - additionalAttributes.srcset = image.srcSet.attribute; - } - const { class: className, ...attributes } = { ...additionalAttributes, ...image.attributes }; - return renderTemplate`${maybeRenderHead()}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/node_modules/astro/components/Image.astro", void 0); - -const $$Astro$1 = createAstro("https://damdug.com"); -const $$Picture = createComponent(async ($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro$1, $$props, $$slots); - Astro2.self = $$Picture; - const defaultFormats = ["webp"]; - const defaultFallbackFormat = "png"; - const specialFormatsFallback = ["gif", "svg", "jpg", "jpeg"]; - const { formats = defaultFormats, pictureAttributes = {}, fallbackFormat, ...props } = Astro2.props; - if (props.alt === void 0 || props.alt === null) { - throw new AstroError(ImageMissingAlt); - } - const scopedStyleClass = props.class?.match(/\bastro-\w{8}\b/)?.[0]; - if (scopedStyleClass) { - if (pictureAttributes.class) { - pictureAttributes.class = `${pictureAttributes.class} ${scopedStyleClass}`; - } else { - pictureAttributes.class = scopedStyleClass; - } - } - const layout = props.layout ?? imageConfig.layout ?? "none"; - const useResponsive = layout !== "none"; - if (useResponsive) { - props.layout ??= imageConfig.layout; - props.fit ??= imageConfig.objectFit ?? "cover"; - props.position ??= imageConfig.objectPosition ?? "center"; - } - for (const key in props) { - if (key.startsWith("data-astro-cid")) { - pictureAttributes[key] = props[key]; - } - } - const originalSrc = await resolveSrc(props.src); - const optimizedImages = await Promise.all( - formats.map( - async (format) => await getImage({ - ...props, - src: originalSrc, - format, - widths: props.widths, - densities: props.densities - }) - ) - ); - let resultFallbackFormat = fallbackFormat ?? defaultFallbackFormat; - if (!fallbackFormat && isESMImportedImage(originalSrc) && specialFormatsFallback.includes(originalSrc.format)) { - resultFallbackFormat = originalSrc.format; - } - const fallbackImage = await getImage({ - ...props, - format: resultFallbackFormat, - widths: props.widths, - densities: props.densities - }); - const imgAdditionalAttributes = {}; - const sourceAdditionalAttributes = {}; - if (props.sizes) { - sourceAdditionalAttributes.sizes = props.sizes; - } - if (fallbackImage.srcSet.values.length > 0) { - imgAdditionalAttributes.srcset = fallbackImage.srcSet.attribute; - } - const { class: className, ...attributes } = { - ...imgAdditionalAttributes, - ...fallbackImage.attributes - }; - return renderTemplate`${maybeRenderHead()} ${Object.entries(optimizedImages).map(([_, image]) => { - const srcsetAttribute = props.densities || !props.densities && !props.widths && !useResponsive ? `${image.src}${image.srcSet.values.length > 0 ? ", " + image.srcSet.attribute : ""}` : image.srcSet.attribute; - return renderTemplate``; - })} `; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/node_modules/astro/components/Picture.astro", void 0); - -const mod = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null -}, Symbol.toStringTag, { value: 'Module' })); - -function filterPreloads(data, preload) { - if (!preload) { - return null; - } - if (preload === true) { - return data; - } - return data.filter( - ({ weight, style, subset }) => preload.some((p) => { - if (p.weight !== void 0 && weight !== void 0 && !checkWeight(p.weight.toString(), weight)) { - return false; - } - if (p.style !== void 0 && p.style !== style) { - return false; - } - if (p.subset !== void 0 && p.subset !== subset) { - return false; - } - return true; - }) - ); -} -function checkWeight(input, target) { - const trimmedInput = input.trim(); - if (trimmedInput.includes(" ")) { - return trimmedInput === target; - } - if (target.includes(" ")) { - const [a, b] = target.split(" "); - const parsedInput = Number.parseInt(input); - return parsedInput >= Number.parseInt(a) && parsedInput <= Number.parseInt(b); - } - return input === target; -} - -const $$Astro = createAstro("https://damdug.com"); -const $$Font = createComponent(($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro, $$props, $$slots); - Astro2.self = $$Font; - const { componentDataByCssVariable } = mod; - if (!componentDataByCssVariable) { - throw new AstroError(ExperimentalFontsNotEnabled); - } - const { cssVariable, preload = false } = Astro2.props; - const data = componentDataByCssVariable.get(cssVariable); - if (!data) { - throw new AstroError({ - ...FontFamilyNotFound, - message: FontFamilyNotFound.message(cssVariable) - }); - } - const filteredPreloadData = filterPreloads(data.preloads, preload); - return renderTemplate`${filteredPreloadData?.map(({ url, type }) => renderTemplate``)}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/node_modules/astro/components/Font.astro", void 0); - -const assetQueryParams = undefined; - const imageConfig = {"endpoint":{"route":"/_image"},"service":{"entrypoint":"astro/assets/services/sharp","config":{}},"domains":[],"remotePatterns":[],"responsiveStyles":false}; - Object.defineProperty(imageConfig, 'assetQueryParams', { - value: assetQueryParams, - enumerable: false, - configurable: true, - }); - const getImage = async (options) => await getImage$1(options, imageConfig); - -const _astro_assets = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - getConfiguredImageService, - getImage, - imageConfig, - isLocalService -}, Symbol.toStringTag, { value: 'Module' })); - -export { _astro_assets as _, baseService as b, getConfiguredImageService as g, imageConfig as i, parseQuality as p }; diff --git a/.vercel/output/_functions/chunks/_astro_content_C1JXYIk2.mjs b/.vercel/output/_functions/chunks/_astro_content_C1JXYIk2.mjs deleted file mode 100644 index 0c26ec1..0000000 --- a/.vercel/output/_functions/chunks/_astro_content_C1JXYIk2.mjs +++ /dev/null @@ -1,438 +0,0 @@ -import { escape } from 'html-escaper'; -import { Traverse } from 'neotraverse/modern'; -import pLimit from 'p-limit'; -import { z } from 'zod'; -import { r as removeBase, i as isRemotePath, p as prependForwardSlash } from './path_Bl04Vi8h.mjs'; -import { V as VALID_INPUT_FORMATS } from './consts_Bd-1c2lz.mjs'; -import { A as AstroError, U as UnknownContentCollectionError, c as createComponent, R as RenderUndefinedEntryError, u as unescapeHTML, a as renderTemplate, f as renderUniqueStylesheet, g as renderScriptElement, h as createHeadAndContent, r as renderComponent } from './astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import * as devalue from 'devalue'; - -const CONTENT_IMAGE_FLAG = "astroContentImageFlag"; -const IMAGE_IMPORT_PREFIX = "__ASTRO_IMAGE_"; - -function imageSrcToImportId(imageSrc, filePath) { - imageSrc = removeBase(imageSrc, IMAGE_IMPORT_PREFIX); - if (isRemotePath(imageSrc)) { - return; - } - const ext = imageSrc.split(".").at(-1)?.toLowerCase(); - if (!ext || !VALID_INPUT_FORMATS.includes(ext)) { - return; - } - const params = new URLSearchParams(CONTENT_IMAGE_FLAG); - if (filePath) { - params.set("importer", filePath); - } - return `${imageSrc}?${params.toString()}`; -} - -class ImmutableDataStore { - _collections = /* @__PURE__ */ new Map(); - constructor() { - this._collections = /* @__PURE__ */ new Map(); - } - get(collectionName, key) { - return this._collections.get(collectionName)?.get(String(key)); - } - entries(collectionName) { - const collection = this._collections.get(collectionName) ?? /* @__PURE__ */ new Map(); - return [...collection.entries()]; - } - values(collectionName) { - const collection = this._collections.get(collectionName) ?? /* @__PURE__ */ new Map(); - return [...collection.values()]; - } - keys(collectionName) { - const collection = this._collections.get(collectionName) ?? /* @__PURE__ */ new Map(); - return [...collection.keys()]; - } - has(collectionName, key) { - const collection = this._collections.get(collectionName); - if (collection) { - return collection.has(String(key)); - } - return false; - } - hasCollection(collectionName) { - return this._collections.has(collectionName); - } - collections() { - return this._collections; - } - /** - * Attempts to load a DataStore from the virtual module. - * This only works in Vite. - */ - static async fromModule() { - try { - const data = await import('./_astro_data-layer-content_BUPw26ki.mjs'); - if (data.default instanceof Map) { - return ImmutableDataStore.fromMap(data.default); - } - const map = devalue.unflatten(data.default); - return ImmutableDataStore.fromMap(map); - } catch { - } - return new ImmutableDataStore(); - } - static async fromMap(data) { - const store = new ImmutableDataStore(); - store._collections = data; - return store; - } -} -function dataStoreSingleton() { - let instance = void 0; - return { - get: async () => { - if (!instance) { - instance = ImmutableDataStore.fromModule(); - } - return instance; - }, - set: (store) => { - instance = store; - } - }; -} -const globalDataStore = dataStoreSingleton(); - -const __vite_import_meta_env__ = {"ASSETS_PREFIX": undefined, "BASE_URL": "/", "DEV": false, "MODE": "production", "PROD": true, "SITE": "https://damdug.com", "SSR": true}; -function createCollectionToGlobResultMap({ - globResult, - contentDir -}) { - const collectionToGlobResultMap = {}; - for (const key in globResult) { - const keyRelativeToContentDir = key.replace(new RegExp(`^${contentDir}`), ""); - const segments = keyRelativeToContentDir.split("/"); - if (segments.length <= 1) continue; - const collection = segments[0]; - collectionToGlobResultMap[collection] ??= {}; - collectionToGlobResultMap[collection][key] = globResult[key]; - } - return collectionToGlobResultMap; -} -z.object({ - tags: z.array(z.string()).optional(), - lastModified: z.date().optional() -}); -function createGetCollection({ - contentCollectionToEntryMap, - dataCollectionToEntryMap, - getRenderEntryImport, - cacheEntriesByCollection, - liveCollections -}) { - return async function getCollection(collection, filter) { - if (collection in liveCollections) { - throw new AstroError({ - ...UnknownContentCollectionError, - message: `Collection "${collection}" is a live collection. Use getLiveCollection() instead of getCollection().` - }); - } - const hasFilter = typeof filter === "function"; - const store = await globalDataStore.get(); - let type; - if (collection in contentCollectionToEntryMap) { - type = "content"; - } else if (collection in dataCollectionToEntryMap) { - type = "data"; - } else if (store.hasCollection(collection)) { - const { default: imageAssetMap } = await import('./content-assets_DleWbedO.mjs'); - const result = []; - for (const rawEntry of store.values(collection)) { - const data = updateImageReferencesInData(rawEntry.data, rawEntry.filePath, imageAssetMap); - let entry = { - ...rawEntry, - data, - collection - }; - if (entry.legacyId) { - entry = emulateLegacyEntry(entry); - } - if (hasFilter && !filter(entry)) { - continue; - } - result.push(entry); - } - return result; - } else { - console.warn( - `The collection ${JSON.stringify( - collection - )} does not exist or is empty. Please check your content config file for errors.` - ); - return []; - } - const lazyImports = Object.values( - type === "content" ? contentCollectionToEntryMap[collection] : dataCollectionToEntryMap[collection] - ); - let entries = []; - if (!Object.assign(__vite_import_meta_env__, { _: process.env._ })?.DEV && cacheEntriesByCollection.has(collection)) { - entries = cacheEntriesByCollection.get(collection); - } else { - const limit = pLimit(10); - entries = await Promise.all( - lazyImports.map( - (lazyImport) => limit(async () => { - const entry = await lazyImport(); - return type === "content" ? { - id: entry.id, - slug: entry.slug, - body: entry.body, - collection: entry.collection, - data: entry.data, - async render() { - return render({ - collection: entry.collection, - id: entry.id, - renderEntryImport: await getRenderEntryImport(collection, entry.slug) - }); - } - } : { - id: entry.id, - collection: entry.collection, - data: entry.data - }; - }) - ) - ); - cacheEntriesByCollection.set(collection, entries); - } - if (hasFilter) { - return entries.filter(filter); - } else { - return entries.slice(); - } - }; -} -function emulateLegacyEntry({ legacyId, ...entry }) { - const legacyEntry = { - ...entry, - id: legacyId, - slug: entry.id - }; - return { - ...legacyEntry, - // Define separately so the render function isn't included in the object passed to `renderEntry()` - render: () => renderEntry(legacyEntry) - }; -} -const CONTENT_LAYER_IMAGE_REGEX = /__ASTRO_IMAGE_="([^"]+)"/g; -async function updateImageReferencesInBody(html, fileName) { - const { default: imageAssetMap } = await import('./content-assets_DleWbedO.mjs'); - const imageObjects = /* @__PURE__ */ new Map(); - const { getImage } = await import('./_astro_assets_BkxcOWlh.mjs').then(n => n._); - for (const [_full, imagePath] of html.matchAll(CONTENT_LAYER_IMAGE_REGEX)) { - try { - const decodedImagePath = JSON.parse(imagePath.replaceAll(""", '"')); - let image; - if (URL.canParse(decodedImagePath.src)) { - image = await getImage(decodedImagePath); - } else { - const id = imageSrcToImportId(decodedImagePath.src, fileName); - const imported = imageAssetMap.get(id); - if (!id || imageObjects.has(id) || !imported) { - continue; - } - image = await getImage({ ...decodedImagePath, src: imported }); - } - imageObjects.set(imagePath, image); - } catch { - throw new Error(`Failed to parse image reference: ${imagePath}`); - } - } - return html.replaceAll(CONTENT_LAYER_IMAGE_REGEX, (full, imagePath) => { - const image = imageObjects.get(imagePath); - if (!image) { - return full; - } - const { index, ...attributes } = image.attributes; - return Object.entries({ - ...attributes, - src: image.src, - srcset: image.srcSet.attribute, - // This attribute is used by the toolbar audit - ...Object.assign(__vite_import_meta_env__, { _: process.env._ }).DEV ? { "data-image-component": "true" } : {} - }).map(([key, value]) => value ? `${key}="${escape(value)}"` : "").join(" "); - }); -} -function updateImageReferencesInData(data, fileName, imageAssetMap) { - return new Traverse(data).map(function(ctx, val) { - if (typeof val === "string" && val.startsWith(IMAGE_IMPORT_PREFIX)) { - const src = val.replace(IMAGE_IMPORT_PREFIX, ""); - const id = imageSrcToImportId(src, fileName); - if (!id) { - ctx.update(src); - return; - } - const imported = imageAssetMap?.get(id); - if (imported) { - ctx.update(imported); - } else { - ctx.update(src); - } - } - }); -} -async function renderEntry(entry) { - if (!entry) { - throw new AstroError(RenderUndefinedEntryError); - } - if ("render" in entry && !("legacyId" in entry)) { - return entry.render(); - } - if (entry.deferredRender) { - try { - const { default: contentModules } = await import('./content-modules_Dz-S_Wwv.mjs'); - const renderEntryImport = contentModules.get(entry.filePath); - return render({ - collection: "", - id: entry.id, - renderEntryImport - }); - } catch (e) { - console.error(e); - } - } - const html = entry?.rendered?.metadata?.imagePaths?.length && entry.filePath ? await updateImageReferencesInBody(entry.rendered.html, entry.filePath) : entry?.rendered?.html; - const Content = createComponent(() => renderTemplate`${unescapeHTML(html)}`); - return { - Content, - headings: entry?.rendered?.metadata?.headings ?? [], - remarkPluginFrontmatter: entry?.rendered?.metadata?.frontmatter ?? {} - }; -} -async function render({ - collection, - id, - renderEntryImport -}) { - const UnexpectedRenderError = new AstroError({ - ...UnknownContentCollectionError, - message: `Unexpected error while rendering ${String(collection)} → ${String(id)}.` - }); - if (typeof renderEntryImport !== "function") throw UnexpectedRenderError; - const baseMod = await renderEntryImport(); - if (baseMod == null || typeof baseMod !== "object") throw UnexpectedRenderError; - const { default: defaultMod } = baseMod; - if (isPropagatedAssetsModule(defaultMod)) { - const { collectedStyles, collectedLinks, collectedScripts, getMod } = defaultMod; - if (typeof getMod !== "function") throw UnexpectedRenderError; - const propagationMod = await getMod(); - if (propagationMod == null || typeof propagationMod !== "object") throw UnexpectedRenderError; - const Content = createComponent({ - factory(result, baseProps, slots) { - let styles = "", links = "", scripts = ""; - if (Array.isArray(collectedStyles)) { - styles = collectedStyles.map((style) => { - return renderUniqueStylesheet(result, { - type: "inline", - content: style - }); - }).join(""); - } - if (Array.isArray(collectedLinks)) { - links = collectedLinks.map((link) => { - return renderUniqueStylesheet(result, { - type: "external", - src: isRemotePath(link) ? link : prependForwardSlash(link) - }); - }).join(""); - } - if (Array.isArray(collectedScripts)) { - scripts = collectedScripts.map((script) => renderScriptElement(script)).join(""); - } - let props = baseProps; - if (id.endsWith("mdx")) { - props = { - components: propagationMod.components ?? {}, - ...baseProps - }; - } - return createHeadAndContent( - unescapeHTML(styles + links + scripts), - renderTemplate`${renderComponent( - result, - "Content", - propagationMod.Content, - props, - slots - )}` - ); - }, - propagation: "self" - }); - return { - Content, - headings: propagationMod.getHeadings?.() ?? [], - remarkPluginFrontmatter: propagationMod.frontmatter ?? {} - }; - } else if (baseMod.Content && typeof baseMod.Content === "function") { - return { - Content: baseMod.Content, - headings: baseMod.getHeadings?.() ?? [], - remarkPluginFrontmatter: baseMod.frontmatter ?? {} - }; - } else { - throw UnexpectedRenderError; - } -} -function isPropagatedAssetsModule(module) { - return typeof module === "object" && module != null && "__astroPropagation" in module; -} - -// astro-head-inject - -const liveCollections = {}; - -const contentDir = '/src/content/'; - -const contentEntryGlob = ""; -const contentCollectionToEntryMap = createCollectionToGlobResultMap({ - globResult: contentEntryGlob, - contentDir, -}); - -const dataEntryGlob = ""; -const dataCollectionToEntryMap = createCollectionToGlobResultMap({ - globResult: dataEntryGlob, - contentDir, -}); -createCollectionToGlobResultMap({ - globResult: { ...contentEntryGlob, ...dataEntryGlob }, - contentDir, -}); - -let lookupMap = {}; -lookupMap = {}; - -new Set(Object.keys(lookupMap)); - -function createGlobLookup(glob) { - return async (collection, lookupId) => { - const filePath = lookupMap[collection]?.entries[lookupId]; - - if (!filePath) return undefined; - return glob[collection][filePath]; - }; -} - -const renderEntryGlob = ""; -const collectionToRenderEntryMap = createCollectionToGlobResultMap({ - globResult: renderEntryGlob, - contentDir, -}); - -const cacheEntriesByCollection = new Map(); -const getCollection = createGetCollection({ - contentCollectionToEntryMap, - dataCollectionToEntryMap, - getRenderEntryImport: createGlobLookup(collectionToRenderEntryMap), - cacheEntriesByCollection, - liveCollections, -}); - -export { getCollection as g }; diff --git a/.vercel/output/_functions/chunks/_astro_data-layer-content_BUPw26ki.mjs b/.vercel/output/_functions/chunks/_astro_data-layer-content_BUPw26ki.mjs deleted file mode 100644 index 5b6e288..0000000 --- a/.vercel/output/_functions/chunks/_astro_data-layer-content_BUPw26ki.mjs +++ /dev/null @@ -1,3 +0,0 @@ -const _astro_dataLayerContent = [["Map",1,2,9,10,114,115,137,138,163,164],"meta::meta",["Map",3,4,5,6,7,8],"astro-version","5.18.0","content-config-digest","e25d79e689a13e47","astro-config-digest","{\"root\":{},\"srcDir\":{},\"publicDir\":{},\"outDir\":{},\"cacheDir\":{},\"site\":\"https://damdug.com\",\"compressHTML\":true,\"base\":\"/\",\"trailingSlash\":\"ignore\",\"output\":\"server\",\"scopedStyleStrategy\":\"attribute\",\"build\":{\"format\":\"directory\",\"client\":{},\"server\":{},\"assets\":\"_astro\",\"serverEntry\":\"entry.mjs\",\"redirects\":false,\"inlineStylesheets\":\"auto\",\"concurrency\":1},\"server\":{\"open\":false,\"host\":false,\"port\":4321,\"streaming\":true,\"allowedHosts\":[]},\"redirects\":{},\"image\":{\"endpoint\":{\"route\":\"/_image\"},\"service\":{\"entrypoint\":\"astro/assets/services/sharp\",\"config\":{}},\"domains\":[],\"remotePatterns\":[],\"responsiveStyles\":false},\"devToolbar\":{\"enabled\":true},\"markdown\":{\"syntaxHighlight\":{\"type\":\"shiki\",\"excludeLangs\":[\"math\"]},\"shikiConfig\":{\"langs\":[],\"langAlias\":{},\"theme\":\"github-dark\",\"themes\":{},\"wrap\":false,\"transformers\":[]},\"remarkPlugins\":[],\"rehypePlugins\":[],\"remarkRehype\":{},\"gfm\":true,\"smartypants\":true},\"security\":{\"checkOrigin\":true,\"allowedDomains\":[],\"actionBodySizeLimit\":1048576},\"env\":{\"schema\":{},\"validateSecrets\":false},\"experimental\":{\"clientPrerender\":false,\"contentIntellisense\":false,\"headingIdCompat\":false,\"preserveScriptOrder\":false,\"liveContentCollections\":false,\"csp\":false,\"staticImportMetaEnv\":false,\"chromeDevtoolsWorkspace\":false,\"failOnPrerenderConflict\":false,\"svgo\":false},\"legacy\":{\"collections\":false}}","notes",["Map",11,12,49,50,80,81],"the-next-step-doctrine",{id:11,data:13,body:22,filePath:23,digest:24,rendered:25,legacyId:48},{title:14,description:15,date:16,category:17,tags:18,author:20,draft:21},"The Next Step Doctrine","The human tendency is to see the result and not the work that produced it. The Next Step Doctrine is the personal practice of The One Rule.",["Date","2026-01-15T00:00:00.000Z"],"life",[19,17],"business","Douglas M. Galloway",false,"The human tendency is to see the result and not the work that produced it.\n\nThe finished business. The person operating at full capacity. The system running cleanly. We see the destination and assume that's the thing to aim at. We set our sights on the outcome and wonder why the gap between where we are and where we want to be doesn't close.\n\nIt doesn't close because we're optimizing for the wrong thing.\n\nThe Next Step Doctrine is the personal practice of The One Rule. Not a planning method. Not a productivity system. A discipline for keeping your attention where it can actually do something — on the step directly in front of you.\n\n## Why the finish line is the wrong focus\n\nOutcomes are the wrong unit of optimization for one reason: you don't control them.\n\nYou control the step in front of you. The quality of your attention at this decision, this task, this moment. Whether what you do right now clears the way for what comes next or quietly impedes it. That's the full extent of your operational leverage at any given point.\n\nThis isn't pessimism about outcomes. It's precision about what you can actually move.\n\nWhen behavior doesn't match values the problem is almost never at the level of values. People rarely stop caring about what matters to them. The problem is at the micro level — individual decisions made without asking whether they serve or violate the thing they're supposed to. The drift is invisible until it's structural. By then it looks like a character problem or a motivation problem. It's a systems problem. Specifically it's an attention problem — attention was on the outcome instead of the step.\n\nThe same drift happens in planning. Someone sets a goal, imagines the result, feels motivated, and begins executing. Three weeks in the motivation fades because the finish line hasn't moved perceptibly. The goal was the fuel and the goal is still distant. The step in front of them — the one that's actually available to work on — becomes something to get through rather than something to execute with precision.\n\nOptimizing for the finish line makes every step feel like an obstacle between you and the thing you actually want. Optimizing for the next step makes every step the thing you actually want.\n\n## The doctrine in practice\n\nThe Next Step Doctrine asks one question before any planning session, any decision, any day:\n\nWhat is the next step, and what does it need from me in order not to impede what follows?\n\nThis question does several things simultaneously.\n\nIt makes the work concrete. The next step is always specific. The goal is often abstract. Abstraction is where motivation lives and dies. Specificity is where work happens.\n\nIt makes quality measurable. A step either clears the way for the next one or it doesn't. That's a standard you can evaluate honestly without waiting for the outcome to tell you whether you succeeded.\n\nIt makes values operational. Your values aren't aspirations to perform toward — they're the standard each micro-decision is measured against before it's made. The question isn't \"am I a person who values X?\" It's \"does this step serve X or impede it?\" One question, applied consistently, closes the gap between stated values and actual behavior without requiring willpower or motivation as the mechanism.\n\nIt makes progress visible at the right scale. Progress measured against a distant outcome is almost always discouraging. Progress measured against whether today handed tomorrow what it needed is available every day. The compound effect of that — days that consistently hand off cleanly — is what outcomes are made of.\n\n## Planning from the next step\n\nMost planning starts at the goal and works backwards. Identify the destination, break it into milestones, break milestones into tasks, execute the tasks.\n\nThis works structurally and fails practically because it front-loads all the clarity into the goal — which is the part you understand least — and assumes the steps will become clear as you move through them. They often don't. The map drawn from the destination is a guess. The map drawn from the next step is built from what you actually know.\n\nThe Next Step Doctrine plans forward instead.\n\nStart with your current honest position — not where you intend to be or used to be but where you actually are right now. From that position identify one step — not the optimal step, not the strategic step, the next available step that doesn't impede what follows. Execute it with full attention. Evaluate it not by whether it moved you toward the goal but by whether it handed the next step what it needed.\n\nRepeat.\n\nThe goal stays visible as orientation. It tells you which direction to face. But the work is always the step in front of you. The finish line is not where your attention lives — it's where you look occasionally to confirm you're still facing the right way.\n\n## The belief underneath all of it\n\nThe One Rule is the governing principle. The Non-Impedance Principle is how you apply it to systems. The Next Step Doctrine is how you apply it to yourself.\n\nAll three are the same idea at different scales.\n\nGood practices generally produce good outcomes. The reverse isn't true.\n\nStart with the next step. The finish line follows.","src/content/notes/the-next-step-doctrine.md","41d63a48e8325144",{html:26,metadata:27},"

The human tendency is to see the result and not the work that produced it.

\n

The finished business. The person operating at full capacity. The system running cleanly. We see the destination and assume that’s the thing to aim at. We set our sights on the outcome and wonder why the gap between where we are and where we want to be doesn’t close.

\n

It doesn’t close because we’re optimizing for the wrong thing.

\n

The Next Step Doctrine is the personal practice of The One Rule. Not a planning method. Not a productivity system. A discipline for keeping your attention where it can actually do something — on the step directly in front of you.

\n

Why the finish line is the wrong focus

\n

Outcomes are the wrong unit of optimization for one reason: you don’t control them.

\n

You control the step in front of you. The quality of your attention at this decision, this task, this moment. Whether what you do right now clears the way for what comes next or quietly impedes it. That’s the full extent of your operational leverage at any given point.

\n

This isn’t pessimism about outcomes. It’s precision about what you can actually move.

\n

When behavior doesn’t match values the problem is almost never at the level of values. People rarely stop caring about what matters to them. The problem is at the micro level — individual decisions made without asking whether they serve or violate the thing they’re supposed to. The drift is invisible until it’s structural. By then it looks like a character problem or a motivation problem. It’s a systems problem. Specifically it’s an attention problem — attention was on the outcome instead of the step.

\n

The same drift happens in planning. Someone sets a goal, imagines the result, feels motivated, and begins executing. Three weeks in the motivation fades because the finish line hasn’t moved perceptibly. The goal was the fuel and the goal is still distant. The step in front of them — the one that’s actually available to work on — becomes something to get through rather than something to execute with precision.

\n

Optimizing for the finish line makes every step feel like an obstacle between you and the thing you actually want. Optimizing for the next step makes every step the thing you actually want.

\n

The doctrine in practice

\n

The Next Step Doctrine asks one question before any planning session, any decision, any day:

\n

What is the next step, and what does it need from me in order not to impede what follows?

\n

This question does several things simultaneously.

\n

It makes the work concrete. The next step is always specific. The goal is often abstract. Abstraction is where motivation lives and dies. Specificity is where work happens.

\n

It makes quality measurable. A step either clears the way for the next one or it doesn’t. That’s a standard you can evaluate honestly without waiting for the outcome to tell you whether you succeeded.

\n

It makes values operational. Your values aren’t aspirations to perform toward — they’re the standard each micro-decision is measured against before it’s made. The question isn’t “am I a person who values X?” It’s “does this step serve X or impede it?” One question, applied consistently, closes the gap between stated values and actual behavior without requiring willpower or motivation as the mechanism.

\n

It makes progress visible at the right scale. Progress measured against a distant outcome is almost always discouraging. Progress measured against whether today handed tomorrow what it needed is available every day. The compound effect of that — days that consistently hand off cleanly — is what outcomes are made of.

\n

Planning from the next step

\n

Most planning starts at the goal and works backwards. Identify the destination, break it into milestones, break milestones into tasks, execute the tasks.

\n

This works structurally and fails practically because it front-loads all the clarity into the goal — which is the part you understand least — and assumes the steps will become clear as you move through them. They often don’t. The map drawn from the destination is a guess. The map drawn from the next step is built from what you actually know.

\n

The Next Step Doctrine plans forward instead.

\n

Start with your current honest position — not where you intend to be or used to be but where you actually are right now. From that position identify one step — not the optimal step, not the strategic step, the next available step that doesn’t impede what follows. Execute it with full attention. Evaluate it not by whether it moved you toward the goal but by whether it handed the next step what it needed.

\n

Repeat.

\n

The goal stays visible as orientation. It tells you which direction to face. But the work is always the step in front of you. The finish line is not where your attention lives — it’s where you look occasionally to confirm you’re still facing the right way.

\n

The belief underneath all of it

\n

The One Rule is the governing principle. The Non-Impedance Principle is how you apply it to systems. The Next Step Doctrine is how you apply it to yourself.

\n

All three are the same idea at different scales.

\n

Good practices generally produce good outcomes. The reverse isn’t true.

\n

Start with the next step. The finish line follows.

",{headings:28,localImagePaths:42,remoteImagePaths:43,frontmatter:44,imagePaths:47},[29,33,36,39],{depth:30,slug:31,text:32},2,"why-the-finish-line-is-the-wrong-focus","Why the finish line is the wrong focus",{depth:30,slug:34,text:35},"the-doctrine-in-practice","The doctrine in practice",{depth:30,slug:37,text:38},"planning-from-the-next-step","Planning from the next step",{depth:30,slug:40,text:41},"the-belief-underneath-all-of-it","The belief underneath all of it",[],[],{title:14,description:15,date:45,category:17,tags:46,author:20,draft:21},["Date","2026-01-15T00:00:00.000Z"],[19,17],[],"the-next-step-doctrine.md","the-one-rule",{id:49,data:51,body:56,filePath:57,digest:58,rendered:59,legacyId:79},{title:52,description:53,date:54,category:19,tags:55,author:20,draft:21},"The One Rule","All traffic law reduces to one rule: don't impede other drivers. Most systems — personal and organizational — don't work this way. They should.",["Date","2025-11-10T00:00:00.000Z"],[17],"All traffic law reduces to one rule: don't impede other drivers.\n\nNot a destination. Not an outcome. One behavioral obligation, followed consistently at every step, that produces a system capable of moving millions of people through impossible complexity without central coordination.\n\nMost systems — personal and organizational — don't work this way. They should.\n\n## The problem this solves\n\nThere is a gap that appears in every system eventually.\n\nIn personal life it looks like behavior that doesn't match values. Someone knows what matters to them and consistently acts against it anyway. Not from weakness. From misalignment at the micro level — individual decisions that seem reasonable in isolation but quietly violate the principle they're supposed to serve.\n\nIn organizations it looks like actions that don't produce results. Teams work hard, execute correctly by local measures, and still miss the outcome. The problem is rarely effort or competence. It's that steps were optimized for their own output rather than for what they hand off to what follows.\n\nBoth are the same problem at different scales.\n\nThe thread gets lost not in the strategy but in the gap between one step and the next. By the time the misalignment is visible it's structural. The drift happened quietly at the micro level and surfaced as something that looks like a macro problem. More planning doesn't fix it. More motivation doesn't fix it.\n\nA clearer governing principle does.\n\n## The One Rule\n\nEvery traffic law — merging, signaling, right of way, speed — exists in service of one thing: don't block the car behind you. That single obligation, honored by every driver at every moment, produces a system that works without anyone managing it from the center.\n\nApplied to how you plan, decide, and build:\n\nEach step has one obligation — not to impede the step that follows.\n\nThis is the governing principle underneath everything I do personally and professionally. Not a productivity hack. Not a goal-setting framework. A standard applied at the micro level that keeps systems aligned through complexity without requiring constant oversight or correction.\n\nThe destination matters. It tells you which direction to face. But you don't drive looking at the destination. You drive looking at the road directly in front of you, making sure you don't impede what comes next, trusting that everyone doing the same thing produces a system that works.\n\n## What changes when you apply it\n\nThe question you ask at every decision point changes.\n\nBefore: Will this get me to the goal?\nAfter: Does this clear the way for what comes next?\n\nThat single reframe shifts focus from outcome — which you don't control — to handoff quality, which you do. A step that produces a locally good result but leaves the next step without what it needs has failed by this standard regardless of its own quality.\n\nThis is where most planning breaks down. Strategy operates at the macro level and assumes the micro will follow. It doesn't. Alignment has to be built into each step or it isn't built at all.\n\nThe One Rule operates at the micro level by design. One question at every step:\n\nWhat does the next step need from this one in order to proceed without friction?\n\nAnswer that consistently and the macro takes care of itself. Miss it consistently and no amount of vision or strategy repairs the drift.\n\n## The belief underneath it\n\nGood practices generally produce good outcomes. The reverse isn't true.\n\nYou cannot optimize for outcomes directly. Outcomes depend on conditions outside your control. What you control is the practice — the step in front of you and whether it clears the way for the next one.\n\nFocus there. The finish line follows.","src/content/notes/the-one-rule.md","bffc2ce23fe6b818",{html:60,metadata:61},"

All traffic law reduces to one rule: don’t impede other drivers.

\n

Not a destination. Not an outcome. One behavioral obligation, followed consistently at every step, that produces a system capable of moving millions of people through impossible complexity without central coordination.

\n

Most systems — personal and organizational — don’t work this way. They should.

\n

The problem this solves

\n

There is a gap that appears in every system eventually.

\n

In personal life it looks like behavior that doesn’t match values. Someone knows what matters to them and consistently acts against it anyway. Not from weakness. From misalignment at the micro level — individual decisions that seem reasonable in isolation but quietly violate the principle they’re supposed to serve.

\n

In organizations it looks like actions that don’t produce results. Teams work hard, execute correctly by local measures, and still miss the outcome. The problem is rarely effort or competence. It’s that steps were optimized for their own output rather than for what they hand off to what follows.

\n

Both are the same problem at different scales.

\n

The thread gets lost not in the strategy but in the gap between one step and the next. By the time the misalignment is visible it’s structural. The drift happened quietly at the micro level and surfaced as something that looks like a macro problem. More planning doesn’t fix it. More motivation doesn’t fix it.

\n

A clearer governing principle does.

\n

The One Rule

\n

Every traffic law — merging, signaling, right of way, speed — exists in service of one thing: don’t block the car behind you. That single obligation, honored by every driver at every moment, produces a system that works without anyone managing it from the center.

\n

Applied to how you plan, decide, and build:

\n

Each step has one obligation — not to impede the step that follows.

\n

This is the governing principle underneath everything I do personally and professionally. Not a productivity hack. Not a goal-setting framework. A standard applied at the micro level that keeps systems aligned through complexity without requiring constant oversight or correction.

\n

The destination matters. It tells you which direction to face. But you don’t drive looking at the destination. You drive looking at the road directly in front of you, making sure you don’t impede what comes next, trusting that everyone doing the same thing produces a system that works.

\n

What changes when you apply it

\n

The question you ask at every decision point changes.

\n

Before: Will this get me to the goal?\nAfter: Does this clear the way for what comes next?

\n

That single reframe shifts focus from outcome — which you don’t control — to handoff quality, which you do. A step that produces a locally good result but leaves the next step without what it needs has failed by this standard regardless of its own quality.

\n

This is where most planning breaks down. Strategy operates at the macro level and assumes the micro will follow. It doesn’t. Alignment has to be built into each step or it isn’t built at all.

\n

The One Rule operates at the micro level by design. One question at every step:

\n

What does the next step need from this one in order to proceed without friction?

\n

Answer that consistently and the macro takes care of itself. Miss it consistently and no amount of vision or strategy repairs the drift.

\n

The belief underneath it

\n

Good practices generally produce good outcomes. The reverse isn’t true.

\n

You cannot optimize for outcomes directly. Outcomes depend on conditions outside your control. What you control is the practice — the step in front of you and whether it clears the way for the next one.

\n

Focus there. The finish line follows.

",{headings:62,localImagePaths:73,remoteImagePaths:74,frontmatter:75,imagePaths:78},[63,66,67,70],{depth:30,slug:64,text:65},"the-problem-this-solves","The problem this solves",{depth:30,slug:49,text:52},{depth:30,slug:68,text:69},"what-changes-when-you-apply-it","What changes when you apply it",{depth:30,slug:71,text:72},"the-belief-underneath-it","The belief underneath it",[],[],{title:52,description:53,date:76,category:19,tags:77,author:20,draft:21},["Date","2025-11-10T00:00:00.000Z"],[17],[],"the-one-rule.md","the-non-impedance-principle",{id:80,data:82,body:88,filePath:89,digest:90,rendered:91,legacyId:113},{title:83,description:84,date:85,category:19,tags:86,author:20,draft:21},"The Non-Impedance Principle","A step that produces a good result but blocks what follows has failed. This is the working definition of impedance in a system.",["Date","2025-12-01T00:00:00.000Z"],[87],"technology","A step that produces a good result but blocks what follows has failed.\n\nThis is the working definition of impedance in a system. Not failure at the local level — failure at the handoff. And it's where most workflows, decision chains, and organizational processes quietly break down.\n\nThe Non-Impedance Principle is The One Rule applied to how you build and operate systems. It answers a specific question: how do you maintain alignment through complexity when the number of steps, people, and variables makes oversight impossible?\n\nYou don't oversee every step. You govern the handoff between them.\n\n## Where systems lose alignment\n\nComplex systems don't fail dramatically. They drift.\n\nA workflow where each step optimizes for its own output rather than its handoff produces friction that compounds invisibly. A decision chain where each choice is locally rational but doesn't account for what it forecloses produces outcomes nobody designed and nobody can fully explain. An AI implementation where each prompt reaches for the final answer rather than the next clarifying input produces responses that sound right and miss the point.\n\nThe misalignment isn't visible at the step level. It accumulates in the gaps between steps and surfaces as a system that doesn't work — without a clear diagnosis of why.\n\nThe conventional response is more process. More documentation. More oversight. More meetings to align the people who were supposed to be aligned by the process.\n\nNone of that addresses the actual problem. The problem is that individual steps weren't designed with their handoff as the primary obligation.\n\n## The principle in practice\n\nThe Non-Impedance Principle introduces one standard at every step of any system:\n\nWhat does the next step need from this one in order to proceed without friction?\n\nThis question is deceptively simple. Answering it honestly requires understanding not just what you're producing but what you're handing off — and to whom, in what condition, with what information attached.\n\nApplied to workflow design this means every step in a process is evaluated not by its output alone but by the quality of what it passes forward. A handoff that requires the next person to interpret, reconstruct, or compensate for missing information is an impedance point regardless of how well the step itself was executed.\n\nApplied to decision-making this means every choice is evaluated not just by its immediate merit but by what it keeps open and what it forecloses. A decision that solves today's problem by constraining tomorrow's options may be locally correct and systemically damaging. Non-impedance asks: does this decision preserve the integrity of the steps that follow?\n\nApplied to AI and chain-of-thought prompting this means each prompt has one job — not to produce the final answer but to produce the next useful input. The goal of a prompt is to not impede the next prompt. The output accumulates across the chain. Reaching for the conclusion at any single step collapses the chain and produces a response that skips the reasoning that would have made it reliable.\n\n## Designing for non-impedance\n\nA system designed around this principle looks different from one designed around outcomes.\n\nOutcome-designed systems work backwards from the goal. Steps exist to serve the destination. Quality is measured by proximity to the result. When things go wrong the diagnosis looks at whether the goal was right, whether people were motivated, whether the strategy was sound.\n\nNon-impedance-designed systems work forward from the first step. Each step is designed to hand off cleanly to the next. Quality is measured at the handoff. When things go wrong the diagnosis looks for the impedance point — the step that failed its obligation to what followed — and fixes it there.\n\nIn SOPs this means writing each step not as an instruction for what to do but as a specification of what the next step needs to receive. The test of a well-written SOP is whether someone could execute each step knowing only what they've been handed and what the next step requires — without needing to understand the whole process.\n\nIn organizational decision-making this means every significant choice includes an explicit account of what it hands forward. Not just what it decides — what it sets up, what it constrains, what information it produces for the next decision-maker in the chain.\n\nIn personal planning this means your system is evaluated not by whether you reached the goal but by whether each day handed the next one what it needed. A day that was productive but left tomorrow's priorities unclear has an impedance problem regardless of what it accomplished.\n\n## The diagnostic question\n\nWhen a system isn't working — personally or organizationally — the Non-Impedance Principle gives you a diagnostic tool more precise than most.\n\nDon't start at the outcome. Don't start at the strategy. Start at the first step and move forward asking one question at each transition:\n\nDid this step give the next one what it needed?\n\nThe first place the answer is no is the impedance point. Fix it there. Not at the goal level. Not at the motivation level. At the handoff.\n\nThis is slower than jumping to a macro diagnosis. It is significantly more likely to produce a fix that holds.","src/content/notes/the-non-impedance-principle.md","f7ef4e036b4837ba",{html:92,metadata:93},"

A step that produces a good result but blocks what follows has failed.

\n

This is the working definition of impedance in a system. Not failure at the local level — failure at the handoff. And it’s where most workflows, decision chains, and organizational processes quietly break down.

\n

The Non-Impedance Principle is The One Rule applied to how you build and operate systems. It answers a specific question: how do you maintain alignment through complexity when the number of steps, people, and variables makes oversight impossible?

\n

You don’t oversee every step. You govern the handoff between them.

\n

Where systems lose alignment

\n

Complex systems don’t fail dramatically. They drift.

\n

A workflow where each step optimizes for its own output rather than its handoff produces friction that compounds invisibly. A decision chain where each choice is locally rational but doesn’t account for what it forecloses produces outcomes nobody designed and nobody can fully explain. An AI implementation where each prompt reaches for the final answer rather than the next clarifying input produces responses that sound right and miss the point.

\n

The misalignment isn’t visible at the step level. It accumulates in the gaps between steps and surfaces as a system that doesn’t work — without a clear diagnosis of why.

\n

The conventional response is more process. More documentation. More oversight. More meetings to align the people who were supposed to be aligned by the process.

\n

None of that addresses the actual problem. The problem is that individual steps weren’t designed with their handoff as the primary obligation.

\n

The principle in practice

\n

The Non-Impedance Principle introduces one standard at every step of any system:

\n

What does the next step need from this one in order to proceed without friction?

\n

This question is deceptively simple. Answering it honestly requires understanding not just what you’re producing but what you’re handing off — and to whom, in what condition, with what information attached.

\n

Applied to workflow design this means every step in a process is evaluated not by its output alone but by the quality of what it passes forward. A handoff that requires the next person to interpret, reconstruct, or compensate for missing information is an impedance point regardless of how well the step itself was executed.

\n

Applied to decision-making this means every choice is evaluated not just by its immediate merit but by what it keeps open and what it forecloses. A decision that solves today’s problem by constraining tomorrow’s options may be locally correct and systemically damaging. Non-impedance asks: does this decision preserve the integrity of the steps that follow?

\n

Applied to AI and chain-of-thought prompting this means each prompt has one job — not to produce the final answer but to produce the next useful input. The goal of a prompt is to not impede the next prompt. The output accumulates across the chain. Reaching for the conclusion at any single step collapses the chain and produces a response that skips the reasoning that would have made it reliable.

\n

Designing for non-impedance

\n

A system designed around this principle looks different from one designed around outcomes.

\n

Outcome-designed systems work backwards from the goal. Steps exist to serve the destination. Quality is measured by proximity to the result. When things go wrong the diagnosis looks at whether the goal was right, whether people were motivated, whether the strategy was sound.

\n

Non-impedance-designed systems work forward from the first step. Each step is designed to hand off cleanly to the next. Quality is measured at the handoff. When things go wrong the diagnosis looks for the impedance point — the step that failed its obligation to what followed — and fixes it there.

\n

In SOPs this means writing each step not as an instruction for what to do but as a specification of what the next step needs to receive. The test of a well-written SOP is whether someone could execute each step knowing only what they’ve been handed and what the next step requires — without needing to understand the whole process.

\n

In organizational decision-making this means every significant choice includes an explicit account of what it hands forward. Not just what it decides — what it sets up, what it constrains, what information it produces for the next decision-maker in the chain.

\n

In personal planning this means your system is evaluated not by whether you reached the goal but by whether each day handed the next one what it needed. A day that was productive but left tomorrow’s priorities unclear has an impedance problem regardless of what it accomplished.

\n

The diagnostic question

\n

When a system isn’t working — personally or organizationally — the Non-Impedance Principle gives you a diagnostic tool more precise than most.

\n

Don’t start at the outcome. Don’t start at the strategy. Start at the first step and move forward asking one question at each transition:

\n

Did this step give the next one what it needed?

\n

The first place the answer is no is the impedance point. Fix it there. Not at the goal level. Not at the motivation level. At the handoff.

\n

This is slower than jumping to a macro diagnosis. It is significantly more likely to produce a fix that holds.

",{headings:94,localImagePaths:107,remoteImagePaths:108,frontmatter:109,imagePaths:112},[95,98,101,104],{depth:30,slug:96,text:97},"where-systems-lose-alignment","Where systems lose alignment",{depth:30,slug:99,text:100},"the-principle-in-practice","The principle in practice",{depth:30,slug:102,text:103},"designing-for-non-impedance","Designing for non-impedance",{depth:30,slug:105,text:106},"the-diagnostic-question","The diagnostic question",[],[],{title:83,description:84,date:110,category:19,tags:111,author:20,draft:21},["Date","2025-12-01T00:00:00.000Z"],[87],[],"the-non-impedance-principle.md","field-notes",["Map",116,117],"first-note",{id:116,data:118,body:126,filePath:127,digest:128,rendered:129,legacyId:136},{title:119,description:120,date:121,tags:122,author:20,draft:21},"On Structure Before Automation","Why organizations reach for tools before they have the structure to use them.",["Date","2026-03-07T00:00:00.000Z"],[123,124,125],"intelligence","systems","doctrine","Most organizations reach for automation before they have structure to automate.\n\nThe pattern is consistent: a new tool is introduced, friction persists, another tool is introduced to manage the first. The underlying problem — fragmented, ungoverned data — compounds with each addition.\n\nStructure is not preparation for intelligence. Structure *is* intelligence.\n\nBefore any tool is introduced, the question to answer is: what decisions does this organization need to make repeatedly, and what information would make those decisions legible?\n\nThat question, answered clearly, is where intelligence infrastructure begins.","src/content/field-notes/first-note.md","da45d08fe5007f74",{html:130,metadata:131},"

Most organizations reach for automation before they have structure to automate.

\n

The pattern is consistent: a new tool is introduced, friction persists, another tool is introduced to manage the first. The underlying problem — fragmented, ungoverned data — compounds with each addition.

\n

Structure is not preparation for intelligence. Structure is intelligence.

\n

Before any tool is introduced, the question to answer is: what decisions does this organization need to make repeatedly, and what information would make those decisions legible?

\n

That question, answered clearly, is where intelligence infrastructure begins.

",{headings:132,localImagePaths:133,remoteImagePaths:134,frontmatter:118,imagePaths:135},[],[],[],[],"first-note.md","hdk",["Map",139,140],"what-is-the-hdk",{id:139,data:141,body:149,filePath:150,digest:151,rendered:152,legacyId:162},{title:142,description:143,date:144,section:145,order:146,tags:147,author:20,draft:21},"What Is the HDK","An introduction to the Human Development Kit — a practical framework for systems-oriented self-development.",["Date","2026-03-07T00:00:00.000Z"],"Introduction",1,[137,148],"introduction","The HDK — Human Development Kit — is a structured framework for intentional personal development.\n\nIt is not a productivity system. It is not a wellness guide. It is a set of governing principles, frameworks, and tools for people who want to operate with greater clarity, structure, and purpose.\n\nThe guidebook is being converted into a series of articles published here. Each entry stands alone. Read in sequence or by topic.\n\nMore entries forthcoming.","src/content/hdk/what-is-the-hdk.md","8c6eac19028f2bb3",{html:153,metadata:154},"

The HDK — Human Development Kit — is a structured framework for intentional personal development.

\n

It is not a productivity system. It is not a wellness guide. It is a set of governing principles, frameworks, and tools for people who want to operate with greater clarity, structure, and purpose.

\n

The guidebook is being converted into a series of articles published here. Each entry stands alone. Read in sequence or by topic.

\n

More entries forthcoming.

",{headings:155,localImagePaths:156,remoteImagePaths:157,frontmatter:158,imagePaths:161},[],[],[],{title:142,description:143,date:159,section:145,order:146,tags:160,author:20,draft:21},["Date","2026-03-07T00:00:00.000Z"],[137,148],[],"what-is-the-hdk.md","white-papers",["Map",165,166],"intelligence-infrastructure-primer",{id:165,data:167,body:174,filePath:175,digest:176,rendered:177,legacyId:193},{title:168,description:169,date:170,tags:171,author:20,draft:21},"Intelligence Infrastructure: A Primer","What intelligence infrastructure is, why it matters, and why most organizations don't have it.",["Date","2026-03-07T00:00:00.000Z"],[123,172,173],"infrastructure","organizations","Most organizations have data. Few have intelligence.\n\nThe difference is not technology. It is structure — the governed layer that determines what gets collected, how it gets interpreted, and who acts on it. Intelligence infrastructure is that layer. It sits below tooling, below automation, below dashboards. Without it, every tool introduced makes the underlying problem harder to solve.\n\nThis primer defines the term, describes the structural gap most organizations face, and outlines the conditions under which intelligence infrastructure becomes possible.\n\n---\n\n## What Intelligence Infrastructure Is\n\nIntelligence infrastructure is the set of governed systems that convert fragmented organizational data into repeatable, legible decision logic.\n\nIt includes:\n\n- **Signal definition** — what information matters, and why\n- **Scoring models** — how information gets weighted and interpreted\n- **Tier frameworks** — how outputs get prioritized\n- **SOP formalization** — how decisions get made consistently over time\n- **AI readiness** — the structural preconditions for embedding AI capability\n\nNone of these are tools. All of them are structural decisions.\n\n---\n\n## Why Most Organizations Don't Have It\n\nThe gap is not a technology problem. It is a sequencing problem.\n\nOrganizations reach for automation before they have structure to automate. They introduce AI before they have governed data for AI to operate on. They build dashboards before they know what decisions the dashboards should inform.\n\nThe result is layered complexity with no foundation. Each new tool adds friction rather than removing it.\n\n---\n\n## The Conditions for Intelligence Infrastructure\n\nThree conditions make intelligence infrastructure possible:\n\n**1. Structural clarity** — the organization can articulate what decisions it needs to make repeatedly, and what information those decisions require.\n\n**2. Data governance** — the organization has defined what data it owns, how it is maintained, and who is accountable for its quality.\n\n**3. Decision logic** — the organization has formalized how information becomes action, not just how information gets collected.\n\nThese conditions precede technology. They are the foundation on which useful tools can be built.\n\n---\n\n*This is an excerpt from ongoing work at Esoteria. A full version of this framework is available through advisory engagements.*","src/content/white-papers/intelligence-infrastructure-primer.md","d3c0162b9e891735",{html:178,metadata:179},"

Most organizations have data. Few have intelligence.

\n

The difference is not technology. It is structure — the governed layer that determines what gets collected, how it gets interpreted, and who acts on it. Intelligence infrastructure is that layer. It sits below tooling, below automation, below dashboards. Without it, every tool introduced makes the underlying problem harder to solve.

\n

This primer defines the term, describes the structural gap most organizations face, and outlines the conditions under which intelligence infrastructure becomes possible.

\n
\n

What Intelligence Infrastructure Is

\n

Intelligence infrastructure is the set of governed systems that convert fragmented organizational data into repeatable, legible decision logic.

\n

It includes:

\n
    \n
  • Signal definition — what information matters, and why
  • \n
  • Scoring models — how information gets weighted and interpreted
  • \n
  • Tier frameworks — how outputs get prioritized
  • \n
  • SOP formalization — how decisions get made consistently over time
  • \n
  • AI readiness — the structural preconditions for embedding AI capability
  • \n
\n

None of these are tools. All of them are structural decisions.

\n
\n

Why Most Organizations Don’t Have It

\n

The gap is not a technology problem. It is a sequencing problem.

\n

Organizations reach for automation before they have structure to automate. They introduce AI before they have governed data for AI to operate on. They build dashboards before they know what decisions the dashboards should inform.

\n

The result is layered complexity with no foundation. Each new tool adds friction rather than removing it.

\n
\n

The Conditions for Intelligence Infrastructure

\n

Three conditions make intelligence infrastructure possible:

\n

1. Structural clarity — the organization can articulate what decisions it needs to make repeatedly, and what information those decisions require.

\n

2. Data governance — the organization has defined what data it owns, how it is maintained, and who is accountable for its quality.

\n

3. Decision logic — the organization has formalized how information becomes action, not just how information gets collected.

\n

These conditions precede technology. They are the foundation on which useful tools can be built.

\n
\n

This is an excerpt from ongoing work at Esoteria. A full version of this framework is available through advisory engagements.

",{headings:180,localImagePaths:190,remoteImagePaths:191,frontmatter:167,imagePaths:192},[181,184,187],{depth:30,slug:182,text:183},"what-intelligence-infrastructure-is","What Intelligence Infrastructure Is",{depth:30,slug:185,text:186},"why-most-organizations-dont-have-it","Why Most Organizations Don’t Have It",{depth:30,slug:188,text:189},"the-conditions-for-intelligence-infrastructure","The Conditions for Intelligence Infrastructure",[],[],[],"intelligence-infrastructure-primer.md"]; - -export { _astro_dataLayerContent as default }; diff --git a/.vercel/output/_functions/chunks/astro-designed-error-pages_C_Ez8g0J.mjs b/.vercel/output/_functions/chunks/astro-designed-error-pages_C_Ez8g0J.mjs deleted file mode 100644 index 51ab9f3..0000000 --- a/.vercel/output/_functions/chunks/astro-designed-error-pages_C_Ez8g0J.mjs +++ /dev/null @@ -1,358 +0,0 @@ -import { parse, stringify } from 'devalue'; -import { ab as REDIRECT_STATUS_CODES, A as AstroError, ac as ActionsReturnedInvalidDataError, D as DEFAULT_404_COMPONENT } from './astro/server_D2NiA7f1.mjs'; -import { escape } from 'html-escaper'; - -const ACTION_QUERY_PARAMS$1 = { - actionName: "_action"}; -const ACTION_RPC_ROUTE_PATTERN = "/_actions/[...path]"; - -const __vite_import_meta_env__ = {"ASSETS_PREFIX": undefined, "BASE_URL": "/", "DEV": false, "MODE": "production", "PROD": true, "SITE": "https://damdug.com", "SSR": true}; -const ACTION_QUERY_PARAMS = ACTION_QUERY_PARAMS$1; -const codeToStatusMap = { - // Implemented from IANA HTTP Status Code Registry - // https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml - BAD_REQUEST: 400, - UNAUTHORIZED: 401, - PAYMENT_REQUIRED: 402, - FORBIDDEN: 403, - NOT_FOUND: 404, - METHOD_NOT_ALLOWED: 405, - NOT_ACCEPTABLE: 406, - PROXY_AUTHENTICATION_REQUIRED: 407, - REQUEST_TIMEOUT: 408, - CONFLICT: 409, - GONE: 410, - LENGTH_REQUIRED: 411, - PRECONDITION_FAILED: 412, - CONTENT_TOO_LARGE: 413, - URI_TOO_LONG: 414, - UNSUPPORTED_MEDIA_TYPE: 415, - RANGE_NOT_SATISFIABLE: 416, - EXPECTATION_FAILED: 417, - MISDIRECTED_REQUEST: 421, - UNPROCESSABLE_CONTENT: 422, - LOCKED: 423, - FAILED_DEPENDENCY: 424, - TOO_EARLY: 425, - UPGRADE_REQUIRED: 426, - PRECONDITION_REQUIRED: 428, - TOO_MANY_REQUESTS: 429, - REQUEST_HEADER_FIELDS_TOO_LARGE: 431, - UNAVAILABLE_FOR_LEGAL_REASONS: 451, - INTERNAL_SERVER_ERROR: 500, - NOT_IMPLEMENTED: 501, - BAD_GATEWAY: 502, - SERVICE_UNAVAILABLE: 503, - GATEWAY_TIMEOUT: 504, - HTTP_VERSION_NOT_SUPPORTED: 505, - VARIANT_ALSO_NEGOTIATES: 506, - INSUFFICIENT_STORAGE: 507, - LOOP_DETECTED: 508, - NETWORK_AUTHENTICATION_REQUIRED: 511 -}; -const statusToCodeMap = Object.entries(codeToStatusMap).reduce( - // reverse the key-value pairs - (acc, [key, value]) => ({ ...acc, [value]: key }), - {} -); -class ActionError extends Error { - type = "AstroActionError"; - code = "INTERNAL_SERVER_ERROR"; - status = 500; - constructor(params) { - super(params.message); - this.code = params.code; - this.status = ActionError.codeToStatus(params.code); - if (params.stack) { - this.stack = params.stack; - } - } - static codeToStatus(code) { - return codeToStatusMap[code]; - } - static statusToCode(status) { - return statusToCodeMap[status] ?? "INTERNAL_SERVER_ERROR"; - } - static fromJson(body) { - if (isInputError(body)) { - return new ActionInputError(body.issues); - } - if (isActionError(body)) { - return new ActionError(body); - } - return new ActionError({ - code: "INTERNAL_SERVER_ERROR" - }); - } -} -function isActionError(error) { - return typeof error === "object" && error != null && "type" in error && error.type === "AstroActionError"; -} -function isInputError(error) { - return typeof error === "object" && error != null && "type" in error && error.type === "AstroActionInputError" && "issues" in error && Array.isArray(error.issues); -} -class ActionInputError extends ActionError { - type = "AstroActionInputError"; - // We don't expose all ZodError properties. - // Not all properties will serialize from server to client, - // and we don't want to import the full ZodError object into the client. - issues; - fields; - constructor(issues) { - super({ - message: `Failed to validate: ${JSON.stringify(issues, null, 2)}`, - code: "BAD_REQUEST" - }); - this.issues = issues; - this.fields = {}; - for (const issue of issues) { - if (issue.path.length > 0) { - const key = issue.path[0].toString(); - this.fields[key] ??= []; - this.fields[key]?.push(issue.message); - } - } - } -} -function getActionQueryString(name) { - const searchParams = new URLSearchParams({ [ACTION_QUERY_PARAMS$1.actionName]: name }); - return `?${searchParams.toString()}`; -} -function serializeActionResult(res) { - if (res.error) { - if (Object.assign(__vite_import_meta_env__, { _: process.env._ })?.DEV) { - actionResultErrorStack.set(res.error.stack); - } - let body2; - if (res.error instanceof ActionInputError) { - body2 = { - type: res.error.type, - issues: res.error.issues, - fields: res.error.fields - }; - } else { - body2 = { - ...res.error, - message: res.error.message - }; - } - return { - type: "error", - status: res.error.status, - contentType: "application/json", - body: JSON.stringify(body2) - }; - } - if (res.data === void 0) { - return { - type: "empty", - status: 204 - }; - } - let body; - try { - body = stringify(res.data, { - // Add support for URL objects - URL: (value) => value instanceof URL && value.href - }); - } catch (e) { - let hint = ActionsReturnedInvalidDataError.hint; - if (res.data instanceof Response) { - hint = REDIRECT_STATUS_CODES.includes(res.data.status) ? "If you need to redirect when the action succeeds, trigger a redirect where the action is called. See the Actions guide for server and client redirect examples: https://docs.astro.build/en/guides/actions." : "If you need to return a Response object, try using a server endpoint instead. See https://docs.astro.build/en/guides/endpoints/#server-endpoints-api-routes"; - } - throw new AstroError({ - ...ActionsReturnedInvalidDataError, - message: ActionsReturnedInvalidDataError.message(String(e)), - hint - }); - } - return { - type: "data", - status: 200, - contentType: "application/json+devalue", - body - }; -} -function deserializeActionResult(res) { - if (res.type === "error") { - let json; - try { - json = JSON.parse(res.body); - } catch { - return { - data: void 0, - error: new ActionError({ - message: res.body, - code: "INTERNAL_SERVER_ERROR" - }) - }; - } - if (Object.assign(__vite_import_meta_env__, { _: process.env._ })?.PROD) { - return { error: ActionError.fromJson(json), data: void 0 }; - } else { - const error = ActionError.fromJson(json); - error.stack = actionResultErrorStack.get(); - return { - error, - data: void 0 - }; - } - } - if (res.type === "empty") { - return { data: void 0, error: void 0 }; - } - return { - data: parse(res.body, { - URL: (href) => new URL(href) - }), - error: void 0 - }; -} -const actionResultErrorStack = /* @__PURE__ */ (function actionResultErrorStackFn() { - let errorStack; - return { - set(stack) { - errorStack = stack; - }, - get() { - return errorStack; - } - }; -})(); - -function template({ - title, - pathname, - statusCode = 404, - tabTitle, - body -}) { - return ` - - - - ${tabTitle} - - - -
- -

${statusCode ? `${statusCode}: ` : ""}${title}

- ${body || ` -
Path: ${escape(pathname)}
- `} -
- -`; -} - -const DEFAULT_404_ROUTE = { - component: DEFAULT_404_COMPONENT, - generate: () => "", - params: [], - pattern: /^\/404\/?$/, - prerender: false, - pathname: "/404", - segments: [[{ content: "404", dynamic: false, spread: false }]], - type: "page", - route: "/404", - fallbackRoutes: [], - isIndex: false, - origin: "internal" -}; -function ensure404Route(manifest) { - if (!manifest.routes.some((route) => route.route === "/404")) { - manifest.routes.push(DEFAULT_404_ROUTE); - } - return manifest; -} -async function default404Page({ pathname }) { - return new Response( - template({ - statusCode: 404, - title: "Not found", - tabTitle: "404: Not Found", - pathname - }), - { status: 404, headers: { "Content-Type": "text/html" } } - ); -} -default404Page.isAstroComponentFactory = true; -const default404Instance = { - default: default404Page -}; - -export { ActionError as A, DEFAULT_404_ROUTE as D, deserializeActionResult as a, ACTION_RPC_ROUTE_PATTERN as b, ACTION_QUERY_PARAMS as c, default404Instance as d, ensure404Route as e, getActionQueryString as g, serializeActionResult as s }; diff --git a/.vercel/output/_functions/chunks/astro/server_D2NiA7f1.mjs b/.vercel/output/_functions/chunks/astro/server_D2NiA7f1.mjs deleted file mode 100644 index 0d5c829..0000000 --- a/.vercel/output/_functions/chunks/astro/server_D2NiA7f1.mjs +++ /dev/null @@ -1,2879 +0,0 @@ -import colors from 'piccolore'; -import { clsx } from 'clsx'; -import { escape } from 'html-escaper'; -import { decodeBase64, encodeBase64, encodeHexUpperCase, decodeHex } from '@oslojs/encoding'; -import { z } from 'zod'; -import 'cssesc'; - -const ASTRO_VERSION = "5.18.0"; -const REROUTE_DIRECTIVE_HEADER = "X-Astro-Reroute"; -const REWRITE_DIRECTIVE_HEADER_KEY = "X-Astro-Rewrite"; -const REWRITE_DIRECTIVE_HEADER_VALUE = "yes"; -const NOOP_MIDDLEWARE_HEADER = "X-Astro-Noop"; -const ROUTE_TYPE_HEADER = "X-Astro-Route-Type"; -const DEFAULT_404_COMPONENT = "astro-default-404.astro"; -const REDIRECT_STATUS_CODES = [301, 302, 303, 307, 308, 300, 304]; -const REROUTABLE_STATUS_CODES = [404, 500]; -const clientAddressSymbol = Symbol.for("astro.clientAddress"); -const originPathnameSymbol = Symbol.for("astro.originPathname"); -const nodeRequestAbortControllerCleanupSymbol = Symbol.for( - "astro.nodeRequestAbortControllerCleanup" -); -const responseSentSymbol = Symbol.for("astro.responseSent"); - -function normalizeLF(code) { - return code.replace(/\r\n|\r(?!\n)|\n/g, "\n"); -} - -function codeFrame(src, loc) { - if (!loc || loc.line === void 0 || loc.column === void 0) { - return ""; - } - const lines = normalizeLF(src).split("\n").map((ln) => ln.replace(/\t/g, " ")); - const visibleLines = []; - for (let n = -2; n <= 2; n++) { - if (lines[loc.line + n]) visibleLines.push(loc.line + n); - } - let gutterWidth = 0; - for (const lineNo of visibleLines) { - let w = `> ${lineNo}`; - if (w.length > gutterWidth) gutterWidth = w.length; - } - let output = ""; - for (const lineNo of visibleLines) { - const isFocusedLine = lineNo === loc.line - 1; - output += isFocusedLine ? "> " : " "; - output += `${lineNo + 1} | ${lines[lineNo]} -`; - if (isFocusedLine) - output += `${Array.from({ length: gutterWidth }).join(" ")} | ${Array.from({ - length: loc.column - }).join(" ")}^ -`; - } - return output; -} - -class AstroError extends Error { - loc; - title; - hint; - frame; - type = "AstroError"; - constructor(props, options) { - const { name, title, message, stack, location, hint, frame } = props; - super(message, options); - this.title = title; - this.name = name; - if (message) this.message = message; - this.stack = stack ? stack : this.stack; - this.loc = location; - this.hint = hint; - this.frame = frame; - } - setLocation(location) { - this.loc = location; - } - setName(name) { - this.name = name; - } - setMessage(message) { - this.message = message; - } - setHint(hint) { - this.hint = hint; - } - setFrame(source, location) { - this.frame = codeFrame(source, location); - } - static is(err) { - return err?.type === "AstroError"; - } -} - -const ClientAddressNotAvailable = { - name: "ClientAddressNotAvailable", - title: "`Astro.clientAddress` is not available in current adapter.", - message: (adapterName) => `\`Astro.clientAddress\` is not available in the \`${adapterName}\` adapter. File an issue with the adapter to add support.` -}; -const PrerenderClientAddressNotAvailable = { - name: "PrerenderClientAddressNotAvailable", - title: "`Astro.clientAddress` cannot be used inside prerendered routes.", - message: (name) => `\`Astro.clientAddress\` cannot be used inside prerendered route ${name}` -}; -const StaticClientAddressNotAvailable = { - name: "StaticClientAddressNotAvailable", - title: "`Astro.clientAddress` is not available in prerendered pages.", - message: "`Astro.clientAddress` is only available on pages that are server-rendered.", - hint: "See https://docs.astro.build/en/guides/on-demand-rendering/ for more information on how to enable SSR." -}; -const NoMatchingStaticPathFound = { - name: "NoMatchingStaticPathFound", - title: "No static path found for requested path.", - message: (pathName) => `A \`getStaticPaths()\` route pattern was matched, but no matching static path was found for requested path \`${pathName}\`.`, - hint: (possibleRoutes) => `Possible dynamic routes being matched: ${possibleRoutes.join(", ")}.` -}; -const OnlyResponseCanBeReturned = { - name: "OnlyResponseCanBeReturned", - title: "Invalid type returned by Astro page.", - message: (route, returnedValue) => `Route \`${route ? route : ""}\` returned a \`${returnedValue}\`. Only a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from Astro files.`, - hint: "See https://docs.astro.build/en/guides/on-demand-rendering/#response for more information." -}; -const MissingMediaQueryDirective = { - name: "MissingMediaQueryDirective", - title: "Missing value for `client:media` directive.", - message: 'Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided' -}; -const NoMatchingRenderer = { - name: "NoMatchingRenderer", - title: "No matching renderer found.", - message: (componentName, componentExtension, plural, validRenderersCount) => `Unable to render \`${componentName}\`. - -${validRenderersCount > 0 ? `There ${plural ? "are" : "is"} ${validRenderersCount} renderer${plural ? "s" : ""} configured in your \`astro.config.mjs\` file, -but ${plural ? "none were" : "it was not"} able to server-side render \`${componentName}\`.` : `No valid renderer was found ${componentExtension ? `for the \`.${componentExtension}\` file extension.` : `for this file extension.`}`}`, - hint: (probableRenderers) => `Did you mean to enable the ${probableRenderers} integration? - -See https://docs.astro.build/en/guides/framework-components/ for more information on how to install and configure integrations.` -}; -const NoClientOnlyHint = { - name: "NoClientOnlyHint", - title: "Missing hint on client:only directive.", - message: (componentName) => `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`, - hint: (probableRenderers) => `Did you mean to pass \`client:only="${probableRenderers}"\`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only` -}; -const InvalidGetStaticPathsEntry = { - name: "InvalidGetStaticPathsEntry", - title: "Invalid entry inside getStaticPath's return value", - message: (entryType) => `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``, - hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths." -}; -const InvalidGetStaticPathsReturn = { - name: "InvalidGetStaticPathsReturn", - title: "Invalid value returned by getStaticPaths.", - message: (returnType) => `Invalid type returned by \`getStaticPaths\`. Expected an \`array\`, got \`${returnType}\``, - hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths." -}; -const GetStaticPathsExpectedParams = { - name: "GetStaticPathsExpectedParams", - title: "Missing params property on `getStaticPaths` route.", - message: "Missing or empty required `params` property on `getStaticPaths` route.", - hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths." -}; -const GetStaticPathsInvalidRouteParam = { - name: "GetStaticPathsInvalidRouteParam", - title: "Invalid value for `getStaticPaths` route parameter.", - message: (key, value, valueType) => `Invalid getStaticPaths route parameter for \`${key}\`. Expected undefined, a string or a number, received \`${valueType}\` (\`${value}\`)`, - hint: "See https://docs.astro.build/en/reference/routing-reference/#getstaticpaths for more information on getStaticPaths." -}; -const GetStaticPathsRequired = { - name: "GetStaticPathsRequired", - title: "`getStaticPaths()` function required for dynamic routes.", - message: "`getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.", - hint: `See https://docs.astro.build/en/guides/routing/#dynamic-routes for more information on dynamic routes. - - If you meant for this route to be server-rendered, set \`export const prerender = false;\` in the page.` -}; -const ReservedSlotName = { - name: "ReservedSlotName", - title: "Invalid slot name.", - message: (slotName) => `Unable to create a slot named \`${slotName}\`. \`${slotName}\` is a reserved slot name. Please update the name of this slot.` -}; -const NoMatchingImport = { - name: "NoMatchingImport", - title: "No import found for component.", - message: (componentName) => `Could not render \`${componentName}\`. No matching import has been found for \`${componentName}\`.`, - hint: "Please make sure the component is properly imported." -}; -const InvalidComponentArgs = { - name: "InvalidComponentArgs", - title: "Invalid component arguments.", - message: (name) => `Invalid arguments passed to${name ? ` <${name}>` : ""} component.`, - hint: "Astro components cannot be rendered directly via function call, such as `Component()` or `{items.map(Component)}`." -}; -const PageNumberParamNotFound = { - name: "PageNumberParamNotFound", - title: "Page number param not found.", - message: (paramName) => `[paginate()] page number param \`${paramName}\` not found in your filepath.`, - hint: "Rename your file to `[page].astro` or `[...page].astro`." -}; -const ImageMissingAlt = { - name: "ImageMissingAlt", - title: 'Image missing required "alt" property.', - message: 'Image missing "alt" property. "alt" text is required to describe important images on the page.', - hint: 'Use an empty string ("") for decorative images.' -}; -const InvalidImageService = { - name: "InvalidImageService", - title: "Error while loading image service.", - message: "There was an error loading the configured image service. Please see the stack trace for more information." -}; -const MissingImageDimension = { - name: "MissingImageDimension", - title: "Missing image dimensions", - message: (missingDimension, imageURL) => `Missing ${missingDimension === "both" ? "width and height attributes" : `${missingDimension} attribute`} for ${imageURL}. When using remote images, both dimensions are required in order to avoid CLS.`, - hint: "If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets). You can also use `inferSize={true}` for remote images to get the original dimensions." -}; -const FailedToFetchRemoteImageDimensions = { - name: "FailedToFetchRemoteImageDimensions", - title: "Failed to retrieve remote image dimensions", - message: (imageURL) => `Failed to get the dimensions for ${imageURL}.`, - hint: "Verify your remote image URL is accurate, and that you are not using `inferSize` with a file located in your `public/` folder." -}; -const RemoteImageNotAllowed = { - name: "RemoteImageNotAllowed", - title: "Remote image is not allowed", - message: (imageURL) => `Remote image ${imageURL} is not allowed by your image configuration.`, - hint: "Update `image.domains` or `image.remotePatterns`, or remove `inferSize` for this image." -}; -const UnsupportedImageFormat = { - name: "UnsupportedImageFormat", - title: "Unsupported image format", - message: (format, imagePath, supportedFormats) => `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join( - ", " - )} are supported by our image services.`, - hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for." -}; -const UnsupportedImageConversion = { - name: "UnsupportedImageConversion", - title: "Unsupported image conversion", - message: "Converting between vector (such as SVGs) and raster (such as PNGs and JPEGs) images is not currently supported." -}; -const PrerenderDynamicEndpointPathCollide = { - name: "PrerenderDynamicEndpointPathCollide", - title: "Prerendered dynamic endpoint has path collision.", - message: (pathname) => `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, or add an additional extension to the endpoint's filename.`, - hint: (filename) => `Rename \`${filename}\` to \`${filename.replace(/\.(?:js|ts)/, (m) => `.json` + m)}\`` -}; -const ExpectedImage = { - name: "ExpectedImage", - title: "Expected src to be an image.", - message: (src, typeofOptions, fullOptions) => `Expected \`src\` property for \`getImage\` or \`\` to be either an ESM imported image or a string with the path of a remote image. Received \`${src}\` (type: \`${typeofOptions}\`). - -Full serialized options received: \`${fullOptions}\`.`, - hint: "This error can often happen because of a wrong path. Make sure the path to your image is correct. If you're passing an async function, make sure to call and await it." -}; -const ExpectedImageOptions = { - name: "ExpectedImageOptions", - title: "Expected image options.", - message: (options) => `Expected getImage() parameter to be an object. Received \`${options}\`.` -}; -const ExpectedNotESMImage = { - name: "ExpectedNotESMImage", - title: "Expected image options, not an ESM-imported image.", - message: "An ESM-imported image cannot be passed directly to `getImage()`. Instead, pass an object with the image in the `src` property.", - hint: "Try changing `getImage(myImage)` to `getImage({ src: myImage })`" -}; -const IncompatibleDescriptorOptions = { - name: "IncompatibleDescriptorOptions", - title: "Cannot set both `densities` and `widths`", - message: "Only one of `densities` or `widths` can be specified. In most cases, you'll probably want to use only `widths` if you require specific widths.", - hint: "Those attributes are used to construct a `srcset` attribute, which cannot have both `x` and `w` descriptors." -}; -const NoImageMetadata = { - name: "NoImageMetadata", - title: "Could not process image metadata.", - message: (imagePath) => `Could not process image metadata${imagePath ? ` for \`${imagePath}\`` : ""}.`, - hint: "This is often caused by a corrupted or malformed image. Re-exporting the image from your image editor may fix this issue." -}; -const ResponseSentError = { - name: "ResponseSentError", - title: "Unable to set response.", - message: "The response has already been sent to the browser and cannot be altered." -}; -const MiddlewareNoDataOrNextCalled = { - name: "MiddlewareNoDataOrNextCalled", - title: "The middleware didn't return a `Response`.", - message: "Make sure your middleware returns a `Response` object, either directly or by returning the `Response` from calling the `next` function." -}; -const MiddlewareNotAResponse = { - name: "MiddlewareNotAResponse", - title: "The middleware returned something that is not a `Response` object.", - message: "Any data returned from middleware must be a valid `Response` object." -}; -const EndpointDidNotReturnAResponse = { - name: "EndpointDidNotReturnAResponse", - title: "The endpoint did not return a `Response`.", - message: "An endpoint must return either a `Response`, or a `Promise` that resolves with a `Response`." -}; -const LocalsNotAnObject = { - name: "LocalsNotAnObject", - title: "Value assigned to `locals` is not accepted.", - message: "`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.", - hint: "If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`." -}; -const LocalsReassigned = { - name: "LocalsReassigned", - title: "`locals` must not be reassigned.", - message: "`locals` can not be assigned directly.", - hint: "Set a `locals` property instead." -}; -const AstroResponseHeadersReassigned = { - name: "AstroResponseHeadersReassigned", - title: "`Astro.response.headers` must not be reassigned.", - message: "Individual headers can be added to and removed from `Astro.response.headers`, but it must not be replaced with another instance of `Headers` altogether.", - hint: "Consider using `Astro.response.headers.add()`, and `Astro.response.headers.delete()`." -}; -const LocalImageUsedWrongly = { - name: "LocalImageUsedWrongly", - title: "Local images must be imported.", - message: (imageFilePath) => `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a string filepath. Received \`${imageFilePath}\`.`, - hint: "If you want to use an image from your `src` folder, you need to either import it or if the image is coming from a content collection, use the [image() schema helper](https://docs.astro.build/en/guides/images/#images-in-content-collections). See https://docs.astro.build/en/guides/images/#src-required for more information on the `src` property." -}; -const AstroGlobUsedOutside = { - name: "AstroGlobUsedOutside", - title: "Astro.glob() used outside of an Astro file.", - message: (globStr) => `\`Astro.glob(${globStr})\` can only be used in \`.astro\` files. \`import.meta.glob(${globStr})\` can be used instead to achieve a similar result.`, - hint: "See Vite's documentation on `import.meta.glob` for more information: https://vite.dev/guide/features.html#glob-import" -}; -const AstroGlobNoMatch = { - name: "AstroGlobNoMatch", - title: "Astro.glob() did not match any files.", - message: (globStr) => `\`Astro.glob(${globStr})\` did not return any matching files.`, - hint: "Check the pattern for typos." -}; -const MissingSharp = { - name: "MissingSharp", - title: "Could not find Sharp.", - message: "Could not find Sharp. Please install Sharp (`sharp`) manually into your project or migrate to another image service.", - hint: "See Sharp's installation instructions for more information: https://sharp.pixelplumbing.com/install. If you are not relying on `astro:assets` to optimize, transform, or process any images, you can configure a passthrough image service instead of installing Sharp. See https://docs.astro.build/en/reference/errors/missing-sharp for more information.\n\nSee https://docs.astro.build/en/guides/images/#default-image-service for more information on how to migrate to another image service." -}; -const FailedToFindPageMapSSR = { - name: "FailedToFindPageMapSSR", - title: "Astro couldn't find the correct page to render", - message: "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error. Please file an issue." -}; -const i18nNoLocaleFoundInPath = { - name: "i18nNoLocaleFoundInPath", - title: "The path doesn't contain any locale", - message: "You tried to use an i18n utility on a path that doesn't contain any locale. You can use `pathHasLocale` first to determine if the path has a locale." -}; -const RewriteWithBodyUsed = { - name: "RewriteWithBodyUsed", - title: "Cannot use Astro.rewrite after the request body has been read", - message: "Astro.rewrite() cannot be used if the request body has already been read. If you need to read the body, first clone the request." -}; -const ForbiddenRewrite = { - name: "ForbiddenRewrite", - title: "Forbidden rewrite to a static route.", - message: (from, to, component) => `You tried to rewrite the on-demand route '${from}' with the static route '${to}', when using the 'server' output. - -The static route '${to}' is rendered by the component -'${component}', which is marked as prerendered. This is a forbidden operation because during the build the component '${component}' is compiled to an -HTML file, which can't be retrieved at runtime by Astro.`, - hint: (component) => `Add \`export const prerender = false\` to the component '${component}', or use a Astro.redirect().` -}; -const ExperimentalFontsNotEnabled = { - name: "ExperimentalFontsNotEnabled", - title: "Experimental fonts are not enabled", - message: "The Font component is used but experimental fonts have not been registered in the config.", - hint: "Check that you have enabled experimental fonts and also configured your preferred fonts." -}; -const FontFamilyNotFound = { - name: "FontFamilyNotFound", - title: "Font family not found", - message: (family) => `No data was found for the \`"${family}"\` family passed to the \`\` component.`, - hint: "This is often caused by a typo. Check that the `` component is using a `cssVariable` specified in your config." -}; -const CspNotEnabled = { - name: "CspNotEnabled", - title: "CSP feature isn't enabled", - message: "The `experimental.csp` configuration isn't enabled." -}; -const UnknownContentCollectionError = { - name: "UnknownContentCollectionError", - title: "Unknown Content Collection Error." -}; -const RenderUndefinedEntryError = { - name: "RenderUndefinedEntryError", - title: "Attempted to render an undefined content collection entry.", - hint: "Check if the entry is undefined before passing it to `render()`" -}; -const ActionsReturnedInvalidDataError = { - name: "ActionsReturnedInvalidDataError", - title: "Action handler returned invalid data.", - message: (error) => `Action handler returned invalid data. Handlers should return serializable data types like objects, arrays, strings, and numbers. Parse error: ${error}`, - hint: "See the devalue library for all supported types: https://github.com/rich-harris/devalue" -}; -const ActionNotFoundError = { - name: "ActionNotFoundError", - title: "Action not found.", - message: (actionName) => `The server received a request for an action named \`${actionName}\` but could not find a match. If you renamed an action, check that you've updated your \`actions/index\` file and your calling code to match.`, - hint: "You can run `astro check` to detect type errors caused by mismatched action names." -}; -const SessionStorageInitError = { - name: "SessionStorageInitError", - title: "Session storage could not be initialized.", - message: (error, driver) => `Error when initializing session storage${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``, - hint: "For more information, see https://docs.astro.build/en/guides/sessions/" -}; -const SessionStorageSaveError = { - name: "SessionStorageSaveError", - title: "Session data could not be saved.", - message: (error, driver) => `Error when saving session data${driver ? ` with driver \`${driver}\`` : ""}. \`${error ?? ""}\``, - hint: "For more information, see https://docs.astro.build/en/guides/sessions/" -}; - -function validateArgs(args) { - if (args.length !== 3) return false; - if (!args[0] || typeof args[0] !== "object") return false; - return true; -} -function baseCreateComponent(cb, moduleId, propagation) { - const name = moduleId?.split("/").pop()?.replace(".astro", "") ?? ""; - const fn = (...args) => { - if (!validateArgs(args)) { - throw new AstroError({ - ...InvalidComponentArgs, - message: InvalidComponentArgs.message(name) - }); - } - return cb(...args); - }; - Object.defineProperty(fn, "name", { value: name, writable: false }); - fn.isAstroComponentFactory = true; - fn.moduleId = moduleId; - fn.propagation = propagation; - return fn; -} -function createComponentWithOptions(opts) { - const cb = baseCreateComponent(opts.factory, opts.moduleId, opts.propagation); - return cb; -} -function createComponent(arg1, moduleId, propagation) { - if (typeof arg1 === "function") { - return baseCreateComponent(arg1, moduleId, propagation); - } else { - return createComponentWithOptions(arg1); - } -} - -function createAstroGlobFn() { - const globHandler = (importMetaGlobResult) => { - console.warn(`Astro.glob is deprecated and will be removed in a future major version of Astro. -Use import.meta.glob instead: https://vitejs.dev/guide/features.html#glob-import`); - if (typeof importMetaGlobResult === "string") { - throw new AstroError({ - ...AstroGlobUsedOutside, - message: AstroGlobUsedOutside.message(JSON.stringify(importMetaGlobResult)) - }); - } - let allEntries = [...Object.values(importMetaGlobResult)]; - if (allEntries.length === 0) { - throw new AstroError({ - ...AstroGlobNoMatch, - message: AstroGlobNoMatch.message(JSON.stringify(importMetaGlobResult)) - }); - } - return Promise.all(allEntries.map((fn) => fn())); - }; - return globHandler; -} -function createAstro(site) { - return { - site: new URL(site) , - generator: `Astro v${ASTRO_VERSION}`, - glob: createAstroGlobFn() - }; -} - -async function renderEndpoint(mod, context, isPrerendered, logger) { - const { request, url } = context; - const method = request.method.toUpperCase(); - let handler = mod[method] ?? mod["ALL"]; - if (!handler && method === "HEAD" && mod["GET"]) { - handler = mod["GET"]; - } - if (isPrerendered && !["GET", "HEAD"].includes(method)) { - logger.warn( - "router", - `${url.pathname} ${colors.bold( - method - )} requests are not available in static endpoints. Mark this page as server-rendered (\`export const prerender = false;\`) or update your config to \`output: 'server'\` to make all your pages server-rendered by default.` - ); - } - if (handler === void 0) { - logger.warn( - "router", - `No API Route handler exists for the method "${method}" for the route "${url.pathname}". -Found handlers: ${Object.keys(mod).map((exp) => JSON.stringify(exp)).join(", ")} -` + ("all" in mod ? `One of the exported handlers is "all" (lowercase), did you mean to export 'ALL'? -` : "") - ); - return new Response(null, { status: 404 }); - } - if (typeof handler !== "function") { - logger.error( - "router", - `The route "${url.pathname}" exports a value for the method "${method}", but it is of the type ${typeof handler} instead of a function.` - ); - return new Response(null, { status: 500 }); - } - let response = await handler.call(mod, context); - if (!response || response instanceof Response === false) { - throw new AstroError(EndpointDidNotReturnAResponse); - } - if (REROUTABLE_STATUS_CODES.includes(response.status)) { - try { - response.headers.set(REROUTE_DIRECTIVE_HEADER, "no"); - } catch (err) { - if (err.message?.includes("immutable")) { - response = new Response(response.body, response); - response.headers.set(REROUTE_DIRECTIVE_HEADER, "no"); - } else { - throw err; - } - } - } - if (method === "HEAD") { - return new Response(null, response); - } - return response; -} - -function isPromise(value) { - return !!value && typeof value === "object" && "then" in value && typeof value.then === "function"; -} -async function* streamAsyncIterator(stream) { - const reader = stream.getReader(); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) return; - yield value; - } - } finally { - reader.releaseLock(); - } -} - -const escapeHTML = escape; -class HTMLBytes extends Uint8Array { -} -Object.defineProperty(HTMLBytes.prototype, Symbol.toStringTag, { - get() { - return "HTMLBytes"; - } -}); -class HTMLString extends String { - get [Symbol.toStringTag]() { - return "HTMLString"; - } -} -const markHTMLString = (value) => { - if (value instanceof HTMLString) { - return value; - } - if (typeof value === "string") { - return new HTMLString(value); - } - return value; -}; -function isHTMLString(value) { - return Object.prototype.toString.call(value) === "[object HTMLString]"; -} -function markHTMLBytes(bytes) { - return new HTMLBytes(bytes); -} -function hasGetReader(obj) { - return typeof obj.getReader === "function"; -} -async function* unescapeChunksAsync(iterable) { - if (hasGetReader(iterable)) { - for await (const chunk of streamAsyncIterator(iterable)) { - yield unescapeHTML(chunk); - } - } else { - for await (const chunk of iterable) { - yield unescapeHTML(chunk); - } - } -} -function* unescapeChunks(iterable) { - for (const chunk of iterable) { - yield unescapeHTML(chunk); - } -} -function unescapeHTML(str) { - if (!!str && typeof str === "object") { - if (str instanceof Uint8Array) { - return markHTMLBytes(str); - } else if (str instanceof Response && str.body) { - const body = str.body; - return unescapeChunksAsync(body); - } else if (typeof str.then === "function") { - return Promise.resolve(str).then((value) => { - return unescapeHTML(value); - }); - } else if (str[Symbol.for("astro:slot-string")]) { - return str; - } else if (Symbol.iterator in str) { - return unescapeChunks(str); - } else if (Symbol.asyncIterator in str || hasGetReader(str)) { - return unescapeChunksAsync(str); - } - } - return markHTMLString(str); -} - -const AstroJSX = "astro:jsx"; -function isVNode(vnode) { - return vnode && typeof vnode === "object" && vnode[AstroJSX]; -} - -function isAstroComponentFactory(obj) { - return obj == null ? false : obj.isAstroComponentFactory === true; -} -function isAPropagatingComponent(result, factory) { - const hint = getPropagationHint(result, factory); - return hint === "in-tree" || hint === "self"; -} -function getPropagationHint(result, factory) { - let hint = factory.propagation || "none"; - if (factory.moduleId && result.componentMetadata.has(factory.moduleId) && hint === "none") { - hint = result.componentMetadata.get(factory.moduleId).propagation; - } - return hint; -} - -const PROP_TYPE = { - Value: 0, - JSON: 1, - // Actually means Array - RegExp: 2, - Date: 3, - Map: 4, - Set: 5, - BigInt: 6, - URL: 7, - Uint8Array: 8, - Uint16Array: 9, - Uint32Array: 10, - Infinity: 11 -}; -function serializeArray(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) { - if (parents.has(value)) { - throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>! - -Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`); - } - parents.add(value); - const serialized = value.map((v) => { - return convertToSerializedForm(v, metadata, parents); - }); - parents.delete(value); - return serialized; -} -function serializeObject(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) { - if (parents.has(value)) { - throw new Error(`Cyclic reference detected while serializing props for <${metadata.displayName} client:${metadata.hydrate}>! - -Cyclic references cannot be safely serialized for client-side usage. Please remove the cyclic reference.`); - } - parents.add(value); - const serialized = Object.fromEntries( - Object.entries(value).map(([k, v]) => { - return [k, convertToSerializedForm(v, metadata, parents)]; - }) - ); - parents.delete(value); - return serialized; -} -function convertToSerializedForm(value, metadata = {}, parents = /* @__PURE__ */ new WeakSet()) { - const tag = Object.prototype.toString.call(value); - switch (tag) { - case "[object Date]": { - return [PROP_TYPE.Date, value.toISOString()]; - } - case "[object RegExp]": { - return [PROP_TYPE.RegExp, value.source]; - } - case "[object Map]": { - return [PROP_TYPE.Map, serializeArray(Array.from(value), metadata, parents)]; - } - case "[object Set]": { - return [PROP_TYPE.Set, serializeArray(Array.from(value), metadata, parents)]; - } - case "[object BigInt]": { - return [PROP_TYPE.BigInt, value.toString()]; - } - case "[object URL]": { - return [PROP_TYPE.URL, value.toString()]; - } - case "[object Array]": { - return [PROP_TYPE.JSON, serializeArray(value, metadata, parents)]; - } - case "[object Uint8Array]": { - return [PROP_TYPE.Uint8Array, Array.from(value)]; - } - case "[object Uint16Array]": { - return [PROP_TYPE.Uint16Array, Array.from(value)]; - } - case "[object Uint32Array]": { - return [PROP_TYPE.Uint32Array, Array.from(value)]; - } - default: { - if (value !== null && typeof value === "object") { - return [PROP_TYPE.Value, serializeObject(value, metadata, parents)]; - } - if (value === Infinity) { - return [PROP_TYPE.Infinity, 1]; - } - if (value === -Infinity) { - return [PROP_TYPE.Infinity, -1]; - } - if (value === void 0) { - return [PROP_TYPE.Value]; - } - return [PROP_TYPE.Value, value]; - } - } -} -function serializeProps(props, metadata) { - const serialized = JSON.stringify(serializeObject(props, metadata)); - return serialized; -} - -const transitionDirectivesToCopyOnIsland = Object.freeze([ - "data-astro-transition-scope", - "data-astro-transition-persist", - "data-astro-transition-persist-props" -]); -function extractDirectives(inputProps, clientDirectives) { - let extracted = { - isPage: false, - hydration: null, - props: {}, - propsWithoutTransitionAttributes: {} - }; - for (const [key, value] of Object.entries(inputProps)) { - if (key.startsWith("server:")) { - if (key === "server:root") { - extracted.isPage = true; - } - } - if (key.startsWith("client:")) { - if (!extracted.hydration) { - extracted.hydration = { - directive: "", - value: "", - componentUrl: "", - componentExport: { value: "" } - }; - } - switch (key) { - case "client:component-path": { - extracted.hydration.componentUrl = value; - break; - } - case "client:component-export": { - extracted.hydration.componentExport.value = value; - break; - } - // This is a special prop added to prove that the client hydration method - // was added statically. - case "client:component-hydration": { - break; - } - case "client:display-name": { - break; - } - default: { - extracted.hydration.directive = key.split(":")[1]; - extracted.hydration.value = value; - if (!clientDirectives.has(extracted.hydration.directive)) { - const hydrationMethods = Array.from(clientDirectives.keys()).map((d) => `client:${d}`).join(", "); - throw new Error( - `Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}` - ); - } - if (extracted.hydration.directive === "media" && typeof extracted.hydration.value !== "string") { - throw new AstroError(MissingMediaQueryDirective); - } - break; - } - } - } else { - extracted.props[key] = value; - if (!transitionDirectivesToCopyOnIsland.includes(key)) { - extracted.propsWithoutTransitionAttributes[key] = value; - } - } - } - for (const sym of Object.getOwnPropertySymbols(inputProps)) { - extracted.props[sym] = inputProps[sym]; - extracted.propsWithoutTransitionAttributes[sym] = inputProps[sym]; - } - return extracted; -} -async function generateHydrateScript(scriptOptions, metadata) { - const { renderer, result, astroId, props, attrs } = scriptOptions; - const { hydrate, componentUrl, componentExport } = metadata; - if (!componentExport.value) { - throw new AstroError({ - ...NoMatchingImport, - message: NoMatchingImport.message(metadata.displayName) - }); - } - const island = { - children: "", - props: { - // This is for HMR, probably can avoid it in prod - uid: astroId - } - }; - if (attrs) { - for (const [key, value] of Object.entries(attrs)) { - island.props[key] = escapeHTML(value); - } - } - island.props["component-url"] = await result.resolve(decodeURI(componentUrl)); - if (renderer.clientEntrypoint) { - island.props["component-export"] = componentExport.value; - island.props["renderer-url"] = await result.resolve( - decodeURI(renderer.clientEntrypoint.toString()) - ); - island.props["props"] = escapeHTML(serializeProps(props, metadata)); - } - island.props["ssr"] = ""; - island.props["client"] = hydrate; - let beforeHydrationUrl = await result.resolve("astro:scripts/before-hydration.js"); - if (beforeHydrationUrl.length) { - island.props["before-hydration-url"] = beforeHydrationUrl; - } - island.props["opts"] = escapeHTML( - JSON.stringify({ - name: metadata.displayName, - value: metadata.hydrateArgs || "" - }) - ); - transitionDirectivesToCopyOnIsland.forEach((name) => { - if (typeof props[name] !== "undefined") { - island.props[name] = props[name]; - } - }); - return island; -} - -/** - * shortdash - https://github.com/bibig/node-shorthash - * - * @license - * - * (The MIT License) - * - * Copyright (c) 2013 Bibig - * - * Permission is hereby granted, free of charge, to any person - * obtaining a copy of this software and associated documentation - * files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, - * copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following - * conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES - * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT - * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR - * OTHER DEALINGS IN THE SOFTWARE. - */ -const dictionary = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY"; -const binary = dictionary.length; -function bitwise(str) { - let hash = 0; - if (str.length === 0) return hash; - for (let i = 0; i < str.length; i++) { - const ch = str.charCodeAt(i); - hash = (hash << 5) - hash + ch; - hash = hash & hash; - } - return hash; -} -function shorthash(text) { - let num; - let result = ""; - let integer = bitwise(text); - const sign = integer < 0 ? "Z" : ""; - integer = Math.abs(integer); - while (integer >= binary) { - num = integer % binary; - integer = Math.floor(integer / binary); - result = dictionary[num] + result; - } - if (integer > 0) { - result = dictionary[integer] + result; - } - return sign + result; -} - -const headAndContentSym = Symbol.for("astro.headAndContent"); -function isHeadAndContent(obj) { - return typeof obj === "object" && obj !== null && !!obj[headAndContentSym]; -} -function createHeadAndContent(head, content) { - return { - [headAndContentSym]: true, - head, - content - }; -} -function createThinHead() { - return { - [headAndContentSym]: true - }; -} - -var astro_island_prebuilt_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var d=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>m(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[l,e]=t;return l in i?i[l](e):void 0},a=t=>t.map(o),m=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([l,e])=>[l,o(e)]));class y extends HTMLElement{constructor(){super(...arguments);d(this,"Component");d(this,"hydrator");d(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},h=this.querySelectorAll("template[data-astro-template]");for(let r of h){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let p;try{p=this.hasAttribute("props")?m(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let u;await this.hydrator(this)(this.Component,p,n,{client:this.getAttribute("client")}),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});d(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[h,{default:p}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),u=this.getAttribute("component-export")||"default";if(!u.includes("."))this.Component=h[u];else{this.Component=h;for(let f of u.split("."))this.Component=this.Component[f]}return this.hydrator=p,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}d(y,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",y)}})();`; - -var astro_island_prebuilt_dev_default = `(()=>{var A=Object.defineProperty;var g=(i,o,a)=>o in i?A(i,o,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[o]=a;var l=(i,o,a)=>g(i,typeof o!="symbol"?o+"":o,a);{let i={0:t=>y(t),1:t=>a(t),2:t=>new RegExp(t),3:t=>new Date(t),4:t=>new Map(a(t)),5:t=>new Set(a(t)),6:t=>BigInt(t),7:t=>new URL(t),8:t=>new Uint8Array(t),9:t=>new Uint16Array(t),10:t=>new Uint32Array(t),11:t=>1/0*t},o=t=>{let[h,e]=t;return h in i?i[h](e):void 0},a=t=>t.map(o),y=t=>typeof t!="object"||t===null?t:Object.fromEntries(Object.entries(t).map(([h,e])=>[h,o(e)]));class f extends HTMLElement{constructor(){super(...arguments);l(this,"Component");l(this,"hydrator");l(this,"hydrate",async()=>{var b;if(!this.hydrator||!this.isConnected)return;let e=(b=this.parentElement)==null?void 0:b.closest("astro-island[ssr]");if(e){e.addEventListener("astro:hydrate",this.hydrate,{once:!0});return}let c=this.querySelectorAll("astro-slot"),n={},p=this.querySelectorAll("template[data-astro-template]");for(let r of p){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("data-astro-template")||"default"]=r.innerHTML,r.remove())}for(let r of c){let s=r.closest(this.tagName);s!=null&&s.isSameNode(this)&&(n[r.getAttribute("name")||"default"]=r.innerHTML)}let u;try{u=this.hasAttribute("props")?y(JSON.parse(this.getAttribute("props"))):{}}catch(r){let s=this.getAttribute("component-url")||"",v=this.getAttribute("component-export");throw v&&(s+=\` (export \${v})\`),console.error(\`[hydrate] Error parsing props for component \${s}\`,this.getAttribute("props"),r),r}let d,m=this.hydrator(this);d=performance.now(),await m(this.Component,u,n,{client:this.getAttribute("client")}),d&&this.setAttribute("client-render-time",(performance.now()-d).toString()),this.removeAttribute("ssr"),this.dispatchEvent(new CustomEvent("astro:hydrate"))});l(this,"unmount",()=>{this.isConnected||this.dispatchEvent(new CustomEvent("astro:unmount"))})}disconnectedCallback(){document.removeEventListener("astro:after-swap",this.unmount),document.addEventListener("astro:after-swap",this.unmount,{once:!0})}connectedCallback(){if(!this.hasAttribute("await-children")||document.readyState==="interactive"||document.readyState==="complete")this.childrenConnectedCallback();else{let e=()=>{document.removeEventListener("DOMContentLoaded",e),c.disconnect(),this.childrenConnectedCallback()},c=new MutationObserver(()=>{var n;((n=this.lastChild)==null?void 0:n.nodeType)===Node.COMMENT_NODE&&this.lastChild.nodeValue==="astro:end"&&(this.lastChild.remove(),e())});c.observe(this,{childList:!0}),document.addEventListener("DOMContentLoaded",e)}}async childrenConnectedCallback(){let e=this.getAttribute("before-hydration-url");e&&await import(e),this.start()}async start(){let e=JSON.parse(this.getAttribute("opts")),c=this.getAttribute("client");if(Astro[c]===void 0){window.addEventListener(\`astro:\${c}\`,()=>this.start(),{once:!0});return}try{await Astro[c](async()=>{let n=this.getAttribute("renderer-url"),[p,{default:u}]=await Promise.all([import(this.getAttribute("component-url")),n?import(n):()=>()=>{}]),d=this.getAttribute("component-export")||"default";if(!d.includes("."))this.Component=p[d];else{this.Component=p;for(let m of d.split("."))this.Component=this.Component[m]}return this.hydrator=u,this.hydrate},e,this)}catch(n){console.error(\`[astro-island] Error hydrating \${this.getAttribute("component-url")}\`,n)}}attributeChangedCallback(){this.hydrate()}}l(f,"observedAttributes",["props"]),customElements.get("astro-island")||customElements.define("astro-island",f)}})();`; - -const ISLAND_STYLES = "astro-island,astro-slot,astro-static-slot{display:contents}"; - -function determineIfNeedsHydrationScript(result) { - if (result._metadata.hasHydrationScript) { - return false; - } - return result._metadata.hasHydrationScript = true; -} -function determinesIfNeedsDirectiveScript(result, directive) { - if (result._metadata.hasDirectives.has(directive)) { - return false; - } - result._metadata.hasDirectives.add(directive); - return true; -} -function getDirectiveScriptText(result, directive) { - const clientDirectives = result.clientDirectives; - const clientDirective = clientDirectives.get(directive); - if (!clientDirective) { - throw new Error(`Unknown directive: ${directive}`); - } - return clientDirective; -} -function getPrescripts(result, type, directive) { - switch (type) { - case "both": - return ``; - case "directive": - return ``; - } -} - -function renderCspContent(result) { - const finalScriptHashes = /* @__PURE__ */ new Set(); - const finalStyleHashes = /* @__PURE__ */ new Set(); - for (const scriptHash of result.scriptHashes) { - finalScriptHashes.add(`'${scriptHash}'`); - } - for (const styleHash of result.styleHashes) { - finalStyleHashes.add(`'${styleHash}'`); - } - for (const styleHash of result._metadata.extraStyleHashes) { - finalStyleHashes.add(`'${styleHash}'`); - } - for (const scriptHash of result._metadata.extraScriptHashes) { - finalScriptHashes.add(`'${scriptHash}'`); - } - let directives; - if (result.directives.length > 0) { - directives = result.directives.join(";") + ";"; - } - let scriptResources = "'self'"; - if (result.scriptResources.length > 0) { - scriptResources = result.scriptResources.map((r) => `${r}`).join(" "); - } - let styleResources = "'self'"; - if (result.styleResources.length > 0) { - styleResources = result.styleResources.map((r) => `${r}`).join(" "); - } - const strictDynamic = result.isStrictDynamic ? ` 'strict-dynamic'` : ""; - const scriptSrc = `script-src ${scriptResources} ${Array.from(finalScriptHashes).join(" ")}${strictDynamic};`; - const styleSrc = `style-src ${styleResources} ${Array.from(finalStyleHashes).join(" ")};`; - return [directives, scriptSrc, styleSrc].filter(Boolean).join(" "); -} - -const RenderInstructionSymbol = Symbol.for("astro:render"); -function createRenderInstruction(instruction) { - return Object.defineProperty(instruction, RenderInstructionSymbol, { - value: true - }); -} -function isRenderInstruction(chunk) { - return chunk && typeof chunk === "object" && chunk[RenderInstructionSymbol]; -} - -const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i; -const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|inert|loop|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|selected|itemscope)$/i; -const AMPERSAND_REGEX = /&/g; -const DOUBLE_QUOTE_REGEX = /"/g; -const STATIC_DIRECTIVES = /* @__PURE__ */ new Set(["set:html", "set:text"]); -const toIdent = (k) => k.trim().replace(/(?!^)\b\w|\s+|\W+/g, (match, index) => { - if (/\W/.test(match)) return ""; - return index === 0 ? match : match.toUpperCase(); -}); -const toAttributeString = (value, shouldEscape = true) => shouldEscape ? String(value).replace(AMPERSAND_REGEX, "&").replace(DOUBLE_QUOTE_REGEX, """) : value; -const kebab = (k) => k.toLowerCase() === k ? k : k.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`); -const toStyleString = (obj) => Object.entries(obj).filter(([_, v]) => typeof v === "string" && v.trim() || typeof v === "number").map(([k, v]) => { - if (k[0] !== "-" && k[1] !== "-") return `${kebab(k)}:${v}`; - return `${k}:${v}`; -}).join(";"); -function defineScriptVars(vars) { - let output = ""; - for (const [key, value] of Object.entries(vars)) { - output += `const ${toIdent(key)} = ${JSON.stringify(value)?.replace( - /<\/script>/g, - "\\x3C/script>" - )}; -`; - } - return markHTMLString(output); -} -function formatList(values) { - if (values.length === 1) { - return values[0]; - } - return `${values.slice(0, -1).join(", ")} or ${values[values.length - 1]}`; -} -function isCustomElement(tagName) { - return tagName.includes("-"); -} -function handleBooleanAttribute(key, value, shouldEscape, tagName) { - if (tagName && isCustomElement(tagName)) { - return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`); - } - return markHTMLString(value ? ` ${key}` : ""); -} -function addAttribute(value, key, shouldEscape = true, tagName = "") { - if (value == null) { - return ""; - } - if (STATIC_DIRECTIVES.has(key)) { - console.warn(`[astro] The "${key}" directive cannot be applied dynamically at runtime. It will not be rendered as an attribute. - -Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the dynamic spread syntax (\`{...{ "${key}": value }}\`).`); - return ""; - } - if (key === "class:list") { - const listValue = toAttributeString(clsx(value), shouldEscape); - if (listValue === "") { - return ""; - } - return markHTMLString(` ${key.slice(0, -5)}="${listValue}"`); - } - if (key === "style" && !(value instanceof HTMLString)) { - if (Array.isArray(value) && value.length === 2) { - return markHTMLString( - ` ${key}="${toAttributeString(`${toStyleString(value[0])};${value[1]}`, shouldEscape)}"` - ); - } - if (typeof value === "object") { - return markHTMLString(` ${key}="${toAttributeString(toStyleString(value), shouldEscape)}"`); - } - } - if (key === "className") { - return markHTMLString(` class="${toAttributeString(value, shouldEscape)}"`); - } - if (typeof value === "string" && value.includes("&") && isHttpUrl(value)) { - return markHTMLString(` ${key}="${toAttributeString(value, false)}"`); - } - if (htmlBooleanAttributes.test(key)) { - return handleBooleanAttribute(key, value, shouldEscape, tagName); - } - if (value === "") { - return markHTMLString(` ${key}`); - } - if (key === "popover" && typeof value === "boolean") { - return handleBooleanAttribute(key, value, shouldEscape, tagName); - } - if (key === "download" && typeof value === "boolean") { - return handleBooleanAttribute(key, value, shouldEscape, tagName); - } - return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`); -} -function internalSpreadAttributes(values, shouldEscape = true, tagName) { - let output = ""; - for (const [key, value] of Object.entries(values)) { - output += addAttribute(value, key, shouldEscape, tagName); - } - return markHTMLString(output); -} -function renderElement$1(name, { props: _props, children = "" }, shouldEscape = true) { - const { lang: _, "data-astro-id": astroId, "define:vars": defineVars, ...props } = _props; - if (defineVars) { - if (name === "style") { - delete props["is:global"]; - delete props["is:scoped"]; - } - if (name === "script") { - delete props.hoist; - children = defineScriptVars(defineVars) + "\n" + children; - } - } - if ((children == null || children == "") && voidElementNames.test(name)) { - return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>`; - } - return `<${name}${internalSpreadAttributes(props, shouldEscape, name)}>${children}`; -} -const noop = () => { -}; -class BufferedRenderer { - chunks = []; - renderPromise; - destination; - /** - * Determines whether buffer has been flushed - * to the final destination. - */ - flushed = false; - constructor(destination, renderFunction) { - this.destination = destination; - this.renderPromise = renderFunction(this); - if (isPromise(this.renderPromise)) { - Promise.resolve(this.renderPromise).catch(noop); - } - } - write(chunk) { - if (this.flushed) { - this.destination.write(chunk); - } else { - this.chunks.push(chunk); - } - } - flush() { - if (this.flushed) { - throw new Error("The render buffer has already been flushed."); - } - this.flushed = true; - for (const chunk of this.chunks) { - this.destination.write(chunk); - } - return this.renderPromise; - } -} -function createBufferedRenderer(destination, renderFunction) { - return new BufferedRenderer(destination, renderFunction); -} -const isNode = typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]"; -const isDeno = typeof Deno !== "undefined"; -function promiseWithResolvers() { - let resolve, reject; - const promise = new Promise((_resolve, _reject) => { - resolve = _resolve; - reject = _reject; - }); - return { - promise, - resolve, - reject - }; -} -const VALID_PROTOCOLS = ["http:", "https:"]; -function isHttpUrl(url) { - try { - const parsedUrl = new URL(url); - return VALID_PROTOCOLS.includes(parsedUrl.protocol); - } catch { - return false; - } -} - -const uniqueElements = (item, index, all) => { - const props = JSON.stringify(item.props); - const children = item.children; - return index === all.findIndex((i) => JSON.stringify(i.props) === props && i.children == children); -}; -function renderAllHeadContent(result) { - result._metadata.hasRenderedHead = true; - let content = ""; - if (result.shouldInjectCspMetaTags && result.cspDestination === "meta") { - content += renderElement$1( - "meta", - { - props: { - "http-equiv": "content-security-policy", - content: renderCspContent(result) - }, - children: "" - }, - false - ); - } - const styles = Array.from(result.styles).filter(uniqueElements).map( - (style) => style.props.rel === "stylesheet" ? renderElement$1("link", style) : renderElement$1("style", style) - ); - result.styles.clear(); - const scripts = Array.from(result.scripts).filter(uniqueElements).map((script) => { - if (result.userAssetsBase) { - script.props.src = (result.base === "/" ? "" : result.base) + result.userAssetsBase + script.props.src; - } - return renderElement$1("script", script, false); - }); - const links = Array.from(result.links).filter(uniqueElements).map((link) => renderElement$1("link", link, false)); - content += styles.join("\n") + links.join("\n") + scripts.join("\n"); - if (result._metadata.extraHead.length > 0) { - for (const part of result._metadata.extraHead) { - content += part; - } - } - return markHTMLString(content); -} -function renderHead() { - return createRenderInstruction({ type: "head" }); -} -function maybeRenderHead() { - return createRenderInstruction({ type: "maybe-head" }); -} - -const ALGORITHMS = { - "SHA-256": "sha256-", - "SHA-384": "sha384-", - "SHA-512": "sha512-" -}; -const ALGORITHM_VALUES = Object.values(ALGORITHMS); -z.enum(Object.keys(ALGORITHMS)).optional().default("SHA-256"); -z.custom((value) => { - if (typeof value !== "string") { - return false; - } - return ALGORITHM_VALUES.some((allowedValue) => { - return value.startsWith(allowedValue); - }); -}); -const ALLOWED_DIRECTIVES = [ - "base-uri", - "child-src", - "connect-src", - "default-src", - "fenced-frame-src", - "font-src", - "form-action", - "frame-ancestors", - "frame-src", - "img-src", - "manifest-src", - "media-src", - "object-src", - "referrer", - "report-to", - "report-uri", - "require-trusted-types-for", - "sandbox", - "trusted-types", - "upgrade-insecure-requests", - "worker-src" -]; -z.custom((value) => { - if (typeof value !== "string") { - return false; - } - return ALLOWED_DIRECTIVES.some((allowedValue) => { - return value.startsWith(allowedValue); - }); -}); - -const ALGORITHM = "AES-GCM"; -async function decodeKey(encoded) { - const bytes = decodeBase64(encoded); - return crypto.subtle.importKey("raw", bytes.buffer, ALGORITHM, true, [ - "encrypt", - "decrypt" - ]); -} -const encoder$1 = new TextEncoder(); -const decoder$1 = new TextDecoder(); -const IV_LENGTH = 24; -async function encryptString(key, raw) { - const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH / 2)); - const data = encoder$1.encode(raw); - const buffer = await crypto.subtle.encrypt( - { - name: ALGORITHM, - iv - }, - key, - data - ); - return encodeHexUpperCase(iv) + encodeBase64(new Uint8Array(buffer)); -} -async function decryptString(key, encoded) { - const iv = decodeHex(encoded.slice(0, IV_LENGTH)); - const dataArray = decodeBase64(encoded.slice(IV_LENGTH)); - const decryptedBuffer = await crypto.subtle.decrypt( - { - name: ALGORITHM, - iv - }, - key, - dataArray - ); - const decryptedString = decoder$1.decode(decryptedBuffer); - return decryptedString; -} -async function generateCspDigest(data, algorithm) { - const hashBuffer = await crypto.subtle.digest(algorithm, encoder$1.encode(data)); - const hash = encodeBase64(new Uint8Array(hashBuffer)); - return `${ALGORITHMS[algorithm]}${hash}`; -} - -const renderTemplateResultSym = Symbol.for("astro.renderTemplateResult"); -class RenderTemplateResult { - [renderTemplateResultSym] = true; - htmlParts; - expressions; - error; - constructor(htmlParts, expressions) { - this.htmlParts = htmlParts; - this.error = void 0; - this.expressions = expressions.map((expression) => { - if (isPromise(expression)) { - return Promise.resolve(expression).catch((err) => { - if (!this.error) { - this.error = err; - throw err; - } - }); - } - return expression; - }); - } - render(destination) { - const flushers = this.expressions.map((exp) => { - return createBufferedRenderer(destination, (bufferDestination) => { - if (exp || exp === 0) { - return renderChild(bufferDestination, exp); - } - }); - }); - let i = 0; - const iterate = () => { - while (i < this.htmlParts.length) { - const html = this.htmlParts[i]; - const flusher = flushers[i]; - i++; - if (html) { - destination.write(markHTMLString(html)); - } - if (flusher) { - const result = flusher.flush(); - if (isPromise(result)) { - return result.then(iterate); - } - } - } - }; - return iterate(); - } -} -function isRenderTemplateResult(obj) { - return typeof obj === "object" && obj !== null && !!obj[renderTemplateResultSym]; -} -function renderTemplate(htmlParts, ...expressions) { - return new RenderTemplateResult(htmlParts, expressions); -} - -const slotString = Symbol.for("astro:slot-string"); -class SlotString extends HTMLString { - instructions; - [slotString]; - constructor(content, instructions) { - super(content); - this.instructions = instructions; - this[slotString] = true; - } -} -function isSlotString(str) { - return !!str[slotString]; -} -function mergeSlotInstructions(target, source) { - if (source.instructions?.length) { - target ??= []; - target.push(...source.instructions); - } - return target; -} -function renderSlot(result, slotted, fallback) { - if (!slotted && fallback) { - return renderSlot(result, fallback); - } - return { - async render(destination) { - await renderChild(destination, typeof slotted === "function" ? slotted(result) : slotted); - } - }; -} -async function renderSlotToString(result, slotted, fallback) { - let content = ""; - let instructions = null; - const temporaryDestination = { - write(chunk) { - if (chunk instanceof SlotString) { - content += chunk; - instructions = mergeSlotInstructions(instructions, chunk); - } else if (chunk instanceof Response) return; - else if (typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string") { - if (instructions === null) { - instructions = []; - } - instructions.push(chunk); - } else { - content += chunkToString(result, chunk); - } - } - }; - const renderInstance = renderSlot(result, slotted, fallback); - await renderInstance.render(temporaryDestination); - return markHTMLString(new SlotString(content, instructions)); -} -async function renderSlots(result, slots = {}) { - let slotInstructions = null; - let children = {}; - if (slots) { - await Promise.all( - Object.entries(slots).map( - ([key, value]) => renderSlotToString(result, value).then((output) => { - if (output.instructions) { - if (slotInstructions === null) { - slotInstructions = []; - } - slotInstructions.push(...output.instructions); - } - children[key] = output; - }) - ) - ); - } - return { slotInstructions, children }; -} -function createSlotValueFromString(content) { - return function() { - return renderTemplate`${unescapeHTML(content)}`; - }; -} - -const internalProps = /* @__PURE__ */ new Set([ - "server:component-path", - "server:component-export", - "server:component-directive", - "server:defer" -]); -function containsServerDirective(props) { - return "server:component-directive" in props; -} -const SCRIPT_RE = /<\/script/giu; -const COMMENT_RE = /"); - for (const name in this.slots) { - if (name === "fallback") { - await renderChild(destination, this.slots.fallback(this.result)); - } - } - destination.write( - `` - ); - } - getComponentPath() { - if (this.componentPath) { - return this.componentPath; - } - const componentPath = this.props["server:component-path"]; - if (!componentPath) { - throw new Error(`Could not find server component path`); - } - this.componentPath = componentPath; - return componentPath; - } - getComponentExport() { - if (this.componentExport) { - return this.componentExport; - } - const componentExport = this.props["server:component-export"]; - if (!componentExport) { - throw new Error(`Could not find server component export`); - } - this.componentExport = componentExport; - return componentExport; - } - async getHostId() { - if (!this.hostId) { - this.hostId = await crypto.randomUUID(); - } - return this.hostId; - } - async getIslandContent() { - if (this.islandContent) { - return this.islandContent; - } - const componentPath = this.getComponentPath(); - const componentExport = this.getComponentExport(); - const componentId = this.result.serverIslandNameMap.get(componentPath); - if (!componentId) { - throw new Error(`Could not find server component name`); - } - for (const key2 of Object.keys(this.props)) { - if (internalProps.has(key2)) { - delete this.props[key2]; - } - } - const renderedSlots = {}; - for (const name in this.slots) { - if (name !== "fallback") { - const content = await renderSlotToString(this.result, this.slots[name]); - renderedSlots[name] = content.toString(); - } - } - const key = await this.result.key; - const componentExportEncrypted = await encryptString(key, componentExport); - const propsEncrypted = Object.keys(this.props).length === 0 ? "" : await encryptString(key, JSON.stringify(this.props)); - const slotsEncrypted = Object.keys(renderedSlots).length === 0 ? "" : await encryptString(key, JSON.stringify(renderedSlots)); - const hostId = await this.getHostId(); - const slash = this.result.base.endsWith("/") ? "" : "/"; - let serverIslandUrl = `${this.result.base}${slash}_server-islands/${componentId}${this.result.trailingSlash === "always" ? "/" : ""}`; - const potentialSearchParams = createSearchParams( - componentExportEncrypted, - propsEncrypted, - slotsEncrypted - ); - const useGETRequest = isWithinURLLimit(serverIslandUrl, potentialSearchParams); - if (useGETRequest) { - serverIslandUrl += "?" + potentialSearchParams.toString(); - this.result._metadata.extraHead.push( - markHTMLString( - `` - ) - ); - } - const adapterHeaders = this.result.internalFetchHeaders || {}; - const headersJson = safeJsonStringify(adapterHeaders); - const method = useGETRequest ? ( - // GET request - `const headers = new Headers(${headersJson}); -let response = await fetch('${serverIslandUrl}', { headers });` - ) : ( - // POST request - `let data = { - encryptedComponentExport: ${safeJsonStringify(componentExportEncrypted)}, - encryptedProps: ${safeJsonStringify(propsEncrypted)}, - encryptedSlots: ${safeJsonStringify(slotsEncrypted)}, -}; -const headers = new Headers({ 'Content-Type': 'application/json', ...${headersJson} }); -let response = await fetch('${serverIslandUrl}', { - method: 'POST', - body: JSON.stringify(data), - headers, -});` - ); - this.islandContent = `${method}replaceServerIsland('${hostId}', response);`; - return this.islandContent; - } -} -const renderServerIslandRuntime = () => { - return ``; -}; -const SERVER_ISLAND_REPLACER = markHTMLString( - `async function replaceServerIsland(id, r) { - let s = document.querySelector(\`script[data-island-id="\${id}"]\`); - // If there's no matching script, or the request fails then return - if (!s || r.status !== 200 || r.headers.get('content-type')?.split(';')[0].trim() !== 'text/html') return; - // Load the HTML before modifying the DOM in case of errors - let html = await r.text(); - // Remove any placeholder content before the island script - while (s.previousSibling && s.previousSibling.nodeType !== 8 && s.previousSibling.data !== '[if astro]>server-island-start line.trim()).filter((line) => line && !line.startsWith("//")).join(" ") -); - -const Fragment = Symbol.for("astro:fragment"); -const Renderer = Symbol.for("astro:renderer"); -const encoder = new TextEncoder(); -const decoder = new TextDecoder(); -function stringifyChunk(result, chunk) { - if (isRenderInstruction(chunk)) { - const instruction = chunk; - switch (instruction.type) { - case "directive": { - const { hydration } = instruction; - let needsHydrationScript = hydration && determineIfNeedsHydrationScript(result); - let needsDirectiveScript = hydration && determinesIfNeedsDirectiveScript(result, hydration.directive); - if (needsHydrationScript) { - let prescripts = getPrescripts(result, "both", hydration.directive); - return markHTMLString(prescripts); - } else if (needsDirectiveScript) { - let prescripts = getPrescripts(result, "directive", hydration.directive); - return markHTMLString(prescripts); - } else { - return ""; - } - } - case "head": { - if (result._metadata.hasRenderedHead || result.partial) { - return ""; - } - return renderAllHeadContent(result); - } - case "maybe-head": { - if (result._metadata.hasRenderedHead || result._metadata.headInTree || result.partial) { - return ""; - } - return renderAllHeadContent(result); - } - case "renderer-hydration-script": { - const { rendererSpecificHydrationScripts } = result._metadata; - const { rendererName } = instruction; - if (!rendererSpecificHydrationScripts.has(rendererName)) { - rendererSpecificHydrationScripts.add(rendererName); - return instruction.render(); - } - return ""; - } - case "server-island-runtime": { - if (result._metadata.hasRenderedServerIslandRuntime) { - return ""; - } - result._metadata.hasRenderedServerIslandRuntime = true; - return renderServerIslandRuntime(); - } - case "script": { - const { id, content } = instruction; - if (result._metadata.renderedScripts.has(id)) { - return ""; - } - result._metadata.renderedScripts.add(id); - return content; - } - default: { - throw new Error(`Unknown chunk type: ${chunk.type}`); - } - } - } else if (chunk instanceof Response) { - return ""; - } else if (isSlotString(chunk)) { - let out = ""; - const c = chunk; - if (c.instructions) { - for (const instr of c.instructions) { - out += stringifyChunk(result, instr); - } - } - out += chunk.toString(); - return out; - } - return chunk.toString(); -} -function chunkToString(result, chunk) { - if (ArrayBuffer.isView(chunk)) { - return decoder.decode(chunk); - } else { - return stringifyChunk(result, chunk); - } -} -function chunkToByteArray(result, chunk) { - if (ArrayBuffer.isView(chunk)) { - return chunk; - } else { - const stringified = stringifyChunk(result, chunk); - return encoder.encode(stringified.toString()); - } -} -function chunkToByteArrayOrString(result, chunk) { - if (ArrayBuffer.isView(chunk)) { - return chunk; - } else { - return stringifyChunk(result, chunk).toString(); - } -} -function isRenderInstance(obj) { - return !!obj && typeof obj === "object" && "render" in obj && typeof obj.render === "function"; -} - -function renderChild(destination, child) { - if (isPromise(child)) { - return child.then((x) => renderChild(destination, x)); - } - if (child instanceof SlotString) { - destination.write(child); - return; - } - if (isHTMLString(child)) { - destination.write(child); - return; - } - if (Array.isArray(child)) { - return renderArray(destination, child); - } - if (typeof child === "function") { - return renderChild(destination, child()); - } - if (!child && child !== 0) { - return; - } - if (typeof child === "string") { - destination.write(markHTMLString(escapeHTML(child))); - return; - } - if (isRenderInstance(child)) { - return child.render(destination); - } - if (isRenderTemplateResult(child)) { - return child.render(destination); - } - if (isAstroComponentInstance(child)) { - return child.render(destination); - } - if (ArrayBuffer.isView(child)) { - destination.write(child); - return; - } - if (typeof child === "object" && (Symbol.asyncIterator in child || Symbol.iterator in child)) { - if (Symbol.asyncIterator in child) { - return renderAsyncIterable(destination, child); - } - return renderIterable(destination, child); - } - destination.write(child); -} -function renderArray(destination, children) { - const flushers = children.map((c) => { - return createBufferedRenderer(destination, (bufferDestination) => { - return renderChild(bufferDestination, c); - }); - }); - const iterator = flushers[Symbol.iterator](); - const iterate = () => { - for (; ; ) { - const { value: flusher, done } = iterator.next(); - if (done) { - break; - } - const result = flusher.flush(); - if (isPromise(result)) { - return result.then(iterate); - } - } - }; - return iterate(); -} -function renderIterable(destination, children) { - const iterator = children[Symbol.iterator](); - const iterate = () => { - for (; ; ) { - const { value, done } = iterator.next(); - if (done) { - break; - } - const result = renderChild(destination, value); - if (isPromise(result)) { - return result.then(iterate); - } - } - }; - return iterate(); -} -async function renderAsyncIterable(destination, children) { - for await (const value of children) { - await renderChild(destination, value); - } -} - -const astroComponentInstanceSym = Symbol.for("astro.componentInstance"); -class AstroComponentInstance { - [astroComponentInstanceSym] = true; - result; - props; - slotValues; - factory; - returnValue; - constructor(result, props, slots, factory) { - this.result = result; - this.props = props; - this.factory = factory; - this.slotValues = {}; - for (const name in slots) { - let didRender = false; - let value = slots[name](result); - this.slotValues[name] = () => { - if (!didRender) { - didRender = true; - return value; - } - return slots[name](result); - }; - } - } - init(result) { - if (this.returnValue !== void 0) { - return this.returnValue; - } - this.returnValue = this.factory(result, this.props, this.slotValues); - if (isPromise(this.returnValue)) { - this.returnValue.then((resolved) => { - this.returnValue = resolved; - }).catch(() => { - }); - } - return this.returnValue; - } - render(destination) { - const returnValue = this.init(this.result); - if (isPromise(returnValue)) { - return returnValue.then((x) => this.renderImpl(destination, x)); - } - return this.renderImpl(destination, returnValue); - } - renderImpl(destination, returnValue) { - if (isHeadAndContent(returnValue)) { - return returnValue.content.render(destination); - } else { - return renderChild(destination, returnValue); - } - } -} -function validateComponentProps(props, clientDirectives, displayName) { - if (props != null) { - const directives = [...clientDirectives.keys()].map((directive) => `client:${directive}`); - for (const prop of Object.keys(props)) { - if (directives.includes(prop)) { - console.warn( - `You are attempting to render <${displayName} ${prop} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.` - ); - } - } - } -} -function createAstroComponentInstance(result, displayName, factory, props, slots = {}) { - validateComponentProps(props, result.clientDirectives, displayName); - const instance = new AstroComponentInstance(result, props, slots, factory); - if (isAPropagatingComponent(result, factory)) { - result._metadata.propagators.add(instance); - } - return instance; -} -function isAstroComponentInstance(obj) { - return typeof obj === "object" && obj !== null && !!obj[astroComponentInstanceSym]; -} - -const DOCTYPE_EXP = /" : "\n"; - str += doctype; - } - } - if (chunk instanceof Response) return; - str += chunkToString(result, chunk); - } - }; - await templateResult.render(destination); - return str; -} -async function renderToReadableStream(result, componentFactory, props, children, isPage = false, route) { - const templateResult = await callComponentAsTemplateResultOrResponse( - result, - componentFactory, - props, - children, - route - ); - if (templateResult instanceof Response) return templateResult; - let renderedFirstPageChunk = false; - if (isPage) { - await bufferHeadContent(result); - } - return new ReadableStream({ - start(controller) { - const destination = { - write(chunk) { - if (isPage && !renderedFirstPageChunk) { - renderedFirstPageChunk = true; - if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) { - const doctype = result.compressHTML ? "" : "\n"; - controller.enqueue(encoder.encode(doctype)); - } - } - if (chunk instanceof Response) { - throw new AstroError({ - ...ResponseSentError - }); - } - const bytes = chunkToByteArray(result, chunk); - controller.enqueue(bytes); - } - }; - (async () => { - try { - await templateResult.render(destination); - controller.close(); - } catch (e) { - if (AstroError.is(e) && !e.loc) { - e.setLocation({ - file: route?.component - }); - } - setTimeout(() => controller.error(e), 0); - } - })(); - }, - cancel() { - result.cancelled = true; - } - }); -} -async function callComponentAsTemplateResultOrResponse(result, componentFactory, props, children, route) { - const factoryResult = await componentFactory(result, props, children); - if (factoryResult instanceof Response) { - return factoryResult; - } else if (isHeadAndContent(factoryResult)) { - if (!isRenderTemplateResult(factoryResult.content)) { - throw new AstroError({ - ...OnlyResponseCanBeReturned, - message: OnlyResponseCanBeReturned.message( - route?.route, - typeof factoryResult - ), - location: { - file: route?.component - } - }); - } - return factoryResult.content; - } else if (!isRenderTemplateResult(factoryResult)) { - throw new AstroError({ - ...OnlyResponseCanBeReturned, - message: OnlyResponseCanBeReturned.message(route?.route, typeof factoryResult), - location: { - file: route?.component - } - }); - } - return factoryResult; -} -async function bufferHeadContent(result) { - const iterator = result._metadata.propagators.values(); - while (true) { - const { value, done } = iterator.next(); - if (done) { - break; - } - const returnValue = await value.init(result); - if (isHeadAndContent(returnValue) && returnValue.head) { - result._metadata.extraHead.push(returnValue.head); - } - } -} -async function renderToAsyncIterable(result, componentFactory, props, children, isPage = false, route) { - const templateResult = await callComponentAsTemplateResultOrResponse( - result, - componentFactory, - props, - children, - route - ); - if (templateResult instanceof Response) return templateResult; - let renderedFirstPageChunk = false; - if (isPage) { - await bufferHeadContent(result); - } - let error = null; - let next = null; - const buffer = []; - let renderingComplete = false; - const iterator = { - async next() { - if (result.cancelled) return { done: true, value: void 0 }; - if (next !== null) { - await next.promise; - } else if (!renderingComplete && !buffer.length) { - next = promiseWithResolvers(); - await next.promise; - } - if (!renderingComplete) { - next = promiseWithResolvers(); - } - if (error) { - throw error; - } - let length = 0; - let stringToEncode = ""; - for (let i = 0, len = buffer.length; i < len; i++) { - const bufferEntry = buffer[i]; - if (typeof bufferEntry === "string") { - const nextIsString = i + 1 < len && typeof buffer[i + 1] === "string"; - stringToEncode += bufferEntry; - if (!nextIsString) { - const encoded = encoder.encode(stringToEncode); - length += encoded.length; - stringToEncode = ""; - buffer[i] = encoded; - } else { - buffer[i] = ""; - } - } else { - length += bufferEntry.length; - } - } - let mergedArray = new Uint8Array(length); - let offset = 0; - for (let i = 0, len = buffer.length; i < len; i++) { - const item = buffer[i]; - if (item === "") { - continue; - } - mergedArray.set(item, offset); - offset += item.length; - } - buffer.length = 0; - const returnValue = { - // The iterator is done when rendering has finished - // and there are no more chunks to return. - done: length === 0 && renderingComplete, - value: mergedArray - }; - return returnValue; - }, - async return() { - result.cancelled = true; - return { done: true, value: void 0 }; - } - }; - const destination = { - write(chunk) { - if (isPage && !renderedFirstPageChunk) { - renderedFirstPageChunk = true; - if (!result.partial && !DOCTYPE_EXP.test(String(chunk))) { - const doctype = result.compressHTML ? "" : "\n"; - buffer.push(encoder.encode(doctype)); - } - } - if (chunk instanceof Response) { - throw new AstroError(ResponseSentError); - } - const bytes = chunkToByteArrayOrString(result, chunk); - if (bytes.length > 0) { - buffer.push(bytes); - next?.resolve(); - } else if (buffer.length > 0) { - next?.resolve(); - } - } - }; - const renderResult = toPromise(() => templateResult.render(destination)); - renderResult.catch((err) => { - error = err; - }).finally(() => { - renderingComplete = true; - next?.resolve(); - }); - return { - [Symbol.asyncIterator]() { - return iterator; - } - }; -} -function toPromise(fn) { - try { - const result = fn(); - return isPromise(result) ? result : Promise.resolve(result); - } catch (err) { - return Promise.reject(err); - } -} - -function componentIsHTMLElement(Component) { - return typeof HTMLElement !== "undefined" && HTMLElement.isPrototypeOf(Component); -} -async function renderHTMLElement(result, constructor, props, slots) { - const name = getHTMLElementName(constructor); - let attrHTML = ""; - for (const attr in props) { - attrHTML += ` ${attr}="${toAttributeString(await props[attr])}"`; - } - return markHTMLString( - `<${name}${attrHTML}>${await renderSlotToString(result, slots?.default)}` - ); -} -function getHTMLElementName(constructor) { - const definedName = customElements.getName(constructor); - if (definedName) return definedName; - const assignedName = constructor.name.replace(/^HTML|Element$/g, "").replace(/[A-Z]/g, "-$&").toLowerCase().replace(/^-/, "html-"); - return assignedName; -} - -const needsHeadRenderingSymbol = Symbol.for("astro.needsHeadRendering"); -const rendererAliases = /* @__PURE__ */ new Map([["solid", "solid-js"]]); -const clientOnlyValues = /* @__PURE__ */ new Set(["solid-js", "react", "preact", "vue", "svelte"]); -function guessRenderers(componentUrl) { - const extname = componentUrl?.split(".").pop(); - switch (extname) { - case "svelte": - return ["@astrojs/svelte"]; - case "vue": - return ["@astrojs/vue"]; - case "jsx": - case "tsx": - return ["@astrojs/react", "@astrojs/preact", "@astrojs/solid-js", "@astrojs/vue (jsx)"]; - case void 0: - default: - return [ - "@astrojs/react", - "@astrojs/preact", - "@astrojs/solid-js", - "@astrojs/vue", - "@astrojs/svelte" - ]; - } -} -function isFragmentComponent(Component) { - return Component === Fragment; -} -function isHTMLComponent(Component) { - return Component && Component["astro:html"] === true; -} -const ASTRO_SLOT_EXP = /<\/?astro-slot\b[^>]*>/g; -const ASTRO_STATIC_SLOT_EXP = /<\/?astro-static-slot\b[^>]*>/g; -function removeStaticAstroSlot(html, supportsAstroStaticSlot = true) { - const exp = supportsAstroStaticSlot ? ASTRO_STATIC_SLOT_EXP : ASTRO_SLOT_EXP; - return html.replace(exp, ""); -} -async function renderFrameworkComponent(result, displayName, Component, _props, slots = {}) { - if (!Component && "client:only" in _props === false) { - throw new Error( - `Unable to render ${displayName} because it is ${Component}! -Did you forget to import the component or is it possible there is a typo?` - ); - } - const { renderers, clientDirectives } = result; - const metadata = { - astroStaticSlot: true, - displayName - }; - const { hydration, isPage, props, propsWithoutTransitionAttributes } = extractDirectives( - _props, - clientDirectives - ); - let html = ""; - let attrs = void 0; - if (hydration) { - metadata.hydrate = hydration.directive; - metadata.hydrateArgs = hydration.value; - metadata.componentExport = hydration.componentExport; - metadata.componentUrl = hydration.componentUrl; - } - const probableRendererNames = guessRenderers(metadata.componentUrl); - const validRenderers = renderers.filter((r) => r.name !== "astro:jsx"); - const { children, slotInstructions } = await renderSlots(result, slots); - let renderer; - if (metadata.hydrate !== "only") { - let isTagged = false; - try { - isTagged = Component && Component[Renderer]; - } catch { - } - if (isTagged) { - const rendererName = Component[Renderer]; - renderer = renderers.find(({ name }) => name === rendererName); - } - if (!renderer) { - let error; - for (const r of renderers) { - try { - if (await r.ssr.check.call({ result }, Component, props, children)) { - renderer = r; - break; - } - } catch (e) { - error ??= e; - } - } - if (!renderer && error) { - throw error; - } - } - if (!renderer && typeof HTMLElement === "function" && componentIsHTMLElement(Component)) { - const output = await renderHTMLElement( - result, - Component, - _props, - slots - ); - return { - render(destination) { - destination.write(output); - } - }; - } - } else { - if (metadata.hydrateArgs) { - const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs; - if (clientOnlyValues.has(rendererName)) { - renderer = renderers.find( - ({ name }) => name === `@astrojs/${rendererName}` || name === rendererName - ); - } - } - if (!renderer && validRenderers.length === 1) { - renderer = validRenderers[0]; - } - if (!renderer) { - const extname = metadata.componentUrl?.split(".").pop(); - renderer = renderers.find(({ name }) => name === `@astrojs/${extname}` || name === extname); - } - } - let componentServerRenderEndTime; - if (!renderer) { - if (metadata.hydrate === "only") { - const rendererName = rendererAliases.has(metadata.hydrateArgs) ? rendererAliases.get(metadata.hydrateArgs) : metadata.hydrateArgs; - if (clientOnlyValues.has(rendererName)) { - const plural = validRenderers.length > 1; - throw new AstroError({ - ...NoMatchingRenderer, - message: NoMatchingRenderer.message( - metadata.displayName, - metadata?.componentUrl?.split(".").pop(), - plural, - validRenderers.length - ), - hint: NoMatchingRenderer.hint( - formatList(probableRendererNames.map((r) => "`" + r + "`")) - ) - }); - } else { - throw new AstroError({ - ...NoClientOnlyHint, - message: NoClientOnlyHint.message(metadata.displayName), - hint: NoClientOnlyHint.hint( - probableRendererNames.map((r) => r.replace("@astrojs/", "")).join("|") - ) - }); - } - } else if (typeof Component !== "string") { - const matchingRenderers = validRenderers.filter( - (r) => probableRendererNames.includes(r.name) - ); - const plural = validRenderers.length > 1; - if (matchingRenderers.length === 0) { - throw new AstroError({ - ...NoMatchingRenderer, - message: NoMatchingRenderer.message( - metadata.displayName, - metadata?.componentUrl?.split(".").pop(), - plural, - validRenderers.length - ), - hint: NoMatchingRenderer.hint( - formatList(probableRendererNames.map((r) => "`" + r + "`")) - ) - }); - } else if (matchingRenderers.length === 1) { - renderer = matchingRenderers[0]; - ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call( - { result }, - Component, - propsWithoutTransitionAttributes, - children, - metadata - )); - } else { - throw new Error(`Unable to render ${metadata.displayName}! - -This component likely uses ${formatList(probableRendererNames)}, -but Astro encountered an error during server-side rendering. - -Please ensure that ${metadata.displayName}: -1. Does not unconditionally access browser-specific globals like \`window\` or \`document\`. - If this is unavoidable, use the \`client:only\` hydration directive. -2. Does not conditionally return \`null\` or \`undefined\` when rendered on the server. - -If you're still stuck, please open an issue on GitHub or join us at https://astro.build/chat.`); - } - } - } else { - if (metadata.hydrate === "only") { - html = await renderSlotToString(result, slots?.fallback); - } else { - const componentRenderStartTime = performance.now(); - ({ html, attrs } = await renderer.ssr.renderToStaticMarkup.call( - { result }, - Component, - propsWithoutTransitionAttributes, - children, - metadata - )); - if (process.env.NODE_ENV === "development") - componentServerRenderEndTime = performance.now() - componentRenderStartTime; - } - } - if (!html && typeof Component === "string") { - const Tag = sanitizeElementName(Component); - const childSlots = Object.values(children).join(""); - const renderTemplateResult = renderTemplate`<${Tag}${internalSpreadAttributes( - props, - true, - Tag - )}${markHTMLString( - childSlots === "" && voidElementNames.test(Tag) ? `/>` : `>${childSlots}` - )}`; - html = ""; - const destination = { - write(chunk) { - if (chunk instanceof Response) return; - html += chunkToString(result, chunk); - } - }; - await renderTemplateResult.render(destination); - } - if (!hydration) { - return { - render(destination) { - if (slotInstructions) { - for (const instruction of slotInstructions) { - destination.write(instruction); - } - } - if (isPage || renderer?.name === "astro:jsx") { - destination.write(html); - } else if (html && html.length > 0) { - destination.write( - markHTMLString(removeStaticAstroSlot(html, renderer?.ssr?.supportsAstroStaticSlot)) - ); - } - } - }; - } - const astroId = shorthash( - ` -${html} -${serializeProps( - props, - metadata - )}` - ); - const island = await generateHydrateScript( - { renderer, result, astroId, props, attrs }, - metadata - ); - if (componentServerRenderEndTime && process.env.NODE_ENV === "development") - island.props["server-render-time"] = componentServerRenderEndTime; - let unrenderedSlots = []; - if (html) { - if (Object.keys(children).length > 0) { - for (const key of Object.keys(children)) { - let tagName = renderer?.ssr?.supportsAstroStaticSlot ? !!metadata.hydrate ? "astro-slot" : "astro-static-slot" : "astro-slot"; - let expectedHTML = key === "default" ? `<${tagName}>` : `<${tagName} name="${key}">`; - if (!html.includes(expectedHTML)) { - unrenderedSlots.push(key); - } - } - } - } else { - unrenderedSlots = Object.keys(children); - } - const template = unrenderedSlots.length > 0 ? unrenderedSlots.map( - (key) => `` - ).join("") : ""; - island.children = `${html ?? ""}${template}`; - if (island.children) { - island.props["await-children"] = ""; - island.children += ``; - } - return { - render(destination) { - if (slotInstructions) { - for (const instruction of slotInstructions) { - destination.write(instruction); - } - } - destination.write(createRenderInstruction({ type: "directive", hydration })); - if (hydration.directive !== "only" && renderer?.ssr.renderHydrationScript) { - destination.write( - createRenderInstruction({ - type: "renderer-hydration-script", - rendererName: renderer.name, - render: renderer.ssr.renderHydrationScript - }) - ); - } - const renderedElement = renderElement$1("astro-island", island, false); - destination.write(markHTMLString(renderedElement)); - } - }; -} -function sanitizeElementName(tag) { - const unsafe = /[&<>'"\s]+/; - if (!unsafe.test(tag)) return tag; - return tag.trim().split(unsafe)[0].trim(); -} -async function renderFragmentComponent(result, slots = {}) { - const children = await renderSlotToString(result, slots?.default); - return { - render(destination) { - if (children == null) return; - destination.write(children); - } - }; -} -async function renderHTMLComponent(result, Component, _props, slots = {}) { - const { slotInstructions, children } = await renderSlots(result, slots); - const html = Component({ slots: children }); - const hydrationHtml = slotInstructions ? slotInstructions.map((instr) => chunkToString(result, instr)).join("") : ""; - return { - render(destination) { - destination.write(markHTMLString(hydrationHtml + html)); - } - }; -} -function renderAstroComponent(result, displayName, Component, props, slots = {}) { - if (containsServerDirective(props)) { - const serverIslandComponent = new ServerIslandComponent(result, props, slots, displayName); - result._metadata.propagators.add(serverIslandComponent); - return serverIslandComponent; - } - const instance = createAstroComponentInstance(result, displayName, Component, props, slots); - return { - render(destination) { - return instance.render(destination); - } - }; -} -function renderComponent(result, displayName, Component, props, slots = {}) { - if (isPromise(Component)) { - return Component.catch(handleCancellation).then((x) => { - return renderComponent(result, displayName, x, props, slots); - }); - } - if (isFragmentComponent(Component)) { - return renderFragmentComponent(result, slots).catch(handleCancellation); - } - props = normalizeProps(props); - if (isHTMLComponent(Component)) { - return renderHTMLComponent(result, Component, props, slots).catch(handleCancellation); - } - if (isAstroComponentFactory(Component)) { - return renderAstroComponent(result, displayName, Component, props, slots); - } - return renderFrameworkComponent(result, displayName, Component, props, slots).catch( - handleCancellation - ); - function handleCancellation(e) { - if (result.cancelled) - return { - render() { - } - }; - throw e; - } -} -function normalizeProps(props) { - if (props["class:list"] !== void 0) { - const value = props["class:list"]; - delete props["class:list"]; - props["class"] = clsx(props["class"], value); - if (props["class"] === "") { - delete props["class"]; - } - } - return props; -} -async function renderComponentToString(result, displayName, Component, props, slots = {}, isPage = false, route) { - let str = ""; - let renderedFirstPageChunk = false; - let head = ""; - if (isPage && !result.partial && nonAstroPageNeedsHeadInjection(Component)) { - head += chunkToString(result, maybeRenderHead()); - } - try { - const destination = { - write(chunk) { - if (isPage && !result.partial && !renderedFirstPageChunk) { - renderedFirstPageChunk = true; - if (!/" : "\n"; - str += doctype + head; - } - } - if (chunk instanceof Response) return; - str += chunkToString(result, chunk); - } - }; - const renderInstance = await renderComponent(result, displayName, Component, props, slots); - if (containsServerDirective(props)) { - await bufferHeadContent(result); - } - await renderInstance.render(destination); - } catch (e) { - if (AstroError.is(e) && !e.loc) { - e.setLocation({ - file: route?.component - }); - } - throw e; - } - return str; -} -function nonAstroPageNeedsHeadInjection(pageComponent) { - return !!pageComponent?.[needsHeadRenderingSymbol]; -} - -const ClientOnlyPlaceholder = "astro-client-only"; -const hasTriedRenderComponentSymbol = Symbol("hasTriedRenderComponent"); -async function renderJSX(result, vnode) { - switch (true) { - case vnode instanceof HTMLString: - if (vnode.toString().trim() === "") { - return ""; - } - return vnode; - case typeof vnode === "string": - return markHTMLString(escapeHTML(vnode)); - case typeof vnode === "function": - return vnode; - case (!vnode && vnode !== 0): - return ""; - case Array.isArray(vnode): { - const renderedItems = await Promise.all(vnode.map((v) => renderJSX(result, v))); - let instructions = null; - let content = ""; - for (const item of renderedItems) { - if (item instanceof SlotString) { - content += item; - instructions = mergeSlotInstructions(instructions, item); - } else { - content += item; - } - } - if (instructions) { - return markHTMLString(new SlotString(content, instructions)); - } - return markHTMLString(content); - } - } - return renderJSXVNode(result, vnode); -} -async function renderJSXVNode(result, vnode) { - if (isVNode(vnode)) { - switch (true) { - case !vnode.type: { - throw new Error(`Unable to render ${result.pathname} because it contains an undefined Component! -Did you forget to import the component or is it possible there is a typo?`); - } - case vnode.type === Symbol.for("astro:fragment"): - return renderJSX(result, vnode.props.children); - case isAstroComponentFactory(vnode.type): { - let props = {}; - let slots = {}; - for (const [key, value] of Object.entries(vnode.props ?? {})) { - if (key === "children" || value && typeof value === "object" && value["$$slot"]) { - slots[key === "children" ? "default" : key] = () => renderJSX(result, value); - } else { - props[key] = value; - } - } - const str = await renderComponentToString( - result, - vnode.type.name, - vnode.type, - props, - slots - ); - const html = markHTMLString(str); - return html; - } - case (!vnode.type && vnode.type !== 0): - return ""; - case (typeof vnode.type === "string" && vnode.type !== ClientOnlyPlaceholder): - return markHTMLString(await renderElement(result, vnode.type, vnode.props ?? {})); - } - if (vnode.type) { - let extractSlots2 = function(child) { - if (Array.isArray(child)) { - return child.map((c) => extractSlots2(c)); - } - if (!isVNode(child)) { - _slots.default.push(child); - return; - } - if ("slot" in child.props) { - _slots[child.props.slot] = [..._slots[child.props.slot] ?? [], child]; - delete child.props.slot; - return; - } - _slots.default.push(child); - }; - if (typeof vnode.type === "function" && vnode.props["server:root"]) { - const output2 = await vnode.type(vnode.props ?? {}); - return await renderJSX(result, output2); - } - if (typeof vnode.type === "function") { - if (vnode.props[hasTriedRenderComponentSymbol]) { - delete vnode.props[hasTriedRenderComponentSymbol]; - const output2 = await vnode.type(vnode.props ?? {}); - if (output2?.[AstroJSX] || !output2) { - return await renderJSXVNode(result, output2); - } else { - return; - } - } else { - vnode.props[hasTriedRenderComponentSymbol] = true; - } - } - const { children = null, ...props } = vnode.props ?? {}; - const _slots = { - default: [] - }; - extractSlots2(children); - for (const [key, value] of Object.entries(props)) { - if (value?.["$$slot"]) { - _slots[key] = value; - delete props[key]; - } - } - const slotPromises = []; - const slots = {}; - for (const [key, value] of Object.entries(_slots)) { - slotPromises.push( - renderJSX(result, value).then((output2) => { - if (output2.toString().trim().length === 0) return; - slots[key] = () => output2; - }) - ); - } - await Promise.all(slotPromises); - let output; - if (vnode.type === ClientOnlyPlaceholder && vnode.props["client:only"]) { - output = await renderComponentToString( - result, - vnode.props["client:display-name"] ?? "", - null, - props, - slots - ); - } else { - output = await renderComponentToString( - result, - typeof vnode.type === "function" ? vnode.type.name : vnode.type, - vnode.type, - props, - slots - ); - } - return markHTMLString(output); - } - } - return markHTMLString(`${vnode}`); -} -async function renderElement(result, tag, { children, ...props }) { - return markHTMLString( - `<${tag}${spreadAttributes(props)}${markHTMLString( - (children == null || children == "") && voidElementNames.test(tag) ? `/>` : `>${children == null ? "" : await renderJSX(result, prerenderElementChildren(tag, children))}` - )}` - ); -} -function prerenderElementChildren(tag, children) { - if (typeof children === "string" && (tag === "style" || tag === "script")) { - return markHTMLString(children); - } else { - return children; - } -} - -async function renderPage(result, componentFactory, props, children, streaming, route) { - if (!isAstroComponentFactory(componentFactory)) { - result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false; - const pageProps = { ...props ?? {}, "server:root": true }; - const str = await renderComponentToString( - result, - componentFactory.name, - componentFactory, - pageProps, - {}, - true, - route - ); - const bytes = encoder.encode(str); - const headers2 = new Headers([ - ["Content-Type", "text/html"], - ["Content-Length", bytes.byteLength.toString()] - ]); - if (result.shouldInjectCspMetaTags && (result.cspDestination === "header" || result.cspDestination === "adapter")) { - headers2.set("content-security-policy", renderCspContent(result)); - } - return new Response(bytes, { - headers: headers2 - }); - } - result._metadata.headInTree = result.componentMetadata.get(componentFactory.moduleId)?.containsHead ?? false; - let body; - if (streaming) { - if (isNode && !isDeno) { - const nodeBody = await renderToAsyncIterable( - result, - componentFactory, - props, - children, - true, - route - ); - body = nodeBody; - } else { - body = await renderToReadableStream(result, componentFactory, props, children, true, route); - } - } else { - body = await renderToString(result, componentFactory, props, children, true, route); - } - if (body instanceof Response) return body; - const init = result.response; - const headers = new Headers(init.headers); - if (result.shouldInjectCspMetaTags && result.cspDestination === "header" || result.cspDestination === "adapter") { - headers.set("content-security-policy", renderCspContent(result)); - } - if (!streaming && typeof body === "string") { - body = encoder.encode(body); - headers.set("Content-Length", body.byteLength.toString()); - } - let status = init.status; - let statusText = init.statusText; - if (route?.route === "/404") { - status = 404; - if (statusText === "OK") { - statusText = "Not Found"; - } - } else if (route?.route === "/500") { - status = 500; - if (statusText === "OK") { - statusText = "Internal Server Error"; - } - } - if (status) { - return new Response(body, { ...init, headers, status, statusText }); - } else { - return new Response(body, { ...init, headers }); - } -} - -async function renderScript(result, id) { - const inlined = result.inlinedScripts.get(id); - let content = ""; - if (inlined != null) { - if (inlined) { - content = ``; - } - } else { - const resolved = await result.resolve(id); - content = ``; - } - return createRenderInstruction({ type: "script", id, content }); -} - -function renderScriptElement({ props, children }) { - return renderElement$1("script", { - props, - children - }); -} -function renderUniqueStylesheet(result, sheet) { - if (sheet.type === "external") { - if (Array.from(result.styles).some((s) => s.props.href === sheet.src)) return ""; - return renderElement$1("link", { props: { rel: "stylesheet", href: sheet.src }, children: "" }); - } - if (sheet.type === "inline") { - if (Array.from(result.styles).some((s) => s.children.includes(sheet.content))) return ""; - return renderElement$1("style", { props: {}, children: sheet.content }); - } -} - -"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []); -"-0123456789_".split("").reduce((v, c) => (v[c.charCodeAt(0)] = c, v), []); - -function spreadAttributes(values = {}, _name, { class: scopedClassName } = {}) { - let output = ""; - if (scopedClassName) { - if (typeof values.class !== "undefined") { - values.class += ` ${scopedClassName}`; - } else if (typeof values["class:list"] !== "undefined") { - values["class:list"] = [values["class:list"], scopedClassName]; - } else { - values.class = scopedClassName; - } - } - for (const [key, value] of Object.entries(values)) { - output += addAttribute(value, key, true, _name); - } - return markHTMLString(output); -} - -export { CspNotEnabled as $, AstroError as A, originPathnameSymbol as B, RewriteWithBodyUsed as C, DEFAULT_404_COMPONENT as D, InvalidGetStaticPathsEntry as E, FailedToFindPageMapSSR as F, GetStaticPathsRequired as G, GetStaticPathsExpectedParams as H, InvalidGetStaticPathsReturn as I, GetStaticPathsInvalidRouteParam as J, PrerenderDynamicEndpointPathCollide as K, LocalsNotAnObject as L, ReservedSlotName as M, NoMatchingStaticPathFound as N, renderSlotToString as O, PageNumberParamNotFound as P, renderJSX as Q, RenderUndefinedEntryError as R, chunkToString as S, isRenderInstruction as T, UnknownContentCollectionError as U, MiddlewareNoDataOrNextCalled as V, MiddlewareNotAResponse as W, SessionStorageInitError as X, SessionStorageSaveError as Y, ForbiddenRewrite as Z, ASTRO_VERSION as _, renderTemplate as a, LocalsReassigned as a0, generateCspDigest as a1, PrerenderClientAddressNotAvailable as a2, ClientAddressNotAvailable as a3, StaticClientAddressNotAvailable as a4, AstroResponseHeadersReassigned as a5, renderPage as a6, REWRITE_DIRECTIVE_HEADER_KEY as a7, REWRITE_DIRECTIVE_HEADER_VALUE as a8, renderEndpoint as a9, NOOP_MIDDLEWARE_HEADER as aa, REDIRECT_STATUS_CODES as ab, ActionsReturnedInvalidDataError as ac, MissingSharp as ad, ExpectedImage as ae, LocalImageUsedWrongly as af, MissingImageDimension as ag, UnsupportedImageFormat as ah, IncompatibleDescriptorOptions as ai, UnsupportedImageConversion as aj, toStyleString as ak, NoImageMetadata as al, FailedToFetchRemoteImageDimensions as am, RemoteImageNotAllowed as an, ExpectedImageOptions as ao, ExpectedNotESMImage as ap, InvalidImageService as aq, ImageMissingAlt as ar, spreadAttributes as as, ExperimentalFontsNotEnabled as at, FontFamilyNotFound as au, createAstro as b, createComponent as c, renderSlot as d, addAttribute as e, renderUniqueStylesheet as f, renderScriptElement as g, createHeadAndContent as h, renderScript as i, renderHead as j, decodeKey as k, ROUTE_TYPE_HEADER as l, maybeRenderHead as m, REROUTE_DIRECTIVE_HEADER as n, ActionNotFoundError as o, clientAddressSymbol as p, REROUTABLE_STATUS_CODES as q, renderComponent as r, responseSentSymbol as s, nodeRequestAbortControllerCleanupSymbol as t, unescapeHTML as u, decryptString as v, createSlotValueFromString as w, isAstroComponentFactory as x, i18nNoLocaleFoundInPath as y, ResponseSentError as z }; diff --git a/.vercel/output/_functions/chunks/consts_Bd-1c2lz.mjs b/.vercel/output/_functions/chunks/consts_Bd-1c2lz.mjs deleted file mode 100644 index 0572f21..0000000 --- a/.vercel/output/_functions/chunks/consts_Bd-1c2lz.mjs +++ /dev/null @@ -1,33 +0,0 @@ -const VALID_INPUT_FORMATS = [ - "jpeg", - "jpg", - "png", - "tiff", - "webp", - "gif", - "svg", - "avif" -]; -const VALID_SUPPORTED_FORMATS = [ - "jpeg", - "jpg", - "png", - "tiff", - "webp", - "gif", - "svg", - "avif" -]; -const DEFAULT_OUTPUT_FORMAT = "webp"; -const DEFAULT_HASH_PROPS = [ - "src", - "width", - "height", - "format", - "quality", - "fit", - "position", - "background" -]; - -export { DEFAULT_OUTPUT_FORMAT as D, VALID_INPUT_FORMATS as V, VALID_SUPPORTED_FORMATS as a, DEFAULT_HASH_PROPS as b }; diff --git a/.vercel/output/_functions/chunks/content-assets_DleWbedO.mjs b/.vercel/output/_functions/chunks/content-assets_DleWbedO.mjs deleted file mode 100644 index dd23cbd..0000000 --- a/.vercel/output/_functions/chunks/content-assets_DleWbedO.mjs +++ /dev/null @@ -1,3 +0,0 @@ -const contentAssets = new Map(); - -export { contentAssets as default }; diff --git a/.vercel/output/_functions/chunks/content-modules_Dz-S_Wwv.mjs b/.vercel/output/_functions/chunks/content-modules_Dz-S_Wwv.mjs deleted file mode 100644 index 60b7476..0000000 --- a/.vercel/output/_functions/chunks/content-modules_Dz-S_Wwv.mjs +++ /dev/null @@ -1,3 +0,0 @@ -const contentModules = new Map(); - -export { contentModules as default }; diff --git a/.vercel/output/_functions/chunks/index_BL6Pqka4.mjs b/.vercel/output/_functions/chunks/index_BL6Pqka4.mjs deleted file mode 100644 index e285755..0000000 --- a/.vercel/output/_functions/chunks/index_BL6Pqka4.mjs +++ /dev/null @@ -1,988 +0,0 @@ -function matchPattern(url, remotePattern) { - return matchProtocol(url, remotePattern.protocol) && matchHostname(url, remotePattern.hostname, true) && matchPort(url, remotePattern.port) && matchPathname(url, remotePattern.pathname, true); -} -function matchPort(url, port) { - return !port || port === url.port; -} -function matchProtocol(url, protocol) { - return !protocol || protocol === url.protocol.slice(0, -1); -} -function matchHostname(url, hostname, allowWildcard = false) { - if (!hostname) { - return true; - } else if (!allowWildcard || !hostname.startsWith("*")) { - return hostname === url.hostname; - } else if (hostname.startsWith("**.")) { - const slicedHostname = hostname.slice(2); - return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname); - } else if (hostname.startsWith("*.")) { - const slicedHostname = hostname.slice(1); - if (!url.hostname.endsWith(slicedHostname)) { - return false; - } - const subdomainWithDot = url.hostname.slice(0, -(slicedHostname.length - 1)); - return subdomainWithDot.endsWith(".") && !subdomainWithDot.slice(0, -1).includes("."); - } - return false; -} -function matchPathname(url, pathname, allowWildcard = false) { - if (!pathname) { - return true; - } else if (!allowWildcard || !pathname.endsWith("*")) { - return pathname === url.pathname; - } else if (pathname.endsWith("/**")) { - const slicedPathname = pathname.slice(0, -2); - return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname); - } else if (pathname.endsWith("/*")) { - const slicedPathname = pathname.slice(0, -1); - const additionalPathChunks = url.pathname.replace(slicedPathname, "").split("/").filter(Boolean); - return additionalPathChunks.length === 1; - } - return false; -} -function isRemoteAllowed(src, { - domains, - remotePatterns -}) { - if (!URL.canParse(src)) { - return false; - } - const url = new URL(src); - if (!["http:", "https:", "data:"].includes(url.protocol)) { - return false; - } - return domains.some((domain) => matchHostname(url, domain)) || remotePatterns.some((remotePattern) => matchPattern(url, remotePattern)); -} - -const decoder = new TextDecoder(); -const toUTF8String = (input, start = 0, end = input.length) => decoder.decode(input.slice(start, end)); -const toHexString = (input, start = 0, end = input.length) => input.slice(start, end).reduce((memo, i) => memo + `0${i.toString(16)}`.slice(-2), ""); -const getView = (input, offset) => new DataView(input.buffer, input.byteOffset + offset); -const readInt16LE = (input, offset = 0) => getView(input, offset).getInt16(0, true); -const readUInt16BE = (input, offset = 0) => getView(input, offset).getUint16(0, false); -const readUInt16LE = (input, offset = 0) => getView(input, offset).getUint16(0, true); -const readUInt24LE = (input, offset = 0) => { - const view = getView(input, offset); - return view.getUint16(0, true) + (view.getUint8(2) << 16); -}; -const readInt32LE = (input, offset = 0) => getView(input, offset).getInt32(0, true); -const readUInt32BE = (input, offset = 0) => getView(input, offset).getUint32(0, false); -const readUInt32LE = (input, offset = 0) => getView(input, offset).getUint32(0, true); -const readUInt64 = (input, offset, isBigEndian) => getView(input, offset).getBigUint64(0, !isBigEndian); -const methods = { - readUInt16BE, - readUInt16LE, - readUInt32BE, - readUInt32LE -}; -function readUInt(input, bits, offset = 0, isBigEndian = false) { - const endian = isBigEndian ? "BE" : "LE"; - const methodName = `readUInt${bits}${endian}`; - return methods[methodName](input, offset); -} -function readBox(input, offset) { - if (input.length - offset < 4) return; - const boxSize = readUInt32BE(input, offset); - if (input.length - offset < boxSize) return; - return { - name: toUTF8String(input, 4 + offset, 8 + offset), - offset, - size: boxSize - }; -} -function findBox(input, boxName, currentOffset) { - while (currentOffset < input.length) { - const box = readBox(input, currentOffset); - if (!box) break; - if (box.name === boxName) return box; - currentOffset += box.size > 0 ? box.size : 8; - } -} - -const BMP = { - validate: (input) => toUTF8String(input, 0, 2) === "BM", - calculate: (input) => ({ - height: Math.abs(readInt32LE(input, 22)), - width: readUInt32LE(input, 18) - }) -}; - -const TYPE_ICON = 1; -const SIZE_HEADER$1 = 2 + 2 + 2; -const SIZE_IMAGE_ENTRY = 1 + 1 + 1 + 1 + 2 + 2 + 4 + 4; -function getSizeFromOffset(input, offset) { - const value = input[offset]; - return value === 0 ? 256 : value; -} -function getImageSize$1(input, imageIndex) { - const offset = SIZE_HEADER$1 + imageIndex * SIZE_IMAGE_ENTRY; - return { - height: getSizeFromOffset(input, offset + 1), - width: getSizeFromOffset(input, offset) - }; -} -const ICO = { - validate(input) { - const reserved = readUInt16LE(input, 0); - const imageCount = readUInt16LE(input, 4); - if (reserved !== 0 || imageCount === 0) return false; - const imageType = readUInt16LE(input, 2); - return imageType === TYPE_ICON; - }, - calculate(input) { - const nbImages = readUInt16LE(input, 4); - const imageSize = getImageSize$1(input, 0); - if (nbImages === 1) return imageSize; - const images = []; - for (let imageIndex = 0; imageIndex < nbImages; imageIndex += 1) { - images.push(getImageSize$1(input, imageIndex)); - } - return { - width: imageSize.width, - height: imageSize.height, - images - }; - } -}; - -const TYPE_CURSOR = 2; -const CUR = { - validate(input) { - const reserved = readUInt16LE(input, 0); - const imageCount = readUInt16LE(input, 4); - if (reserved !== 0 || imageCount === 0) return false; - const imageType = readUInt16LE(input, 2); - return imageType === TYPE_CURSOR; - }, - calculate: (input) => ICO.calculate(input) -}; - -const DDS = { - validate: (input) => readUInt32LE(input, 0) === 542327876, - calculate: (input) => ({ - height: readUInt32LE(input, 12), - width: readUInt32LE(input, 16) - }) -}; - -const gifRegexp = /^GIF8[79]a/; -const GIF = { - validate: (input) => gifRegexp.test(toUTF8String(input, 0, 6)), - calculate: (input) => ({ - height: readUInt16LE(input, 8), - width: readUInt16LE(input, 6) - }) -}; - -const brandMap = { - avif: "avif", - avis: "avif", - // avif-sequence - mif1: "heif", - msf1: "heif", - // heif-sequence - heic: "heic", - heix: "heic", - hevc: "heic", - // heic-sequence - hevx: "heic" - // heic-sequence -}; -function detectType(input, start, end) { - let hasAvif = false; - let hasHeic = false; - let hasHeif = false; - for (let i = start; i <= end; i += 4) { - const brand = toUTF8String(input, i, i + 4); - if (brand === "avif" || brand === "avis") hasAvif = true; - else if (brand === "heic" || brand === "heix" || brand === "hevc" || brand === "hevx") hasHeic = true; - else if (brand === "mif1" || brand === "msf1") hasHeif = true; - } - if (hasAvif) return "avif"; - if (hasHeic) return "heic"; - if (hasHeif) return "heif"; -} -const HEIF = { - validate(input) { - const boxType = toUTF8String(input, 4, 8); - if (boxType !== "ftyp") return false; - const ftypBox = findBox(input, "ftyp", 0); - if (!ftypBox) return false; - const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12); - return brand in brandMap; - }, - calculate(input) { - const metaBox = findBox(input, "meta", 0); - const iprpBox = metaBox && findBox(input, "iprp", metaBox.offset + 12); - const ipcoBox = iprpBox && findBox(input, "ipco", iprpBox.offset + 8); - if (!ipcoBox) { - throw new TypeError("Invalid HEIF, no ipco box found"); - } - const type = detectType(input, 8, metaBox.offset); - const images = []; - let currentOffset = ipcoBox.offset + 8; - while (currentOffset < ipcoBox.offset + ipcoBox.size) { - const ispeBox = findBox(input, "ispe", currentOffset); - if (!ispeBox) break; - const rawWidth = readUInt32BE(input, ispeBox.offset + 12); - const rawHeight = readUInt32BE(input, ispeBox.offset + 16); - const clapBox = findBox(input, "clap", currentOffset); - let width = rawWidth; - let height = rawHeight; - if (clapBox && clapBox.offset < ipcoBox.offset + ipcoBox.size) { - const cropRight = readUInt32BE(input, clapBox.offset + 12); - width = rawWidth - cropRight; - } - images.push({ height, width }); - currentOffset = ispeBox.offset + ispeBox.size; - } - if (images.length === 0) { - throw new TypeError("Invalid HEIF, no sizes found"); - } - return { - width: images[0].width, - height: images[0].height, - type, - ...images.length > 1 ? { images } : {} - }; - } -}; - -const SIZE_HEADER = 4 + 4; -const FILE_LENGTH_OFFSET = 4; -const ENTRY_LENGTH_OFFSET = 4; -const ICON_TYPE_SIZE = { - ICON: 32, - "ICN#": 32, - // m => 16 x 16 - "icm#": 16, - icm4: 16, - icm8: 16, - // s => 16 x 16 - "ics#": 16, - ics4: 16, - ics8: 16, - is32: 16, - s8mk: 16, - icp4: 16, - // l => 32 x 32 - icl4: 32, - icl8: 32, - il32: 32, - l8mk: 32, - icp5: 32, - ic11: 32, - // h => 48 x 48 - ich4: 48, - ich8: 48, - ih32: 48, - h8mk: 48, - // . => 64 x 64 - icp6: 64, - ic12: 32, - // t => 128 x 128 - it32: 128, - t8mk: 128, - ic07: 128, - // . => 256 x 256 - ic08: 256, - ic13: 256, - // . => 512 x 512 - ic09: 512, - ic14: 512, - // . => 1024 x 1024 - ic10: 1024 -}; -function readImageHeader(input, imageOffset) { - const imageLengthOffset = imageOffset + ENTRY_LENGTH_OFFSET; - return [ - toUTF8String(input, imageOffset, imageLengthOffset), - readUInt32BE(input, imageLengthOffset) - ]; -} -function getImageSize(type) { - const size = ICON_TYPE_SIZE[type]; - return { width: size, height: size, type }; -} -const ICNS = { - validate: (input) => toUTF8String(input, 0, 4) === "icns", - calculate(input) { - const inputLength = input.length; - const fileLength = readUInt32BE(input, FILE_LENGTH_OFFSET); - let imageOffset = SIZE_HEADER; - const images = []; - while (imageOffset < fileLength && imageOffset < inputLength) { - const imageHeader = readImageHeader(input, imageOffset); - const imageSize = getImageSize(imageHeader[0]); - images.push(imageSize); - imageOffset += imageHeader[1]; - } - if (images.length === 0) { - throw new TypeError("Invalid ICNS, no sizes found"); - } - return { - width: images[0].width, - height: images[0].height, - ...images.length > 1 ? { images } : {} - }; - } -}; - -const J2C = { - // TODO: this doesn't seem right. SIZ marker doesn't have to be right after the SOC - validate: (input) => readUInt32BE(input, 0) === 4283432785, - calculate: (input) => ({ - height: readUInt32BE(input, 12), - width: readUInt32BE(input, 8) - }) -}; - -const JP2 = { - validate(input) { - const boxType = toUTF8String(input, 4, 8); - if (boxType !== "jP ") return false; - const ftypBox = findBox(input, "ftyp", 0); - if (!ftypBox) return false; - const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12); - return brand === "jp2 "; - }, - calculate(input) { - const jp2hBox = findBox(input, "jp2h", 0); - const ihdrBox = jp2hBox && findBox(input, "ihdr", jp2hBox.offset + 8); - if (ihdrBox) { - return { - height: readUInt32BE(input, ihdrBox.offset + 8), - width: readUInt32BE(input, ihdrBox.offset + 12) - }; - } - throw new TypeError("Unsupported JPEG 2000 format"); - } -}; - -const EXIF_MARKER = "45786966"; -const APP1_DATA_SIZE_BYTES = 2; -const EXIF_HEADER_BYTES = 6; -const TIFF_BYTE_ALIGN_BYTES = 2; -const BIG_ENDIAN_BYTE_ALIGN = "4d4d"; -const LITTLE_ENDIAN_BYTE_ALIGN = "4949"; -const IDF_ENTRY_BYTES = 12; -const NUM_DIRECTORY_ENTRIES_BYTES = 2; -function isEXIF(input) { - return toHexString(input, 2, 6) === EXIF_MARKER; -} -function extractSize(input, index) { - return { - height: readUInt16BE(input, index), - width: readUInt16BE(input, index + 2) - }; -} -function extractOrientation(exifBlock, isBigEndian) { - const idfOffset = 8; - const offset = EXIF_HEADER_BYTES + idfOffset; - const idfDirectoryEntries = readUInt(exifBlock, 16, offset, isBigEndian); - for (let directoryEntryNumber = 0; directoryEntryNumber < idfDirectoryEntries; directoryEntryNumber++) { - const start = offset + NUM_DIRECTORY_ENTRIES_BYTES + directoryEntryNumber * IDF_ENTRY_BYTES; - const end = start + IDF_ENTRY_BYTES; - if (start > exifBlock.length) { - return; - } - const block = exifBlock.slice(start, end); - const tagNumber = readUInt(block, 16, 0, isBigEndian); - if (tagNumber === 274) { - const dataFormat = readUInt(block, 16, 2, isBigEndian); - if (dataFormat !== 3) { - return; - } - const numberOfComponents = readUInt(block, 32, 4, isBigEndian); - if (numberOfComponents !== 1) { - return; - } - return readUInt(block, 16, 8, isBigEndian); - } - } -} -function validateExifBlock(input, index) { - const exifBlock = input.slice(APP1_DATA_SIZE_BYTES, index); - const byteAlign = toHexString( - exifBlock, - EXIF_HEADER_BYTES, - EXIF_HEADER_BYTES + TIFF_BYTE_ALIGN_BYTES - ); - const isBigEndian = byteAlign === BIG_ENDIAN_BYTE_ALIGN; - const isLittleEndian = byteAlign === LITTLE_ENDIAN_BYTE_ALIGN; - if (isBigEndian || isLittleEndian) { - return extractOrientation(exifBlock, isBigEndian); - } -} -function validateInput(input, index) { - if (index > input.length) { - throw new TypeError("Corrupt JPG, exceeded buffer limits"); - } -} -const JPG = { - validate: (input) => toHexString(input, 0, 2) === "ffd8", - calculate(_input) { - let input = _input.slice(4); - let orientation; - let next; - while (input.length) { - const i = readUInt16BE(input, 0); - validateInput(input, i); - if (input[i] !== 255) { - input = input.slice(1); - continue; - } - if (isEXIF(input)) { - orientation = validateExifBlock(input, i); - } - next = input[i + 1]; - if (next === 192 || next === 193 || next === 194) { - const size = extractSize(input, i + 5); - if (!orientation) { - return size; - } - return { - height: size.height, - orientation, - width: size.width - }; - } - input = input.slice(i + 2); - } - throw new TypeError("Invalid JPG, no size found"); - } -}; - -class BitReader { - constructor(input, endianness) { - this.input = input; - this.endianness = endianness; - } - // Skip the first 16 bits (2 bytes) of signature - byteOffset = 2; - bitOffset = 0; - /** Reads a specified number of bits, and move the offset */ - getBits(length = 1) { - let result = 0; - let bitsRead = 0; - while (bitsRead < length) { - if (this.byteOffset >= this.input.length) { - throw new Error("Reached end of input"); - } - const currentByte = this.input[this.byteOffset]; - const bitsLeft = 8 - this.bitOffset; - const bitsToRead = Math.min(length - bitsRead, bitsLeft); - if (this.endianness === "little-endian") { - const mask = (1 << bitsToRead) - 1; - const bits = currentByte >> this.bitOffset & mask; - result |= bits << bitsRead; - } else { - const mask = (1 << bitsToRead) - 1 << 8 - this.bitOffset - bitsToRead; - const bits = (currentByte & mask) >> 8 - this.bitOffset - bitsToRead; - result = result << bitsToRead | bits; - } - bitsRead += bitsToRead; - this.bitOffset += bitsToRead; - if (this.bitOffset === 8) { - this.byteOffset++; - this.bitOffset = 0; - } - } - return result; - } -} - -function calculateImageDimension(reader, isSmallImage) { - if (isSmallImage) { - return 8 * (1 + reader.getBits(5)); - } - const sizeClass = reader.getBits(2); - const extraBits = [9, 13, 18, 30][sizeClass]; - return 1 + reader.getBits(extraBits); -} -function calculateImageWidth(reader, isSmallImage, widthMode, height) { - if (isSmallImage && widthMode === 0) { - return 8 * (1 + reader.getBits(5)); - } - if (widthMode === 0) { - return calculateImageDimension(reader, false); - } - const aspectRatios = [1, 1.2, 4 / 3, 1.5, 16 / 9, 5 / 4, 2]; - return Math.floor(height * aspectRatios[widthMode - 1]); -} -const JXLStream = { - validate: (input) => { - return toHexString(input, 0, 2) === "ff0a"; - }, - calculate(input) { - const reader = new BitReader(input, "little-endian"); - const isSmallImage = reader.getBits(1) === 1; - const height = calculateImageDimension(reader, isSmallImage); - const widthMode = reader.getBits(3); - const width = calculateImageWidth(reader, isSmallImage, widthMode, height); - return { width, height }; - } -}; - -function extractCodestream(input) { - const jxlcBox = findBox(input, "jxlc", 0); - if (jxlcBox) { - return input.slice(jxlcBox.offset + 8, jxlcBox.offset + jxlcBox.size); - } - const partialStreams = extractPartialStreams(input); - if (partialStreams.length > 0) { - return concatenateCodestreams(partialStreams); - } - return void 0; -} -function extractPartialStreams(input) { - const partialStreams = []; - let offset = 0; - while (offset < input.length) { - const jxlpBox = findBox(input, "jxlp", offset); - if (!jxlpBox) break; - partialStreams.push( - input.slice(jxlpBox.offset + 12, jxlpBox.offset + jxlpBox.size) - ); - offset = jxlpBox.offset + jxlpBox.size; - } - return partialStreams; -} -function concatenateCodestreams(partialCodestreams) { - const totalLength = partialCodestreams.reduce( - (acc, curr) => acc + curr.length, - 0 - ); - const codestream = new Uint8Array(totalLength); - let position = 0; - for (const partial of partialCodestreams) { - codestream.set(partial, position); - position += partial.length; - } - return codestream; -} -const JXL = { - validate: (input) => { - const boxType = toUTF8String(input, 4, 8); - if (boxType !== "JXL ") return false; - const ftypBox = findBox(input, "ftyp", 0); - if (!ftypBox) return false; - const brand = toUTF8String(input, ftypBox.offset + 8, ftypBox.offset + 12); - return brand === "jxl "; - }, - calculate(input) { - const codestream = extractCodestream(input); - if (codestream) return JXLStream.calculate(codestream); - throw new Error("No codestream found in JXL container"); - } -}; - -const KTX = { - validate: (input) => { - const signature = toUTF8String(input, 1, 7); - return ["KTX 11", "KTX 20"].includes(signature); - }, - calculate: (input) => { - const type = input[5] === 49 ? "ktx" : "ktx2"; - const offset = type === "ktx" ? 36 : 20; - return { - height: readUInt32LE(input, offset + 4), - width: readUInt32LE(input, offset), - type - }; - } -}; - -const pngSignature = "PNG\r\n\n"; -const pngImageHeaderChunkName = "IHDR"; -const pngFriedChunkName = "CgBI"; -const PNG = { - validate(input) { - if (pngSignature === toUTF8String(input, 1, 8)) { - let chunkName = toUTF8String(input, 12, 16); - if (chunkName === pngFriedChunkName) { - chunkName = toUTF8String(input, 28, 32); - } - if (chunkName !== pngImageHeaderChunkName) { - throw new TypeError("Invalid PNG"); - } - return true; - } - return false; - }, - calculate(input) { - if (toUTF8String(input, 12, 16) === pngFriedChunkName) { - return { - height: readUInt32BE(input, 36), - width: readUInt32BE(input, 32) - }; - } - return { - height: readUInt32BE(input, 20), - width: readUInt32BE(input, 16) - }; - } -}; - -const PNMTypes = { - P1: "pbm/ascii", - P2: "pgm/ascii", - P3: "ppm/ascii", - P4: "pbm", - P5: "pgm", - P6: "ppm", - P7: "pam", - PF: "pfm" -}; -const handlers = { - default: (lines) => { - let dimensions = []; - while (lines.length > 0) { - const line = lines.shift(); - if (line[0] === "#") { - continue; - } - dimensions = line.split(" "); - break; - } - if (dimensions.length === 2) { - return { - height: Number.parseInt(dimensions[1], 10), - width: Number.parseInt(dimensions[0], 10) - }; - } - throw new TypeError("Invalid PNM"); - }, - pam: (lines) => { - const size = {}; - while (lines.length > 0) { - const line = lines.shift(); - if (line.length > 16 || line.charCodeAt(0) > 128) { - continue; - } - const [key, value] = line.split(" "); - if (key && value) { - size[key.toLowerCase()] = Number.parseInt(value, 10); - } - if (size.height && size.width) { - break; - } - } - if (size.height && size.width) { - return { - height: size.height, - width: size.width - }; - } - throw new TypeError("Invalid PAM"); - } -}; -const PNM = { - validate: (input) => toUTF8String(input, 0, 2) in PNMTypes, - calculate(input) { - const signature = toUTF8String(input, 0, 2); - const type = PNMTypes[signature]; - const lines = toUTF8String(input, 3).split(/[\r\n]+/); - const handler = handlers[type] || handlers.default; - return handler(lines); - } -}; - -const PSD = { - validate: (input) => toUTF8String(input, 0, 4) === "8BPS", - calculate: (input) => ({ - height: readUInt32BE(input, 14), - width: readUInt32BE(input, 18) - }) -}; - -const svgReg = /"']|"[^"]*"|'[^']*')*>/; -const extractorRegExps = { - height: /\sheight=(['"])([^%]+?)\1/, - root: svgReg, - viewbox: /\sviewBox=(['"])(.+?)\1/i, - width: /\swidth=(['"])([^%]+?)\1/ -}; -const INCH_CM = 2.54; -const units = { - in: 96, - cm: 96 / INCH_CM, - em: 16, - ex: 8, - m: 96 / INCH_CM * 100, - mm: 96 / INCH_CM / 10, - pc: 96 / 72 / 12, - pt: 96 / 72, - px: 1 -}; -const unitsReg = new RegExp( - `^([0-9.]+(?:e\\d+)?)(${Object.keys(units).join("|")})?$` -); -function parseLength(len) { - const m = unitsReg.exec(len); - if (!m) { - return void 0; - } - return Math.round(Number(m[1]) * (units[m[2]] || 1)); -} -function parseViewbox(viewbox) { - const bounds = viewbox.split(" "); - return { - height: parseLength(bounds[3]), - width: parseLength(bounds[2]) - }; -} -function parseAttributes(root) { - const width = extractorRegExps.width.exec(root); - const height = extractorRegExps.height.exec(root); - const viewbox = extractorRegExps.viewbox.exec(root); - return { - height: height && parseLength(height[2]), - viewbox: viewbox && parseViewbox(viewbox[2]), - width: width && parseLength(width[2]) - }; -} -function calculateByDimensions(attrs) { - return { - height: attrs.height, - width: attrs.width - }; -} -function calculateByViewbox(attrs, viewbox) { - const ratio = viewbox.width / viewbox.height; - if (attrs.width) { - return { - height: Math.floor(attrs.width / ratio), - width: attrs.width - }; - } - if (attrs.height) { - return { - height: attrs.height, - width: Math.floor(attrs.height * ratio) - }; - } - return { - height: viewbox.height, - width: viewbox.width - }; -} -const SVG = { - // Scan only the first kilo-byte to speed up the check on larger files - validate: (input) => svgReg.test(toUTF8String(input, 0, 1e3)), - calculate(input) { - const root = extractorRegExps.root.exec(toUTF8String(input)); - if (root) { - const attrs = parseAttributes(root[0]); - if (attrs.width && attrs.height) { - return calculateByDimensions(attrs); - } - if (attrs.viewbox) { - return calculateByViewbox(attrs, attrs.viewbox); - } - } - throw new TypeError("Invalid SVG"); - } -}; - -const TGA = { - validate(input) { - return readUInt16LE(input, 0) === 0 && readUInt16LE(input, 4) === 0; - }, - calculate(input) { - return { - height: readUInt16LE(input, 14), - width: readUInt16LE(input, 12) - }; - } -}; - -const CONSTANTS = { - TAG: { - WIDTH: 256, - HEIGHT: 257, - COMPRESSION: 259 - }, - TYPE: { - SHORT: 3, - LONG: 4, - LONG8: 16 - }, - ENTRY_SIZE: { - STANDARD: 12, - BIG: 20 - }, - COUNT_SIZE: { - STANDARD: 2, - BIG: 8 - } -}; -function readIFD(input, { isBigEndian, isBigTiff }) { - const ifdOffset = isBigTiff ? Number(readUInt64(input, 8, isBigEndian)) : readUInt(input, 32, 4, isBigEndian); - const entryCountSize = isBigTiff ? CONSTANTS.COUNT_SIZE.BIG : CONSTANTS.COUNT_SIZE.STANDARD; - return input.slice(ifdOffset + entryCountSize); -} -function readTagValue(input, type, offset, isBigEndian) { - switch (type) { - case CONSTANTS.TYPE.SHORT: - return readUInt(input, 16, offset, isBigEndian); - case CONSTANTS.TYPE.LONG: - return readUInt(input, 32, offset, isBigEndian); - case CONSTANTS.TYPE.LONG8: { - const value = Number(readUInt64(input, offset, isBigEndian)); - if (value > Number.MAX_SAFE_INTEGER) { - throw new TypeError("Value too large"); - } - return value; - } - default: - return 0; - } -} -function nextTag(input, isBigTiff) { - const entrySize = isBigTiff ? CONSTANTS.ENTRY_SIZE.BIG : CONSTANTS.ENTRY_SIZE.STANDARD; - if (input.length > entrySize) { - return input.slice(entrySize); - } -} -function extractTags(input, { isBigEndian, isBigTiff }) { - const tags = {}; - let temp = input; - while (temp?.length) { - const code = readUInt(temp, 16, 0, isBigEndian); - const type = readUInt(temp, 16, 2, isBigEndian); - const length = isBigTiff ? Number(readUInt64(temp, 4, isBigEndian)) : readUInt(temp, 32, 4, isBigEndian); - if (code === 0) break; - if (length === 1 && (type === CONSTANTS.TYPE.SHORT || type === CONSTANTS.TYPE.LONG || isBigTiff && type === CONSTANTS.TYPE.LONG8)) { - const valueOffset = isBigTiff ? 12 : 8; - tags[code] = readTagValue(temp, type, valueOffset, isBigEndian); - } - temp = nextTag(temp, isBigTiff); - } - return tags; -} -function determineFormat(input) { - const signature = toUTF8String(input, 0, 2); - const version = readUInt(input, 16, 2, signature === "MM"); - return { - isBigEndian: signature === "MM", - isBigTiff: version === 43 - }; -} -function validateBigTIFFHeader(input, isBigEndian) { - const byteSize = readUInt(input, 16, 4, isBigEndian); - const reserved = readUInt(input, 16, 6, isBigEndian); - if (byteSize !== 8 || reserved !== 0) { - throw new TypeError("Invalid BigTIFF header"); - } -} -const signatures = /* @__PURE__ */ new Set([ - "49492a00", - // Little Endian - "4d4d002a", - // Big Endian - "49492b00", - // BigTIFF Little Endian - "4d4d002b" - // BigTIFF Big Endian -]); -const TIFF = { - validate: (input) => { - const signature = toHexString(input, 0, 4); - return signatures.has(signature); - }, - calculate(input) { - const format = determineFormat(input); - if (format.isBigTiff) { - validateBigTIFFHeader(input, format.isBigEndian); - } - const ifdBuffer = readIFD(input, format); - const tags = extractTags(ifdBuffer, format); - const info = { - height: tags[CONSTANTS.TAG.HEIGHT], - width: tags[CONSTANTS.TAG.WIDTH], - type: format.isBigTiff ? "bigtiff" : "tiff" - }; - if (tags[CONSTANTS.TAG.COMPRESSION]) { - info.compression = tags[CONSTANTS.TAG.COMPRESSION]; - } - if (!info.width || !info.height) { - throw new TypeError("Invalid Tiff. Missing tags"); - } - return info; - } -}; - -function calculateExtended(input) { - return { - height: 1 + readUInt24LE(input, 7), - width: 1 + readUInt24LE(input, 4) - }; -} -function calculateLossless(input) { - return { - height: 1 + ((input[4] & 15) << 10 | input[3] << 2 | (input[2] & 192) >> 6), - width: 1 + ((input[2] & 63) << 8 | input[1]) - }; -} -function calculateLossy(input) { - return { - height: readInt16LE(input, 8) & 16383, - width: readInt16LE(input, 6) & 16383 - }; -} -const WEBP = { - validate(input) { - const riffHeader = "RIFF" === toUTF8String(input, 0, 4); - const webpHeader = "WEBP" === toUTF8String(input, 8, 12); - const vp8Header = "VP8" === toUTF8String(input, 12, 15); - return riffHeader && webpHeader && vp8Header; - }, - calculate(_input) { - const chunkHeader = toUTF8String(_input, 12, 16); - const input = _input.slice(20, 30); - if (chunkHeader === "VP8X") { - const extendedHeader = input[0]; - const validStart = (extendedHeader & 192) === 0; - const validEnd = (extendedHeader & 1) === 0; - if (validStart && validEnd) { - return calculateExtended(input); - } - throw new TypeError("Invalid WebP"); - } - if (chunkHeader === "VP8 " && input[0] !== 47) { - return calculateLossy(input); - } - const signature = toHexString(input, 3, 6); - if (chunkHeader === "VP8L" && signature !== "9d012a") { - return calculateLossless(input); - } - throw new TypeError("Invalid WebP"); - } -}; - -const typeHandlers = /* @__PURE__ */ new Map([ - ["bmp", BMP], - ["cur", CUR], - ["dds", DDS], - ["gif", GIF], - ["heif", HEIF], - ["icns", ICNS], - ["ico", ICO], - ["j2c", J2C], - ["jp2", JP2], - ["jpg", JPG], - ["jxl", JXL], - ["jxl-stream", JXLStream], - ["ktx", KTX], - ["png", PNG], - ["pnm", PNM], - ["psd", PSD], - ["svg", SVG], - ["tga", TGA], - ["tiff", TIFF], - ["webp", WEBP] -]); -const types = Array.from(typeHandlers.keys()); - -export { types as a, isRemoteAllowed as i, matchPattern as m, typeHandlers as t }; diff --git a/.vercel/output/_functions/chunks/index_BMBZwZG1.mjs b/.vercel/output/_functions/chunks/index_BMBZwZG1.mjs deleted file mode 100644 index 552862d..0000000 --- a/.vercel/output/_functions/chunks/index_BMBZwZG1.mjs +++ /dev/null @@ -1,2687 +0,0 @@ -import { v as decryptString, w as createSlotValueFromString, x as isAstroComponentFactory, r as renderComponent, a as renderTemplate, n as REROUTE_DIRECTIVE_HEADER, A as AstroError, y as i18nNoLocaleFoundInPath, z as ResponseSentError, B as originPathnameSymbol, C as RewriteWithBodyUsed, G as GetStaticPathsRequired, I as InvalidGetStaticPathsReturn, E as InvalidGetStaticPathsEntry, H as GetStaticPathsExpectedParams, J as GetStaticPathsInvalidRouteParam, P as PageNumberParamNotFound, D as DEFAULT_404_COMPONENT, N as NoMatchingStaticPathFound, K as PrerenderDynamicEndpointPathCollide, M as ReservedSlotName, O as renderSlotToString, Q as renderJSX, S as chunkToString, T as isRenderInstruction, o as ActionNotFoundError, V as MiddlewareNoDataOrNextCalled, W as MiddlewareNotAResponse, X as SessionStorageInitError, Y as SessionStorageSaveError, l as ROUTE_TYPE_HEADER, Z as ForbiddenRewrite, _ as ASTRO_VERSION, $ as CspNotEnabled, a0 as LocalsReassigned, a1 as generateCspDigest, a2 as PrerenderClientAddressNotAvailable, p as clientAddressSymbol, a3 as ClientAddressNotAvailable, a4 as StaticClientAddressNotAvailable, a5 as AstroResponseHeadersReassigned, s as responseSentSymbol$1, a6 as renderPage, a7 as REWRITE_DIRECTIVE_HEADER_KEY, a8 as REWRITE_DIRECTIVE_HEADER_VALUE, a9 as renderEndpoint } from './astro/server_D2NiA7f1.mjs'; -import colors from 'piccolore'; -import 'clsx'; -import 'es-module-lexer'; -import { g as getActionQueryString, a as deserializeActionResult, D as DEFAULT_404_ROUTE, A as ActionError, s as serializeActionResult, b as ACTION_RPC_ROUTE_PATTERN, c as ACTION_QUERY_PARAMS } from './astro-designed-error-pages_C_Ez8g0J.mjs'; -import { b as appendForwardSlash, j as joinPaths, a as removeTrailingForwardSlash, p as prependForwardSlash, t as trimSlashes } from './path_Bl04Vi8h.mjs'; -import { serialize, parse } from 'cookie'; -import { unflatten as unflatten$1, stringify as stringify$1 } from 'devalue'; -import { createStorage, builtinDrivers } from 'unstorage'; - -const ACTION_API_CONTEXT_SYMBOL = Symbol.for("astro.actionAPIContext"); -const formContentTypes = ["application/x-www-form-urlencoded", "multipart/form-data"]; -function hasContentType(contentType, expected) { - const type = contentType.split(";")[0].toLowerCase(); - return expected.some((t) => type === t); -} - -function hasActionPayload(locals) { - return "_actionPayload" in locals; -} -function createGetActionResult(locals) { - return (actionFn) => { - if (!hasActionPayload(locals) || actionFn.toString() !== getActionQueryString(locals._actionPayload.actionName)) { - return void 0; - } - return deserializeActionResult(locals._actionPayload.actionResult); - }; -} -function createCallAction(context) { - return (baseAction, input) => { - Reflect.set(context, ACTION_API_CONTEXT_SYMBOL, true); - const action = baseAction.bind(context); - return action(input); - }; -} - -function shouldAppendForwardSlash(trailingSlash, buildFormat) { - switch (trailingSlash) { - case "always": - return true; - case "never": - return false; - case "ignore": { - switch (buildFormat) { - case "directory": - return true; - case "preserve": - case "file": - return false; - } - } - } -} - -function redirectIsExternal(redirect) { - if (typeof redirect === "string") { - return redirect.startsWith("http://") || redirect.startsWith("https://"); - } else { - return redirect.destination.startsWith("http://") || redirect.destination.startsWith("https://"); - } -} -async function renderRedirect(renderContext) { - const { - request: { method }, - routeData - } = renderContext; - const { redirect, redirectRoute } = routeData; - const status = redirectRoute && typeof redirect === "object" ? redirect.status : method === "GET" ? 301 : 308; - const headers = { location: encodeURI(redirectRouteGenerate(renderContext)) }; - if (redirect && redirectIsExternal(redirect)) { - if (typeof redirect === "string") { - return Response.redirect(redirect, status); - } else { - return Response.redirect(redirect.destination, status); - } - } - return new Response(null, { status, headers }); -} -function redirectRouteGenerate(renderContext) { - const { - params, - routeData: { redirect, redirectRoute } - } = renderContext; - if (typeof redirectRoute !== "undefined") { - return redirectRoute?.generate(params) || redirectRoute?.pathname || "/"; - } else if (typeof redirect === "string") { - if (redirectIsExternal(redirect)) { - return redirect; - } else { - let target = redirect; - for (const param of Object.keys(params)) { - const paramValue = params[param]; - target = target.replace(`[${param}]`, paramValue).replace(`[...${param}]`, paramValue); - } - return target; - } - } else if (typeof redirect === "undefined") { - return "/"; - } - return redirect.destination; -} - -const SERVER_ISLAND_ROUTE = "/_server-islands/[name]"; -const SERVER_ISLAND_COMPONENT = "_server-islands.astro"; -const SERVER_ISLAND_BASE_PREFIX = "_server-islands"; -function badRequest(reason) { - return new Response(null, { - status: 400, - statusText: "Bad request: " + reason - }); -} -async function getRequestData(request) { - switch (request.method) { - case "GET": { - const url = new URL(request.url); - const params = url.searchParams; - if (!params.has("s") || !params.has("e") || !params.has("p")) { - return badRequest("Missing required query parameters."); - } - const encryptedSlots = params.get("s"); - return { - encryptedComponentExport: params.get("e"), - encryptedProps: params.get("p"), - encryptedSlots - }; - } - case "POST": { - try { - const raw = await request.text(); - const data = JSON.parse(raw); - if ("slots" in data && typeof data.slots === "object") { - return badRequest("Plaintext slots are not allowed. Slots must be encrypted."); - } - if ("componentExport" in data && typeof data.componentExport === "string") { - return badRequest( - "Plaintext componentExport is not allowed. componentExport must be encrypted." - ); - } - return data; - } catch (e) { - if (e instanceof SyntaxError) { - return badRequest("Request format is invalid."); - } - throw e; - } - } - default: { - return new Response(null, { status: 405 }); - } - } -} -function createEndpoint(manifest) { - const page = async (result) => { - const params = result.params; - if (!params.name) { - return new Response(null, { - status: 400, - statusText: "Bad request" - }); - } - const componentId = params.name; - const data = await getRequestData(result.request); - if (data instanceof Response) { - return data; - } - const imp = manifest.serverIslandMap?.get(componentId); - if (!imp) { - return new Response(null, { - status: 404, - statusText: "Not found" - }); - } - const key = await manifest.key; - let componentExport; - try { - componentExport = await decryptString(key, data.encryptedComponentExport); - } catch (_e) { - return badRequest("Encrypted componentExport value is invalid."); - } - const encryptedProps = data.encryptedProps; - let props = {}; - if (encryptedProps !== "") { - try { - const propString = await decryptString(key, encryptedProps); - props = JSON.parse(propString); - } catch (_e) { - return badRequest("Encrypted props value is invalid."); - } - } - let decryptedSlots = {}; - const encryptedSlots = data.encryptedSlots; - if (encryptedSlots !== "") { - try { - const slotsString = await decryptString(key, encryptedSlots); - decryptedSlots = JSON.parse(slotsString); - } catch (_e) { - return badRequest("Encrypted slots value is invalid."); - } - } - const componentModule = await imp(); - let Component = componentModule[componentExport]; - const slots = {}; - for (const prop in decryptedSlots) { - slots[prop] = createSlotValueFromString(decryptedSlots[prop]); - } - result.response.headers.set("X-Robots-Tag", "noindex"); - if (isAstroComponentFactory(Component)) { - const ServerIsland = Component; - Component = function(...args) { - return ServerIsland.apply(this, args); - }; - Object.assign(Component, ServerIsland); - Component.propagation = "self"; - } - return renderTemplate`${renderComponent(result, "Component", Component, props, slots)}`; - }; - page.isAstroComponentFactory = true; - const instance = { - default: page, - partial: true - }; - return instance; -} - -function matchRoute(pathname, manifest) { - return manifest.routes.find((route) => { - return route.pattern.test(pathname) || route.fallbackRoutes.some((fallbackRoute) => fallbackRoute.pattern.test(pathname)); - }); -} -const ROUTE404_RE = /^\/404\/?$/; -const ROUTE500_RE = /^\/500\/?$/; -function isRoute404(route) { - return ROUTE404_RE.test(route); -} -function isRoute500(route) { - return ROUTE500_RE.test(route); -} -function isRoute404or500(route) { - return isRoute404(route.route) || isRoute500(route.route); -} -function isRouteServerIsland(route) { - return route.component === SERVER_ISLAND_COMPONENT; -} -function isRequestServerIsland(request, base = "") { - const url = new URL(request.url); - const pathname = base === "/" ? url.pathname.slice(base.length) : url.pathname.slice(base.length + 1); - return pathname.startsWith(SERVER_ISLAND_BASE_PREFIX); -} -function requestIs404Or500(request, base = "") { - const url = new URL(request.url); - const pathname = url.pathname.slice(base.length); - return isRoute404(pathname) || isRoute500(pathname); -} -function isRouteExternalRedirect(route) { - return !!(route.type === "redirect" && route.redirect && redirectIsExternal(route.redirect)); -} - -function requestHasLocale(locales) { - return function(context) { - return pathHasLocale(context.url.pathname, locales); - }; -} -function pathHasLocale(path, locales) { - const segments = path.split("/").map(normalizeThePath); - for (const segment of segments) { - for (const locale of locales) { - if (typeof locale === "string") { - if (normalizeTheLocale(segment) === normalizeTheLocale(locale)) { - return true; - } - } else if (segment === locale.path) { - return true; - } - } - } - return false; -} -function getPathByLocale(locale, locales) { - for (const loopLocale of locales) { - if (typeof loopLocale === "string") { - if (loopLocale === locale) { - return loopLocale; - } - } else { - for (const code of loopLocale.codes) { - if (code === locale) { - return loopLocale.path; - } - } - } - } - throw new AstroError(i18nNoLocaleFoundInPath); -} -function normalizeTheLocale(locale) { - return locale.replaceAll("_", "-").toLowerCase(); -} -function normalizeThePath(path) { - return path.endsWith(".html") ? path.slice(0, -5) : path; -} -function getAllCodes(locales) { - const result = []; - for (const loopLocale of locales) { - if (typeof loopLocale === "string") { - result.push(loopLocale); - } else { - result.push(...loopLocale.codes); - } - } - return result; -} -function redirectToDefaultLocale({ - trailingSlash, - format, - base, - defaultLocale -}) { - return function(context, statusCode) { - if (shouldAppendForwardSlash(trailingSlash, format)) { - return context.redirect(`${appendForwardSlash(joinPaths(base, defaultLocale))}`, statusCode); - } else { - return context.redirect(`${joinPaths(base, defaultLocale)}`, statusCode); - } - }; -} -function notFound({ base, locales, fallback }) { - return function(context, response) { - if (response?.headers.get(REROUTE_DIRECTIVE_HEADER) === "no" && typeof fallback === "undefined") { - return response; - } - const url = context.url; - const isRoot = url.pathname === base + "/" || url.pathname === base; - if (!(isRoot || pathHasLocale(url.pathname, locales))) { - if (response) { - response.headers.set(REROUTE_DIRECTIVE_HEADER, "no"); - return new Response(response.body, { - status: 404, - headers: response.headers - }); - } else { - return new Response(null, { - status: 404, - headers: { - [REROUTE_DIRECTIVE_HEADER]: "no" - } - }); - } - } - return void 0; - }; -} -function redirectToFallback({ - fallback, - locales, - defaultLocale, - strategy, - base, - fallbackType -}) { - return async function(context, response) { - if (response.status >= 300 && fallback) { - const fallbackKeys = fallback ? Object.keys(fallback) : []; - const segments = context.url.pathname.split("/"); - const urlLocale = segments.find((segment) => { - for (const locale of locales) { - if (typeof locale === "string") { - if (locale === segment) { - return true; - } - } else if (locale.path === segment) { - return true; - } - } - return false; - }); - if (urlLocale && fallbackKeys.includes(urlLocale)) { - const fallbackLocale = fallback[urlLocale]; - const pathFallbackLocale = getPathByLocale(fallbackLocale, locales); - let newPathname; - if (pathFallbackLocale === defaultLocale && strategy === "pathname-prefix-other-locales") { - if (context.url.pathname.includes(`${base}`)) { - newPathname = context.url.pathname.replace(`/${urlLocale}`, ``); - if (newPathname === "") { - newPathname = "/"; - } - } else { - newPathname = context.url.pathname.replace(`/${urlLocale}`, `/`); - } - } else { - newPathname = context.url.pathname.replace(`/${urlLocale}`, `/${pathFallbackLocale}`); - } - if (fallbackType === "rewrite") { - return await context.rewrite(newPathname + context.url.search); - } else { - return context.redirect(newPathname + context.url.search); - } - } - } - return response; - }; -} - -function parseLocale(header) { - if (header === "*") { - return [{ locale: header, qualityValue: void 0 }]; - } - const result = []; - const localeValues = header.split(",").map((str) => str.trim()); - for (const localeValue of localeValues) { - const split = localeValue.split(";").map((str) => str.trim()); - const localeName = split[0]; - const qualityValue = split[1]; - if (!split) { - continue; - } - if (qualityValue && qualityValue.startsWith("q=")) { - const qualityValueAsFloat = Number.parseFloat(qualityValue.slice("q=".length)); - if (Number.isNaN(qualityValueAsFloat) || qualityValueAsFloat > 1) { - result.push({ - locale: localeName, - qualityValue: void 0 - }); - } else { - result.push({ - locale: localeName, - qualityValue: qualityValueAsFloat - }); - } - } else { - result.push({ - locale: localeName, - qualityValue: void 0 - }); - } - } - return result; -} -function sortAndFilterLocales(browserLocaleList, locales) { - const normalizedLocales = getAllCodes(locales).map(normalizeTheLocale); - return browserLocaleList.filter((browserLocale) => { - if (browserLocale.locale !== "*") { - return normalizedLocales.includes(normalizeTheLocale(browserLocale.locale)); - } - return true; - }).sort((a, b) => { - if (a.qualityValue && b.qualityValue) { - return Math.sign(b.qualityValue - a.qualityValue); - } - return 0; - }); -} -function computePreferredLocale(request, locales) { - const acceptHeader = request.headers.get("Accept-Language"); - let result = void 0; - if (acceptHeader) { - const browserLocaleList = sortAndFilterLocales(parseLocale(acceptHeader), locales); - const firstResult = browserLocaleList.at(0); - if (firstResult && firstResult.locale !== "*") { - for (const currentLocale of locales) { - if (typeof currentLocale === "string") { - if (normalizeTheLocale(currentLocale) === normalizeTheLocale(firstResult.locale)) { - result = currentLocale; - break; - } - } else { - for (const currentCode of currentLocale.codes) { - if (normalizeTheLocale(currentCode) === normalizeTheLocale(firstResult.locale)) { - result = currentCode; - break; - } - } - } - } - } - } - return result; -} -function computePreferredLocaleList(request, locales) { - const acceptHeader = request.headers.get("Accept-Language"); - let result = []; - if (acceptHeader) { - const browserLocaleList = sortAndFilterLocales(parseLocale(acceptHeader), locales); - if (browserLocaleList.length === 1 && browserLocaleList.at(0).locale === "*") { - return getAllCodes(locales); - } else if (browserLocaleList.length > 0) { - for (const browserLocale of browserLocaleList) { - for (const loopLocale of locales) { - if (typeof loopLocale === "string") { - if (normalizeTheLocale(loopLocale) === normalizeTheLocale(browserLocale.locale)) { - result.push(loopLocale); - } - } else { - for (const code of loopLocale.codes) { - if (code === browserLocale.locale) { - result.push(code); - } - } - } - } - } - } - } - return result; -} -function computeCurrentLocale(pathname, locales, defaultLocale) { - for (const segment of pathname.split("/").map(normalizeThePath)) { - for (const locale of locales) { - if (typeof locale === "string") { - if (!segment.includes(locale)) continue; - if (normalizeTheLocale(locale) === normalizeTheLocale(segment)) { - return locale; - } - } else { - if (locale.path === segment) { - return locale.codes.at(0); - } else { - for (const code of locale.codes) { - if (normalizeTheLocale(code) === normalizeTheLocale(segment)) { - return code; - } - } - } - } - } - } - for (const locale of locales) { - if (typeof locale === "string") { - if (locale === defaultLocale) { - return locale; - } - } else { - if (locale.path === defaultLocale) { - return locale.codes.at(0); - } - } - } -} - -const DELETED_EXPIRATION = /* @__PURE__ */ new Date(0); -const DELETED_VALUE = "deleted"; -const responseSentSymbol = Symbol.for("astro.responseSent"); -const identity = (value) => value; -class AstroCookie { - constructor(value) { - this.value = value; - } - json() { - if (this.value === void 0) { - throw new Error(`Cannot convert undefined to an object.`); - } - return JSON.parse(this.value); - } - number() { - return Number(this.value); - } - boolean() { - if (this.value === "false") return false; - if (this.value === "0") return false; - return Boolean(this.value); - } -} -class AstroCookies { - #request; - #requestValues; - #outgoing; - #consumed; - constructor(request) { - this.#request = request; - this.#requestValues = null; - this.#outgoing = null; - this.#consumed = false; - } - /** - * Astro.cookies.delete(key) is used to delete a cookie. Using this method will result - * in a Set-Cookie header added to the response. - * @param key The cookie to delete - * @param options Options related to this deletion, such as the path of the cookie. - */ - delete(key, options) { - const { - // @ts-expect-error - maxAge: _ignoredMaxAge, - // @ts-expect-error - expires: _ignoredExpires, - ...sanitizedOptions - } = options || {}; - const serializeOptions = { - expires: DELETED_EXPIRATION, - ...sanitizedOptions - }; - this.#ensureOutgoingMap().set(key, [ - DELETED_VALUE, - serialize(key, DELETED_VALUE, serializeOptions), - false - ]); - } - /** - * Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the - * request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken - * from that set call, overriding any values already part of the request. - * @param key The cookie to get. - * @returns An object containing the cookie value as well as convenience methods for converting its value. - */ - get(key, options = void 0) { - if (this.#outgoing?.has(key)) { - let [serializedValue, , isSetValue] = this.#outgoing.get(key); - if (isSetValue) { - return new AstroCookie(serializedValue); - } else { - return void 0; - } - } - const decode = options?.decode ?? decodeURIComponent; - const values = this.#ensureParsed(); - if (key in values) { - const value = values[key]; - if (value) { - let decodedValue; - try { - decodedValue = decode(value); - } catch (_error) { - decodedValue = value; - } - return new AstroCookie(decodedValue); - } - } - } - /** - * Astro.cookies.has(key) returns a boolean indicating whether this cookie is either - * part of the initial request or set via Astro.cookies.set(key) - * @param key The cookie to check for. - * @param _options This parameter is no longer used. - * @returns - */ - has(key, _options) { - if (this.#outgoing?.has(key)) { - let [, , isSetValue] = this.#outgoing.get(key); - return isSetValue; - } - const values = this.#ensureParsed(); - return values[key] !== void 0; - } - /** - * Astro.cookies.set(key, value) is used to set a cookie's value. If provided - * an object it will be stringified via JSON.stringify(value). Additionally you - * can provide options customizing how this cookie will be set, such as setting httpOnly - * in order to prevent the cookie from being read in client-side JavaScript. - * @param key The name of the cookie to set. - * @param value A value, either a string or other primitive or an object. - * @param options Options for the cookie, such as the path and security settings. - */ - set(key, value, options) { - if (this.#consumed) { - const warning = new Error( - "Astro.cookies.set() was called after the cookies had already been sent to the browser.\nThis may have happened if this method was called in an imported component.\nPlease make sure that Astro.cookies.set() is only called in the frontmatter of the main page." - ); - warning.name = "Warning"; - console.warn(warning); - } - let serializedValue; - if (typeof value === "string") { - serializedValue = value; - } else { - let toStringValue = value.toString(); - if (toStringValue === Object.prototype.toString.call(value)) { - serializedValue = JSON.stringify(value); - } else { - serializedValue = toStringValue; - } - } - const serializeOptions = {}; - if (options) { - Object.assign(serializeOptions, options); - } - this.#ensureOutgoingMap().set(key, [ - serializedValue, - serialize(key, serializedValue, serializeOptions), - true - ]); - if (this.#request[responseSentSymbol]) { - throw new AstroError({ - ...ResponseSentError - }); - } - } - /** - * Merges a new AstroCookies instance into the current instance. Any new cookies - * will be added to the current instance, overwriting any existing cookies with the same name. - */ - merge(cookies) { - const outgoing = cookies.#outgoing; - if (outgoing) { - for (const [key, value] of outgoing) { - this.#ensureOutgoingMap().set(key, value); - } - } - } - /** - * Astro.cookies.header() returns an iterator for the cookies that have previously - * been set by either Astro.cookies.set() or Astro.cookies.delete(). - * This method is primarily used by adapters to set the header on outgoing responses. - * @returns - */ - *headers() { - if (this.#outgoing == null) return; - for (const [, value] of this.#outgoing) { - yield value[1]; - } - } - /** - * Behaves the same as AstroCookies.prototype.headers(), - * but allows a warning when cookies are set after the instance is consumed. - */ - static consume(cookies) { - cookies.#consumed = true; - return cookies.headers(); - } - #ensureParsed() { - if (!this.#requestValues) { - this.#parse(); - } - if (!this.#requestValues) { - this.#requestValues = {}; - } - return this.#requestValues; - } - #ensureOutgoingMap() { - if (!this.#outgoing) { - this.#outgoing = /* @__PURE__ */ new Map(); - } - return this.#outgoing; - } - #parse() { - const raw = this.#request.headers.get("cookie"); - if (!raw) { - return; - } - this.#requestValues = parse(raw, { decode: identity }); - } -} - -const astroCookiesSymbol = Symbol.for("astro.cookies"); -function attachCookiesToResponse(response, cookies) { - Reflect.set(response, astroCookiesSymbol, cookies); -} -function getCookiesFromResponse(response) { - let cookies = Reflect.get(response, astroCookiesSymbol); - if (cookies != null) { - return cookies; - } else { - return void 0; - } -} -function* getSetCookiesFromResponse(response) { - const cookies = getCookiesFromResponse(response); - if (!cookies) { - return []; - } - for (const headerValue of AstroCookies.consume(cookies)) { - yield headerValue; - } - return []; -} - -function createRequest({ - url, - headers, - method = "GET", - body = void 0, - logger, - isPrerendered = false, - routePattern, - init -}) { - const headersObj = isPrerendered ? void 0 : headers instanceof Headers ? headers : new Headers( - // Filter out HTTP/2 pseudo-headers. These are internally-generated headers added to all HTTP/2 requests with trusted metadata about the request. - // Examples include `:method`, `:scheme`, `:authority`, and `:path`. - // They are always prefixed with a colon to distinguish them from other headers, and it is an error to add the to a Headers object manually. - // See https://httpwg.org/specs/rfc7540.html#HttpRequest - Object.entries(headers).filter(([name]) => !name.startsWith(":")) - ); - if (typeof url === "string") url = new URL(url); - if (isPrerendered) { - url.search = ""; - } - const request = new Request(url, { - method, - headers: headersObj, - // body is made available only if the request is for a page that will be on-demand rendered - body: isPrerendered ? null : body, - ...init - }); - if (isPrerendered) { - let _headers = request.headers; - const { value, writable, ...headersDesc } = Object.getOwnPropertyDescriptor(request, "headers") || {}; - Object.defineProperty(request, "headers", { - ...headersDesc, - get() { - logger.warn( - null, - `\`Astro.request.headers\` was used when rendering the route \`${routePattern}'\`. \`Astro.request.headers\` is not available on prerendered pages. If you need access to request headers, make sure that the page is server-rendered using \`export const prerender = false;\` or by setting \`output\` to \`"server"\` in your Astro config to make all your pages server-rendered by default.` - ); - return _headers; - }, - set(newHeaders) { - _headers = newHeaders; - } - }); - } - return request; -} - -function findRouteToRewrite({ - payload, - routes, - request, - trailingSlash, - buildFormat, - base, - outDir -}) { - let newUrl = void 0; - if (payload instanceof URL) { - newUrl = payload; - } else if (payload instanceof Request) { - newUrl = new URL(payload.url); - } else { - newUrl = new URL(payload, new URL(request.url).origin); - } - let pathname = newUrl.pathname; - const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); - if (base !== "/") { - const isBasePathRequest = newUrl.pathname === base || newUrl.pathname === removeTrailingForwardSlash(base); - if (isBasePathRequest) { - pathname = shouldAppendSlash ? "/" : ""; - } else if (newUrl.pathname.startsWith(base)) { - pathname = shouldAppendSlash ? appendForwardSlash(newUrl.pathname) : removeTrailingForwardSlash(newUrl.pathname); - pathname = pathname.slice(base.length); - } - } - if (!pathname.startsWith("/") && shouldAppendSlash && newUrl.pathname.endsWith("/")) { - pathname = prependForwardSlash(pathname); - } - if (pathname === "/" && base !== "/" && !shouldAppendSlash) { - pathname = ""; - } - if (buildFormat === "file") { - pathname = pathname.replace(/\.html$/, ""); - } - if (base !== "/" && (pathname === "" || pathname === "/") && !shouldAppendSlash) { - newUrl.pathname = removeTrailingForwardSlash(base); - } else { - newUrl.pathname = joinPaths(...[base, pathname].filter(Boolean)); - } - const decodedPathname = decodeURI(pathname); - let foundRoute; - for (const route of routes) { - if (route.pattern.test(decodedPathname)) { - if (route.params && route.params.length !== 0 && route.distURL && route.distURL.length !== 0) { - if (!route.distURL.find( - (url) => url.href.replace(outDir.toString(), "").replace(/(?:\/index\.html|\.html)$/, "") == trimSlashes(decodedPathname) - )) { - continue; - } - } - foundRoute = route; - break; - } - } - if (foundRoute) { - return { - routeData: foundRoute, - newUrl, - pathname: decodedPathname - }; - } else { - const custom404 = routes.find((route) => route.route === "/404"); - if (custom404) { - return { routeData: custom404, newUrl, pathname }; - } else { - return { routeData: DEFAULT_404_ROUTE, newUrl, pathname }; - } - } -} -function copyRequest(newUrl, oldRequest, isPrerendered, logger, routePattern) { - if (oldRequest.bodyUsed) { - throw new AstroError(RewriteWithBodyUsed); - } - return createRequest({ - url: newUrl, - method: oldRequest.method, - body: oldRequest.body, - isPrerendered, - logger, - headers: isPrerendered ? {} : oldRequest.headers, - routePattern, - init: { - referrer: oldRequest.referrer, - referrerPolicy: oldRequest.referrerPolicy, - mode: oldRequest.mode, - credentials: oldRequest.credentials, - cache: oldRequest.cache, - redirect: oldRequest.redirect, - integrity: oldRequest.integrity, - signal: oldRequest.signal, - keepalive: oldRequest.keepalive, - // https://fetch.spec.whatwg.org/#dom-request-duplex - // @ts-expect-error It isn't part of the types, but undici accepts it and it allows to carry over the body to a new request - duplex: "half" - } - }); -} -function setOriginPathname(request, pathname, trailingSlash, buildFormat) { - if (!pathname) { - pathname = "/"; - } - const shouldAppendSlash = shouldAppendForwardSlash(trailingSlash, buildFormat); - let finalPathname; - if (pathname === "/") { - finalPathname = "/"; - } else if (shouldAppendSlash) { - finalPathname = appendForwardSlash(pathname); - } else { - finalPathname = removeTrailingForwardSlash(pathname); - } - Reflect.set(request, originPathnameSymbol, encodeURIComponent(finalPathname)); -} -function getOriginPathname(request) { - const origin = Reflect.get(request, originPathnameSymbol); - if (origin) { - return decodeURIComponent(origin); - } - return new URL(request.url).pathname; -} - -const VALID_PARAM_TYPES = ["string", "number", "undefined"]; -function validateGetStaticPathsParameter([key, value], route) { - if (!VALID_PARAM_TYPES.includes(typeof value)) { - throw new AstroError({ - ...GetStaticPathsInvalidRouteParam, - message: GetStaticPathsInvalidRouteParam.message(key, value, typeof value), - location: { - file: route - } - }); - } -} -function validateDynamicRouteModule(mod, { - ssr, - route -}) { - if ((!ssr || route.prerender) && !mod.getStaticPaths) { - throw new AstroError({ - ...GetStaticPathsRequired, - location: { file: route.component } - }); - } -} -function validateGetStaticPathsResult(result, logger, route) { - if (!Array.isArray(result)) { - throw new AstroError({ - ...InvalidGetStaticPathsReturn, - message: InvalidGetStaticPathsReturn.message(typeof result), - location: { - file: route.component - } - }); - } - result.forEach((pathObject) => { - if (typeof pathObject === "object" && Array.isArray(pathObject) || pathObject === null) { - throw new AstroError({ - ...InvalidGetStaticPathsEntry, - message: InvalidGetStaticPathsEntry.message( - Array.isArray(pathObject) ? "array" : typeof pathObject - ) - }); - } - if (pathObject.params === void 0 || pathObject.params === null || pathObject.params && Object.keys(pathObject.params).length === 0) { - throw new AstroError({ - ...GetStaticPathsExpectedParams, - location: { - file: route.component - } - }); - } - for (const [key, val] of Object.entries(pathObject.params)) { - if (!(typeof val === "undefined" || typeof val === "string" || typeof val === "number")) { - logger.warn( - "router", - `getStaticPaths() returned an invalid path param: "${key}". A string, number or undefined value was expected, but got \`${JSON.stringify( - val - )}\`.` - ); - } - if (typeof val === "string" && val === "") { - logger.warn( - "router", - `getStaticPaths() returned an invalid path param: "${key}". \`undefined\` expected for an optional param, but got empty string.` - ); - } - } - }); -} - -function stringifyParams(params, route) { - const validatedParams = Object.entries(params).reduce((acc, next) => { - validateGetStaticPathsParameter(next, route.component); - const [key, value] = next; - if (value !== void 0) { - acc[key] = typeof value === "string" ? trimSlashes(value) : value.toString(); - } - return acc; - }, {}); - return route.generate(validatedParams); -} - -function generatePaginateFunction(routeMatch, base) { - return function paginateUtility(data, args = {}) { - let { pageSize: _pageSize, params: _params, props: _props } = args; - const pageSize = _pageSize || 10; - const paramName = "page"; - const additionalParams = _params || {}; - const additionalProps = _props || {}; - let includesFirstPageNumber; - if (routeMatch.params.includes(`...${paramName}`)) { - includesFirstPageNumber = false; - } else if (routeMatch.params.includes(`${paramName}`)) { - includesFirstPageNumber = true; - } else { - throw new AstroError({ - ...PageNumberParamNotFound, - message: PageNumberParamNotFound.message(paramName) - }); - } - const lastPage = Math.max(1, Math.ceil(data.length / pageSize)); - const result = [...Array(lastPage).keys()].map((num) => { - const pageNum = num + 1; - const start = pageSize === Infinity ? 0 : (pageNum - 1) * pageSize; - const end = Math.min(start + pageSize, data.length); - const params = { - ...additionalParams, - [paramName]: includesFirstPageNumber || pageNum > 1 ? String(pageNum) : void 0 - }; - const current = addRouteBase(routeMatch.generate({ ...params }), base); - const next = pageNum === lastPage ? void 0 : addRouteBase(routeMatch.generate({ ...params, page: String(pageNum + 1) }), base); - const prev = pageNum === 1 ? void 0 : addRouteBase( - routeMatch.generate({ - ...params, - page: !includesFirstPageNumber && pageNum - 1 === 1 ? void 0 : String(pageNum - 1) - }), - base - ); - const first = pageNum === 1 ? void 0 : addRouteBase( - routeMatch.generate({ - ...params, - page: includesFirstPageNumber ? "1" : void 0 - }), - base - ); - const last = pageNum === lastPage ? void 0 : addRouteBase(routeMatch.generate({ ...params, page: String(lastPage) }), base); - return { - params, - props: { - ...additionalProps, - page: { - data: data.slice(start, end), - start, - end: end - 1, - size: pageSize, - total: data.length, - currentPage: pageNum, - lastPage, - url: { current, next, prev, first, last } - } - } - }; - }); - return result; - }; -} -function addRouteBase(route, base) { - let routeWithBase = joinPaths(base, route); - if (routeWithBase === "") routeWithBase = "/"; - return routeWithBase; -} - -async function callGetStaticPaths({ - mod, - route, - routeCache, - logger, - ssr, - base -}) { - const cached = routeCache.get(route); - if (!mod) { - throw new Error("This is an error caused by Astro and not your code. Please file an issue."); - } - if (cached?.staticPaths) { - return cached.staticPaths; - } - validateDynamicRouteModule(mod, { ssr, route }); - if (ssr && !route.prerender) { - const entry = Object.assign([], { keyed: /* @__PURE__ */ new Map() }); - routeCache.set(route, { ...cached, staticPaths: entry }); - return entry; - } - let staticPaths = []; - if (!mod.getStaticPaths) { - throw new Error("Unexpected Error."); - } - staticPaths = await mod.getStaticPaths({ - // Q: Why the cast? - // A: So users downstream can have nicer typings, we have to make some sacrifice in our internal typings, which necessitate a cast here - paginate: generatePaginateFunction(route, base), - routePattern: route.route - }); - validateGetStaticPathsResult(staticPaths, logger, route); - const keyedStaticPaths = staticPaths; - keyedStaticPaths.keyed = /* @__PURE__ */ new Map(); - for (const sp of keyedStaticPaths) { - const paramsKey = stringifyParams(sp.params, route); - keyedStaticPaths.keyed.set(paramsKey, sp); - } - routeCache.set(route, { ...cached, staticPaths: keyedStaticPaths }); - return keyedStaticPaths; -} -class RouteCache { - logger; - cache = {}; - runtimeMode; - constructor(logger, runtimeMode = "production") { - this.logger = logger; - this.runtimeMode = runtimeMode; - } - /** Clear the cache. */ - clearAll() { - this.cache = {}; - } - set(route, entry) { - const key = this.key(route); - if (this.runtimeMode === "production" && this.cache[key]?.staticPaths) { - this.logger.warn(null, `Internal Warning: route cache overwritten. (${key})`); - } - this.cache[key] = entry; - } - get(route) { - return this.cache[this.key(route)]; - } - key(route) { - return `${route.route}_${route.component}`; - } -} -function findPathItemByKey(staticPaths, params, route, logger) { - const paramsKey = stringifyParams(params, route); - const matchedStaticPath = staticPaths.keyed.get(paramsKey); - if (matchedStaticPath) { - return matchedStaticPath; - } - logger.debug("router", `findPathItemByKey() - Unexpected cache miss looking for ${paramsKey}`); -} - -function routeIsRedirect(route) { - return route?.type === "redirect"; -} -function routeIsFallback(route) { - return route?.type === "fallback"; -} - -async function getProps(opts) { - const { logger, mod, routeData: route, routeCache, pathname, serverLike, base } = opts; - if (!route || route.pathname) { - return {}; - } - if (routeIsRedirect(route) || routeIsFallback(route) || route.component === DEFAULT_404_COMPONENT) { - return {}; - } - const staticPaths = await callGetStaticPaths({ - mod, - route, - routeCache, - logger, - ssr: serverLike, - base - }); - const params = getParams(route, pathname); - const matchedStaticPath = findPathItemByKey(staticPaths, params, route, logger); - if (!matchedStaticPath && (serverLike ? route.prerender : true)) { - throw new AstroError({ - ...NoMatchingStaticPathFound, - message: NoMatchingStaticPathFound.message(pathname), - hint: NoMatchingStaticPathFound.hint([route.component]) - }); - } - if (mod) { - validatePrerenderEndpointCollision(route, mod, params); - } - const props = matchedStaticPath?.props ? { ...matchedStaticPath.props } : {}; - return props; -} -function getParams(route, pathname) { - if (!route.params.length) return {}; - const paramsMatch = route.pattern.exec(pathname) || route.fallbackRoutes.map((fallbackRoute) => fallbackRoute.pattern.exec(pathname)).find((x) => x); - if (!paramsMatch) return {}; - const params = {}; - route.params.forEach((key, i) => { - if (key.startsWith("...")) { - params[key.slice(3)] = paramsMatch[i + 1] ? paramsMatch[i + 1] : void 0; - } else { - params[key] = paramsMatch[i + 1]; - } - }); - return params; -} -function validatePrerenderEndpointCollision(route, mod, params) { - if (route.type === "endpoint" && mod.getStaticPaths) { - const lastSegment = route.segments[route.segments.length - 1]; - const paramValues = Object.values(params); - const lastParam = paramValues[paramValues.length - 1]; - if (lastSegment.length === 1 && lastSegment[0].dynamic && lastParam === void 0) { - throw new AstroError({ - ...PrerenderDynamicEndpointPathCollide, - message: PrerenderDynamicEndpointPathCollide.message(route.route), - hint: PrerenderDynamicEndpointPathCollide.hint(route.component), - location: { - file: route.component - } - }); - } - } -} - -function getFunctionExpression(slot) { - if (!slot) return; - const expressions = slot?.expressions?.filter((e) => isRenderInstruction(e) === false); - if (expressions?.length !== 1) return; - return expressions[0]; -} -class Slots { - #result; - #slots; - #logger; - constructor(result, slots, logger) { - this.#result = result; - this.#slots = slots; - this.#logger = logger; - if (slots) { - for (const key of Object.keys(slots)) { - if (this[key] !== void 0) { - throw new AstroError({ - ...ReservedSlotName, - message: ReservedSlotName.message(key) - }); - } - Object.defineProperty(this, key, { - get() { - return true; - }, - enumerable: true - }); - } - } - } - has(name) { - if (!this.#slots) return false; - return Boolean(this.#slots[name]); - } - async render(name, args = []) { - if (!this.#slots || !this.has(name)) return; - const result = this.#result; - if (!Array.isArray(args)) { - this.#logger.warn( - null, - `Expected second parameter to be an array, received a ${typeof args}. If you're trying to pass an array as a single argument and getting unexpected results, make sure you're passing your array as a item of an array. Ex: Astro.slots.render('default', [["Hello", "World"]])` - ); - } else if (args.length > 0) { - const slotValue = this.#slots[name]; - const component = typeof slotValue === "function" ? await slotValue(result) : await slotValue; - const expression = getFunctionExpression(component); - if (expression) { - const slot = async () => typeof expression === "function" ? expression(...args) : expression; - return await renderSlotToString(result, slot).then((res) => { - return res; - }); - } - if (typeof component === "function") { - return await renderJSX(result, component(...args)).then( - (res) => res != null ? String(res) : res - ); - } - } - const content = await renderSlotToString(result, this.#slots[name]); - const outHTML = chunkToString(result, content); - return outHTML; - } -} - -function getActionContext(context) { - const callerInfo = getCallerInfo(context); - const actionResultAlreadySet = Boolean(context.locals._actionPayload); - let action = void 0; - if (callerInfo && context.request.method === "POST" && !actionResultAlreadySet) { - action = { - calledFrom: callerInfo.from, - name: callerInfo.name, - handler: async () => { - const pipeline = Reflect.get(context, apiContextRoutesSymbol); - const callerInfoName = shouldAppendForwardSlash( - pipeline.manifest.trailingSlash, - pipeline.manifest.buildFormat - ) ? removeTrailingForwardSlash(callerInfo.name) : callerInfo.name; - let baseAction; - try { - baseAction = await pipeline.getAction(callerInfoName); - } catch (error) { - if (error instanceof Error && "name" in error && typeof error.name === "string" && error.name === ActionNotFoundError.name) { - return { data: void 0, error: new ActionError({ code: "NOT_FOUND" }) }; - } - throw error; - } - const bodySizeLimit = pipeline.manifest.actionBodySizeLimit; - let input; - try { - input = await parseRequestBody(context.request, bodySizeLimit); - } catch (e) { - if (e instanceof ActionError) { - return { data: void 0, error: e }; - } - if (e instanceof TypeError) { - return { data: void 0, error: new ActionError({ code: "UNSUPPORTED_MEDIA_TYPE" }) }; - } - throw e; - } - const omitKeys = ["props", "getActionResult", "callAction", "redirect"]; - const actionAPIContext = Object.create( - Object.getPrototypeOf(context), - Object.fromEntries( - Object.entries(Object.getOwnPropertyDescriptors(context)).filter( - ([key]) => !omitKeys.includes(key) - ) - ) - ); - Reflect.set(actionAPIContext, ACTION_API_CONTEXT_SYMBOL, true); - const handler = baseAction.bind(actionAPIContext); - return handler(input); - } - }; - } - function setActionResult(actionName, actionResult) { - context.locals._actionPayload = { - actionResult, - actionName - }; - } - return { - action, - setActionResult, - serializeActionResult, - deserializeActionResult - }; -} -function getCallerInfo(ctx) { - if (ctx.routePattern === ACTION_RPC_ROUTE_PATTERN) { - return { from: "rpc", name: ctx.url.pathname.replace(/^.*\/_actions\//, "") }; - } - const queryParam = ctx.url.searchParams.get(ACTION_QUERY_PARAMS.actionName); - if (queryParam) { - return { from: "form", name: queryParam }; - } - return void 0; -} -async function parseRequestBody(request, bodySizeLimit) { - const contentType = request.headers.get("content-type"); - const contentLengthHeader = request.headers.get("content-length"); - const contentLength = contentLengthHeader ? Number.parseInt(contentLengthHeader, 10) : void 0; - const hasContentLength = typeof contentLength === "number" && Number.isFinite(contentLength); - if (!contentType) return void 0; - if (hasContentLength && contentLength > bodySizeLimit) { - throw new ActionError({ - code: "CONTENT_TOO_LARGE", - message: `Request body exceeds ${bodySizeLimit} bytes` - }); - } - if (hasContentType(contentType, formContentTypes)) { - if (!hasContentLength) { - const body = await readRequestBodyWithLimit(request.clone(), bodySizeLimit); - const formRequest = new Request(request.url, { - method: request.method, - headers: request.headers, - body: toArrayBuffer(body) - }); - return await formRequest.formData(); - } - return await request.clone().formData(); - } - if (hasContentType(contentType, ["application/json"])) { - if (contentLength === 0) return void 0; - if (!hasContentLength) { - const body = await readRequestBodyWithLimit(request.clone(), bodySizeLimit); - if (body.byteLength === 0) return void 0; - return JSON.parse(new TextDecoder().decode(body)); - } - return await request.clone().json(); - } - throw new TypeError("Unsupported content type"); -} -async function readRequestBodyWithLimit(request, limit) { - if (!request.body) return new Uint8Array(); - const reader = request.body.getReader(); - const chunks = []; - let received = 0; - while (true) { - const { done, value } = await reader.read(); - if (done) break; - if (value) { - received += value.byteLength; - if (received > limit) { - throw new ActionError({ - code: "CONTENT_TOO_LARGE", - message: `Request body exceeds ${limit} bytes` - }); - } - chunks.push(value); - } - } - const buffer = new Uint8Array(received); - let offset = 0; - for (const chunk of chunks) { - buffer.set(chunk, offset); - offset += chunk.byteLength; - } - return buffer; -} -function toArrayBuffer(buffer) { - const copy = new Uint8Array(buffer.byteLength); - copy.set(buffer); - return copy.buffer; -} - -function deduplicateDirectiveValues(existingDirective, newDirective) { - const [directiveName, ...existingValues] = existingDirective.split(/\s+/).filter(Boolean); - const [newDirectiveName, ...newValues] = newDirective.split(/\s+/).filter(Boolean); - if (directiveName !== newDirectiveName) { - return void 0; - } - const finalDirectives = Array.from(/* @__PURE__ */ new Set([...existingValues, ...newValues])); - return `${directiveName} ${finalDirectives.join(" ")}`; -} -function pushDirective(directives, newDirective) { - let deduplicated = false; - if (directives.length === 0) { - return [newDirective]; - } - const finalDirectives = []; - for (const directive of directives) { - if (deduplicated) { - finalDirectives.push(directive); - continue; - } - const result = deduplicateDirectiveValues(directive, newDirective); - if (result) { - finalDirectives.push(result); - deduplicated = true; - } else { - finalDirectives.push(directive); - finalDirectives.push(newDirective); - } - } - return finalDirectives; -} - -async function callMiddleware(onRequest, apiContext, responseFunction) { - let nextCalled = false; - let responseFunctionPromise = void 0; - const next = async (payload) => { - nextCalled = true; - responseFunctionPromise = responseFunction(apiContext, payload); - return responseFunctionPromise; - }; - let middlewarePromise = onRequest(apiContext, next); - return await Promise.resolve(middlewarePromise).then(async (value) => { - if (nextCalled) { - if (typeof value !== "undefined") { - if (value instanceof Response === false) { - throw new AstroError(MiddlewareNotAResponse); - } - return value; - } else { - if (responseFunctionPromise) { - return responseFunctionPromise; - } else { - throw new AstroError(MiddlewareNotAResponse); - } - } - } else if (typeof value === "undefined") { - throw new AstroError(MiddlewareNoDataOrNextCalled); - } else if (value instanceof Response === false) { - throw new AstroError(MiddlewareNotAResponse); - } else { - return value; - } - }); -} - -const PERSIST_SYMBOL = Symbol(); -const DEFAULT_COOKIE_NAME = "astro-session"; -const VALID_COOKIE_REGEX = /^[\w-]+$/; -const unflatten = (parsed, _) => { - return unflatten$1(parsed, { - URL: (href) => new URL(href) - }); -}; -const stringify = (data, _) => { - return stringify$1(data, { - // Support URL objects - URL: (val) => val instanceof URL && val.href - }); -}; -class AstroSession { - // The cookies object. - #cookies; - // The session configuration. - #config; - // The cookie config - #cookieConfig; - // The cookie name - #cookieName; - // The unstorage object for the session driver. - #storage; - #data; - // The session ID. A v4 UUID. - #sessionID; - // Sessions to destroy. Needed because we won't have the old session ID after it's destroyed locally. - #toDestroy = /* @__PURE__ */ new Set(); - // Session keys to delete. Used for partial data sets to avoid overwriting the deleted value. - #toDelete = /* @__PURE__ */ new Set(); - // Whether the session is dirty and needs to be saved. - #dirty = false; - // Whether the session cookie has been set. - #cookieSet = false; - // The local data is "partial" if it has not been loaded from storage yet and only - // contains values that have been set or deleted in-memory locally. - // We do this to avoid the need to block on loading data when it is only being set. - // When we load the data from storage, we need to merge it with the local partial data, - // preserving in-memory changes and deletions. - #partial = true; - static #sharedStorage = /* @__PURE__ */ new Map(); - constructor(cookies, { - cookie: cookieConfig = DEFAULT_COOKIE_NAME, - ...config - }, runtimeMode) { - const { driver } = config; - if (!driver) { - throw new AstroError({ - ...SessionStorageInitError, - message: SessionStorageInitError.message( - "No driver was defined in the session configuration and the adapter did not provide a default driver." - ) - }); - } - this.#cookies = cookies; - let cookieConfigObject; - if (typeof cookieConfig === "object") { - const { name = DEFAULT_COOKIE_NAME, ...rest } = cookieConfig; - this.#cookieName = name; - cookieConfigObject = rest; - } else { - this.#cookieName = cookieConfig || DEFAULT_COOKIE_NAME; - } - this.#cookieConfig = { - sameSite: "lax", - secure: runtimeMode === "production", - path: "/", - ...cookieConfigObject, - httpOnly: true - }; - this.#config = { ...config, driver }; - } - /** - * Gets a session value. Returns `undefined` if the session or value does not exist. - */ - async get(key) { - return (await this.#ensureData()).get(key)?.data; - } - /** - * Checks if a session value exists. - */ - async has(key) { - return (await this.#ensureData()).has(key); - } - /** - * Gets all session values. - */ - async keys() { - return (await this.#ensureData()).keys(); - } - /** - * Gets all session values. - */ - async values() { - return [...(await this.#ensureData()).values()].map((entry) => entry.data); - } - /** - * Gets all session entries. - */ - async entries() { - return [...(await this.#ensureData()).entries()].map(([key, entry]) => [key, entry.data]); - } - /** - * Deletes a session value. - */ - delete(key) { - this.#data?.delete(key); - if (this.#partial) { - this.#toDelete.add(key); - } - this.#dirty = true; - } - /** - * Sets a session value. The session is created if it does not exist. - */ - set(key, value, { ttl } = {}) { - if (!key) { - throw new AstroError({ - ...SessionStorageSaveError, - message: "The session key was not provided." - }); - } - let cloned; - try { - cloned = unflatten(JSON.parse(stringify(value))); - } catch (err) { - throw new AstroError( - { - ...SessionStorageSaveError, - message: `The session data for ${key} could not be serialized.`, - hint: "See the devalue library for all supported types: https://github.com/rich-harris/devalue" - }, - { cause: err } - ); - } - if (!this.#cookieSet) { - this.#setCookie(); - this.#cookieSet = true; - } - this.#data ??= /* @__PURE__ */ new Map(); - const lifetime = ttl ?? this.#config.ttl; - const expires = typeof lifetime === "number" ? Date.now() + lifetime * 1e3 : lifetime; - this.#data.set(key, { - data: cloned, - expires - }); - this.#dirty = true; - } - /** - * Destroys the session, clearing the cookie and storage if it exists. - */ - destroy() { - const sessionId = this.#sessionID ?? this.#cookies.get(this.#cookieName)?.value; - if (sessionId) { - this.#toDestroy.add(sessionId); - } - this.#cookies.delete(this.#cookieName, this.#cookieConfig); - this.#sessionID = void 0; - this.#data = void 0; - this.#dirty = true; - } - /** - * Regenerates the session, creating a new session ID. The existing session data is preserved. - */ - async regenerate() { - let data = /* @__PURE__ */ new Map(); - try { - data = await this.#ensureData(); - } catch (err) { - console.error("Failed to load session data during regeneration:", err); - } - const oldSessionId = this.#sessionID; - this.#sessionID = crypto.randomUUID(); - this.#data = data; - await this.#setCookie(); - if (oldSessionId && this.#storage) { - this.#storage.removeItem(oldSessionId).catch((err) => { - console.error("Failed to remove old session data:", err); - }); - } - } - // Persists the session data to storage. - // This is called automatically at the end of the request. - // Uses a symbol to prevent users from calling it directly. - async [PERSIST_SYMBOL]() { - if (!this.#dirty && !this.#toDestroy.size) { - return; - } - const storage = await this.#ensureStorage(); - if (this.#dirty && this.#data) { - const data = await this.#ensureData(); - this.#toDelete.forEach((key2) => data.delete(key2)); - const key = this.#ensureSessionID(); - let serialized; - try { - serialized = stringify(data); - } catch (err) { - throw new AstroError( - { - ...SessionStorageSaveError, - message: SessionStorageSaveError.message( - "The session data could not be serialized.", - this.#config.driver - ) - }, - { cause: err } - ); - } - await storage.setItem(key, serialized); - this.#dirty = false; - } - if (this.#toDestroy.size > 0) { - const cleanupPromises = [...this.#toDestroy].map( - (sessionId) => storage.removeItem(sessionId).catch((err) => { - console.error(`Failed to clean up session ${sessionId}:`, err); - }) - ); - await Promise.all(cleanupPromises); - this.#toDestroy.clear(); - } - } - get sessionID() { - return this.#sessionID; - } - /** - * Loads a session from storage with the given ID, and replaces the current session. - * Any changes made to the current session will be lost. - * This is not normally needed, as the session is automatically loaded using the cookie. - * However it can be used to restore a session where the ID has been recorded somewhere - * else (e.g. in a database). - */ - async load(sessionID) { - this.#sessionID = sessionID; - this.#data = void 0; - await this.#setCookie(); - await this.#ensureData(); - } - /** - * Sets the session cookie. - */ - async #setCookie() { - if (!VALID_COOKIE_REGEX.test(this.#cookieName)) { - throw new AstroError({ - ...SessionStorageSaveError, - message: "Invalid cookie name. Cookie names can only contain letters, numbers, and dashes." - }); - } - const value = this.#ensureSessionID(); - this.#cookies.set(this.#cookieName, value, this.#cookieConfig); - } - /** - * Attempts to load the session data from storage, or creates a new data object if none exists. - * If there is existing partial data, it will be merged into the new data object. - */ - async #ensureData() { - const storage = await this.#ensureStorage(); - if (this.#data && !this.#partial) { - return this.#data; - } - this.#data ??= /* @__PURE__ */ new Map(); - const raw = await storage.get(this.#ensureSessionID()); - if (!raw) { - return this.#data; - } - try { - const storedMap = unflatten(raw); - if (!(storedMap instanceof Map)) { - await this.destroy(); - throw new AstroError({ - ...SessionStorageInitError, - message: SessionStorageInitError.message( - "The session data was an invalid type.", - this.#config.driver - ) - }); - } - const now = Date.now(); - for (const [key, value] of storedMap) { - const expired = typeof value.expires === "number" && value.expires < now; - if (!this.#data.has(key) && !this.#toDelete.has(key) && !expired) { - this.#data.set(key, value); - } - } - this.#partial = false; - return this.#data; - } catch (err) { - await this.destroy(); - if (err instanceof AstroError) { - throw err; - } - throw new AstroError( - { - ...SessionStorageInitError, - message: SessionStorageInitError.message( - "The session data could not be parsed.", - this.#config.driver - ) - }, - { cause: err } - ); - } - } - /** - * Returns the session ID, generating a new one if it does not exist. - */ - #ensureSessionID() { - this.#sessionID ??= this.#cookies.get(this.#cookieName)?.value ?? crypto.randomUUID(); - return this.#sessionID; - } - /** - * Ensures the storage is initialized. - * This is called automatically when a storage operation is needed. - */ - async #ensureStorage() { - if (this.#storage) { - return this.#storage; - } - if (AstroSession.#sharedStorage.has(this.#config.driver)) { - this.#storage = AstroSession.#sharedStorage.get(this.#config.driver); - return this.#storage; - } - if (this.#config.driver === "test") { - this.#storage = this.#config.options.mockStorage; - return this.#storage; - } - if (this.#config.driver === "fs" || this.#config.driver === "fsLite" || this.#config.driver === "fs-lite") { - this.#config.options ??= {}; - this.#config.driver = "fs-lite"; - this.#config.options.base ??= ".astro/session"; - } - let driver = null; - try { - if (this.#config.driverModule) { - driver = (await this.#config.driverModule()).default; - } else if (this.#config.driver) { - const driverName = resolveSessionDriverName(this.#config.driver); - if (driverName) { - driver = (await import(driverName)).default; - } - } - } catch (err) { - if (err.code === "ERR_MODULE_NOT_FOUND") { - throw new AstroError( - { - ...SessionStorageInitError, - message: SessionStorageInitError.message( - err.message.includes(`Cannot find package`) ? "The driver module could not be found." : err.message, - this.#config.driver - ) - }, - { cause: err } - ); - } - throw err; - } - if (!driver) { - throw new AstroError({ - ...SessionStorageInitError, - message: SessionStorageInitError.message( - "The module did not export a driver.", - this.#config.driver - ) - }); - } - try { - this.#storage = createStorage({ - driver: driver(this.#config.options) - }); - AstroSession.#sharedStorage.set(this.#config.driver, this.#storage); - return this.#storage; - } catch (err) { - throw new AstroError( - { - ...SessionStorageInitError, - message: SessionStorageInitError.message("Unknown error", this.#config.driver) - }, - { cause: err } - ); - } - } -} -function resolveSessionDriverName(driver) { - if (!driver) { - return null; - } - try { - if (driver === "fs") { - return builtinDrivers.fsLite; - } - if (driver in builtinDrivers) { - return builtinDrivers[driver]; - } - } catch { - return null; - } - return driver; -} - -function validateAndDecodePathname(pathname) { - let decoded; - try { - decoded = decodeURI(pathname); - } catch (_e) { - throw new Error("Invalid URL encoding"); - } - const hasDecoding = decoded !== pathname; - const decodedStillHasEncoding = /%[0-9a-fA-F]{2}/.test(decoded); - if (hasDecoding && decodedStillHasEncoding) { - throw new Error("Multi-level URL encoding is not allowed"); - } - return decoded; -} - -const apiContextRoutesSymbol = Symbol.for("context.routes"); -class RenderContext { - constructor(pipeline, locals, middleware, actions, pathname, request, routeData, status, clientAddress, cookies = new AstroCookies(request), params = getParams(routeData, pathname), url = RenderContext.#createNormalizedUrl(request.url), props = {}, partial = void 0, shouldInjectCspMetaTags = !!pipeline.manifest.csp, session = pipeline.manifest.sessionConfig ? new AstroSession(cookies, pipeline.manifest.sessionConfig, pipeline.runtimeMode) : void 0) { - this.pipeline = pipeline; - this.locals = locals; - this.middleware = middleware; - this.actions = actions; - this.pathname = pathname; - this.request = request; - this.routeData = routeData; - this.status = status; - this.clientAddress = clientAddress; - this.cookies = cookies; - this.params = params; - this.url = url; - this.props = props; - this.partial = partial; - this.shouldInjectCspMetaTags = shouldInjectCspMetaTags; - this.session = session; - } - static #createNormalizedUrl(requestUrl) { - const url = new URL(requestUrl); - try { - url.pathname = validateAndDecodePathname(url.pathname); - } catch { - try { - url.pathname = decodeURI(url.pathname); - } catch { - } - } - return url; - } - /** - * A flag that tells the render content if the rewriting was triggered - */ - isRewriting = false; - /** - * A safety net in case of loops - */ - counter = 0; - result = void 0; - static async create({ - locals = {}, - middleware, - pathname, - pipeline, - request, - routeData, - clientAddress, - status = 200, - props, - partial = void 0, - actions, - shouldInjectCspMetaTags - }) { - const pipelineMiddleware = await pipeline.getMiddleware(); - const pipelineActions = actions ?? await pipeline.getActions(); - setOriginPathname( - request, - pathname, - pipeline.manifest.trailingSlash, - pipeline.manifest.buildFormat - ); - return new RenderContext( - pipeline, - locals, - sequence(...pipeline.internalMiddleware, middleware ?? pipelineMiddleware), - pipelineActions, - pathname, - request, - routeData, - status, - clientAddress, - void 0, - void 0, - void 0, - props, - partial, - shouldInjectCspMetaTags ?? !!pipeline.manifest.csp - ); - } - /** - * The main function of the RenderContext. - * - * Use this function to render any route known to Astro. - * It attempts to render a route. A route can be a: - * - * - page - * - redirect - * - endpoint - * - fallback - */ - async render(componentInstance, slots = {}) { - const { middleware, pipeline } = this; - const { logger, serverLike, streaming, manifest } = pipeline; - const props = Object.keys(this.props).length > 0 ? this.props : await getProps({ - mod: componentInstance, - routeData: this.routeData, - routeCache: this.pipeline.routeCache, - pathname: this.pathname, - logger, - serverLike, - base: manifest.base - }); - const actionApiContext = this.createActionAPIContext(); - const apiContext = this.createAPIContext(props, actionApiContext); - this.counter++; - if (this.counter === 4) { - return new Response("Loop Detected", { - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/508 - status: 508, - statusText: "Astro detected a loop where you tried to call the rewriting logic more than four times." - }); - } - const lastNext = async (ctx, payload) => { - if (payload) { - const oldPathname = this.pathname; - pipeline.logger.debug("router", "Called rewriting to:", payload); - const { - routeData, - componentInstance: newComponent, - pathname, - newUrl - } = await pipeline.tryRewrite(payload, this.request); - if (this.pipeline.serverLike === true && this.routeData.prerender === false && routeData.prerender === true) { - throw new AstroError({ - ...ForbiddenRewrite, - message: ForbiddenRewrite.message(this.pathname, pathname, routeData.component), - hint: ForbiddenRewrite.hint(routeData.component) - }); - } - this.routeData = routeData; - componentInstance = newComponent; - if (payload instanceof Request) { - this.request = payload; - } else { - this.request = copyRequest( - newUrl, - this.request, - // need to send the flag of the previous routeData - routeData.prerender, - this.pipeline.logger, - this.routeData.route - ); - } - this.isRewriting = true; - this.url = RenderContext.#createNormalizedUrl(this.request.url); - this.params = getParams(routeData, pathname); - this.pathname = pathname; - this.status = 200; - setOriginPathname( - this.request, - oldPathname, - this.pipeline.manifest.trailingSlash, - this.pipeline.manifest.buildFormat - ); - } - let response2; - if (!ctx.isPrerendered) { - const { action, setActionResult, serializeActionResult } = getActionContext(ctx); - if (action?.calledFrom === "form") { - const actionResult = await action.handler(); - setActionResult(action.name, serializeActionResult(actionResult)); - } - } - switch (this.routeData.type) { - case "endpoint": { - response2 = await renderEndpoint( - componentInstance, - ctx, - this.routeData.prerender, - logger - ); - break; - } - case "redirect": - return renderRedirect(this); - case "page": { - this.result = await this.createResult(componentInstance, actionApiContext); - try { - response2 = await renderPage( - this.result, - componentInstance?.default, - props, - slots, - streaming, - this.routeData - ); - } catch (e) { - this.result.cancelled = true; - throw e; - } - response2.headers.set(ROUTE_TYPE_HEADER, "page"); - if (this.routeData.route === "/404" || this.routeData.route === "/500") { - response2.headers.set(REROUTE_DIRECTIVE_HEADER, "no"); - } - if (this.isRewriting) { - response2.headers.set(REWRITE_DIRECTIVE_HEADER_KEY, REWRITE_DIRECTIVE_HEADER_VALUE); - } - break; - } - case "fallback": { - return new Response(null, { status: 500, headers: { [ROUTE_TYPE_HEADER]: "fallback" } }); - } - } - const responseCookies = getCookiesFromResponse(response2); - if (responseCookies) { - this.cookies.merge(responseCookies); - } - return response2; - }; - if (isRouteExternalRedirect(this.routeData)) { - return renderRedirect(this); - } - const response = await callMiddleware(middleware, apiContext, lastNext); - if (response.headers.get(ROUTE_TYPE_HEADER)) { - response.headers.delete(ROUTE_TYPE_HEADER); - } - attachCookiesToResponse(response, this.cookies); - return response; - } - createAPIContext(props, context) { - const redirect = (path, status = 302) => new Response(null, { status, headers: { Location: path } }); - Reflect.set(context, apiContextRoutesSymbol, this.pipeline); - return Object.assign(context, { - props, - redirect, - getActionResult: createGetActionResult(context.locals), - callAction: createCallAction(context) - }); - } - async #executeRewrite(reroutePayload) { - this.pipeline.logger.debug("router", "Calling rewrite: ", reroutePayload); - const oldPathname = this.pathname; - const { routeData, componentInstance, newUrl, pathname } = await this.pipeline.tryRewrite( - reroutePayload, - this.request - ); - const isI18nFallback = routeData.fallbackRoutes && routeData.fallbackRoutes.length > 0; - if (this.pipeline.serverLike && !this.routeData.prerender && routeData.prerender && !isI18nFallback) { - throw new AstroError({ - ...ForbiddenRewrite, - message: ForbiddenRewrite.message(this.pathname, pathname, routeData.component), - hint: ForbiddenRewrite.hint(routeData.component) - }); - } - this.routeData = routeData; - if (reroutePayload instanceof Request) { - this.request = reroutePayload; - } else { - this.request = copyRequest( - newUrl, - this.request, - // need to send the flag of the previous routeData - routeData.prerender, - this.pipeline.logger, - this.routeData.route - ); - } - this.url = RenderContext.#createNormalizedUrl(this.request.url); - const newCookies = new AstroCookies(this.request); - if (this.cookies) { - newCookies.merge(this.cookies); - } - this.cookies = newCookies; - this.params = getParams(routeData, pathname); - this.pathname = pathname; - this.isRewriting = true; - this.status = 200; - setOriginPathname( - this.request, - oldPathname, - this.pipeline.manifest.trailingSlash, - this.pipeline.manifest.buildFormat - ); - return await this.render(componentInstance); - } - createActionAPIContext() { - const renderContext = this; - const { params, pipeline, url } = this; - const generator = `Astro v${ASTRO_VERSION}`; - const rewrite = async (reroutePayload) => { - return await this.#executeRewrite(reroutePayload); - }; - return { - // Don't allow reassignment of cookies because it doesn't work - get cookies() { - return renderContext.cookies; - }, - routePattern: this.routeData.route, - isPrerendered: this.routeData.prerender, - get clientAddress() { - return renderContext.getClientAddress(); - }, - get currentLocale() { - return renderContext.computeCurrentLocale(); - }, - generator, - get locals() { - return renderContext.locals; - }, - set locals(_) { - throw new AstroError(LocalsReassigned); - }, - params, - get preferredLocale() { - return renderContext.computePreferredLocale(); - }, - get preferredLocaleList() { - return renderContext.computePreferredLocaleList(); - }, - rewrite, - request: this.request, - site: pipeline.site, - url, - get originPathname() { - return getOriginPathname(renderContext.request); - }, - get session() { - if (this.isPrerendered) { - pipeline.logger.warn( - "session", - `context.session was used when rendering the route ${colors.green(this.routePattern)}, but it is not available on prerendered routes. If you need access to sessions, make sure that the route is server-rendered using \`export const prerender = false;\` or by setting \`output\` to \`"server"\` in your Astro config to make all your routes server-rendered by default. For more information, see https://docs.astro.build/en/guides/sessions/` - ); - return void 0; - } - if (!renderContext.session) { - pipeline.logger.warn( - "session", - `context.session was used when rendering the route ${colors.green(this.routePattern)}, but no storage configuration was provided. Either configure the storage manually or use an adapter that provides session storage. For more information, see https://docs.astro.build/en/guides/sessions/` - ); - return void 0; - } - return renderContext.session; - }, - get csp() { - return { - insertDirective(payload) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - if (renderContext?.result?.directives) { - renderContext.result.directives = pushDirective( - renderContext.result.directives, - payload - ); - } else { - renderContext?.result?.directives.push(payload); - } - }, - insertScriptResource(resource) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.scriptResources.push(resource); - }, - insertStyleResource(resource) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.styleResources.push(resource); - }, - insertStyleHash(hash) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.styleHashes.push(hash); - }, - insertScriptHash(hash) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.scriptHashes.push(hash); - } - }; - } - }; - } - async createResult(mod, ctx) { - const { cookies, pathname, pipeline, routeData, status } = this; - const { clientDirectives, inlinedScripts, compressHTML, manifest, renderers, resolve } = pipeline; - const { links, scripts, styles } = await pipeline.headElements(routeData); - const extraStyleHashes = []; - const extraScriptHashes = []; - const shouldInjectCspMetaTags = this.shouldInjectCspMetaTags; - const cspAlgorithm = manifest.csp?.algorithm ?? "SHA-256"; - if (shouldInjectCspMetaTags) { - for (const style of styles) { - extraStyleHashes.push(await generateCspDigest(style.children, cspAlgorithm)); - } - for (const script of scripts) { - extraScriptHashes.push(await generateCspDigest(script.children, cspAlgorithm)); - } - } - const componentMetadata = await pipeline.componentMetadata(routeData) ?? manifest.componentMetadata; - const headers = new Headers({ "Content-Type": "text/html" }); - const partial = typeof this.partial === "boolean" ? this.partial : Boolean(mod.partial); - const actionResult = hasActionPayload(this.locals) ? deserializeActionResult(this.locals._actionPayload.actionResult) : void 0; - const response = { - status: actionResult?.error ? actionResult?.error.status : status, - statusText: actionResult?.error ? actionResult?.error.type : "OK", - get headers() { - return headers; - }, - // Disallow `Astro.response.headers = new Headers` - set headers(_) { - throw new AstroError(AstroResponseHeadersReassigned); - } - }; - const result = { - base: manifest.base, - userAssetsBase: manifest.userAssetsBase, - cancelled: false, - clientDirectives, - inlinedScripts, - componentMetadata, - compressHTML, - cookies, - /** This function returns the `Astro` faux-global */ - createAstro: (astroGlobal, props, slots) => this.createAstro(result, astroGlobal, props, slots, ctx), - links, - params: this.params, - partial, - pathname, - renderers, - resolve, - response, - request: this.request, - scripts, - styles, - actionResult, - serverIslandNameMap: manifest.serverIslandNameMap ?? /* @__PURE__ */ new Map(), - key: manifest.key, - trailingSlash: manifest.trailingSlash, - _metadata: { - hasHydrationScript: false, - rendererSpecificHydrationScripts: /* @__PURE__ */ new Set(), - hasRenderedHead: false, - renderedScripts: /* @__PURE__ */ new Set(), - hasDirectives: /* @__PURE__ */ new Set(), - hasRenderedServerIslandRuntime: false, - headInTree: false, - extraHead: [], - extraStyleHashes, - extraScriptHashes, - propagators: /* @__PURE__ */ new Set() - }, - cspDestination: manifest.csp?.cspDestination ?? (routeData.prerender ? "meta" : "header"), - shouldInjectCspMetaTags, - cspAlgorithm, - // The following arrays must be cloned, otherwise they become mutable across routes. - scriptHashes: manifest.csp?.scriptHashes ? [...manifest.csp.scriptHashes] : [], - scriptResources: manifest.csp?.scriptResources ? [...manifest.csp.scriptResources] : [], - styleHashes: manifest.csp?.styleHashes ? [...manifest.csp.styleHashes] : [], - styleResources: manifest.csp?.styleResources ? [...manifest.csp.styleResources] : [], - directives: manifest.csp?.directives ? [...manifest.csp.directives] : [], - isStrictDynamic: manifest.csp?.isStrictDynamic ?? false, - internalFetchHeaders: manifest.internalFetchHeaders - }; - return result; - } - #astroPagePartial; - /** - * The Astro global is sourced in 3 different phases: - * - **Static**: `.generator` and `.glob` is printed by the compiler, instantiated once per process per astro file - * - **Page-level**: `.request`, `.cookies`, `.locals` etc. These remain the same for the duration of the request. - * - **Component-level**: `.props`, `.slots`, and `.self` are unique to each _use_ of each component. - * - * The page level partial is used as the prototype of the user-visible `Astro` global object, which is instantiated once per use of a component. - */ - createAstro(result, astroStaticPartial, props, slotValues, apiContext) { - let astroPagePartial; - if (this.isRewriting) { - astroPagePartial = this.#astroPagePartial = this.createAstroPagePartial( - result, - astroStaticPartial, - apiContext - ); - } else { - astroPagePartial = this.#astroPagePartial ??= this.createAstroPagePartial( - result, - astroStaticPartial, - apiContext - ); - } - const astroComponentPartial = { props, self: null }; - const Astro = Object.assign( - Object.create(astroPagePartial), - astroComponentPartial - ); - let _slots; - Object.defineProperty(Astro, "slots", { - get: () => { - if (!_slots) { - _slots = new Slots( - result, - slotValues, - this.pipeline.logger - ); - } - return _slots; - } - }); - return Astro; - } - createAstroPagePartial(result, astroStaticPartial, apiContext) { - const renderContext = this; - const { cookies, locals, params, pipeline, url } = this; - const { response } = result; - const redirect = (path, status = 302) => { - if (this.request[responseSentSymbol$1]) { - throw new AstroError({ - ...ResponseSentError - }); - } - return new Response(null, { status, headers: { Location: path } }); - }; - const rewrite = async (reroutePayload) => { - return await this.#executeRewrite(reroutePayload); - }; - const callAction = createCallAction(apiContext); - return { - generator: astroStaticPartial.generator, - glob: astroStaticPartial.glob, - routePattern: this.routeData.route, - isPrerendered: this.routeData.prerender, - cookies, - get session() { - if (this.isPrerendered) { - pipeline.logger.warn( - "session", - `Astro.session was used when rendering the route ${colors.green(this.routePattern)}, but it is not available on prerendered pages. If you need access to sessions, make sure that the page is server-rendered using \`export const prerender = false;\` or by setting \`output\` to \`"server"\` in your Astro config to make all your pages server-rendered by default. For more information, see https://docs.astro.build/en/guides/sessions/` - ); - return void 0; - } - if (!renderContext.session) { - pipeline.logger.warn( - "session", - `Astro.session was used when rendering the route ${colors.green(this.routePattern)}, but no storage configuration was provided. Either configure the storage manually or use an adapter that provides session storage. For more information, see https://docs.astro.build/en/guides/sessions/` - ); - return void 0; - } - return renderContext.session; - }, - get clientAddress() { - return renderContext.getClientAddress(); - }, - get currentLocale() { - return renderContext.computeCurrentLocale(); - }, - params, - get preferredLocale() { - return renderContext.computePreferredLocale(); - }, - get preferredLocaleList() { - return renderContext.computePreferredLocaleList(); - }, - locals, - redirect, - rewrite, - request: this.request, - response, - site: pipeline.site, - getActionResult: createGetActionResult(locals), - get callAction() { - return callAction; - }, - url, - get originPathname() { - return getOriginPathname(renderContext.request); - }, - get csp() { - return { - insertDirective(payload) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - if (renderContext?.result?.directives) { - renderContext.result.directives = pushDirective( - renderContext.result.directives, - payload - ); - } else { - renderContext?.result?.directives.push(payload); - } - }, - insertScriptResource(resource) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.scriptResources.push(resource); - }, - insertStyleResource(resource) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.styleResources.push(resource); - }, - insertStyleHash(hash) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.styleHashes.push(hash); - }, - insertScriptHash(hash) { - if (!pipeline.manifest.csp) { - throw new AstroError(CspNotEnabled); - } - renderContext.result?.scriptHashes.push(hash); - } - }; - } - }; - } - getClientAddress() { - const { pipeline, request, routeData, clientAddress } = this; - if (routeData.prerender) { - throw new AstroError({ - ...PrerenderClientAddressNotAvailable, - message: PrerenderClientAddressNotAvailable.message(routeData.component) - }); - } - if (clientAddress) { - return clientAddress; - } - if (clientAddressSymbol in request) { - return Reflect.get(request, clientAddressSymbol); - } - if (pipeline.adapterName) { - throw new AstroError({ - ...ClientAddressNotAvailable, - message: ClientAddressNotAvailable.message(pipeline.adapterName) - }); - } - throw new AstroError(StaticClientAddressNotAvailable); - } - /** - * API Context may be created multiple times per request, i18n data needs to be computed only once. - * So, it is computed and saved here on creation of the first APIContext and reused for later ones. - */ - #currentLocale; - computeCurrentLocale() { - const { - url, - pipeline: { i18n }, - routeData - } = this; - if (!i18n) return; - const { defaultLocale, locales, strategy } = i18n; - const fallbackTo = strategy === "pathname-prefix-other-locales" || strategy === "domains-prefix-other-locales" ? defaultLocale : void 0; - if (this.#currentLocale) { - return this.#currentLocale; - } - let computedLocale; - if (isRouteServerIsland(routeData)) { - let referer = this.request.headers.get("referer"); - if (referer) { - if (URL.canParse(referer)) { - referer = new URL(referer).pathname; - } - computedLocale = computeCurrentLocale(referer, locales, defaultLocale); - } - } else { - let pathname = routeData.pathname; - if (!routeData.pattern.test(url.pathname)) { - for (const fallbackRoute of routeData.fallbackRoutes) { - if (fallbackRoute.pattern.test(url.pathname)) { - pathname = fallbackRoute.pathname; - break; - } - } - } - pathname = pathname && !isRoute404or500(routeData) ? pathname : url.pathname; - computedLocale = computeCurrentLocale(pathname, locales, defaultLocale); - } - this.#currentLocale = computedLocale ?? fallbackTo; - return this.#currentLocale; - } - #preferredLocale; - computePreferredLocale() { - const { - pipeline: { i18n }, - request - } = this; - if (!i18n) return; - return this.#preferredLocale ??= computePreferredLocale(request, i18n.locales); - } - #preferredLocaleList; - computePreferredLocaleList() { - const { - pipeline: { i18n }, - request - } = this; - if (!i18n) return; - return this.#preferredLocaleList ??= computePreferredLocaleList(request, i18n.locales); - } -} - -function sequence(...handlers) { - const filtered = handlers.filter((h) => !!h); - const length = filtered.length; - if (!length) { - return defineMiddleware((_context, next) => { - return next(); - }); - } - return defineMiddleware((context, next) => { - let carriedPayload = void 0; - return applyHandle(0, context); - function applyHandle(i, handleContext) { - const handle = filtered[i]; - const result = handle(handleContext, async (payload) => { - if (i < length - 1) { - if (payload) { - let newRequest; - if (payload instanceof Request) { - newRequest = payload; - } else if (payload instanceof URL) { - newRequest = new Request(payload, handleContext.request.clone()); - } else { - newRequest = new Request( - new URL(payload, handleContext.url.origin), - handleContext.request.clone() - ); - } - const oldPathname = handleContext.url.pathname; - const pipeline = Reflect.get(handleContext, apiContextRoutesSymbol); - const { routeData, pathname } = await pipeline.tryRewrite( - payload, - handleContext.request - ); - if (pipeline.serverLike === true && handleContext.isPrerendered === false && routeData.prerender === true) { - throw new AstroError({ - ...ForbiddenRewrite, - message: ForbiddenRewrite.message( - handleContext.url.pathname, - pathname, - routeData.component - ), - hint: ForbiddenRewrite.hint(routeData.component) - }); - } - carriedPayload = payload; - handleContext.request = newRequest; - handleContext.url = new URL(newRequest.url); - handleContext.params = getParams(routeData, pathname); - handleContext.routePattern = routeData.route; - setOriginPathname( - handleContext.request, - oldPathname, - pipeline.manifest.trailingSlash, - pipeline.manifest.buildFormat - ); - } - return applyHandle(i + 1, handleContext); - } else { - return next(payload ?? carriedPayload); - } - }); - return result; - } - }); -} - -function defineMiddleware(fn) { - return fn; -} - -export { PERSIST_SYMBOL as P, RouteCache as R, SERVER_ISLAND_COMPONENT as S, normalizeTheLocale as a, redirectToFallback as b, redirectToDefaultLocale as c, defineMiddleware as d, requestHasLocale as e, SERVER_ISLAND_ROUTE as f, createEndpoint as g, findRouteToRewrite as h, isRequestServerIsland as i, RenderContext as j, getSetCookiesFromResponse as k, matchRoute as m, notFound as n, requestIs404Or500 as r, sequence as s, validateAndDecodePathname as v }; diff --git a/.vercel/output/_functions/chunks/noop-middleware_hVW5dbP7.mjs b/.vercel/output/_functions/chunks/noop-middleware_hVW5dbP7.mjs deleted file mode 100644 index 4f9c938..0000000 --- a/.vercel/output/_functions/chunks/noop-middleware_hVW5dbP7.mjs +++ /dev/null @@ -1,9 +0,0 @@ -import { aa as NOOP_MIDDLEWARE_HEADER } from './astro/server_D2NiA7f1.mjs'; - -const NOOP_MIDDLEWARE_FN = async (_ctx, next) => { - const response = await next(); - response.headers.set(NOOP_MIDDLEWARE_HEADER, "true"); - return response; -}; - -export { NOOP_MIDDLEWARE_FN as N }; diff --git a/.vercel/output/_functions/chunks/path_Bl04Vi8h.mjs b/.vercel/output/_functions/chunks/path_Bl04Vi8h.mjs deleted file mode 100644 index 4104f04..0000000 --- a/.vercel/output/_functions/chunks/path_Bl04Vi8h.mjs +++ /dev/null @@ -1,111 +0,0 @@ -function appendForwardSlash(path) { - return path.endsWith("/") ? path : path + "/"; -} -function prependForwardSlash(path) { - return path[0] === "/" ? path : "/" + path; -} -const MANY_TRAILING_SLASHES = /\/{2,}$/g; -function collapseDuplicateTrailingSlashes(path, trailingSlash) { - if (!path) { - return path; - } - return path.replace(MANY_TRAILING_SLASHES, trailingSlash ? "/" : "") || "/"; -} -function removeTrailingForwardSlash(path) { - return path.endsWith("/") ? path.slice(0, path.length - 1) : path; -} -function removeLeadingForwardSlash(path) { - return path.startsWith("/") ? path.substring(1) : path; -} -function trimSlashes(path) { - return path.replace(/^\/|\/$/g, ""); -} -function isString(path) { - return typeof path === "string" || path instanceof String; -} -const INTERNAL_PREFIXES = /* @__PURE__ */ new Set(["/_", "/@", "/.", "//"]); -const JUST_SLASHES = /^\/{2,}$/; -function isInternalPath(path) { - return INTERNAL_PREFIXES.has(path.slice(0, 2)) && !JUST_SLASHES.test(path); -} -function joinPaths(...paths) { - return paths.filter(isString).map((path, i) => { - if (i === 0) { - return removeTrailingForwardSlash(path); - } else if (i === paths.length - 1) { - return removeLeadingForwardSlash(path); - } else { - return trimSlashes(path); - } - }).join("/"); -} -function isRemotePath(src) { - if (!src) return false; - const trimmed = src.trim(); - if (!trimmed) return false; - let decoded = trimmed; - let previousDecoded = ""; - let maxIterations = 10; - while (decoded !== previousDecoded && maxIterations > 0) { - previousDecoded = decoded; - try { - decoded = decodeURIComponent(decoded); - } catch { - break; - } - maxIterations--; - } - if (/^[a-zA-Z]:/.test(decoded)) { - return false; - } - if (decoded[0] === "/" && decoded[1] !== "/" && decoded[1] !== "\\") { - return false; - } - if (decoded[0] === "\\") { - return true; - } - if (decoded.startsWith("//")) { - return true; - } - try { - const url = new URL(decoded, "http://n"); - if (url.username || url.password) { - return true; - } - if (decoded.includes("@") && !url.pathname.includes("@") && !url.search.includes("@")) { - return true; - } - if (url.origin !== "http://n") { - const protocol = url.protocol.toLowerCase(); - if (protocol === "file:") { - return false; - } - return true; - } - if (URL.canParse(decoded)) { - return true; - } - return false; - } catch { - return true; - } -} -function slash(path) { - return path.replace(/\\/g, "/"); -} -function fileExtension(path) { - const ext = path.split(".").pop(); - return ext !== path ? `.${ext}` : ""; -} -function removeBase(path, base) { - if (path.startsWith(base)) { - return path.slice(removeTrailingForwardSlash(base).length); - } - return path; -} -const WITH_FILE_EXT = /\/[^/]+\.\w+$/; -function hasFileExtension(path) { - return WITH_FILE_EXT.test(path); -} - -export { removeTrailingForwardSlash as a, appendForwardSlash as b, isInternalPath as c, collapseDuplicateTrailingSlashes as d, fileExtension as f, hasFileExtension as h, isRemotePath as i, joinPaths as j, prependForwardSlash as p, removeBase as r, slash as s, trimSlashes as t }; diff --git a/.vercel/output/_functions/chunks/sharp_BTdjpfI2.mjs b/.vercel/output/_functions/chunks/sharp_BTdjpfI2.mjs deleted file mode 100644 index 48067f2..0000000 --- a/.vercel/output/_functions/chunks/sharp_BTdjpfI2.mjs +++ /dev/null @@ -1,101 +0,0 @@ -import { A as AstroError, ad as MissingSharp } from './astro/server_D2NiA7f1.mjs'; -import { b as baseService, p as parseQuality } from './_astro_assets_BkxcOWlh.mjs'; - -let sharp; -const qualityTable = { - low: 25, - mid: 50, - high: 80, - max: 100 -}; -async function loadSharp() { - let sharpImport; - try { - sharpImport = (await import('sharp')).default; - } catch { - throw new AstroError(MissingSharp); - } - sharpImport.cache(false); - return sharpImport; -} -const fitMap = { - fill: "fill", - contain: "inside", - cover: "cover", - none: "outside", - "scale-down": "inside", - outside: "outside", - inside: "inside" -}; -const sharpService = { - validateOptions: baseService.validateOptions, - getURL: baseService.getURL, - parseURL: baseService.parseURL, - getHTMLAttributes: baseService.getHTMLAttributes, - getSrcSet: baseService.getSrcSet, - async transform(inputBuffer, transformOptions, config) { - if (!sharp) sharp = await loadSharp(); - const transform = transformOptions; - const kernel = config.service.config.kernel; - if (transform.format === "svg") return { data: inputBuffer, format: "svg" }; - const result = sharp(inputBuffer, { - failOnError: false, - pages: -1, - limitInputPixels: config.service.config.limitInputPixels - }); - result.rotate(); - const { format } = await result.metadata(); - const withoutEnlargement = Boolean(transform.fit); - if (transform.width && transform.height && transform.fit) { - const fit = fitMap[transform.fit] ?? "inside"; - result.resize({ - width: Math.round(transform.width), - height: Math.round(transform.height), - kernel, - fit, - position: transform.position, - withoutEnlargement - }); - } else if (transform.height && !transform.width) { - result.resize({ - height: Math.round(transform.height), - kernel, - withoutEnlargement - }); - } else if (transform.width) { - result.resize({ - width: Math.round(transform.width), - kernel, - withoutEnlargement - }); - } - if (transform.background) { - result.flatten({ background: transform.background }); - } - if (transform.format) { - let quality = void 0; - if (transform.quality) { - const parsedQuality = parseQuality(transform.quality); - if (typeof parsedQuality === "number") { - quality = parsedQuality; - } else { - quality = transform.quality in qualityTable ? qualityTable[transform.quality] : void 0; - } - } - if (transform.format === "webp" && format === "gif") { - result.webp({ quality: typeof quality === "number" ? quality : void 0, loop: 0 }); - } else { - result.toFormat(transform.format, { quality }); - } - } - const { data, info } = await result.toBuffer({ resolveWithObject: true }); - const needsCopy = "buffer" in data && data.buffer instanceof SharedArrayBuffer; - return { - data: needsCopy ? new Uint8Array(data) : data, - format: info.format - }; - } -}; -var sharp_default = sharpService; - -export { sharp_default as default }; diff --git a/.vercel/output/_functions/entry.mjs b/.vercel/output/_functions/entry.mjs deleted file mode 100644 index be5433b..0000000 --- a/.vercel/output/_functions/entry.mjs +++ /dev/null @@ -1,52 +0,0 @@ -import { renderers } from './renderers.mjs'; -import { c as createExports, s as serverEntrypointModule } from './chunks/_@astrojs-ssr-adapter_DkQ011Ef.mjs'; -import { manifest } from './manifest_BkFuMUuC.mjs'; - -const serverIslandMap = new Map();; - -const _page0 = () => import('./pages/_image.astro.mjs'); -const _page1 = () => import('./pages/about.astro.mjs'); -const _page2 = () => import('./pages/api/subscribe.astro.mjs'); -const _page3 = () => import('./pages/api/verify.astro.mjs'); -const _page4 = () => import('./pages/confirm.astro.mjs'); -const _page5 = () => import('./pages/contact.astro.mjs'); -const _page6 = () => import('./pages/hdk.astro.mjs'); -const _page7 = () => import('./pages/notes/_slug_.astro.mjs'); -const _page8 = () => import('./pages/notes.astro.mjs'); -const _page9 = () => import('./pages/one-rule.astro.mjs'); -const _page10 = () => import('./pages/resources.astro.mjs'); -const _page11 = () => import('./pages/work-with-me.astro.mjs'); -const _page12 = () => import('./pages/index.astro.mjs'); -const pageMap = new Map([ - ["node_modules/astro/dist/assets/endpoint/generic.js", _page0], - ["src/pages/about.astro", _page1], - ["src/pages/api/subscribe.ts", _page2], - ["src/pages/api/verify.ts", _page3], - ["src/pages/confirm.astro", _page4], - ["src/pages/contact.astro", _page5], - ["src/pages/hdk.astro", _page6], - ["src/pages/notes/[slug].astro", _page7], - ["src/pages/notes/index.astro", _page8], - ["src/pages/one-rule.astro", _page9], - ["src/pages/resources.astro", _page10], - ["src/pages/work-with-me.astro", _page11], - ["src/pages/index.astro", _page12] -]); - -const _manifest = Object.assign(manifest, { - pageMap, - serverIslandMap, - renderers, - actions: () => import('./noop-entrypoint.mjs'), - middleware: () => import('./_astro-internal_middleware.mjs') -}); -const _args = { - "middlewareSecret": "09662dc5-0a25-484a-b0c7-ed4f70a03631", - "skewProtection": false -}; -const _exports = createExports(_manifest, _args); -const __astrojsSsrVirtualEntry = _exports.default; -const _start = 'start'; -if (Object.prototype.hasOwnProperty.call(serverEntrypointModule, _start)) ; - -export { __astrojsSsrVirtualEntry as default, pageMap }; diff --git a/.vercel/output/_functions/manifest_BkFuMUuC.mjs b/.vercel/output/_functions/manifest_BkFuMUuC.mjs deleted file mode 100644 index bc56119..0000000 --- a/.vercel/output/_functions/manifest_BkFuMUuC.mjs +++ /dev/null @@ -1,102 +0,0 @@ -import 'piccolore'; -import { k as decodeKey } from './chunks/astro/server_D2NiA7f1.mjs'; -import 'clsx'; -import './chunks/astro-designed-error-pages_C_Ez8g0J.mjs'; -import 'es-module-lexer'; -import { N as NOOP_MIDDLEWARE_FN } from './chunks/noop-middleware_hVW5dbP7.mjs'; - -function sanitizeParams(params) { - return Object.fromEntries( - Object.entries(params).map(([key, value]) => { - if (typeof value === "string") { - return [key, value.normalize().replace(/#/g, "%23").replace(/\?/g, "%3F")]; - } - return [key, value]; - }) - ); -} -function getParameter(part, params) { - if (part.spread) { - return params[part.content.slice(3)] || ""; - } - if (part.dynamic) { - if (!params[part.content]) { - throw new TypeError(`Missing parameter: ${part.content}`); - } - return params[part.content]; - } - return part.content.normalize().replace(/\?/g, "%3F").replace(/#/g, "%23").replace(/%5B/g, "[").replace(/%5D/g, "]"); -} -function getSegment(segment, params) { - const segmentPath = segment.map((part) => getParameter(part, params)).join(""); - return segmentPath ? "/" + segmentPath : ""; -} -function getRouteGenerator(segments, addTrailingSlash) { - return (params) => { - const sanitizedParams = sanitizeParams(params); - let trailing = ""; - if (addTrailingSlash === "always" && segments.length) { - trailing = "/"; - } - const path = segments.map((segment) => getSegment(segment, sanitizedParams)).join("") + trailing; - return path || "/"; - }; -} - -function deserializeRouteData(rawRouteData) { - return { - route: rawRouteData.route, - type: rawRouteData.type, - pattern: new RegExp(rawRouteData.pattern), - params: rawRouteData.params, - component: rawRouteData.component, - generate: getRouteGenerator(rawRouteData.segments, rawRouteData._meta.trailingSlash), - pathname: rawRouteData.pathname || void 0, - segments: rawRouteData.segments, - prerender: rawRouteData.prerender, - redirect: rawRouteData.redirect, - redirectRoute: rawRouteData.redirectRoute ? deserializeRouteData(rawRouteData.redirectRoute) : void 0, - fallbackRoutes: rawRouteData.fallbackRoutes.map((fallback) => { - return deserializeRouteData(fallback); - }), - isIndex: rawRouteData.isIndex, - origin: rawRouteData.origin - }; -} - -function deserializeManifest(serializedManifest) { - const routes = []; - for (const serializedRoute of serializedManifest.routes) { - routes.push({ - ...serializedRoute, - routeData: deserializeRouteData(serializedRoute.routeData) - }); - const route = serializedRoute; - route.routeData = deserializeRouteData(serializedRoute.routeData); - } - const assets = new Set(serializedManifest.assets); - const componentMetadata = new Map(serializedManifest.componentMetadata); - const inlinedScripts = new Map(serializedManifest.inlinedScripts); - const clientDirectives = new Map(serializedManifest.clientDirectives); - const serverIslandNameMap = new Map(serializedManifest.serverIslandNameMap); - const key = decodeKey(serializedManifest.key); - return { - // in case user middleware exists, this no-op middleware will be reassigned (see plugin-ssr.ts) - middleware() { - return { onRequest: NOOP_MIDDLEWARE_FN }; - }, - ...serializedManifest, - assets, - componentMetadata, - inlinedScripts, - clientDirectives, - routes, - serverIslandNameMap, - key - }; -} - -const manifest = deserializeManifest({"hrefRoot":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/","cacheDir":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/node_modules/.astro/","outDir":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/dist/","srcDir":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/","publicDir":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/public/","buildClientDir":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/dist/client/","buildServerDir":"file:///Users/douglasgalloway/Documents/GitHub/damdug.github.io/dist/server/","adapterName":"@astrojs/vercel","routes":[{"file":"","links":[],"scripts":[],"styles":[],"routeData":{"type":"page","component":"_server-islands.astro","params":["name"],"segments":[[{"content":"_server-islands","dynamic":false,"spread":false}],[{"content":"name","dynamic":true,"spread":false}]],"pattern":"^\\/_server-islands\\/([^/]+?)\\/?$","prerender":false,"isIndex":false,"fallbackRoutes":[],"route":"/_server-islands/[name]","origin":"internal","_meta":{"trailingSlash":"ignore"}}},{"file":"resources/index.html","links":[],"scripts":[],"styles":[],"routeData":{"route":"/resources","isIndex":false,"type":"page","pattern":"^\\/resources\\/?$","segments":[[{"content":"resources","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/resources.astro","pathname":"/resources","prerender":true,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[],"routeData":{"type":"endpoint","isIndex":false,"route":"/_image","pattern":"^\\/_image\\/?$","segments":[[{"content":"_image","dynamic":false,"spread":false}]],"params":[],"component":"node_modules/astro/dist/assets/endpoint/generic.js","pathname":"/_image","prerender":false,"fallbackRoutes":[],"origin":"internal","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/about","isIndex":false,"type":"page","pattern":"^\\/about\\/?$","segments":[[{"content":"about","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/about.astro","pathname":"/about","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[],"routeData":{"route":"/api/subscribe","isIndex":false,"type":"endpoint","pattern":"^\\/api\\/subscribe\\/?$","segments":[[{"content":"api","dynamic":false,"spread":false}],[{"content":"subscribe","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/api/subscribe.ts","pathname":"/api/subscribe","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[],"routeData":{"route":"/api/verify","isIndex":false,"type":"endpoint","pattern":"^\\/api\\/verify\\/?$","segments":[[{"content":"api","dynamic":false,"spread":false}],[{"content":"verify","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/api/verify.ts","pathname":"/api/verify","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[],"routeData":{"route":"/confirm","isIndex":false,"type":"page","pattern":"^\\/confirm\\/?$","segments":[[{"content":"confirm","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/confirm.astro","pathname":"/confirm","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/contact","isIndex":false,"type":"page","pattern":"^\\/contact\\/?$","segments":[[{"content":"contact","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/contact.astro","pathname":"/contact","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/hdk","isIndex":false,"type":"page","pattern":"^\\/hdk\\/?$","segments":[[{"content":"hdk","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/hdk.astro","pathname":"/hdk","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/notes","isIndex":true,"type":"page","pattern":"^\\/notes\\/?$","segments":[[{"content":"notes","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/notes/index.astro","pathname":"/notes","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"a[data-astro-cid-hghskpuw][href^=\"/notes/\"]:hover{border-color:var(--accent)}\n@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/one-rule","isIndex":false,"type":"page","pattern":"^\\/one-rule\\/?$","segments":[[{"content":"one-rule","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/one-rule.astro","pathname":"/one-rule","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/work-with-me","isIndex":false,"type":"page","pattern":"^\\/work-with-me\\/?$","segments":[[{"content":"work-with-me","dynamic":false,"spread":false}]],"params":[],"component":"src/pages/work-with-me.astro","pathname":"/work-with-me","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}},{"file":"","links":[],"scripts":[],"styles":[{"type":"inline","content":"@import\"https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@300;400;500;600&display=swap\";:root{--bg-primary: #0A0A0A;--bg-surface: #111111;--bg-elevated: #1A1A1A;--border: #222222;--border-subtle: #1A1A1A;--text-primary: #E0E0E0;--text-secondary: #909090;--text-tertiary: #505050;--accent: #C9706A;--accent-hover: #B85E58;--font-mono: \"IBM Plex Mono\", \"Courier New\", monospace;--space-xs: .25rem;--space-sm: .5rem;--space-md: 1rem;--space-lg: 2rem;--space-xl: 4rem;--space-2xl: 8rem;--max-width: 760px;--max-width-wide: 1100px}*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}html{font-size:16px;-webkit-font-smoothing:antialiased}body{font-family:var(--font-mono);background-color:var(--bg-primary);color:var(--text-primary);line-height:1.7;min-height:100vh;display:flex;flex-direction:column}main{flex:1}a{color:var(--text-primary);text-decoration:none}a:hover{color:var(--accent)}::selection{background:var(--accent);color:var(--bg-primary)}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cursor:after{content:\"_\";color:var(--accent);animation:blink 1.2s step-end infinite}@media(max-width:640px){:root{--space-xl: 2rem;--space-2xl: 4rem}}h1,h2,h3,h4,h5,h6{font-family:var(--font-mono);font-weight:500;color:var(--text-primary);line-height:1.3}h1{font-size:clamp(1.5rem,4vw,2.25rem)}h2{font-size:clamp(1.2rem,3vw,1.6rem)}h3{font-size:clamp(1rem,2.5vw,1.25rem)}p{color:var(--text-secondary);font-size:.9375rem;line-height:1.8;max-width:65ch}.label{font-size:.7rem;font-weight:500;text-transform:uppercase;letter-spacing:.12em;color:var(--text-tertiary)}hr{border:none;border-top:1px solid var(--border);margin:var(--space-xl) 0}.container{width:100%;max-width:var(--max-width);margin:0 auto;padding:0 var(--space-lg)}.container--wide{max-width:var(--max-width-wide)}.section{padding:var(--space-xl) 0}.card{background:var(--bg-surface);border:1px solid var(--border);padding:var(--space-lg);transition:border-color .15s}.card:hover{border-color:var(--accent)}.note-item{display:flex;justify-content:space-between;align-items:baseline;padding:var(--space-md) 0;border-bottom:1px solid var(--border-subtle);gap:var(--space-md)}.note-item:hover .note-title{color:var(--accent)}.note-date{font-size:.8rem;color:var(--text-tertiary);white-space:nowrap;flex-shrink:0}.tag{display:inline-block;font-size:.7rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-tertiary);border:1px solid var(--border);padding:.15rem .5rem}.tag--accent{border-color:var(--accent);color:var(--accent)}.btn{display:inline-block;font-family:var(--font-mono);font-size:.8125rem;letter-spacing:.06em;text-transform:uppercase;color:var(--text-primary);border:1px solid var(--border);padding:.6rem 1.5rem;cursor:pointer;background:transparent;transition:border-color .15s,color .15s}.btn:hover,.btn--accent{border-color:var(--accent);color:var(--accent)}.btn--accent:hover{background:var(--accent);color:var(--bg-primary)}.form-row{display:flex;gap:var(--space-sm);flex-wrap:wrap}.form-input{font-family:var(--font-mono);font-size:.875rem;background:var(--bg-surface);border:1px solid var(--border);color:var(--text-primary);padding:.6rem 1rem;flex:1;min-width:200px;outline:none}.form-input:focus{border-color:var(--accent)}.form-input::placeholder{color:var(--text-tertiary)}\n"}],"routeData":{"route":"/","isIndex":true,"type":"page","pattern":"^\\/$","segments":[],"params":[],"component":"src/pages/index.astro","pathname":"/","prerender":false,"fallbackRoutes":[],"distURL":[],"origin":"project","_meta":{"trailingSlash":"ignore"}}}],"site":"https://damdug.com","base":"/","trailingSlash":"ignore","compressHTML":true,"componentMetadata":[["\u0000astro:content",{"propagation":"in-tree","containsHead":false}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/notes/[slug].astro",{"propagation":"in-tree","containsHead":true}],["\u0000@astro-page:src/pages/notes/[slug]@_@astro",{"propagation":"in-tree","containsHead":false}],["\u0000@astrojs-ssr-virtual-entry",{"propagation":"in-tree","containsHead":false}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/notes/index.astro",{"propagation":"in-tree","containsHead":true}],["\u0000@astro-page:src/pages/notes/index@_@astro",{"propagation":"in-tree","containsHead":false}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/about.astro",{"propagation":"none","containsHead":true}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/contact.astro",{"propagation":"none","containsHead":true}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/hdk.astro",{"propagation":"none","containsHead":true}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/index.astro",{"propagation":"none","containsHead":true}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/one-rule.astro",{"propagation":"none","containsHead":true}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/resources.astro",{"propagation":"none","containsHead":true}],["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/work-with-me.astro",{"propagation":"none","containsHead":true}]],"renderers":[],"clientDirectives":[["idle","(()=>{var l=(n,t)=>{let i=async()=>{await(await n())()},e=typeof t.value==\"object\"?t.value:void 0,s={timeout:e==null?void 0:e.timeout};\"requestIdleCallback\"in window?window.requestIdleCallback(i,s):setTimeout(i,s.timeout||200)};(self.Astro||(self.Astro={})).idle=l;window.dispatchEvent(new Event(\"astro:idle\"));})();"],["load","(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).load=e;window.dispatchEvent(new Event(\"astro:load\"));})();"],["media","(()=>{var n=(a,t)=>{let i=async()=>{await(await a())()};if(t.value){let e=matchMedia(t.value);e.matches?i():e.addEventListener(\"change\",i,{once:!0})}};(self.Astro||(self.Astro={})).media=n;window.dispatchEvent(new Event(\"astro:media\"));})();"],["only","(()=>{var e=async t=>{await(await t())()};(self.Astro||(self.Astro={})).only=e;window.dispatchEvent(new Event(\"astro:only\"));})();"],["visible","(()=>{var a=(s,i,o)=>{let r=async()=>{await(await s())()},t=typeof i.value==\"object\"?i.value:void 0,c={rootMargin:t==null?void 0:t.rootMargin},n=new IntersectionObserver(e=>{for(let l of e)if(l.isIntersecting){n.disconnect(),r();break}},c);for(let e of o.children)n.observe(e)};(self.Astro||(self.Astro={})).visible=a;window.dispatchEvent(new Event(\"astro:visible\"));})();"]],"entryModules":{"\u0000astro-internal:middleware":"_astro-internal_middleware.mjs","\u0000virtual:astro:actions/noop-entrypoint":"noop-entrypoint.mjs","\u0000@astro-page:node_modules/astro/dist/assets/endpoint/generic@_@js":"pages/_image.astro.mjs","\u0000@astro-page:src/pages/about@_@astro":"pages/about.astro.mjs","\u0000@astro-page:src/pages/api/subscribe@_@ts":"pages/api/subscribe.astro.mjs","\u0000@astro-page:src/pages/api/verify@_@ts":"pages/api/verify.astro.mjs","\u0000@astro-page:src/pages/confirm@_@astro":"pages/confirm.astro.mjs","\u0000@astro-page:src/pages/contact@_@astro":"pages/contact.astro.mjs","\u0000@astro-page:src/pages/hdk@_@astro":"pages/hdk.astro.mjs","\u0000@astro-page:src/pages/notes/[slug]@_@astro":"pages/notes/_slug_.astro.mjs","\u0000@astro-page:src/pages/notes/index@_@astro":"pages/notes.astro.mjs","\u0000@astro-page:src/pages/one-rule@_@astro":"pages/one-rule.astro.mjs","\u0000@astro-page:src/pages/resources@_@astro":"pages/resources.astro.mjs","\u0000@astro-page:src/pages/work-with-me@_@astro":"pages/work-with-me.astro.mjs","\u0000@astro-page:src/pages/index@_@astro":"pages/index.astro.mjs","\u0000@astrojs-ssr-virtual-entry":"entry.mjs","\u0000@astro-renderers":"renderers.mjs","\u0000@astrojs-ssr-adapter":"_@astrojs-ssr-adapter.mjs","\u0000@astrojs-manifest":"manifest_BkFuMUuC.mjs","/Users/douglasgalloway/Documents/GitHub/damdug.github.io/node_modules/astro/dist/assets/services/sharp.js":"chunks/sharp_BTdjpfI2.mjs","/Users/douglasgalloway/Documents/GitHub/damdug.github.io/.astro/content-assets.mjs":"chunks/content-assets_DleWbedO.mjs","/Users/douglasgalloway/Documents/GitHub/damdug.github.io/.astro/content-modules.mjs":"chunks/content-modules_Dz-S_Wwv.mjs","\u0000astro:data-layer-content":"chunks/_astro_data-layer-content_BUPw26ki.mjs","/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/SignupForm.astro?astro&type=script&index=0&lang.ts":"_astro/SignupForm.astro_astro_type_script_index_0_lang.CMfWwlql.js","astro:scripts/before-hydration.js":""},"inlinedScripts":[["/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/components/SignupForm.astro?astro&type=script&index=0&lang.ts","const t=document.getElementById(\"signup-form\"),e=document.getElementById(\"signup-message\");t?.addEventListener(\"submit\",async n=>{n.preventDefault();const o=new FormData(t);try{const s=await(await fetch(\"/api/subscribe\",{method:\"POST\",body:o})).json();e.style.display=\"block\",s.success?(e.style.color=\"var(--accent)\",e.textContent=\"✓ Check your email for your access link.\",t.reset()):(e.style.color=\"#d47d7d\",e.textContent=s.error||\"Something went wrong. Please try again.\")}catch{e.style.display=\"block\",e.style.color=\"#d47d7d\",e.textContent=\"Something went wrong. Please try again.\"}});"]],"assets":["/favicon.ico","/favicon.svg","/assets/icons/facebook.svg","/assets/icons/github.svg","/assets/icons/instagram.svg","/assets/icons/linkedin.svg","/assets/icons/twitter-x.svg","/assets/icons/whatsapp.svg","/assets/logo/dune.svg","/resources/index.html"],"buildFormat":"directory","checkOrigin":true,"allowedDomains":[],"actionBodySizeLimit":1048576,"serverIslandNameMap":[],"key":"p2HGj2s7pgncBTA0RJuCQIWOo6rmIj3wVniIdqRv07Q="}); -if (manifest.sessionConfig) manifest.sessionConfig.driverModule = null; - -export { manifest }; diff --git a/.vercel/output/_functions/noop-entrypoint.mjs b/.vercel/output/_functions/noop-entrypoint.mjs deleted file mode 100644 index f30dc32..0000000 --- a/.vercel/output/_functions/noop-entrypoint.mjs +++ /dev/null @@ -1,3 +0,0 @@ -const server = {}; - -export { server }; diff --git a/.vercel/output/_functions/pages/_image.astro.mjs b/.vercel/output/_functions/pages/_image.astro.mjs deleted file mode 100644 index f7d0f80..0000000 --- a/.vercel/output/_functions/pages/_image.astro.mjs +++ /dev/null @@ -1,101 +0,0 @@ -import { g as getConfiguredImageService, i as imageConfig } from '../chunks/_astro_assets_BkxcOWlh.mjs'; -import { i as isRemotePath } from '../chunks/path_Bl04Vi8h.mjs'; -import { i as isRemoteAllowed } from '../chunks/index_BL6Pqka4.mjs'; -import * as mime from 'mrmime'; -export { renderers } from '../renderers.mjs'; - -const fnv1a52 = (str) => { - const len = str.length; - let i = 0, t0 = 0, v0 = 8997, t1 = 0, v1 = 33826, t2 = 0, v2 = 40164, t3 = 0, v3 = 52210; - while (i < len) { - v0 ^= str.charCodeAt(i++); - t0 = v0 * 435; - t1 = v1 * 435; - t2 = v2 * 435; - t3 = v3 * 435; - t2 += v0 << 8; - t3 += v1 << 8; - t1 += t0 >>> 16; - v0 = t0 & 65535; - t2 += t1 >>> 16; - v1 = t1 & 65535; - v3 = t3 + (t2 >>> 16) & 65535; - v2 = t2 & 65535; - } - return (v3 & 15) * 281474976710656 + v2 * 4294967296 + v1 * 65536 + (v0 ^ v3 >> 4); -}; -const etag = (payload, weak = false) => { - const prefix = weak ? 'W/"' : '"'; - return prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '"'; -}; - -async function loadRemoteImage(src, headers) { - try { - const res = await fetch(src, { - // Forward all headers from the original request - headers, - redirect: "manual" - }); - if (res.status >= 300 && res.status < 400) { - return void 0; - } - if (!res.ok) { - return void 0; - } - return await res.arrayBuffer(); - } catch { - return void 0; - } -} -const GET = async ({ request }) => { - try { - const imageService = await getConfiguredImageService(); - if (!("transform" in imageService)) { - throw new Error("Configured image service is not a local service"); - } - const url = new URL(request.url); - const transform = await imageService.parseURL(url, imageConfig); - if (!transform?.src) { - throw new Error("Incorrect transform returned by `parseURL`"); - } - let inputBuffer = void 0; - const isRemoteImage = isRemotePath(transform.src); - if (isRemoteImage && isRemoteAllowed(transform.src, imageConfig) === false) { - return new Response("Forbidden", { status: 403 }); - } - const sourceUrl = new URL(transform.src, url.origin); - if (!isRemoteImage && sourceUrl.origin !== url.origin) { - return new Response("Forbidden", { status: 403 }); - } - inputBuffer = await loadRemoteImage(sourceUrl, isRemoteImage ? new Headers() : request.headers); - if (!inputBuffer) { - return new Response("Not Found", { status: 404 }); - } - const { data, format } = await imageService.transform( - new Uint8Array(inputBuffer), - transform, - imageConfig - ); - return new Response(data, { - status: 200, - headers: { - "Content-Type": mime.lookup(format) ?? `image/${format}`, - "Cache-Control": "public, max-age=31536000", - ETag: etag(data.toString()), - Date: (/* @__PURE__ */ new Date()).toUTCString() - } - }); - } catch (err) { - console.error("Could not process image request:", err); - return new Response(`Server Error: ${err}`, { status: 500 }); - } -}; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - GET -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/about.astro.mjs b/.vercel/output/_functions/pages/about.astro.mjs deleted file mode 100644 index 237ca52..0000000 --- a/.vercel/output/_functions/pages/about.astro.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -export { renderers } from '../renderers.mjs'; - -const $$About = createComponent(($$result, $$props, $$slots) => { - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "About" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}

Douglas M. Galloway

Intelligence Architect · Co-Founder, Esoteria · Baja California

I build systems. For organizations, for teams, for myself. The approach is the same — understand the structure before changing it, build the practice before expecting the outcome, iterate from evidence rather than assumption. This applies whether the system is personal (how you spend your time, make decisions, show up in your work) or organizational (governance design, decision logic, intelligence infrastructure).

I co-founded Esoteria in Baja California. We build intelligence infrastructure for mission-driven organizations — the structural layer that converts fragmented data into governed, repeatable decision logic. The work grew from years of practice in a region where the gap between organizational ambition and organizational capacity is immediate and visible.

The HDK — Human Development Kit — is a personal framework I built over years of practice. I made it public because the methodology is worth sharing. It's not a self-help book. It's a practitioner's field manual for people who want to design their lives with the same rigor they'd bring to building anything else that matters.


Current Work

At any given time I'm running several things in parallel — some organizational, some personal, some creative, some technical. The throughline is the same across all of it: understand the system before changing it, build the practice before expecting the outcome, iterate from evidence rather than assumption.

I'm selective about who I work with — not out of scarcity, but because the work only lands when there's genuine alignment. Details on the Work With Me page.


Outside the work

I'm based in Baja California. I climb, make electronic music, and spend time outdoors when possible. These aren't separate from the work — they're where a lot of it gets tested. A system that only works at a desk isn't much of a system.


` })}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/about.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/about.astro"; -const $$url = "/about"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$About, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/api/subscribe.astro.mjs b/.vercel/output/_functions/pages/api/subscribe.astro.mjs deleted file mode 100644 index ab9e0ad..0000000 --- a/.vercel/output/_functions/pages/api/subscribe.astro.mjs +++ /dev/null @@ -1,47 +0,0 @@ -import { createHmac } from 'crypto'; -export { renderers } from '../../renderers.mjs'; - -const POST = async ({ request }) => { - const data = await request.formData(); - const email = data.get("email")?.toString(); - if (!email || !email.includes("@")) { - return new Response(JSON.stringify({ error: "Valid email required" }), { - status: 400, - headers: { "Content-Type": "application/json" } - }); - } - try { - await fetch("https://api.buttondown.email/v1/subscribers", { - method: "POST", - headers: { - "Authorization": `Token ${undefined }`, - "Content-Type": "application/json" - }, - body: JSON.stringify({ email, tags: ["resources-access"] }) - }); - } catch (e) { - console.error("Buttondown error:", e); - } - const secret = undefined ; - const expiry = Date.now() + 1e3 * 60 * 60 * 24; - const payload = `${email}:${expiry}`; - const token = createHmac("sha256", secret).update(payload).digest("hex"); - const magicLink = `${undefined }/confirm?token=${token}&email=${encodeURIComponent(email)}&expiry=${expiry}`; - console.log("Magic link (dev):", magicLink); - return new Response(JSON.stringify({ - success: true, - message: "Check your email for access link" - }), { - status: 200, - headers: { "Content-Type": "application/json" } - }); -}; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - POST -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/api/verify.astro.mjs b/.vercel/output/_functions/pages/api/verify.astro.mjs deleted file mode 100644 index 76888b7..0000000 --- a/.vercel/output/_functions/pages/api/verify.astro.mjs +++ /dev/null @@ -1,37 +0,0 @@ -import { createHmac } from 'crypto'; -export { renderers } from '../../renderers.mjs'; - -const GET = async ({ request, redirect }) => { - const url = new URL(request.url); - const token = url.searchParams.get("token"); - const email = url.searchParams.get("email"); - const expiry = url.searchParams.get("expiry"); - if (!token || !email || !expiry) { - return redirect("/hdk?error=invalid"); - } - if (Date.now() > parseInt(expiry)) { - return redirect("/hdk?error=expired"); - } - const secret = undefined ; - const payload = `${email}:${expiry}`; - const expected = createHmac("sha256", secret).update(payload).digest("hex"); - if (token !== expected) { - return redirect("/hdk?error=invalid"); - } - const cookieValue = createHmac("sha256", secret).update(email).digest("hex"); - const maxAge = 60 * 60 * 24 * 90; - return redirect("/resources", 302, { - headers: { - "Set-Cookie": `damdug_access=${cookieValue}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${maxAge}` - } - }); -}; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - GET -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/confirm.astro.mjs b/.vercel/output/_functions/pages/confirm.astro.mjs deleted file mode 100644 index 00ce726..0000000 --- a/.vercel/output/_functions/pages/confirm.astro.mjs +++ /dev/null @@ -1,34 +0,0 @@ -import { b as createAstro, c as createComponent, a as renderTemplate } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import 'clsx'; -export { renderers } from '../renderers.mjs'; - -const $$Astro = createAstro("https://damdug.com"); -const $$Confirm = createComponent(($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro, $$props, $$slots); - Astro2.self = $$Confirm; - const token = Astro2.url.searchParams.get("token"); - const email = Astro2.url.searchParams.get("email"); - const expiry = Astro2.url.searchParams.get("expiry"); - if (token && email && expiry) { - const encodedEmail = encodeURIComponent(email); - return Astro2.redirect( - `/api/verify?token=${token}&email=${encodedEmail}&expiry=${expiry}` - ); - } - return renderTemplate``; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/confirm.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/confirm.astro"; -const $$url = "/confirm"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$Confirm, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/contact.astro.mjs b/.vercel/output/_functions/pages/contact.astro.mjs deleted file mode 100644 index 1ae2b88..0000000 --- a/.vercel/output/_functions/pages/contact.astro.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -export { renderers } from '../renderers.mjs'; - -const $$Contact = createComponent(($$result, $$props, $$slots) => { - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "Contact" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}

Contact

For inquiries not covered by the Work With Me page.

` })}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/contact.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/contact.astro"; -const $$url = "/contact"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$Contact, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/hdk.astro.mjs b/.vercel/output/_functions/pages/hdk.astro.mjs deleted file mode 100644 index 14c7508..0000000 --- a/.vercel/output/_functions/pages/hdk.astro.mjs +++ /dev/null @@ -1,41 +0,0 @@ -import { b as createAstro, c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -import { $ as $$SignupForm } from '../chunks/SignupForm_DXiTqlCO.mjs'; -export { renderers } from '../renderers.mjs'; - -const $$Astro = createAstro("https://damdug.com"); -const $$Hdk = createComponent(($$result, $$props, $$slots) => { - const Astro2 = $$result.createAstro($$Astro, $$props, $$slots); - Astro2.self = $$Hdk; - const error = Astro2.url.searchParams.get("error"); - const signup = Astro2.url.searchParams.get("signup"); - let errorMessage = ""; - if (error === "expired") errorMessage = "// That link has expired. Request a new one below."; - if (error === "invalid") errorMessage = "// That link isn't valid. Request a new one below."; - if (signup === "true") errorMessage = "// Sign up to access the full resources library."; - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "HDK" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}

Human Development Kit

What It Is

A structured approach to building your personal operating system. Process design applied to life — not as metaphor, but as method. Built from years of practice across work, health, learning, decision-making, and creative output. It's a field manual for people who understand that sustainable outcomes don't come from motivation or shortcuts — they come from well-designed systems.

What's Inside

Nine chapters, each a layer of the framework:

  • 1. Stack Audit — where you actually are -
  • 2. Physical Systems — the hardware layer -
  • 3. Mental & Emotional Architecture — the operating system -
  • 4. Environment — configuring your inputs -
  • 5. Structure & Routine — daily operating procedures -
  • 6. Growth Modules — deliberate expansion -
  • 7. Purpose & Philosophy — the why layer -
  • 8. Adaptability — version control for your LifeStack -
  • 9. Integration — running the full stack -

The Field Kit

The HDK Field Kit is the working companion to this framework. Seven worksheets for mapping your stack, tracking your changelog, clarifying your values, and building your minimum viable routine.

Pay what it's worth. Suggested $5. Minimum $1.

Get the Field Kit

${errorMessage && renderTemplate`

${errorMessage}

`}

Free to download. One signup unlocks this and everything else I've built.

${renderComponent($$result2, "SignupForm", $$SignupForm, { "label": "", "buttonText": "Get Access", "placeholder": "your@email.com" })}
` })}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/hdk.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/hdk.astro"; -const $$url = "/hdk"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$Hdk, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/index.astro.mjs b/.vercel/output/_functions/pages/index.astro.mjs deleted file mode 100644 index 96013c9..0000000 --- a/.vercel/output/_functions/pages/index.astro.mjs +++ /dev/null @@ -1,29 +0,0 @@ -import { c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -import { $ as $$SignupForm } from '../chunks/SignupForm_DXiTqlCO.mjs'; -export { renderers } from '../renderers.mjs'; - -const $$Index = createComponent(($$result, $$props, $$slots) => { - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "Home" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}

DOUGLAS M. GALLOWAY

Systems over shortcuts.

-I build systems — for organizations, for teams, for myself. This is where I think out loud about what that looks like in practice. -

Process. Design. Execution. One approach.

-Free access to everything I've built. The HDK. The One Rule framework. One signup. -

${renderComponent($$result2, "SignupForm", $$SignupForm, { "buttonText": "Get Access", "placeholder": "your@email.com", "label": "" })}
` })}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/index.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/index.astro"; -const $$url = ""; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$Index, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/notes.astro.mjs b/.vercel/output/_functions/pages/notes.astro.mjs deleted file mode 100644 index 8289771..0000000 --- a/.vercel/output/_functions/pages/notes.astro.mjs +++ /dev/null @@ -1,35 +0,0 @@ -import { c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead, e as addAttribute } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -import { g as getCollection } from '../chunks/_astro_content_C1JXYIk2.mjs'; -export { renderers } from '../renderers.mjs'; - -const $$Index = createComponent(async ($$result, $$props, $$slots) => { - const allNotes = await getCollection("notes", ({ data }) => !data.draft); - const sortedNotes = allNotes.sort((a, b) => b.data.date.getTime() - a.data.date.getTime()); - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "Notes" }, { "default": async ($$result2) => renderTemplate` ${maybeRenderHead()}

Notes

${sortedNotes.length === 0 ? renderTemplate`

// Nothing here yet. Check back soon.

` : renderTemplate`
${sortedNotes.map((note) => { - const formatted = note.data.date.toISOString().split("T")[0]; - const noteUrl = `/notes/${note.slug}`; - const isOneRuleNote = ["the-one-rule", "the-non-impedance-principle", "the-next-step-doctrine"].includes(note.slug); - return renderTemplate`

${note.data.title}

${note.data.category}
${isOneRuleNote && renderTemplate`

-Part of${" "} -The One Rule Framework -${" "} -→ -

`}
${formatted} `; - })}
`}
` })}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/notes/index.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/notes/index.astro"; -const $$url = "/notes"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$Index, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/notes/_slug_.astro.mjs b/.vercel/output/_functions/pages/notes/_slug_.astro.mjs deleted file mode 100644 index e8ff7a4..0000000 --- a/.vercel/output/_functions/pages/notes/_slug_.astro.mjs +++ /dev/null @@ -1 +0,0 @@ -// Contents removed by Astro as it's used for prerendering only \ No newline at end of file diff --git a/.vercel/output/_functions/pages/one-rule.astro.mjs b/.vercel/output/_functions/pages/one-rule.astro.mjs deleted file mode 100644 index c8a212f..0000000 --- a/.vercel/output/_functions/pages/one-rule.astro.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import { c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -import { $ as $$SignupForm } from '../chunks/SignupForm_DXiTqlCO.mjs'; -/* empty css */ -export { renderers } from '../renderers.mjs'; - -const $$OneRule = createComponent(($$result, $$props, $$slots) => { - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "The One Rule", "data-astro-cid-hghskpuw": true }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}

The One Rule

I've been applying the same principle to everything I do for years without naming it.

Traffic law taught it to me. All of it reduces to one rule: don't impede other drivers. Not a destination. Not an outcome. One obligation at every step that produces a system capable of moving through impossible complexity without breaking down.

I use it for personal planning. For organizational decision logic. For AI implementation. For SOPs. For how I structure my days. The scale changes. The principle doesn't.

This is that principle, documented in three parts.


  1. 01

    The One Rule

    The principle and the problem it solves.

    Read →

  2. 02

    The Non-Impedance Principle

    How to apply it to systems and workflows.

    Read →

  3. 03

    The Next Step Doctrine

    How to apply it to yourself.

    Read →


If this changes how you think about something, you can follow it as it develops.

One signup also unlocks the HDK — a personal operating system framework built on the same foundation.

${renderComponent($$result2, "SignupForm", $$SignupForm, { "buttonText": "Get Access", "placeholder": "your@email.com", "label": "", "data-astro-cid-hghskpuw": true })}

If you want to apply this directly — to your own system or your organization's — Work With Me is where that starts.

` })} `; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/one-rule.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/one-rule.astro"; -const $$url = "/one-rule"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$OneRule, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/pages/resources.astro.mjs b/.vercel/output/_functions/pages/resources.astro.mjs deleted file mode 100644 index e8ff7a4..0000000 --- a/.vercel/output/_functions/pages/resources.astro.mjs +++ /dev/null @@ -1 +0,0 @@ -// Contents removed by Astro as it's used for prerendering only \ No newline at end of file diff --git a/.vercel/output/_functions/pages/work-with-me.astro.mjs b/.vercel/output/_functions/pages/work-with-me.astro.mjs deleted file mode 100644 index 6e23de6..0000000 --- a/.vercel/output/_functions/pages/work-with-me.astro.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { c as createComponent, r as renderComponent, a as renderTemplate, m as maybeRenderHead } from '../chunks/astro/server_D2NiA7f1.mjs'; -import 'piccolore'; -import { $ as $$BaseLayout } from '../chunks/BaseLayout_CRo5-Q8Q.mjs'; -export { renderers } from '../renderers.mjs'; - -const $$WorkWithMe = createComponent(($$result, $$props, $$slots) => { - return renderTemplate`${renderComponent($$result, "BaseLayout", $$BaseLayout, { "title": "Work With Me" }, { "default": ($$result2) => renderTemplate` ${maybeRenderHead()}

Work With Me

Good practices generally produce good outcomes. The reverse isn't true. That single inversion is the basis of everything I do — personally and professionally.

For individuals

Structured, honest work on your personal system. Where you are. What's not working. What the next step actually is. This applies whether you're working on how you spend your time, how you make decisions, or how you want to show up in your work and life. 1:1. Limited availability.

For organizations

For organizations and teams ready to examine how they actually work — the process design, the decision logic, the execution gaps that compound quietly over time. The market is full of platforms, AI solutions, and software promising to solve structural problems — and most of them make those problems harder to diagnose. The work starts before the tool selection. Decision logic, governance, the conditions that make good outcomes repeatable. Scope varies by engagement. The methodology doesn't.


Both start the same way.

A conversation first. No proposal without one. If there's a fit, we build something together. If there isn't, you'll leave with a clearer picture of what you actually need.

` })}`; -}, "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/work-with-me.astro", void 0); - -const $$file = "/Users/douglasgalloway/Documents/GitHub/damdug.github.io/src/pages/work-with-me.astro"; -const $$url = "/work-with-me"; - -const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ - __proto__: null, - default: $$WorkWithMe, - file: $$file, - url: $$url -}, Symbol.toStringTag, { value: 'Module' })); - -const page = () => _page; - -export { page }; diff --git a/.vercel/output/_functions/renderers.mjs b/.vercel/output/_functions/renderers.mjs deleted file mode 100644 index a97849f..0000000 --- a/.vercel/output/_functions/renderers.mjs +++ /dev/null @@ -1,3 +0,0 @@ -const renderers = []; - -export { renderers }; diff --git a/.vercel/output/config.json b/.vercel/output/config.json deleted file mode 100644 index ec5213f..0000000 --- a/.vercel/output/config.json +++ /dev/null @@ -1,63 +0,0 @@ -{ - "version": 3, - "routes": [ - { - "handle": "filesystem" - }, - { - "src": "^/_astro/(.*)$", - "headers": { - "cache-control": "public, max-age=31536000, immutable" - }, - "continue": true - }, - { - "src": "^/_server-islands/([^/]+?)/?$", - "dest": "_render" - }, - { - "src": "^/_image/?$", - "dest": "_render" - }, - { - "src": "^/about/?$", - "dest": "_render" - }, - { - "src": "^/api/subscribe/?$", - "dest": "_render" - }, - { - "src": "^/api/verify/?$", - "dest": "_render" - }, - { - "src": "^/confirm/?$", - "dest": "_render" - }, - { - "src": "^/contact/?$", - "dest": "_render" - }, - { - "src": "^/hdk/?$", - "dest": "_render" - }, - { - "src": "^/notes/?$", - "dest": "_render" - }, - { - "src": "^/one-rule/?$", - "dest": "_render" - }, - { - "src": "^/work-with-me/?$", - "dest": "_render" - }, - { - "src": "^/$", - "dest": "_render" - } - ] -} \ No newline at end of file diff --git a/.vercel/output/functions/_render.func/.vc-config.json b/.vercel/output/functions/_render.func/.vc-config.json deleted file mode 100644 index a094d8e..0000000 --- a/.vercel/output/functions/_render.func/.vc-config.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "runtime": "nodejs20.x", - "handler": "dist/server/entry.mjs", - "launcherType": "Nodejs", - "supportsResponseStreaming": true -} \ No newline at end of file diff --git a/.vercel/output/functions/_render.func/package.json b/.vercel/output/functions/_render.func/package.json deleted file mode 100644 index 47dc78d..0000000 --- a/.vercel/output/functions/_render.func/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "type": "module" -} \ No newline at end of file diff --git a/.vercel/output/functions/_render.func/src/pages/about.astro b/.vercel/output/functions/_render.func/src/pages/about.astro deleted file mode 100644 index 041097b..0000000 --- a/.vercel/output/functions/_render.func/src/pages/about.astro +++ /dev/null @@ -1,42 +0,0 @@ ---- -import BaseLayout from '../layouts/BaseLayout.astro'; ---- - -
-

Douglas M. Galloway

-

Intelligence Architect · Co-Founder, Esoteria · Baja California

- -
-

I build systems. For organizations, for teams, for myself. The approach is the same — understand the structure before changing it, build the practice before expecting the outcome, iterate from evidence rather than assumption. This applies whether the system is personal (how you spend your time, make decisions, show up in your work) or organizational (governance design, decision logic, intelligence infrastructure).

- -

I co-founded Esoteria in Baja California. We build intelligence infrastructure for mission-driven organizations — the structural layer that converts fragmented data into governed, repeatable decision logic. The work grew from years of practice in a region where the gap between organizational ambition and organizational capacity is immediate and visible.

- -

The HDK — Human Development Kit — is a personal framework I built over years of practice. I made it public because the methodology is worth sharing. It's not a self-help book. It's a practitioner's field manual for people who want to design their lives with the same rigor they'd bring to building anything else that matters.

- -
- -
-

Current Work

-

At any given time I'm running several things in parallel — some organizational, some personal, some creative, some technical. The throughline is the same across all of it: understand the system before changing it, build the practice before expecting the outcome, iterate from evidence rather than assumption.

-

I'm selective about who I work with — not out of scarcity, but because the work only lands when there's genuine alignment. Details on the Work With Me page.

-
- -
- -
-

Outside the work

-

I'm based in Baja California. I climb, make electronic music, and spend time outdoors when possible. These aren't separate from the work — they're where a lot of it gets tested. A system that only works at a desk isn't much of a system.

-
- -
- -
-

Elsewhere

- -
-
-
-
diff --git a/.vercel/output/functions/_render.func/src/pages/confirm.astro b/.vercel/output/functions/_render.func/src/pages/confirm.astro deleted file mode 100644 index 036de1c..0000000 --- a/.vercel/output/functions/_render.func/src/pages/confirm.astro +++ /dev/null @@ -1,14 +0,0 @@ ---- -// Client-side redirect to /api/verify with all params -const token = Astro.url.searchParams.get('token'); -const email = Astro.url.searchParams.get('email'); -const expiry = Astro.url.searchParams.get('expiry'); - -if (token && email && expiry) { - const encodedEmail = encodeURIComponent(email); - return Astro.redirect( - `/api/verify?token=${token}&email=${encodedEmail}&expiry=${expiry}` - ); -} ---- - diff --git a/.vercel/output/functions/_render.func/src/pages/contact.astro b/.vercel/output/functions/_render.func/src/pages/contact.astro deleted file mode 100644 index 88a7dc1..0000000 --- a/.vercel/output/functions/_render.func/src/pages/contact.astro +++ /dev/null @@ -1,31 +0,0 @@ ---- -import BaseLayout from '../layouts/BaseLayout.astro'; ---- - -
-

Contact

- -
-

For inquiries not covered by the Work With Me page.

- -
-
- - -
- -
- - -
- -
- - -
- - -
-
-
-
diff --git a/.vercel/output/functions/_render.func/src/pages/hdk.astro b/.vercel/output/functions/_render.func/src/pages/hdk.astro deleted file mode 100644 index 313afbb..0000000 --- a/.vercel/output/functions/_render.func/src/pages/hdk.astro +++ /dev/null @@ -1,71 +0,0 @@ ---- -import BaseLayout from '../layouts/BaseLayout.astro'; -import SignupForm from '../components/SignupForm.astro'; - -const error = Astro.url.searchParams.get('error'); -const signup = Astro.url.searchParams.get('signup'); - -let errorMessage = ''; -if (error === 'expired') errorMessage = '// That link has expired. Request a new one below.'; -if (error === 'invalid') errorMessage = '// That link isn\'t valid. Request a new one below.'; -if (signup === 'true') errorMessage = '// Sign up to access the full resources library.'; ---- - -
-

Human Development Kit

- -
-
-

What It Is

-

A structured approach to building your personal operating system. Process design applied to life — not as metaphor, but as method. Built from years of practice across work, health, learning, decision-making, and creative output. It's a field manual for people who understand that sustainable outcomes don't come from motivation or shortcuts — they come from well-designed systems.

-
- -
-

What's Inside

-

Nine chapters, each a layer of the framework:

-
    -
  • - 1. Stack Audit — where you actually are -
  • -
  • - 2. Physical Systems — the hardware layer -
  • -
  • - 3. Mental & Emotional Architecture — the operating system -
  • -
  • - 4. Environment — configuring your inputs -
  • -
  • - 5. Structure & Routine — daily operating procedures -
  • -
  • - 6. Growth Modules — deliberate expansion -
  • -
  • - 7. Purpose & Philosophy — the why layer -
  • -
  • - 8. Adaptability — version control for your LifeStack -
  • -
  • - 9. Integration — running the full stack -
  • -
-
- -
-

The Field Kit

-

The HDK Field Kit is the working companion to this framework. Seven worksheets for mapping your stack, tracking your changelog, clarifying your values, and building your minimum viable routine.

-

Pay what it's worth. Suggested $5. Minimum $1.

-

Get the Field Kit

-
- -
- {errorMessage &&

{errorMessage}

} -

Free to download. One signup unlocks this and everything else I've built.

- -
-
-
-
diff --git a/.vercel/output/functions/_render.func/src/pages/index.astro b/.vercel/output/functions/_render.func/src/pages/index.astro deleted file mode 100644 index 1fe1238..0000000 --- a/.vercel/output/functions/_render.func/src/pages/index.astro +++ /dev/null @@ -1,50 +0,0 @@ ---- -import BaseLayout from '../layouts/BaseLayout.astro'; -import SignupForm from '../components/SignupForm.astro'; ---- - - -
-
-

DOUGLAS M. GALLOWAY

-

Systems over shortcuts.

-

- I build systems — for organizations, for teams, for myself. This is where I think out loud about what that looks like in practice. -

-

Process. Design. Execution. One approach.

-
-
- -
- -
- -
-
-

- Free access to everything I've built. The HDK. The One Rule framework. One signup. -

- -
-
-
diff --git a/.vercel/output/functions/_render.func/src/pages/notes/index.astro b/.vercel/output/functions/_render.func/src/pages/notes/index.astro deleted file mode 100644 index bc3e6aa..0000000 --- a/.vercel/output/functions/_render.func/src/pages/notes/index.astro +++ /dev/null @@ -1,49 +0,0 @@ ---- -import BaseLayout from '../../layouts/BaseLayout.astro'; -import { getCollection } from 'astro:content'; - -const allNotes = await getCollection('notes', ({ data }) => !data.draft); -const sortedNotes = allNotes.sort((a, b) => b.data.date.getTime() - a.data.date.getTime()); ---- - - -
-

Notes

- - { - sortedNotes.length === 0 ? ( -

// Nothing here yet. Check back soon.

- ) : ( -
- {sortedNotes.map((note) => { - const formatted = note.data.date.toISOString().split('T')[0]; - const noteUrl = `/notes/${note.slug}`; - const isOneRuleNote = ['the-one-rule', 'the-non-impedance-principle', 'the-next-step-doctrine'].includes(note.slug); - return ( - - - {formatted} - - ); - })} -
- ) - } -
-
diff --git a/.vercel/output/functions/_render.func/src/pages/one-rule.astro b/.vercel/output/functions/_render.func/src/pages/one-rule.astro deleted file mode 100644 index 6a22f28..0000000 --- a/.vercel/output/functions/_render.func/src/pages/one-rule.astro +++ /dev/null @@ -1,77 +0,0 @@ ---- -import BaseLayout from '../layouts/BaseLayout.astro'; -import SignupForm from '../components/SignupForm.astro'; ---- - -
-

The One Rule

- -
-

I've been applying the same principle to everything I do for years without naming it.

- -

Traffic law taught it to me. All of it reduces to one rule: don't impede other drivers. Not a destination. Not an outcome. One obligation at every step that produces a system capable of moving through impossible complexity without breaking down.

- -

I use it for personal planning. For organizational decision logic. For AI implementation. For SOPs. For how I structure my days. The scale changes. The principle doesn't.

- -

This is that principle, documented in three parts.

- -
- -
-
    -
  1. - -
    - 01 -
    -

    The One Rule

    -

    The principle and the problem it solves.

    -

    Read →

    -
    -
    -
    -
  2. -
  3. - -
    - 02 -
    -

    The Non-Impedance Principle

    -

    How to apply it to systems and workflows.

    -

    Read →

    -
    -
    -
    -
  4. -
  5. - -
    - 03 -
    -

    The Next Step Doctrine

    -

    How to apply it to yourself.

    -

    Read →

    -
    -
    -
    -
  6. -
-
- -
- -
-

If this changes how you think about something, you can follow it as it develops.

-

One signup also unlocks the HDK — a personal operating system framework built on the same foundation.

- -

If you want to apply this directly — to your own system or your organization's — Work With Me is where that starts.

-
-
-
-
- - diff --git a/.vercel/output/functions/_render.func/src/pages/work-with-me.astro b/.vercel/output/functions/_render.func/src/pages/work-with-me.astro deleted file mode 100644 index 113448d..0000000 --- a/.vercel/output/functions/_render.func/src/pages/work-with-me.astro +++ /dev/null @@ -1,50 +0,0 @@ ---- -import BaseLayout from '../layouts/BaseLayout.astro'; ---- - -
-

Work With Me

- -
-

Good practices generally produce good outcomes. The reverse isn't true. That single inversion is the basis of everything I do — personally and professionally.

- -
-

For individuals

-

Structured, honest work on your personal system. Where you are. What's not working. What the next step actually is. This applies whether you're working on how you spend your time, how you make decisions, or how you want to show up in your work and life. 1:1. Limited availability.

-
- -
-

For organizations

-

For organizations and teams ready to examine how they actually work — the process design, the decision logic, the execution gaps that compound quietly over time. The market is full of platforms, AI solutions, and software promising to solve structural problems — and most of them make those problems harder to diagnose. The work starts before the tool selection. Decision logic, governance, the conditions that make good outcomes repeatable. Scope varies by engagement. The methodology doesn't.

-
- -
- -
-

Both start the same way.

-

A conversation first. No proposal without one. If there's a fit, we build something together. If there isn't, you'll leave with a clearer picture of what you actually need.

-
- -
-
-
- - -
- -
- - -
- -
- - -
- - -
-
-
-
-
diff --git a/.vercel/output/static/assets/icons/facebook.svg b/.vercel/output/static/assets/icons/facebook.svg deleted file mode 100644 index ce5af39..0000000 --- a/.vercel/output/static/assets/icons/facebook.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.vercel/output/static/assets/icons/github.svg b/.vercel/output/static/assets/icons/github.svg deleted file mode 100644 index d699b79..0000000 --- a/.vercel/output/static/assets/icons/github.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.vercel/output/static/assets/icons/instagram.svg b/.vercel/output/static/assets/icons/instagram.svg deleted file mode 100644 index c8da4b2..0000000 --- a/.vercel/output/static/assets/icons/instagram.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.vercel/output/static/assets/icons/linkedin.svg b/.vercel/output/static/assets/icons/linkedin.svg deleted file mode 100644 index afb268d..0000000 --- a/.vercel/output/static/assets/icons/linkedin.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.vercel/output/static/assets/icons/twitter-x.svg b/.vercel/output/static/assets/icons/twitter-x.svg deleted file mode 100644 index 4d55c27..0000000 --- a/.vercel/output/static/assets/icons/twitter-x.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.vercel/output/static/assets/icons/whatsapp.svg b/.vercel/output/static/assets/icons/whatsapp.svg deleted file mode 100644 index 73cc4ac..0000000 --- a/.vercel/output/static/assets/icons/whatsapp.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/.vercel/output/static/assets/logo/dune.svg b/.vercel/output/static/assets/logo/dune.svg deleted file mode 100644 index e37359f..0000000 --- a/.vercel/output/static/assets/logo/dune.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/.vercel/output/static/favicon.ico b/.vercel/output/static/favicon.ico deleted file mode 100644 index 7f48a94d16071d6c8d06478c7458ab12e675019c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 655 zcmV;A0&x9_P)Rl-XF(A`bsas&GH{e7U1}Ri zJr5jR8B2*Jd6$=$AqgTM2o2FV$WZ9|#jJ3mmpEs{jB0ps@*Kxv}=RB|IJih8Z&fqwCG`%bN0000#bW%=J zQ=IH#a_&L{B{_6Lu_3m>0bMN%+@aOmN_3G~H^8EGi>+bXO=;-|Z`uFnf==AdP z{Oj-S=ltmI=<4`LcLE*&009F@L_t(|+I`d4ZUZ3@1<*Uo7H^LoCw6-8z4wsbd;b4l zA}zMFtOw2mLX6O5Mgl}(5P=uOM4%=tnuHiuAp%(G<c=npm$Fz%eL - - - diff --git a/.vercel/output/static/notes/the-next-step-doctrine/index.html b/.vercel/output/static/notes/the-next-step-doctrine/index.html deleted file mode 100644 index 3b80e6b..0000000 --- a/.vercel/output/static/notes/the-next-step-doctrine/index.html +++ /dev/null @@ -1,34 +0,0 @@ - The Next Step Doctrine — DMG
life businesslife

The Next Step Doctrine

2026-01-15

The human tendency is to see the result and not the work that produced it.

-

The finished business. The person operating at full capacity. The system running cleanly. We see the destination and assume that’s the thing to aim at. We set our sights on the outcome and wonder why the gap between where we are and where we want to be doesn’t close.

-

It doesn’t close because we’re optimizing for the wrong thing.

-

The Next Step Doctrine is the personal practice of The One Rule. Not a planning method. Not a productivity system. A discipline for keeping your attention where it can actually do something — on the step directly in front of you.

-

Why the finish line is the wrong focus

-

Outcomes are the wrong unit of optimization for one reason: you don’t control them.

-

You control the step in front of you. The quality of your attention at this decision, this task, this moment. Whether what you do right now clears the way for what comes next or quietly impedes it. That’s the full extent of your operational leverage at any given point.

-

This isn’t pessimism about outcomes. It’s precision about what you can actually move.

-

When behavior doesn’t match values the problem is almost never at the level of values. People rarely stop caring about what matters to them. The problem is at the micro level — individual decisions made without asking whether they serve or violate the thing they’re supposed to. The drift is invisible until it’s structural. By then it looks like a character problem or a motivation problem. It’s a systems problem. Specifically it’s an attention problem — attention was on the outcome instead of the step.

-

The same drift happens in planning. Someone sets a goal, imagines the result, feels motivated, and begins executing. Three weeks in the motivation fades because the finish line hasn’t moved perceptibly. The goal was the fuel and the goal is still distant. The step in front of them — the one that’s actually available to work on — becomes something to get through rather than something to execute with precision.

-

Optimizing for the finish line makes every step feel like an obstacle between you and the thing you actually want. Optimizing for the next step makes every step the thing you actually want.

-

The doctrine in practice

-

The Next Step Doctrine asks one question before any planning session, any decision, any day:

-

What is the next step, and what does it need from me in order not to impede what follows?

-

This question does several things simultaneously.

-

It makes the work concrete. The next step is always specific. The goal is often abstract. Abstraction is where motivation lives and dies. Specificity is where work happens.

-

It makes quality measurable. A step either clears the way for the next one or it doesn’t. That’s a standard you can evaluate honestly without waiting for the outcome to tell you whether you succeeded.

-

It makes values operational. Your values aren’t aspirations to perform toward — they’re the standard each micro-decision is measured against before it’s made. The question isn’t “am I a person who values X?” It’s “does this step serve X or impede it?” One question, applied consistently, closes the gap between stated values and actual behavior without requiring willpower or motivation as the mechanism.

-

It makes progress visible at the right scale. Progress measured against a distant outcome is almost always discouraging. Progress measured against whether today handed tomorrow what it needed is available every day. The compound effect of that — days that consistently hand off cleanly — is what outcomes are made of.

-

Planning from the next step

-

Most planning starts at the goal and works backwards. Identify the destination, break it into milestones, break milestones into tasks, execute the tasks.

-

This works structurally and fails practically because it front-loads all the clarity into the goal — which is the part you understand least — and assumes the steps will become clear as you move through them. They often don’t. The map drawn from the destination is a guess. The map drawn from the next step is built from what you actually know.

-

The Next Step Doctrine plans forward instead.

-

Start with your current honest position — not where you intend to be or used to be but where you actually are right now. From that position identify one step — not the optimal step, not the strategic step, the next available step that doesn’t impede what follows. Execute it with full attention. Evaluate it not by whether it moved you toward the goal but by whether it handed the next step what it needed.

-

Repeat.

-

The goal stays visible as orientation. It tells you which direction to face. But the work is always the step in front of you. The finish line is not where your attention lives — it’s where you look occasionally to confirm you’re still facing the right way.

-

The belief underneath all of it

-

The One Rule is the governing principle. The Non-Impedance Principle is how you apply it to systems. The Next Step Doctrine is how you apply it to yourself.

-

All three are the same idea at different scales.

-

Good practices generally produce good outcomes. The reverse isn’t true.

-

Start with the next step. The finish line follows.

\ No newline at end of file diff --git a/.vercel/output/static/notes/the-non-impedance-principle/index.html b/.vercel/output/static/notes/the-non-impedance-principle/index.html deleted file mode 100644 index 242cb52..0000000 --- a/.vercel/output/static/notes/the-non-impedance-principle/index.html +++ /dev/null @@ -1,33 +0,0 @@ - The Non-Impedance Principle — DMG
business technology

The Non-Impedance Principle

2025-12-01

A step that produces a good result but blocks what follows has failed.

-

This is the working definition of impedance in a system. Not failure at the local level — failure at the handoff. And it’s where most workflows, decision chains, and organizational processes quietly break down.

-

The Non-Impedance Principle is The One Rule applied to how you build and operate systems. It answers a specific question: how do you maintain alignment through complexity when the number of steps, people, and variables makes oversight impossible?

-

You don’t oversee every step. You govern the handoff between them.

-

Where systems lose alignment

-

Complex systems don’t fail dramatically. They drift.

-

A workflow where each step optimizes for its own output rather than its handoff produces friction that compounds invisibly. A decision chain where each choice is locally rational but doesn’t account for what it forecloses produces outcomes nobody designed and nobody can fully explain. An AI implementation where each prompt reaches for the final answer rather than the next clarifying input produces responses that sound right and miss the point.

-

The misalignment isn’t visible at the step level. It accumulates in the gaps between steps and surfaces as a system that doesn’t work — without a clear diagnosis of why.

-

The conventional response is more process. More documentation. More oversight. More meetings to align the people who were supposed to be aligned by the process.

-

None of that addresses the actual problem. The problem is that individual steps weren’t designed with their handoff as the primary obligation.

-

The principle in practice

-

The Non-Impedance Principle introduces one standard at every step of any system:

-

What does the next step need from this one in order to proceed without friction?

-

This question is deceptively simple. Answering it honestly requires understanding not just what you’re producing but what you’re handing off — and to whom, in what condition, with what information attached.

-

Applied to workflow design this means every step in a process is evaluated not by its output alone but by the quality of what it passes forward. A handoff that requires the next person to interpret, reconstruct, or compensate for missing information is an impedance point regardless of how well the step itself was executed.

-

Applied to decision-making this means every choice is evaluated not just by its immediate merit but by what it keeps open and what it forecloses. A decision that solves today’s problem by constraining tomorrow’s options may be locally correct and systemically damaging. Non-impedance asks: does this decision preserve the integrity of the steps that follow?

-

Applied to AI and chain-of-thought prompting this means each prompt has one job — not to produce the final answer but to produce the next useful input. The goal of a prompt is to not impede the next prompt. The output accumulates across the chain. Reaching for the conclusion at any single step collapses the chain and produces a response that skips the reasoning that would have made it reliable.

-

Designing for non-impedance

-

A system designed around this principle looks different from one designed around outcomes.

-

Outcome-designed systems work backwards from the goal. Steps exist to serve the destination. Quality is measured by proximity to the result. When things go wrong the diagnosis looks at whether the goal was right, whether people were motivated, whether the strategy was sound.

-

Non-impedance-designed systems work forward from the first step. Each step is designed to hand off cleanly to the next. Quality is measured at the handoff. When things go wrong the diagnosis looks for the impedance point — the step that failed its obligation to what followed — and fixes it there.

-

In SOPs this means writing each step not as an instruction for what to do but as a specification of what the next step needs to receive. The test of a well-written SOP is whether someone could execute each step knowing only what they’ve been handed and what the next step requires — without needing to understand the whole process.

-

In organizational decision-making this means every significant choice includes an explicit account of what it hands forward. Not just what it decides — what it sets up, what it constrains, what information it produces for the next decision-maker in the chain.

-

In personal planning this means your system is evaluated not by whether you reached the goal but by whether each day handed the next one what it needed. A day that was productive but left tomorrow’s priorities unclear has an impedance problem regardless of what it accomplished.

-

The diagnostic question

-

When a system isn’t working — personally or organizationally — the Non-Impedance Principle gives you a diagnostic tool more precise than most.

-

Don’t start at the outcome. Don’t start at the strategy. Start at the first step and move forward asking one question at each transition:

-

Did this step give the next one what it needed?

-

The first place the answer is no is the impedance point. Fix it there. Not at the goal level. Not at the motivation level. At the handoff.

-

This is slower than jumping to a macro diagnosis. It is significantly more likely to produce a fix that holds.

\ No newline at end of file diff --git a/.vercel/output/static/notes/the-one-rule/index.html b/.vercel/output/static/notes/the-one-rule/index.html deleted file mode 100644 index 134c011..0000000 --- a/.vercel/output/static/notes/the-one-rule/index.html +++ /dev/null @@ -1,32 +0,0 @@ - The One Rule — DMG
business life

The One Rule

2025-11-10

All traffic law reduces to one rule: don’t impede other drivers.

-

Not a destination. Not an outcome. One behavioral obligation, followed consistently at every step, that produces a system capable of moving millions of people through impossible complexity without central coordination.

-

Most systems — personal and organizational — don’t work this way. They should.

-

The problem this solves

-

There is a gap that appears in every system eventually.

-

In personal life it looks like behavior that doesn’t match values. Someone knows what matters to them and consistently acts against it anyway. Not from weakness. From misalignment at the micro level — individual decisions that seem reasonable in isolation but quietly violate the principle they’re supposed to serve.

-

In organizations it looks like actions that don’t produce results. Teams work hard, execute correctly by local measures, and still miss the outcome. The problem is rarely effort or competence. It’s that steps were optimized for their own output rather than for what they hand off to what follows.

-

Both are the same problem at different scales.

-

The thread gets lost not in the strategy but in the gap between one step and the next. By the time the misalignment is visible it’s structural. The drift happened quietly at the micro level and surfaced as something that looks like a macro problem. More planning doesn’t fix it. More motivation doesn’t fix it.

-

A clearer governing principle does.

-

The One Rule

-

Every traffic law — merging, signaling, right of way, speed — exists in service of one thing: don’t block the car behind you. That single obligation, honored by every driver at every moment, produces a system that works without anyone managing it from the center.

-

Applied to how you plan, decide, and build:

-

Each step has one obligation — not to impede the step that follows.

-

This is the governing principle underneath everything I do personally and professionally. Not a productivity hack. Not a goal-setting framework. A standard applied at the micro level that keeps systems aligned through complexity without requiring constant oversight or correction.

-

The destination matters. It tells you which direction to face. But you don’t drive looking at the destination. You drive looking at the road directly in front of you, making sure you don’t impede what comes next, trusting that everyone doing the same thing produces a system that works.

-

What changes when you apply it

-

The question you ask at every decision point changes.

-

Before: Will this get me to the goal? -After: Does this clear the way for what comes next?

-

That single reframe shifts focus from outcome — which you don’t control — to handoff quality, which you do. A step that produces a locally good result but leaves the next step without what it needs has failed by this standard regardless of its own quality.

-

This is where most planning breaks down. Strategy operates at the macro level and assumes the micro will follow. It doesn’t. Alignment has to be built into each step or it isn’t built at all.

-

The One Rule operates at the micro level by design. One question at every step:

-

What does the next step need from this one in order to proceed without friction?

-

Answer that consistently and the macro takes care of itself. Miss it consistently and no amount of vision or strategy repairs the drift.

-

The belief underneath it

-

Good practices generally produce good outcomes. The reverse isn’t true.

-

You cannot optimize for outcomes directly. Outcomes depend on conditions outside your control. What you control is the practice — the step in front of you and whether it clears the way for the next one.

-

Focus there. The finish line follows.

\ No newline at end of file diff --git a/.vercel/output/static/resources/index.html b/.vercel/output/static/resources/index.html deleted file mode 100644 index 4f8d7f1..0000000 --- a/.vercel/output/static/resources/index.html +++ /dev/null @@ -1,3 +0,0 @@ - Resources — DMG

Resources

Everything here is free. One signup unlocks all of it. These are the tools and references I actually use — built by practitioners, not consulting firms.

Curated Stack

Anthropic Prompting Documentation

The most honest practical documentation on using AI effectively. No hype. How chain-of-thought actually works.

Shape Up by Basecamp

Free online. Project methodology built around appetite and fixed time rather than estimates. Constraints force clarity. Ship what matters.

Measure What Matters by John Doerr

The OKR framework. Worth understanding as context for how most organizations measure progress — and why a simpler scoring approach often works better.

Untools

A free collection of thinking frameworks organized by category. Systems thinking, decision making, problem solving. Browse before you need it.

NIST AI Risk Management Framework

The closest thing to an institutional standard for AI governance. Free to download. What regulators and enterprise clients increasingly reference.

readmake.com

Resources for independent makers and builders. Practical, practitioner-built, no fluff.

This list is updated as I find things worth adding.

\ No newline at end of file diff --git a/package.json b/package.json index 8708e78..cd36fef 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "damdug.com", + "name": "receptive-resonance", "type": "module", "version": "0.0.1", "scripts": {