theokit 0.76.2 → 0.77.0
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 +59 -0
- package/dist/{actions-virtual-module-52O6HJZT.js → actions-virtual-module-UIX5YWZR.js} +4 -4
- package/dist/{actions-virtual-module-HS4W7HQU.js → actions-virtual-module-V5Q4XVL5.js} +2 -2
- package/dist/add-DOR7HORT.js +23 -0
- package/dist/{agent-HCK5RHH7.js → agent-MJWQRSJ2.js} +2 -2
- package/dist/{app-typed-client-CJCOALMM.js → app-typed-client-6FQB5FQO.js} +4 -4
- package/dist/{app-typed-client-BWITJLJA.js → app-typed-client-JCBQGPMP.js} +2 -2
- package/dist/{build-Y3CWTWP6.js → build-QDZEOCJ3.js} +4 -4
- package/dist/{chunk-W2I6L4IJ.js → chunk-35OI2TKT.js} +2 -2
- package/dist/{chunk-OIYSUQM7.js → chunk-3TCWOHLY.js} +4 -2
- package/dist/{chunk-OIYSUQM7.js.map → chunk-3TCWOHLY.js.map} +1 -1
- package/dist/{chunk-UQQQ3V43.js → chunk-3XR6CBUA.js} +65 -5
- package/dist/chunk-3XR6CBUA.js.map +1 -0
- package/dist/{chunk-BTDTHXUI.js → chunk-BFDEEJOK.js} +1 -1
- package/dist/{chunk-BTDTHXUI.js.map → chunk-BFDEEJOK.js.map} +1 -1
- package/dist/{chunk-XI4FALFZ.js → chunk-E22GPCCO.js} +24 -1
- package/dist/chunk-E22GPCCO.js.map +1 -0
- package/dist/{chunk-OED37LE5.js → chunk-GNV34JMI.js} +37 -3
- package/dist/chunk-GNV34JMI.js.map +1 -0
- package/dist/{chunk-2SGNODVJ.js → chunk-HNALEGOL.js} +40 -10
- package/dist/chunk-HNALEGOL.js.map +1 -0
- package/dist/{chunk-ZQJORKBM.js → chunk-HZAXFD55.js} +49 -2
- package/dist/chunk-HZAXFD55.js.map +1 -0
- package/dist/{add-3VLFUPF4.js → chunk-JVXDEIT4.js} +15 -12
- package/dist/chunk-JVXDEIT4.js.map +1 -0
- package/dist/{chunk-PVCXREGE.js → chunk-KQBY62AE.js} +2 -2
- package/dist/{chunk-BXQCJJPT.js → chunk-N5YHENWJ.js} +2 -2
- package/dist/{chunk-FEK25JUL.js → chunk-OKFRGAYZ.js} +67 -9
- package/dist/chunk-OKFRGAYZ.js.map +1 -0
- package/dist/{chunk-XDLFOATW.js → chunk-OSSNCUS6.js} +4 -4
- package/dist/{chunk-C2BRSL4W.js → chunk-PQWVT6JC.js} +11 -1
- package/dist/{chunk-C2BRSL4W.js.map → chunk-PQWVT6JC.js.map} +1 -1
- package/dist/{chunk-47FFT43U.js → chunk-YH5CDWLU.js} +25 -1
- package/dist/chunk-YH5CDWLU.js.map +1 -0
- package/dist/cli/index.js +12 -12
- package/dist/{db-ZWDKD57T.js → db-5WOK6HA2.js} +3 -3
- package/dist/{define-middleware-BOHpPOBs.d.ts → define-middleware-D7LFaTv-.d.ts} +27 -2
- package/dist/{dev-R2ZYHZV4.js → dev-N5LQFLBR.js} +9 -7
- package/dist/dev-N5LQFLBR.js.map +1 -0
- package/dist/{generate-ORWEIXCL.js → generate-OA5ARO3P.js} +120 -52
- package/dist/generate-OA5ARO3P.js.map +1 -0
- package/dist/{index-DfsJ3Qhk.d.ts → index-C2lcEI-4.d.ts} +2 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +5 -4
- package/dist/index.js.map +1 -1
- package/dist/{info-IPMW56PI.js → info-ELSPSCXK.js} +3 -3
- package/dist/{internal-api-6RAOYIET.js → internal-api-5FTPYSEQ.js} +2 -2
- package/dist/{internal-api-YGFPLQ4E.js → internal-api-H3C2ID6N.js} +4 -4
- package/dist/{job-backend-WvUs5rO1.d.ts → job-backend-BX-PwnZW.d.ts} +25 -0
- package/dist/{load-config-USRR4GXP.js → load-config-SKLFH7YL.js} +3 -3
- package/dist/{mcp-FBXEX45H.js → mcp-3ENI2IPS.js} +3 -3
- package/dist/{openapi-CA3E3LZH.js → openapi-OVXYHZ2S.js} +3 -3
- package/dist/{preview-DLIVPM7A.js → preview-GP6J6IGJ.js} +3 -3
- package/dist/{routes-BJ7GGRCV.js → routes-UNJ77IQU.js} +3 -3
- package/dist/{schema-FBM2UH72.js → schema-2EAIJFWA.js} +2 -2
- package/dist/server/define/index.d.ts +5 -4
- package/dist/server/define/index.js +1 -1
- package/dist/server/http/index.d.ts +4 -3
- package/dist/server/http/index.js +3 -3
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +7 -5
- package/dist/server/index.js.map +1 -1
- package/dist/server/jobs/index.d.ts +75 -6
- package/dist/server/jobs/index.js +4 -2
- package/dist/{server-boundary-EKIGYL7B.js → server-boundary-5ZTBC2KF.js} +2 -2
- package/dist/{server-boundary-IDWIB24L.js → server-boundary-DTF6ZEUO.js} +4 -4
- package/dist/{start-LNT5UVSY.js → start-EJFYT7ZU.js} +13 -37
- package/dist/start-EJFYT7ZU.js.map +1 -0
- package/dist/vite-plugin/index.js +5 -4
- package/dist/{vite-plugin-LE42ZIGV.js → vite-plugin-MNZHNOM4.js} +6 -6
- package/dist/vite-plugin-MNZHNOM4.js.map +1 -0
- package/package.json +1 -1
- package/dist/add-3VLFUPF4.js.map +0 -1
- package/dist/chunk-2SGNODVJ.js.map +0 -1
- package/dist/chunk-47FFT43U.js.map +0 -1
- package/dist/chunk-FEK25JUL.js.map +0 -1
- package/dist/chunk-OED37LE5.js.map +0 -1
- package/dist/chunk-UQQQ3V43.js.map +0 -1
- package/dist/chunk-XI4FALFZ.js.map +0 -1
- package/dist/chunk-ZQJORKBM.js.map +0 -1
- package/dist/dev-R2ZYHZV4.js.map +0 -1
- package/dist/generate-ORWEIXCL.js.map +0 -1
- package/dist/start-LNT5UVSY.js.map +0 -1
- /package/dist/{actions-virtual-module-52O6HJZT.js.map → actions-virtual-module-UIX5YWZR.js.map} +0 -0
- /package/dist/{actions-virtual-module-HS4W7HQU.js.map → actions-virtual-module-V5Q4XVL5.js.map} +0 -0
- /package/dist/{agent-HCK5RHH7.js.map → add-DOR7HORT.js.map} +0 -0
- /package/dist/{internal-api-6RAOYIET.js.map → agent-MJWQRSJ2.js.map} +0 -0
- /package/dist/{app-typed-client-CJCOALMM.js.map → app-typed-client-6FQB5FQO.js.map} +0 -0
- /package/dist/{app-typed-client-BWITJLJA.js.map → app-typed-client-JCBQGPMP.js.map} +0 -0
- /package/dist/{build-Y3CWTWP6.js.map → build-QDZEOCJ3.js.map} +0 -0
- /package/dist/{chunk-W2I6L4IJ.js.map → chunk-35OI2TKT.js.map} +0 -0
- /package/dist/{chunk-PVCXREGE.js.map → chunk-KQBY62AE.js.map} +0 -0
- /package/dist/{chunk-BXQCJJPT.js.map → chunk-N5YHENWJ.js.map} +0 -0
- /package/dist/{chunk-XDLFOATW.js.map → chunk-OSSNCUS6.js.map} +0 -0
- /package/dist/{db-ZWDKD57T.js.map → db-5WOK6HA2.js.map} +0 -0
- /package/dist/{info-IPMW56PI.js.map → info-ELSPSCXK.js.map} +0 -0
- /package/dist/{load-config-USRR4GXP.js.map → internal-api-5FTPYSEQ.js.map} +0 -0
- /package/dist/{internal-api-YGFPLQ4E.js.map → internal-api-H3C2ID6N.js.map} +0 -0
- /package/dist/{schema-FBM2UH72.js.map → load-config-SKLFH7YL.js.map} +0 -0
- /package/dist/{mcp-FBXEX45H.js.map → mcp-3ENI2IPS.js.map} +0 -0
- /package/dist/{openapi-CA3E3LZH.js.map → openapi-OVXYHZ2S.js.map} +0 -0
- /package/dist/{preview-DLIVPM7A.js.map → preview-GP6J6IGJ.js.map} +0 -0
- /package/dist/{routes-BJ7GGRCV.js.map → routes-UNJ77IQU.js.map} +0 -0
- /package/dist/{vite-plugin-LE42ZIGV.js.map → schema-2EAIJFWA.js.map} +0 -0
- /package/dist/{server-boundary-EKIGYL7B.js.map → server-boundary-5ZTBC2KF.js.map} +0 -0
- /package/dist/{server-boundary-IDWIB24L.js.map → server-boundary-DTF6ZEUO.js.map} +0 -0
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import "tsx/esm";
|
|
3
3
|
import {
|
|
4
4
|
jobBackendFromConfig
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-HZAXFD55.js";
|
|
6
6
|
import {
|
|
7
7
|
extractTraceContext,
|
|
8
8
|
generateNewTraceContext
|
|
@@ -153,7 +153,7 @@ async function configureStorageManagerFromConfig(storageConfig) {
|
|
|
153
153
|
if (storageConfig === void 0 || storageConfig === null) return;
|
|
154
154
|
try {
|
|
155
155
|
const { getStorageManager } = await import("./storage-manager-3IUIEG2P.js");
|
|
156
|
-
const { storageSchema } = await import("./schema-
|
|
156
|
+
const { storageSchema } = await import("./schema-2EAIJFWA.js");
|
|
157
157
|
const parsed = storageSchema.parse(storageConfig);
|
|
158
158
|
getStorageManager().configure(parsed);
|
|
159
159
|
} catch (err) {
|
|
@@ -425,6 +425,39 @@ function isJobDefinition(value) {
|
|
|
425
425
|
const candidate = value;
|
|
426
426
|
return typeof candidate.name === "string" && typeof candidate.handler === "function" && typeof candidate.maxAttempts === "number";
|
|
427
427
|
}
|
|
428
|
+
var JobBackendSetupError = class extends Error {
|
|
429
|
+
code = "JOB_BACKEND_SETUP_FAILED";
|
|
430
|
+
backend;
|
|
431
|
+
constructor(backend, cause) {
|
|
432
|
+
const reason = describeCause(cause);
|
|
433
|
+
super(
|
|
434
|
+
`jobs.backend (${backend}) could not create its storage at boot: ${reason}. Jobs enqueued now would be lost, so the server did not start. Check that the database in theo.config.ts is reachable and that its user may create tables.`,
|
|
435
|
+
{ cause }
|
|
436
|
+
);
|
|
437
|
+
this.name = "JobBackendSetupError";
|
|
438
|
+
this.backend = backend;
|
|
439
|
+
}
|
|
440
|
+
};
|
|
441
|
+
function describeCause(cause) {
|
|
442
|
+
if (cause instanceof AggregateError && cause.message === "") {
|
|
443
|
+
return cause.errors.map(describeCause).join("; ");
|
|
444
|
+
}
|
|
445
|
+
if (cause instanceof Error) {
|
|
446
|
+
const code = cause.code;
|
|
447
|
+
if (cause.message !== "") return cause.message;
|
|
448
|
+
return typeof code === "string" ? code : cause.name;
|
|
449
|
+
}
|
|
450
|
+
return String(cause);
|
|
451
|
+
}
|
|
452
|
+
async function prepareJobBackend(config) {
|
|
453
|
+
const backend = jobBackendFromConfig(config);
|
|
454
|
+
if (backend?.migrate === void 0) return;
|
|
455
|
+
try {
|
|
456
|
+
await backend.migrate();
|
|
457
|
+
} catch (err) {
|
|
458
|
+
throw new JobBackendSetupError(backend.name, err);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
428
461
|
function startJobWorker(config, definitions) {
|
|
429
462
|
if (definitions.length === 0) return { worker: void 0, summary: void 0 };
|
|
430
463
|
const declared = `Jobs: ${String(definitions.length)} declared`;
|
|
@@ -464,6 +497,7 @@ export {
|
|
|
464
497
|
loadCronModules,
|
|
465
498
|
loadJobDefinitions,
|
|
466
499
|
loadJobModules,
|
|
500
|
+
prepareJobBackend,
|
|
467
501
|
startJobWorker
|
|
468
502
|
};
|
|
469
|
-
//# sourceMappingURL=chunk-
|
|
503
|
+
//# sourceMappingURL=chunk-GNV34JMI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server/cache-bootstrap.ts","../src/server/cron/cron-runtime-node.ts","../src/cli/commands/start/bootstrap-stages.ts","../src/cli/commands/start/cron-bootstrap.ts","../src/cli/commands/start/job-bootstrap.ts","../src/server/jobs/job-backend.ts","../src/server/jobs/job-runner.ts","../src/server/jobs/job-worker.ts"],"sourcesContent":["import type { NormalizedCacheConfig } from '../cache/engine-singleton.js'\n\n/**\n * Initialize the singleton cache engine from `theo.config.ts > cache` (#352).\n *\n * Until this existed, `initCacheEngine` had no production caller while\n * `getCacheEngine` had three — so `revalidateTag`, `updateTag` and\n * `revalidatePath`, all exported publicly, threw \"Cache engine not initialized\"\n * in every application. The subsystem was not unreachable code; it was a bridge\n * with one half published and the other half never built.\n *\n * Three states a boot legitimately reaches, each handled by a guard rather than\n * by a `catch`, because `initCacheEngine` throws on all three and absorbing the\n * throws would absorb the real double-init bug with them:\n *\n * - no `cache` key at all — the framework stays backward compatible, no engine\n * - `enabled: false` — an explicit opt-out, not an error\n * - already initialized — HMR, a second server in one process, a test booting\n * twice in one worker\n *\n * Unlike `configureStorageManagerFromConfig`, its sibling in the CLI bootstrap,\n * a malformed config is NOT\n * degraded into a warning here, and the divergence is deliberate. Warning and\n * continuing would boot an application whose `revalidateTag` still throws — the\n * exact defect this function exists to remove, restored silently and now\n * attributable to nothing.\n */\nexport async function initCacheEngineFromConfig(cacheConfig: unknown): Promise<void> {\n if (cacheConfig === undefined || cacheConfig === null) return\n\n const { initCacheEngine, isCacheEngineInitialized } = await import('../cache/engine-singleton.js')\n if (isCacheEngineInitialized()) return\n\n const { cacheSchema } = await import('../config/schemas/index.js')\n const parsed = cacheSchema.parse(cacheConfig)\n if (!parsed.enabled) return\n\n initCacheEngine({\n enabled: parsed.enabled,\n // The schema accepts `'memory'` or a caller-supplied adapter instance, which\n // it cannot type beyond `unknown` without importing the adapter contract\n // into the config layer.\n storage: parsed.storage as NormalizedCacheConfig['storage'],\n maxEntries: parsed.maxEntries,\n defaults: parsed.defaults,\n })\n}\n","import { CronExpressionParser } from 'cron-parser'\n\nimport { generateNewTraceContext } from '../observability/trace-context-propagation.js'\n\nimport type { CronLock } from './cron-lock.js'\nimport type { CronContext, CronDefinition } from './cron-types.js'\n\n/**\n * In-process cron scheduler, run by `theokit start` (and by `theokit dev --crons`).\n *\n * Algorithm:\n * - For each cron, compute `nextFireAt = cron-parser.next()`.\n * - Schedule a `setTimeout(handler, nextFireAt - now)`.\n * - After handler invocation (sync return or Promise scheduled), recompute\n * next fire from CURRENT time (drift-free vs scheduled time).\n *\n * Per-cron isolation (EC-109):\n * - Each cron's handler invocation is fire-and-forget (`void` scheduled).\n * A hanging handler does NOT block the scheduler loop nor other crons.\n * - `concurrency: 'forbid'` (default) tracks an in-flight flag per-cron;\n * subsequent ticks skip + warn while the in-flight flag is set.\n * - `concurrency: 'allow'` runs handlers concurrently — caller's responsibility.\n *\n * Several processes (replicas) each run this scheduler under `theokit start`. Without a `lock`,\n * each one fires every tick. With one, each tick asks the lock first and only the process that\n * gets `true` runs the handler (usetheokit/theokit#1016). A lock that fails skips the tick and logs\n * the error: running unguarded would repeat the side effect on every replica, which is the defect\n * the lock exists for.\n *\n * Serverless targets use platform-native triggers (T1.5 adapter translators), which fire once.\n */\n\nexport interface CronSchedulerOptions {\n /** Shared lock deciding which process runs each tick. Absent: this process runs every tick. */\n lock?: CronLock\n}\n\nexport interface CronScheduler {\n start(): void\n stop(): void\n}\n\ninterface CronJobState {\n readonly def: CronDefinition\n inFlight: boolean\n timer: NodeJS.Timeout | null\n abortController: AbortController | null\n}\n\nexport function createCronScheduler(\n definitions: readonly CronDefinition[],\n options: CronSchedulerOptions = {},\n): CronScheduler {\n const lock = options.lock\n const states: CronJobState[] = definitions.map((def) => ({\n def,\n inFlight: false,\n timer: null,\n abortController: null,\n }))\n\n let started = false\n\n /** Run the tick if the lock (when there is one) gives it to this process. */\n const fireIfLockAllows = (state: CronJobState, scheduledAt: Date): void => {\n if (lock === undefined) {\n fireAndReschedule(state, scheduledAt)\n return\n }\n state.timer = null\n void lock.acquire(state.def.name, scheduledAt).then(\n (won) => {\n if (won) fireAndReschedule(state, scheduledAt)\n else scheduleNext(state)\n },\n (err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()}: ` +\n 'the cron lock could not be acquired:',\n err instanceof Error ? err.message : err,\n )\n scheduleNext(state)\n },\n )\n }\n\n const fireAndReschedule = (state: CronJobState, scheduledAt: Date): void => {\n state.timer = null\n\n if (state.inFlight && state.def.concurrency === 'forbid') {\n console.warn(\n `[theokit:cron] \"${state.def.name}\" skipped tick at ${scheduledAt.toISOString()} ` +\n '— previous handler still running (concurrency: forbid).',\n )\n scheduleNext(state)\n return\n }\n\n state.inFlight = true\n state.abortController = new AbortController()\n const traceCtx = generateNewTraceContext()\n const ctx: CronContext = {\n traceId: traceCtx.trace_id,\n scheduledAt,\n signal: state.abortController.signal,\n }\n\n // Fire-and-forget: EC-109 — never await here so a hanging handler\n // can't block the scheduler loop or other crons.\n void Promise.resolve()\n .then(() => state.def.handler(ctx))\n .catch((err: unknown) => {\n console.error(\n `[theokit:cron] \"${state.def.name}\" handler error:`,\n err instanceof Error ? err.message : err,\n )\n })\n .finally(() => {\n state.inFlight = false\n })\n\n scheduleNext(state)\n }\n\n const scheduleNext = (state: CronJobState): void => {\n if (!started) return\n const interval = CronExpressionParser.parse(state.def.schedule, {\n tz: 'UTC',\n currentDate: new Date(),\n })\n const next = interval.next().toDate()\n const delayMs = Math.max(0, next.getTime() - Date.now())\n state.timer = setTimeout(() => {\n fireIfLockAllows(state, next)\n }, delayMs)\n // setTimeout returns a Timeout object; in Node, .unref() is available but\n // we DO want this to keep the event loop alive in dev — explicit no-unref.\n }\n\n return {\n start(): void {\n if (started) return\n started = true\n for (const state of states) {\n scheduleNext(state)\n }\n },\n stop(): void {\n started = false\n for (const state of states) {\n if (state.timer) {\n clearTimeout(state.timer)\n state.timer = null\n }\n state.abortController?.abort()\n state.abortController = null\n }\n },\n }\n}\n","/**\n * Bootstrap stages extracted from `start.ts` per T4.2 (architecture-cleanup, ADR-0017).\n *\n * The full goal of T4.2 is a ≤30-LOC `startCommand` spine + 6-8 stage files. This\n * file ships the first batch: the configure-from-config bootstrap helpers + the\n * SSR entry resolver. They are stand-alone, side-effect-free at module load, and\n * already individually testable.\n *\n * Remaining stages (request-handler extraction, graceful-shutdown extraction,\n * signal-handlers extraction) are deferred to a follow-up sprint — see plan\n * ks.\n */\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { warnOnce } from '../../../server/observability/logger.js'\n\ninterface SdkAgentRegistry {\n configure?: (opts: { maxAgents?: number; idleTimeoutMs?: number }) => void\n}\ninterface SdkModule {\n Agent?: { registry?: SdkAgentRegistry }\n}\n\n/**\n * Configure SDK's Agent.registry from `theo.config.ts > agents.registry`.\n * Lazy at boot; EC-3 sync flag flip prevents race under concurrent boot.\n * Silent no-op when registry config is absent or SDK is uninstalled.\n */\nexport async function configureAgentRegistryFromConfig(\n registryConfig: { maxAgents: number; idleTimeoutMs: number } | undefined,\n): Promise<void> {\n if (registryConfig === undefined) return\n try {\n const sdk = (await import('@theokit/sdk').catch(() => null)) as SdkModule | null\n const sdkConfigure = sdk?.Agent?.registry?.configure\n if (sdkConfigure === undefined) return\n const { configureAgentRegistryOnce } =\n await import('../../../server/agent/configure-agent-registry.js')\n configureAgentRegistryOnce(\n {\n configure: (opts) => {\n sdkConfigure(opts)\n },\n },\n registryConfig,\n )\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.agent_registry_skip', {\n event: 'bootstrap.agent_registry_skip',\n message: msg,\n })\n }\n}\n\n/**\n * Configure the StorageManager from `theo.config.ts > storage` (ADR-0007).\n * Manager enforces configure-once internally (D3); this helper bridges the\n * config to the singleton with actionable error handling.\n */\nexport async function configureStorageManagerFromConfig(storageConfig: unknown): Promise<void> {\n if (storageConfig === undefined || storageConfig === null) return\n try {\n const { getStorageManager } = await import('../../../server/storage/storage-manager.js')\n const { storageSchema } = await import('../../../config/schema.js')\n // Re-validate at boot so a malformed config from a non-Zod source\n // (test fixtures, dynamic configs) surfaces a clear error early.\n const parsed = storageSchema.parse(storageConfig)\n getStorageManager().configure(parsed)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('bootstrap.storage_skip', {\n event: 'bootstrap.storage_skip',\n message: msg,\n })\n }\n}\n\nconst SSR_EXTENSIONS = ['.mjs', '.js'] as const\n\n/**\n * Resolve the SSR entry-server module path. tsup may emit `.mjs` or `.js`\n * depending on output format. Try `.mjs` first (modern default) then fall\n * back to `.js`. Returns null when neither exists — SSR stays disabled.\n *\n * Exported so unit tests can pin the resolution order without booting the\n * full CLI.\n */\nexport function resolveSsrEntry(distDir: string): string | null {\n for (const ext of SSR_EXTENSIONS) {\n const path = resolve(distDir, `server/entry-server${ext}`)\n\n if (existsSync(path)) return path\n }\n return null\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { CronManifest } from '../../../server/cron/cron-manifest.js'\nimport type { CronDefinition } from '../../../server/cron/cron-types.js'\n\n/**\n * Reads the cron manifest `theokit build` writes and re-loads each handler so\n * `theokit start` can drive the in-process scheduler.\n *\n * The build prints \"Cron → in-process scheduler (theokit start)\" for\n * `target: node`, but nothing on the serving side ever read `dist/crons.json`\n * — the crons were declared, validated, written, and then never ran\n * (theokit#324).\n *\n * The manifest names WHICH files hold a cron; the definition itself is taken\n * from the module, which is the source `defineCron` produced. Trusting the\n * manifest's copy of the schedule would let a stale build silently run a cron\n * on the wrong cadence.\n */\nexport async function loadCronDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n if (!existsSync(manifestPath)) return []\n\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as CronManifest\n return loadCronModules(\n manifest.crons.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/**\n * Import each file and take its `defineCron` default export, refusing a file without one. Shared\n * with `theokit dev --crons`, which lists the files itself and loads them through Vite.\n */\nexport async function loadCronModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<CronDefinition[]> {\n const definitions: CronDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `\"${filePath}\" is listed as a cron but has no valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`. ' +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(exported)\n }\n return definitions\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.schedule === 'string' &&\n typeof candidate.handler === 'function'\n )\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../../../config/schema.js'\nimport { jobBackendFromConfig } from '../../../server/jobs/job-backend-from-config.js'\nimport type { JobBackend } from '../../../server/jobs/job-backend.js'\nimport type { JobManifest } from '../../../server/jobs/job-manifest.js'\nimport { createJobRunner } from '../../../server/jobs/job-runner.js'\nimport type { JobDefinition } from '../../../server/jobs/job-types.js'\nimport { createJobWorker, type JobWorker } from '../../../server/jobs/job-worker.js'\n\n/**\n * Reads the job manifest `theokit build` writes and re-loads each definition, the jobs twin of\n * `loadCronDefinitions`. The manifest names WHICH files hold a job; the definition comes from the\n * module, so a stale build cannot run a handler the source no longer has.\n *\n * Before usetheokit/theokit#1010 nothing on the serving side read `jobs.json`.\n */\nexport async function loadJobDefinitions(\n manifestPath: string,\n projectRoot: string,\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n if (!existsSync(manifestPath)) return []\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as JobManifest\n return loadJobModules(\n manifest.jobs.map((entry) => resolve(projectRoot, entry.filePath)),\n loadModule,\n )\n}\n\n/** Import each file and take its `defineJob` default export, refusing a file without one. */\nexport async function loadJobModules(\n filePaths: readonly string[],\n loadModule: (filePath: string) => unknown,\n): Promise<JobDefinition[]> {\n const definitions: JobDefinition[] = []\n for (const filePath of filePaths) {\n const mod = (await loadModule(filePath)) as { default?: unknown }\n if (!isJobDefinition(mod.default)) {\n throw new Error(\n `\"${filePath}\" is listed as a job but has no valid default export. ` +\n \"Expected `export default defineJob(name, { handler })` from 'theokit/server/jobs'. \" +\n 'Re-run `theokit build` if the file changed since the last build.',\n )\n }\n definitions.push(mod.default)\n }\n return definitions\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const candidate = value as Record<string, unknown>\n return (\n typeof candidate.name === 'string' &&\n typeof candidate.handler === 'function' &&\n typeof candidate.maxAttempts === 'number'\n )\n}\n\n/**\n * `migrate()` of the configured `jobs.backend` rejected at boot. The process must not serve: every\n * route would answer 2xx while the outbox dropped each job it enqueued (usetheokit/theokit#1072).\n */\nclass JobBackendSetupError extends Error {\n readonly code = 'JOB_BACKEND_SETUP_FAILED'\n readonly backend: string\n constructor(backend: string, cause: unknown) {\n const reason = describeCause(cause)\n super(\n `jobs.backend (${backend}) could not create its storage at boot: ${reason}. ` +\n 'Jobs enqueued now would be lost, so the server did not start. Check that the database ' +\n 'in theo.config.ts is reachable and that its user may create tables.',\n { cause },\n )\n this.name = 'JobBackendSetupError'\n this.backend = backend\n }\n}\n\n/**\n * The text of a setup failure. `pg` connecting to `localhost` tries every address it resolves to\n * and rejects with an `AggregateError` whose own message is empty, which printed \"could not create\n * its storage at boot: .\" on a CI runner. The attempts are listed instead, and an error without a\n * message falls back to its code.\n */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof AggregateError && cause.message === '') {\n return cause.errors.map(describeCause).join('; ')\n }\n if (cause instanceof Error) {\n const code = (cause as { code?: unknown }).code\n if (cause.message !== '') return cause.message\n return typeof code === 'string' ? code : cause.name\n }\n return String(cause)\n}\n\n/**\n * Run `migrate()` on the configured `jobs.backend`, when it has one, before anything can enqueue\n * or dequeue. `theokit start` and `theokit dev` call it at boot whether or not this process runs\n * the worker: a web-only process enqueues into the same table.\n *\n * It used to be the app's job, and nothing told the app: the README configured a\n * `PostgresJobBackend` without the call, and a fresh database answered 2xx while every job was\n * dropped. Calling it from `theo.config.ts` instead made `theokit build` need a database.\n */\nexport async function prepareJobBackend(config: Pick<TheoConfig, 'jobs'>): Promise<void> {\n const backend = jobBackendFromConfig(config)\n if (backend?.migrate === undefined) return\n try {\n await backend.migrate()\n } catch (err) {\n throw new JobBackendSetupError(backend.name, err)\n }\n}\n\nexport interface JobWorkerBootstrap {\n /** The running worker, or `undefined` when none was started (see `summary`). */\n readonly worker: JobWorker | undefined\n /** One line for the boot log saying what happens to the declared jobs, or `undefined` if none. */\n readonly summary: string | undefined\n}\n\n/**\n * Start the in-process job worker when there is something to run and somewhere to run it from.\n *\n * - no declared jobs: no worker. A worker with no definitions would lease other processes' jobs\n * and fail them as \"No job definition\".\n * - jobs but no `jobs.backend`: no worker, and the summary says the jobs cannot run.\n * - `jobs.worker.enabled: false`: no worker, said in the summary, so a web-only process is visibly\n * one.\n */\nexport function startJobWorker(\n config: Pick<TheoConfig, 'jobs'>,\n definitions: readonly JobDefinition[],\n): JobWorkerBootstrap {\n if (definitions.length === 0) return { worker: undefined, summary: undefined }\n const declared = `Jobs: ${String(definitions.length)} declared`\n const backend: JobBackend | undefined = jobBackendFromConfig(config)\n if (backend === undefined) {\n return {\n worker: undefined,\n summary:\n `${declared}, NOT running: theo.config.ts sets no jobs.backend, so ctx.queue is absent ` +\n 'and nothing can enqueue or run them.',\n }\n }\n const options = config.jobs?.worker\n if (options?.enabled === false) {\n return {\n worker: undefined,\n summary: `${declared}, worker disabled (jobs.worker.enabled: false); another process must run them.`,\n }\n }\n const worker = createJobWorker(createJobRunner(backend, definitions), {\n pollIntervalMs: options?.pollIntervalMs,\n batchSize: options?.batchSize,\n lockSeconds: options?.lockSeconds,\n })\n worker.start()\n return {\n worker,\n summary: `${declared}, worker polling the ${backend.name} backend in-process`,\n }\n}\n","/**\n * Neutral `JobBackend` interface.\n *\n * Implementations ship in core:\n * - `InMemoryJobBackend` (T2.2) — dev + tests; no external deps\n * - `PostgresJobBackend` (T3.1) — production; requires `pg` peer dep\n *\n * Community packages (`@theokit/jobs-redis`, `@theokit/jobs-sqs`, etc.)\n * implement this same interface to plug in alternate substrates without\n * modifying TheoKit core.\n */\n\nimport type { PoolLike } from '../storage/storage-types.js'\n\nexport interface JobEnqueueInput {\n /** The job name (matches a `defineJob` declaration). */\n name: string\n /** Validated input (already passed through Zod or equivalent at the queue-client layer). */\n input: unknown\n /**\n * Optional idempotency key, scoped to `name`: a second enqueue of the same (name, key) returns the\n * first job's id instead of creating a job, including when the two calls race. The window is\n * backend-specific: `PostgresJobBackend` holds the key while the row exists (until `ack`, or for\n * good once the job has failed); `InMemoryJobBackend` holds it for 60 seconds.\n */\n idempotencyKey?: string\n /** Optional delay before the job becomes available for dispatch. */\n delaySeconds?: number\n /** W3C Trace Context propagation per ADR/R0.5.9. */\n traceparent?: string\n /**\n * Maximum dispatch attempts stored with the job (default 1). The queue client has no access to\n * the job definitions and leaves it unset; `createJobRunner` passes the definition's\n * `maxAttempts` to `nack`, which takes precedence over this stored value.\n */\n maxAttempts?: number\n}\n\nexport interface JobLease {\n readonly jobId: string\n readonly name: string\n readonly input: unknown\n readonly attempts: number\n readonly maxAttempts: number\n readonly traceparent?: string\n readonly lockExpiresAt: Date\n /**\n * Identifies THIS lease. Pass it back to `ack`/`nack` so a worker whose lease expired, and was\n * handed to another worker, cannot finish the job on the new holder's behalf. Both first-party\n * backends set it; optional so a backend written against the earlier contract still compiles.\n */\n readonly leaseToken?: string\n}\n\n/** What `nack` is told about the failure. */\nexport interface JobNackOptions extends JobLeaseFence {\n /** The failure message. */\n error: string\n /** The handler threw `NonRetryableError`: no retry, whatever the attempts left. */\n nonRetryable?: boolean\n /**\n * The retry ceiling from the job's definition. Takes precedence over the value stored at\n * enqueue, which is 1 for every job enqueued through the queue client.\n */\n maxAttempts?: number\n}\n\n/** Fences `ack`/`nack` to the lease that is finishing the job. */\nexport interface JobLeaseFence {\n /** The `leaseToken` of the `JobLease` being finished. Omitted, the call is not fenced. */\n leaseToken?: string\n}\n\nexport interface JobBackend {\n /** Human-readable name for logging (e.g., \"memory\", \"postgres\"). */\n readonly name: string\n\n /** Persist a job for later dispatch. Returns the generated jobId. */\n enqueue(input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /** Worker loop polls for the next available leases. */\n dequeue(opts: { batchSize?: number; lockSeconds?: number }): Promise<JobLease[]>\n\n /**\n * Mark a job complete (success). With `leaseToken`, rejects with `JobLeaseLostError` and leaves\n * the job alone when that lease no longer holds it.\n */\n ack(jobId: string, fence?: JobLeaseFence): Promise<void>\n\n /**\n * Mark a job failed; backend decides retry vs DLQ via attempts. With `leaseToken`, rejects with\n * `JobLeaseLostError` and leaves the job alone when that lease no longer holds it.\n */\n nack(jobId: string, opts: JobNackOptions): Promise<void>\n\n /**\n * Optional: persist a job through `client`, a connection inside a transaction the caller opened,\n * so the job commits or rolls back with the caller's writes (usetheokit/theokit#1077). Only a\n * backend whose jobs live in the caller's database can offer it; `ctx.queue.enqueueInTransaction`\n * refuses a backend without it rather than enqueueing outside the transaction.\n */\n enqueueInTransaction?(client: PoolLike, input: JobEnqueueInput): Promise<{ jobId: string }>\n\n /**\n * Optional: resolve when the backend's store answers, reject when it does not. `GET /__theo/ready`\n * calls it under `theokit start` and `theokit dev`, so an unreachable job store answers 503\n * (usetheokit/theokit#1071). A backend with nothing remote to reach leaves it out.\n */\n ping?(): Promise<void>\n\n /**\n * Optional: create or upgrade whatever storage the backend needs (a table, an index). Must be\n * idempotent and safe to run from several processes at once. `theokit start` and `theokit dev`\n * call it once at boot, before serving a request or starting the worker, and refuse to boot when\n * it rejects (usetheokit/theokit#1072). A backend that needs no setup leaves it out.\n */\n migrate?(): Promise<void>\n\n /**\n * Optional: return the existing jobId if `key` was enqueued within `ttlSeconds`. Pass `name` to\n * scope the lookup to one job type, as `enqueue` deduplicates on (name, key); without it, a key\n * shared by two job types may return either job.\n */\n idempotency?(key: string, ttlSeconds: number, name?: string): Promise<{ jobId: string } | null>\n}\n\n/**\n * Thrown from a job handler to opt out of retry policy. The runner nacks with\n * `nonRetryable: true` and the backend never retries the job: `PostgresJobBackend`\n * keeps it as failed with the error, `InMemoryJobBackend` drops it with a warning.\n */\nexport class NonRetryableError extends Error {\n readonly code = 'NON_RETRYABLE'\n constructor(message: string) {\n super(message)\n this.name = 'NonRetryableError'\n }\n}\n\n/**\n * `ack`/`nack` was called with a lease token that no longer holds the job: the lease expired and\n * another worker leased the job again (or the job is gone). The job is left untouched, because the\n * current holder owns its outcome. The runner logs it and moves on; a direct caller decides.\n */\nexport class JobLeaseLostError extends Error {\n readonly code = 'JOB_LEASE_LOST'\n readonly jobId: string\n readonly operation: 'ack' | 'nack'\n constructor(jobId: string, operation: 'ack' | 'nack') {\n super(\n `Cannot ${operation} job \"${jobId}\": its lease expired and another worker holds it now, ` +\n 'or the job no longer exists. The current holder decides its outcome.',\n )\n this.name = 'JobLeaseLostError'\n this.jobId = jobId\n this.operation = operation\n }\n}\n","import { createLogger } from '../observability/logger.js'\nimport {\n extractTraceContext,\n generateNewTraceContext,\n} from '../observability/trace-context-propagation.js'\n\nimport {\n type JobBackend,\n type JobLease,\n JobLeaseLostError,\n NonRetryableError,\n} from './job-backend.js'\nimport type { JobContext, JobDefinition } from './job-types.js'\n\n/**\n * Job runner — pulls leases from a backend and invokes the matching\n * handler. Each invocation wires up `JobContext` with:\n * - `traceId` extracted from the lease's `traceparent` header (W3C\n * Trace Context per R0.5.9), OR a fresh generated trace_id when\n * the upstream had no traceparent OR it was malformed.\n * - `attempt` from the lease.\n * - `signal` that aborts when the lease times out.\n *\n * `tick()` runs one dequeue+dispatch cycle and returns when all leases\n * have been ack'd or nack'd. `createJobWorker` (`job-worker.ts`) is the loop\n * around it, with idle polling and error backoff; `theokit start` and\n * `theokit dev` run one.\n *\n * EC-6 (trace continuity edge): when a lease has no traceparent OR a\n * malformed one, the handler still gets a valid traceId (generated) —\n * never null/undefined. The job MAY itself enqueue child jobs that\n * continue the new trace_id.\n */\n\nconst runnerLogger = createLogger({ context: { component: 'theokit:jobs:runner' } })\n\n/**\n * Run an ack or nack, fenced by the lease. A lost lease means another worker owns the job now, so\n * its outcome is not ours to write: log it and move on. Any other failure propagates.\n */\nasync function finish(\n lease: JobLease,\n outcome: 'ack' | 'nack',\n write: () => Promise<void>,\n): Promise<void> {\n try {\n await write()\n } catch (err) {\n if (!(err instanceof JobLeaseLostError)) throw err\n runnerLogger.warn('job lease lost before the outcome was written; the new holder decides it', {\n jobId: lease.jobId,\n job: lease.name,\n attempt: lease.attempts,\n outcome,\n code: err.code,\n })\n }\n}\n\nexport interface JobRunner {\n /** Run one dequeue+dispatch cycle. */\n tick(opts?: { batchSize?: number; lockSeconds?: number }): Promise<number>\n}\n\nexport function createJobRunner(\n backend: JobBackend,\n definitions: readonly JobDefinition[],\n): JobRunner {\n const byName = new Map<string, JobDefinition>()\n for (const def of definitions) {\n byName.set(def.name, def)\n }\n\n const runOne = async (lease: JobLease): Promise<void> => {\n const def = byName.get(lease.name)\n if (!def) {\n // Job name not registered in this runner's definition set. Nack\n // permanently — the lease can't be processed by this runner.\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `No job definition for \"${lease.name}\"`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n\n // Resolve trace ID from lease's traceparent, or fall back to fresh.\n let traceId: string\n if (lease.traceparent) {\n const headers = new Headers({ traceparent: lease.traceparent })\n const ctx = extractTraceContext(headers)\n traceId = ctx?.trace_id ?? generateNewTraceContext().trace_id\n } else {\n traceId = generateNewTraceContext().trace_id\n }\n\n // Optional Zod validation on input.\n let parsedInput: unknown = lease.input\n if (def.inputSchema) {\n try {\n parsedInput = def.inputSchema.parse(lease.input)\n } catch (err) {\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: `Input validation failed: ${err instanceof Error ? err.message : String(err)}`,\n nonRetryable: true,\n leaseToken: lease.leaseToken,\n }),\n )\n return\n }\n }\n\n const abortController = new AbortController()\n // Auto-abort when lease expires\n const lockMs = lease.lockExpiresAt.getTime() - Date.now()\n const lockTimer = setTimeout(\n () => {\n abortController.abort()\n },\n Math.max(0, lockMs),\n )\n\n const jobCtx: JobContext = {\n traceId,\n input: parsedInput,\n signal: abortController.signal,\n attempt: lease.attempts,\n }\n\n let failure: unknown\n let failed = false\n try {\n await def.handler(jobCtx)\n } catch (err) {\n failed = true\n failure = err\n } finally {\n clearTimeout(lockTimer)\n }\n // The outcome is written outside the handler's try, so a failed ack is never mistaken for a\n // failed handler and nacked.\n if (!failed) {\n await finish(lease, 'ack', () => backend.ack(lease.jobId, { leaseToken: lease.leaseToken }))\n return\n }\n await finish(lease, 'nack', () =>\n backend.nack(lease.jobId, {\n error: failure instanceof Error ? failure.message : String(failure),\n nonRetryable: failure instanceof NonRetryableError,\n leaseToken: lease.leaseToken,\n // The definition is the source of truth: a job enqueued through the queue client was stored\n // with the backend default of 1 (usetheokit/theokit#1013).\n maxAttempts: def.maxAttempts,\n }),\n )\n }\n\n return {\n async tick(opts) {\n const leases = await backend.dequeue({\n batchSize: opts?.batchSize ?? 10,\n lockSeconds: opts?.lockSeconds ?? 30,\n })\n // Process leases sequentially — caller controls concurrency via\n // batchSize and tick frequency.\n for (const lease of leases) {\n await runOne(lease)\n }\n return leases.length\n },\n }\n}\n","import { createLogger } from '../observability/logger.js'\n\nimport type { JobRunner } from './job-runner.js'\n\n/**\n * The loop around `JobRunner.tick()`.\n *\n * `tick()` runs one dequeue-and-dispatch cycle and left the loop to its caller, and `theokit start`\n * never wrote one, so jobs were enqueued into a backend nothing drained (usetheokit/theokit#1010).\n * This is that loop, shared by `theokit start`, `theokit dev` and anyone running a worker process\n * of their own:\n *\n * - a tick that leased jobs is followed by another at once, so a backlog drains at full speed;\n * - an empty tick waits `pollIntervalMs` before asking again;\n * - a tick that throws (the database is down) is logged and retried with exponential backoff\n * capped at `maxErrorBackoffMs`, so an outage neither kills the process nor spins;\n * - `stop()` lets the tick in progress finish (its jobs are acked or nacked) and resolves after it.\n * A wait in progress is cut short.\n */\nexport interface JobWorkerOptions {\n /** Wait after a tick that leased nothing. Default 1000 ms. */\n pollIntervalMs?: number\n /** Leases per tick, passed to `tick()`. Default 10. */\n batchSize?: number\n /** Lease duration per job, passed to `tick()`. Default 30 s. */\n lockSeconds?: number\n /** Ceiling of the backoff after consecutive failed ticks. Default 30 000 ms. */\n maxErrorBackoffMs?: number\n}\n\nexport interface JobWorker {\n /** Start polling. A second call is a no-op. */\n start(): void\n /** Stop polling; resolves once the tick in progress, if any, has finished. */\n stop(): Promise<void>\n}\n\nconst workerLogger = createLogger({ context: { component: 'theokit:jobs:worker' } })\n\nexport function createJobWorker(runner: JobRunner, options: JobWorkerOptions = {}): JobWorker {\n const pollIntervalMs = options.pollIntervalMs ?? 1000\n const maxErrorBackoffMs = options.maxErrorBackoffMs ?? 30_000\n const tickOptions = { batchSize: options.batchSize ?? 10, lockSeconds: options.lockSeconds ?? 30 }\n\n let running = false\n let loop: Promise<void> | undefined\n let wake: (() => void) | undefined\n\n const wait = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(done, ms)\n function done(): void {\n clearTimeout(timer)\n wake = undefined\n resolve()\n }\n wake = done\n })\n\n const run = async (): Promise<void> => {\n let failures = 0\n while (running) {\n try {\n const leased = await runner.tick(tickOptions)\n failures = 0\n if (leased > 0) continue\n await wait(pollIntervalMs)\n } catch (err) {\n failures++\n const delayMs = Math.min(pollIntervalMs * 2 ** failures, maxErrorBackoffMs)\n workerLogger.error('job worker tick failed; retrying', {\n error: err instanceof Error ? err.message : String(err),\n consecutiveFailures: failures,\n retryInMs: delayMs,\n })\n await wait(delayMs)\n }\n }\n }\n\n return {\n start() {\n if (running) return\n running = true\n loop = run()\n },\n async stop() {\n running = false\n wake?.()\n await loop\n loop = undefined\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,eAAsB,0BAA0B,aAAqC;AACnF,MAAI,gBAAgB,UAAa,gBAAgB,KAAM;AAEvD,QAAM,EAAE,iBAAiB,yBAAyB,IAAI,MAAM,OAAO,gCAA8B;AACjG,MAAI,yBAAyB,EAAG;AAEhC,QAAM,EAAE,YAAY,IAAI,MAAM,OAAO,uBAA4B;AACjE,QAAM,SAAS,YAAY,MAAM,WAAW;AAC5C,MAAI,CAAC,OAAO,QAAS;AAErB,kBAAgB;AAAA,IACd,SAAS,OAAO;AAAA;AAAA;AAAA;AAAA,IAIhB,SAAS,OAAO;AAAA,IAChB,YAAY,OAAO;AAAA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AAqB,QAAQ,MAAM,GAAG;AAAA,EAClD;AACF;AAkBO,SAAS,eACd,QACA,aACoB;AACpB,MAAI,YAAY,WAAW,EAAG,QAAO,EAAE,QAAQ,QAAW,SAAS,OAAU;AAC7E,QAAM,WAAW,SAAS,OAAO,YAAY,MAAM,CAAC;AACpD,QAAM,UAAkC,qBAAqB,MAAM;AACnE,MAAI,YAAY,QAAW;AACzB,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SACE,GAAG,QAAQ;AAAA,IAEf;AAAA,EACF;AACA,QAAM,UAAU,OAAO,MAAM;AAC7B,MAAI,SAAS,YAAY,OAAO;AAC9B,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,SAAS,GAAG,QAAQ;AAAA,IACtB;AAAA,EACF;AACA,QAAM,SAAS,gBAAgB,gBAAgB,SAAS,WAAW,GAAG;AAAA,IACpE,gBAAgB,SAAS;AAAA,IACzB,WAAW,SAAS;AAAA,IACpB,aAAa,SAAS;AAAA,EACxB,CAAC;AACD,SAAO,MAAM;AACb,SAAO;AAAA,IACL;AAAA,IACA,SAAS,GAAG,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,EAC1D;AACF;","names":["existsSync","resolve","existsSync","readFileSync","resolve","resolve","existsSync","readFileSync","resolve"]}
|
|
@@ -8,12 +8,14 @@ import {
|
|
|
8
8
|
jobBackendFromConfig,
|
|
9
9
|
matchAgentAuxRoute,
|
|
10
10
|
parseApprovalAgentName,
|
|
11
|
+
reservedRoutesFromConfig,
|
|
11
12
|
resolvePluginSpecifiers,
|
|
12
13
|
resolveTransformer,
|
|
13
14
|
serveMatchedAuxRoute,
|
|
15
|
+
serveReservedRoute,
|
|
14
16
|
serveThroughPluginLifecycle,
|
|
15
17
|
setupSsrDevMiddleware
|
|
16
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-HZAXFD55.js";
|
|
17
19
|
import {
|
|
18
20
|
resolveTheoRootDir
|
|
19
21
|
} from "./chunk-FDOOBTXJ.js";
|
|
@@ -35,7 +37,7 @@ import {
|
|
|
35
37
|
mountAgent,
|
|
36
38
|
readAgentPolicy,
|
|
37
39
|
writeWebResponseToServerResponse
|
|
38
|
-
} from "./chunk-
|
|
40
|
+
} from "./chunk-E22GPCCO.js";
|
|
39
41
|
import {
|
|
40
42
|
getApprovalRegistry,
|
|
41
43
|
resolveProvider
|
|
@@ -69,7 +71,7 @@ import {
|
|
|
69
71
|
} from "./chunk-4WP7A7RX.js";
|
|
70
72
|
import {
|
|
71
73
|
loadConfig
|
|
72
|
-
} from "./chunk-
|
|
74
|
+
} from "./chunk-35OI2TKT.js";
|
|
73
75
|
import {
|
|
74
76
|
buildServicesProxyConfig
|
|
75
77
|
} from "./chunk-L4V5V2TI.js";
|
|
@@ -286,7 +288,8 @@ var DEFAULT_RESOLVED = {
|
|
|
286
288
|
devtoolsEnabled: true,
|
|
287
289
|
openapi: void 0,
|
|
288
290
|
distDir: ".theokit",
|
|
289
|
-
jobBackend: void 0
|
|
291
|
+
jobBackend: void 0,
|
|
292
|
+
reservedRoutes: {}
|
|
290
293
|
};
|
|
291
294
|
async function resolvePluginConfig(projectRoot) {
|
|
292
295
|
try {
|
|
@@ -325,7 +328,8 @@ async function resolvePluginConfig(projectRoot) {
|
|
|
325
328
|
devtoolsEnabled: userConfig.devtools !== false,
|
|
326
329
|
openapi: userConfig.openapi,
|
|
327
330
|
distDir: userConfig.distDir,
|
|
328
|
-
jobBackend: jobBackendFromConfig(userConfig)
|
|
331
|
+
jobBackend: jobBackendFromConfig(userConfig),
|
|
332
|
+
reservedRoutes: reservedRoutesFromConfig(userConfig)
|
|
329
333
|
};
|
|
330
334
|
} catch {
|
|
331
335
|
return DEFAULT_RESOLVED;
|
|
@@ -932,6 +936,28 @@ function createApiMiddleware(vite, serverDir, rateLimitConfigOrOptions) {
|
|
|
932
936
|
};
|
|
933
937
|
}
|
|
934
938
|
|
|
939
|
+
// src/vite-plugin/reserved-route-middleware.ts
|
|
940
|
+
function createReservedRouteMiddleware(routes) {
|
|
941
|
+
const serve = async (req, res, next) => {
|
|
942
|
+
try {
|
|
943
|
+
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
944
|
+
const reserved = await serveReservedRoute(pathname, routes);
|
|
945
|
+
if (reserved === null) {
|
|
946
|
+
next();
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
res.statusCode = reserved.status;
|
|
950
|
+
res.setHeader("Content-Type", "application/json");
|
|
951
|
+
res.end(JSON.stringify(reserved.body));
|
|
952
|
+
} catch (err) {
|
|
953
|
+
next(err);
|
|
954
|
+
}
|
|
955
|
+
};
|
|
956
|
+
return (req, res, next) => {
|
|
957
|
+
void serve(req, res, next);
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
|
|
935
961
|
// src/vite-plugin/ws-upgrade.ts
|
|
936
962
|
function setupWsUpgrade(server, serverDir) {
|
|
937
963
|
const wsRoutes = scanWebSocketRoutes(serverDir);
|
|
@@ -991,6 +1017,7 @@ async function runConfigureServer(server, ctx) {
|
|
|
991
1017
|
} catch {
|
|
992
1018
|
}
|
|
993
1019
|
});
|
|
1020
|
+
server.middlewares.use(createReservedRouteMiddleware(ctx.reservedRoutes));
|
|
994
1021
|
const serverDir = ctx.serverDir;
|
|
995
1022
|
server.middlewares.use(
|
|
996
1023
|
createActionMiddleware(server, serverDir, {
|
|
@@ -2254,7 +2281,7 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
2254
2281
|
}
|
|
2255
2282
|
const { assetsMapPlugin } = await import("./assets-map-BMQASQHW.js");
|
|
2256
2283
|
const assetsMap = assetsMapPlugin({ appDir: resolve5(projectRoot, options.appDir ?? "app") });
|
|
2257
|
-
const { appTypedClientPlugin } = await import("./app-typed-client-
|
|
2284
|
+
const { appTypedClientPlugin } = await import("./app-typed-client-JCBQGPMP.js");
|
|
2258
2285
|
const appClientPlugin = appTypedClientPlugin({
|
|
2259
2286
|
cwd: projectRoot,
|
|
2260
2287
|
serverDir: serverDirAbs,
|
|
@@ -2262,13 +2289,13 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
2262
2289
|
// B-313 — the same name line 226 already passes. This call passed neither it nor the root.
|
|
2263
2290
|
agentsDir: agentsDirName
|
|
2264
2291
|
});
|
|
2265
|
-
const { actionsVirtualModule } = await import("./actions-virtual-module-
|
|
2292
|
+
const { actionsVirtualModule } = await import("./actions-virtual-module-V5Q4XVL5.js");
|
|
2266
2293
|
const actionsPlugin = actionsVirtualModule({
|
|
2267
2294
|
serverDir: serverDirAbs,
|
|
2268
2295
|
distDir: resolve5(projectRoot, ".theokit")
|
|
2269
2296
|
});
|
|
2270
2297
|
const { agentsTypedClientPlugin } = await import("./agents-typed-client-D4OA2TXB.js");
|
|
2271
|
-
const { generateManifest } = await import("./internal-api-
|
|
2298
|
+
const { generateManifest } = await import("./internal-api-5FTPYSEQ.js");
|
|
2272
2299
|
const agentsClientPlugin = agentsTypedClientPlugin({
|
|
2273
2300
|
projectRoot,
|
|
2274
2301
|
agentsDir: agentsDirName,
|
|
@@ -2285,7 +2312,7 @@ async function theoPluginAsync(rootOrOptions) {
|
|
|
2285
2312
|
const controllerTransformPlugin = controllerSwcTransformPlugin({
|
|
2286
2313
|
serverDir: serverDirAbs
|
|
2287
2314
|
});
|
|
2288
|
-
const { serverOnlyImportBoundary } = await import("./server-boundary-
|
|
2315
|
+
const { serverOnlyImportBoundary } = await import("./server-boundary-5ZTBC2KF.js");
|
|
2289
2316
|
const serverBoundaryPlugin = serverOnlyImportBoundary({
|
|
2290
2317
|
projectRoot,
|
|
2291
2318
|
serverDir: serverDirAbs
|
|
@@ -2355,6 +2382,7 @@ function theoPlugin(rootOrOptions) {
|
|
|
2355
2382
|
let resolvedOpenApi;
|
|
2356
2383
|
let resolvedDistDir = ".theokit";
|
|
2357
2384
|
let jobBackend;
|
|
2385
|
+
let reservedRoutes = {};
|
|
2358
2386
|
const isDevModeRef = { value: false };
|
|
2359
2387
|
let configLoadedOnce = false;
|
|
2360
2388
|
return {
|
|
@@ -2376,6 +2404,7 @@ function theoPlugin(rootOrOptions) {
|
|
|
2376
2404
|
resolvedOpenApi = resolved.openapi;
|
|
2377
2405
|
resolvedDistDir = resolved.distDir;
|
|
2378
2406
|
jobBackend = resolved.jobBackend;
|
|
2407
|
+
reservedRoutes = resolved.reservedRoutes;
|
|
2379
2408
|
},
|
|
2380
2409
|
// T2.6 (M6) — config() body extracted to config-hook.ts. The hook
|
|
2381
2410
|
// owns optimizeDeps + warmup + services proxy + alias cascade.
|
|
@@ -2448,6 +2477,7 @@ function theoPlugin(rootOrOptions) {
|
|
|
2448
2477
|
services: options.services,
|
|
2449
2478
|
rateLimit: options.rateLimit,
|
|
2450
2479
|
jobBackend,
|
|
2480
|
+
reservedRoutes,
|
|
2451
2481
|
csrfReadinessStoreOverride: options.csrfReadinessStore,
|
|
2452
2482
|
virtualEntryServerId: VIRTUAL_ENTRY_SERVER_ID,
|
|
2453
2483
|
resolvedManifestId: RESOLVED_MANIFEST_ID
|
|
@@ -2465,4 +2495,4 @@ export {
|
|
|
2465
2495
|
buildOptimizeDepsInclude,
|
|
2466
2496
|
theoPlugin
|
|
2467
2497
|
};
|
|
2468
|
-
//# sourceMappingURL=chunk-
|
|
2498
|
+
//# sourceMappingURL=chunk-HNALEGOL.js.map
|