@luckystack/devkit 0.2.0 → 0.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.
@@ -9,6 +9,8 @@ import { watch } from "chokidar";
9
9
  import { parse as parseDotenv } from "dotenv";
10
10
  var RESTART_DEBOUNCE_MS = 150;
11
11
  var CRASH_RESTART_DELAY_MS = 300;
12
+ var FAST_CRASH_THRESHOLD_MS = 3e3;
13
+ var MAX_CONSECUTIVE_FAST_CRASHES = 4;
12
14
  var SHUTDOWN_GRACE_MS = Number(process.env.LUCKYSTACK_SUPERVISOR_GRACE_MS) || 1500;
13
15
  var DEFAULT_ENV_FILES = [".env", ".env.local"];
14
16
  var getEnvFiles = () => {
@@ -48,6 +50,7 @@ var pendingRestart = false;
48
50
  var restartTimer = null;
49
51
  var crashRestartTimer = null;
50
52
  var childBootStartedAt = 0;
53
+ var consecutiveFastCrashes = 0;
51
54
  var isShuttingDown = false;
52
55
  var startChild = () => {
53
56
  if (isShuttingDown) return;
@@ -90,6 +93,7 @@ var startChild = () => {
90
93
  }
91
94
  if (shouldRestart) {
92
95
  pendingRestart = false;
96
+ consecutiveFastCrashes = 0;
93
97
  console.log(`[Supervisor] Restarting server after ${String(uptimeMs)}ms uptime`);
94
98
  startChild();
95
99
  return;
@@ -98,6 +102,17 @@ var startChild = () => {
98
102
  return;
99
103
  }
100
104
  if (typeof code === "number" && code !== 0) {
105
+ if (uptimeMs < FAST_CRASH_THRESHOLD_MS) {
106
+ consecutiveFastCrashes += 1;
107
+ } else {
108
+ consecutiveFastCrashes = 0;
109
+ }
110
+ if (consecutiveFastCrashes >= MAX_CONSECUTIVE_FAST_CRASHES) {
111
+ console.log(
112
+ `[Supervisor] Server crashed ${String(consecutiveFastCrashes)} times within ${String(FAST_CRASH_THRESHOLD_MS / 1e3)}s of starting \u2014 giving up. Fix the startup error above (e.g. a port already in use), then re-run \`npm run server\`.`
113
+ );
114
+ process.exit(1);
115
+ }
101
116
  console.log(`[Supervisor] Server crashed with code ${String(code)}. Restarting in ${String(CRASH_RESTART_DELAY_MS)}ms`);
102
117
  crashRestartTimer = setTimeout(() => {
103
118
  crashRestartTimer = null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/supervisor.ts"],"sourcesContent":["#!/usr/bin/env node\n//? CRITICAL INVARIANT: this process must NEVER merge `.env` files into its own\n//? `process.env`. The child is spawned with `{ ...process.env }`, and the\n//? child's own `loadEnvFiles()` loads `.env` with `override: false` — any\n//? `.env`-derived value that leaks into the supervisor's env would therefore\n//? WIN over freshly edited file values on every restart (stale-env bug).\n//? That is why this file imports NOTHING from `@luckystack/core` (core runs\n//? `bootstrapEnv()` as an import side-effect) and reads env files via\n//? `dotenv.parse` (pure — no `process.env` mutation). The previous design\n//? (an `ambientEnvSnapshot` module imported first) broke as soon as tsup\n//? inlined the snapshot into the entry body: ESM imports are hoisted, so\n//? core's side-effect ran BEFORE the snapshot line.\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { performance } from 'node:perf_hooks';\nimport path from 'node:path';\nimport { watch } from 'chokidar';\nimport { parse as parseDotenv } from 'dotenv';\n\nconst RESTART_DEBOUNCE_MS = 150;\nconst CRASH_RESTART_DELAY_MS = 300;\n//? Force-exit grace: how long we wait for the child to honour SIGTERM before\n//? the supervisor hard-exits. Windows does not deliver SIGKILL so the only\n//? lever is this timer. 1 500 ms is intentionally short (dev restarts should\n//? be fast); increase via LUCKYSTACK_SUPERVISOR_GRACE_MS for slow servers.\nconst SHUTDOWN_GRACE_MS = Number(process.env.LUCKYSTACK_SUPERVISOR_GRACE_MS) || 1500;\n\n//? Mirrors `getEnvFiles()` from @luckystack/core — duplicated on purpose so the\n//? supervisor never imports core (see the invariant above). Keep in sync.\nconst DEFAULT_ENV_FILES = ['.env', '.env.local'];\nconst getEnvFiles = (): string[] => {\n const override = process.env.LUCKYSTACK_ENV_FILES;\n if (override) {\n const list = override.split(',').map((entry) => entry.trim()).filter(Boolean);\n if (list.length > 0) return list;\n }\n return DEFAULT_ENV_FILES;\n};\n\n//? Resolve NODE_ENV without mutating `process.env`: a real ambient env var\n//? wins; otherwise read the env files via the pure `dotenv.parse` (\"later\n//? overrides earlier\", matching loadEnvFiles' file order).\nconst resolveNodeEnv = (): string => {\n if (process.env.NODE_ENV) return process.env.NODE_ENV;\n let fromFiles: string | undefined;\n for (const file of getEnvFiles()) {\n const filePath = path.resolve(process.cwd(), file);\n if (!existsSync(filePath)) continue;\n const parsed = parseDotenv(readFileSync(filePath, 'utf8'));\n if (typeof parsed.NODE_ENV === 'string' && parsed.NODE_ENV.length > 0) fromFiles = parsed.NODE_ENV;\n }\n return fromFiles ?? 'development';\n};\n\nconst CORE_WATCH_GLOBS = [\n 'config.ts',\n ...getEnvFiles(),\n 'server/server.ts',\n 'server/bootstrap/**/*.ts',\n 'server/auth/**/*.ts',\n 'server/functions/db.ts',\n 'server/functions/redis.ts',\n 'server/functions/sentry.ts',\n];\n\nconst tsxCliPath = path.resolve(process.cwd(), 'node_modules', 'tsx', 'dist', 'cli.mjs');\n//? Scaffolded projects carry a dedicated server tsconfig — pass it when present\n//? so the child matches a manual `tsx --tsconfig tsconfig.server.json` run.\nconst tsconfigServerArgs = existsSync(path.resolve(process.cwd(), 'tsconfig.server.json'))\n ? ['--tsconfig', 'tsconfig.server.json']\n : [];\nconst childArgs = [tsxCliPath, ...tsconfigServerArgs, 'server/server.ts'];\n\nlet childProcess: ChildProcess | null = null;\nlet pendingRestart = false;\nlet restartTimer: NodeJS.Timeout | null = null;\nlet crashRestartTimer: NodeJS.Timeout | null = null;\nlet childBootStartedAt = 0;\nlet isShuttingDown = false;\n\nconst startChild = () => {\n if (isShuttingDown) return;\n childBootStartedAt = performance.now();\n const spawned = spawn(process.execPath, childArgs, {\n stdio: 'inherit',\n //? `process.env` is guaranteed `.env`-free here (see the invariant at the\n //? top of this file), so the child loads `.env` fresh on every restart and\n //? picks up edited values — mirroring a cold `npm run server` boot.\n env: {\n ...process.env,\n LUCKYSTACK_CORE_SUPERVISED: 'true',\n },\n });\n childProcess = spawned;\n\n console.log(`[Supervisor] Started server process (pid: ${String(spawned.pid)})`);\n\n //? `'error'` and `'exit'` can BOTH fire for a single spawn (a failed spawn\n //? emits `'error'`, and some platforms then emit `'exit'` too). This flag\n //? resolves THIS child's lifecycle exactly once regardless of event order, so\n //? we never double-schedule a restart.\n let handled = false;\n\n //? A failed `spawn` (ENOENT/EACCES — e.g. a missing `tsx`) emits `'error'`,\n //? NOT `'exit'`. Without this listener Node re-throws it as an uncaught\n //? exception that kills the SUPERVISOR instead of retrying — the dev wrapper\n //? would just disappear. Route it through the same crash-restart delay.\n spawned.on('error', (err) => {\n console.log(`[Supervisor] Failed to spawn server process: ${String(err)}`, 'red');\n if (handled) return;\n handled = true;\n childProcess = null;\n\n if (isShuttingDown) {\n process.exit(1);\n }\n\n console.log(`[Supervisor] Retrying server spawn in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n });\n\n spawned.on('exit', (code, signal) => {\n const uptimeMs = Math.round(performance.now() - childBootStartedAt);\n const shouldRestart = pendingRestart;\n\n if (handled) return;\n handled = true;\n childProcess = null;\n\n //? Once the user has asked us to stop, never spawn another child — no matter\n //? what the previous one's exit reason was. Without this guard a crash that\n //? races with Ctrl+C re-spawns indefinitely.\n if (isShuttingDown) {\n process.exit(0);\n }\n\n if (shouldRestart) {\n pendingRestart = false;\n console.log(`[Supervisor] Restarting server after ${String(uptimeMs)}ms uptime`);\n startChild();\n return;\n }\n\n if (signal === 'SIGTERM' || signal === 'SIGINT') {\n return;\n }\n\n if (typeof code === 'number' && code !== 0) {\n console.log(`[Supervisor] Server crashed with code ${String(code)}. Restarting in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n }\n });\n};\n\nconst scheduleRestart = ({\n event,\n changedPath,\n}: {\n event: string;\n changedPath: string;\n}) => {\n if (restartTimer) {\n clearTimeout(restartTimer);\n }\n\n restartTimer = setTimeout(() => {\n restartTimer = null;\n pendingRestart = true;\n\n console.log(`[Supervisor] Core change detected (${event}): ${changedPath}. Restarting server`);\n\n if (!childProcess) {\n pendingRestart = false;\n startChild();\n return;\n }\n\n childProcess.kill('SIGTERM');\n }, RESTART_DEBOUNCE_MS);\n};\n\nconst shutdownSupervisor = () => {\n isShuttingDown = true;\n\n if (restartTimer) {\n clearTimeout(restartTimer);\n restartTimer = null;\n }\n if (crashRestartTimer) {\n clearTimeout(crashRestartTimer);\n crashRestartTimer = null;\n }\n\n pendingRestart = false;\n\n if (childProcess) {\n //? Child is still alive — its 'exit' handler will see isShuttingDown\n //? and call process.exit(0) once the child is gone. Force-exit after a\n //? short grace period in case the child ignores SIGTERM (Windows).\n childProcess.kill('SIGTERM');\n setTimeout(() => process.exit(0), SHUTDOWN_GRACE_MS).unref();\n } else {\n //? No child running (e.g. we were between crashes, sitting in the\n //? crash-restart setTimeout we just cleared above) — exit immediately.\n process.exit(0);\n }\n};\n\nif (resolveNodeEnv() === 'production') {\n //? In production the supervisor has no file watcher, but it still needs to\n //? forward shutdown signals so the child gets a chance to drain (e.g. flush\n //? error trackers, close DB connections). Without these handlers a SIGTERM\n //? from a process manager (systemd, Docker) kills the supervisor instantly\n //? and the child may never exit cleanly.\n process.on('SIGINT', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n process.on('SIGTERM', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n startChild();\n} else {\n const watcher = watch(CORE_WATCH_GLOBS, {\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 120,\n pollInterval: 20,\n },\n });\n\n watcher.on('all', (event, changedPath) => {\n scheduleRestart({ event, changedPath });\n });\n\n const handleSignal = (signalName: string) => {\n //? Set the flag synchronously so any in-flight child 'exit' handler\n //? running BEFORE watcher.close() resolves won't schedule a new spawn.\n if (isShuttingDown) {\n //? Second Ctrl+C — user is impatient. Hard-exit immediately.\n process.exit(1);\n }\n isShuttingDown = true;\n console.log(`[Supervisor] Received ${signalName}, shutting down`);\n void watcher.close().then(() => {\n shutdownSupervisor();\n }).catch(() => {\n shutdownSupervisor();\n });\n };\n\n process.on('SIGINT', () => { handleSignal('SIGINT'); });\n process.on('SIGTERM', () => { handleSignal('SIGTERM'); });\n\n startChild();\n}\n"],"mappings":";;;AAYA,SAAS,aAAgC;AACzC,SAAS,YAAY,oBAAoB;AACzC,SAAS,mBAAmB;AAC5B,OAAO,UAAU;AACjB,SAAS,aAAa;AACtB,SAAS,SAAS,mBAAmB;AAErC,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAK/B,IAAM,oBAAoB,OAAO,QAAQ,IAAI,8BAA8B,KAAK;AAIhF,IAAM,oBAAoB,CAAC,QAAQ,YAAY;AAC/C,IAAM,cAAc,MAAgB;AAClC,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI,UAAU;AACZ,UAAM,OAAO,SAAS,MAAM,GAAG,EAAE,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO;AAC5E,QAAI,KAAK,SAAS,EAAG,QAAO;AAAA,EAC9B;AACA,SAAO;AACT;AAKA,IAAM,iBAAiB,MAAc;AACnC,MAAI,QAAQ,IAAI,SAAU,QAAO,QAAQ,IAAI;AAC7C,MAAI;AACJ,aAAW,QAAQ,YAAY,GAAG;AAChC,UAAM,WAAW,KAAK,QAAQ,QAAQ,IAAI,GAAG,IAAI;AACjD,QAAI,CAAC,WAAW,QAAQ,EAAG;AAC3B,UAAM,SAAS,YAAY,aAAa,UAAU,MAAM,CAAC;AACzD,QAAI,OAAO,OAAO,aAAa,YAAY,OAAO,SAAS,SAAS,EAAG,aAAY,OAAO;AAAA,EAC5F;AACA,SAAO,aAAa;AACtB;AAEA,IAAM,mBAAmB;AAAA,EAC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A,EAChB;AACF;AAEA,IAAI,eAAe,MAAM,cAAc;AAMrC,UAAQ,GAAG,UAAU,MAAM;AACzB,qBAAiB;AACjB,uBAAmB;AAAA,EACrB,CAAC;AACD,UAAQ,GAAG,WAAW,MAAM;AAC1B,qBAAiB;AACjB,uBAAmB;AAAA,EACrB,CAAC;AACD,aAAW;AACb,OAAO;AACL,QAAM,UAAU,MAAM,kBAAkB;AAAA,IACtC,eAAe;AAAA,IACf,kBAAkB;AAAA,MAChB,oBAAoB;AAAA,MACpB,cAAc;AAAA,IAChB;AAAA,EACF,CAAC;AAED,UAAQ,GAAG,OAAO,CAAC,OAAO,gBAAgB;AACxC,oBAAgB,EAAE,OAAO,YAAY,CAAC;AAAA,EACxC,CAAC;AAED,QAAM,eAAe,CAAC,eAAuB;AAG3C,QAAI,gBAAgB;AAElB,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,qBAAiB;AACjB,YAAQ,IAAI,yBAAyB,UAAU,iBAAiB;AAChE,SAAK,QAAQ,MAAM,EAAE,KAAK,MAAM;AAC9B,yBAAmB;AAAA,IACrB,CAAC,EAAE,MAAM,MAAM;AACb,yBAAmB;AAAA,IACrB,CAAC;AAAA,EACH;AAEA,UAAQ,GAAG,UAAU,MAAM;AAAE,iBAAa,QAAQ;AAAA,EAAG,CAAC;AACtD,UAAQ,GAAG,WAAW,MAAM;AAAE,iBAAa,SAAS;AAAA,EAAG,CAAC;AAExD,aAAW;AACb;","names":[]}
1
+ {"version":3,"sources":["../src/supervisor.ts"],"sourcesContent":["#!/usr/bin/env node\n//? CRITICAL INVARIANT: this process must NEVER merge `.env` files into its own\n//? `process.env`. The child is spawned with `{ ...process.env }`, and the\n//? child's own `loadEnvFiles()` loads `.env` with `override: false` — any\n//? `.env`-derived value that leaks into the supervisor's env would therefore\n//? WIN over freshly edited file values on every restart (stale-env bug).\n//? That is why this file imports NOTHING from `@luckystack/core` (core runs\n//? `bootstrapEnv()` as an import side-effect) and reads env files via\n//? `dotenv.parse` (pure — no `process.env` mutation). The previous design\n//? (an `ambientEnvSnapshot` module imported first) broke as soon as tsup\n//? inlined the snapshot into the entry body: ESM imports are hoisted, so\n//? core's side-effect ran BEFORE the snapshot line.\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { performance } from 'node:perf_hooks';\nimport path from 'node:path';\nimport { watch } from 'chokidar';\nimport { parse as parseDotenv } from 'dotenv';\n\nconst RESTART_DEBOUNCE_MS = 150;\nconst CRASH_RESTART_DELAY_MS = 300;\n//? Rapid-crash-loop breaker. A child that exits non-zero within\n//? FAST_CRASH_THRESHOLD_MS of booting counts as a \"fast crash\" (it died during\n//? startup rather than after serving). MAX_CONSECUTIVE_FAST_CRASHES of those in\n//? a row means the startup error is not transient (a port already in use, a\n//? syntax error, a missing env) — restarting forever just spams the console, so\n//? we give up and print an actionable message. A child that survives longer than\n//? the threshold resets the counter, so a normal restart loop is unaffected.\nconst FAST_CRASH_THRESHOLD_MS = 3000;\nconst MAX_CONSECUTIVE_FAST_CRASHES = 4;\n//? Force-exit grace: how long we wait for the child to honour SIGTERM before\n//? the supervisor hard-exits. Windows does not deliver SIGKILL so the only\n//? lever is this timer. 1 500 ms is intentionally short (dev restarts should\n//? be fast); increase via LUCKYSTACK_SUPERVISOR_GRACE_MS for slow servers.\nconst SHUTDOWN_GRACE_MS = Number(process.env.LUCKYSTACK_SUPERVISOR_GRACE_MS) || 1500;\n\n//? Mirrors `getEnvFiles()` from @luckystack/core — duplicated on purpose so the\n//? supervisor never imports core (see the invariant above). Keep in sync.\nconst DEFAULT_ENV_FILES = ['.env', '.env.local'];\nconst getEnvFiles = (): string[] => {\n const override = process.env.LUCKYSTACK_ENV_FILES;\n if (override) {\n const list = override.split(',').map((entry) => entry.trim()).filter(Boolean);\n if (list.length > 0) return list;\n }\n return DEFAULT_ENV_FILES;\n};\n\n//? Resolve NODE_ENV without mutating `process.env`: a real ambient env var\n//? wins; otherwise read the env files via the pure `dotenv.parse` (\"later\n//? overrides earlier\", matching loadEnvFiles' file order).\nconst resolveNodeEnv = (): string => {\n if (process.env.NODE_ENV) return process.env.NODE_ENV;\n let fromFiles: string | undefined;\n for (const file of getEnvFiles()) {\n const filePath = path.resolve(process.cwd(), file);\n if (!existsSync(filePath)) continue;\n const parsed = parseDotenv(readFileSync(filePath, 'utf8'));\n if (typeof parsed.NODE_ENV === 'string' && parsed.NODE_ENV.length > 0) fromFiles = parsed.NODE_ENV;\n }\n return fromFiles ?? 'development';\n};\n\nconst CORE_WATCH_GLOBS = [\n 'config.ts',\n ...getEnvFiles(),\n 'server/server.ts',\n 'server/bootstrap/**/*.ts',\n 'server/auth/**/*.ts',\n 'server/functions/db.ts',\n 'server/functions/redis.ts',\n 'server/functions/sentry.ts',\n];\n\nconst tsxCliPath = path.resolve(process.cwd(), 'node_modules', 'tsx', 'dist', 'cli.mjs');\n//? Scaffolded projects carry a dedicated server tsconfig — pass it when present\n//? so the child matches a manual `tsx --tsconfig tsconfig.server.json` run.\nconst tsconfigServerArgs = existsSync(path.resolve(process.cwd(), 'tsconfig.server.json'))\n ? ['--tsconfig', 'tsconfig.server.json']\n : [];\nconst childArgs = [tsxCliPath, ...tsconfigServerArgs, 'server/server.ts'];\n\nlet childProcess: ChildProcess | null = null;\nlet pendingRestart = false;\nlet restartTimer: NodeJS.Timeout | null = null;\nlet crashRestartTimer: NodeJS.Timeout | null = null;\nlet childBootStartedAt = 0;\nlet consecutiveFastCrashes = 0;\nlet isShuttingDown = false;\n\nconst startChild = () => {\n if (isShuttingDown) return;\n childBootStartedAt = performance.now();\n const spawned = spawn(process.execPath, childArgs, {\n stdio: 'inherit',\n //? `process.env` is guaranteed `.env`-free here (see the invariant at the\n //? top of this file), so the child loads `.env` fresh on every restart and\n //? picks up edited values — mirroring a cold `npm run server` boot.\n env: {\n ...process.env,\n LUCKYSTACK_CORE_SUPERVISED: 'true',\n },\n });\n childProcess = spawned;\n\n console.log(`[Supervisor] Started server process (pid: ${String(spawned.pid)})`);\n\n //? `'error'` and `'exit'` can BOTH fire for a single spawn (a failed spawn\n //? emits `'error'`, and some platforms then emit `'exit'` too). This flag\n //? resolves THIS child's lifecycle exactly once regardless of event order, so\n //? we never double-schedule a restart.\n let handled = false;\n\n //? A failed `spawn` (ENOENT/EACCES — e.g. a missing `tsx`) emits `'error'`,\n //? NOT `'exit'`. Without this listener Node re-throws it as an uncaught\n //? exception that kills the SUPERVISOR instead of retrying — the dev wrapper\n //? would just disappear. Route it through the same crash-restart delay.\n spawned.on('error', (err) => {\n console.log(`[Supervisor] Failed to spawn server process: ${String(err)}`, 'red');\n if (handled) return;\n handled = true;\n childProcess = null;\n\n if (isShuttingDown) {\n process.exit(1);\n }\n\n console.log(`[Supervisor] Retrying server spawn in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n });\n\n spawned.on('exit', (code, signal) => {\n const uptimeMs = Math.round(performance.now() - childBootStartedAt);\n const shouldRestart = pendingRestart;\n\n if (handled) return;\n handled = true;\n childProcess = null;\n\n //? Once the user has asked us to stop, never spawn another child — no matter\n //? what the previous one's exit reason was. Without this guard a crash that\n //? races with Ctrl+C re-spawns indefinitely.\n if (isShuttingDown) {\n process.exit(0);\n }\n\n if (shouldRestart) {\n pendingRestart = false;\n //? A watcher-driven restart is an explicit edit to a watched file — give\n //? the new code a clean slate instead of inheriting a previous crash burst.\n consecutiveFastCrashes = 0;\n console.log(`[Supervisor] Restarting server after ${String(uptimeMs)}ms uptime`);\n startChild();\n return;\n }\n\n if (signal === 'SIGTERM' || signal === 'SIGINT') {\n return;\n }\n\n if (typeof code === 'number' && code !== 0) {\n //? Rapid-crash-loop breaker: a child that died within the boot window\n //? counts toward the consecutive-fast-crash tally; one that lived longer\n //? proves the startup error cleared, so reset the tally.\n if (uptimeMs < FAST_CRASH_THRESHOLD_MS) {\n consecutiveFastCrashes += 1;\n } else {\n consecutiveFastCrashes = 0;\n }\n\n if (consecutiveFastCrashes >= MAX_CONSECUTIVE_FAST_CRASHES) {\n console.log(\n `[Supervisor] Server crashed ${String(consecutiveFastCrashes)} times within ` +\n `${String(FAST_CRASH_THRESHOLD_MS / 1000)}s of starting — giving up. Fix the startup ` +\n `error above (e.g. a port already in use), then re-run \\`npm run server\\`.`,\n );\n process.exit(1);\n }\n\n console.log(`[Supervisor] Server crashed with code ${String(code)}. Restarting in ${String(CRASH_RESTART_DELAY_MS)}ms`);\n crashRestartTimer = setTimeout(() => {\n crashRestartTimer = null;\n startChild();\n }, CRASH_RESTART_DELAY_MS);\n }\n });\n};\n\nconst scheduleRestart = ({\n event,\n changedPath,\n}: {\n event: string;\n changedPath: string;\n}) => {\n if (restartTimer) {\n clearTimeout(restartTimer);\n }\n\n restartTimer = setTimeout(() => {\n restartTimer = null;\n pendingRestart = true;\n\n console.log(`[Supervisor] Core change detected (${event}): ${changedPath}. Restarting server`);\n\n if (!childProcess) {\n pendingRestart = false;\n startChild();\n return;\n }\n\n childProcess.kill('SIGTERM');\n }, RESTART_DEBOUNCE_MS);\n};\n\nconst shutdownSupervisor = () => {\n isShuttingDown = true;\n\n if (restartTimer) {\n clearTimeout(restartTimer);\n restartTimer = null;\n }\n if (crashRestartTimer) {\n clearTimeout(crashRestartTimer);\n crashRestartTimer = null;\n }\n\n pendingRestart = false;\n\n if (childProcess) {\n //? Child is still alive — its 'exit' handler will see isShuttingDown\n //? and call process.exit(0) once the child is gone. Force-exit after a\n //? short grace period in case the child ignores SIGTERM (Windows).\n childProcess.kill('SIGTERM');\n setTimeout(() => process.exit(0), SHUTDOWN_GRACE_MS).unref();\n } else {\n //? No child running (e.g. we were between crashes, sitting in the\n //? crash-restart setTimeout we just cleared above) — exit immediately.\n process.exit(0);\n }\n};\n\nif (resolveNodeEnv() === 'production') {\n //? In production the supervisor has no file watcher, but it still needs to\n //? forward shutdown signals so the child gets a chance to drain (e.g. flush\n //? error trackers, close DB connections). Without these handlers a SIGTERM\n //? from a process manager (systemd, Docker) kills the supervisor instantly\n //? and the child may never exit cleanly.\n process.on('SIGINT', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n process.on('SIGTERM', () => {\n isShuttingDown = true;\n shutdownSupervisor();\n });\n startChild();\n} else {\n const watcher = watch(CORE_WATCH_GLOBS, {\n ignoreInitial: true,\n awaitWriteFinish: {\n stabilityThreshold: 120,\n pollInterval: 20,\n },\n });\n\n watcher.on('all', (event, changedPath) => {\n scheduleRestart({ event, changedPath });\n });\n\n const handleSignal = (signalName: string) => {\n //? Set the flag synchronously so any in-flight child 'exit' handler\n //? running BEFORE watcher.close() resolves won't schedule a new spawn.\n if (isShuttingDown) {\n //? Second Ctrl+C — user is impatient. Hard-exit immediately.\n process.exit(1);\n }\n isShuttingDown = true;\n console.log(`[Supervisor] Received ${signalName}, shutting down`);\n void watcher.close().then(() => {\n shutdownSupervisor();\n }).catch(() => {\n shutdownSupervisor();\n });\n };\n\n process.on('SIGINT', () => { handleSignal('SIGINT'); });\n process.on('SIGTERM', () => { handleSignal('SIGTERM'); });\n\n startChild();\n}\n"],"mappings":";;;AAYA,SAAS,aAAgC;AACzC,SAAS,YAAY,oBAAoB;AACzC,SAAS,mBAAmB;AAC5B,OAAO,UAAU;AACjB,SAAS,aAAa;AACtB,SAAS,SAAS,mBAAmB;AAErC,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAQ/B,IAAM,0BAA0B;AAChC,IAAM,+BAA+B;AAKrC,IAAM,oBAAoB,OAAO,QAAQ,IAAI,8BAA8B,KAAK;AAIhF,IAAM,oBAAoB,CAAC,QAAQ,YAAY;AAC/C,IAAM,cAAc,MAAgB;AAClC,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI,UAAU;AACZ,UAAM,OAAO,SAAS,MAAM,GAAG,EAAE,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,OAAO;AAC5E,QAAI,KAAK,SAAS,EAAG,QAAO;AAAA,EAC9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AQ,KAAK,CAAC;AAAA,IAChB;AACA,qBAAiB;AACjB,YAAQ,IAAI,yBAAyB,UAAU,iBAAiB;AAChE,SAAK,QAAQ,MAAM,EAAE,KAAK,MAAM;AAC9B,yBAAmB;AAAA,IACrB,CAAC,EAAE,MAAM,MAAM;AACb,yBAAmB;AAAA,IACrB,CAAC;AAAA,EACH;AAEA,UAAQ,GAAG,UAAU,MAAM;AAAE,iBAAa,QAAQ;AAAA,EAAG,CAAC;AACtD,UAAQ,GAAG,WAAW,MAAM;AAAE,iBAAa,SAAS;AAAA,EAAG,CAAC;AAExD,aAAW;AACb;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luckystack/devkit",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public",
@@ -56,7 +56,7 @@
56
56
  "test": "vitest run"
57
57
  },
58
58
  "dependencies": {
59
- "@luckystack/core": "^0.2.0",
59
+ "@luckystack/core": "^0.2.1",
60
60
  "chokidar": "^5.0.0",
61
61
  "dotenv": "^16.6.1"
62
62
  },