theokit 0.2.0 → 0.2.2

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.
Files changed (130) hide show
  1. package/dist/actions-virtual-module-E6PU47GV.js +175 -0
  2. package/dist/actions-virtual-module-E6PU47GV.js.map +1 -0
  3. package/dist/actions-virtual-module-E7IELVHL.js +174 -0
  4. package/dist/actions-virtual-module-E7IELVHL.js.map +1 -0
  5. package/dist/app-typed-client-RZMVWHJ3.js +289 -0
  6. package/dist/app-typed-client-RZMVWHJ3.js.map +1 -0
  7. package/dist/app-typed-client-YIBP6JWH.js +289 -0
  8. package/dist/app-typed-client-YIBP6JWH.js.map +1 -0
  9. package/dist/{aws-lambda-PONVF3UX.js → aws-lambda-XYCGZH3I.js} +2 -2
  10. package/dist/{build-IQQYCA3B.js → build-NCGIV4LL.js} +41 -14
  11. package/dist/build-NCGIV4LL.js.map +1 -0
  12. package/dist/build-request-body-preview-EOP2Y4F3.js +52 -0
  13. package/dist/build-request-body-preview-EOP2Y4F3.js.map +1 -0
  14. package/dist/build-request-body-preview-II2235E6.js +54 -0
  15. package/dist/build-request-body-preview-II2235E6.js.map +1 -0
  16. package/dist/{bun-DITMZMKL.js → bun-K73TQEWC.js} +2 -2
  17. package/dist/{chunk-GQSTRXXB.js → chunk-2BQYEBCK.js} +77 -68
  18. package/dist/chunk-2BQYEBCK.js.map +1 -0
  19. package/dist/chunk-7DHGV77J.js +140 -0
  20. package/dist/chunk-7DHGV77J.js.map +1 -0
  21. package/dist/{chunk-WQCPKA2L.js → chunk-C27AZN46.js} +570 -165
  22. package/dist/chunk-C27AZN46.js.map +1 -0
  23. package/dist/chunk-ERAZNHHR.js +73 -0
  24. package/dist/chunk-ERAZNHHR.js.map +1 -0
  25. package/dist/{chunk-ZK5JCE5J.js → chunk-EXJWO2HB.js} +201 -43
  26. package/dist/chunk-EXJWO2HB.js.map +1 -0
  27. package/dist/chunk-F3TG5FJV.js +97 -0
  28. package/dist/chunk-F3TG5FJV.js.map +1 -0
  29. package/dist/{chunk-OK2PJOLK.js → chunk-KJVEJILQ.js} +7 -3
  30. package/dist/chunk-KJVEJILQ.js.map +1 -0
  31. package/dist/{chunk-JBC7PFV4.js → chunk-M23FP2AS.js} +2 -2
  32. package/dist/chunk-M23FP2AS.js.map +1 -0
  33. package/dist/{chunk-FRBYJANT.js → chunk-M6MYZSD2.js} +195 -41
  34. package/dist/chunk-M6MYZSD2.js.map +1 -0
  35. package/dist/{chunk-S3JBIFKS.js → chunk-MG7H3LAW.js} +2 -2
  36. package/dist/chunk-MOT42NAH.js +165 -0
  37. package/dist/chunk-MOT42NAH.js.map +1 -0
  38. package/dist/{chunk-OEB3OIYP.js → chunk-OJHO2X7C.js} +497 -168
  39. package/dist/chunk-OJHO2X7C.js.map +1 -0
  40. package/dist/chunk-QLGES2HC.js +189 -0
  41. package/dist/chunk-QLGES2HC.js.map +1 -0
  42. package/dist/{chunk-JZ5WEG3S.js → chunk-SEVYARIU.js} +9 -5
  43. package/dist/chunk-SEVYARIU.js.map +1 -0
  44. package/dist/chunk-WSJKACWB.js +17 -0
  45. package/dist/chunk-WSJKACWB.js.map +1 -0
  46. package/dist/{chunk-3Q36SEDK.js → chunk-ZBWROIIO.js} +43 -2
  47. package/dist/{chunk-3Q36SEDK.js.map → chunk-ZBWROIIO.js.map} +1 -1
  48. package/dist/{chunk-Y5KE6YFP.js → chunk-ZJW5FFYJ.js} +3 -3
  49. package/dist/chunk-ZJW5FFYJ.js.map +1 -0
  50. package/dist/chunk-ZOXNJV2O.js +358 -0
  51. package/dist/chunk-ZOXNJV2O.js.map +1 -0
  52. package/dist/cli/index.js +22 -7
  53. package/dist/cli/index.js.map +1 -1
  54. package/dist/client/index.d.ts +31 -1
  55. package/dist/client/index.js +100 -0
  56. package/dist/client/index.js.map +1 -1
  57. package/dist/{cloudflare-RBANU3SE.js → cloudflare-LCAOTRYZ.js} +2 -2
  58. package/dist/{deno-deploy-J7LI6HNL.js → deno-deploy-ZN4RE5HF.js} +2 -2
  59. package/dist/{dev-VN6WS3CM.js → dev-WDXC74CK.js} +15 -7
  60. package/dist/dev-WDXC74CK.js.map +1 -0
  61. package/dist/dev-emit-3CHM73TV.js +390 -0
  62. package/dist/dev-emit-3CHM73TV.js.map +1 -0
  63. package/dist/dev-emit-I3CKOHML.js +44 -0
  64. package/dist/dev-emit-I3CKOHML.js.map +1 -0
  65. package/dist/devtools/entry.js +545 -181
  66. package/dist/devtools/entry.js.map +1 -1
  67. package/dist/{dispatcher-IK3FVMX5.js → dispatcher-AQJGI3HU.js} +2 -2
  68. package/dist/dispatcher-E6QV32BO.js +83 -0
  69. package/dist/dispatcher-E6QV32BO.js.map +1 -0
  70. package/dist/{dist-Q5VBFWVL.js → dist-R2Q7GVDW.js} +10357 -12068
  71. package/dist/dist-R2Q7GVDW.js.map +1 -0
  72. package/dist/{generate-SIO4JSKJ.js → generate-DT4IIAHF.js} +88 -22
  73. package/dist/generate-DT4IIAHF.js.map +1 -0
  74. package/dist/index.d.ts +108 -1
  75. package/dist/index.js +5 -2
  76. package/dist/index.js.map +1 -1
  77. package/dist/{info-B3UOXFUF.js → info-VM7EK4JC.js} +3 -3
  78. package/dist/{netlify-IFY6ZGFV.js → netlify-5VQ22Z2P.js} +2 -2
  79. package/dist/{node-KWZI3CKV.js → node-3APTLGWB.js} +2 -2
  80. package/dist/openapi-CBASKC7W.js +84 -0
  81. package/dist/openapi-CBASKC7W.js.map +1 -0
  82. package/dist/registry-5QFTLOL2.js +25 -0
  83. package/dist/{routes-CAGFZKUK.js → routes-7O4NUDYS.js} +9 -7
  84. package/dist/{routes-CAGFZKUK.js.map → routes-7O4NUDYS.js.map} +1 -1
  85. package/dist/{schema-Cxq2qqwh.d.ts → schema-CjVly9c_.d.ts} +43 -1
  86. package/dist/{schema-MVB2FVK6.js → schema-JAKF23GR.js} +2 -2
  87. package/dist/server/cost/index.js +1 -1
  88. package/dist/server/index.d.ts +219 -47
  89. package/dist/server/index.js +35 -116
  90. package/dist/server/index.js.map +1 -1
  91. package/dist/{start-ZGWW5MOL.js → start-5JTFWF4T.js} +20 -14
  92. package/dist/start-5JTFWF4T.js.map +1 -0
  93. package/dist/{static-BH6JQNM2.js → static-TZBVBDTB.js} +4 -4
  94. package/dist/{upgrade-readiness-OHL36FQL.js → upgrade-readiness-Q46KTG2J.js} +6 -1
  95. package/dist/upgrade-readiness-Q46KTG2J.js.map +1 -0
  96. package/dist/{vercel-RHADE5IP.js → vercel-MWW24ABC.js} +2 -2
  97. package/dist/vite-plugin/index.d.ts +25 -1
  98. package/dist/vite-plugin/index.js +5 -2
  99. package/dist/{vite-plugin-WA3G45YY.js → vite-plugin-4WZ3C2AC.js} +7 -6
  100. package/package.json +4 -2
  101. package/dist/build-IQQYCA3B.js.map +0 -1
  102. package/dist/chunk-FRBYJANT.js.map +0 -1
  103. package/dist/chunk-GQSTRXXB.js.map +0 -1
  104. package/dist/chunk-JBC7PFV4.js.map +0 -1
  105. package/dist/chunk-JZ5WEG3S.js.map +0 -1
  106. package/dist/chunk-OEB3OIYP.js.map +0 -1
  107. package/dist/chunk-OK2PJOLK.js.map +0 -1
  108. package/dist/chunk-WQCPKA2L.js.map +0 -1
  109. package/dist/chunk-Y5KE6YFP.js.map +0 -1
  110. package/dist/chunk-ZK5JCE5J.js.map +0 -1
  111. package/dist/dev-VN6WS3CM.js.map +0 -1
  112. package/dist/dist-Q5VBFWVL.js.map +0 -1
  113. package/dist/generate-SIO4JSKJ.js.map +0 -1
  114. package/dist/registry-BB3UYAOG.js +0 -25
  115. package/dist/start-ZGWW5MOL.js.map +0 -1
  116. package/dist/upgrade-readiness-OHL36FQL.js.map +0 -1
  117. /package/dist/{aws-lambda-PONVF3UX.js.map → aws-lambda-XYCGZH3I.js.map} +0 -0
  118. /package/dist/{bun-DITMZMKL.js.map → bun-K73TQEWC.js.map} +0 -0
  119. /package/dist/{chunk-S3JBIFKS.js.map → chunk-MG7H3LAW.js.map} +0 -0
  120. /package/dist/{cloudflare-RBANU3SE.js.map → cloudflare-LCAOTRYZ.js.map} +0 -0
  121. /package/dist/{deno-deploy-J7LI6HNL.js.map → deno-deploy-ZN4RE5HF.js.map} +0 -0
  122. /package/dist/{dispatcher-IK3FVMX5.js.map → dispatcher-AQJGI3HU.js.map} +0 -0
  123. /package/dist/{info-B3UOXFUF.js.map → info-VM7EK4JC.js.map} +0 -0
  124. /package/dist/{netlify-IFY6ZGFV.js.map → netlify-5VQ22Z2P.js.map} +0 -0
  125. /package/dist/{node-KWZI3CKV.js.map → node-3APTLGWB.js.map} +0 -0
  126. /package/dist/{registry-BB3UYAOG.js.map → registry-5QFTLOL2.js.map} +0 -0
  127. /package/dist/{schema-MVB2FVK6.js.map → schema-JAKF23GR.js.map} +0 -0
  128. /package/dist/{static-BH6JQNM2.js.map → static-TZBVBDTB.js.map} +0 -0
  129. /package/dist/{vercel-RHADE5IP.js.map → vercel-MWW24ABC.js.map} +0 -0
  130. /package/dist/{vite-plugin-WA3G45YY.js.map → vite-plugin-4WZ3C2AC.js.map} +0 -0
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
3
  import {
4
- loadManifest
5
- } from "./chunk-JZ5WEG3S.js";
4
+ preflightNodeAndBindings
5
+ } from "./chunk-F3TG5FJV.js";
6
6
  import {
7
7
  buildSecurityHeaders,
8
8
  createPluginRunnerFromConfig,
@@ -16,19 +16,24 @@ import {
16
16
  resolveTransformer,
17
17
  sendError,
18
18
  warnOnce
19
- } from "./chunk-WQCPKA2L.js";
19
+ } from "./chunk-C27AZN46.js";
20
+ import {
21
+ loadConfig,
22
+ loadEnv
23
+ } from "./chunk-MG7H3LAW.js";
24
+ import "./chunk-ZBWROIIO.js";
25
+ import "./chunk-WZ7CPVQB.js";
26
+ import {
27
+ loadManifest
28
+ } from "./chunk-SEVYARIU.js";
20
29
  import {
21
30
  matchRoute,
22
- scanServerActions,
23
31
  scanServerRoutes,
24
32
  scanWebSocketRoutes
25
- } from "./chunk-GQSTRXXB.js";
33
+ } from "./chunk-QLGES2HC.js";
26
34
  import {
27
- loadConfig,
28
- loadEnv
29
- } from "./chunk-S3JBIFKS.js";
30
- import "./chunk-3Q36SEDK.js";
31
- import "./chunk-WZ7CPVQB.js";
35
+ scanServerActions
36
+ } from "./chunk-MOT42NAH.js";
32
37
  import "./chunk-KT3MWNZG.js";
