@astroscope/node 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -254,14 +254,14 @@ node({
254
254
  // request logging at the native handler. Enabled by default in production;
255
255
  // false disables it (the log proxy keeps working).
256
256
  logging: {
257
- exclude: [{ prefix: '/internal/' }], // replaces RECOMMENDED_EXCLUDES + STATIC_EXCLUDES
257
+ exclude: [{ prefix: '/internal/' }], // replaces RECOMMENDED_EXCLUDES
258
258
  extended: false, // query/headers/client address (may capture sensitive data)
259
259
  dev: false, // also log requests in dev (astro narrates them already)
260
260
  },
261
261
 
262
262
  // platform telemetry. Enabled by default in production, off in dev; false disables.
263
263
  telemetry: {
264
- exclude: [{ prefix: '/internal/' }], // replaces RECOMMENDED_EXCLUDES + STATIC_EXCLUDES
264
+ exclude: [{ prefix: '/internal/' }], // replaces RECOMMENDED_EXCLUDES
265
265
  prometheus: { host: '0.0.0.0', port: 9464 }, // false disables the reader
266
266
  dev: false, // start the SDK in dev too (once per process)
267
267
  },
package/dist/index.d.ts CHANGED
@@ -46,7 +46,7 @@ interface NodeHealthOptions {
46
46
  interface NodeLoggingOptions {
47
47
  /**
48
48
  * Paths excluded from request logging. Replaces the default
49
- * (`RECOMMENDED_EXCLUDES` + `STATIC_EXCLUDES`) entirely when provided.
49
+ * (`RECOMMENDED_EXCLUDES`) entirely when provided.
50
50
  */
51
51
  exclude?: ExcludePattern[] | undefined;
52
52
  /**
@@ -77,7 +77,7 @@ interface NodePrometheusOptions {
77
77
  interface NodeTelemetryOptions {
78
78
  /**
79
79
  * Paths excluded from request tracing and metrics. Replaces the default
80
- * (`RECOMMENDED_EXCLUDES` + `STATIC_EXCLUDES`) entirely when provided.
80
+ * (`RECOMMENDED_EXCLUDES`) entirely when provided.
81
81
  */
82
82
  exclude?: ExcludePattern[] | undefined;
83
83
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/integration/integration.ts","../src/platform/prepare.ts","../src/lifecycle/lifecycle.ts"],"mappings":";;;;;;UAEiB,eAAA;;;;;EAKf,KAAA;EALe;;;;AAYV;EAAL,KAAK;AAAA;;;;UAMU,gBAAA;EACf,IAAA;EACA,OAAA;EACA,KAAA;EACA,MAAA;AAAA;AAAA,UAGe,iBAAA;;;;;EAKf,IAAA;EAYQ;;AAAgB;AAG1B;EATE,IAAA;;;;;EAMA,KAAA,GAAQ,gBAAgB;AAAA;AAAA,UAGT,kBAAA;EAmBZ;AAGL;;;EAjBE,OAAA,GAAU,cAAc;EA4BpB;AAGN;;;;EAxBE,QAAA;EA6BU;;;;;EAtBV,GAAA;AAAA;AAAA,UAGe,qBAAA;;;;;EAKf,IAAA;EAqEmB;;;;EA/DnB,IAAI;AAAA;AAAA,UAGW,oBAAA;EA6Cf;;;;EAxCA,OAAA,GAAU,cAAA;EAuDD;;;;EAjDT,UAAA,GAAa,qBAAqB;EA8DnB;;;;ACzI+D;EDkF9E,GAAA;AAAA;AAAA,UAGe,WAAA;EClCqB;;;;AAAmC;;;ED0CvE,IAAA,GAAO,eAAA;EE1GQ;;;;AACZ;;EFiHH,OAAA,GAAU,kBAAA;;AGrHZ;;;;;EH6HE,SAAA,GAAY,oBAAA;EG3H4B;;;;;EHkIxC,MAAA,GAAS,iBAAA;EGnI8B;;;;;;EH2IvC,IAAA;IAAS,OAAA,GAAU,cAAA;EAAA;;;;;EAMnB,aAAA;;;;;;EAOA,eAAA;AAAA;;;;;;AA9IK;AAMP;;iBCkDwB,IAAA,CAAK,OAAA,GAAS,WAAA,GAAmB,gBAAgB;;;UChExD,sBAAA;EACf,GAAG;AAAA;;;UCJY,UAAA;EACf,SAAA,KAAc,OAAA,EAAS,WAAA,KAAgB,OAAA;EACvC,UAAA,KAAe,OAAA,EAAS,WAAA,KAAgB,OAAA;AAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/integration/integration.ts","../src/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i as createRequestInstrumentation, o as runStartup, t as preparePlatform } from "./prepare-Be2GgRyf.js";
2
+ import { a as runShutdown, i as createRequestInstrumentation, o as runStartup, t as preparePlatform } from "./prepare-DQEf2Bnt.js";
3
3
  import { n as dispatchNativeMount, t as clearNativeMounts } from "./native-mount-hhwWdLtL.js";
4
4
  import { n as getCurrentGeneration, r as incrementGeneration, t as GEN_HEADER } from "./generation-Bp2IA0jf.js";
5
- import { i as STATIC_EXCLUDES, r as RECOMMENDED_EXCLUDES } from "./excludes-pE23EbmQ.js";
5
+ import { r as RECOMMENDED_EXCLUDES } from "./excludes-pE23EbmQ.js";
6
6
  import fs, { readFileSync } from "node:fs";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
@@ -540,7 +540,7 @@ const SERVER_ENVIRONMENTS = [
540
540
  "prerender",
541
541
  "astro"
542
542
  ];
543
- const DEFAULT_REQUEST_EXCLUDES = [...RECOMMENDED_EXCLUDES, ...STATIC_EXCLUDES];
543
+ const DEFAULT_REQUEST_EXCLUDES = [...RECOMMENDED_EXCLUDES];
544
544
  function resolveHost(host) {
545
545
  if (typeof host === "string") return host;
546
546
  return host === true ? "0.0.0.0" : "localhost";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/dev-mode/serialize-error.ts","../src/dev-mode/scheduler.ts","../src/dev-mode/vite-env.ts","../src/dev-mode/ignored.ts","../src/dev-mode/watch.ts","../src/dev-mode/machinery.ts","../src/excludes/serialize.ts","../src/tweaks/sourcemap.ts","../src/tweaks/strip-effects.ts","../src/integration/integration.ts"],"sourcesContent":["export function serializeError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? error.message;\n }\n\n return JSON.stringify(error);\n}\n","import path from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport { serializeError } from './serialize-error.js';\n\ntype Logger = { info(msg: string): void; error(msg: string): void };\n\nconst FULL_RELOAD_UNKNOWN = '<unknown>';\n\n/**\n * Coordinates dev-server restarts: debounces bursts, chains a follow-up if\n * changes arrive mid-restart (vite's `ssrImport` reads disk at import time,\n * so changes during a restart would otherwise be missed), and logs once per\n * restart with what triggered it.\n *\n * One instance per integration, shared across restart-induced configureServer\n * reruns — chain coordination would be lost if recreated each time.\n */\nexport class RestartScheduler {\n private _inFlight = false;\n private _pending = false;\n private _debounceTimer: ReturnType<typeof setTimeout> | undefined;\n private _pendingBootDeps = new Set<string>();\n private _pendingFullReloads = new Set<string>();\n // set while a restart chain is running. the gate probes it (`isRestartPending`)\n // to short-circuit requests, and awaits it (`waitForRestart`) on readiness.\n private _runPromise: Promise<void> | undefined;\n // set when a restart attempt fails\n private _lastFailure: { message: string } | undefined;\n\n constructor(\n private readonly debounceMs: number,\n private readonly logger: Logger,\n ) {}\n\n // true from the moment a change is queued until the restart completes — covers\n // the debounce window too, so requests don't slip past the gate before _run starts.\n isRestartPending(): boolean {\n return !!this._runPromise || !!this._debounceTimer || !!this._lastFailure;\n }\n\n getLastFailure(): { message: string } | undefined {\n return this._lastFailure;\n }\n\n recordFailure(message: string): void {\n this._lastFailure = { message };\n }\n\n clearFailure(): void {\n this._lastFailure = undefined;\n }\n\n schedule(server: ViteDevServer, changedPath: string): void {\n this._pendingBootDeps.add(changedPath);\n this._scheduleRun(server);\n }\n\n scheduleFullReload(server: ViteDevServer, triggeredBy?: string): void {\n this._pendingFullReloads.add(triggeredBy ?? FULL_RELOAD_UNKNOWN);\n this._scheduleRun(server);\n }\n\n /**\n * Resolves when no restart is running. Loops to handle back-to-back restarts\n * (e.g. one chain ends and a queued debounce timer immediately fires a new\n * one). Never rejects, so a failed restart still releases the gate — caller\n * proceeds against the broken state rather than hanging forever.\n */\n async waitForRestart(): Promise<void> {\n while (this._runPromise) {\n try {\n await this._runPromise;\n } catch {\n // restart failed — release anyway\n }\n }\n }\n\n private _scheduleRun(server: ViteDevServer): void {\n clearTimeout(this._debounceTimer);\n this._debounceTimer = setTimeout(() => {\n this._debounceTimer = undefined;\n void this._run(server);\n }, this.debounceMs);\n }\n\n private async _run(server: ViteDevServer): Promise<void> {\n if (this._inFlight) {\n // loop driving the in-flight restart will pick up the next iteration.\n this._pending = true;\n\n return;\n }\n\n this._inFlight = true;\n\n let resolveRun!: () => void;\n\n this._runPromise = new Promise<void>((resolve) => {\n resolveRun = resolve;\n });\n\n try {\n do {\n this._pending = false;\n\n const bootDeps = [...this._pendingBootDeps].sort();\n const fullReloads = [...this._pendingFullReloads].sort();\n\n this._pendingBootDeps.clear();\n this._pendingFullReloads.clear();\n\n if (bootDeps.length > 0 || fullReloads.length > 0) {\n this.logger.info(this._formatReason(server, bootDeps, fullReloads));\n }\n\n try {\n await server.restart();\n } catch (error) {\n this.logger.error(`error during dev server restart: ${serializeError(error)}`);\n }\n } while (this._pending);\n } finally {\n this._inFlight = false;\n this._runPromise = undefined;\n resolveRun();\n }\n }\n\n private _formatReason(server: ViteDevServer, bootDeps: string[], fullReloads: string[]): string {\n const root = server.config.root;\n const rel = (p: string): string => path.relative(root, p) || p;\n const parts: string[] = [];\n\n if (bootDeps.length === 1) {\n parts.push(`boot dep changed: ${rel(bootDeps[0]!)}`);\n } else if (bootDeps.length > 1) {\n parts.push(`boot deps changed (${bootDeps.length}): ${bootDeps.map(rel).join(', ')}`);\n }\n\n if (fullReloads.length > 0) {\n const named = fullReloads.filter((p) => p !== FULL_RELOAD_UNKNOWN);\n\n if (named.length === 0) {\n parts.push('vite SSR full-reload');\n } else {\n parts.push(`vite SSR full-reload (triggered by ${named.map(rel).join(', ')})`);\n }\n }\n\n return `${parts.join(' + ')} — restarting dev server`;\n }\n}\n","import type { DevEnvironment, ViteDevServer } from 'vite';\n\ntype RunnableEnv = DevEnvironment & { runner: { import: (id: string) => Promise<unknown> } };\n\n/**\n * duck-typed runnable-env check. avoids `isRunnableDevEnvironment` which relies on\n * `instanceof RunnableDevEnvironment` — that breaks when the consumer and vite host\n * resolve to different vite installs (e.g. linked packages outside the workspace).\n */\nfunction isRunnable(env: DevEnvironment | undefined): env is RunnableEnv {\n return (\n !!env &&\n typeof (env as { runner?: unknown }).runner === 'object' &&\n typeof (env as RunnableEnv).runner.import === 'function'\n );\n}\n\n/**\n * resolve a runnable dev environment — prefers `ssr`, falls back to `astro`.\n * astro 6 exposes a separate `astro` environment when `ssr` isn't runnable\n * (see astro/core/constants.ts ASTRO_VITE_ENVIRONMENT_NAMES).\n */\nfunction getRunnableEnv(server: ViteDevServer): RunnableEnv {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n const names = Object.keys(server.environments);\n\n throw new Error(`no runnable dev environment found — available: ${names.join(', ')}`);\n}\n\n/**\n * load a module via the Vite Environment API.\n */\nexport async function ssrImport<T = Record<string, unknown>>(server: ViteDevServer, moduleId: string): Promise<T> {\n return getRunnableEnv(server).runner.import(moduleId) as Promise<T>;\n}\n\n/**\n * return the env whose `hot` channel should receive astro-targeted events.\n * astro listens on the env that backs its middleware runner.\n */\nexport function getAstroHotEnv(server: ViteDevServer): DevEnvironment | undefined {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n return undefined;\n}\n","export const ignoredSuffixes = [\n // type definitions\n '.d.ts',\n '.d.mts',\n '.d.cts',\n // images\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.svg',\n '.webp',\n '.avif',\n '.ico',\n // fonts\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n // other static assets\n '.pdf',\n '.mp3',\n '.mp4',\n '.webm',\n '.ogg',\n '.wav',\n // data/config that boot typically doesn't import\n '.json',\n '.yaml',\n '.yml',\n '.toml',\n '.md',\n '.mdx',\n '.txt',\n // styles (handled by Vite's CSS HMR)\n '.css',\n '.scss',\n '.sass',\n '.less',\n];\n","import type { EventEmitter } from 'node:events';\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { HotPayload, ViteDevServer } from 'vite';\nimport { GEN_HEADER, getCurrentGeneration } from './generation.js';\nimport { ignoredSuffixes } from './ignored.js';\nimport type { RestartScheduler } from './scheduler.js';\nimport { getAstroHotEnv } from './vite-env.js';\n\nconst RESTART_HTML = readFileSync(fileURLToPath(new URL('./restart-page.html', import.meta.url)), 'utf8');\n\nexport function setupBootWatch(server: ViteDevServer, entries: string[], scheduler: RestartScheduler): void {\n const entryFilePaths = entries.map((entry) => path.resolve(server.config.root, entry));\n\n const runnableEnv = getAstroHotEnv(server);\n const bootModuleGraph = runnableEnv?.moduleGraph;\n\n const collectBootDependencies = (): Set<string> => {\n const deps = new Set<string>();\n const seen = new Set<string>();\n\n for (const entryFilePath of entryFilePaths) {\n const entryModules = bootModuleGraph?.getModulesByFile(entryFilePath);\n const entryModule = entryModules ? [...entryModules][0] : undefined;\n\n if (!entryModule) continue;\n\n const visit = (mod: typeof entryModule): void => {\n if (!mod?.file || seen.has(mod.file)) return;\n\n seen.add(mod.file);\n deps.add(mod.file);\n\n for (const imp of mod.importedModules) visit(imp);\n };\n\n visit(entryModule);\n }\n\n return deps;\n };\n\n const shouldIgnore = (filePath: string): boolean => {\n const p = filePath.toLowerCase();\n\n return ignoredSuffixes.some((suffix) => p.endsWith(suffix));\n };\n\n const onWatcherEvent = (changedPath: string): void => {\n if (shouldIgnore(changedPath)) return;\n\n const bootDeps = collectBootDependencies();\n\n if (!bootDeps.has(changedPath)) return;\n\n scheduler.schedule(server, changedPath);\n };\n\n server.watcher.on('change', onWatcherEvent);\n server.watcher.on('add', onWatcherEvent);\n server.watcher.on('unlink', onWatcherEvent);\n\n // ignore full-reloads emitted during server startup (dep optimization, port retries).\n let handleFullReloads = false;\n\n if (server.httpServer) {\n server.httpServer.once('listening', () => {\n handleFullReloads = true;\n });\n } else {\n // middleware mode — no httpServer, enable immediately\n handleFullReloads = true;\n }\n\n // SSR full-reloads come through the runnable env's hot channel and clear\n // its module runner's cache — onStartup needs to run again on a fresh server.\n const outsideEmitter = (runnableEnv?.hot as { api?: { outsideEmitter?: EventEmitter } } | undefined)?.api\n ?.outsideEmitter;\n\n if (outsideEmitter) {\n outsideEmitter.on('send', (payload: HotPayload) => {\n if (!handleFullReloads) return;\n if (payload.type !== 'full-reload') return;\n\n const triggeredBy = 'triggeredBy' in payload ? (payload.triggeredBy as string) : undefined;\n\n scheduler.scheduleFullReload(server, triggeredBy);\n });\n }\n}\n\nconst READINESS_PATH = '/__astroscope_boot_ready';\n\n/**\n * Gate requests: show 503 holding page during restart, readiness probe for the reload.\n */\nexport function installBootGate(\n server: Pick<ViteDevServer, 'middlewares'>,\n scheduler: Pick<RestartScheduler, 'waitForRestart' | 'isRestartPending' | 'getLastFailure'>,\n): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n // must be `stack.unshift`ed to land before astro's handler\n middlewares.stack.unshift({\n route: '',\n handle: (async (\n req: { url?: string },\n res: {\n writeHead: (status: number, headers: Record<string, string>) => void;\n end: (body?: string) => void;\n headersSent?: boolean;\n },\n next: (err?: unknown) => void,\n ) => {\n // readiness probe: holding page polls this. blocks until no restart is in\n // flight, then 204 on success / 503 + JSON error if last attempt failed.\n if (req.url === READINESS_PATH) {\n await scheduler.waitForRestart();\n\n if (res.headersSent) return;\n\n const failure = scheduler.getLastFailure();\n\n if (failure) {\n res.writeHead(503, { 'cache-control': 'no-store', 'content-type': 'application/json' });\n res.end(JSON.stringify({ error: failure.message }));\n\n return;\n }\n\n res.writeHead(204, { 'cache-control': 'no-store' });\n res.end();\n\n return;\n }\n\n if (isDevInternalPath(req.url)) {\n next();\n\n return;\n }\n\n // respond now; awaiting the restart would let vite destroy the socket mid-response.\n if (scheduler.isRestartPending()) {\n res.writeHead(503, {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n 'retry-after': '1',\n });\n res.end(RESTART_HTML);\n\n return;\n }\n\n next();\n }) as never,\n });\n}\n\nfunction isDevInternalPath(url: string | undefined): boolean {\n if (!url) return false;\n\n return url.startsWith('/@') || url.startsWith('/__') || url.includes('/node_modules/');\n}\n\n/**\n * Stamp the current generation onto every incoming request so the runtime\n * Astro middleware can later detect whether the request belongs to a previous\n * (now torn-down) generation\n */\nexport function installGenStamp(server: Pick<ViteDevServer, 'middlewares'>): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n middlewares.stack.unshift({\n route: '',\n handle: ((req: { headers: Record<string, string> }, _res: unknown, next: () => void) => {\n req.headers[GEN_HEADER] = String(getCurrentGeneration());\n next();\n }) as never,\n });\n}\n","import type { AstroConfig } from 'astro';\nimport type { Plugin } from 'vite';\nimport { setBootContext } from '../lifecycle/context.js';\nimport { type BootModule, runShutdown, runStartup } from '../lifecycle/lifecycle.js';\nimport type { BootContext } from '../lifecycle/types.js';\nimport { clearNativeMounts } from '../server/native-mount.js';\nimport { incrementGeneration } from './generation.js';\nimport { RestartScheduler } from './scheduler.js';\nimport { serializeError } from './serialize-error.js';\nimport { ssrImport } from './vite-env.js';\nimport { installBootGate, installGenStamp, setupBootWatch } from './watch.js';\n\ninterface Logger {\n info(msg: string): void;\n warn(msg: string): void;\n error(msg: string): void;\n}\n\nexport interface DevMachineryOptions {\n /** boot file path relative to the project root; undefined = no boot module */\n entry: string | undefined;\n /** restart the dev server when watched dependencies change */\n watch: boolean;\n /** extra files (relative to the root) whose changes restart the dev server */\n watchEntries: string[];\n /** platform seams; runs each generation before the boot module starts */\n prepare: (importModule: <T = Record<string, unknown>>(id: string) => Promise<T>) => Promise<void>;\n logger: Logger;\n getConfig: () => AstroConfig | null;\n}\n\n/**\n * Resolve the default host and port from the Astro server config.\n * Falls back to `localhost:4321` when no config is provided.\n */\nfunction getServerDefaults(config: AstroConfig | null): { host: string; port: number } {\n return {\n host:\n typeof config?.server?.host === 'string'\n ? config.server.host\n : config?.server?.host === true\n ? '0.0.0.0'\n : 'localhost',\n port: config?.server?.port ?? 4321,\n };\n}\n\n/**\n * Build a dev-mode boot context from the running server's address,\n * falling back to Astro config defaults if the server isn't listening yet.\n */\nfunction resolveBootContext(\n server: { httpServer?: { address(): unknown } | null | undefined },\n config: AstroConfig | null,\n): BootContext {\n const addr = server.httpServer?.address();\n\n if (addr && typeof addr === 'object' && 'address' in addr && 'port' in addr) {\n const host =\n (addr as { address: string }).address === '::' || (addr as { address: string }).address === '0.0.0.0'\n ? 'localhost'\n : (addr as { address: string }).address;\n\n return { dev: true, host, port: (addr as { port: number }).port };\n }\n\n const { host, port } = getServerDefaults(config);\n\n return { dev: true, host, port };\n}\n\n/**\n * The dev-mode boot machinery: runs the platform seams and the boot lifecycle\n * per restart generation, restarts the dev server when watched dependencies\n * change, and gates requests behind a holding page during restarts.\n */\nexport function createDevMachinery(options: DevMachineryOptions): Plugin[] {\n const { entry, logger } = options;\n\n let hasStartupSucceededOnce = false;\n // run by the next configureServer before its startup so resources (ports,\n // sockets, locks) from the previous module are released first. idempotent.\n let priorShutdown: (() => Promise<void>) | undefined;\n // shared across restart-induced configureServer reruns\n const scheduler = options.watch ? new RestartScheduler(100, logger) : undefined;\n\n return [\n // gate plugin: enforce 'post' + returned-function so our `stack.unshift`\n // (in installBootGate / installGenStamp) lands at connect position 0,\n // ahead of astro's handler.\n {\n name: '@astroscope/node/dev-gate',\n enforce: 'post',\n\n configureServer(server) {\n if (!scheduler) return;\n\n return () => {\n // gen-stamp is unshifted last so it ends up at position 0:\n // every request gets a generation header before anything else,\n // including the gate's readiness probe.\n installBootGate(server, scheduler);\n installGenStamp(server);\n };\n },\n },\n\n // startup plugin: runs after all other configureServer hooks\n {\n name: '@astroscope/node/dev-startup',\n enforce: 'post',\n\n async configureServer(server) {\n incrementGeneration();\n\n // tear down the previous module first so its resources are released\n // before the new startup tries to claim them.\n if (priorShutdown) {\n await priorShutdown();\n priorShutdown = undefined;\n }\n\n const astroConfig = options.getConfig();\n const bootContext = resolveBootContext(server, astroConfig);\n let bootModule: BootModule | undefined;\n\n setBootContext(bootContext);\n\n try {\n await options.prepare((id) => ssrImport(server, id));\n\n bootModule = entry ? await ssrImport<BootModule>(server, `/${entry}`) : {};\n\n await runStartup(bootModule, bootContext);\n } catch (error) {\n logger.error(`Error running startup script: ${serializeError(error)}`);\n\n if (bootModule) {\n try {\n await runShutdown(bootModule, bootContext);\n } catch {\n // best-effort cleanup\n }\n }\n\n // restart failure: the gate can keep the holding\n // page up with an error message instead of dropping users onto a\n // half-broken old server.\n if (hasStartupSucceededOnce) {\n scheduler?.recordFailure(serializeError(error));\n\n throw error;\n }\n\n // initial failure: exit cleanly (mirrors the production server).\n process.exit(1);\n }\n\n hasStartupSucceededOnce = true;\n scheduler?.clearFailure();\n\n // capture so shutdown sees the same instance that started.\n const startedModule = bootModule;\n let shutdownDone = false;\n\n const shutdown = async (): Promise<void> => {\n if (shutdownDone) return;\n\n shutdownDone = true;\n\n try {\n await runShutdown(startedModule, resolveBootContext(server, options.getConfig()));\n } catch (error) {\n logger.error(`Error running shutdown script: ${serializeError(error)}`);\n }\n\n // the next generation's onStartup re-registers its mounts\n clearNativeMounts();\n };\n\n priorShutdown = shutdown;\n\n // sigint/sigterm path. also fires during restart but shutdown is idempotent.\n server.httpServer?.once('close', () => {\n void shutdown();\n });\n\n if (scheduler) {\n setupBootWatch(server, [...(entry ? [entry] : []), ...options.watchEntries], scheduler);\n }\n },\n },\n ];\n}\n","import type { ExcludePattern } from './excludes.js';\n\n/**\n * Serialize exclude patterns to JavaScript code for use in virtual modules.\n * Handles RegExp objects which JSON.stringify cannot serialize.\n */\nexport function serializeExcludePatterns(patterns: ExcludePattern[]): string {\n return `[${patterns.map((p) => ('pattern' in p ? `{ pattern: ${p.pattern.toString()} }` : JSON.stringify(p))).join(', ')}]`;\n}\n","import type { Plugin } from 'vite';\n\n/**\n * emit sourcemaps only for the SSR build. client bundles are left unmapped\n * so browsers can't fetch source via `//# sourceMappingURL=`.\n *\n * vite 7's `environments.ssr.build.sourcemap` looks cleaner but wholesale\n * replaces astro's SSR build defaults (including entry file naming), which\n * breaks the embedded dev boot machinery. using `isSsrBuild` keeps the\n * rest of astro's SSR config intact.\n */\nexport function ssrSourcemapPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/sourcemap',\n config(_config, { isSsrBuild }) {\n if (isSsrBuild) return { build: { sourcemap: true } };\n\n return {};\n },\n };\n}\n","import { Parser } from 'acorn';\nimport MagicString from 'magic-string';\nimport type { Plugin } from 'vite';\n\nconst HOOK_NAMES = new Set(['useEffect', 'useLayoutEffect', 'useInsertionEffect']);\nconst REACT_SOURCE = /^react(\\/.*)?$/;\nconst TRANSFORMABLE = /\\.(?:[mc]?[jt]sx?)$/;\nconst EMPTY_FN = '(()=>{})';\n\n/**\n * in SSR builds, react effect hooks never execute. emptying their callbacks\n * lets rolldown drop dead branches — including dynamic imports of client-only\n * libs (maplibre-gl, hls.js, etc.) — from the server bundle, which in turn\n * stops nft from tracing them at docker-image time.\n *\n * scope is deliberately narrow: first-party code only (no node_modules), only\n * in the SSR pass, and binding-aware (the React import must resolve to the\n * real react package). raw chunks where bundling has erased the binding are\n * left alone — that's NFT's domain, not ours.\n */\nexport function stripSsrEffectsPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/strip-effects',\n enforce: 'post',\n transform(code, id, options) {\n if (!options?.ssr) return null;\n if (id.includes('/node_modules/')) return null;\n\n const cleanId = id.split('?')[0] ?? id;\n\n if (!TRANSFORMABLE.test(cleanId)) return null;\n if (!code.includes('useEffect') && !code.includes('useLayoutEffect') && !code.includes('useInsertionEffect')) {\n return null;\n }\n\n let ast: any;\n\n try {\n ast = Parser.parse(code, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n allowReturnOutsideFunction: true,\n allowAwaitOutsideFunction: true,\n allowImportExportEverywhere: true,\n allowHashBang: true,\n });\n } catch {\n return null;\n }\n\n const directHooks = new Set<string>();\n const namespaceHooks = new Set<string>();\n\n walk(ast, (node) => {\n if (node.type !== 'ImportDeclaration') return;\n\n const src = node.source?.value;\n\n if (typeof src !== 'string' || !REACT_SOURCE.test(src)) return;\n\n for (const spec of node.specifiers ?? []) {\n if (spec.type === 'ImportSpecifier') {\n const imported = spec.imported?.name ?? spec.imported?.value;\n\n if (HOOK_NAMES.has(imported)) directHooks.add(spec.local.name);\n } else if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {\n namespaceHooks.add(spec.local.name);\n }\n }\n });\n\n if (directHooks.size === 0 && namespaceHooks.size === 0) return null;\n\n const replacements: { start: number; end: number }[] = [];\n\n walk(ast, (node) => {\n if (node.type !== 'CallExpression' || !node.arguments?.length) return;\n\n const callee = node.callee;\n const isDirect = callee.type === 'Identifier' && directHooks.has(callee.name);\n const isMember =\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.object?.type === 'Identifier' &&\n namespaceHooks.has(callee.object.name) &&\n callee.property?.type === 'Identifier' &&\n HOOK_NAMES.has(callee.property.name);\n\n if (!isDirect && !isMember) return;\n\n const arg = node.arguments[0];\n\n replacements.push({ start: arg.start, end: arg.end });\n });\n\n if (replacements.length === 0) return null;\n\n const s = new MagicString(code);\n\n for (const { start, end } of replacements) {\n s.overwrite(start, end, EMPTY_FN);\n }\n\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n },\n };\n}\n\nfunction walk(node: any, visit: (n: any) => void): void {\n if (!node || typeof node !== 'object') return;\n\n if (typeof node.type === 'string') visit(node);\n\n for (const key of Object.keys(node)) {\n const v = node[key];\n\n if (Array.isArray(v)) for (const item of v) walk(item, visit);\n else if (v && typeof v === 'object') walk(v, visit);\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AstroConfig, AstroIntegration } from 'astro';\nimport { createDevMachinery } from '../dev-mode/machinery.js';\nimport { type ExcludePattern, RECOMMENDED_EXCLUDES, STATIC_EXCLUDES } from '../excludes/excludes.js';\nimport { serializeExcludePatterns } from '../excludes/serialize.js';\nimport { createRequestInstrumentation } from '../observability/instrument.js';\nimport { preparePlatform } from '../platform/prepare.js';\nimport { dispatchNativeMount } from '../server/native-mount.js';\nimport { ssrSourcemapPlugin } from '../tweaks/sourcemap.js';\nimport { stripSsrEffectsPlugin } from '../tweaks/strip-effects.js';\nimport type { NodeOptions, RuntimeOptions } from '../types.js';\n\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config';\nexport const BOOT_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/boot';\nexport const CSRF_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/csrf';\nexport const CONFIG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config-entry';\nexport const INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/instrumentation-entry';\nexport const LOG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/log-entry';\n\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_BOOT_VIRTUAL_MODULE_ID = `\\0${BOOT_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CSRF_VIRTUAL_MODULE_ID = `\\0${CSRF_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID = `\\0${CONFIG_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = `\\0${INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID = `\\0${LOG_ENTRY_VIRTUAL_MODULE_ID}`;\n\nconst SERVER_ENVIRONMENTS = ['ssr', 'prerender', 'astro'];\n\nconst DEFAULT_REQUEST_EXCLUDES: ExcludePattern[] = [...RECOMMENDED_EXCLUDES, ...STATIC_EXCLUDES];\n\nfunction resolveHost(host: string | boolean | undefined): string {\n if (typeof host === 'string') return host;\n\n return host === true ? '0.0.0.0' : 'localhost';\n}\n\nfunction resolveBootEntry(root: string, entry: string | undefined): string | undefined {\n if (entry) {\n const abs = path.resolve(root, entry);\n\n if (!fs.existsSync(abs)) {\n throw new Error(`[@astroscope/node] boot entry not found: ${entry}`);\n }\n\n return abs;\n }\n\n for (const candidate of ['src/boot/index.ts', 'src/boot.ts']) {\n const abs = path.resolve(root, candidate);\n\n if (fs.existsSync(abs)) return abs;\n }\n\n return undefined;\n}\n\nfunction resolveSeam(root: string, candidate: string): string | undefined {\n const abs = path.resolve(root, candidate);\n\n return fs.existsSync(abs) ? abs : undefined;\n}\n\n/**\n * Node adapter for Astro with a first-class server entrypoint: the boot\n * lifecycle, module warmup, health probes, request logging and telemetry run\n * as plain code around `server.listen()` instead of being injected into the\n * build output.\n */\nexport default function node(options: NodeOptions = {}): AstroIntegration {\n const bootOptions = options.boot ?? {};\n const healthOptions = options.health ?? {};\n const csrfOptions = options.csrf ?? {};\n const loggingOptions = options.logging ?? {};\n const telemetryOptions = options.telemetry ?? {};\n\n const loggingExclude = loggingOptions ? (loggingOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n const telemetryExclude = telemetryOptions ? (telemetryOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n\n let astroConfig: AstroConfig | null = null;\n let bootEntry: string | undefined;\n let configSeam: string | undefined;\n let instrumentationSeam: string | undefined;\n let logSeam: string | undefined;\n let isDev = false;\n\n return {\n name: '@astroscope/node',\n hooks: {\n 'astro:config:setup': ({ command, config, updateConfig, addMiddleware, logger }) => {\n isDev = command === 'dev';\n\n // route enrichment first so csrf-rejected requests still carry a route\n if (loggingOptions || telemetryOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/route-middleware' });\n }\n\n if (csrfOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/csrf-middleware' });\n }\n\n const root = fileURLToPath(config.root);\n const watch = bootOptions === false ? false : (bootOptions.watch ?? true);\n\n bootEntry = bootOptions === false ? undefined : resolveBootEntry(root, bootOptions.entry);\n configSeam = resolveSeam(root, 'src/config.ts');\n instrumentationSeam = resolveSeam(root, 'src/instrumentation.ts');\n logSeam = resolveSeam(root, 'src/log.ts');\n\n const relativeSeam = (abs: string | undefined) =>\n abs ? path.relative(root, abs).split(path.sep).join('/') : undefined;\n\n const devMachinery =\n command === 'dev' && bootOptions !== false\n ? createDevMachinery({\n entry: bootEntry ? path.relative(root, bootEntry) : undefined,\n watch,\n // instrumentation runs once per process — watching it would\n // restart generations that can't re-apply it\n watchEntries: [relativeSeam(configSeam), relativeSeam(logSeam)].filter(\n (entry): entry is string => !!entry,\n ),\n prepare: (importModule) =>\n preparePlatform({\n dev: true,\n telemetry:\n telemetryOptions && telemetryOptions.dev\n ? { prometheus: telemetryOptions.prometheus ?? {} }\n : false,\n seams: {\n ...(configSeam && { config: () => importModule(`/${relativeSeam(configSeam)}`) }),\n ...(instrumentationSeam && {\n instrumentation: () => importModule(`/${relativeSeam(instrumentationSeam)}`),\n }),\n ...(logSeam && { log: () => importModule(`/${relativeSeam(logSeam)}`) }),\n },\n }),\n logger,\n getConfig: () => astroConfig,\n })\n : [];\n\n if (command === 'dev' && bootOptions !== false && watch) {\n // catches errors thrown by stale (post-shutdown) requests so\n // they don't pollute the logs during dev-server restarts.\n addMiddleware({ entrypoint: '@astroscope/node/dev-middleware', order: 'pre' });\n }\n\n updateConfig({\n build: { redirects: false },\n // opinionated defaults: no trailing slashes, behind LB\n ...(config.trailingSlash === 'ignore' && { trailingSlash: 'never' as const }),\n security: {\n // assumed to run behind LB\n ...(!config.security.allowedDomains?.length && { allowedDomains: [{}] }),\n // the embedded csrf middleware replaces the built-in origin check\n ...(csrfOptions && { checkOrigin: false }),\n },\n image: {\n endpoint: {\n route: config.image.endpoint.route ?? '_image',\n entrypoint:\n config.image.endpoint.entrypoint ??\n (command === 'dev' ? 'astro/assets/endpoint/dev' : 'astro/assets/endpoint/node'),\n },\n },\n vite: {\n plugins: [\n ...devMachinery,\n ssrSourcemapPlugin(),\n stripSsrEffectsPlugin(),\n {\n name: '@astroscope/node',\n\n configEnvironment(environmentName: string) {\n if (SERVER_ENVIRONMENTS.includes(environmentName)) {\n return { resolve: { noExternal: ['@astroscope/node'] } };\n }\n },\n\n resolveId(id: string) {\n if (id === CONFIG_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n if (id === BOOT_VIRTUAL_MODULE_ID) return RESOLVED_BOOT_VIRTUAL_MODULE_ID;\n if (id === CSRF_VIRTUAL_MODULE_ID) return RESOLVED_CSRF_VIRTUAL_MODULE_ID;\n if (id === CONFIG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID;\n if (id === INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID;\n }\n if (id === LOG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID;\n },\n\n load(id: string) {\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n if (!astroConfig) throw new Error('[@astroscope/node] astro config not resolved yet');\n\n const runtimeOptions: Omit<RuntimeOptions, 'logging' | 'telemetry'> = {\n host: resolveHost(astroConfig.server.host),\n port: astroConfig.server.port ?? 4321,\n client: astroConfig.build.client.toString(),\n server: astroConfig.build.server.toString(),\n bodySizeLimit: options.bodySizeLimit ?? 1024 * 1024 * 1024,\n shutdownTimeout: options.shutdownTimeout ?? 10_000,\n health: healthOptions\n ? {\n ...(healthOptions.host !== undefined && { host: healthOptions.host }),\n ...(healthOptions.port !== undefined && { port: healthOptions.port }),\n ...(healthOptions.paths && { paths: healthOptions.paths }),\n }\n : false,\n };\n\n // exclude patterns may contain RegExp — serialized as code, not JSON\n const logging = loggingOptions\n ? `{ exclude: ${serializeExcludePatterns(loggingExclude)}, extended: ${JSON.stringify(\n loggingOptions.extended ?? false,\n )} }`\n : 'false';\n const telemetry = telemetryOptions\n ? `{ exclude: ${serializeExcludePatterns(telemetryExclude)}, prometheus: ${JSON.stringify(\n telemetryOptions.prometheus ?? {},\n )} }`\n : 'false';\n\n return `export const options = { ...${JSON.stringify(runtimeOptions)}, logging: ${logging}, telemetry: ${telemetry} };`;\n }\n\n if (id === RESOLVED_BOOT_VIRTUAL_MODULE_ID) {\n // re-export to avoid absolute path manifest leaks\n return bootEntry ? `export * from ${JSON.stringify(bootEntry)};` : 'export {};';\n }\n\n if (id === RESOLVED_CSRF_VIRTUAL_MODULE_ID) {\n return `export const excludePatterns = ${serializeExcludePatterns(csrfOptions ? (csrfOptions.exclude ?? []) : [])};`;\n }\n\n if (id === RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID) {\n // side-effect import: @entwico/zod-conf validation runs at module load\n return configSeam ? `import ${JSON.stringify(configSeam)};\\nexport {};` : 'export {};';\n }\n\n if (id === RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return instrumentationSeam ? `export * from ${JSON.stringify(instrumentationSeam)};` : 'export {};';\n }\n\n if (id === RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID) {\n return logSeam\n ? `export { default } from ${JSON.stringify(logSeam)};`\n : 'export default undefined;';\n }\n },\n },\n ],\n },\n });\n },\n 'astro:server:setup': ({ server }) => {\n if (!isDev) return;\n\n const devLogging = loggingOptions && loggingOptions.dev;\n const devTelemetry = telemetryOptions && telemetryOptions.dev;\n\n const instrument =\n devLogging || devTelemetry\n ? createRequestInstrumentation({\n logging: devLogging ? { exclude: loggingExclude, extended: loggingOptions.extended ?? false } : false,\n telemetry: devTelemetry ? { exclude: telemetryExclude } : false,\n })\n : undefined;\n\n server.middlewares.use((req, res, next) => {\n const inner = (): void => {\n if (!dispatchNativeMount(req, res)) next();\n };\n\n if (instrument) {\n instrument(req, res, inner);\n } else {\n inner();\n }\n });\n },\n 'astro:config:done': ({ config, setAdapter }) => {\n astroConfig = config;\n\n setAdapter({\n name: '@astroscope/node',\n entrypointResolution: 'auto',\n serverEntrypoint: '@astroscope/node/server',\n previewEntrypoint: '@astroscope/node/preview',\n adapterFeatures: {\n buildOutput: 'server',\n middlewareMode: 'classic',\n },\n supportedAstroFeatures: {\n hybridOutput: 'stable',\n staticOutput: 'stable',\n serverOutput: 'stable',\n sharpImageService: 'stable',\n i18nDomains: 'experimental',\n envGetSecret: 'stable',\n },\n });\n },\n 'astro:build:done': async ({ logger }) => {\n if (!astroConfig) return;\n\n const { compressClientDir } = await import('../compress/compress.js');\n\n await compressClientDir(fileURLToPath(astroConfig.build.client), logger);\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAgB,eAAe,OAAwB;CACrD,IAAI,iBAAiB,OACnB,OAAO,MAAM,SAAS,MAAM;CAG9B,OAAO,KAAK,UAAU,KAAK;AAC7B;;;ACAA,MAAM,sBAAsB;;;;;;;;;;AAW5B,IAAa,mBAAb,MAA8B;CAaT;CACA;CAbnB,YAAoB;CACpB,WAAmB;CACnB;CACA,mCAA2B,IAAI,IAAY;CAC3C,sCAA8B,IAAI,IAAY;CAG9C;CAEA;CAEA,YACE,YACA,QACA;EAFiB,KAAA,aAAA;EACA,KAAA,SAAA;CAChB;CAIH,mBAA4B;EAC1B,OAAO,CAAC,CAAC,KAAK,eAAe,CAAC,CAAC,KAAK,kBAAkB,CAAC,CAAC,KAAK;CAC/D;CAEA,iBAAkD;EAChD,OAAO,KAAK;CACd;CAEA,cAAc,SAAuB;EACnC,KAAK,eAAe,EAAE,QAAQ;CAChC;CAEA,eAAqB;EACnB,KAAK,eAAe,KAAA;CACtB;CAEA,SAAS,QAAuB,aAA2B;EACzD,KAAK,iBAAiB,IAAI,WAAW;EACrC,KAAK,aAAa,MAAM;CAC1B;CAEA,mBAAmB,QAAuB,aAA4B;EACpE,KAAK,oBAAoB,IAAI,eAAe,mBAAmB;EAC/D,KAAK,aAAa,MAAM;CAC1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5D,CAAC,IACD,KAAA;IAEN,OAAO,YAAY,KAAK,KAAK,KAAK,SAAS;KACzC,MAAM,cAAoB;MACxB,IAAI,CAAC,oBAAoB,KAAK,GAAG,GAAG,KAAK;KAC3C;KAEA,IAAI,YACF,WAAW,KAAK,KAAK,KAAK;UAE1B,MAAM;IAEV,CAAC;GACH;GACA,sBAAsB,EAAE,QAAQ,iBAAiB;IAC/C,cAAc;IAEd,WAAW;KACT,MAAM;KACN,sBAAsB;KACtB,kBAAkB;KAClB,mBAAmB;KACnB,iBAAiB;MACf,aAAa;MACb,gBAAgB;KAClB;KACA,wBAAwB;MACtB,cAAc;MACd,cAAc;MACd,cAAc;MACd,mBAAmB;MACnB,aAAa;MACb,cAAc;KAChB;IACF,CAAC;GACH;GACA,oBAAoB,OAAO,EAAE,aAAa;IACxC,IAAI,CAAC,aAAa;IAElB,MAAM,EAAE,sBAAsB,MAAM,OAAO;IAE3C,MAAM,kBAAkB,cAAc,YAAY,MAAM,MAAM,GAAG,MAAM;GACzE;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/dev-mode/serialize-error.ts","../src/dev-mode/scheduler.ts","../src/dev-mode/vite-env.ts","../src/dev-mode/ignored.ts","../src/dev-mode/watch.ts","../src/dev-mode/machinery.ts","../src/excludes/serialize.ts","../src/tweaks/sourcemap.ts","../src/tweaks/strip-effects.ts","../src/integration/integration.ts"],"sourcesContent":["export function serializeError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? error.message;\n }\n\n return JSON.stringify(error);\n}\n","import path from 'node:path';\nimport type { ViteDevServer } from 'vite';\nimport { serializeError } from './serialize-error.js';\n\ntype Logger = { info(msg: string): void; error(msg: string): void };\n\nconst FULL_RELOAD_UNKNOWN = '<unknown>';\n\n/**\n * Coordinates dev-server restarts: debounces bursts, chains a follow-up if\n * changes arrive mid-restart (vite's `ssrImport` reads disk at import time,\n * so changes during a restart would otherwise be missed), and logs once per\n * restart with what triggered it.\n *\n * One instance per integration, shared across restart-induced configureServer\n * reruns — chain coordination would be lost if recreated each time.\n */\nexport class RestartScheduler {\n private _inFlight = false;\n private _pending = false;\n private _debounceTimer: ReturnType<typeof setTimeout> | undefined;\n private _pendingBootDeps = new Set<string>();\n private _pendingFullReloads = new Set<string>();\n // set while a restart chain is running. the gate probes it (`isRestartPending`)\n // to short-circuit requests, and awaits it (`waitForRestart`) on readiness.\n private _runPromise: Promise<void> | undefined;\n // set when a restart attempt fails\n private _lastFailure: { message: string } | undefined;\n\n constructor(\n private readonly debounceMs: number,\n private readonly logger: Logger,\n ) {}\n\n // true from the moment a change is queued until the restart completes — covers\n // the debounce window too, so requests don't slip past the gate before _run starts.\n isRestartPending(): boolean {\n return !!this._runPromise || !!this._debounceTimer || !!this._lastFailure;\n }\n\n getLastFailure(): { message: string } | undefined {\n return this._lastFailure;\n }\n\n recordFailure(message: string): void {\n this._lastFailure = { message };\n }\n\n clearFailure(): void {\n this._lastFailure = undefined;\n }\n\n schedule(server: ViteDevServer, changedPath: string): void {\n this._pendingBootDeps.add(changedPath);\n this._scheduleRun(server);\n }\n\n scheduleFullReload(server: ViteDevServer, triggeredBy?: string): void {\n this._pendingFullReloads.add(triggeredBy ?? FULL_RELOAD_UNKNOWN);\n this._scheduleRun(server);\n }\n\n /**\n * Resolves when no restart is running. Loops to handle back-to-back restarts\n * (e.g. one chain ends and a queued debounce timer immediately fires a new\n * one). Never rejects, so a failed restart still releases the gate — caller\n * proceeds against the broken state rather than hanging forever.\n */\n async waitForRestart(): Promise<void> {\n while (this._runPromise) {\n try {\n await this._runPromise;\n } catch {\n // restart failed — release anyway\n }\n }\n }\n\n private _scheduleRun(server: ViteDevServer): void {\n clearTimeout(this._debounceTimer);\n this._debounceTimer = setTimeout(() => {\n this._debounceTimer = undefined;\n void this._run(server);\n }, this.debounceMs);\n }\n\n private async _run(server: ViteDevServer): Promise<void> {\n if (this._inFlight) {\n // loop driving the in-flight restart will pick up the next iteration.\n this._pending = true;\n\n return;\n }\n\n this._inFlight = true;\n\n let resolveRun!: () => void;\n\n this._runPromise = new Promise<void>((resolve) => {\n resolveRun = resolve;\n });\n\n try {\n do {\n this._pending = false;\n\n const bootDeps = [...this._pendingBootDeps].sort();\n const fullReloads = [...this._pendingFullReloads].sort();\n\n this._pendingBootDeps.clear();\n this._pendingFullReloads.clear();\n\n if (bootDeps.length > 0 || fullReloads.length > 0) {\n this.logger.info(this._formatReason(server, bootDeps, fullReloads));\n }\n\n try {\n await server.restart();\n } catch (error) {\n this.logger.error(`error during dev server restart: ${serializeError(error)}`);\n }\n } while (this._pending);\n } finally {\n this._inFlight = false;\n this._runPromise = undefined;\n resolveRun();\n }\n }\n\n private _formatReason(server: ViteDevServer, bootDeps: string[], fullReloads: string[]): string {\n const root = server.config.root;\n const rel = (p: string): string => path.relative(root, p) || p;\n const parts: string[] = [];\n\n if (bootDeps.length === 1) {\n parts.push(`boot dep changed: ${rel(bootDeps[0]!)}`);\n } else if (bootDeps.length > 1) {\n parts.push(`boot deps changed (${bootDeps.length}): ${bootDeps.map(rel).join(', ')}`);\n }\n\n if (fullReloads.length > 0) {\n const named = fullReloads.filter((p) => p !== FULL_RELOAD_UNKNOWN);\n\n if (named.length === 0) {\n parts.push('vite SSR full-reload');\n } else {\n parts.push(`vite SSR full-reload (triggered by ${named.map(rel).join(', ')})`);\n }\n }\n\n return `${parts.join(' + ')} — restarting dev server`;\n }\n}\n","import type { DevEnvironment, ViteDevServer } from 'vite';\n\ntype RunnableEnv = DevEnvironment & { runner: { import: (id: string) => Promise<unknown> } };\n\n/**\n * duck-typed runnable-env check. avoids `isRunnableDevEnvironment` which relies on\n * `instanceof RunnableDevEnvironment` — that breaks when the consumer and vite host\n * resolve to different vite installs (e.g. linked packages outside the workspace).\n */\nfunction isRunnable(env: DevEnvironment | undefined): env is RunnableEnv {\n return (\n !!env &&\n typeof (env as { runner?: unknown }).runner === 'object' &&\n typeof (env as RunnableEnv).runner.import === 'function'\n );\n}\n\n/**\n * resolve a runnable dev environment — prefers `ssr`, falls back to `astro`.\n * astro 6 exposes a separate `astro` environment when `ssr` isn't runnable\n * (see astro/core/constants.ts ASTRO_VITE_ENVIRONMENT_NAMES).\n */\nfunction getRunnableEnv(server: ViteDevServer): RunnableEnv {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n const names = Object.keys(server.environments);\n\n throw new Error(`no runnable dev environment found — available: ${names.join(', ')}`);\n}\n\n/**\n * load a module via the Vite Environment API.\n */\nexport async function ssrImport<T = Record<string, unknown>>(server: ViteDevServer, moduleId: string): Promise<T> {\n return getRunnableEnv(server).runner.import(moduleId) as Promise<T>;\n}\n\n/**\n * return the env whose `hot` channel should receive astro-targeted events.\n * astro listens on the env that backs its middleware runner.\n */\nexport function getAstroHotEnv(server: ViteDevServer): DevEnvironment | undefined {\n const ssr = server.environments['ssr'];\n\n if (isRunnable(ssr)) return ssr;\n\n const astro = server.environments['astro'];\n\n if (isRunnable(astro)) return astro;\n\n return undefined;\n}\n","export const ignoredSuffixes = [\n // type definitions\n '.d.ts',\n '.d.mts',\n '.d.cts',\n // images\n '.png',\n '.jpg',\n '.jpeg',\n '.gif',\n '.svg',\n '.webp',\n '.avif',\n '.ico',\n // fonts\n '.woff',\n '.woff2',\n '.ttf',\n '.otf',\n '.eot',\n // other static assets\n '.pdf',\n '.mp3',\n '.mp4',\n '.webm',\n '.ogg',\n '.wav',\n // data/config that boot typically doesn't import\n '.json',\n '.yaml',\n '.yml',\n '.toml',\n '.md',\n '.mdx',\n '.txt',\n // styles (handled by Vite's CSS HMR)\n '.css',\n '.scss',\n '.sass',\n '.less',\n];\n","import type { EventEmitter } from 'node:events';\nimport { readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { HotPayload, ViteDevServer } from 'vite';\nimport { GEN_HEADER, getCurrentGeneration } from './generation.js';\nimport { ignoredSuffixes } from './ignored.js';\nimport type { RestartScheduler } from './scheduler.js';\nimport { getAstroHotEnv } from './vite-env.js';\n\nconst RESTART_HTML = readFileSync(fileURLToPath(new URL('./restart-page.html', import.meta.url)), 'utf8');\n\nexport function setupBootWatch(server: ViteDevServer, entries: string[], scheduler: RestartScheduler): void {\n const entryFilePaths = entries.map((entry) => path.resolve(server.config.root, entry));\n\n const runnableEnv = getAstroHotEnv(server);\n const bootModuleGraph = runnableEnv?.moduleGraph;\n\n const collectBootDependencies = (): Set<string> => {\n const deps = new Set<string>();\n const seen = new Set<string>();\n\n for (const entryFilePath of entryFilePaths) {\n const entryModules = bootModuleGraph?.getModulesByFile(entryFilePath);\n const entryModule = entryModules ? [...entryModules][0] : undefined;\n\n if (!entryModule) continue;\n\n const visit = (mod: typeof entryModule): void => {\n if (!mod?.file || seen.has(mod.file)) return;\n\n seen.add(mod.file);\n deps.add(mod.file);\n\n for (const imp of mod.importedModules) visit(imp);\n };\n\n visit(entryModule);\n }\n\n return deps;\n };\n\n const shouldIgnore = (filePath: string): boolean => {\n const p = filePath.toLowerCase();\n\n return ignoredSuffixes.some((suffix) => p.endsWith(suffix));\n };\n\n const onWatcherEvent = (changedPath: string): void => {\n if (shouldIgnore(changedPath)) return;\n\n const bootDeps = collectBootDependencies();\n\n if (!bootDeps.has(changedPath)) return;\n\n scheduler.schedule(server, changedPath);\n };\n\n server.watcher.on('change', onWatcherEvent);\n server.watcher.on('add', onWatcherEvent);\n server.watcher.on('unlink', onWatcherEvent);\n\n // ignore full-reloads emitted during server startup (dep optimization, port retries).\n let handleFullReloads = false;\n\n if (server.httpServer) {\n server.httpServer.once('listening', () => {\n handleFullReloads = true;\n });\n } else {\n // middleware mode — no httpServer, enable immediately\n handleFullReloads = true;\n }\n\n // SSR full-reloads come through the runnable env's hot channel and clear\n // its module runner's cache — onStartup needs to run again on a fresh server.\n const outsideEmitter = (runnableEnv?.hot as { api?: { outsideEmitter?: EventEmitter } } | undefined)?.api\n ?.outsideEmitter;\n\n if (outsideEmitter) {\n outsideEmitter.on('send', (payload: HotPayload) => {\n if (!handleFullReloads) return;\n if (payload.type !== 'full-reload') return;\n\n const triggeredBy = 'triggeredBy' in payload ? (payload.triggeredBy as string) : undefined;\n\n scheduler.scheduleFullReload(server, triggeredBy);\n });\n }\n}\n\nconst READINESS_PATH = '/__astroscope_boot_ready';\n\n/**\n * Gate requests: show 503 holding page during restart, readiness probe for the reload.\n */\nexport function installBootGate(\n server: Pick<ViteDevServer, 'middlewares'>,\n scheduler: Pick<RestartScheduler, 'waitForRestart' | 'isRestartPending' | 'getLastFailure'>,\n): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n // must be `stack.unshift`ed to land before astro's handler\n middlewares.stack.unshift({\n route: '',\n handle: (async (\n req: { url?: string },\n res: {\n writeHead: (status: number, headers: Record<string, string>) => void;\n end: (body?: string) => void;\n headersSent?: boolean;\n },\n next: (err?: unknown) => void,\n ) => {\n // readiness probe: holding page polls this. blocks until no restart is in\n // flight, then 204 on success / 503 + JSON error if last attempt failed.\n if (req.url === READINESS_PATH) {\n await scheduler.waitForRestart();\n\n if (res.headersSent) return;\n\n const failure = scheduler.getLastFailure();\n\n if (failure) {\n res.writeHead(503, { 'cache-control': 'no-store', 'content-type': 'application/json' });\n res.end(JSON.stringify({ error: failure.message }));\n\n return;\n }\n\n res.writeHead(204, { 'cache-control': 'no-store' });\n res.end();\n\n return;\n }\n\n if (isDevInternalPath(req.url)) {\n next();\n\n return;\n }\n\n // respond now; awaiting the restart would let vite destroy the socket mid-response.\n if (scheduler.isRestartPending()) {\n res.writeHead(503, {\n 'content-type': 'text/html; charset=utf-8',\n 'cache-control': 'no-store',\n 'retry-after': '1',\n });\n res.end(RESTART_HTML);\n\n return;\n }\n\n next();\n }) as never,\n });\n}\n\nfunction isDevInternalPath(url: string | undefined): boolean {\n if (!url) return false;\n\n return url.startsWith('/@') || url.startsWith('/__') || url.includes('/node_modules/');\n}\n\n/**\n * Stamp the current generation onto every incoming request so the runtime\n * Astro middleware can later detect whether the request belongs to a previous\n * (now torn-down) generation\n */\nexport function installGenStamp(server: Pick<ViteDevServer, 'middlewares'>): void {\n const middlewares = server.middlewares as unknown as {\n stack: { route: string; handle: unknown }[];\n };\n\n middlewares.stack.unshift({\n route: '',\n handle: ((req: { headers: Record<string, string> }, _res: unknown, next: () => void) => {\n req.headers[GEN_HEADER] = String(getCurrentGeneration());\n next();\n }) as never,\n });\n}\n","import type { AstroConfig } from 'astro';\nimport type { Plugin } from 'vite';\nimport { setBootContext } from '../lifecycle/context.js';\nimport { type BootModule, runShutdown, runStartup } from '../lifecycle/lifecycle.js';\nimport type { BootContext } from '../lifecycle/types.js';\nimport { clearNativeMounts } from '../server/native-mount.js';\nimport { incrementGeneration } from './generation.js';\nimport { RestartScheduler } from './scheduler.js';\nimport { serializeError } from './serialize-error.js';\nimport { ssrImport } from './vite-env.js';\nimport { installBootGate, installGenStamp, setupBootWatch } from './watch.js';\n\ninterface Logger {\n info(msg: string): void;\n warn(msg: string): void;\n error(msg: string): void;\n}\n\nexport interface DevMachineryOptions {\n /** boot file path relative to the project root; undefined = no boot module */\n entry: string | undefined;\n /** restart the dev server when watched dependencies change */\n watch: boolean;\n /** extra files (relative to the root) whose changes restart the dev server */\n watchEntries: string[];\n /** platform seams; runs each generation before the boot module starts */\n prepare: (importModule: <T = Record<string, unknown>>(id: string) => Promise<T>) => Promise<void>;\n logger: Logger;\n getConfig: () => AstroConfig | null;\n}\n\n/**\n * Resolve the default host and port from the Astro server config.\n * Falls back to `localhost:4321` when no config is provided.\n */\nfunction getServerDefaults(config: AstroConfig | null): { host: string; port: number } {\n return {\n host:\n typeof config?.server?.host === 'string'\n ? config.server.host\n : config?.server?.host === true\n ? '0.0.0.0'\n : 'localhost',\n port: config?.server?.port ?? 4321,\n };\n}\n\n/**\n * Build a dev-mode boot context from the running server's address,\n * falling back to Astro config defaults if the server isn't listening yet.\n */\nfunction resolveBootContext(\n server: { httpServer?: { address(): unknown } | null | undefined },\n config: AstroConfig | null,\n): BootContext {\n const addr = server.httpServer?.address();\n\n if (addr && typeof addr === 'object' && 'address' in addr && 'port' in addr) {\n const host =\n (addr as { address: string }).address === '::' || (addr as { address: string }).address === '0.0.0.0'\n ? 'localhost'\n : (addr as { address: string }).address;\n\n return { dev: true, host, port: (addr as { port: number }).port };\n }\n\n const { host, port } = getServerDefaults(config);\n\n return { dev: true, host, port };\n}\n\n/**\n * The dev-mode boot machinery: runs the platform seams and the boot lifecycle\n * per restart generation, restarts the dev server when watched dependencies\n * change, and gates requests behind a holding page during restarts.\n */\nexport function createDevMachinery(options: DevMachineryOptions): Plugin[] {\n const { entry, logger } = options;\n\n let hasStartupSucceededOnce = false;\n // run by the next configureServer before its startup so resources (ports,\n // sockets, locks) from the previous module are released first. idempotent.\n let priorShutdown: (() => Promise<void>) | undefined;\n // shared across restart-induced configureServer reruns\n const scheduler = options.watch ? new RestartScheduler(100, logger) : undefined;\n\n return [\n // gate plugin: enforce 'post' + returned-function so our `stack.unshift`\n // (in installBootGate / installGenStamp) lands at connect position 0,\n // ahead of astro's handler.\n {\n name: '@astroscope/node/dev-gate',\n enforce: 'post',\n\n configureServer(server) {\n if (!scheduler) return;\n\n return () => {\n // gen-stamp is unshifted last so it ends up at position 0:\n // every request gets a generation header before anything else,\n // including the gate's readiness probe.\n installBootGate(server, scheduler);\n installGenStamp(server);\n };\n },\n },\n\n // startup plugin: runs after all other configureServer hooks\n {\n name: '@astroscope/node/dev-startup',\n enforce: 'post',\n\n async configureServer(server) {\n incrementGeneration();\n\n // tear down the previous module first so its resources are released\n // before the new startup tries to claim them.\n if (priorShutdown) {\n await priorShutdown();\n priorShutdown = undefined;\n }\n\n const astroConfig = options.getConfig();\n const bootContext = resolveBootContext(server, astroConfig);\n let bootModule: BootModule | undefined;\n\n setBootContext(bootContext);\n\n try {\n await options.prepare((id) => ssrImport(server, id));\n\n bootModule = entry ? await ssrImport<BootModule>(server, `/${entry}`) : {};\n\n await runStartup(bootModule, bootContext);\n } catch (error) {\n logger.error(`Error running startup script: ${serializeError(error)}`);\n\n if (bootModule) {\n try {\n await runShutdown(bootModule, bootContext);\n } catch {\n // best-effort cleanup\n }\n }\n\n // restart failure: the gate can keep the holding\n // page up with an error message instead of dropping users onto a\n // half-broken old server.\n if (hasStartupSucceededOnce) {\n scheduler?.recordFailure(serializeError(error));\n\n throw error;\n }\n\n // initial failure: exit cleanly (mirrors the production server).\n process.exit(1);\n }\n\n hasStartupSucceededOnce = true;\n scheduler?.clearFailure();\n\n // capture so shutdown sees the same instance that started.\n const startedModule = bootModule;\n let shutdownDone = false;\n\n const shutdown = async (): Promise<void> => {\n if (shutdownDone) return;\n\n shutdownDone = true;\n\n try {\n await runShutdown(startedModule, resolveBootContext(server, options.getConfig()));\n } catch (error) {\n logger.error(`Error running shutdown script: ${serializeError(error)}`);\n }\n\n // the next generation's onStartup re-registers its mounts\n clearNativeMounts();\n };\n\n priorShutdown = shutdown;\n\n // sigint/sigterm path. also fires during restart but shutdown is idempotent.\n server.httpServer?.once('close', () => {\n void shutdown();\n });\n\n if (scheduler) {\n setupBootWatch(server, [...(entry ? [entry] : []), ...options.watchEntries], scheduler);\n }\n },\n },\n ];\n}\n","import type { ExcludePattern } from './excludes.js';\n\n/**\n * Serialize exclude patterns to JavaScript code for use in virtual modules.\n * Handles RegExp objects which JSON.stringify cannot serialize.\n */\nexport function serializeExcludePatterns(patterns: ExcludePattern[]): string {\n return `[${patterns.map((p) => ('pattern' in p ? `{ pattern: ${p.pattern.toString()} }` : JSON.stringify(p))).join(', ')}]`;\n}\n","import type { Plugin } from 'vite';\n\n/**\n * emit sourcemaps only for the SSR build. client bundles are left unmapped\n * so browsers can't fetch source via `//# sourceMappingURL=`.\n *\n * vite 7's `environments.ssr.build.sourcemap` looks cleaner but wholesale\n * replaces astro's SSR build defaults (including entry file naming), which\n * breaks the embedded dev boot machinery. using `isSsrBuild` keeps the\n * rest of astro's SSR config intact.\n */\nexport function ssrSourcemapPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/sourcemap',\n config(_config, { isSsrBuild }) {\n if (isSsrBuild) return { build: { sourcemap: true } };\n\n return {};\n },\n };\n}\n","import { Parser } from 'acorn';\nimport MagicString from 'magic-string';\nimport type { Plugin } from 'vite';\n\nconst HOOK_NAMES = new Set(['useEffect', 'useLayoutEffect', 'useInsertionEffect']);\nconst REACT_SOURCE = /^react(\\/.*)?$/;\nconst TRANSFORMABLE = /\\.(?:[mc]?[jt]sx?)$/;\nconst EMPTY_FN = '(()=>{})';\n\n/**\n * in SSR builds, react effect hooks never execute. emptying their callbacks\n * lets rolldown drop dead branches — including dynamic imports of client-only\n * libs (maplibre-gl, hls.js, etc.) — from the server bundle, which in turn\n * stops nft from tracing them at docker-image time.\n *\n * scope is deliberately narrow: first-party code only (no node_modules), only\n * in the SSR pass, and binding-aware (the React import must resolve to the\n * real react package). raw chunks where bundling has erased the binding are\n * left alone — that's NFT's domain, not ours.\n */\nexport function stripSsrEffectsPlugin(): Plugin {\n return {\n name: '@astroscope/node/tweaks/strip-effects',\n enforce: 'post',\n transform(code, id, options) {\n if (!options?.ssr) return null;\n if (id.includes('/node_modules/')) return null;\n\n const cleanId = id.split('?')[0] ?? id;\n\n if (!TRANSFORMABLE.test(cleanId)) return null;\n if (!code.includes('useEffect') && !code.includes('useLayoutEffect') && !code.includes('useInsertionEffect')) {\n return null;\n }\n\n let ast: any;\n\n try {\n ast = Parser.parse(code, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n allowReturnOutsideFunction: true,\n allowAwaitOutsideFunction: true,\n allowImportExportEverywhere: true,\n allowHashBang: true,\n });\n } catch {\n return null;\n }\n\n const directHooks = new Set<string>();\n const namespaceHooks = new Set<string>();\n\n walk(ast, (node) => {\n if (node.type !== 'ImportDeclaration') return;\n\n const src = node.source?.value;\n\n if (typeof src !== 'string' || !REACT_SOURCE.test(src)) return;\n\n for (const spec of node.specifiers ?? []) {\n if (spec.type === 'ImportSpecifier') {\n const imported = spec.imported?.name ?? spec.imported?.value;\n\n if (HOOK_NAMES.has(imported)) directHooks.add(spec.local.name);\n } else if (spec.type === 'ImportDefaultSpecifier' || spec.type === 'ImportNamespaceSpecifier') {\n namespaceHooks.add(spec.local.name);\n }\n }\n });\n\n if (directHooks.size === 0 && namespaceHooks.size === 0) return null;\n\n const replacements: { start: number; end: number }[] = [];\n\n walk(ast, (node) => {\n if (node.type !== 'CallExpression' || !node.arguments?.length) return;\n\n const callee = node.callee;\n const isDirect = callee.type === 'Identifier' && directHooks.has(callee.name);\n const isMember =\n callee.type === 'MemberExpression' &&\n !callee.computed &&\n callee.object?.type === 'Identifier' &&\n namespaceHooks.has(callee.object.name) &&\n callee.property?.type === 'Identifier' &&\n HOOK_NAMES.has(callee.property.name);\n\n if (!isDirect && !isMember) return;\n\n const arg = node.arguments[0];\n\n replacements.push({ start: arg.start, end: arg.end });\n });\n\n if (replacements.length === 0) return null;\n\n const s = new MagicString(code);\n\n for (const { start, end } of replacements) {\n s.overwrite(start, end, EMPTY_FN);\n }\n\n return { code: s.toString(), map: s.generateMap({ hires: true }) };\n },\n };\n}\n\nfunction walk(node: any, visit: (n: any) => void): void {\n if (!node || typeof node !== 'object') return;\n\n if (typeof node.type === 'string') visit(node);\n\n for (const key of Object.keys(node)) {\n const v = node[key];\n\n if (Array.isArray(v)) for (const item of v) walk(item, visit);\n else if (v && typeof v === 'object') walk(v, visit);\n }\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { AstroConfig, AstroIntegration } from 'astro';\nimport { createDevMachinery } from '../dev-mode/machinery.js';\nimport { type ExcludePattern, RECOMMENDED_EXCLUDES } from '../excludes/excludes.js';\nimport { serializeExcludePatterns } from '../excludes/serialize.js';\nimport { createRequestInstrumentation } from '../observability/instrument.js';\nimport { preparePlatform } from '../platform/prepare.js';\nimport { dispatchNativeMount } from '../server/native-mount.js';\nimport { ssrSourcemapPlugin } from '../tweaks/sourcemap.js';\nimport { stripSsrEffectsPlugin } from '../tweaks/strip-effects.js';\nimport type { NodeOptions, RuntimeOptions } from '../types.js';\n\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config';\nexport const BOOT_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/boot';\nexport const CSRF_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/csrf';\nexport const CONFIG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/config-entry';\nexport const INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/instrumentation-entry';\nexport const LOG_ENTRY_VIRTUAL_MODULE_ID = 'virtual:@astroscope/node/log-entry';\n\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_BOOT_VIRTUAL_MODULE_ID = `\\0${BOOT_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CSRF_VIRTUAL_MODULE_ID = `\\0${CSRF_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID = `\\0${CONFIG_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID = `\\0${INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID}`;\nconst RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID = `\\0${LOG_ENTRY_VIRTUAL_MODULE_ID}`;\n\nconst SERVER_ENVIRONMENTS = ['ssr', 'prerender', 'astro'];\nconst DEFAULT_REQUEST_EXCLUDES: ExcludePattern[] = [...RECOMMENDED_EXCLUDES];\n\nfunction resolveHost(host: string | boolean | undefined): string {\n if (typeof host === 'string') return host;\n\n return host === true ? '0.0.0.0' : 'localhost';\n}\n\nfunction resolveBootEntry(root: string, entry: string | undefined): string | undefined {\n if (entry) {\n const abs = path.resolve(root, entry);\n\n if (!fs.existsSync(abs)) {\n throw new Error(`[@astroscope/node] boot entry not found: ${entry}`);\n }\n\n return abs;\n }\n\n for (const candidate of ['src/boot/index.ts', 'src/boot.ts']) {\n const abs = path.resolve(root, candidate);\n\n if (fs.existsSync(abs)) return abs;\n }\n\n return undefined;\n}\n\nfunction resolveSeam(root: string, candidate: string): string | undefined {\n const abs = path.resolve(root, candidate);\n\n return fs.existsSync(abs) ? abs : undefined;\n}\n\n/**\n * Node adapter for Astro with a first-class server entrypoint: the boot\n * lifecycle, module warmup, health probes, request logging and telemetry run\n * as plain code around `server.listen()` instead of being injected into the\n * build output.\n */\nexport default function node(options: NodeOptions = {}): AstroIntegration {\n const bootOptions = options.boot ?? {};\n const healthOptions = options.health ?? {};\n const csrfOptions = options.csrf ?? {};\n const loggingOptions = options.logging ?? {};\n const telemetryOptions = options.telemetry ?? {};\n\n const loggingExclude = loggingOptions ? (loggingOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n const telemetryExclude = telemetryOptions ? (telemetryOptions.exclude ?? DEFAULT_REQUEST_EXCLUDES) : [];\n\n let astroConfig: AstroConfig | null = null;\n let bootEntry: string | undefined;\n let configSeam: string | undefined;\n let instrumentationSeam: string | undefined;\n let logSeam: string | undefined;\n let isDev = false;\n\n return {\n name: '@astroscope/node',\n hooks: {\n 'astro:config:setup': ({ command, config, updateConfig, addMiddleware, logger }) => {\n isDev = command === 'dev';\n\n // route enrichment first so csrf-rejected requests still carry a route\n if (loggingOptions || telemetryOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/route-middleware' });\n }\n\n if (csrfOptions) {\n addMiddleware({ order: 'pre', entrypoint: '@astroscope/node/csrf-middleware' });\n }\n\n const root = fileURLToPath(config.root);\n const watch = bootOptions === false ? false : (bootOptions.watch ?? true);\n\n bootEntry = bootOptions === false ? undefined : resolveBootEntry(root, bootOptions.entry);\n configSeam = resolveSeam(root, 'src/config.ts');\n instrumentationSeam = resolveSeam(root, 'src/instrumentation.ts');\n logSeam = resolveSeam(root, 'src/log.ts');\n\n const relativeSeam = (abs: string | undefined) =>\n abs ? path.relative(root, abs).split(path.sep).join('/') : undefined;\n\n const devMachinery =\n command === 'dev' && bootOptions !== false\n ? createDevMachinery({\n entry: bootEntry ? path.relative(root, bootEntry) : undefined,\n watch,\n // instrumentation runs once per process — watching it would\n // restart generations that can't re-apply it\n watchEntries: [relativeSeam(configSeam), relativeSeam(logSeam)].filter(\n (entry): entry is string => !!entry,\n ),\n prepare: (importModule) =>\n preparePlatform({\n dev: true,\n telemetry:\n telemetryOptions && telemetryOptions.dev\n ? { prometheus: telemetryOptions.prometheus ?? {} }\n : false,\n seams: {\n ...(configSeam && { config: () => importModule(`/${relativeSeam(configSeam)}`) }),\n ...(instrumentationSeam && {\n instrumentation: () => importModule(`/${relativeSeam(instrumentationSeam)}`),\n }),\n ...(logSeam && { log: () => importModule(`/${relativeSeam(logSeam)}`) }),\n },\n }),\n logger,\n getConfig: () => astroConfig,\n })\n : [];\n\n if (command === 'dev' && bootOptions !== false && watch) {\n // catches errors thrown by stale (post-shutdown) requests so\n // they don't pollute the logs during dev-server restarts.\n addMiddleware({ entrypoint: '@astroscope/node/dev-middleware', order: 'pre' });\n }\n\n updateConfig({\n build: { redirects: false },\n // opinionated defaults: no trailing slashes, behind LB\n ...(config.trailingSlash === 'ignore' && { trailingSlash: 'never' as const }),\n security: {\n // assumed to run behind LB\n ...(!config.security.allowedDomains?.length && { allowedDomains: [{}] }),\n // the embedded csrf middleware replaces the built-in origin check\n ...(csrfOptions && { checkOrigin: false }),\n },\n image: {\n endpoint: {\n route: config.image.endpoint.route ?? '_image',\n entrypoint:\n config.image.endpoint.entrypoint ??\n (command === 'dev' ? 'astro/assets/endpoint/dev' : 'astro/assets/endpoint/node'),\n },\n },\n vite: {\n plugins: [\n ...devMachinery,\n ssrSourcemapPlugin(),\n stripSsrEffectsPlugin(),\n {\n name: '@astroscope/node',\n\n configEnvironment(environmentName: string) {\n if (SERVER_ENVIRONMENTS.includes(environmentName)) {\n return { resolve: { noExternal: ['@astroscope/node'] } };\n }\n },\n\n resolveId(id: string) {\n if (id === CONFIG_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n if (id === BOOT_VIRTUAL_MODULE_ID) return RESOLVED_BOOT_VIRTUAL_MODULE_ID;\n if (id === CSRF_VIRTUAL_MODULE_ID) return RESOLVED_CSRF_VIRTUAL_MODULE_ID;\n if (id === CONFIG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID;\n if (id === INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID;\n }\n if (id === LOG_ENTRY_VIRTUAL_MODULE_ID) return RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID;\n },\n\n load(id: string) {\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n if (!astroConfig) throw new Error('[@astroscope/node] astro config not resolved yet');\n\n const runtimeOptions: Omit<RuntimeOptions, 'logging' | 'telemetry'> = {\n host: resolveHost(astroConfig.server.host),\n port: astroConfig.server.port ?? 4321,\n client: astroConfig.build.client.toString(),\n server: astroConfig.build.server.toString(),\n bodySizeLimit: options.bodySizeLimit ?? 1024 * 1024 * 1024,\n shutdownTimeout: options.shutdownTimeout ?? 10_000,\n health: healthOptions\n ? {\n ...(healthOptions.host !== undefined && { host: healthOptions.host }),\n ...(healthOptions.port !== undefined && { port: healthOptions.port }),\n ...(healthOptions.paths && { paths: healthOptions.paths }),\n }\n : false,\n };\n\n // exclude patterns may contain RegExp — serialized as code, not JSON\n const logging = loggingOptions\n ? `{ exclude: ${serializeExcludePatterns(loggingExclude)}, extended: ${JSON.stringify(\n loggingOptions.extended ?? false,\n )} }`\n : 'false';\n const telemetry = telemetryOptions\n ? `{ exclude: ${serializeExcludePatterns(telemetryExclude)}, prometheus: ${JSON.stringify(\n telemetryOptions.prometheus ?? {},\n )} }`\n : 'false';\n\n return `export const options = { ...${JSON.stringify(runtimeOptions)}, logging: ${logging}, telemetry: ${telemetry} };`;\n }\n\n if (id === RESOLVED_BOOT_VIRTUAL_MODULE_ID) {\n // re-export to avoid absolute path manifest leaks\n return bootEntry ? `export * from ${JSON.stringify(bootEntry)};` : 'export {};';\n }\n\n if (id === RESOLVED_CSRF_VIRTUAL_MODULE_ID) {\n return `export const excludePatterns = ${serializeExcludePatterns(csrfOptions ? (csrfOptions.exclude ?? []) : [])};`;\n }\n\n if (id === RESOLVED_CONFIG_ENTRY_VIRTUAL_MODULE_ID) {\n // side-effect import: @entwico/zod-conf validation runs at module load\n return configSeam ? `import ${JSON.stringify(configSeam)};\\nexport {};` : 'export {};';\n }\n\n if (id === RESOLVED_INSTRUMENTATION_ENTRY_VIRTUAL_MODULE_ID) {\n return instrumentationSeam ? `export * from ${JSON.stringify(instrumentationSeam)};` : 'export {};';\n }\n\n if (id === RESOLVED_LOG_ENTRY_VIRTUAL_MODULE_ID) {\n return logSeam\n ? `export { default } from ${JSON.stringify(logSeam)};`\n : 'export default undefined;';\n }\n },\n },\n ],\n },\n });\n },\n 'astro:server:setup': ({ server }) => {\n if (!isDev) return;\n\n const devLogging = loggingOptions && loggingOptions.dev;\n const devTelemetry = telemetryOptions && telemetryOptions.dev;\n\n const instrument =\n devLogging || devTelemetry\n ? createRequestInstrumentation({\n logging: devLogging ? { exclude: loggingExclude, extended: loggingOptions.extended ?? false } : false,\n telemetry: devTelemetry ? { exclude: telemetryExclude } : false,\n })\n : undefined;\n\n server.middlewares.use((req, res, next) => {\n const inner = (): void => {\n if (!dispatchNativeMount(req, res)) next();\n };\n\n if (instrument) {\n instrument(req, res, inner);\n } else {\n inner();\n }\n });\n },\n 'astro:config:done': ({ config, setAdapter }) => {\n astroConfig = config;\n\n setAdapter({\n name: '@astroscope/node',\n entrypointResolution: 'auto',\n serverEntrypoint: '@astroscope/node/server',\n previewEntrypoint: '@astroscope/node/preview',\n adapterFeatures: {\n buildOutput: 'server',\n middlewareMode: 'classic',\n },\n supportedAstroFeatures: {\n hybridOutput: 'stable',\n staticOutput: 'stable',\n serverOutput: 'stable',\n sharpImageService: 'stable',\n i18nDomains: 'experimental',\n envGetSecret: 'stable',\n },\n });\n },\n 'astro:build:done': async ({ logger }) => {\n if (!astroConfig) return;\n\n const { compressClientDir } = await import('../compress/compress.js');\n\n await compressClientDir(fileURLToPath(astroConfig.build.client), logger);\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAgB,eAAe,OAAwB;CACrD,IAAI,iBAAiB,OACnB,OAAO,MAAM,SAAS,MAAM;CAG9B,OAAO,KAAK,UAAU,KAAK;AAC7B;;;ACAA,MAAM,sBAAsB;;;;;;;;;;AAW5B,IAAa,mBAAb,MAA8B;CAaT;CACA;CAbnB,YAAoB;CACpB,WAAmB;CACnB;CACA,mCAA2B,IAAI,IAAY;CAC3C,sCAA8B,IAAI,IAAY;CAG9C;CAEA;CAEA,YACE,YACA,QACA;EAFiB,KAAA,aAAA;EACA,KAAA,SAAA;CAChB;CAIH,mBAA4B;EAC1B,OAAO,CAAC,CAAC,KAAK,eAAe,CAAC,CAAC,KAAK,kBAAkB,CAAC,CAAC,KAAK;CAC/D;CAEA,iBAAkD;EAChD,OAAO,KAAK;CACd;CAEA,cAAc,SAAuB;EACnC,KAAK,eAAe,EAAE,QAAQ;CAChC;CAEA,eAAqB;EACnB,KAAK,eAAe,KAAA;CACtB;CAEA,SAAS,QAAuB,aAA2B;EACzD,KAAK,iBAAiB,IAAI,WAAW;EACrC,KAAK,aAAa,MAAM;CAC1B;CAEA,mBAAmB,QAAuB,aAA4B;EACpE,KAAK,oBAAoB,IAAI,eAAe,mBAAmB;EAC/D,KAAK,aAAa,MAAM;CAC1B;;;;;;;CAQA,MAAM,iBAAgC;EACpC,OAAO,KAAK,aACV,IAAI;GACF,MAAM,KAAK;EACb,QAAQ,CAER;CAEJ;CAEA,aAAqB,QAA6B;EAChD,aAAa,KAAK,cAAc;EAChC,KAAK,iBA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K,KAAK;UAE1B,MAAM;IAEV,CAAC;GACH;GACA,sBAAsB,EAAE,QAAQ,iBAAiB;IAC/C,cAAc;IAEd,WAAW;KACT,MAAM;KACN,sBAAsB;KACtB,kBAAkB;KAClB,mBAAmB;KACnB,iBAAiB;MACf,aAAa;MACb,gBAAgB;KAClB;KACA,wBAAwB;MACtB,cAAc;MACd,cAAc;MACd,cAAc;MACd,mBAAmB;MACnB,aAAa;MACb,cAAc;KAChB;IACF,CAAC;GACH;GACA,oBAAoB,OAAO,EAAE,aAAa;IACxC,IAAI,CAAC,aAAa;IAElB,MAAM,EAAE,sBAAsB,MAAM,OAAO;IAE3C,MAAM,kBAAkB,cAAc,YAAY,MAAM,MAAM,GAAG,MAAM;GACzE;EACF;CACF;AACF"}
@@ -2,7 +2,7 @@ import { t as emit } from "./events-CgoM3Fvu.js";
2
2
  import { t as getLogStore } from "./store-BIUF4lqk.js";
3
3
  import { n as log, t as generateReqId } from "./log-CSJlKaxY.js";
4
4
  import fs from "node:fs";
5
- import { SpanKind, SpanStatusCode, ValueType, context, isSpanContextValid, metrics, propagation, trace } from "@opentelemetry/api";
5
+ import { ROOT_CONTEXT, SpanKind, SpanStatusCode, ValueType, context, isSpanContextValid, metrics, propagation, trace } from "@opentelemetry/api";
6
6
  import pino from "pino";
7
7
  import { createMatcher } from "@entwico/dash/match";
8
8
  //#region src/lifecycle/lifecycle.ts
@@ -141,9 +141,10 @@ function createRequestInstrumentation(config) {
141
141
  actionName: isAction ? pathname.slice(10).replace(/\/$/, "") : void 0
142
142
  };
143
143
  let span;
144
+ let firstByteSpan;
144
145
  let endActiveRequest;
145
146
  if (telemetry) {
146
- const parentContext = propagation.extract(context.active(), req.headers);
147
+ const parentContext = propagation.extract(ROOT_CONTEXT, req.headers);
147
148
  const contentLength = req.headers["content-length"];
148
149
  const clientIp = getClientIp(req);
149
150
  const host = req.headers["host"];
@@ -160,19 +161,28 @@ function createRequestInstrumentation(config) {
160
161
  ...clientIp && { "client.address": clientIp }
161
162
  }
162
163
  }, parentContext);
164
+ firstByteSpan = tracer.startSpan("response:first-byte", void 0, trace.setSpan(parentContext, span));
163
165
  endActiveRequest = recordHttpRequestStart(method);
164
166
  }
165
167
  let responseSize = 0;
166
168
  let firstByteTime;
167
169
  const originalWrite = res.write.bind(res);
168
170
  const originalEnd = res.end.bind(res);
171
+ const markFirstByte = () => {
172
+ if (firstByteTime !== void 0) return;
173
+ firstByteTime = performance.now();
174
+ if (firstByteSpan) {
175
+ firstByteSpan.setAttribute("http.response.status_code", res.statusCode);
176
+ firstByteSpan.end();
177
+ }
178
+ };
169
179
  res.write = ((chunk, ...rest) => {
170
- firstByteTime ??= performance.now();
180
+ markFirstByte();
171
181
  responseSize += chunkSize(chunk);
172
182
  return originalWrite(chunk, ...rest);
173
183
  });
174
184
  res.end = ((chunk, ...rest) => {
175
- firstByteTime ??= performance.now();
185
+ markFirstByte();
176
186
  responseSize += chunkSize(chunk);
177
187
  return originalEnd(chunk, ...rest);
178
188
  });
@@ -182,17 +192,26 @@ function createRequestInstrumentation(config) {
182
192
  finalized = true;
183
193
  const status = res.statusCode;
184
194
  const responseTime = performance.now() - startTime;
195
+ const ttfb = roundTime((firstByteTime ?? performance.now()) - startTime);
185
196
  if (requestLogger) requestLogger[status >= 500 ? "error" : status >= 400 ? "warn" : "info"]({
186
197
  res: { statusCode: status },
187
198
  responseTime: roundTime(responseTime),
188
- ttfb: roundTime((firstByteTime ?? performance.now()) - startTime),
199
+ ttfb,
189
200
  responseSize,
190
201
  ...record.route && { route: record.route },
191
202
  ...aborted && { aborted: true }
192
203
  }, aborted ? "request aborted" : "request completed");
204
+ if (firstByteSpan && firstByteTime === void 0) {
205
+ firstByteSpan.setStatus({
206
+ code: SpanStatusCode.ERROR,
207
+ message: "request aborted"
208
+ });
209
+ firstByteSpan.end();
210
+ }
193
211
  if (span) {
194
212
  span.setAttribute("http.response.status_code", status);
195
213
  span.setAttribute("http.response.body.size", responseSize);
214
+ span.setAttribute("ttfb", ttfb);
196
215
  if (aborted || status >= 400) span.setStatus({
197
216
  code: SpanStatusCode.ERROR,
198
217
  message: aborted ? "request aborted" : `HTTP ${status}`
@@ -387,4 +406,4 @@ async function preparePlatform(options) {
387
406
  //#endregion
388
407
  export { runShutdown as a, createRequestInstrumentation as i, shutdownTelemetry as n, runStartup as o, dumpEarlyLogs as r, preparePlatform as t };
389
408
 
390
- //# sourceMappingURL=prepare-Be2GgRyf.js.map
409
+ //# sourceMappingURL=prepare-DQEf2Bnt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prepare-DQEf2Bnt.js","names":["LIB_NAME"],"sources":["../src/lifecycle/lifecycle.ts","../src/observability/telemetry/metrics.ts","../src/observability/instrument.ts","../src/observability/log/construct.ts","../src/observability/telemetry/sdk.ts","../src/platform/env.ts","../src/platform/prepare.ts"],"sourcesContent":["import { emit } from './events.js';\nimport type { BootContext } from './types.js';\n\nexport interface BootModule {\n onStartup?: ((context: BootContext) => Promise<void> | void) | undefined;\n onShutdown?: ((context: BootContext) => Promise<void> | void) | undefined;\n}\n\nexport async function runStartup(boot: BootModule, context: BootContext): Promise<void> {\n await emit('beforeOnStartup', context);\n await boot.onStartup?.(context);\n await emit('afterOnStartup', context);\n}\n\nexport async function runShutdown(boot: BootModule, context: BootContext): Promise<void> {\n try {\n await emit('beforeOnShutdown', context);\n await boot.onShutdown?.(context);\n } finally {\n await emit('afterOnShutdown', context);\n }\n}\n","import { type Histogram, type UpDownCounter, ValueType, metrics } from '@opentelemetry/api';\n\nconst LIB_NAME = '@astroscope/node';\n\n// lazy initialization so instruments bind to the SDK meter provider\nlet httpRequestDuration: Histogram | null = null;\nlet httpActiveRequests: UpDownCounter | null = null;\nlet actionDuration: Histogram | null = null;\n\nfunction getHttpRequestDuration(): Histogram {\n return (httpRequestDuration ??= metrics.getMeter(LIB_NAME).createHistogram('http.server.request.duration', {\n description: 'Duration of HTTP server requests',\n unit: 's',\n valueType: ValueType.DOUBLE,\n }));\n}\n\nfunction getHttpActiveRequests(): UpDownCounter {\n return (httpActiveRequests ??= metrics.getMeter(LIB_NAME).createUpDownCounter('http.server.active_requests', {\n description: 'Number of active HTTP server requests',\n unit: '{request}',\n valueType: ValueType.INT,\n }));\n}\n\nfunction getActionDuration(): Histogram {\n return (actionDuration ??= metrics.getMeter(LIB_NAME).createHistogram('astro.action.duration', {\n description: 'Duration of Astro action executions',\n unit: 's',\n valueType: ValueType.DOUBLE,\n }));\n}\n\n/**\n * Record the start of an HTTP request. Returns a function to call when the\n * request ends. Route is unknown at the native-handler level, so active\n * requests carry only the method.\n */\nexport function recordHttpRequestStart(method: string): () => void {\n getHttpActiveRequests().add(1, { 'http.request.method': method });\n\n return () => {\n getHttpActiveRequests().add(-1, { 'http.request.method': method });\n };\n}\n\nexport function recordHttpRequestDuration(\n attributes: { method: string; route: string | undefined; status: number },\n durationMs: number,\n): void {\n getHttpRequestDuration().record(durationMs / 1000, {\n 'http.request.method': attributes.method,\n 'http.route': attributes.route ?? '',\n 'http.response.status_code': attributes.status,\n });\n}\n\nexport function recordActionDuration(attributes: { name: string; status: number }, durationMs: number): void {\n getActionDuration().record(durationMs / 1000, {\n 'astro.action.name': attributes.name,\n 'http.response.status_code': attributes.status,\n });\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { createMatcher } from '@entwico/dash/match';\nimport { ROOT_CONTEXT, SpanKind, SpanStatusCode, context, propagation, trace } from '@opentelemetry/api';\nimport type { Logger } from 'pino';\nimport type { ExcludePattern } from '../excludes/excludes.js';\nimport { generateReqId } from './log/index.js';\nimport { type RequestRecord, getLogStore } from './log/store.js';\nimport { recordActionDuration, recordHttpRequestDuration, recordHttpRequestStart } from './telemetry/metrics.js';\n\nconst LIB_NAME = '@astroscope/node';\nconst ACTIONS_PREFIX = '/_actions/';\nconst REQUEST_ID_PATTERN = /^[\\w.-]{1,64}$/;\n\nconst roundTime = (n: number) => Math.round(n * 100) / 100;\n\nexport interface RequestLoggingConfig {\n exclude: ExcludePattern[];\n extended: boolean;\n}\n\nexport interface RequestTelemetryConfig {\n exclude: ExcludePattern[];\n}\n\nexport interface RequestInstrumentationConfig {\n logging: RequestLoggingConfig | false;\n telemetry: RequestTelemetryConfig | false;\n}\n\nfunction getClientIp(req: IncomingMessage): string | undefined {\n const forwarded = req.headers['x-forwarded-for'];\n const first = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n\n return (\n first?.split(',')[0]?.trim() ??\n (req.headers['x-real-ip'] as string | undefined) ??\n (req.headers['cf-connecting-ip'] as string | undefined)\n );\n}\n\nfunction resolveReqId(req: IncomingMessage): string {\n const incoming = req.headers['x-request-id'];\n const value = Array.isArray(incoming) ? incoming[0] : incoming;\n\n return value && REQUEST_ID_PATTERN.test(value) ? value : generateReqId();\n}\n\nfunction chunkSize(chunk: unknown): number {\n if (chunk == null) return 0;\n if (ArrayBuffer.isView(chunk)) return chunk.byteLength;\n if (typeof chunk === 'string') return Buffer.byteLength(chunk);\n\n return 0;\n}\n\n/**\n * Wraps the native request/response with logging and telemetry: a request\n * logger in async context (real status, response size, aborted-vs-completed\n * on `finish`/`close`), a SERVER span with propagation extraction, and\n * request metrics. Both concerns honor their own exclude patterns; when both\n * are excluded the request passes through untouched.\n */\nexport function createRequestInstrumentation(config: RequestInstrumentationConfig) {\n const tracer = trace.getTracer(LIB_NAME);\n const store = getLogStore();\n const loggingExcluded = config.logging ? createMatcher(config.logging.exclude) : () => true;\n const telemetryExcluded = config.telemetry ? createMatcher(config.telemetry.exclude) : () => true;\n\n return (req: IncomingMessage, res: ServerResponse, inner: () => void): void => {\n const url = req.url ?? '';\n const queryIndex = url.indexOf('?');\n const pathname = queryIndex === -1 ? url : url.slice(0, queryIndex);\n const method = req.method ?? 'GET';\n\n const logging = config.logging && !loggingExcluded(pathname) ? config.logging : false;\n const telemetry = config.telemetry && !telemetryExcluded(pathname) ? config.telemetry : false;\n\n if (!logging && !telemetry) {\n inner();\n\n return;\n }\n\n const startTime = performance.now();\n const isAction = pathname.startsWith(ACTIONS_PREFIX);\n\n let requestLogger: Logger | undefined;\n\n if (logging && store.root) {\n const reqId = resolveReqId(req);\n const reqData: Record<string, unknown> = { method, url: pathname };\n\n // extended logging includes potentially sensitive data\n if (logging.extended) {\n reqData['query'] = queryIndex === -1 ? '' : url.slice(queryIndex + 1);\n reqData['headers'] = req.headers;\n reqData['remoteAddress'] = getClientIp(req) ?? req.socket.remoteAddress;\n }\n\n requestLogger = store.root.child({ reqId, req: reqData });\n\n res.setHeader('x-request-id', reqId);\n }\n\n const record: RequestRecord = {\n logger: requestLogger,\n url,\n route: undefined,\n actionName: isAction ? pathname.slice(ACTIONS_PREFIX.length).replace(/\\/$/, '') : undefined,\n };\n\n let span: ReturnType<typeof tracer.startSpan> | undefined;\n let firstByteSpan: ReturnType<typeof tracer.startSpan> | undefined;\n let endActiveRequest: (() => void) | undefined;\n\n if (telemetry) {\n const parentContext = propagation.extract(ROOT_CONTEXT, req.headers);\n const contentLength = req.headers['content-length'];\n const clientIp = getClientIp(req);\n const host = req.headers['host'];\n\n span = tracer.startSpan(\n isAction ? `ACTION ${record.actionName}` : method,\n {\n kind: SpanKind.SERVER,\n attributes: {\n 'http.request.method': method,\n 'url.path': pathname,\n 'url.query': queryIndex === -1 ? '' : url.slice(queryIndex + 1),\n 'url.scheme': 'http',\n 'user_agent.original': req.headers['user-agent'] ?? '',\n ...(host && { 'server.address': host }),\n ...(contentLength && { 'http.request.body.size': parseInt(contentLength) }),\n ...(clientIp && { 'client.address': clientIp }),\n },\n },\n parentContext,\n );\n\n firstByteSpan = tracer.startSpan('response:first-byte', undefined, trace.setSpan(parentContext, span));\n\n endActiveRequest = recordHttpRequestStart(method);\n }\n\n let responseSize = 0;\n let firstByteTime: number | undefined;\n\n const originalWrite = res.write.bind(res);\n const originalEnd = res.end.bind(res);\n\n const markFirstByte = (): void => {\n if (firstByteTime !== undefined) return;\n\n firstByteTime = performance.now();\n\n if (firstByteSpan) {\n firstByteSpan.setAttribute('http.response.status_code', res.statusCode);\n firstByteSpan.end();\n }\n };\n\n res.write = ((chunk: unknown, ...rest: unknown[]) => {\n markFirstByte();\n responseSize += chunkSize(chunk);\n\n return (originalWrite as (...args: unknown[]) => boolean)(chunk, ...rest);\n }) as typeof res.write;\n\n res.end = ((chunk: unknown, ...rest: unknown[]) => {\n markFirstByte();\n responseSize += chunkSize(chunk);\n\n return (originalEnd as (...args: unknown[]) => ServerResponse)(chunk, ...rest);\n }) as typeof res.end;\n\n let finalized = false;\n\n const finalize = (aborted: boolean): void => {\n if (finalized) return;\n\n finalized = true;\n\n const status = res.statusCode;\n const responseTime = performance.now() - startTime;\n const ttfb = roundTime((firstByteTime ?? performance.now()) - startTime);\n\n if (requestLogger) {\n const level = status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info';\n\n requestLogger[level](\n {\n res: { statusCode: status },\n responseTime: roundTime(responseTime),\n ttfb,\n responseSize,\n ...(record.route && { route: record.route }),\n ...(aborted && { aborted: true }),\n },\n aborted ? 'request aborted' : 'request completed',\n );\n }\n\n if (firstByteSpan && firstByteTime === undefined) {\n firstByteSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'request aborted' });\n firstByteSpan.end();\n }\n\n if (span) {\n span.setAttribute('http.response.status_code', status);\n span.setAttribute('http.response.body.size', responseSize);\n span.setAttribute('ttfb', ttfb);\n\n if (aborted || status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: aborted ? 'request aborted' : `HTTP ${status}` });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n\n span.end();\n }\n\n if (telemetry) {\n endActiveRequest?.();\n recordHttpRequestDuration({ method, route: record.route, status }, responseTime);\n\n if (record.actionName) {\n recordActionDuration({ name: record.actionName, status }, responseTime);\n }\n }\n };\n\n res.once('finish', () => finalize(false));\n res.once('close', () => finalize(!res.writableFinished));\n\n const run = (): void => store.requestStorage.run(record, inner);\n\n if (span) {\n context.with(trace.setSpan(context.active(), span), run);\n } else {\n run();\n }\n };\n}\n","import { isSpanContextValid, trace } from '@opentelemetry/api';\nimport pino, { type Bindings, type Logger, type LoggerOptions } from 'pino';\nimport { getLogStore } from './store.js';\n\n/**\n * Contract of the `src/log.ts` entry seam: pino logger options, or a factory\n * producing them. Never a logger instance — the platform constructs the\n * logger itself (after instrumentation, so trace correlation works).\n */\nexport type LoggerOptionsFactory = LoggerOptions | ((ctx: { dev: boolean }) => LoggerOptions | Promise<LoggerOptions>);\n\n/**\n * Compose the user mixin (if any) with platform trace correlation: when a\n * span is active, every entry carries `trace_id` / `span_id` / `trace_flags`.\n */\nfunction composeMixin(userMixin: LoggerOptions['mixin']): NonNullable<LoggerOptions['mixin']> {\n return (mergeObject, level, logger) => {\n const user = userMixin ? userMixin(mergeObject, level, logger) : {};\n const spanContext = trace.getActiveSpan()?.spanContext();\n\n if (!spanContext || !isSpanContextValid(spanContext)) return user;\n\n return {\n ...user,\n trace_id: spanContext.traceId,\n span_id: spanContext.spanId,\n trace_flags: `0${spanContext.traceFlags.toString(16)}`,\n };\n };\n}\n\n/**\n * Construct the root logger from the app's options seam and replay any logs\n * buffered before construction (original timestamps kept as `bufferedTime`).\n * In dev this runs once per generation; the buffer only exists the first time.\n */\nexport async function constructRootLogger(\n factory: LoggerOptionsFactory | undefined,\n ctx: { dev: boolean },\n): Promise<Logger> {\n const store = getLogStore();\n const options = (typeof factory === 'function' ? await factory(ctx) : factory) ?? {};\n const root = pino({ level: 'info', ...options, mixin: composeMixin(options.mixin) });\n\n store.root = root;\n\n for (const entry of store.buffer.splice(0)) {\n const bindings = entry.bindings.length ? (Object.assign({}, ...entry.bindings) as Bindings) : {};\n const target = root.child({ ...bindings, bufferedTime: new Date(entry.time).toISOString() });\n\n (target[entry.level] as (...args: unknown[]) => void)(...entry.args);\n }\n\n if (store.dropped > 0) {\n root.warn({ dropped: store.dropped }, 'early log buffer overflowed, entries dropped');\n store.dropped = 0;\n }\n\n return root;\n}\n\n/**\n * Failure path for startups that die before the logger exists: dump the\n * buffered entries to the console so no phase is silent.\n */\nexport function dumpEarlyLogs(): void {\n const store = getLogStore();\n\n if (store.root) return;\n\n for (const entry of store.buffer.splice(0)) {\n const bindings = entry.bindings.length ? Object.assign({}, ...entry.bindings) : undefined;\n\n console.error(\n new Date(entry.time).toISOString(),\n entry.level.toUpperCase(),\n ...(bindings ? [bindings] : []),\n ...entry.args,\n );\n }\n\n if (store.dropped > 0) {\n console.error(`(${store.dropped} early log entries dropped)`);\n store.dropped = 0;\n }\n}\n","import { log } from '../log/index.js';\n\n/**\n * Platform-owned telemetry bundle: NodeSDK with undici (fetch) and node\n * runtime instrumentation, host metrics, and a Prometheus reader. Trace\n * exporters are driven by standard `OTEL_*` env vars; without any of them\n * traces stay off (no failing localhost OTLP exports).\n *\n * Guarded per process (dev restarts are in-process; a re-created NodeSDK\n * would double-register instrumentations and leak the Prometheus port).\n */\n\nconst TELEMETRY_KEY = Symbol.for('@astroscope/node/telemetry');\n\ninterface TelemetryHandle {\n shutdown: () => Promise<void>;\n}\n\nexport interface TelemetrySdkOptions {\n prometheus: { host?: string | undefined; port?: number | undefined } | false;\n}\n\nfunction getHandle(): TelemetryHandle | undefined {\n return (globalThis as Record<symbol, unknown>)[TELEMETRY_KEY] as TelemetryHandle | undefined;\n}\n\nfunction defaultEnv(key: string, value: string): void {\n if (!process.env[key]) process.env[key] = value;\n}\n\nexport async function startTelemetry(options: TelemetrySdkOptions): Promise<void> {\n const g = globalThis as Record<symbol, unknown>;\n\n if (g[TELEMETRY_KEY]) return;\n\n if (process.env['OTEL_SDK_DISABLED'] === 'true') {\n log.debug('telemetry disabled via OTEL_SDK_DISABLED');\n\n return;\n }\n\n // without an explicitly configured exporter target, exporting traces to the\n // default localhost OTLP endpoint would fail on every flush\n if (!process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] && !process.env['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT']) {\n defaultEnv('OTEL_TRACES_EXPORTER', 'none');\n }\n\n defaultEnv('OTEL_METRICS_EXPORTER', 'none');\n defaultEnv('OTEL_LOGS_EXPORTER', 'none');\n\n const [\n { NodeSDK },\n { UndiciInstrumentation },\n { RuntimeNodeInstrumentation },\n { PrometheusExporter },\n { HostMetrics },\n ] = await Promise.all([\n import('@opentelemetry/sdk-node'),\n import('@opentelemetry/instrumentation-undici'),\n import('@opentelemetry/instrumentation-runtime-node'),\n import('@opentelemetry/exporter-prometheus'),\n import('@opentelemetry/host-metrics'),\n ]);\n\n const prometheus = options.prometheus\n ? {\n host: process.env['OTEL_EXPORTER_PROMETHEUS_HOST'] ?? options.prometheus.host ?? '0.0.0.0',\n port: process.env['OTEL_EXPORTER_PROMETHEUS_PORT']\n ? Number(process.env['OTEL_EXPORTER_PROMETHEUS_PORT'])\n : (options.prometheus.port ?? 9464),\n }\n : false;\n\n const sdk = new NodeSDK({\n instrumentations: [new UndiciInstrumentation(), new RuntimeNodeInstrumentation()],\n ...(prometheus && { metricReaders: [new PrometheusExporter(prometheus)] }),\n });\n\n sdk.start();\n\n const hostMetrics = new HostMetrics();\n\n hostMetrics.start();\n\n g[TELEMETRY_KEY] = {\n shutdown: () => sdk.shutdown(),\n } satisfies TelemetryHandle;\n\n if (prometheus) {\n log.debug({ host: prometheus.host, port: prometheus.port }, 'prometheus metrics listening');\n }\n}\n\n/**\n * Flush and shut the SDK down. Prod-only (dev keeps the SDK for the process\n * lifetime across generations).\n */\nexport async function shutdownTelemetry(): Promise<void> {\n const handle = getHandle();\n\n if (!handle) return;\n\n delete (globalThis as Record<symbol, unknown>)[TELEMETRY_KEY];\n\n await handle.shutdown();\n}\n","import fs from 'node:fs';\nimport { log } from '../observability/log/index.js';\n\n/**\n * Platform env loading (position −1, before the config seam):\n * `CONFIG_PATH` → `./.env` → none. Existing process env vars win\n */\nexport function loadEnvFiles(): void {\n const configPath = process.env['CONFIG_PATH'];\n\n if (configPath) {\n process.loadEnvFile(configPath);\n\n log.debug({ path: configPath }, 'loaded env file from CONFIG_PATH');\n\n return;\n }\n\n if (fs.existsSync('.env')) {\n process.loadEnvFile('.env');\n log.debug({ path: '.env' }, 'loaded env file');\n\n return;\n }\n\n log.debug('no env file loaded');\n}\n","import { type LoggerOptionsFactory, constructRootLogger } from '../observability/log/construct.js';\nimport { type TelemetrySdkOptions, startTelemetry } from '../observability/telemetry/sdk.js';\nimport { loadEnvFiles } from './env.js';\n\nconst INSTRUMENTATION_KEY = Symbol.for('@astroscope/node/instrumentation');\n\nexport interface InstrumentationContext {\n dev: boolean;\n}\n\ninterface InstrumentationSeam {\n register?: ((ctx: InstrumentationContext) => void | Promise<void>) | undefined;\n}\n\ninterface LogSeam {\n default?: LoggerOptionsFactory | undefined;\n}\n\nexport interface PlatformSeams {\n /** `src/config.ts` — validation runs at import; a throw fails the startup */\n config?: (() => Promise<unknown>) | undefined;\n /** `src/instrumentation.ts` — extra instrumentation, once per process */\n instrumentation?: (() => Promise<InstrumentationSeam>) | undefined;\n /** `src/log.ts` — pino logger options (or a factory), never an instance */\n log?: (() => Promise<LogSeam>) | undefined;\n}\n\nexport interface PreparePlatformOptions {\n dev: boolean;\n telemetry: TelemetrySdkOptions | false;\n seams: PlatformSeams;\n}\n\n/**\n * The platform sequence in front of the boot lifecycle:\n * env → config → instrumentation (platform SDK + `register`, once per\n * process) → logger construction (after instrumentation, so entries carry\n * trace correlation). Prod runs it once in `startServer()`; dev re-runs it\n * per generation with the once-per-process parts guarded.\n */\nexport async function preparePlatform(options: PreparePlatformOptions): Promise<void> {\n loadEnvFiles();\n\n await options.seams.config?.();\n\n const g = globalThis as Record<symbol, unknown>;\n\n if (!g[INSTRUMENTATION_KEY]) {\n g[INSTRUMENTATION_KEY] = true;\n\n if (options.telemetry) {\n await startTelemetry(options.telemetry);\n }\n\n const instrumentation = await options.seams.instrumentation?.();\n\n await instrumentation?.register?.({ dev: options.dev });\n }\n\n const logSeam = await options.seams.log?.();\n\n await constructRootLogger(logSeam?.default, { dev: options.dev });\n}\n"],"mappings":";;;;;;;;AAQA,eAAsB,WAAW,MAAkB,SAAqC;CACtF,MAAM,KAAK,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CAE/B,IAAI,YAAY;EACd,QAAQ,YAAY,UAAU;EAE9B,IAAI,MAAM,EAAE,MAAM,WAAW,GAAG,kCAAkC;EAElE;CACF;CAEA,IAAI,GAAG,WAAW,MAAM,GAAG;EACzB,QAAQ,YAAY,MAAM;EAC1B,IAAI,MAAM,EAAE,MAAM,OAAO,GAAG,iBAAiB;EAE7C;CACF;CAEA,IAAI,MAAM,oBAAoB;AAChC;;;ACtBA,MAAM,sBAAsB,OAAO,IAAI,kCAAkC;;;;;;;;AAoCzE,eAAsB,gBAAgB,SAAgD;CACpF,aAAa;CAEb,MAAM,QAAQ,MAAM,SAAS;CAE7B,MAAM,IAAI;CAEV,IAAI,CAAC,EAAE,sBAAsB;EAC3B,EAAE,uBAAuB;EAEzB,IAAI,QAAQ,WACV,MAAM,eAAe,QAAQ,SAAS;EAKxC,OAAM,MAFwB,QAAQ,MAAM,kBAAkB,EAAA,EAEvC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC;CACxD;CAIA,MAAM,qBAAoB,MAFJ,QAAQ,MAAM,MAAM,EAAA,EAEP,SAAS,EAAE,KAAK,QAAQ,IAAI,CAAC;AAClE"}
package/dist/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as setBootContext } from "./context-Bkg-FnnQ.js";
2
- import { a as runShutdown, i as createRequestInstrumentation, n as shutdownTelemetry, o as runStartup, r as dumpEarlyLogs, t as preparePlatform } from "./prepare-Be2GgRyf.js";
2
+ import { a as runShutdown, i as createRequestInstrumentation, n as shutdownTelemetry, o as runStartup, r as dumpEarlyLogs, t as preparePlatform } from "./prepare-DQEf2Bnt.js";
3
3
  import { n as getRequestRecord } from "./store-BIUF4lqk.js";
4
4
  import { n as log } from "./log-CSJlKaxY.js";
5
5
  import { n as dispatchNativeMount, t as clearNativeMounts } from "./native-mount-hhwWdLtL.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astroscope/node",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Opinionated, cloud-friendly Node adapter for Astro: boot lifecycle, health probes, request logging, telemetry, CSRF and static serving run as plain code around server.listen()",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"file":"prepare-Be2GgRyf.js","names":["LIB_NAME"],"sources":["../src/lifecycle/lifecycle.ts","../src/observability/telemetry/metrics.ts","../src/observability/instrument.ts","../src/observability/log/construct.ts","../src/observability/telemetry/sdk.ts","../src/platform/env.ts","../src/platform/prepare.ts"],"sourcesContent":["import { emit } from './events.js';\nimport type { BootContext } from './types.js';\n\nexport interface BootModule {\n onStartup?: ((context: BootContext) => Promise<void> | void) | undefined;\n onShutdown?: ((context: BootContext) => Promise<void> | void) | undefined;\n}\n\nexport async function runStartup(boot: BootModule, context: BootContext): Promise<void> {\n await emit('beforeOnStartup', context);\n await boot.onStartup?.(context);\n await emit('afterOnStartup', context);\n}\n\nexport async function runShutdown(boot: BootModule, context: BootContext): Promise<void> {\n try {\n await emit('beforeOnShutdown', context);\n await boot.onShutdown?.(context);\n } finally {\n await emit('afterOnShutdown', context);\n }\n}\n","import { type Histogram, type UpDownCounter, ValueType, metrics } from '@opentelemetry/api';\n\nconst LIB_NAME = '@astroscope/node';\n\n// lazy initialization so instruments bind to the SDK meter provider\nlet httpRequestDuration: Histogram | null = null;\nlet httpActiveRequests: UpDownCounter | null = null;\nlet actionDuration: Histogram | null = null;\n\nfunction getHttpRequestDuration(): Histogram {\n return (httpRequestDuration ??= metrics.getMeter(LIB_NAME).createHistogram('http.server.request.duration', {\n description: 'Duration of HTTP server requests',\n unit: 's',\n valueType: ValueType.DOUBLE,\n }));\n}\n\nfunction getHttpActiveRequests(): UpDownCounter {\n return (httpActiveRequests ??= metrics.getMeter(LIB_NAME).createUpDownCounter('http.server.active_requests', {\n description: 'Number of active HTTP server requests',\n unit: '{request}',\n valueType: ValueType.INT,\n }));\n}\n\nfunction getActionDuration(): Histogram {\n return (actionDuration ??= metrics.getMeter(LIB_NAME).createHistogram('astro.action.duration', {\n description: 'Duration of Astro action executions',\n unit: 's',\n valueType: ValueType.DOUBLE,\n }));\n}\n\n/**\n * Record the start of an HTTP request. Returns a function to call when the\n * request ends. Route is unknown at the native-handler level, so active\n * requests carry only the method.\n */\nexport function recordHttpRequestStart(method: string): () => void {\n getHttpActiveRequests().add(1, { 'http.request.method': method });\n\n return () => {\n getHttpActiveRequests().add(-1, { 'http.request.method': method });\n };\n}\n\nexport function recordHttpRequestDuration(\n attributes: { method: string; route: string | undefined; status: number },\n durationMs: number,\n): void {\n getHttpRequestDuration().record(durationMs / 1000, {\n 'http.request.method': attributes.method,\n 'http.route': attributes.route ?? '',\n 'http.response.status_code': attributes.status,\n });\n}\n\nexport function recordActionDuration(attributes: { name: string; status: number }, durationMs: number): void {\n getActionDuration().record(durationMs / 1000, {\n 'astro.action.name': attributes.name,\n 'http.response.status_code': attributes.status,\n });\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { createMatcher } from '@entwico/dash/match';\nimport { SpanKind, SpanStatusCode, context, propagation, trace } from '@opentelemetry/api';\nimport type { Logger } from 'pino';\nimport type { ExcludePattern } from '../excludes/excludes.js';\nimport { generateReqId } from './log/index.js';\nimport { type RequestRecord, getLogStore } from './log/store.js';\nimport { recordActionDuration, recordHttpRequestDuration, recordHttpRequestStart } from './telemetry/metrics.js';\n\nconst LIB_NAME = '@astroscope/node';\nconst ACTIONS_PREFIX = '/_actions/';\nconst REQUEST_ID_PATTERN = /^[\\w.-]{1,64}$/;\n\nconst roundTime = (n: number) => Math.round(n * 100) / 100;\n\nexport interface RequestLoggingConfig {\n exclude: ExcludePattern[];\n extended: boolean;\n}\n\nexport interface RequestTelemetryConfig {\n exclude: ExcludePattern[];\n}\n\nexport interface RequestInstrumentationConfig {\n logging: RequestLoggingConfig | false;\n telemetry: RequestTelemetryConfig | false;\n}\n\nfunction getClientIp(req: IncomingMessage): string | undefined {\n const forwarded = req.headers['x-forwarded-for'];\n const first = Array.isArray(forwarded) ? forwarded[0] : forwarded;\n\n return (\n first?.split(',')[0]?.trim() ??\n (req.headers['x-real-ip'] as string | undefined) ??\n (req.headers['cf-connecting-ip'] as string | undefined)\n );\n}\n\nfunction resolveReqId(req: IncomingMessage): string {\n const incoming = req.headers['x-request-id'];\n const value = Array.isArray(incoming) ? incoming[0] : incoming;\n\n return value && REQUEST_ID_PATTERN.test(value) ? value : generateReqId();\n}\n\nfunction chunkSize(chunk: unknown): number {\n if (chunk == null) return 0;\n if (ArrayBuffer.isView(chunk)) return chunk.byteLength;\n if (typeof chunk === 'string') return Buffer.byteLength(chunk);\n\n return 0;\n}\n\n/**\n * Wraps the native request/response with logging and telemetry: a request\n * logger in async context (real status, response size, aborted-vs-completed\n * on `finish`/`close`), a SERVER span with propagation extraction, and\n * request metrics. Both concerns honor their own exclude patterns; when both\n * are excluded the request passes through untouched.\n */\nexport function createRequestInstrumentation(config: RequestInstrumentationConfig) {\n const tracer = trace.getTracer(LIB_NAME);\n const store = getLogStore();\n const loggingExcluded = config.logging ? createMatcher(config.logging.exclude) : () => true;\n const telemetryExcluded = config.telemetry ? createMatcher(config.telemetry.exclude) : () => true;\n\n return (req: IncomingMessage, res: ServerResponse, inner: () => void): void => {\n const url = req.url ?? '';\n const queryIndex = url.indexOf('?');\n const pathname = queryIndex === -1 ? url : url.slice(0, queryIndex);\n const method = req.method ?? 'GET';\n\n const logging = config.logging && !loggingExcluded(pathname) ? config.logging : false;\n const telemetry = config.telemetry && !telemetryExcluded(pathname) ? config.telemetry : false;\n\n if (!logging && !telemetry) {\n inner();\n\n return;\n }\n\n const startTime = performance.now();\n const isAction = pathname.startsWith(ACTIONS_PREFIX);\n\n let requestLogger: Logger | undefined;\n\n if (logging && store.root) {\n const reqId = resolveReqId(req);\n const reqData: Record<string, unknown> = { method, url: pathname };\n\n // extended logging includes potentially sensitive data\n if (logging.extended) {\n reqData['query'] = queryIndex === -1 ? '' : url.slice(queryIndex + 1);\n reqData['headers'] = req.headers;\n reqData['remoteAddress'] = getClientIp(req) ?? req.socket.remoteAddress;\n }\n\n requestLogger = store.root.child({ reqId, req: reqData });\n\n res.setHeader('x-request-id', reqId);\n }\n\n const record: RequestRecord = {\n logger: requestLogger,\n url,\n route: undefined,\n actionName: isAction ? pathname.slice(ACTIONS_PREFIX.length).replace(/\\/$/, '') : undefined,\n };\n\n let span: ReturnType<typeof tracer.startSpan> | undefined;\n let endActiveRequest: (() => void) | undefined;\n\n if (telemetry) {\n const parentContext = propagation.extract(context.active(), req.headers);\n const contentLength = req.headers['content-length'];\n const clientIp = getClientIp(req);\n const host = req.headers['host'];\n\n span = tracer.startSpan(\n isAction ? `ACTION ${record.actionName}` : method,\n {\n kind: SpanKind.SERVER,\n attributes: {\n 'http.request.method': method,\n 'url.path': pathname,\n 'url.query': queryIndex === -1 ? '' : url.slice(queryIndex + 1),\n 'url.scheme': 'http',\n 'user_agent.original': req.headers['user-agent'] ?? '',\n ...(host && { 'server.address': host }),\n ...(contentLength && { 'http.request.body.size': parseInt(contentLength) }),\n ...(clientIp && { 'client.address': clientIp }),\n },\n },\n parentContext,\n );\n\n endActiveRequest = recordHttpRequestStart(method);\n }\n\n let responseSize = 0;\n let firstByteTime: number | undefined;\n\n const originalWrite = res.write.bind(res);\n const originalEnd = res.end.bind(res);\n\n res.write = ((chunk: unknown, ...rest: unknown[]) => {\n firstByteTime ??= performance.now();\n responseSize += chunkSize(chunk);\n\n return (originalWrite as (...args: unknown[]) => boolean)(chunk, ...rest);\n }) as typeof res.write;\n\n res.end = ((chunk: unknown, ...rest: unknown[]) => {\n firstByteTime ??= performance.now();\n responseSize += chunkSize(chunk);\n\n return (originalEnd as (...args: unknown[]) => ServerResponse)(chunk, ...rest);\n }) as typeof res.end;\n\n let finalized = false;\n\n const finalize = (aborted: boolean): void => {\n if (finalized) return;\n\n finalized = true;\n\n const status = res.statusCode;\n const responseTime = performance.now() - startTime;\n\n if (requestLogger) {\n const level = status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info';\n\n requestLogger[level](\n {\n res: { statusCode: status },\n responseTime: roundTime(responseTime),\n ttfb: roundTime((firstByteTime ?? performance.now()) - startTime),\n responseSize,\n ...(record.route && { route: record.route }),\n ...(aborted && { aborted: true }),\n },\n aborted ? 'request aborted' : 'request completed',\n );\n }\n\n if (span) {\n span.setAttribute('http.response.status_code', status);\n span.setAttribute('http.response.body.size', responseSize);\n\n if (aborted || status >= 400) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: aborted ? 'request aborted' : `HTTP ${status}` });\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n\n span.end();\n }\n\n if (telemetry) {\n endActiveRequest?.();\n recordHttpRequestDuration({ method, route: record.route, status }, responseTime);\n\n if (record.actionName) {\n recordActionDuration({ name: record.actionName, status }, responseTime);\n }\n }\n };\n\n res.once('finish', () => finalize(false));\n res.once('close', () => finalize(!res.writableFinished));\n\n const run = (): void => store.requestStorage.run(record, inner);\n\n if (span) {\n context.with(trace.setSpan(context.active(), span), run);\n } else {\n run();\n }\n };\n}\n","import { isSpanContextValid, trace } from '@opentelemetry/api';\nimport pino, { type Bindings, type Logger, type LoggerOptions } from 'pino';\nimport { getLogStore } from './store.js';\n\n/**\n * Contract of the `src/log.ts` entry seam: pino logger options, or a factory\n * producing them. Never a logger instance — the platform constructs the\n * logger itself (after instrumentation, so trace correlation works).\n */\nexport type LoggerOptionsFactory = LoggerOptions | ((ctx: { dev: boolean }) => LoggerOptions | Promise<LoggerOptions>);\n\n/**\n * Compose the user mixin (if any) with platform trace correlation: when a\n * span is active, every entry carries `trace_id` / `span_id` / `trace_flags`.\n */\nfunction composeMixin(userMixin: LoggerOptions['mixin']): NonNullable<LoggerOptions['mixin']> {\n return (mergeObject, level, logger) => {\n const user = userMixin ? userMixin(mergeObject, level, logger) : {};\n const spanContext = trace.getActiveSpan()?.spanContext();\n\n if (!spanContext || !isSpanContextValid(spanContext)) return user;\n\n return {\n ...user,\n trace_id: spanContext.traceId,\n span_id: spanContext.spanId,\n trace_flags: `0${spanContext.traceFlags.toString(16)}`,\n };\n };\n}\n\n/**\n * Construct the root logger from the app's options seam and replay any logs\n * buffered before construction (original timestamps kept as `bufferedTime`).\n * In dev this runs once per generation; the buffer only exists the first time.\n */\nexport async function constructRootLogger(\n factory: LoggerOptionsFactory | undefined,\n ctx: { dev: boolean },\n): Promise<Logger> {\n const store = getLogStore();\n const options = (typeof factory === 'function' ? await factory(ctx) : factory) ?? {};\n const root = pino({ level: 'info', ...options, mixin: composeMixin(options.mixin) });\n\n store.root = root;\n\n for (const entry of store.buffer.splice(0)) {\n const bindings = entry.bindings.length ? (Object.assign({}, ...entry.bindings) as Bindings) : {};\n const target = root.child({ ...bindings, bufferedTime: new Date(entry.time).toISOString() });\n\n (target[entry.level] as (...args: unknown[]) => void)(...entry.args);\n }\n\n if (store.dropped > 0) {\n root.warn({ dropped: store.dropped }, 'early log buffer overflowed, entries dropped');\n store.dropped = 0;\n }\n\n return root;\n}\n\n/**\n * Failure path for startups that die before the logger exists: dump the\n * buffered entries to the console so no phase is silent.\n */\nexport function dumpEarlyLogs(): void {\n const store = getLogStore();\n\n if (store.root) return;\n\n for (const entry of store.buffer.splice(0)) {\n const bindings = entry.bindings.length ? Object.assign({}, ...entry.bindings) : undefined;\n\n console.error(\n new Date(entry.time).toISOString(),\n entry.level.toUpperCase(),\n ...(bindings ? [bindings] : []),\n ...entry.args,\n );\n }\n\n if (store.dropped > 0) {\n console.error(`(${store.dropped} early log entries dropped)`);\n store.dropped = 0;\n }\n}\n","import { log } from '../log/index.js';\n\n/**\n * Platform-owned telemetry bundle: NodeSDK with undici (fetch) and node\n * runtime instrumentation, host metrics, and a Prometheus reader. Trace\n * exporters are driven by standard `OTEL_*` env vars; without any of them\n * traces stay off (no failing localhost OTLP exports).\n *\n * Guarded per process (dev restarts are in-process; a re-created NodeSDK\n * would double-register instrumentations and leak the Prometheus port).\n */\n\nconst TELEMETRY_KEY = Symbol.for('@astroscope/node/telemetry');\n\ninterface TelemetryHandle {\n shutdown: () => Promise<void>;\n}\n\nexport interface TelemetrySdkOptions {\n prometheus: { host?: string | undefined; port?: number | undefined } | false;\n}\n\nfunction getHandle(): TelemetryHandle | undefined {\n return (globalThis as Record<symbol, unknown>)[TELEMETRY_KEY] as TelemetryHandle | undefined;\n}\n\nfunction defaultEnv(key: string, value: string): void {\n if (!process.env[key]) process.env[key] = value;\n}\n\nexport async function startTelemetry(options: TelemetrySdkOptions): Promise<void> {\n const g = globalThis as Record<symbol, unknown>;\n\n if (g[TELEMETRY_KEY]) return;\n\n if (process.env['OTEL_SDK_DISABLED'] === 'true') {\n log.debug('telemetry disabled via OTEL_SDK_DISABLED');\n\n return;\n }\n\n // without an explicitly configured exporter target, exporting traces to the\n // default localhost OTLP endpoint would fail on every flush\n if (!process.env['OTEL_EXPORTER_OTLP_ENDPOINT'] && !process.env['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT']) {\n defaultEnv('OTEL_TRACES_EXPORTER', 'none');\n }\n\n defaultEnv('OTEL_METRICS_EXPORTER', 'none');\n defaultEnv('OTEL_LOGS_EXPORTER', 'none');\n\n const [\n { NodeSDK },\n { UndiciInstrumentation },\n { RuntimeNodeInstrumentation },\n { PrometheusExporter },\n { HostMetrics },\n ] = await Promise.all([\n import('@opentelemetry/sdk-node'),\n import('@opentelemetry/instrumentation-undici'),\n import('@opentelemetry/instrumentation-runtime-node'),\n import('@opentelemetry/exporter-prometheus'),\n import('@opentelemetry/host-metrics'),\n ]);\n\n const prometheus = options.prometheus\n ? {\n host: process.env['OTEL_EXPORTER_PROMETHEUS_HOST'] ?? options.prometheus.host ?? '0.0.0.0',\n port: process.env['OTEL_EXPORTER_PROMETHEUS_PORT']\n ? Number(process.env['OTEL_EXPORTER_PROMETHEUS_PORT'])\n : (options.prometheus.port ?? 9464),\n }\n : false;\n\n const sdk = new NodeSDK({\n instrumentations: [new UndiciInstrumentation(), new RuntimeNodeInstrumentation()],\n ...(prometheus && { metricReaders: [new PrometheusExporter(prometheus)] }),\n });\n\n sdk.start();\n\n const hostMetrics = new HostMetrics();\n\n hostMetrics.start();\n\n g[TELEMETRY_KEY] = {\n shutdown: () => sdk.shutdown(),\n } satisfies TelemetryHandle;\n\n if (prometheus) {\n log.debug({ host: prometheus.host, port: prometheus.port }, 'prometheus metrics listening');\n }\n}\n\n/**\n * Flush and shut the SDK down. Prod-only (dev keeps the SDK for the process\n * lifetime across generations).\n */\nexport async function shutdownTelemetry(): Promise<void> {\n const handle = getHandle();\n\n if (!handle) return;\n\n delete (globalThis as Record<symbol, unknown>)[TELEMETRY_KEY];\n\n await handle.shutdown();\n}\n","import fs from 'node:fs';\nimport { log } from '../observability/log/index.js';\n\n/**\n * Platform env loading (position −1, before the config seam):\n * `CONFIG_PATH` → `./.env` → none. Existing process env vars win\n */\nexport function loadEnvFiles(): void {\n const configPath = process.env['CONFIG_PATH'];\n\n if (configPath) {\n process.loadEnvFile(configPath);\n\n log.debug({ path: configPath }, 'loaded env file from CONFIG_PATH');\n\n return;\n }\n\n if (fs.existsSync('.env')) {\n process.loadEnvFile('.env');\n log.debug({ path: '.env' }, 'loaded env file');\n\n return;\n }\n\n log.debug('no env file loaded');\n}\n","import { type LoggerOptionsFactory, constructRootLogger } from '../observability/log/construct.js';\nimport { type TelemetrySdkOptions, startTelemetry } from '../observability/telemetry/sdk.js';\nimport { loadEnvFiles } from './env.js';\n\nconst INSTRUMENTATION_KEY = Symbol.for('@astroscope/node/instrumentation');\n\nexport interface InstrumentationContext {\n dev: boolean;\n}\n\ninterface InstrumentationSeam {\n register?: ((ctx: InstrumentationContext) => void | Promise<void>) | undefined;\n}\n\ninterface LogSeam {\n default?: LoggerOptionsFactory | undefined;\n}\n\nexport interface PlatformSeams {\n /** `src/config.ts` — validation runs at import; a throw fails the startup */\n config?: (() => Promise<unknown>) | undefined;\n /** `src/instrumentation.ts` — extra instrumentation, once per process */\n instrumentation?: (() => Promise<InstrumentationSeam>) | undefined;\n /** `src/log.ts` — pino logger options (or a factory), never an instance */\n log?: (() => Promise<LogSeam>) | undefined;\n}\n\nexport interface PreparePlatformOptions {\n dev: boolean;\n telemetry: TelemetrySdkOptions | false;\n seams: PlatformSeams;\n}\n\n/**\n * The platform sequence in front of the boot lifecycle:\n * env → config → instrumentation (platform SDK + `register`, once per\n * process) → logger construction (after instrumentation, so entries carry\n * trace correlation). Prod runs it once in `startServer()`; dev re-runs it\n * per generation with the once-per-process parts guarded.\n */\nexport async function preparePlatform(options: PreparePlatformOptions): Promise<void> {\n loadEnvFiles();\n\n await options.seams.config?.();\n\n const g = globalThis as Record<symbol, unknown>;\n\n if (!g[INSTRUMENTATION_KEY]) {\n g[INSTRUMENTATION_KEY] = true;\n\n if (options.telemetry) {\n await startTelemetry(options.telemetry);\n }\n\n const instrumentation = await options.seams.instrumentation?.();\n\n await instrumentation?.register?.({ dev: options.dev });\n }\n\n const logSeam = await options.seams.log?.();\n\n await constructRootLogger(logSeam?.default, { dev: options.dev });\n}\n"],"mappings":";;;;;;;;AAQA,eAAsB,WAAW,MAAkB,SAAqC;CACtF,MAAM,KAAK,mBAAmB,OAAO;CACrC,MAAM,KAAK,YAAY,OAAO;CAC9B,MAAM,KAAK,kBAAkB,OAAO;AACtC;AAEA,eAAsB,YAAY,MAAkB,SAAqC;CACvF,IAAI;EACF,MAAM,KAAK,oBAAoB,OAAO;EACtC,MAAM,KAAK,aAAa,OAAO;CACjC,UAAU;EACR,MAAM,KAAK,mBAAmB,OAAO;CACvC;AACF;;;ACnBA,MAAMA,aAAW;AAGjB,IAAI,sBAAwC;AAC5C,IAAI,qBAA2C;AAC/C,IAAI,iBAAmC;AAEvC,SAAS,yBAAoC;CAC3C,OAAQ,wBAAwB,QAAQ,SAASA,UAAQ,CAAC,CAAC,gBAAgB,gCAAgC;EACzG,aAAa;EACb,MAAM;EACN,WAAW,UAAU;CACvB,CAAC;AACH;AAEA,SAAS,wBAAuC;CAC9C,OAAQ,uBAAuB,QAAQ,SAASA,UAAQ,CAAC,CAAC,o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