33
38
 
34
39
  // src/cli/commands/start.ts
@@ -42,7 +47,7 @@ import { resolve } from "path";
42
47
  async function configureAgentRegistryFromConfig(registryConfig) {
43
48
  if (registryConfig === void 0) return;
44
49
  try {
45
- const sdk = await import("./dist-Q5VBFWVL.js").catch(() => null);
50
+ const sdk = await import("./dist-R2Q7GVDW.js").catch(() => null);
46
51
  const sdkConfigure = sdk?.Agent?.registry?.configure;
47
52
  if (sdkConfigure === void 0) return;
48
53
  const { configureAgentRegistryOnce } = await import("./configure-agent-registry-6YGTJYBC.js");
@@ -66,7 +71,7 @@ async function configureStorageManagerFromConfig(storageConfig) {
66
71
  if (storageConfig === void 0 || storageConfig === null) return;
67
72
  try {
68
73
  const { getStorageManager } = await import("./storage-manager-D5KBXXKB.js");
69
- const { storageSchema } = await import("./schema-MVB2FVK6.js");
74
+ const { storageSchema } = await import("./schema-JAKF23GR.js");
70
75
  const parsed = storageSchema.parse(storageConfig);
71
76
  getStorageManager().configure(parsed);
72
77
  } catch (err) {
@@ -96,7 +101,7 @@ function installGracefulShutdown(server) {
96
101
  [theokit] ${signal} received \u2014 evicting agents`);
97
102
  void (async () => {
98
103
  try {
99
- const sdk = await import("./dist-Q5VBFWVL.js").catch(() => null);
104
+ const sdk = await import("./dist-R2Q7GVDW.js").catch(() => null);
100
105
  if (sdk?.Agent?.registry?.evictAll !== void 0) {
101
106
  await sdk.Agent.registry.evictAll();
102
107
  }
@@ -531,6 +536,7 @@ async function attachWebSocketHandler(server, wsRoutes, loadModule) {
531
536
  // src/cli/commands/start.ts
532
537
  async function startCommand(options) {
533
538
  const cwd = process.cwd();
539
+ preflightNodeAndBindings(cwd);
534
540
  loadEnv({ cwd, mode: "production" });
535
541
  const config = await loadConfig(cwd);
536
542
  await configureAgentRegistryFromConfig(config.agents?.registry);
@@ -606,4 +612,4 @@ export {
606
612
  resolveSsrEntry,
607
613
  startCommand
608
614
  };
609
- //# sourceMappingURL=start-ZGWW5MOL.js.map
615
+ //# sourceMappingURL=start-5JTFWF4T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/start.ts","../src/cli/commands/start-bootstrap-stages.ts","../src/cli/commands/start-graceful-shutdown.ts","../src/cli/commands/start-manifest-loader.ts","../src/cli/commands/start-request-handler.ts","../src/cli/commands/start-handlers.ts","../src/server/http/static.ts","../src/cli/commands/start-ssr-setup.ts","../src/cli/commands/start-websocket-handler.ts"],"sourcesContent":["/**\n * theokit start — production server orchestration spine.\n *\n * T4.2 (architecture-cleanup, ADR-0017): stages extracted to sibling modules.\n * - start-bootstrap-stages.ts — config/registry/storage bootstrap + resolveSsrEntry\n * - start-manifest-loader.ts — manifest.json or scan fallback\n * - start-ssr-setup.ts — SSR entry-server + HTML template split\n * - start-handlers.ts — branch handlers (action/route/static/404)\n * - start-request-handler.ts — request lifecycle wiring\n * - start-websocket-handler.ts — WS upgrade (opt-in)\n * - start-graceful-shutdown.ts — SIGTERM/SIGINT drain\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { createServer } from 'node:http'\nimport { join, resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { createPluginRunnerFromConfig } from '../../server/plugins/load-plugins.js'\nimport { createRateLimiter } from '../../server/rate-limit/rate-limit.js'\nimport { createProductionLoader } from '../../server/scan/module-loader.js'\nimport { resolveTransformer } from '../../server/transformer.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport {\n configureAgentRegistryFromConfig,\n configureStorageManagerFromConfig,\n} from './start-bootstrap-stages.js'\nimport { installGracefulShutdown } from './start-graceful-shutdown.js'\nimport type { RequestHandlerCtx } from './start-handlers.js'\nimport { loadRoutesAndActions } from './start-manifest-loader.js'\nimport { createRequestHandler } from './start-request-handler.js'\nimport { setupSsr } from './start-ssr-setup.js'\nimport { attachWebSocketHandler } from './start-websocket-handler.js'\n\n// Backwards-compat: external test fixtures may import resolveSsrEntry from here.\nexport { resolveSsrEntry } from './start-bootstrap-stages.js'\n\ninterface StartOptions {\n port?: number\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n loadEnv({ cwd, mode: 'production' })\n const config = await loadConfig(cwd)\n\n await configureAgentRegistryFromConfig(config.agents?.registry)\n await configureStorageManagerFromConfig(config.storage)\n\n const distDir = resolve(cwd, '.theo')\n const clientDir = resolve(distDir, 'client')\n const serverDir = resolve(cwd, 'server')\n\n if (!existsSync(clientDir)) {\n throw new Error('No build found. Run `theo build` first.')\n }\n\n const indexHtml = readFileSync(join(clientDir, 'index.html'), 'utf-8')\n const loadModule = createProductionLoader()\n const port = options.port ?? config.port\n const pluginRunner = await createPluginRunnerFromConfig(config.plugins)\n const transformer = resolveTransformer(config.serialization)\n\n const custom404Path = join(clientDir, '404.html')\n const custom500Path = join(clientDir, '500.html')\n const custom404Html = existsSync(custom404Path) ? readFileSync(custom404Path, 'utf-8') : null\n const custom500Html = existsSync(custom500Path) ? readFileSync(custom500Path, 'utf-8') : null\n\n const {\n routes: cachedRoutes,\n actions: cachedActions,\n wsRoutes: cachedWsRoutes,\n } = loadRoutesAndActions(distDir, serverDir)\n\n // Rate limiter (legacy flat form only — per-route variant is handled in\n // api-middleware integration path, not this fallback).\n const flatRateLimit =\n config.rateLimit && 'windowMs' in config.rateLimit && 'max' in config.rateLimit\n ? config.rateLimit\n : undefined\n const rateLimiter = flatRateLimit ? createRateLimiter(flatRateLimit) : null\n\n const ssr = await setupSsr({\n distDir,\n indexHtml,\n ssrConfigEnabled: config.ssr,\n ssrStreamingConfig: config.ssrStreaming,\n })\n\n const server = createServer(\n createRequestHandler({\n buildCtx: (req, res, requestId, startTime): RequestHandlerCtx => ({\n req,\n res,\n url: req.url ?? '/',\n requestId,\n startTime,\n clientDir,\n custom404Html,\n cachedRoutes,\n cachedActions,\n loadModule,\n serverDir,\n pluginRunner,\n transformer,\n csrfMode: config.security?.csrf ?? 'strict',\n disallowed: config.security?.disallowed,\n rateLimiter,\n }),\n securityHeadersConfig: config.security?.headers ?? {},\n ssrRender: ssr.render,\n ssrRenderStreaming: ssr.renderStreaming,\n ssrStreamingEnabled: ssr.streamingEnabled,\n htmlHead: ssr.htmlHead,\n htmlTail: ssr.htmlTail,\n indexHtml,\n custom500Html,\n }),\n )\n\n await attachWebSocketHandler(server, cachedWsRoutes, loadModule)\n\n server.listen(port, () => {\n console.log(`\\n Theo production server`)\n console.log(` → http://localhost:${String(port)}\\n`)\n })\n\n installGracefulShutdown(server)\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 * `docs/plans/architecture-cleanup-plan.md` T4.2 Deferred sub-tasks.\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('@usetheo/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 // eslint-disable-next-line security/detect-non-literal-fs-filename -- distDir is from `theokit start`'s own caller-controlled config; the suffix is from a const literal array\n if (existsSync(path)) return path\n }\n return null\n}\n","/**\n * Graceful shutdown stage for `theokit start` (T4.2 architecture-cleanup,\n * ADR-0007 D6 — SIGTERM evicts agents + drains StorageManager).\n *\n * EC-13: SIGTERM evicts agents IMMEDIATELY (no per-request drain). In-flight\n * requests get aborted mid-stream — acceptable because the platform LB\n * removed this pod from rotation BEFORE sending SIGTERM (K8s preStop hook +\n * terminationGracePeriodSeconds; same on Vercel/CF/Render).\n *\n * Re-entry guard: multiple SIGTERMs in quick succession run shutdown ONCE.\n */\n\nimport type { Server as HttpServer } from 'node:http'\n\nimport { warnOnce } from '../../server/observability/logger.js'\n\nexport function installGracefulShutdown(server: HttpServer): void {\n let shuttingDown = false\n const shutdown = (signal: NodeJS.Signals): void => {\n if (shuttingDown) return\n shuttingDown = true\n console.log(`\\n [theokit] ${signal} received — evicting agents`)\n void (async () => {\n // Lazy-import SDK only at shutdown time to avoid forcing the dep on\n // apps that don't use agents at all.\n try {\n const sdk = (await import('@usetheo/sdk').catch(() => null)) as {\n Agent?: { registry?: { evictAll?: () => Promise<void> } }\n } | null\n if (sdk?.Agent?.registry?.evictAll !== undefined) {\n await sdk.Agent.registry.evictAll()\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('shutdown.evict_error', {\n event: 'shutdown.evict_error',\n message: msg,\n })\n }\n // T3.1 — drain the StorageManager AFTER agent eviction. Order matters:\n // agents may still hold open pool refs while evicting; closing pools\n // first would break in-flight queries.\n try {\n const { getStorageManager } = await import('../../server/storage/storage-manager.js')\n const manager = getStorageManager()\n await manager.dispose()\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n warnOnce('shutdown.dispose_error', {\n event: 'shutdown.dispose_error',\n message: msg,\n })\n }\n console.log(` [theokit] shutdown complete`)\n server.close(() => {\n process.exit(0)\n })\n setTimeout(() => {\n warnOnce('shutdown.forced_exit', {\n event: 'shutdown.forced_exit',\n message: 'forced exit after 25s timeout',\n })\n process.exit(0)\n }, 25_000).unref()\n })()\n }\n process.on('SIGTERM', () => {\n shutdown('SIGTERM')\n })\n process.on('SIGINT', () => {\n shutdown('SIGINT')\n })\n}\n","/**\n * Manifest loading stage for `theokit start` (T4.2 architecture-cleanup).\n *\n * Loads pre-built manifest from `.theo/manifest.json` if present; otherwise\n * scans server/ for routes/actions/ws at startup with a structured warn.\n */\n\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { warnOnce } from '../../server/observability/logger.js'\nimport type { ActionNode } from '../../server/scan/action-scan.js'\nimport { scanServerActions } from '../../server/scan/action-scan.js'\nimport { loadManifest } from '../../server/scan/manifest.js'\nimport type { ServerRouteNode } from '../../server/scan/match.js'\nimport { scanServerRoutes } from '../../server/scan/scan.js'\nimport type { WebSocketRouteNode } from '../../server/scan/ws-scan.js'\nimport { scanWebSocketRoutes } from '../../server/scan/ws-scan.js'\n\nexport interface LoadedRoutes {\n routes: ServerRouteNode[]\n actions: ActionNode[]\n wsRoutes: WebSocketRouteNode[]\n}\n\nexport function loadRoutesAndActions(distDir: string, serverDir: string): LoadedRoutes {\n const manifestPath = join(distDir, 'manifest.json')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- distDir is from `theokit start`'s own caller-controlled cwd\n if (existsSync(manifestPath)) {\n const manifest = loadManifest(distDir, serverDir)\n return {\n routes: manifest.routes,\n actions: manifest.actions,\n wsRoutes: manifest.websockets,\n }\n }\n warnOnce('bootstrap.manifest_not_found', {\n event: 'bootstrap.manifest_not_found',\n message:\n 'No manifest found, scanning routes at startup. Run \"theo build\" to generate manifest.',\n serverDir,\n })\n return {\n routes: scanServerRoutes(serverDir),\n actions: scanServerActions(serverDir),\n wsRoutes: scanWebSocketRoutes(serverDir),\n }\n}\n","/**\n * Inline request handler for `theokit start` (T4.2 architecture-cleanup).\n *\n * Wires the per-request flow: security headers → action/route/static branches\n * → SSR fallback → CSR fallback → 500 page.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { generateNonce } from '../../server/auth/nonce.js'\nimport { sendError } from '../../server/http/send-response.js'\nimport { buildSecurityHeaders } from '../../server/security/security-headers.js'\n\nimport {\n tryServeAction,\n tryServeApiRoute,\n tryServeCustom404,\n tryServeStatic,\n type RequestHandlerCtx,\n} from './start-handlers.js'\nimport {\n isSsrRenderResult,\n type SsrRender,\n type SsrRenderResult,\n type SsrRenderStreaming,\n} from './start-ssr-setup.js'\n\nexport interface RequestHandlerContext {\n buildCtx: (\n req: IncomingMessage,\n res: ServerResponse,\n requestId: string,\n startTime: number,\n ) => RequestHandlerCtx\n securityHeadersConfig: Parameters<typeof buildSecurityHeaders>[0]\n ssrRender: SsrRender | null\n ssrRenderStreaming: SsrRenderStreaming | null\n ssrStreamingEnabled: boolean\n htmlHead: string\n htmlTail: string\n indexHtml: string\n custom500Html: string | null\n}\n\nfunction asSsrRenderResult(value: SsrRenderResult): SsrRenderResult {\n return value\n}\n\n/* eslint-disable complexity, sonarjs/cognitive-complexity --\n * inline request orchestrator co-located so the lifecycle is readable end-to-end.\n */\nexport function createRequestHandler(\n ctx: RequestHandlerContext,\n): (req: IncomingMessage, res: ServerResponse) => void {\n return (req: IncomingMessage, res: ServerResponse) => {\n void (async () => {\n const url = req.url ?? '/'\n const requestId = randomUUID()\n const start = Date.now()\n\n // Per-request nonce (EC-6 dev/prod parity).\n const nonce = generateNonce()\n const securityHeaders = buildSecurityHeaders(\n ctx.securityHeadersConfig,\n { production: true },\n { nonce },\n )\n for (const [k, v] of Object.entries(securityHeaders)) {\n res.setHeader(k, v)\n }\n\n const handlerCtx = ctx.buildCtx(req, res, requestId, start)\n\n try {\n if (await tryServeAction(handlerCtx)) return\n if (await tryServeApiRoute(handlerCtx)) return\n if (tryServeStatic(handlerCtx)) return\n if (tryServeCustom404(handlerCtx)) return\n\n // SSR streaming branch\n if (ctx.ssrStreamingEnabled && ctx.ssrRenderStreaming) {\n const controller = new AbortController()\n const onClose = (): void => {\n controller.abort()\n }\n req.on('close', onClose)\n try {\n const result = await ctx.ssrRenderStreaming(url, res, {\n signal: controller.signal,\n nonce,\n })\n if (result && typeof result === 'object' && 'redirect' in result) {\n res.writeHead(302, { Location: result.redirect.headers.get('location') ?? '/' })\n res.end()\n return\n }\n return\n } catch (streamErr) {\n console.error('[SSR Stream Error]', (streamErr as Error).message)\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/html' })\n }\n if (!res.writableEnded) {\n res.end(ctx.custom500Html ?? '<h1>500 — Server Error</h1>')\n }\n return\n } finally {\n req.removeListener('close', onClose)\n }\n }\n\n // SSR (non-streaming) branch\n if (ctx.ssrRender) {\n try {\n const result = await ctx.ssrRender(url, { nonce })\n if (result && typeof result === 'object' && 'redirect' in result) {\n res.writeHead(302, { Location: result.redirect.headers.get('location') ?? '/' })\n res.end()\n return\n }\n let ssrHtml = ''\n let hydrationScript = ''\n if (typeof result === 'string') {\n ssrHtml = result\n } else if (isSsrRenderResult(result)) {\n const rendered = asSsrRenderResult(result)\n ssrHtml = rendered.html\n const dataJson = JSON.stringify(rendered.hydrationData).replace(/</g, '\\\\u003c')\n hydrationScript = `<script${\n nonce ? ` nonce=\"${nonce}\"` : ''\n }>window.__staticRouterHydrationData=${dataJson}</script>`\n }\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(ctx.htmlHead + ssrHtml + hydrationScript + ctx.htmlTail)\n return\n } catch (ssrErr) {\n console.error('[SSR Error] Falling back to CSR:', (ssrErr as Error).message)\n // Fall through to CSR fallback\n }\n }\n\n // CSR fallback\n res.writeHead(200, { 'Content-Type': 'text/html' })\n res.end(ctx.indexHtml)\n } catch (err) {\n if (ctx.custom500Html && !res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'text/html' })\n res.end(ctx.custom500Html)\n } else if (!res.headersSent) {\n sendError(res, 'INTERNAL_ERROR', (err as Error).message, 500)\n } else {\n res.end()\n }\n }\n })()\n }\n}\n/* eslint-enable complexity, sonarjs/cognitive-complexity */\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { extname } from 'node:path'\n\nimport { executeAction } from '../../server/http/action-execute.js'\nimport { executeRoute } from '../../server/http/execute.js'\nimport { sendError } from '../../server/http/send-response.js'\nimport { serveStaticFile } from '../../server/http/static.js'\nimport { logRequest } from '../../server/observability/logger.js'\nimport { findSuggestion } from '../../server/observability/suggest.js'\nimport type { PluginRunner } from '../../server/plugins/plugin-runner.js'\nimport type { ActionNode } from '../../server/scan/action-scan.js'\nimport { matchRoute } from '../../server/scan/match.js'\nimport type { ServerRouteNode } from '../../server/scan/match.js'\nimport type { LoadModule } from '../../server/scan/module-loader.js'\nimport type { CsrfMode, DisallowedConfig } from '../../server/security/csrf.js'\nimport type { TheoTransformer } from '../../server/transformer.js'\n\n/**\n * T6.1 (PV-7 SRP): start.ts request orchestrator decomposed into 5 focused\n * per-branch handlers. Each handler returns `true` if it handled the\n * request (response sent) so the orchestrator can stop iterating.\n *\n * The original 455-LOC monolith closed over 14+ locals; the shared shape\n * `RequestHandlerCtx` makes the dependencies explicit + reviewable.\n */\nexport interface RequestHandlerCtx {\n req: IncomingMessage\n res: ServerResponse\n url: string\n requestId: string\n startTime: number\n // Pre-loaded build artifacts\n clientDir: string\n custom404Html: string | null\n // Manifest-resolved tables\n cachedRoutes: ServerRouteNode[]\n cachedActions: ActionNode[]\n // Runtime infra\n loadModule: LoadModule\n serverDir: string\n pluginRunner: PluginRunner | undefined\n transformer: TheoTransformer | undefined\n csrfMode: CsrfMode\n disallowed: DisallowedConfig | undefined\n rateLimiter:\n | ((req: IncomingMessage) => { limited: boolean; headers: Record<string, string> })\n | null\n}\n\n/** Apply rate limit; return true if request was limited (response sent). */\nfunction applyRateLimit(c: RequestHandlerCtx, method: string): boolean {\n if (!c.rateLimiter) return false\n const check = c.rateLimiter(c.req)\n for (const [k, v] of Object.entries(check.headers)) c.res.setHeader(k, v)\n if (check.limited) {\n sendError(c.res, 'RATE_LIMITED', 'Too many requests', 429, undefined, c.requestId)\n logRequest({\n method,\n url: c.url,\n status: 429,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n return false\n}\n\n/** Branch 1: action routes (`/api/__actions/{file}/{exportName}`). */\nexport async function tryServeAction(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/__actions/')) return false\n c.res.setHeader('x-request-id', c.requestId)\n\n if (applyRateLimit(c, c.req.method ?? 'POST')) return true\n\n const pathAfterPrefix = c.url.slice('/api/__actions/'.length).split('?')[0]\n const segments = pathAfterPrefix.split('/').filter(Boolean)\n if (segments.length < 2) {\n sendError(\n c.res,\n 'BAD_REQUEST',\n 'Action URL must be /api/__actions/{file}/{exportName}',\n 400,\n undefined,\n c.requestId,\n )\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: 400,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n const exportName = segments[segments.length - 1]\n const actionPath = segments.slice(0, -1).join('/')\n const action = c.cachedActions.find((a) => a.actionPath === actionPath)\n if (!action) {\n const actionPaths = c.cachedActions.map((a) => a.actionPath)\n const suggestion = findSuggestion(actionPath, actionPaths)\n const msg = suggestion\n ? `Action \"${actionPath}\" not found. Did you mean: ${suggestion}?`\n : `Action \"${actionPath}\" not found`\n sendError(c.res, 'NOT_FOUND', msg, 404, undefined, c.requestId)\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: 404,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n await executeAction(\n action.filePath,\n exportName,\n c.req,\n c.res,\n c.loadModule,\n c.serverDir,\n c.requestId,\n c.pluginRunner,\n c.csrfMode,\n c.disallowed,\n )\n logRequest({\n method: c.req.method ?? 'POST',\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/** Branch 2: API routes (`/api/*` excluding actions). */\nexport async function tryServeApiRoute(c: RequestHandlerCtx): Promise<boolean> {\n if (!c.url.startsWith('/api/')) return false\n c.res.setHeader('x-request-id', c.requestId)\n\n if (applyRateLimit(c, c.req.method ?? 'GET')) return true\n\n const match = matchRoute(c.url, c.cachedRoutes)\n if (!match) {\n const urlPath = c.url.split('?')[0]\n const routePaths = c.cachedRoutes.map((r) => r.routePath)\n const suggestion = findSuggestion(urlPath, routePaths)\n const msg = suggestion\n ? `API route not found: ${urlPath}. Did you mean: ${suggestion}?`\n : 'API route not found'\n sendError(c.res, 'NOT_FOUND', msg, 404, undefined, c.requestId)\n logRequest({\n method: c.req.method ?? 'GET',\n url: c.url,\n status: 404,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n }\n const method = (c.req.method ?? 'GET').toUpperCase()\n // T3.1 (ADR-0016) — context object replaces 12 positional args\n await executeRoute({\n route: match.route,\n method,\n params: match.params,\n req: c.req,\n res: c.res,\n loadModule: c.loadModule,\n serverDir: c.serverDir,\n requestId: c.requestId,\n pluginRunner: c.pluginRunner,\n transformer: c.transformer,\n csrfMode: c.csrfMode,\n disallowed: c.disallowed,\n })\n logRequest({\n method,\n url: c.url,\n status: c.res.statusCode,\n duration: Date.now() - c.startTime,\n requestId: c.requestId,\n })\n return true\n}\n\n/** Branch 3: static files (returns true if a static asset was served). */\nexport function tryServeStatic(c: RequestHandlerCtx): boolean {\n return serveStaticFile(c.req, c.res, c.clientDir)\n}\n\n/** Branch 4: custom 404 for URLs that look like missing assets. */\nexport function tryServeCustom404(c: RequestHandlerCtx): boolean {\n const urlPath = c.url.split('?')[0]\n if (c.custom404Html && extname(urlPath)) {\n c.res.writeHead(404, { 'Content-Type': 'text/html' })\n c.res.end(c.custom404Html)\n return true\n }\n return false\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Static-file server. The URL path IS user-controlled, BUT before any fs\n * call we resolve to absolute and reject with 403 if the resolved path\n * escapes `clientDir` (see EC-1 guard at line below). The guard is\n * authoritative; the rule cannot see it.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { resolve, extname } from 'node:path'\n\nconst MIME_TYPES: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'application/javascript',\n '.mjs': 'application/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2',\n '.ttf': 'font/ttf',\n '.txt': 'text/plain',\n '.map': 'application/json',\n}\n\nexport function serveStaticFile(\n req: IncomingMessage,\n res: ServerResponse,\n clientDir: string,\n): boolean {\n const urlPath = (req.url ?? '/').split('?')[0]\n\n // Path traversal prevention (EC-1)\n const filePath = resolve(clientDir, '.' + urlPath)\n if (!filePath.startsWith(clientDir)) {\n res.writeHead(403)\n res.end('Forbidden')\n return true\n }\n\n if (!existsSync(filePath)) return false\n\n const stat = statSync(filePath)\n if (!stat.isFile()) return false\n\n const ext = extname(filePath)\n const contentType = MIME_TYPES[ext] ?? 'application/octet-stream'\n const content = readFileSync(filePath)\n\n res.writeHead(200, {\n 'Content-Type': contentType,\n 'Content-Length': content.length,\n })\n res.end(content)\n return true\n}\n","/**\n * SSR setup stage for `theokit start` (T4.2 architecture-cleanup).\n *\n * Loads the SSR entry-server module if configured + builds template split\n * around the React root div. Returns null renderers when SSR is disabled.\n */\n\nimport type { ServerResponse } from 'node:http'\n\nimport { resolveSsrEntry } from './start-bootstrap-stages.js'\n\nexport interface SsrRenderResult {\n html: string\n hydrationData: {\n loaderData?: unknown\n actionData?: unknown\n errors?: unknown\n }\n}\n\nexport type RenderStreamingResult = { redirect: Response } | { streaming: true } | undefined\n\nexport type SsrRender = (\n url: string,\n options?: { nonce?: string },\n) => Promise<SsrRenderResult | { redirect: Response } | string>\n\nexport type SsrRenderStreaming = (\n url: string,\n response: ServerResponse,\n options?: { signal?: AbortSignal; nonce?: string },\n) => Promise<RenderStreamingResult>\n\nexport interface SsrSetupResult {\n enabled: boolean\n streamingEnabled: boolean\n render: SsrRender | null\n renderStreaming: SsrRenderStreaming | null\n htmlHead: string\n htmlTail: string\n}\n\nexport function isSsrRenderResult(value: unknown): value is SsrRenderResult {\n if (typeof value !== 'object' || value === null) return false\n if (!('html' in value)) return false\n const html = (value as Record<string, unknown>).html\n if (typeof html !== 'string') return false\n return true\n}\n\ninterface SsrEntryServer {\n render: SsrRender\n renderStreaming?: SsrRenderStreaming\n}\n\nexport async function setupSsr(opts: {\n distDir: string\n indexHtml: string\n ssrConfigEnabled: boolean\n ssrStreamingConfig: boolean | undefined\n}): Promise<SsrSetupResult> {\n const ssrServerPath: string | null = opts.ssrConfigEnabled ? resolveSsrEntry(opts.distDir) : null\n const enabled = ssrServerPath !== null\n const streamingEnabled = enabled && Boolean(opts.ssrStreamingConfig)\n\n if (ssrServerPath === null) {\n return {\n enabled: false,\n streamingEnabled: false,\n render: null,\n renderStreaming: null,\n htmlHead: '',\n htmlTail: '',\n }\n }\n\n const mod = (await import(ssrServerPath)) as SsrEntryServer\n const render = mod.render\n const renderStreaming = typeof mod.renderStreaming === 'function' ? mod.renderStreaming : null\n\n // Split HTML template on root div\n let htmlHead = ''\n let htmlTail = ''\n const rootDivMatch = /<div id=[\"']root[\"'][^>]*>/.exec(opts.indexHtml)\n if (rootDivMatch) {\n const splitIdx = opts.indexHtml.indexOf(rootDivMatch[0]) + rootDivMatch[0].length\n htmlHead = opts.indexHtml.slice(0, splitIdx)\n htmlTail = opts.indexHtml.slice(splitIdx)\n }\n\n return { enabled, streamingEnabled, render, renderStreaming, htmlHead, htmlTail }\n}\n","/**\n * WebSocket upgrade handler for `theokit start` (T4.2 architecture-cleanup).\n *\n * Wires `server.on('upgrade')` for declared WS routes. Opt-in: only attached\n * when `wsRoutes.length > 0`. Lazy-imports `ws` package — throws an actionable\n * error when wsRoutes declared but `ws` not installed.\n */\n\nimport type { Server as HttpServer } from 'node:http'\n\nimport type * as WsLib from 'ws'\n\nimport type { WebSocketHandler } from '../../server/define/define-websocket.js'\nimport type { LoadModule } from '../../server/scan/module-loader.js'\nimport type { WebSocketRouteNode } from '../../server/scan/ws-scan.js'\n\nexport async function attachWebSocketHandler(\n server: HttpServer,\n wsRoutes: WebSocketRouteNode[],\n loadModule: LoadModule,\n): Promise<void> {\n if (wsRoutes.length === 0) return\n\n let WebSocketServerCtor: typeof WsLib.WebSocketServer\n try {\n const wsModule = await import('ws')\n WebSocketServerCtor = wsModule.WebSocketServer\n } catch {\n throw new Error('WebSocket routes found but \"ws\" package is not installed. Run: npm install ws')\n }\n\n const wss = new WebSocketServerCtor({ noServer: true })\n\n server.on('upgrade', (request, socket, head) => {\n void (async () => {\n const url = request.url ?? '/'\n if (!url.startsWith('/ws/')) {\n socket.destroy()\n return\n }\n\n const wsPath = url.split('?')[0]\n const match = wsRoutes.find((r) => r.wsPath === wsPath)\n if (!match) {\n socket.destroy()\n return\n }\n\n try {\n const mod = await loadModule(match.filePath)\n const handler = ((mod as { default?: unknown }).default ?? mod) as WebSocketHandler\n\n wss.handleUpgrade(request, socket, head, (ws) => {\n handler.onOpen?.(ws, request)\n ws.on('message', (data: Buffer) => {\n handler.onMessage?.(ws, data.toString())\n })\n ws.on('close', (code: number, reason: Buffer) => {\n handler.onClose?.(ws, code, reason)\n })\n ws.on('error', (err: Error) => {\n handler.onError?.(ws, err)\n })\n })\n } catch {\n socket.destroy()\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,QAAAC,OAAM,WAAAC,gBAAe;;;ACF9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAgBxB,eAAsB,iCACpB,gBACe;AACf,MAAI,mBAAmB,OAAW;AAClC,MAAI;AACF,UAAM,MAAO,MAAM,OAAO,oBAAc,EAAE,MAAM,MAA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AS;AAAA,IACb,qBAAqB;AAAA,MACnB,UAAU,CAAC,KAAK,KAAK,WAAW,eAAkC;AAAA,QAChE;AAAA,QACA;AAAA,QACA,KAAK,IAAI,OAAO;AAAA,QAChB;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,UAAU,OAAO,UAAU,QAAQ;AAAA,QACnC,YAAY,OAAO,UAAU;AAAA,QAC7B;AAAA,MACF;AAAA,MACA,uBAAuB,OAAO,UAAU,WAAW,CAAC;AAAA,MACpD,WAAW,IAAI;AAAA,MACf,oBAAoB,IAAI;AAAA,MACxB,qBAAqB,IAAI;AAAA,MACzB,UAAU,IAAI;AAAA,MACd,UAAU,IAAI;AAAA,MACd;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,QAAM,uBAAuB,QAAQ,gBAAgB,UAAU;AAE/D,SAAO,OAAO,MAAM,MAAM;AACxB,YAAQ,IAAI;AAAA,yBAA4B;AACxC,YAAQ,IAAI,6BAAwB,OAAO,IAAI,CAAC;AAAA,CAAI;AAAA,EACtD,CAAC;AAED,0BAAwB,MAAM;AAChC;","names":["existsSync","readFileSync","join","resolve","existsSync","existsSync","extname","existsSync","resolve","extname","resolve","existsSync","readFileSync","join"]}
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
+ import {
4
+ nodeAdapter
5
+ } from "./chunk-ZJW5FFYJ.js";
3
6
  import {
4
7
  scanRoutes
5
8
  } from "./chunk-O7335ZGH.js";
6
- import {
7
- nodeAdapter
8
- } from "./chunk-Y5KE6YFP.js";
9
9
  import {
10
10
  assertServicesUnsupported,
11
11
  readManifest
@@ -226,4 +226,4 @@ export {
226
226
  detectApiRoutes,
227
227
  staticAdapter
228
228
  };
229
- //# sourceMappingURL=static-BH6JQNM2.js.map
229
+ //# sourceMappingURL=static-TZBVBDTB.js.map
@@ -230,6 +230,9 @@ async function upgradeReadinessCommand(opts) {
230
230
  if (report.violations.length === 0) {
231
231
  console.log(" \u2713 Upgrade-readiness 0.3: no violations detected.");
232
232
  console.log("");
233
+ console.log(" Migration guide: https://theokit.dev/migration/0.2-to-0.3");
234
+ console.log(" Need to roll back temporarily? See #rollback");
235
+ console.log("");
233
236
  process.exit(report.exitCode);
234
237
  }
235
238
  console.log(` \u2717 Upgrade-readiness 0.3: ${report.violations.length} violation(s)`);
@@ -240,10 +243,12 @@ async function upgradeReadinessCommand(opts) {
240
243
  console.log(` fix: ${v.fix}`);
241
244
  console.log("");
242
245
  }
246
+ console.log(" Migration guide: https://theokit.dev/migration/0.2-to-0.3#rollback");
247
+ console.log("");
243
248
  process.exit(report.exitCode);
244
249
  }
245
250
  export {
246
251
  scanUpgradeReadiness,
247
252
  upgradeReadinessCommand
248
253
  };
249
- //# sourceMappingURL=upgrade-readiness-OHL36FQL.js.map
254
+ //# sourceMappingURL=upgrade-readiness-Q46KTG2J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/upgrade-readiness.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * CLI lint scanner. Reads user source files under `projectRoot` (CLI\n * argument resolved to absolute). Read-only; never writes. No HTTP input.\n */\nimport { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'\nimport { resolve, relative, sep } from 'node:path'\n\n/**\n * T2.3 — Upgrade-readiness scanner for the 0.2 → 0.3 cutover.\n *\n * LINT-only. Reads user source, reports anticipated 0.3.0 violations with\n * file:line + suggested fix. NEVER writes user files (ADR D1).\n *\n * Three rules:\n * 1. csrf-missing-header — raw fetch POST/PUT/PATCH/DELETE missing the\n * X-Theo-Action: '1' header → 403 under strict CSRF.\n * 2. inline-script — <script>...</script> in .html files without\n * `src=` attribute → blocked under enforce CSP without unsafe-inline.\n * 3. dangerously-set-inline-script — React `dangerouslySetInnerHTML`\n * payload that contains <script>.\n *\n * EC-7: occurrences inside line comments (// ...) or wrapped in quoted\n * strings are best-effort skipped. The scanner is not a parser — it\n * filters obvious false-positive lines before running the violation\n * regex.\n * EC-8: scanning a directory with no `app/` and no `server/` returns a\n * 'no-project-detected' report with exitCode 0 (no crash).\n */\n\nexport type ViolationRule =\n | 'csrf-missing-header'\n | 'inline-script'\n | 'dangerously-set-inline-script'\n | 'zero-config-tailwind-suggest'\n | 'handrolled-dotenv-suggest'\n\nexport interface Violation {\n file: string\n line: number\n rule: ViolationRule\n message: string\n fix: string\n}\n\nexport type ReadinessStatus =\n | 'ready'\n | 'has-violations'\n | 'no-project-detected'\n | 'not-a-theokit-project'\n\nexport interface UpgradeReadinessReport {\n status: ReadinessStatus\n exitCode: 0 | 1\n violations: Violation[]\n}\n\nexport interface ScanOptions {\n cwd: string\n /** When true, exitCode is forced to 0 even when violations exist. */\n allowWarnings?: boolean\n}\n\nconst SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next', '.theokit', '.cache'])\nconst SOURCE_EXTS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'])\nconst HTML_EXTS = new Set(['.html', '.htm'])\n\nfunction walkFiles(dir: string, root: string, out: string[]): void {\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n return\n }\n for (const name of entries) {\n if (SKIP_DIRS.has(name)) continue\n const full = resolve(dir, name)\n let s\n try {\n s = statSync(full)\n } catch {\n continue\n }\n if (s.isDirectory()) {\n walkFiles(full, root, out)\n } else if (s.isFile()) {\n const dot = name.lastIndexOf('.')\n if (dot < 0) continue\n const ext = name.slice(dot)\n if (SOURCE_EXTS.has(ext) || HTML_EXTS.has(ext)) out.push(full)\n }\n }\n}\n\nfunction isLikelyCommentOrString(rawLine: string, matchIndex: number): boolean {\n // Comment: line-comment marker (//) appears before the match position.\n const lineCommentIdx = rawLine.indexOf('//')\n if (lineCommentIdx !== -1 && lineCommentIdx < matchIndex) {\n // Make sure // is not inside a string (best-effort: count unescaped\n // quote chars before the //)\n const before = rawLine.slice(0, lineCommentIdx)\n const quoteCount = (before.match(/(?<!\\\\)[\"']/g) ?? []).length\n if (quoteCount % 2 === 0) return true\n }\n // String literal: scan quote characters around match. If the match is\n // surrounded by an odd number of unescaped quotes on either side, it\n // sits inside a string. Best-effort — does not parse template literals\n // or multiline strings.\n const before = rawLine.slice(0, matchIndex)\n const doubleQuotes = (before.match(/(?<!\\\\)\"/g) ?? []).length\n const singleQuotes = (before.match(/(?<!\\\\)'/g) ?? []).length\n return doubleQuotes % 2 === 1 || singleQuotes % 2 === 1\n}\n\n// `fetch(` followed (within ~200 chars, same call site) by a method:\n// 'POST' | 'PUT' | 'PATCH' | 'DELETE'. We scan per-line to keep regex\n// state simple; multi-line fetch calls match on the line that carries\n// the `method:` literal.\nconst METHOD_PATTERN = /method\\s*:\\s*['\"`](POST|PUT|PATCH|DELETE)['\"`]/gi\n\nfunction scanSourceFile(file: string, rel: string, content: string, out: Violation[]): void {\n const lines = content.split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n METHOD_PATTERN.lastIndex = 0\n const match = METHOD_PATTERN.exec(line)\n if (!match) continue\n if (isLikelyCommentOrString(line, match.index)) continue\n\n // Look 8 lines back AND forward for the enclosing `fetch(` and for an\n // X-Theo-Action header in the same call-site block.\n const blockStart = Math.max(0, i - 8)\n const blockEnd = Math.min(lines.length - 1, i + 8)\n const block = lines.slice(blockStart, blockEnd + 1).join('\\n')\n if (!/\\bfetch\\s*\\(/.test(block)) continue\n if (/\\btheoFetch\\s*\\(/.test(block)) continue\n if (/['\"`]X-Theo-Action['\"`]\\s*:/i.test(block)) continue\n\n out.push({\n file: rel,\n line: i + 1,\n rule: 'csrf-missing-header',\n message:\n 'fetch(' +\n match[1] +\n ') without X-Theo-Action header — will return 403 under 0.3.0 strict CSRF',\n fix: \"Use theoFetch(path, { method, body }) OR add headers: { 'X-Theo-Action': '1' }\",\n })\n }\n\n // dangerouslySetInnerHTML with <script> in the payload.\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (!/dangerouslySetInnerHTML/i.test(line)) continue\n // The script may live on the same line or in __html on a following\n // line; check a small window.\n const window = lines.slice(i, Math.min(lines.length, i + 6)).join('\\n')\n if (!/__html\\s*:\\s*['\"`][^'\"`]*<script\\b/i.test(window)) continue\n out.push({\n file: rel,\n line: i + 1,\n rule: 'dangerously-set-inline-script',\n message:\n 'dangerouslySetInnerHTML payload contains <script> — blocked under 0.3.0 enforce CSP',\n fix: 'Move the script into a real module loaded via <script src=\"...\">, or thread ctx.nonce',\n })\n }\n}\n\nconst INLINE_SCRIPT_PATTERN = /<script\\b(?![^>]*\\bsrc\\s*=)[^>]*>[\\s\\S]*?<\\/script>/gi\n\nfunction scanHtmlFile(file: string, rel: string, content: string, out: Violation[]): void {\n INLINE_SCRIPT_PATTERN.lastIndex = 0\n let match: RegExpExecArray | null\n while ((match = INLINE_SCRIPT_PATTERN.exec(content)) !== null) {\n // Compute 1-based line number from match index.\n const before = content.slice(0, match.index)\n const line = (before.match(/\\n/g) ?? []).length + 1\n out.push({\n file: rel,\n line,\n rule: 'inline-script',\n message:\n 'Inline <script> without src — blocked under 0.3.0 enforce CSP without unsafe-inline',\n fix: \"Move into a real script file (e.g. /main.js) and load with <script src='/main.js'>, or thread ctx.nonce\",\n })\n }\n}\n\n/**\n * T4.1 — Zero-config hint: consumer has @usetheo/ui in deps AND a manual\n * tailwind.config.* that does NOT import the @usetheo/ui preset. Suggest\n * extending via `import preset from '@usetheo/ui/preset'`.\n */\nfunction scanZeroConfigTailwindHint(cwd: string, out: Violation[]): void {\n const pkgPath = resolve(cwd, 'package.json')\n if (!existsSync(pkgPath)) return\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as typeof pkg\n } catch {\n return\n }\n const hasUi =\n Boolean(pkg.dependencies?.['@usetheo/ui']) || Boolean(pkg.devDependencies?.['@usetheo/ui'])\n if (!hasUi) return\n\n for (const ext of ['.ts', '.js', '.mjs', '.cjs']) {\n const cfgPath = resolve(cwd, `tailwind.config${ext}`)\n if (!existsSync(cfgPath)) continue\n let content: string\n try {\n content = readFileSync(cfgPath, 'utf8')\n } catch {\n continue\n }\n if (content.includes('@usetheo/ui/preset')) return // already using preset\n out.push({\n file: `tailwind.config${ext}`,\n line: 1,\n rule: 'zero-config-tailwind-suggest',\n message:\n '@usetheo/ui detected with a manual tailwind.config — extend with the UI preset to keep theme tokens in sync.',\n fix: \"import preset from '@usetheo/ui/preset'; export default { presets: [preset], content: [...] }\",\n })\n return\n }\n}\n\n/**\n * T4.1 — Zero-config hint: consumer has hand-rolled dotenv loading in\n * server/ (import 'dotenv/config', dotenv.config(), readFile('.env'), etc.).\n * Suggest the framework's loadEnv (auto-invoked by CLI commands; importable\n * from theokit/server for standalone scripts).\n */\nfunction scanHandRolledDotenvHint(\n file: string,\n rel: string,\n content: string,\n out: Violation[],\n): void {\n // Only flag server/ files\n if (!rel.startsWith('server/')) return\n const lines = content.split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? ''\n // import 'dotenv/config' or import * as dotenv from 'dotenv'\n if (/from\\s+['\"]dotenv['\"]/.test(line) || /import\\s+['\"]dotenv\\/config['\"]/.test(line)) {\n out.push({\n file: rel,\n line: i + 1,\n rule: 'handrolled-dotenv-suggest',\n message:\n 'Manual dotenv import detected — TheoKit auto-loads .env in CLI commands. For standalone scripts, import { loadEnv } from \"theokit/server\".',\n fix: \"Remove this import. CLI commands (dev/build/start) auto-load .env. For standalone scripts: import { loadEnv } from 'theokit/server'; loadEnv()\",\n })\n return // one hint per file\n }\n }\n}\n\n/**\n * EC-3: a directory may have an `app/` directory (Next.js, Remix, etc.) but\n * not actually be a TheoKit project. Run our 3 rules against such a project\n * would generate many false positives. The strict guard checks for `theokit`\n * in dependencies OR devDependencies of the cwd's package.json. Returns\n * `null` when the project IS a TheoKit project, or a non-TheoKit report\n * otherwise.\n */\nfunction detectNonTheokitProject(cwd: string): UpgradeReadinessReport | null {\n const pkgPath = resolve(cwd, 'package.json')\n if (!existsSync(pkgPath)) {\n // No package.json — let the existing app/server detection handle it.\n return null\n }\n let pkg: { dependencies?: Record<string, string>; devDependencies?: Record<string, string> }\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as typeof pkg\n } catch {\n // Malformed package.json — treat as \"not a TheoKit project we can verify\".\n return { status: 'not-a-theokit-project', exitCode: 1, violations: [] }\n }\n const deps = pkg.dependencies ?? {}\n const devDeps = pkg.devDependencies ?? {}\n if (!Object.hasOwn(deps, 'theokit') && !Object.hasOwn(devDeps, 'theokit')) {\n return { status: 'not-a-theokit-project', exitCode: 1, violations: [] }\n }\n return null\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- async surface for future fs.promises migration\nexport async function scanUpgradeReadiness(options: ScanOptions): Promise<UpgradeReadinessReport> {\n const cwd = options.cwd\n const allowWarnings = options.allowWarnings === true\n\n const appDir = resolve(cwd, 'app')\n const serverDir = resolve(cwd, 'server')\n const publicDir = resolve(cwd, 'public')\n\n const hasApp = existsSync(appDir)\n const hasServer = existsSync(serverDir)\n\n if (!hasApp && !hasServer) {\n return { status: 'no-project-detected', exitCode: 0, violations: [] }\n }\n\n // EC-3: refuse to scan non-TheoKit projects (avoid FP avalanche).\n const nonTheokit = detectNonTheokitProject(cwd)\n if (nonTheokit) return nonTheokit\n\n const files: string[] = []\n if (hasApp) walkFiles(appDir, cwd, files)\n if (hasServer) walkFiles(serverDir, cwd, files)\n if (existsSync(publicDir)) walkFiles(publicDir, cwd, files)\n\n const violations: Violation[] = []\n for (const file of files) {\n let content: string\n try {\n content = readFileSync(file, 'utf8')\n } catch {\n continue\n }\n const rel = relative(cwd, file).split(sep).join('/')\n const dot = file.lastIndexOf('.')\n const ext = dot >= 0 ? file.slice(dot) : ''\n if (HTML_EXTS.has(ext)) {\n scanHtmlFile(file, rel, content, violations)\n } else if (SOURCE_EXTS.has(ext)) {\n scanSourceFile(file, rel, content, violations)\n scanHandRolledDotenvHint(file, rel, content, violations)\n }\n }\n\n // T4.1 — Project-level hint (not per-file): does the consumer have a\n // manual tailwind.config without the UI preset?\n scanZeroConfigTailwindHint(cwd, violations)\n\n const hasHigh = violations.length > 0\n const status: ReadinessStatus = hasHigh ? 'has-violations' : 'ready'\n const exitCode: 0 | 1 = hasHigh && !allowWarnings ? 1 : 0\n return { status, exitCode, violations }\n}\n\n/**\n * CLI wrapper. Prints a human-readable or JSON report and exits with the\n * computed exit code. Imported lazily from `cli/index.ts`.\n */\nexport async function upgradeReadinessCommand(opts: {\n json?: boolean\n allowWarnings?: boolean\n}): Promise<void> {\n const report = await scanUpgradeReadiness({\n cwd: process.cwd(),\n allowWarnings: opts.allowWarnings,\n })\n\n if (opts.json) {\n console.log(JSON.stringify(report, null, 2))\n process.exit(report.exitCode)\n }\n\n console.log('')\n if (report.status === 'no-project-detected') {\n console.log(\" · No theokit project detected here (no 'app/' or 'server/' dir).\")\n console.log('')\n process.exit(report.exitCode)\n }\n if (report.status === 'not-a-theokit-project') {\n console.log(' ✗ Not a TheoKit project (theokit not in package.json).')\n console.log(' Run this command from a TheoKit project root.')\n console.log('')\n process.exit(report.exitCode)\n }\n if (report.violations.length === 0) {\n console.log(' ✓ Upgrade-readiness 0.3: no violations detected.')\n console.log('')\n // T1.3 — friendly post-success URL (blueprint R4; Next.js next-codemod precedent).\n // Anchor canon: #rollback (existing in docs/migration/0.2-to-0.3.md per T1.1).\n console.log(' Migration guide: https://theokit.dev/migration/0.2-to-0.3')\n console.log(' Need to roll back temporarily? See #rollback')\n console.log('')\n process.exit(report.exitCode)\n }\n console.log(` ✗ Upgrade-readiness 0.3: ${report.violations.length} violation(s)`)\n console.log('')\n for (const v of report.violations) {\n console.log(` ${v.file}:${v.line} [${v.rule}]`)\n console.log(` ${v.message}`)\n console.log(` fix: ${v.fix}`)\n console.log('')\n }\n // T1.3 — print migration-guide URL on violations branch too (one canonical link\n // regardless of verdict, per blueprint Q5 Astro CHANGELOG URL patt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.js";
6
6
  import {
7
7
  assertServicesUnsupported,
8
8
  readManifest
@@ -131,4 +131,4 @@ export {
131
131
  renderVercelVcConfigJson,
132
132
  vercelAdapter
133
133
  };
134
- //# sourceMappingURL=vercel-RHADE5IP.js.map
134
+ //# sourceMappingURL=vercel-MWW24ABC.js.map
@@ -1,5 +1,5 @@
1
1
  import { Plugin } from 'vite';
2
- import { R as RateLimitConfig, S as ServicesConfig } from '../schema-Cxq2qqwh.js';
2
+ import { R as RateLimitConfig, S as ServicesConfig, C as CsrfReadinessStore } from '../schema-CjVly9c_.js';
3
3
  import 'node:http';
4
4
  import '../rate-limit-store-BEJnhWdw.js';
5
5
  import 'zod';
@@ -67,6 +67,30 @@ interface TheoPluginOptions {
67
67
  * per service with an OpenAPI URL. Empty `{}` → no-op.
68
68
  */
69
69
  services?: ServicesConfig;
70
+ /**
71
+ * T4.1 (canvas-ecosystem-refactor / ADR D6) — extra package names appended
72
+ * to Vite `optimizeDeps.include`. Required when an installed plugin
73
+ * peer-dep is consumed via a literal `import('<pkg>')` (dynamic specifier)
74
+ * — Vite cannot trace those without a hint, and the browser receives a
75
+ * `Failed to resolve module specifier '<pkg>'` error.
76
+ *
77
+ * Default targets pre-bundled regardless: `@usetheo/ui`, `lucide-react`.
78
+ *
79
+ * Example:
80
+ * viteOptimizeDeps: ['mermaid']
81
+ */
82
+ viteOptimizeDeps?: string[];
83
+ /**
84
+ * Optional override for the in-memory CSRF readiness store consumed by
85
+ * the `/__theo/csrf-readiness` endpoint and the devtools CSRF Readiness
86
+ * tab. When omitted, the plugin auto-instantiates a default in-process
87
+ * `CsrfReadinessStore` so the tab works out-of-the-box in dev.
88
+ *
89
+ * Override with a custom impl when you need cross-worker telemetry
90
+ * (e.g., Redis-backed store) or want to silence the tab entirely
91
+ * (pass an inert store that discards writes).
92
+ */
93
+ csrfReadinessStore?: CsrfReadinessStore;
70
94
  }
71
95
  /**
72
96
  * Async factory companion. Returns `[theoPlugin, ...autoChainedPlugins]`.
@@ -5,13 +5,16 @@ import {
5
5
  defineTheoIntegration,
6
6
  theoPlugin,
7
7
  theoPluginAsync
8
- } from "../chunk-FRBYJANT.js";
8
+ } from "../chunk-M6MYZSD2.js";
9
9
  import "../chunk-7BIM27LV.js";
10
10
  import "../chunk-O4BLVPML.js";
11
- import "../chunk-OEB3OIYP.js";
11
+ import "../chunk-OJHO2X7C.js";
12
+ import "../chunk-2BQYEBCK.js";
13
+ import "../chunk-7DHGV77J.js";
12
14
  import "../chunk-PB4GR7EP.js";
13
15
  import "../chunk-GY5Q27BJ.js";
14
16
  import "../chunk-X2VVCJ4V.js";
17
+ import "../chunk-WSJKACWB.js";
15
18
  import "../chunk-DGUM43GV.js";
16
19
  export {
17
20
  IntegrationRouteCollisionError,
@@ -7,14 +7,15 @@ import {
7
7
  defineTheoIntegration,
8
8
  theoPlugin,
9
9
  theoPluginAsync
10
- } from "./chunk-ZK5JCE5J.js";
11
- import "./chunk-WQCPKA2L.js";
12
- import "./chunk-GQSTRXXB.js";
13
- import "./chunk-S3JBIFKS.js";
14
- import "./chunk-3Q36SEDK.js";
10
+ } from "./chunk-EXJWO2HB.js";
11
+ import "./chunk-C27AZN46.js";
12
+ import "./chunk-MG7H3LAW.js";
13
+ import "./chunk-ZBWROIIO.js";
15
14
  import "./chunk-5ODOE6EF.js";
16
15
  import "./chunk-O7335ZGH.js";
17
16
  import "./chunk-WZ7CPVQB.js";
17
+ import "./chunk-QLGES2HC.js";
18
+ import "./chunk-MOT42NAH.js";
18
19
  import "./chunk-KT3MWNZG.js";
19
20
  export {
20
21
  IntegrationRouteCollisionError,
@@ -24,4 +25,4 @@ export {
24
25
  theoPlugin,
25
26
  theoPluginAsync
26
27
  };
27
- //# sourceMappingURL=vite-plugin-WA3G45YY.js.map
28
+ //# sourceMappingURL=vite-plugin-4WZ3C2AC.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theokit",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "scripts": {
@@ -63,17 +63,19 @@
63
63
  "busboy": "^1.6.0",
64
64
  "cac": "^6.7.14",
65
65
  "cron-parser": "^5.5.0",
66
+ "devalue": "^5.6.4",
66
67
  "dotenv": "^16.4.5",
67
68
  "dotenv-expand": "^11.0.6",
68
69
  "goober": "^2.1.16",
69
70
  "picomatch": "^4.0.0",
70
71
  "superjson": "^2.2.6",
71
72
  "tsx": "^4.19.0",
73
+ "typescript": "^5.0.0",
72
74
  "vite": "^6.0.0",
73
75
  "zod-to-json-schema": "^3.24.0"
74
76
  },
75
77
  "peerDependencies": {
76
- "@usetheo/ui": "^0.12.0-next.0",
78
+ "@usetheo/ui": "^0.13.0",
77
79
  "db0": "^0.3.0",
78
80
  "react": "^19.0.0",
79
81
  "react-dom": "^19.0.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/build.ts","../src/adapters/types.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/cron/cron-scan.ts","../src/server/jobs/job-manifest.ts","../src/server/jobs/job-scan.ts","../src/cli/cleanup/cleanup.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\n// T1.1 (architecture-medium-deferrals) — nodeAdapter no longer static-imported.\n// All adapters dispatch via `adapterRegistry` (lazy-imported within runAdapterBuild).\nimport { VALID_TARGETS, type BuildTarget, type AdapterBuildContext } from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../core/validate-structure.js'\nimport {\n ExistingConfigUnparseableError,\n translateCronToAws,\n translateCronToCloudflare,\n translateCronToDeno,\n translateCronToVercel,\n} from '../../server/cron/adapter-translators.js'\nimport { writeCronManifest } from '../../server/cron/cron-manifest.js'\nimport { scanCrons } from '../../server/cron/cron-scan.js'\nimport { writeJobManifest } from '../../server/jobs/job-manifest.js'\nimport { scanJobs } from '../../server/jobs/job-scan.js'\nimport { generateManifest, writeManifest } from '../../server/scan/manifest.js'\nimport {\n buildManifest as buildServicesManifest,\n writeManifest as writeServicesManifest,\n} from '../../services/index.js'\nimport { cleanOutDir } from '../cleanup/cleanup.js'\n\n// Adapters that do NOT support cron triggers natively. Build still\n// succeeds with crons declared, but emits a warning + skip note.\nconst CRON_NA_TARGETS = new Set<BuildTarget>(['bun', 'netlify', 'static'])\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n validateProjectStructure(cwd)\n\n // T2.2 — Clean .theo/ at build start (Astro pattern). Skip .git*.\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanOutDir({ dir: distDirAbs })\n\n const target = (options?.target ?? 'node') as BuildTarget\n\n if (!VALID_TARGETS.includes(target)) {\n throw new Error(\n `Invalid build target \"${target}\". Available targets: ${VALID_TARGETS.join(', ')}`,\n )\n }\n\n // EC-201 — cross-reference note when config.adapters[] diverges from\n // the --target flag. --target is authoritative per ADR D2.\n const configAdapters = (config as { adapters?: readonly string[] }).adapters\n if (configAdapters && configAdapters.length > 0) {\n const otherAdapters = configAdapters.filter((a) => a !== target)\n if (otherAdapters.length > 0) {\n console.log(\n `\\n Note: theo.config.ts.adapters lists [${otherAdapters.join(', ')}]; ` +\n `this build translates for ${target} only. ` +\n `Run \\`theokit build --target=<adapter>\\` separately for each (cross-reference).`,\n )\n }\n }\n\n console.log(`\\n Building for ${target}...\\n`)\n\n // Manifests emit BEFORE adapter bundling (Vite). Why: manifests are\n // fast + deterministic + don't depend on Vite. If Vite fails (missing\n // dep, malformed entry), the user still gets manifests for diagnostics.\n const serverDir = resolve(cwd, config.serverDir)\n const distDir = distDirAbs\n const manifest = generateManifest(serverDir)\n writeManifest(manifest, distDir)\n\n const totalEndpoints =\n manifest.routes.length + manifest.actions.length + manifest.websockets.length\n console.log(\n ` ✓ Manifest: ${manifest.routes.length} routes, ${manifest.actions.length} actions, ${manifest.websockets.length} ws (${totalEndpoints} total)`,\n )\n\n // T1.1 — cron scan + manifest + per-target adapter translation\n await emitCronArtifacts({ cwd, serverDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theo/services.json. Always\n // emit (empty array when services: {} is empty) so adapters can rely on\n // the file existing. Topological order preserved by buildServicesManifest.\n const servicesManifest = buildServicesManifest(config.services)\n writeServicesManifest(cwd, servicesManifest)\n if (servicesManifest.services.length > 0) {\n console.log(\n ` ✓ Services manifest: ${String(servicesManifest.services.length)} service(s) ` +\n `(${servicesManifest.services.map((s) => s.name).join(', ')})`,\n )\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd)\n\n const ssrNote = config.ssr ? ' (SSR)' : ''\n console.log(`\\n ✓ Build complete → ${target}${ssrNote}\\n`)\n}\n\nasync function runAdapterBuild(\n target: BuildTarget,\n config: Awaited<ReturnType<typeof loadConfig>>,\n cwd: string,\n): Promise<void> {\n // T1.1 (architecture-cleanup) — CLI composes the Vite Plugin[] and INJECTS it into\n // the adapter via ctx.makeVitePlugins. This inverts the previous `adapters → vite-plugin`\n // edge — adapters no longer import from vite-plugin/ directly.\n //\n // theoPlugin AND `@vitejs/plugin-react` are dynamically imported so the deps are\n // materialized only when needed (adapter is `node`). This keeps the CLI's startup\n // path independent of optional build-time deps (so e.g. `theokit build --target=static`\n // does not need react installed). dep-cruiser's per-module rule allows `cli → vite-plugin`.\n const { theoPlugin } = await import('../../vite-plugin/index.js')\n const { default: react } = await import('@vitejs/plugin-react')\n const ctx: AdapterBuildContext = {\n // `react()` may return Plugin or Plugin[] depending on version; flatten so the\n // contract returns a flat Plugin[] as declared in AdapterBuildContext.\n makeVitePlugins: (opts) => [react(), theoPlugin(opts)].flat(),\n }\n\n // T1.1 (architecture-medium-deferrals, ADR D1) — Adapter Registry replaces\n // the previous 9-case switch. New adapters add 1 line in `adapters/registry.ts`;\n // CLI is closed for modification (OCP).\n const { resolveAdapter } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n const cronsDir = resolve(opts.serverDir, 'crons')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- known-internal path under project's own serverDir\n const cronNodes = existsSync(cronsDir) ? await scanCrons(cronsDir) : []\n const manifestPath = resolve(opts.distDir, 'crons.json')\n writeCronManifest(manifestPath, cronNodes, opts.cwd)\n\n console.log(` ✓ Crons: ${cronNodes.length} declared`)\n\n if (cronNodes.length === 0) return\n\n // EC-201: target-specific translation. N/A targets emit a warning + skip.\n if (CRON_NA_TARGETS.has(opts.target)) {\n console.log(\n ` ⚠ Cron not supported by target \"${opts.target}\" — declared crons skipped. ` +\n `See docs/concepts/crons.md for supported targets.`,\n )\n return\n }\n\n const manifestEntries = cronNodes.map((n) => ({\n name: n.name,\n filePath: relativize(n.filePath, opts.cwd),\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n\n try {\n switch (opts.target) {\n case 'vercel':\n translateCronToVercel(resolve(opts.cwd, 'vercel.json'), manifestEntries)\n console.log(` ✓ Cron → vercel.json crons[] (${cronNodes.length} entries)`)\n break\n case 'cloudflare':\n translateCronToCloudflare(resolve(opts.cwd, 'wrangler.toml'), manifestEntries)\n console.log(` ✓ Cron → wrangler.toml [triggers] (${cronNodes.length})`)\n break\n case 'aws-lambda':\n translateCronToAws(resolve(opts.cwd, 'serverless.yml'), manifestEntries)\n console.log(` ✓ Cron → serverless.yml functions (${cronNodes.length})`)\n break\n case 'deno-deploy':\n translateCronToDeno(resolve(opts.distDir, 'crons-entry.ts'), manifestEntries)\n console.log(` ✓ Cron → ${opts.distDir}/crons-entry.ts (Deno.cron)`)\n break\n case 'node':\n console.log(` ✓ Cron → in-process scheduler (theokit start)`)\n break\n }\n } catch (err) {\n if (err instanceof ExistingConfigUnparseableError) throw err\n throw err\n }\n}\n\nasync function emitJobArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n}): Promise<void> {\n const jobsDir = resolve(opts.serverDir, 'jobs')\n // eslint-disable-next-line security/detect-non-literal-fs-filename -- known-internal path under project's own serverDir\n const jobNodes = existsSync(jobsDir) ? await scanJobs(jobsDir) : []\n const manifestPath = resolve(opts.distDir, 'jobs.json')\n writeJobManifest(manifestPath, jobNodes, opts.cwd)\n console.log(` ✓ Jobs: ${jobNodes.length} declared`)\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","import type { Plugin } from 'vite'\n\nimport type { TheoConfig } from '../config/schema.js'\n\n/**\n * Build context injected by the CLI into adapter.build.\n *\n * - `makeVitePlugins` — optional factory provided by CLI for adapters\n * that drive `viteBuild()` directly (currently: `nodeAdapter`).\n * When omitted, adapters that need Vite must fail with an actionable\n * error. This inverts the previous direct edge `adapters → vite-plugin`\n * per ADR-0001 v3 (T1.1 of the architecture-cleanup plan).\n */\nexport interface AdapterBuildContext {\n makeVitePlugins?: (opts: { root: string; ssr?: boolean }) => Plugin[]\n}\n\nexport interface DeployAdapter {\n name: string\n build(config: TheoConfig, cwd: string, ctx?: AdapterBuildContext): Promise<void>\n}\n\nexport type BuildTarget =\n | 'node'\n | 'vercel'\n | 'cloudflare'\n | 'static'\n | 'bun'\n | 'deno-deploy'\n | 'netlify'\n | 'aws-lambda'\n | 'theo-cloud'\n\nexport const VALID_TARGETS: BuildTarget[] = [\n 'node',\n 'vercel',\n 'cloudflare',\n 'static',\n 'bun',\n 'deno-deploy',\n 'netlify',\n 'aws-lambda',\n 'theo-cloud',\n]\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time adapter translators: caller-controlled paths only.\n */\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronManifestEntry } from './cron-manifest.js'\n\n/**\n * Thrown when an existing platform-config file (vercel.json, wrangler.toml,\n * serverless.yml) cannot be parsed. Caller must fix the file before\n * re-running `theokit build`. We NEVER silently overwrite a user's config.\n */\nexport class ExistingConfigUnparseableError extends Error {\n readonly code = 'EXISTING_CONFIG_UNPARSEABLE'\n constructor(\n public readonly filePath: string,\n public readonly parseError: string,\n ) {\n super(\n `Existing config \"${filePath}\" could not be parsed: ${parseError}. ` +\n 'Fix or remove the file before re-running build — TheoKit never silently overwrites user configuration.',\n )\n this.name = 'ExistingConfigUnparseableError'\n }\n}\n\n// ──────────────────────────────────────────────────────────\n// Vercel — vercel.json crons[]\n// ──────────────────────────────────────────────────────────\n\ninterface VercelJson {\n crons?: { path: string; schedule: string }[]\n [key: string]: unknown\n}\n\n/**\n * Translate a TheoKit cron manifest into `vercel.json crons[]`.\n *\n * EC-105: existing fields (functions, headers, redirects, rewrites, env,\n * etc.) are preserved verbatim — ONLY the `crons[]` slice is replaced.\n */\nexport function translateCronToVercel(\n vercelJsonPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n let existing: VercelJson = {}\n if (existsSync(vercelJsonPath)) {\n const raw = readFileSync(vercelJsonPath, 'utf8')\n try {\n existing = JSON.parse(raw) as VercelJson\n } catch (err) {\n throw new ExistingConfigUnparseableError(\n vercelJsonPath,\n err instanceof Error ? err.message : String(err),\n )\n }\n }\n const merged: VercelJson = {\n ...existing,\n crons: crons.map((c) => ({\n path: `/api/__crons/${c.name}`,\n schedule: c.schedule,\n })),\n }\n writeAtomic(vercelJsonPath, JSON.stringify(merged, null, 2))\n}\n\n// ──────────────────────────────────────────────────────────\n// Cloudflare — wrangler.toml [triggers] crons\n// ──────────────────────────────────────────────────────────\n\n/**\n * Translate a TheoKit cron manifest into `wrangler.toml [triggers] crons`.\n *\n * EC-105: regex-based mutation that preserves comments + other sections\n * verbatim. Replaces only the `[triggers]` block (or appends if absent).\n */\nexport function translateCronToCloudflare(\n wranglerTomlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const schedules = crons.map((c) => `\"${c.schedule}\"`).join(', ')\n const triggersBlock = `[triggers]\\ncrons = [${schedules}]\\n`\n\n if (!existsSync(wranglerTomlPath)) {\n writeAtomic(wranglerTomlPath, triggersBlock)\n return\n }\n\n const existing = readFileSync(wranglerTomlPath, 'utf8')\n\n // Replace existing [triggers] section if present. Strategy: split into\n // line array, find the [triggers] header line, drop subsequent lines\n // until the next section header (line starting with `[`) or EOF.\n const lines = existing.split('\\n')\n const triggersIdx = lines.findIndex((l) => l.trim() === '[triggers]')\n\n let next: string\n if (triggersIdx !== -1) {\n let endIdx = lines.length\n for (let i = triggersIdx + 1; i < lines.length; i++) {\n if (lines[i].trim().startsWith('[')) {\n endIdx = i\n break\n }\n }\n const before = lines.slice(0, triggersIdx).join('\\n')\n const after = lines.slice(endIdx).join('\\n')\n next = `${before}\\n${triggersBlock.trimEnd()}\\n${after}`.replace(/\\n{3,}/g, '\\n\\n')\n } else {\n next = existing.endsWith('\\n')\n ? `${existing}\\n${triggersBlock}`\n : `${existing}\\n\\n${triggersBlock}`\n }\n writeAtomic(wranglerTomlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// AWS Lambda — serverless.yml functions.<fn>.events: schedule\n// ──────────────────────────────────────────────────────────\n\n/**\n * Convert TheoKit's 5-field UTC cron to AWS EventBridge's 6-field format.\n * EventBridge requires `?` in EITHER day-of-month OR day-of-week (not both `*`).\n *\n * Algorithm:\n * - If DOM is \"*\" and DOW is \"*\" → insert ? in DOW (default)\n * - If DOM is \"*\" and DOW is specific → insert ? in DOM\n * - If DOM is specific and DOW is \"*\" → insert ? in DOW\n * - Append \"*\" year field at end.\n */\nexport function convertToAwsCron(schedule: string): string {\n const parts = schedule.trim().split(/\\s+/)\n if (parts.length !== 5) {\n throw new Error(`Invalid 5-field schedule for AWS conversion: \"${schedule}\"`)\n }\n const [minute, hour, dom, month, dow] = parts\n let awsDom = dom\n let awsDow = dow\n if (dom === '*' && dow === '*') {\n awsDow = '?'\n } else if (dom === '*') {\n awsDom = '?'\n } else if (dow === '*') {\n awsDow = '?'\n }\n return `cron(${minute} ${hour} ${awsDom} ${month} ${awsDow} *)`\n}\n\n/**\n * Translate a TheoKit cron manifest into a `serverless.yml` functions\n * map with `events: - schedule: cron(...)` entries.\n *\n * EC-105: appends to `functions:` block, preserving all existing\n * functions/sections. Cron functions are named `cron_<name>` to avoid\n * collision with user-declared functions.\n */\nexport function translateCronToAws(\n serverlessYmlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const cronFunctionsYaml = crons\n .map(\n (c) => ` cron_${c.name}:\n handler: .theo/server/crons/${c.name}.handler\n events:\n - schedule: ${convertToAwsCron(c.schedule)}`,\n )\n .join('\\n')\n\n const block = `\\nfunctions:\\n${cronFunctionsYaml}\\n`\n\n if (!existsSync(serverlessYmlPath)) {\n // Minimal serverless.yml scaffold\n writeAtomic(\n serverlessYmlPath,\n `service: theokit-app\\nprovider:\\n name: aws\\n runtime: nodejs22.x\\n${block}`,\n )\n return\n }\n\n const existing = readFileSync(serverlessYmlPath, 'utf8')\n\n // Look for an existing top-level `functions:` block; if present, append our\n // cron entries under it (don't replace user-declared functions).\n const functionsRe = /^functions:\\s*\\n/m\n let next: string\n if (functionsRe.test(existing)) {\n next = existing.replace(functionsRe, (match) => `${match}${cronFunctionsYaml}\\n`)\n } else {\n next = existing.endsWith('\\n') ? `${existing}${block}` : `${existing}\\n${block}`\n }\n writeAtomic(serverlessYmlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// Deno Deploy — Deno.cron registrations\n// ──────────────────────────────────────────────────────────\n\n/**\n * Emit a Deno entry file that registers each cron via `Deno.cron`.\n *\n * Unlike Vercel/CF/AWS, Deno.cron is an in-process runtime API — the\n * entry file is a managed artifact (overwritten each build), not a user\n * config (so EC-105 doesn't apply here).\n */\nexport function translateCronToDeno(entryPath: string, crons: readonly CronManifestEntry[]): void {\n const lines = crons.map(\n (c) =>\n `Deno.cron(\"${c.name}\", \"${c.schedule}\", async () => {\n const mod = await import(\"../${c.filePath}\");\n const def = mod.default;\n await def.handler({\n traceId: crypto.randomUUID().replace(/-/g, \"\"),\n scheduledAt: new Date(),\n signal: AbortSignal.timeout(60_000),\n });\n});`,\n )\n const content = `// AUTOGENERATED by TheoKit cron build — DO NOT EDIT.\n// Source: server/crons/*.ts → .theo/crons.json → this file.\n${lines.join('\\n\\n')}\n`\n writeAtomic(entryPath, content)\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time atomic write: caller-controlled paths only. No HTTP input\n * reaches these fs calls.\n */\nimport { randomBytes } from 'node:crypto'\nimport { mkdirSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\n/**\n * Write `content` to `path` atomically via the tmp + rename pattern.\n *\n * Two concurrent calls to `writeAtomic(path, ...)` are guaranteed to\n * leave `path` containing valid content from ONE of the calls (never\n * truncated, never interleaved). POSIX rename is atomic on the same\n * filesystem.\n *\n * EC-106 (jobs-crons-webhooks-cost-tracking-plan) — shared helper for\n * `.theo/crons.json` and `.theo/jobs.json` manifest writes so a\n * concurrent dev-server scan + build manifest emit never produces\n * partial JSON.\n *\n * @param path destination path\n * @param content bytes (UTF-8 string) to write\n */\nexport function writeAtomic(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n // Include a random suffix so two concurrent writes don't trample each\n // other's tmp file. crypto.randomBytes is non-blocking + collision-safe\n // for the tiny entropy we need (8 hex chars = 32 bits).\n const tmp = `${path}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`\n writeFileSync(tmp, content, 'utf8')\n renameSync(tmp, path)\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronNode } from './cron-scan.js'\n\nexport const CRON_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface CronManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: 'forbid' | 'allow'\n}\n\nexport interface CronManifest {\n readonly schemaVersion: typeof CRON_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly crons: readonly CronManifestEntry[]\n}\n\n/**\n * Build a `CronManifest` from scanned `CronNode[]`. Filepaths are kept\n * relative to the caller's project root for portability.\n */\nexport function buildCronManifest(nodes: readonly CronNode[], projectRoot?: string): CronManifest {\n const crons: CronManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n return {\n schemaVersion: CRON_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n crons,\n }\n}\n\n/**\n * Write the cron manifest to `path` atomically (EC-106).\n *\n * Accepts either a pre-built `CronManifest` OR an array of `CronNode[]`\n * (which gets converted via `buildCronManifest`). The atomic-write\n * helper guarantees `path` always contains valid JSON, even under\n * concurrent writes (e.g., dev-server rescan + build).\n */\nexport function writeCronManifest(\n path: string,\n input: readonly CronNode[] | CronManifest,\n projectRoot?: string,\n): void {\n const manifest: CronManifest = isManifest(input) ? input : buildCronManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is CronManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'crons' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only. No HTTP\n * input ever reaches these fs calls.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { CronConcurrencyPolicy, CronDefinition } from './cron-types.js'\n\n/**\n * One discovered cron from build-time scan. The handler is intentionally\n * NOT included — manifest is platform-neutral and consumed by adapters\n * that emit static config. Runtime dispatch loads the handler at fire time.\n */\nexport interface CronNode {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: CronConcurrencyPolicy\n}\n\nexport class DuplicateCronNameError extends Error {\n readonly code = 'DUPLICATE_CRON_NAME'\n constructor(\n public readonly cronName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate cron name \"${cronName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Cron names must be unique across server/crons/.',\n )\n this.name = 'DuplicateCronNameError'\n }\n}\n\nconst CRON_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface CronModule {\n default?: unknown\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.schedule === 'string' &&\n typeof def.handler === 'function' &&\n (def.concurrency === 'forbid' || def.concurrency === 'allow')\n )\n}\n\n/**\n * Scan a directory for cron definition files and return the discovered\n * `CronNode[]` sorted by name. Throws `DuplicateCronNameError` on name\n * collision and `Error` on missing default export.\n *\n * Sequential by design — module imports are awaited one-by-one to keep\n * error messages anchored to the file that failed.\n */\nexport async function scanCrons(cronsDir: string): Promise<CronNode[]> {\n if (!existsSync(cronsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(cronsDir, { extensions: CRON_EXTENSIONS }, (p) => {\n const base = basename(p)\n // Skip private helpers (`_helper.ts`) and OS junk (`.DS_Store`).\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: CronNode[] = []\n for (const filePath of filePaths) {\n let mod: CronModule\n try {\n mod = (await import(pathToFileURL(filePath).href)) as CronModule\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import cron file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `Cron file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n schedule: exported.schedule,\n concurrency: exported.concurrency,\n })\n }\n\n // Dup-name detection\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateCronNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => a.name.localeCompare(b.name))\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { JobNode } from './job-scan.js'\n\nexport const JOB_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface JobManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport interface JobManifest {\n readonly schemaVersion: typeof JOB_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly jobs: readonly JobManifestEntry[]\n}\n\nexport function buildJobManifest(nodes: readonly JobNode[], projectRoot?: string): JobManifest {\n const jobs: JobManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n maxAttempts: n.maxAttempts,\n hasInputSchema: n.hasInputSchema,\n }))\n return {\n schemaVersion: JOB_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n jobs,\n }\n}\n\nexport function writeJobManifest(\n path: string,\n input: readonly JobNode[] | JobManifest,\n projectRoot?: string,\n): void {\n const manifest: JobManifest = isManifest(input) ? input : buildJobManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is JobManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'jobs' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { JobDefinition } from './job-types.js'\n\nexport interface JobNode {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport class DuplicateJobNameError extends Error {\n readonly code = 'DUPLICATE_JOB_NAME'\n constructor(\n public readonly jobName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate job name \"${jobName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Job names must be unique across server/jobs/.',\n )\n this.name = 'DuplicateJobNameError'\n }\n}\n\nconst JOB_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface JobModule {\n default?: unknown\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.handler === 'function' &&\n typeof def.maxAttempts === 'number' &&\n typeof def.hasInputSchema === 'boolean'\n )\n}\n\nexport async function scanJobs(jobsDir: string): Promise<JobNode[]> {\n if (!existsSync(jobsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(jobsDir, { extensions: JOB_EXTENSIONS }, (p) => {\n const base = basename(p)\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: JobNode[] = []\n for (const filePath of filePaths) {\n let mod: JobModule\n try {\n mod = (await import(pathToFileURL(filePath).href)) as JobModule\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import job file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isJobDefinition(exported)) {\n throw new Error(\n `Job file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineJob(name, { handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n maxAttempts: exported.maxAttempts,\n hasInputSchema: exported.hasInputSchema,\n })\n }\n\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateJobNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => a.name.localeCompare(b.name))\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Cleanup helpers. Paths are caller-controlled (CLI/config); EC-3 path-safety\n * guard rejects absolute paths outside cwd to prevent catastrophic data loss.\n */\n/**\n * State cleanup utilities (Phase 2 of\n * docs/plans/framework-zero-config-polish-plan.md).\n *\n * - `cleanOutDir` — Astro pattern: empty a directory except a skip list,\n * used at `theokit build` start.\n * - `gcAgentRegistry` — Nuxt LRU pattern: delete oldest agent dirs when\n * count exceeds cap, used at `theokit dev` startup.\n *\n * EC-3 (MUST FIX, CRITICAL): cleanOutDir refuses to wipe anything outside\n * the current cwd. Prevents catastrophic `distDir: '/'` data loss.\n * EC-9 (SHOULD TEST): gcAgentRegistry handles dirs with mtime=0 (Docker overlay).\n * EC-11 (SHOULD TEST): cleanOutDir normalizes trailing-slash in skip basenames.\n * EC-12 (SHOULD TEST): cleanOutDir catches EROFS and continues.\n */\n\nimport { promises as fs } from 'node:fs'\nimport { basename, resolve as resolvePath, sep } from 'node:path'\n\nimport type {\n CleanOutDirOptions,\n CleanOutDirResult,\n GcAgentRegistryOptions,\n GcAgentRegistryResult,\n} from './cleanup-types.js'\n\nconst DEFAULT_SKIP = ['.git', '.gitkeep', '.gitignore']\n// DEFAULT_MAX_AGENTS removed in Phase 7 — gcAgentRegistry is a tombstone.\n\nfunction normalizeSkipName(name: string): string {\n // EC-11 — strip trailing slash + leading `./`\n return basename(name.replace(/\\/$/, ''))\n}\n\n/**\n * Empty a directory, preserving entries in the skip list.\n *\n * Throws if `opts.dir` is not inside `process.cwd()` (EC-3 path safety).\n * Returns `{deleted:0, kept:0}` when the directory does not exist.\n */\nexport async function cleanOutDir(opts: CleanOutDirOptions): Promise<CleanOutDirResult> {\n const resolvedDir = resolvePath(opts.dir)\n const resolvedCwd = resolvePath(process.cwd())\n\n // EC-3 — path safety guard. CRITICAL.\n if (resolvedDir === resolvedCwd) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be a child of cwd, not cwd itself`,\n )\n }\n if (!resolvedDir.startsWith(resolvedCwd + sep)) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be inside cwd (${resolvedCwd})`,\n )\n }\n\n const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName))\n\n let entries: { name: string }[]\n try {\n entries = await fs.readdir(resolvedDir, { withFileTypes: true })\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { deleted: 0, kept: 0 }\n throw err\n }\n\n let deleted = 0\n let kept = 0\n for (const entry of entries) {\n const name = entry.name\n if (skip.has(name)) {\n kept++\n continue\n }\n const fullPath = resolvePath(resolvedDir, name)\n try {\n await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 })\n deleted++\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n deleted++ // already gone\n continue\n }\n // EC-12 — EROFS or other rm failure: warn + continue, don't crash.\n console.warn(\n `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? 'unknown'}); skipping`,\n )\n kept++\n }\n }\n\n return { deleted, kept }\n}\n\n/**\n * Phase 7 — TOMBSTONE for backward-compat. The SDK v1.1.0's `Agent.registry`\n * handles GC natively; this function is a no-op + emits a deprecation warning\n * ONCE per process (EC-10).\n *\n * Will be deleted entirely in TheoKit 0.4.0. Marked deprecated via runtime\n * warning rather than `@deprecated` JSDoc tag to avoid the eslint\n * sonarjs/deprecation flagging our own internal symbols.\n */\nlet warnedOnce = false\nexport async function gcAgentRegistry(\n _opts: GcAgentRegistryOptions,\n): Promise<GcAgentRegistryResult> {\n if (!warnedOnce) {\n warnedOnce = true\n console.warn(\n '[theokit] gcAgentRegistry is deprecated; SDK Agent.registry handles GC natively (configure via theo.config.ts > agents.registry)',\n )\n }\n return Promise.resolve({ deleted: 0, kept: 0 })\n}\n\n/**\n * @internal — testing helper. Resets the module-scoped warnedOnce flag.\n */\nexport function __resetGcDeprecationWarnedForTests(): void {\n warnedOnce = false\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,eAAe;;;ACgCjB,IAAM,gBAA+B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;;;ACxCA,SAAS,YAAY,oBAAoB;;;ACCzC,SAAS,mBAAmB;AAC5B,SAAS,WAAW,YAAY,qBAAqB;AACrD,SAAS,eAAe;AAkBjB,SAAS,YAAY,MAAc,SAAuB;AAC/D,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAI5C,QAAM,MAAM,GAAG,IAAI,QAAQ,QAAQ,GAAG,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC;AACxE,gBAAc,KAAK,SAAS,MAAM;AAClC,aAAW,KAAK,IAAI;AACtB;;;ADlBO,IAAM,iCAAN,cAA6C,MAAM;AAAA,EAExD,YACkB,UACA,YAChB;AACA;AAAA,MACE,oBAAoB,QAAQ,0BAA0B,UAAU;AAAA,IAElE;AANgB;AACA;AAMhB,SAAK,OAAO;AAAA,EACd;AAAA,EARkB;AAAA,EACA;AAAA,EAHT,OAAO;AAWlB;AAiBO,SAAS,sBACd,gBACA,OACM;AACN,MAAI,WAAuB,CAAC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AK;AACH,8BAAsB,QAAQ,KAAK,KAAK,aAAa,GAAG,eAAe;AACvE,gBAAQ,IAAI,6CAAmC,UAAU,MAAM,WAAW;AAC1E;AAAA,MACF,KAAK;AACH,kCAA0B,QAAQ,KAAK,KAAK,eAAe,GAAG,eAAe;AAC7E,gBAAQ,IAAI,kDAAwC,UAAU,MAAM,GAAG;AACvE;AAAA,MACF,KAAK;AACH,2BAAmB,QAAQ,KAAK,KAAK,gBAAgB,GAAG,eAAe;AACvE,gBAAQ,IAAI,kDAAwC,UAAU,MAAM,GAAG;AACvE;AAAA,MACF,KAAK;AACH,4BAAoB,QAAQ,KAAK,SAAS,gBAAgB,GAAG,eAAe;AAC5E,gBAAQ,IAAI,wBAAc,KAAK,OAAO,6BAA6B;AACnE;AAAA,MACF,KAAK;AACH,gBAAQ,IAAI,2DAAiD;AAC7D;AAAA,IACJ;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,eAAe,+BAAgC,OAAM;AACzD,UAAM;AAAA,EACR;AACF;AAEA,eAAe,iBAAiB,MAId;AAChB,QAAM,UAAU,QAAQ,KAAK,WAAW,MAAM;AAE9C,QAAM,WAAWD,YAAW,OAAO,IAAI,MAAM,SAAS,OAAO,IAAI,CAAC;AAClE,QAAM,eAAe,QAAQ,KAAK,SAAS,WAAW;AACtD,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASC,YAAW,SAAiB,MAAsB;AACzD,MAAI,QAAQ,WAAW,IAAI,GAAG;AAC5B,UAAM,UAAU,QAAQ,MAAM,KAAK,MAAM;AACzC,WAAO,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAAA,EACtD;AACA,SAAO;AACT;","names":["existsSync","existsSync","existsSync","relativize","isManifest","existsSync","basename","pathToFileURL","existsSync","basename","pathToFileURL","basename","writeManifest","existsSync","relativize"]}