theokit 0.77.0 → 0.77.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ import {
9
9
  detectProjectPackageManager,
10
10
  runAdd,
11
11
  validatePackageInput
12
- } from "./chunk-JVXDEIT4.js";
12
+ } from "./chunk-I2IDWM26.js";
13
13
  export {
14
14
  InvalidPackageNameError,
15
15
  KNOWN_PACKAGES,
@@ -20,4 +20,4 @@ export {
20
20
  runAdd,
21
21
  validatePackageInput
22
22
  };
23
- //# sourceMappingURL=add-DOR7HORT.js.map
23
+ //# sourceMappingURL=add-NFDL4OJ7.js.map
@@ -1,5 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
+ import {
4
+ cleanBuildOutput
5
+ } from "./chunk-V3LMUQSB.js";
3
6
  import {
4
7
  VALID_TARGETS,
5
8
  targetRendersDocument
@@ -275,62 +278,6 @@ function relativize2(absPath, root) {
275
278
  return absPath;
276
279
  }
277
280
 
278
- // src/cli/cleanup/cleanup.ts
279
- import { promises as fs } from "fs";
280
- import { basename, resolve as resolvePath, sep } from "path";
281
- var DEFAULT_SKIP = [".git", ".gitkeep", ".gitignore"];
282
- function normalizeSkipName(name) {
283
- return basename(name.replace(/\/$/, ""));
284
- }
285
- async function cleanOutDir(opts) {
286
- const resolvedDir = resolvePath(opts.dir);
287
- const resolvedCwd = resolvePath(process.cwd());
288
- if (resolvedDir === resolvedCwd) {
289
- throw new Error(
290
- `cleanOutDir refused to wipe ${resolvedDir} \u2014 must be a child of cwd, not cwd itself`
291
- );
292
- }
293
- if (!resolvedDir.startsWith(resolvedCwd + sep)) {
294
- throw new Error(
295
- `cleanOutDir refused to wipe ${resolvedDir} \u2014 must be inside cwd (${resolvedCwd})`
296
- );
297
- }
298
- const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName));
299
- let entries;
300
- try {
301
- entries = await fs.readdir(resolvedDir, { withFileTypes: true });
302
- } catch (err) {
303
- const code = err.code;
304
- if (code === "ENOENT") return { deleted: 0, kept: 0 };
305
- throw err;
306
- }
307
- let deleted = 0;
308
- let kept = 0;
309
- for (const entry of entries) {
310
- const name = entry.name;
311
- if (skip.has(name)) {
312
- kept++;
313
- continue;
314
- }
315
- const fullPath = resolvePath(resolvedDir, name);
316
- try {
317
- await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 });
318
- deleted++;
319
- } catch (err) {
320
- const code = err.code;
321
- if (code === "ENOENT") {
322
- deleted++;
323
- continue;
324
- }
325
- console.warn(
326
- `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? "unknown"}); skipping`
327
- );
328
- kept++;
329
- }
330
- }
331
- return { deleted, kept };
332
- }
333
-
334
281
  // src/cli/commands/build/describe-services-manifest.ts
335
282
  function describeServicesManifest(manifest, target) {
336
283
  if (manifest.services.length > 0) {
@@ -346,11 +293,11 @@ function describeServicesManifest(manifest, target) {
346
293
 
347
294
  // src/cli/commands/build-scan-routes.ts
348
295
  import { existsSync as existsSync2 } from "fs";
349
- import { join, relative, resolve, sep as sep2 } from "path";
296
+ import { join, relative, resolve, sep } from "path";
350
297
  function createBuildScanRoutes(projectRoot, config) {
351
298
  return (serverDir) => {
352
299
  const abs = resolve(projectRoot, serverDir);
353
- const toProjectRelative = (p) => relative(projectRoot, p).split(sep2).join("/");
300
+ const toProjectRelative = (p) => relative(projectRoot, p).split(sep).join("/");
354
301
  return {
355
302
  routes: scanServerRoutes(abs).map((route) => ({
356
303
  filePath: toProjectRelative(route.filePath),
@@ -407,7 +354,7 @@ async function buildCommand(options) {
407
354
  assertRateLimitEnforceable(config, adapter, target);
408
355
  assertStreamingSupported(config, adapter, target, await streamingTargets());
409
356
  const distDirAbs = resolve2(cwd, config.distDir);
410
- await cleanOutDir({ dir: distDirAbs });
357
+ await cleanBuildOutput(distDirAbs);
411
358
  const configAdapters = config.adapters;
412
359
  if (configAdapters && configAdapters.length > 0) {
413
360
  const otherAdapters = configAdapters.filter((a) => a !== target);
@@ -559,4 +506,4 @@ function relativize3(absPath, root) {
559
506
  export {
560
507
  buildCommand
561
508
  };
562
- //# sourceMappingURL=build-QDZEOCJ3.js.map
509
+ //# sourceMappingURL=build-Y457R5HE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/build.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/jobs/job-manifest.ts","../src/cli/commands/build/describe-services-manifest.ts","../src/cli/commands/build-scan-routes.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 {\n VALID_TARGETS,\n targetRendersDocument,\n type BuildTarget,\n type AdapterBuildContext,\n type DeployAdapter,\n} from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../config/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 { cronScanDirs, scanCronDirs } 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'\n// G2 T2.2 — OpenAPI emit. Opt-in via `config.openapi`. Dual output:\n// 1. <distDir>/openapi.json (pre-Vite, dev surface + manifests sibling)\n// 2. dist/openapi.json (post-Vite, build artifact)\n// The dist emit awaits runAdapterBuild — if Vite fails, the second emit\n// never runs (EC-2 absorbed: no stale dist artifact).\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\nimport { cleanBuildOutput } from '../cleanup/cleanup.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport { describeServicesManifest } from './build/describe-services-manifest.js'\nimport { describeControllerArtifacts, emitControllerArtifacts } from './build/emit-controllers.js'\nimport { createBuildScanRoutes } from './build-scan-routes.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\n// DERIVED, never restated. A hand-written list here went stale and told users\n// that three working targets were unsupported: it named node/vercel/cloudflare\n// while aws-lambda, deno-deploy and theo-cloud also translate crons. Deriving\n// from the two constants means adding a target cannot desynchronise the message.\nconst CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t))\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n // #95 — honor config.appDir so a custom frontend dir (e.g. apps/web) passes the structure gate.\n validateProjectStructure(cwd, config.appDir)\n\n // B-336 — EVERY refusal that is decidable from the target and the config alone runs BEFORE the\n // clean. `cleanOutDir` used to sit here, above even the check that the target EXISTS: measured on a\n // real project, `theokit build --target nao-existe` destroyed 302 files in `.theokit/client/assets`\n // and answered with a message about the typo. The comment above\n // `assertRateLimitEnforceable` already stated this intent in its own words — \"refused by name,\n // BEFORE the build writes anything\" — and the order defeated it.\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 const { resolveAdapter, streamingTargets } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n const { assertRateLimitEnforceable, assertStreamingSupported } =\n await import('../../adapters/config-support.js')\n\n // #461 — a dropped `cors` degrades where someone can see it; a dropped RATE LIMIT looks exactly like\n // success until the abuse it was meant to stop. Refused by name, and now genuinely before anything is\n // written or destroyed.\n assertRateLimitEnforceable(config, adapter, target)\n assertStreamingSupported(config, adapter, target, await streamingTargets())\n\n // T2.2 — Clean .theokit/ at build start (Astro pattern), keeping the agent context that lives\n // beside the build output (#1079).\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanBuildOutput(distDirAbs)\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 // #95 follow-up — pass projectRoot (cwd) + config.agentsDir so agents scan honors a custom dir.\n const manifest = generateManifest(serverDir, cwd, config.agentsDir)\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, agentsDir: config.agentsDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // theokit#123 — compile `server/controllers/**` so `theokit start` can serve them.\n //\n // #122 made controllers first-class in dev, where Vite's swc transform compiles them on the fly.\n // Production has neither, so an uncompiled `.controller.ts` cannot load and its routes 404'd —\n // working in dev and failing in prod, which is the worst place for a gap to live.\n //\n // Deliberately NOT folded into `generateManifest` (ADR-5): the manifest is the deploy-adapter\n // contract, and a parallel route source in it would ripple through every adapter. This writes a\n // separate artifact only the Node start path reads. No controllers ⇒ no artifact at all.\n const controllerManifest = await emitControllerArtifacts({ serverDir, distDir })\n if (controllerManifest !== null) {\n console.log(` ${describeControllerArtifacts(controllerManifest)}`)\n }\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theokit/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 //\n // Plan v1.2 T2.1 — when theo.config.ts declares `name`, emit services.json\n // v2 with that project identifier. Falling back to v1 (no project field)\n // keeps TheoCloud's deprecation warning path intact (services-bundle).\n const projectName = config.name\n const servicesManifest = buildServicesManifest(config.services, projectName)\n writeServicesManifest(cwd, servicesManifest)\n const servicesLine = describeServicesManifest(servicesManifest, target)\n if (servicesLine !== null) console.log(` ${servicesLine}`)\n\n // G2 T2.2 — OpenAPI dev-surface emit (pre-Vite, sibling of manifests).\n // Opt-in: only when config.openapi is defined. Best-effort: a route load\n // failure produces a warning, not a build abort.\n if (config.openapi !== undefined) {\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const devResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(` ✓ OpenAPI: ${String(hydrated.length)} ops → ${devResult.path}`)\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd, adapter)\n\n // G2 T2.2 — OpenAPI build-artifact emit (post-Vite, EC-2 gated on success).\n // If runAdapterBuild threw, execution never reaches this point — no stale\n // dist/openapi.json is written.\n if (config.openapi !== undefined) {\n const distOut = resolve(cwd, 'dist')\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const distResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distOut },\n })\n console.log(` ✓ OpenAPI (dist): ${distResult.path}`)\n }\n\n // Derived, not asserted. This read `config.ssr` alone, so a target whose entry delegates the\n // document to a static host was announced as server-rendering — measured on `--target bun`, which\n // printed `(SSR)` and served an empty `<div id=\"root\">` (B-334).\n const ssrNote = config.ssr && targetRendersDocument(target) ? ' (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 // Resolved by the caller, which needs it before `cleanOutDir` to run the refusals (B-336). Passing it\n // in rather than resolving again keeps one answer to \"which adapter is this build\".\n adapter: DeployAdapter,\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 //\n // 0.2.2 regression fix: switched sync `theoPlugin()` → `theoPluginAsync()` so the\n // returned Plugin[] includes the @theo/actions virtual module + typed-client +\n // services + @theokit/ui auto-chain. Without async, build-time Rollup couldn't\n // resolve `@theo/actions` even though dev-time Vite (which already used async)\n // could. See https://github.com/usetheo/theokit/commits — 0.2.2 changelog.\n const { theoPluginAsync } = 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; spread the\n // async chain so the contract returns a flat Plugin[] (AdapterBuildContext\n // type updated to `Plugin[] | Promise<Plugin[]>`).\n // #95 — inject the config dirs so the client build's router/entry + typed-client codegen honor\n // custom appDir/serverDir/agentsDir (e.g. \"apps/web\" / \"core\" / \"core/agents\").\n makeVitePlugins: async (opts) =>\n [\n react(),\n ...(await theoPluginAsync({\n ...opts,\n appDir: config.appDir,\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })),\n ].flat(),\n\n // #369 — the same inversion, for the same reason. A Worker has no filesystem, so the Cloudflare\n // entry bakes its routes at build time; importing the scanner from `adapters/` would add the\n // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The\n // CLI already imports both sides, so it composes the scan and hands over the result.\n //\n // A module rather than a closure since B-312: the wrong argument it carried was unreachable from\n // any test while it lived in here, because reaching it meant running the whole build.\n scanRoutes: createBuildScanRoutes(cwd, config),\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 // #409 / #410 — a config key that validates and is then never read makes the\n // deployed app behave as if the operator had not written it, with nothing\n // anywhere saying so. Name it before the build output scrolls past.\n const { warnUnappliedConfig } = await import('../../adapters/config-support.js')\n\n // #461 / #321 / #322 — the rate-limit refusal moved to `buildCommand`, above `cleanOutDir`, because\n // this position made its own comment false: it claimed the combination was refused \"BEFORE the build\n // writes anything\" and it is reached a hundred lines after the output has been emptied (B-336).\n\n warnUnappliedConfig(config, adapter, target, (message) => {\n console.log(message)\n })\n\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n agentsDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n // Crons live in two conventional homes: `server/crons/` (a backend trigger) and\n // `agents/schedules/` (a scheduled agent run, kept in the agent domain). Both feed one manifest.\n const { crons, schedules } = cronScanDirs(opts.cwd, opts.serverDir, opts.agentsDir)\n\n const cronNodes = await scanCronDirs([crons, schedules])\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 `Supported targets: ${CRON_SUPPORTED_TARGETS.join(', ')}.`,\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\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","/* 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: .theokit/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 → .theokit/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 */\n// T5a.1b — Web Crypto migration. Build-time only; node:fs + node:path stay\n// because this is a manifest-write leaf (e.g. .theokit/jobs.json) and per\n// ADR-0028 the runtime-portable boundary is the request handler, not the\n// scanner. Only node:crypto is swapped out — Web Crypto's\n// getRandomValues works in every supported runtime.\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 * `.theokit/crons.json` and `.theokit/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. Web Crypto getRandomValues is non-blocking +\n // collision-safe for the tiny entropy we need (8 hex chars = 32 bits).\n // Hex-encoded manually to avoid Buffer (runtime-agnostic per ADR-0028).\n const randBuf = new Uint8Array(4)\n globalThis.crypto.getRandomValues(randBuf)\n let suffix = ''\n for (const b of randBuf) suffix += b.toString(16).padStart(2, '0')\n const tmp = `${path}.tmp-${process.pid}-${suffix}`\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","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","import type { BuildTarget } from '../../../adapters/types.js'\nimport type { ServicesManifest } from '../../../services/index.js'\n\n/**\n * The build line about `.theokit/services.json`, or `null` when there is nothing worth saying.\n *\n * The v1 warning is addressed to `theo-cloud`, the one target that reads the file. It used to print\n * on every target, for apps that declare no services, and it named a sunset in `theokit 0.6.0` that\n * had passed 68 minors earlier without anything being removed. A deadline nobody enforces teaches\n * the reader to skip the line, so the warning states what the file is and how to upgrade it.\n */\nexport function describeServicesManifest(\n manifest: ServicesManifest,\n target: BuildTarget,\n): string | null {\n if (manifest.services.length > 0) {\n const projectLabel = manifest.version === 2 ? ` project=\"${manifest.project}\"` : ''\n const names = manifest.services.map((s) => s.name).join(', ')\n return (\n `✓ Services manifest (v${String(manifest.version)}${projectLabel}): ` +\n `${String(manifest.services.length)} service(s) (${names})`\n )\n }\n if (manifest.version === 1 && target === 'theo-cloud') {\n return (\n '⚠ services.json emitted as v1 (no `name` in theo.config.ts), which TheoCloud reads as ' +\n 'deprecated. Run `theokit migrate services-json-v1-to-v2` to upgrade.'\n )\n }\n return null\n}\n","import { existsSync } from 'node:fs'\nimport { join, relative, resolve, sep } from 'node:path'\n\nimport type { AdapterBuildContext } from '../../adapters/types.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\nimport { scanServerRoutes } from '../../server/scan/scan.js'\nimport { scanWebSocketRoutes } from '../../server/scan/ws-scan.js'\n\n/**\n * What a scanned deploy target is handed instead of a filesystem.\n *\n * #369 — a Worker has no filesystem at request time, so the Cloudflare entry bakes its routes at\n * build time. Importing the scanner from `adapters/` would add the `adapters → server` edge that\n * `adapters-may-only-depend-on-core-router-services` refuses, so the CLI composes the scan and\n * hands over the result.\n *\n * ## Why this is a module rather than a closure inside `buildCommand`\n *\n * It was a closure, and the defect it carried was invisible to every test: `buildCommand` loads a\n * config, runs vite twice and writes a tree, so nothing could ask it one question about one call.\n * Extracted at B-312, whose whole content was a single argument being wrong.\n *\n * Paths are made relative to the project root here, where `projectRoot` is known: that string is\n * both the emitted import specifier and the key the executor looks a module up by, and the scanners\n * return absolute paths.\n */\nexport function createBuildScanRoutes(\n projectRoot: string,\n config: { agentsDir?: string },\n): NonNullable<AdapterBuildContext['scanRoutes']> {\n return (serverDir: string) => {\n const abs = resolve(projectRoot, serverDir)\n const toProjectRelative = (p: string): string => relative(projectRoot, p).split(sep).join('/')\n\n return {\n routes: scanServerRoutes(abs).map((route) => ({\n filePath: toProjectRelative(route.filePath),\n routePath: route.routePath,\n methods: route.methods ?? [],\n })),\n wsRoutes: scanWebSocketRoutes(abs).map((ws) =>\n toProjectRelative(typeof ws === 'string' ? ws : ws.filePath),\n ),\n // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no adapter\n // had ever heard of them: the entries route `/api/` through `scanServerRoutes` +\n // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.\n // Scanned here, beside the routes, because the same inversion argument applies verbatim.\n //\n // B-312 — the root is the PROJECT ROOT, and was `dirname(abs)`. `config.agentsDir` is\n // documented and declared relative to the project root, while `dirname(serverDir)` is the\n // root only when `serverDir` is a direct child of it. The scaffold's own nested layout\n // (`serverDir: 'src/server'`, `agentsDir: 'src/server/agents'`) made the two disagree, and\n // `join()` produced `<root>/src/src/server/agents` — so `scanAgents` returned `[]` and every\n // `/api/agents/*` route 404'd on every scanned target. Measured on a live Cloudflare deploy,\n // 2026-09-26. Every other caller in the tree already passes the project root.\n agents: scanAgents(projectRoot, config.agentsDir).map((agent) => ({\n filePath: toProjectRelative(agent.filePath),\n agentPath: agent.agentPath,\n name: agent.name,\n })),\n // B-185 — the identity module, decided here for the same reason the agents are: this provider\n // is handed `serverDir`, and a Worker has no filesystem to look for it on. An app with no\n // `server/context.ts` yields `undefined`, and the generator then emits no import — importing\n // a file that is not there would fail the BUILD rather than one request.\n contextModule: existsSync(join(abs, 'context.ts'))\n ? toProjectRelative(join(abs, 'context.ts'))\n : undefined,\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAA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AAK,KAAK,eAAe,GAAG,eAAe;AAC7E,gBAAQ,IAAI,kDAAwC,UAAU,MAAM,GAAG;AACvE;AAAA,MACF,KAAK;AACH,2BAAmBA,SAAQ,KAAK,KAAK,gBAAgB,GAAG,eAAe;AACvE,gBAAQ,IAAI,kDAAwC,UAAU,MAAM,GAAG;AACvE;AAAA,MACF,KAAK;AACH,4BAAoBA,SAAQ,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,UAAUA,SAAQ,KAAK,WAAW,MAAM;AAE9C,QAAM,WAAWG,YAAW,OAAO,IAAI,MAAM,SAAS,OAAO,IAAI,CAAC;AAClE,QAAM,eAAeH,SAAQ,KAAK,SAAS,WAAW;AACtD,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASE,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","resolve","relativize","isManifest","existsSync","existsSync","resolve","writeManifest","relativize","existsSync"]}
@@ -19,13 +19,17 @@ var UnknownPackageError = class extends Error {
19
19
  this.name = "UnknownPackageError";
20
20
  }
21
21
  };
22
- var PACKAGE_NAME_REGEX = /^[a-z0-9][a-z0-9-]*$/;
22
+ var FIRST_PARTY_SCOPE = "@theokit/";
23
+ var PACKAGE_NAME_REGEX = /^(@theokit\/)?[a-z0-9][a-z0-9-]*$/;
23
24
  function validatePackageInput(input) {
24
25
  if (typeof input !== "string" || input.length === 0) {
25
26
  throw new InvalidPackageNameError(input, "must be a non-empty string");
26
27
  }
27
28
  if (!PACKAGE_NAME_REGEX.test(input)) {
28
- throw new InvalidPackageNameError(input, "allowed: lowercase letters, digits, hyphens only");
29
+ throw new InvalidPackageNameError(
30
+ input,
31
+ "allowed: lowercase letters, digits, hyphens, and an optional @theokit/ scope"
32
+ );
29
33
  }
30
34
  return true;
31
35
  }
@@ -64,8 +68,27 @@ var KNOWN_PACKAGES = {
64
68
  static: {
65
69
  kind: "bundled",
66
70
  usage: "theokit build --target=static"
67
- }
71
+ },
72
+ // #1076 — the first-party plugins published under @theokit. Install by short or scoped name.
73
+ ...firstPartyPlugins([
74
+ "plugin-canvas",
75
+ "plugin-copilot",
76
+ "plugin-db-drizzle",
77
+ "plugin-email",
78
+ "plugin-forms",
79
+ "plugin-payments",
80
+ "plugin-realtime",
81
+ "plugin-voice"
82
+ ])
68
83
  };
84
+ function firstPartyPlugins(names) {
85
+ return Object.fromEntries(
86
+ names.map((name) => {
87
+ const npm = `${FIRST_PARTY_SCOPE}${name}`;
88
+ return [name, { kind: "external", npm, usage: `import { ... } from '${npm}'` }];
89
+ })
90
+ );
91
+ }
69
92
  function levenshtein(a, b) {
70
93
  const m = a.length;
71
94
  const n = b.length;
@@ -97,14 +120,15 @@ function findSuggestion(input, candidates) {
97
120
  async function runAdd(deps) {
98
121
  validatePackageInput(deps.input);
99
122
  const registry = deps.registry ?? KNOWN_PACKAGES;
100
- if (!Object.hasOwn(registry, deps.input)) {
101
- const suggestion = findSuggestion(deps.input, Object.keys(registry));
123
+ const name = deps.input.startsWith(FIRST_PARTY_SCOPE) ? deps.input.slice(FIRST_PARTY_SCOPE.length) : deps.input;
124
+ if (!Object.hasOwn(registry, name)) {
125
+ const suggestion = findSuggestion(name, Object.keys(registry));
102
126
  throw new UnknownPackageError(deps.input, suggestion);
103
127
  }
104
- const entry = registry[deps.input];
128
+ const entry = registry[name];
105
129
  if (entry.kind === "bundled") {
106
130
  return {
107
- packageInstalled: `${deps.input} (bundled inside theokit)`,
131
+ packageInstalled: `${name} (bundled inside theokit)`,
108
132
  packageManager: "bundled",
109
133
  usage: entry.usage,
110
134
  exitCode: 0
@@ -144,7 +168,7 @@ async function addCommand(input) {
144
168
  console.log(`
145
169
  \u2713 Installed ${result.packageInstalled} via ${result.packageManager}
146
170
  `);
147
- console.log(` Next: import { /* ... */ } from '${result.packageInstalled}'
171
+ console.log(` Next: ${result.usage}
148
172
  `);
149
173
  } catch (err) {
150
174
  console.error(`
@@ -164,4 +188,4 @@ export {
164
188
  runAdd,
165
189
  addCommand
166
190
  };
167
- //# sourceMappingURL=chunk-JVXDEIT4.js.map
191
+ //# sourceMappingURL=chunk-I2IDWM26.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/add.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport class InvalidPackageNameError extends Error {\n constructor(input: string, reason: string) {\n super(`Invalid package name \"${input}\": ${reason}`)\n this.name = 'InvalidPackageNameError'\n }\n}\n\nexport class UnknownPackageError extends Error {\n constructor(input: string, suggestion?: string) {\n super(\n suggestion\n ? `Unknown package: ${input}. Did you mean: ${suggestion}?`\n : `Unknown package: ${input}.`,\n )\n this.name = 'UnknownPackageError'\n }\n}\n\n/**\n * EC-4 — strict whitelist of characters allowed in package input.\n * Lowercase ASCII letters, digits, hyphens. Must start with letter/digit.\n * Rejects: shell metacharacters, path traversal, uppercase, and every scope but `@theokit/`.\n *\n * The `@theokit/` scope is accepted because the help text and the Plugins page document\n * `theokit add @theokit/plugin-payments` (#1076). The scope is stripped before the whitelist\n * lookup, so it only ever names an entry already in `KNOWN_PACKAGES`.\n */\nconst FIRST_PARTY_SCOPE = '@theokit/'\nconst PACKAGE_NAME_REGEX = /^(@theokit\\/)?[a-z0-9][a-z0-9-]*$/\n\nexport function validatePackageInput(input: string): true {\n if (typeof input !== 'string' || input.length === 0) {\n throw new InvalidPackageNameError(input, 'must be a non-empty string')\n }\n if (!PACKAGE_NAME_REGEX.test(input)) {\n throw new InvalidPackageNameError(\n input,\n 'allowed: lowercase letters, digits, hyphens, and an optional @theokit/ scope',\n )\n }\n return true\n}\n\nexport type PackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm'\n\nexport function detectPackageManager(lockfiles: Record<string, boolean>): PackageManager {\n if (lockfiles['pnpm-lock.yaml']) return 'pnpm'\n if (lockfiles['bun.lockb']) return 'bun'\n if (lockfiles['yarn.lock']) return 'yarn'\n if (lockfiles['package-lock.json']) return 'npm'\n return 'npm'\n}\n\n/** The package manager whose lockfile sits in `cwd`; npm when there is none. */\nexport function detectProjectPackageManager(\n cwd: string,\n existsFn: (path: string) => boolean = existsSync,\n): PackageManager {\n return detectPackageManager({\n 'pnpm-lock.yaml': existsFn(resolve(cwd, 'pnpm-lock.yaml')),\n 'bun.lockb': existsFn(resolve(cwd, 'bun.lockb')),\n 'yarn.lock': existsFn(resolve(cwd, 'yarn.lock')),\n 'package-lock.json': existsFn(resolve(cwd, 'package-lock.json')),\n })\n}\n\ninterface PackageRegistryEntry {\n /** 'bundled' = adapter already shipped inside theokit; no npm install needed.\n * 'external' = adapter/plugin lives as a separate npm package. */\n kind: 'bundled' | 'external'\n /** Required when kind === 'external'. */\n npm?: string\n /** Usage hint printed to the user (e.g. `theokit build --target=bun`). */\n usage: string\n}\n\nexport const KNOWN_PACKAGES: Record<string, PackageRegistryEntry> = {\n bun: {\n kind: 'bundled',\n usage: 'theokit build --target=bun',\n },\n deno: {\n kind: 'bundled',\n usage: 'theokit build --target=deno-deploy',\n },\n netlify: {\n kind: 'bundled',\n usage: 'theokit build --target=netlify',\n },\n 'aws-lambda': {\n kind: 'bundled',\n usage: 'theokit build --target=aws-lambda',\n },\n static: {\n kind: 'bundled',\n usage: 'theokit build --target=static',\n },\n // #1076 — the first-party plugins published under @theokit. Install by short or scoped name.\n ...firstPartyPlugins([\n 'plugin-canvas',\n 'plugin-copilot',\n 'plugin-db-drizzle',\n 'plugin-email',\n 'plugin-forms',\n 'plugin-payments',\n 'plugin-realtime',\n 'plugin-voice',\n ]),\n}\n\nfunction firstPartyPlugins(names: readonly string[]): Record<string, PackageRegistryEntry> {\n return Object.fromEntries(\n names.map((name) => {\n const npm = `${FIRST_PARTY_SCOPE}${name}`\n return [name, { kind: 'external', npm, usage: `import { ... } from '${npm}'` }]\n }),\n )\n}\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length\n const n = b.length\n if (m === 0) return n\n if (n === 0) return m\n const dp: number[][] = Array.from({ length: m + 1 }, () =>\n Array.from<number>({ length: n + 1 }).fill(0),\n )\n for (let i = 0; i <= m; i++) dp[i][0] = i\n for (let j = 0; j <= n; j++) dp[0][j] = j\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n}\n\nfunction findSuggestion(input: string, candidates: string[]): string | undefined {\n let best: { name: string; d: number } | null = null\n for (const c of candidates) {\n const d = levenshtein(input, c)\n if (best === null || d < best.d) best = { name: c, d }\n }\n if (best && best.d <= 3) return best.name\n return undefined\n}\n\ninterface RunAddDeps {\n input: string\n cwd: string\n existsSync?: (path: string) => boolean\n spawnPm?: (\n cmd: string,\n args: string[],\n opts: { cwd: string; shell: boolean },\n ) => Promise<{ ok: boolean; code: number }>\n registry?: Record<string, PackageRegistryEntry>\n}\n\ninterface AddResult {\n packageInstalled: string\n packageManager: PackageManager | 'bundled'\n usage: string\n exitCode: 0\n}\n\nexport async function runAdd(deps: RunAddDeps): Promise<AddResult> {\n validatePackageInput(deps.input)\n\n const registry = deps.registry ?? KNOWN_PACKAGES\n const name = deps.input.startsWith(FIRST_PARTY_SCOPE)\n ? deps.input.slice(FIRST_PARTY_SCOPE.length)\n : deps.input\n if (!Object.hasOwn(registry, name)) {\n const suggestion = findSuggestion(name, Object.keys(registry))\n throw new UnknownPackageError(deps.input, suggestion)\n }\n const entry = registry[name]\n\n // T6.1 — bundled adapters need no install\n if (entry.kind === 'bundled') {\n return {\n packageInstalled: `${name} (bundled inside theokit)`,\n packageManager: 'bundled',\n usage: entry.usage,\n exitCode: 0,\n }\n }\n\n if (!entry.npm) {\n throw new Error(`External package \"${deps.input}\" missing npm field in registry`)\n }\n\n const pm = detectProjectPackageManager(deps.cwd, deps.existsSync)\n\n const args = pm === 'npm' ? ['install', entry.npm] : ['add', entry.npm]\n const spawnFn = deps.spawnPm ?? defaultSpawnPm\n const result = await spawnFn(pm, args, { cwd: deps.cwd, shell: false })\n\n if (!result.ok) {\n throw new Error(`Package manager exited with non-zero exit code ${result.code}`)\n }\n\n return {\n packageInstalled: entry.npm,\n packageManager: pm,\n usage: entry.usage,\n exitCode: 0,\n }\n}\n\nfunction defaultSpawnPm(\n cmd: string,\n args: string[],\n opts: { cwd: string; shell: boolean },\n): Promise<{ ok: boolean; code: number }> {\n return new Promise((resolve) => {\n const proc = spawn(cmd, args, { cwd: opts.cwd, shell: opts.shell, stdio: 'inherit' })\n proc.on('close', (code) => {\n resolve({ ok: code === 0, code: code ?? 1 })\n })\n proc.on('error', () => {\n resolve({ ok: false, code: 1 })\n })\n })\n}\n\nexport async function addCommand(input: string): Promise<void> {\n try {\n const result = await runAdd({ input, cwd: process.cwd() })\n console.log(`\\n ✓ Installed ${result.packageInstalled} via ${result.packageManager}\\n`)\n console.log(` Next: ${result.usage}\\n`)\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`)\n process.exit(1)\n }\n}\n"],"mappings":";;;;AAAA,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAEjB,IAAM,0BAAN,cAAsC,MAAM;AAAA,EACjD,YAAY,OAAe,QAAgB;AACzC,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AAK,KAAK,KAAK,OAAO,MAAM,CAAC;AAEtE,MAAI,CAAC,OAAO,IAAI;AACd,UAAM,IAAI,MAAM,kDAAkD,OAAO,IAAI,EAAE;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,kBAAkB,MAAM;AAAA,IACxB,gBAAgB;AAAA,IAChB,OAAO,MAAM;AAAA,IACb,UAAU;AAAA,EACZ;AACF;AAEA,SAAS,eACP,KACA,MACA,MACwC;AACxC,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B,UAAM,OAAO,MAAM,KAAK,MAAM,EAAE,KAAK,KAAK,KAAK,OAAO,KAAK,OAAO,OAAO,UAAU,CAAC;AACpF,SAAK,GAAG,SAAS,CAAC,SAAS;AACzB,MAAAA,SAAQ,EAAE,IAAI,SAAS,GAAG,MAAM,QAAQ,EAAE,CAAC;AAAA,IAC7C,CAAC;AACD,SAAK,GAAG,SAAS,MAAM;AACrB,MAAAA,SAAQ,EAAE,IAAI,OAAO,MAAM,EAAE,CAAC;AAAA,IAChC,CAAC;AAAA,EACH,CAAC;AACH;AAEA,eAAsB,WAAW,OAA8B;AAC7D,MAAI;AACF,UAAM,SAAS,MAAM,OAAO,EAAE,OAAO,KAAK,QAAQ,IAAI,EAAE,CAAC;AACzD,YAAQ,IAAI;AAAA,qBAAmB,OAAO,gBAAgB,QAAQ,OAAO,cAAc;AAAA,CAAI;AACvF,YAAQ,IAAI,WAAW,OAAO,KAAK;AAAA,CAAI;AAAA,EACzC,SAAS,KAAK;AACZ,YAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["resolve"]}
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ import "tsx/esm";
3
+
4
+ // src/cli/cleanup/cleanup.ts
5
+ import { promises as fs } from "fs";
6
+ import { basename, resolve as resolvePath, sep } from "path";
7
+ var DEFAULT_SKIP = [".git", ".gitkeep", ".gitignore"];
8
+ var AUTHORED_AGENT_CONTEXT = [
9
+ "THEO.md",
10
+ "rules",
11
+ "personalities",
12
+ "skills",
13
+ "agents",
14
+ "commands",
15
+ "hooks.json"
16
+ ];
17
+ var LOCAL_AGENT_STATE = [
18
+ "THEO.local.md",
19
+ "AGENTS.local.md",
20
+ "memory",
21
+ "context",
22
+ "context.json",
23
+ "config.json",
24
+ "settings.json",
25
+ "mcp.json",
26
+ "hooks",
27
+ "plugins",
28
+ "cron",
29
+ "profiles",
30
+ "auth.json",
31
+ "mcp-tokens.json",
32
+ "credential-pool.json",
33
+ "tool-permissions.json",
34
+ "hook-approvals.json"
35
+ ];
36
+ function normalizeSkipName(name) {
37
+ return basename(name.replace(/\/$/, ""));
38
+ }
39
+ async function cleanOutDir(opts) {
40
+ const resolvedDir = resolvePath(opts.dir);
41
+ const resolvedCwd = resolvePath(process.cwd());
42
+ if (resolvedDir === resolvedCwd) {
43
+ throw new Error(
44
+ `cleanOutDir refused to wipe ${resolvedDir} \u2014 must be a child of cwd, not cwd itself`
45
+ );
46
+ }
47
+ if (!resolvedDir.startsWith(resolvedCwd + sep)) {
48
+ throw new Error(
49
+ `cleanOutDir refused to wipe ${resolvedDir} \u2014 must be inside cwd (${resolvedCwd})`
50
+ );
51
+ }
52
+ const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName));
53
+ let entries;
54
+ try {
55
+ entries = await fs.readdir(resolvedDir, { withFileTypes: true });
56
+ } catch (err) {
57
+ const code = err.code;
58
+ if (code === "ENOENT") return { deleted: 0, kept: 0 };
59
+ throw err;
60
+ }
61
+ let deleted = 0;
62
+ let kept = 0;
63
+ for (const entry of entries) {
64
+ const name = entry.name;
65
+ if (skip.has(name)) {
66
+ kept++;
67
+ continue;
68
+ }
69
+ const fullPath = resolvePath(resolvedDir, name);
70
+ try {
71
+ await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 });
72
+ deleted++;
73
+ } catch (err) {
74
+ const code = err.code;
75
+ if (code === "ENOENT") {
76
+ deleted++;
77
+ continue;
78
+ }
79
+ console.warn(
80
+ `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? "unknown"}); skipping`
81
+ );
82
+ kept++;
83
+ }
84
+ }
85
+ return { deleted, kept };
86
+ }
87
+ async function cleanBuildOutput(distDir) {
88
+ return cleanOutDir({
89
+ dir: distDir,
90
+ skip: [...DEFAULT_SKIP, ...AUTHORED_AGENT_CONTEXT, ...LOCAL_AGENT_STATE]
91
+ });
92
+ }
93
+
94
+ export {
95
+ AUTHORED_AGENT_CONTEXT,
96
+ cleanBuildOutput
97
+ };
98
+ //# sourceMappingURL=chunk-V3LMUQSB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/cleanup/cleanup.ts"],"sourcesContent":["/**\n * State cleanup utilities (Phase 2 of\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\n/**\n * `.theokit/` holds two unrelated things: what `theokit build` writes (the default `distDir`), and\n * the agent context the framework and `@theokit/sdk` read at runtime. These lists name the second\n * kind so the build stops deleting it (#1079) and the generated ignore files can tell the two apart\n * (#1075, #1069).\n */\n\n/**\n * Entries a person writes and the project versions and ships: the instruction file, rules,\n * personalities, skills, sub-agents, slash commands and hooks.\n *\n * `packages/create-theokit/templates/default/_gitignore` un-ignores the same names; a test keeps\n * the two in step, because create-theokit cannot import from this package.\n */\nexport const AUTHORED_AGENT_CONTEXT = [\n 'THEO.md',\n 'rules',\n 'personalities',\n 'skills',\n 'agents',\n 'commands',\n 'hooks.json',\n] as const\n\n/**\n * Entries the agent runtime or a single developer writes: memory, local overrides, credentials,\n * trust and approval records, plugin bundles. A build keeps them; git and the image leave them out,\n * since several hold tokens.\n */\nconst LOCAL_AGENT_STATE = [\n 'THEO.local.md',\n 'AGENTS.local.md',\n 'memory',\n 'context',\n 'context.json',\n 'config.json',\n 'settings.json',\n 'mcp.json',\n 'hooks',\n 'plugins',\n 'cron',\n 'profiles',\n 'auth.json',\n 'mcp-tokens.json',\n 'credential-pool.json',\n 'tool-permissions.json',\n 'hook-approvals.json',\n] as const\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\n/**\n * Empty the build output directory before `theokit build` writes into it, keeping the agent context\n * and local agent state that share `.theokit/` with the build output. Emptying it whole deleted the\n * scaffold's THEO.md, rules and personalities on the first build (#1079).\n */\nexport async function cleanBuildOutput(distDir: string): Promise<CleanOutDirResult> {\n return cleanOutDir({\n dir: distDir,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U;AACd,MAAI,OAAO;AACX,aAAW,SAAS,SAAS;AAC3B,UAAM,OAAO,MAAM;AACnB,QAAI,KAAK,IAAI,IAAI,GAAG;AAClB;AACA;AAAA,IACF;AACA,UAAM,WAAW,YAAY,aAAa,IAAI;AAC9C,QAAI;AACF,YAAM,GAAG,GAAG,UAAU,EAAE,WAAW,MAAM,OAAO,MAAM,YAAY,EAAE,CAAC;AACrE;AAAA,IACF,SAAS,KAAK;AACZ,YAAM,OAAQ,IAA8B;AAC5C,UAAI,SAAS,UAAU;AACrB;AACA;AAAA,MACF;AAEA,cAAQ;AAAA,QACN,0CAA0C,QAAQ,KAAK,QAAQ,SAAS;AAAA,MAC1E;AACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,SAAS,KAAK;AACzB;AAoCA,eAAsB,iBAAiB,SAA6C;AAClF,SAAO,YAAY;AAAA,IACjB,KAAK;AAAA,IACL,MAAM,CAAC,GAAG,cAAc,GAAG,wBAAwB,GAAG,iBAAiB;AAAA,EACzE,CAAC;AACH;","names":[]}
package/dist/cli/index.js CHANGED
@@ -23,7 +23,7 @@ cli.command("dev", "Start development server").option("--port <port>", "Port num
23
23
  });
24
24
  cli.command("build", "Build for production").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
25
25
  try {
26
- const { buildCommand } = await import("../build-QDZEOCJ3.js");
26
+ const { buildCommand } = await import("../build-Y457R5HE.js");
27
27
  await buildCommand({ target: options.target });
28
28
  } catch (err) {
29
29
  const msg = err instanceof Error ? err.message : String(err);
@@ -47,7 +47,7 @@ cli.command("start", "Start production server").option("--port <port>", "Port nu
47
47
  });
48
48
  cli.command("preview", "Build for production, then serve it \u2014 one step (B-030)").option("--port <port>", "Port number").option("--target <target>", "Deploy target (node, vercel, cloudflare)").action(async (options) => {
49
49
  try {
50
- const { previewCommand } = await import("../preview-GP6J6IGJ.js");
50
+ const { previewCommand } = await import("../preview-Y3JNYOFK.js");
51
51
  await previewCommand({
52
52
  port: options.port ? Number(options.port) : void 0,
53
53
  target: options.target
@@ -65,7 +65,7 @@ cli.command(
65
65
  "Scaffold a route, action, page, ws, controller, agent, toolbox, workflow, eval, sandbox, schedule, memory, or resource (resource accepts field:type args)"
66
66
  ).action(async (type, name, fields) => {
67
67
  try {
68
- const { generateCommand } = await import("../generate-OA5ARO3P.js");
68
+ const { generateCommand } = await import("../generate-4DY3MEYB.js");
69
69
  await generateCommand(type, name, fields.length > 0 ? fields : void 0);
70
70
  } catch (err) {
71
71
  const msg = err instanceof Error ? err.message : String(err);
@@ -160,7 +160,7 @@ cli.command("check", "Run typecheck + scan + (optional) eslint").option(
160
160
  await checkCommand();
161
161
  });
162
162
  cli.command("add <package>", "Install a known TheoKit adapter or plugin (whitelist-only)").action(async (pkg) => {
163
- const { addCommand } = await import("../add-DOR7HORT.js");
163
+ const { addCommand } = await import("../add-NFDL4OJ7.js");
164
164
  await addCommand(pkg);
165
165
  });
166
166
  cli.command("info", "Print environment info (runtime, config, routes)").action(async () => {
@@ -223,7 +223,7 @@ cli.command(
223
223
  });
224
224
  cli.command("docker", "Generate Dockerfile for production").option("--force", "Overwrite existing Dockerfile").action(async (options) => {
225
225
  try {
226
- const { dockerCommand } = await import("../docker-LZZB4D5E.js");
226
+ const { dockerCommand } = await import("../docker-OTV3M54A.js");
227
227
  await dockerCommand({ force: options.force });
228
228
  } catch (err) {
229
229
  const msg = err instanceof Error ? err.message : String(err);
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+ import "tsx/esm";
3
+ import {
4
+ AUTHORED_AGENT_CONTEXT
5
+ } from "./chunk-V3LMUQSB.js";
6
+ import {
7
+ loadConfig
8
+ } from "./chunk-35OI2TKT.js";
9
+ import "./chunk-3QPVEJ7D.js";
10
+ import "./chunk-O5JZ6ROY.js";
11
+ import "./chunk-PQWVT6JC.js";
12
+ import "./chunk-L4V5V2TI.js";
13
+ import "./chunk-MAJZ2L3A.js";
14
+
15
+ // src/cli/commands/docker.ts
16
+ import { existsSync, writeFileSync } from "fs";
17
+ import { resolve } from "path";
18
+ function detectPkgManager(cwd) {
19
+ if (existsSync(resolve(cwd, "pnpm-lock.yaml"))) return "pnpm";
20
+ if (existsSync(resolve(cwd, "yarn.lock"))) return "yarn";
21
+ return "npm";
22
+ }
23
+ var THEOKIT_BIN = "./node_modules/.bin/theokit";
24
+ function topLevelDir(path) {
25
+ return path.replace(/^\.\//, "").split("/")[0];
26
+ }
27
+ function generateDockerfile(input) {
28
+ const { pkgManager, distDir } = input;
29
+ const installCmd = {
30
+ pnpm: "RUN corepack enable && pnpm install --frozen-lockfile",
31
+ npm: "RUN npm ci",
32
+ yarn: "RUN yarn install --frozen-lockfile"
33
+ }[pkgManager];
34
+ const lockfile = {
35
+ pnpm: "pnpm-lock.yaml",
36
+ npm: "package-lock.json",
37
+ yarn: "yarn.lock"
38
+ }[pkgManager];
39
+ const manifests = [
40
+ "package.json",
41
+ lockfile,
42
+ ...pkgManager === "pnpm" && input.hasPnpmWorkspace ? ["pnpm-workspace.yaml"] : []
43
+ ];
44
+ const copySources = [...new Set(input.sourceRoots)].map(
45
+ (root) => `COPY --from=builder /app/${root} ./${root}`
46
+ );
47
+ return [
48
+ "# Generated by TheoKit",
49
+ "# Multi-stage build for production",
50
+ "",
51
+ "# Stage 1: Build",
52
+ "FROM node:22-alpine AS builder",
53
+ "WORKDIR /app",
54
+ `COPY ${manifests.join(" ")} ./`,
55
+ installCmd,
56
+ "COPY . .",
57
+ `RUN ${THEOKIT_BIN} build`,
58
+ "",
59
+ "# Stage 2: Production",
60
+ "FROM node:22-alpine AS runner",
61
+ "WORKDIR /app",
62
+ "ENV NODE_ENV=production",
63
+ // Inside a container `localhost` answers nobody, the image's own health check included (#402).
64
+ "ENV HOST=0.0.0.0",
65
+ "ENV PORT=3000",
66
+ `COPY --from=builder /app/${distDir} ./${distDir}`,
67
+ ...copySources,
68
+ ...input.hasConfigFile ? ["COPY --from=builder /app/theo.config.ts ./theo.config.ts"] : [],
69
+ ...manifests.map((file) => `COPY --from=builder /app/${file} ./${file}`),
70
+ "COPY --from=builder /app/node_modules ./node_modules",
71
+ "",
72
+ "EXPOSE 3000",
73
+ `CMD ["${THEOKIT_BIN}", "start"]`,
74
+ ""
75
+ ].join("\n");
76
+ }
77
+ function generateDockerignore(distDir = ".theokit") {
78
+ return [
79
+ "node_modules",
80
+ ".git",
81
+ `${distDir}/*`,
82
+ // A re-included directory brings its contents: Docker matches a pattern against every parent.
83
+ ...AUTHORED_AGENT_CONTEXT.map((entry) => `!${distDir}/${entry}`),
84
+ "dist",
85
+ ".env",
86
+ ".env.*",
87
+ "!.env.example",
88
+ "*.log",
89
+ ".DS_Store",
90
+ ".vscode",
91
+ ".idea",
92
+ "Dockerfile",
93
+ ".dockerignore",
94
+ ""
95
+ ].join("\n");
96
+ }
97
+ async function dockerCommand(options) {
98
+ const cwd = process.cwd();
99
+ const dockerfilePath = resolve(cwd, "Dockerfile");
100
+ const dockerignorePath = resolve(cwd, ".dockerignore");
101
+ const pkgManager = detectPkgManager(cwd);
102
+ const { serverDir, agentsDir, distDir } = await loadConfig(cwd);
103
+ const dockerfile = generateDockerfile({
104
+ pkgManager,
105
+ sourceRoots: [topLevelDir(serverDir), topLevelDir(agentsDir)],
106
+ distDir,
107
+ hasConfigFile: existsSync(resolve(cwd, "theo.config.ts")),
108
+ hasPnpmWorkspace: existsSync(resolve(cwd, "pnpm-workspace.yaml"))
109
+ });
110
+ try {
111
+ writeFileSync(dockerfilePath, dockerfile, { flag: options?.force ? "w" : "wx" });
112
+ } catch (err) {
113
+ if (err.code !== "EEXIST") throw err;
114
+ console.log("\n \u26A0 Dockerfile already exists. Use --force to overwrite.\n");
115
+ return;
116
+ }
117
+ writeFileSync(dockerignorePath, generateDockerignore(distDir));
118
+ console.log(`
119
+ \u2713 Generated Dockerfile (${pkgManager})`);
120
+ console.log(` \u2713 Generated .dockerignore`);
121
+ console.log(`
122
+ Next steps:`);
123
+ console.log(` docker build -t my-app .`);
124
+ console.log(` docker run -p 3000:3000 my-app
125
+ `);
126
+ }
127
+ export {
128
+ dockerCommand
129
+ };
130
+ //# sourceMappingURL=docker-OTV3M54A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/docker.ts"],"sourcesContent":["import { existsSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { loadConfig } from '../../config/load-config.js'\nimport { AUTHORED_AGENT_CONTEXT } from '../cleanup/cleanup.js'\n\nfunction detectPkgManager(cwd: string): PkgManager {\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(resolve(cwd, 'yarn.lock'))) return 'yarn'\n return 'npm'\n}\n\ntype PkgManager = 'pnpm' | 'npm' | 'yarn'\n\ninterface DockerfileInput {\n readonly pkgManager: PkgManager\n /** Top-level directories holding the server and agent sources, e.g. `['src']` for the scaffold. */\n readonly sourceRoots: readonly string[]\n /** The configured build output directory, `.theokit` by default. */\n readonly distDir: string\n readonly hasConfigFile: boolean\n readonly hasPnpmWorkspace: boolean\n}\n\n/**\n * The installed CLI, by path. `npx theo build` asked the registry for a package named `theo`, an\n * unrelated design-tokens tool, then installed and ran it inside the image build (#1069). A path\n * into `node_modules/.bin` cannot fall back to the registry under any package manager.\n */\nconst THEOKIT_BIN = './node_modules/.bin/theokit'\n\n/**\n * The top-level directory a configured path lives in. The runner copies whole roots: the scaffold's\n * `src/server` imports `src/shared`, so copying only `serverDir` would leave an import dangling.\n */\nfunction topLevelDir(path: string): string {\n return path.replace(/^\\.\\//, '').split('/')[0]\n}\n\nfunction generateDockerfile(input: DockerfileInput): string {\n const { pkgManager, distDir } = input\n const installCmd = {\n pnpm: 'RUN corepack enable && pnpm install --frozen-lockfile',\n npm: 'RUN npm ci',\n yarn: 'RUN yarn install --frozen-lockfile',\n }[pkgManager]\n\n const lockfile = {\n pnpm: 'pnpm-lock.yaml',\n npm: 'package-lock.json',\n yarn: 'yarn.lock',\n }[pkgManager]\n\n // pnpm 10 reads `allowBuilds` from pnpm-workspace.yaml; installing without it leaves esbuild unbuilt.\n const manifests = [\n 'package.json',\n lockfile,\n ...(pkgManager === 'pnpm' && input.hasPnpmWorkspace ? ['pnpm-workspace.yaml'] : []),\n ]\n\n const copySources = [...new Set(input.sourceRoots)].map(\n (root) => `COPY --from=builder /app/${root} ./${root}`,\n )\n\n return [\n '# Generated by TheoKit',\n '# Multi-stage build for production',\n '',\n '# Stage 1: Build',\n 'FROM node:22-alpine AS builder',\n 'WORKDIR /app',\n `COPY ${manifests.join(' ')} ./`,\n installCmd,\n 'COPY . .',\n `RUN ${THEOKIT_BIN} build`,\n '',\n '# Stage 2: Production',\n 'FROM node:22-alpine AS runner',\n 'WORKDIR /app',\n 'ENV NODE_ENV=production',\n // Inside a container `localhost` answers nobody, the image's own health check included (#402).\n 'ENV HOST=0.0.0.0',\n 'ENV PORT=3000',\n `COPY --from=builder /app/${distDir} ./${distDir}`,\n ...copySources,\n ...(input.hasConfigFile ? ['COPY --from=builder /app/theo.config.ts ./theo.config.ts'] : []),\n ...manifests.map((file) => `COPY --from=builder /app/${file} ./${file}`),\n 'COPY --from=builder /app/node_modules ./node_modules',\n '',\n 'EXPOSE 3000',\n `CMD [\"${THEOKIT_BIN}\", \"start\"]`,\n '',\n ].join('\\n')\n}\n\n/**\n * `.theokit` is both the build output and the agent context (#1079). The context a person writes\n * (THEO.md, rules, personalities ...) goes into the image; local agent state such as memory and MCP\n * tokens stays out, and so does a stale local build, which the image rebuilds anyway.\n */\nfunction generateDockerignore(distDir = '.theokit'): string {\n return [\n 'node_modules',\n '.git',\n `${distDir}/*`,\n // A re-included directory brings its contents: Docker matches a pattern against every parent.\n ...AUTHORED_AGENT_CONTEXT.map((entry) => `!${distDir}/${entry}`),\n 'dist',\n '.env',\n '.env.*',\n '!.env.example',\n '*.log',\n '.DS_Store',\n '.vscode',\n '.idea',\n 'Dockerfile',\n '.dockerignore',\n '',\n ].join('\\n')\n}\n\nexport async function dockerCommand(options?: { force?: boolean }): Promise<void> {\n const cwd = process.cwd()\n const dockerfilePath = resolve(cwd, 'Dockerfile')\n const dockerignorePath = resolve(cwd, '.dockerignore')\n\n const pkgManager = detectPkgManager(cwd)\n const { serverDir, agentsDir, distDir } = await loadConfig(cwd)\n const dockerfile = generateDockerfile({\n pkgManager,\n sourceRoots: [topLevelDir(serverDir), topLevelDir(agentsDir)],\n distDir,\n hasConfigFile: existsSync(resolve(cwd, 'theo.config.ts')),\n hasPnpmWorkspace: existsSync(resolve(cwd, 'pnpm-workspace.yaml')),\n })\n\n // `wx` refuses an existing file in the same call that creates it. A separate exists check\n // followed by a write leaves a window, wider now that the config load sits between them.\n try {\n writeFileSync(dockerfilePath, dockerfile, { flag: options?.force ? 'w' : 'wx' })\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err\n console.log('\\n ⚠ Dockerfile already exists. Use --force to overwrite.\\n')\n return\n }\n writeFileSync(dockerignorePath, generateDockerignore(distDir))\n\n console.log(`\\n ✓ Generated Dockerfile (${pkgManager})`)\n console.log(` ✓ Generated .dockerignore`)\n console.log(`\\n Next steps:`)\n console.log(` docker build -t my-app .`)\n console.log(` docker run -p 3000:3000 my-app\\n`)\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,YAAY,qBAAqB;AAC1C,SAAS,eAAe;AAKxB,SAAS,iBAAiB,KAAyB;AACjD,MAAI,WAAW,QAAQ,KAAK,gBAAgB,CAAC,EAAG,QAAO;AACvD,MAAI,WAAW,QAAQ,KAAK,WAAW,CAAC,EAAG,QAAO;AAClD,SAAO;AACT;AAmBA,IAAM,cAAc;AAMpB,SAAS,YAAY,MAAsB;AACzC,SAAO,KAAK,QAAQ,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAC/C;AAEA,SAAS,mBAAmB,OAAgC;AAC1D,QAAM,EAAE,YAAY,QAAQ,IAAI;AAChC,QAAM,aAAa;AAAA,IACjB,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;A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ACb;AAEA,eAAsB,cAAc,SAA8C;AAChF,QAAM,MAAM,QAAQ,IAAI;AACxB,QAAM,iBAAiB,QAAQ,KAAK,YAAY;AAChD,QAAM,mBAAmB,QAAQ,KAAK,eAAe;AAErD,QAAM,aAAa,iBAAiB,GAAG;AACvC,QAAM,EAAE,WAAW,WAAW,QAAQ,IAAI,MAAM,WAAW,GAAG;AAC9D,QAAM,aAAa,mBAAmB;AAAA,IACpC;AAAA,IACA,aAAa,CAAC,YAAY,SAAS,GAAG,YAAY,SAAS,CAAC;AAAA,IAC5D;AAAA,IACA,eAAe,WAAW,QAAQ,KAAK,gBAAgB,CAAC;AAAA,IACxD,kBAAkB,WAAW,QAAQ,KAAK,qBAAqB,CAAC;AAAA,EAClE,CAAC;AAID,MAAI;AACF,kBAAc,gBAAgB,YAAY,EAAE,MAAM,SAAS,QAAQ,MAAM,KAAK,CAAC;AAAA,EACjF,SAAS,KAAK;AACZ,QAAK,IAA8B,SAAS,SAAU,OAAM;AAC5D,YAAQ,IAAI,mEAA8D;AAC1E;AAAA,EACF;AACA,gBAAc,kBAAkB,qBAAqB,OAAO,CAAC;AAE7D,UAAQ,IAAI;AAAA,iCAA+B,UAAU,GAAG;AACxD,UAAQ,IAAI,kCAA6B;AACzC,UAAQ,IAAI;AAAA,cAAiB;AAC7B,UAAQ,IAAI,8BAA8B;AAC1C,UAAQ,IAAI;AAAA,CAAsC;AACpD;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  detectProjectPackageManager
5
- } from "./chunk-JVXDEIT4.js";
5
+ } from "./chunk-I2IDWM26.js";
6
6
  import {
7
7
  cronScanDirs,
8
8
  isDiscoverableCronFile,
@@ -1068,4 +1068,4 @@ export {
1068
1068
  generate,
1069
1069
  generateCommand
1070
1070
  };
1071
- //# sourceMappingURL=generate-OA5ARO3P.js.map
1071
+ //# sourceMappingURL=generate-4DY3MEYB.js.map
@@ -4,7 +4,7 @@ import "tsx/esm";
4
4
  // src/cli/commands/preview.ts
5
5
  async function defaultSteps() {
6
6
  const [{ buildCommand }, { startCommand }] = await Promise.all([
7
- import("./build-QDZEOCJ3.js"),
7
+ import("./build-Y457R5HE.js"),
8
8
  import("./start-EJFYT7ZU.js")
9
9
  ]);
10
10
  return {
@@ -20,4 +20,4 @@ async function previewCommand(options = {}, steps) {
20
20
  export {
21
21
  previewCommand
22
22
  };
23
- //# sourceMappingURL=preview-GP6J6IGJ.js.map
23
+ //# sourceMappingURL=preview-Y3JNYOFK.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "theokit",
3
- "version": "0.77.0",
3
+ "version": "0.77.1",
4
4
  "description": "The TheoKit web framework — file-based routing, typed server surfaces, the Vite plugin, the CLI and the deploy adapters, around agents served from agents/*.ts.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -151,8 +151,8 @@
151
151
  "typescript": "^5.9.3",
152
152
  "vite": "^7.3.7",
153
153
  "@theokit/agents": "^16.1.1",
154
- "@theokit/http": "^2.3.0",
155
- "@theokit/presenter": "^0.10.0"
154
+ "@theokit/presenter": "^0.10.0",
155
+ "@theokit/http": "^2.3.1"
156
156
  },
157
157
  "peerDependencies": {
158
158
  "@theokit/sdk": "^5.11.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/build.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/jobs/job-manifest.ts","../src/cli/cleanup/cleanup.ts","../src/cli/commands/build/describe-services-manifest.ts","../src/cli/commands/build-scan-routes.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 {\n VALID_TARGETS,\n targetRendersDocument,\n type BuildTarget,\n type AdapterBuildContext,\n type DeployAdapter,\n} from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../config/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 { cronScanDirs, scanCronDirs } 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'\n// G2 T2.2 — OpenAPI emit. Opt-in via `config.openapi`. Dual output:\n// 1. <distDir>/openapi.json (pre-Vite, dev surface + manifests sibling)\n// 2. dist/openapi.json (post-Vite, build artifact)\n// The dist emit awaits runAdapterBuild — if Vite fails, the second emit\n// never runs (EC-2 absorbed: no stale dist artifact).\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\nimport { cleanOutDir } from '../cleanup/cleanup.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport { describeServicesManifest } from './build/describe-services-manifest.js'\nimport { describeControllerArtifacts, emitControllerArtifacts } from './build/emit-controllers.js'\nimport { createBuildScanRoutes } from './build-scan-routes.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\n// DERIVED, never restated. A hand-written list here went stale and told users\n// that three working targets were unsupported: it named node/vercel/cloudflare\n// while aws-lambda, deno-deploy and theo-cloud also translate crons. Deriving\n// from the two constants means adding a target cannot desynchronise the message.\nconst CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t))\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n // #95 — honor config.appDir so a custom frontend dir (e.g. apps/web) passes the structure gate.\n validateProjectStructure(cwd, config.appDir)\n\n // B-336 — EVERY refusal that is decidable from the target and the config alone runs BEFORE the\n // clean. `cleanOutDir` used to sit here, above even the check that the target EXISTS: measured on a\n // real project, `theokit build --target nao-existe` destroyed 302 files in `.theokit/client/assets`\n // and answered with a message about the typo. The comment above\n // `assertRateLimitEnforceable` already stated this intent in its own words — \"refused by name,\n // BEFORE the build writes anything\" — and the order defeated it.\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 const { resolveAdapter, streamingTargets } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n const { assertRateLimitEnforceable, assertStreamingSupported } =\n await import('../../adapters/config-support.js')\n\n // #461 — a dropped `cors` degrades where someone can see it; a dropped RATE LIMIT looks exactly like\n // success until the abuse it was meant to stop. Refused by name, and now genuinely before anything is\n // written or destroyed.\n assertRateLimitEnforceable(config, adapter, target)\n assertStreamingSupported(config, adapter, target, await streamingTargets())\n\n // T2.2 — Clean .theokit/ at build start (Astro pattern). Skip .git*.\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanOutDir({ dir: distDirAbs })\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 // #95 follow-up — pass projectRoot (cwd) + config.agentsDir so agents scan honors a custom dir.\n const manifest = generateManifest(serverDir, cwd, config.agentsDir)\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, agentsDir: config.agentsDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // theokit#123 — compile `server/controllers/**` so `theokit start` can serve them.\n //\n // #122 made controllers first-class in dev, where Vite's swc transform compiles them on the fly.\n // Production has neither, so an uncompiled `.controller.ts` cannot load and its routes 404'd —\n // working in dev and failing in prod, which is the worst place for a gap to live.\n //\n // Deliberately NOT folded into `generateManifest` (ADR-5): the manifest is the deploy-adapter\n // contract, and a parallel route source in it would ripple through every adapter. This writes a\n // separate artifact only the Node start path reads. No controllers ⇒ no artifact at all.\n const controllerManifest = await emitControllerArtifacts({ serverDir, distDir })\n if (controllerManifest !== null) {\n console.log(` ${describeControllerArtifacts(controllerManifest)}`)\n }\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theokit/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 //\n // Plan v1.2 T2.1 — when theo.config.ts declares `name`, emit services.json\n // v2 with that project identifier. Falling back to v1 (no project field)\n // keeps TheoCloud's deprecation warning path intact (services-bundle).\n const projectName = config.name\n const servicesManifest = buildServicesManifest(config.services, projectName)\n writeServicesManifest(cwd, servicesManifest)\n const servicesLine = describeServicesManifest(servicesManifest, target)\n if (servicesLine !== null) console.log(` ${servicesLine}`)\n\n // G2 T2.2 — OpenAPI dev-surface emit (pre-Vite, sibling of manifests).\n // Opt-in: only when config.openapi is defined. Best-effort: a route load\n // failure produces a warning, not a build abort.\n if (config.openapi !== undefined) {\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const devResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(` ✓ OpenAPI: ${String(hydrated.length)} ops → ${devResult.path}`)\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd, adapter)\n\n // G2 T2.2 — OpenAPI build-artifact emit (post-Vite, EC-2 gated on success).\n // If runAdapterBuild threw, execution never reaches this point — no stale\n // dist/openapi.json is written.\n if (config.openapi !== undefined) {\n const distOut = resolve(cwd, 'dist')\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const distResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distOut },\n })\n console.log(` ✓ OpenAPI (dist): ${distResult.path}`)\n }\n\n // Derived, not asserted. This read `config.ssr` alone, so a target whose entry delegates the\n // document to a static host was announced as server-rendering — measured on `--target bun`, which\n // printed `(SSR)` and served an empty `<div id=\"root\">` (B-334).\n const ssrNote = config.ssr && targetRendersDocument(target) ? ' (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 // Resolved by the caller, which needs it before `cleanOutDir` to run the refusals (B-336). Passing it\n // in rather than resolving again keeps one answer to \"which adapter is this build\".\n adapter: DeployAdapter,\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 //\n // 0.2.2 regression fix: switched sync `theoPlugin()` → `theoPluginAsync()` so the\n // returned Plugin[] includes the @theo/actions virtual module + typed-client +\n // services + @theokit/ui auto-chain. Without async, build-time Rollup couldn't\n // resolve `@theo/actions` even though dev-time Vite (which already used async)\n // could. See https://github.com/usetheo/theokit/commits — 0.2.2 changelog.\n const { theoPluginAsync } = 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; spread the\n // async chain so the contract returns a flat Plugin[] (AdapterBuildContext\n // type updated to `Plugin[] | Promise<Plugin[]>`).\n // #95 — inject the config dirs so the client build's router/entry + typed-client codegen honor\n // custom appDir/serverDir/agentsDir (e.g. \"apps/web\" / \"core\" / \"core/agents\").\n makeVitePlugins: async (opts) =>\n [\n react(),\n ...(await theoPluginAsync({\n ...opts,\n appDir: config.appDir,\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })),\n ].flat(),\n\n // #369 — the same inversion, for the same reason. A Worker has no filesystem, so the Cloudflare\n // entry bakes its routes at build time; importing the scanner from `adapters/` would add the\n // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The\n // CLI already imports both sides, so it composes the scan and hands over the result.\n //\n // A module rather than a closure since B-312: the wrong argument it carried was unreachable from\n // any test while it lived in here, because reaching it meant running the whole build.\n scanRoutes: createBuildScanRoutes(cwd, config),\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 // #409 / #410 — a config key that validates and is then never read makes the\n // deployed app behave as if the operator had not written it, with nothing\n // anywhere saying so. Name it before the build output scrolls past.\n const { warnUnappliedConfig } = await import('../../adapters/config-support.js')\n\n // #461 / #321 / #322 — the rate-limit refusal moved to `buildCommand`, above `cleanOutDir`, because\n // this position made its own comment false: it claimed the combination was refused \"BEFORE the build\n // writes anything\" and it is reached a hundred lines after the output has been emptied (B-336).\n\n warnUnappliedConfig(config, adapter, target, (message) => {\n console.log(message)\n })\n\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n agentsDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n // Crons live in two conventional homes: `server/crons/` (a backend trigger) and\n // `agents/schedules/` (a scheduled agent run, kept in the agent domain). Both feed one manifest.\n const { crons, schedules } = cronScanDirs(opts.cwd, opts.serverDir, opts.agentsDir)\n\n const cronNodes = await scanCronDirs([crons, schedules])\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 `Supported targets: ${CRON_SUPPORTED_TARGETS.join(', ')}.`,\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\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","/* 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: .theokit/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 → .theokit/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 */\n// T5a.1b — Web Crypto migration. Build-time only; node:fs + node:path stay\n// because this is a manifest-write leaf (e.g. .theokit/jobs.json) and per\n// ADR-0028 the runtime-portable boundary is the request handler, not the\n// scanner. Only node:crypto is swapped out — Web Crypto's\n// getRandomValues works in every supported runtime.\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 * `.theokit/crons.json` and `.theokit/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. Web Crypto getRandomValues is non-blocking +\n // collision-safe for the tiny entropy we need (8 hex chars = 32 bits).\n // Hex-encoded manually to avoid Buffer (runtime-agnostic per ADR-0028).\n const randBuf = new Uint8Array(4)\n globalThis.crypto.getRandomValues(randBuf)\n let suffix = ''\n for (const b of randBuf) suffix += b.toString(16).padStart(2, '0')\n const tmp = `${path}.tmp-${process.pid}-${suffix}`\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","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","/**\n * State cleanup utilities (Phase 2 of\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","import type { BuildTarget } from '../../../adapters/types.js'\nimport type { ServicesManifest } from '../../../services/index.js'\n\n/**\n * The build line about `.theokit/services.json`, or `null` when there is nothing worth saying.\n *\n * The v1 warning is addressed to `theo-cloud`, the one target that reads the file. It used to print\n * on every target, for apps that declare no services, and it named a sunset in `theokit 0.6.0` that\n * had passed 68 minors earlier without anything being removed. A deadline nobody enforces teaches\n * the reader to skip the line, so the warning states what the file is and how to upgrade it.\n */\nexport function describeServicesManifest(\n manifest: ServicesManifest,\n target: BuildTarget,\n): string | null {\n if (manifest.services.length > 0) {\n const projectLabel = manifest.version === 2 ? ` project=\"${manifest.project}\"` : ''\n const names = manifest.services.map((s) => s.name).join(', ')\n return (\n `✓ Services manifest (v${String(manifest.version)}${projectLabel}): ` +\n `${String(manifest.services.length)} service(s) (${names})`\n )\n }\n if (manifest.version === 1 && target === 'theo-cloud') {\n return (\n '⚠ services.json emitted as v1 (no `name` in theo.config.ts), which TheoCloud reads as ' +\n 'deprecated. Run `theokit migrate services-json-v1-to-v2` to upgrade.'\n )\n }\n return null\n}\n","import { existsSync } from 'node:fs'\nimport { join, relative, resolve, sep } from 'node:path'\n\nimport type { AdapterBuildContext } from '../../adapters/types.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\nimport { scanServerRoutes } from '../../server/scan/scan.js'\nimport { scanWebSocketRoutes } from '../../server/scan/ws-scan.js'\n\n/**\n * What a scanned deploy target is handed instead of a filesystem.\n *\n * #369 — a Worker has no filesystem at request time, so the Cloudflare entry bakes its routes at\n * build time. Importing the scanner from `adapters/` would add the `adapters → server` edge that\n * `adapters-may-only-depend-on-core-router-services` refuses, so the CLI composes the scan and\n * hands over the result.\n *\n * ## Why this is a module rather than a closure inside `buildCommand`\n *\n * It was a closure, and the defect it carried was invisible to every test: `buildCommand` loads a\n * config, runs vite twice and writes a tree, so nothing could ask it one question about one call.\n * Extracted at B-312, whose whole content was a single argument being wrong.\n *\n * Paths are made relative to the project root here, where `projectRoot` is known: that string is\n * both the emitted import specifier and the key the executor looks a module up by, and the scanners\n * return absolute paths.\n */\nexport function createBuildScanRoutes(\n projectRoot: string,\n config: { agentsDir?: string },\n): NonNullable<AdapterBuildContext['scanRoutes']> {\n return (serverDir: string) => {\n const abs = resolve(projectRoot, serverDir)\n const toProjectRelative = (p: string): string => relative(projectRoot, p).split(sep).join('/')\n\n return {\n routes: scanServerRoutes(abs).map((route) => ({\n filePath: toProjectRelative(route.filePath),\n routePath: route.routePath,\n methods: route.methods ?? [],\n })),\n wsRoutes: scanWebSocketRoutes(abs).map((ws) =>\n toProjectRelative(typeof ws === 'string' ? ws : ws.filePath),\n ),\n // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no adapter\n // had ever heard of them: the entries route `/api/` through `scanServerRoutes` +\n // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.\n // Scanned here, beside the routes, because the same inversion argument applies verbatim.\n //\n // B-312 — the root is the PROJECT ROOT, and was `dirname(abs)`. `config.agentsDir` is\n // documented and declared relative to the project root, while `dirname(serverDir)` is the\n // root only when `serverDir` is a direct child of it. The scaffold's own nested layout\n // (`serverDir: 'src/server'`, `agentsDir: 'src/server/agents'`) made the two disagree, and\n // `join()` produced `<root>/src/src/server/agents` — so `scanAgents` returned `[]` and every\n // `/api/agents/*` route 404'd on every scanned target. Measured on a live Cloudflare deploy,\n // 2026-09-26. Every other caller in the tree already passes the project root.\n agents: scanAgents(projectRoot, config.agentsDir).map((agent) => ({\n filePath: toProjectRelative(agent.filePath),\n agentPath: agent.agentPath,\n name: agent.name,\n })),\n // B-185 — the identity module, decided here for the same reason the agents are: this provider\n // is handed `serverDir`, and a Worker has no filesystem to look for it on. An app with no\n // `server/context.ts` yields `undefined`, and the generator then emits no import — importing\n // a file that is not there would fail the BUILD rather than one request.\n contextModule: existsSync(join(abs, 'context.ts'))\n ? toProjectRelative(join(abs, 'context.ts'))\n : undefined,\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,WAAAC,gBAAe;;;ACExB,SAAS,YAAY,oBAAoB;;;ACMzC,SAAS,WAAW,YAAY,qBAAqB;AACrD,SAAS,eAAe;AAkBjB,SAAS,YAAY,MAAc,SAAuB;AAC/D,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAK5C,QAAM,UAAU,IAAI,WAAW,CAAC;AAChC,aAAW,OAAO,gBAAgB,OAAO;AACzC,MAAI,SAAS;AACb,aAAW,KAAK,QAAS,WAAU,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACjE,QAAM,MAAM,GAAG,IAAI,QAAQ,QAAQ,GAAG,IAAI,MAAM;AAChD,gBAAc,KAAK,SAAS,MAAM;AAClC,aAAW,KAAK,IAAI;AACtB;;;AD3BO,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;A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,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASE,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","resolve","relativize","isManifest","existsSync","sep","sep","existsSync","resolve","writeManifest","relativize","existsSync"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/add.ts"],"sourcesContent":["import { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nexport class InvalidPackageNameError extends Error {\n constructor(input: string, reason: string) {\n super(`Invalid package name \"${input}\": ${reason}`)\n this.name = 'InvalidPackageNameError'\n }\n}\n\nexport class UnknownPackageError extends Error {\n constructor(input: string, suggestion?: string) {\n super(\n suggestion\n ? `Unknown package: ${input}. Did you mean: ${suggestion}?`\n : `Unknown package: ${input}.`,\n )\n this.name = 'UnknownPackageError'\n }\n}\n\n/**\n * EC-4 — strict whitelist of characters allowed in package input.\n * Lowercase ASCII letters, digits, hyphens. Must start with letter/digit.\n * Rejects: shell metacharacters, path traversal, scope syntax, uppercase.\n */\nconst PACKAGE_NAME_REGEX = /^[a-z0-9][a-z0-9-]*$/\n\nexport function validatePackageInput(input: string): true {\n if (typeof input !== 'string' || input.length === 0) {\n throw new InvalidPackageNameError(input, 'must be a non-empty string')\n }\n if (!PACKAGE_NAME_REGEX.test(input)) {\n throw new InvalidPackageNameError(input, 'allowed: lowercase letters, digits, hyphens only')\n }\n return true\n}\n\nexport type PackageManager = 'pnpm' | 'bun' | 'yarn' | 'npm'\n\nexport function detectPackageManager(lockfiles: Record<string, boolean>): PackageManager {\n if (lockfiles['pnpm-lock.yaml']) return 'pnpm'\n if (lockfiles['bun.lockb']) return 'bun'\n if (lockfiles['yarn.lock']) return 'yarn'\n if (lockfiles['package-lock.json']) return 'npm'\n return 'npm'\n}\n\n/** The package manager whose lockfile sits in `cwd`; npm when there is none. */\nexport function detectProjectPackageManager(\n cwd: string,\n existsFn: (path: string) => boolean = existsSync,\n): PackageManager {\n return detectPackageManager({\n 'pnpm-lock.yaml': existsFn(resolve(cwd, 'pnpm-lock.yaml')),\n 'bun.lockb': existsFn(resolve(cwd, 'bun.lockb')),\n 'yarn.lock': existsFn(resolve(cwd, 'yarn.lock')),\n 'package-lock.json': existsFn(resolve(cwd, 'package-lock.json')),\n })\n}\n\ninterface PackageRegistryEntry {\n /** 'bundled' = adapter already shipped inside theokit; no npm install needed.\n * 'external' = adapter/plugin lives as a separate npm package. */\n kind: 'bundled' | 'external'\n /** Required when kind === 'external'. */\n npm?: string\n /** Usage hint printed to the user (e.g. `theokit build --target=bun`). */\n usage: string\n}\n\nexport const KNOWN_PACKAGES: Record<string, PackageRegistryEntry> = {\n bun: {\n kind: 'bundled',\n usage: 'theokit build --target=bun',\n },\n deno: {\n kind: 'bundled',\n usage: 'theokit build --target=deno-deploy',\n },\n netlify: {\n kind: 'bundled',\n usage: 'theokit build --target=netlify',\n },\n 'aws-lambda': {\n kind: 'bundled',\n usage: 'theokit build --target=aws-lambda',\n },\n static: {\n kind: 'bundled',\n usage: 'theokit build --target=static',\n },\n}\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length\n const n = b.length\n if (m === 0) return n\n if (n === 0) return m\n const dp: number[][] = Array.from({ length: m + 1 }, () =>\n Array.from<number>({ length: n + 1 }).fill(0),\n )\n for (let i = 0; i <= m; i++) dp[i][0] = i\n for (let j = 0; j <= n; j++) dp[0][j] = j\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)\n }\n }\n return dp[m][n]\n}\n\nfunction findSuggestion(input: string, candidates: string[]): string | undefined {\n let best: { name: string; d: number } | null = null\n for (const c of candidates) {\n const d = levenshtein(input, c)\n if (best === null || d < best.d) best = { name: c, d }\n }\n if (best && best.d <= 3) return best.name\n return undefined\n}\n\ninterface RunAddDeps {\n input: string\n cwd: string\n existsSync?: (path: string) => boolean\n spawnPm?: (\n cmd: string,\n args: string[],\n opts: { cwd: string; shell: boolean },\n ) => Promise<{ ok: boolean; code: number }>\n registry?: Record<string, PackageRegistryEntry>\n}\n\ninterface AddResult {\n packageInstalled: string\n packageManager: PackageManager | 'bundled'\n usage: string\n exitCode: 0\n}\n\nexport async function runAdd(deps: RunAddDeps): Promise<AddResult> {\n validatePackageInput(deps.input)\n\n const registry = deps.registry ?? KNOWN_PACKAGES\n if (!Object.hasOwn(registry, deps.input)) {\n const suggestion = findSuggestion(deps.input, Object.keys(registry))\n throw new UnknownPackageError(deps.input, suggestion)\n }\n const entry = registry[deps.input]\n\n // T6.1 — bundled adapters need no install\n if (entry.kind === 'bundled') {\n return {\n packageInstalled: `${deps.input} (bundled inside theokit)`,\n packageManager: 'bundled',\n usage: entry.usage,\n exitCode: 0,\n }\n }\n\n if (!entry.npm) {\n throw new Error(`External package \"${deps.input}\" missing npm field in registry`)\n }\n\n const pm = detectProjectPackageManager(deps.cwd, deps.existsSync)\n\n const args = pm === 'npm' ? ['install', entry.npm] : ['add', entry.npm]\n const spawnFn = deps.spawnPm ?? defaultSpawnPm\n const result = await spawnFn(pm, args, { cwd: deps.cwd, shell: false })\n\n if (!result.ok) {\n throw new Error(`Package manager exited with non-zero exit code ${result.code}`)\n }\n\n return {\n packageInstalled: entry.npm,\n packageManager: pm,\n usage: entry.usage,\n exitCode: 0,\n }\n}\n\nfunction defaultSpawnPm(\n cmd: string,\n args: string[],\n opts: { cwd: string; shell: boolean },\n): Promise<{ ok: boolean; code: number }> {\n return new Promise((resolve) => {\n const proc = spawn(cmd, args, { cwd: opts.cwd, shell: opts.shell, stdio: 'inherit' })\n proc.on('close', (code) => {\n resolve({ ok: code === 0, code: code ?? 1 })\n })\n proc.on('error', () => {\n resolve({ ok: false, code: 1 })\n })\n })\n}\n\nexport async function addCommand(input: string): Promise<void> {\n try {\n const result = await runAdd({ input, cwd: process.cwd() })\n console.log(`\\n ✓ Installed ${result.packageInstalled} via ${result.packageManager}\\n`)\n console.log(` Next: import { /* ... */ } from '${result.packageInstalled}'\\n`)\n } catch (err) {\n console.error(`\\n ✗ ${(err as Error).message}\\n`)\n process.exit(1)\n }\n}\n"],"mappings":";;;;AAAA,SAAS,aAAa;AACtB,SAAS,kBAAkB;AAC3B,SAAS,eAAe;AAEjB,IAAM,0BAAN,cAAsC,MAAM;AAAA,EACjD,YAAY,OAAe,QAAgB;AACzC,UAAM,yBAAyB,KAAK,MAAM,MAAM,EAAE;AAClD,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,OAAe,YAAqB;AAC9C;AAAA,MACE,aACI,oBAAoB,KAAK,mBAAmB,UAAU,MACtD,oBAAoB,KAAK;AAAA,IAC/B;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAOA,IAAM,qBAAqB;AAEpB,SAAS,qBAAqB,OAAqB;AACxD,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACnD,UAAM,IAAI,wBAAwB,OAAO,4BAA4B;AAAA,EACvE;AACA,MAAI,CAAC,mBAAmB,KAAK,KAAK,GAAG;AACnC,UAAM,IAAI,wBAAwB,OAAO,kDAAkD;AAAA,EAC7F;AACA,SAAO;AACT;AAIO,SAAS,qBAAqB,WAAoD;AACvF,MAAI,UAAU,gBAAgB,EAAG,QAAO;AACxC,MAAI,UAAU,WAAW,EAAG,QAAO;AACnC,MAAI,UAAU,WAAW,EAAG,QAAO;AACnC,MAAI,UAAU,mBAAmB,EAAG,QAAO;AAC3C,SAAO;AACT;AAGO,SAAS,4BACd,KACA,WAAsC,YACt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,EAAE,KAAK,KAAK,KAAK,OAAO,MAAM,CAAC;AAEtE,MAAI,CAAC,OAAO,IAAI;AACd,UAAM,IAAI,MAAM,kDAAkD,OAAO,IAAI,EAAE;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,kBAAkB,MAAM;AAAA,IACxB,gBAAgB;AAAA,IAChB,OAAO,MAAM;AAAA,IACb,UAAU;AAAA,EACZ;AACF;AAEA,SAAS,eACP,KACA,MACA,MACwC;AACxC,SAAO,IAAI,QAAQ,CAACA,aAAY;AAC9B,UAAM,OAAO,MAAM,KAAK,MAAM,EAAE,KAAK,KAAK,KAAK,OAAO,KAAK,OAAO,OAAO,UAAU,CAAC;AACpF,SAAK,GAAG,SAAS,CAAC,SAAS;AACzB,MAAAA,SAAQ,EAAE,IAAI,SAAS,GAAG,MAAM,QAAQ,EAAE,CAAC;AAAA,IAC7C,CAAC;AACD,SAAK,GAAG,SAAS,MAAM;AACrB,MAAAA,SAAQ,EAAE,IAAI,OAAO,MAAM,EAAE,CAAC;AAAA,IAChC,CAAC;AAAA,EACH,CAAC;AACH;AAEA,eAAsB,WAAW,OAA8B;AAC7D,MAAI;AACF,UAAM,SAAS,MAAM,OAAO,EAAE,OAAO,KAAK,QAAQ,IAAI,EAAE,CAAC;AACzD,YAAQ,IAAI;AAAA,qBAAmB,OAAO,gBAAgB,QAAQ,OAAO,cAAc;AAAA,CAAI;AACvF,YAAQ,IAAI,sCAAsC,OAAO,gBAAgB;AAAA,CAAK;AAAA,EAChF,SAAS,KAAK;AACZ,YAAQ,MAAM;AAAA,WAAU,IAAc,OAAO;AAAA,CAAI;AACjD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["resolve"]}
@@ -1,102 +0,0 @@
1
- #!/usr/bin/env node
2
- import "tsx/esm";
3
-
4
- // src/cli/commands/docker.ts
5
- import { existsSync, writeFileSync } from "fs";
6
- import { resolve } from "path";
7
- function detectPkgManager(cwd) {
8
- if (existsSync(resolve(cwd, "pnpm-lock.yaml"))) return "pnpm";
9
- if (existsSync(resolve(cwd, "yarn.lock"))) return "yarn";
10
- return "npm";
11
- }
12
- function generateDockerfile(pkgManager) {
13
- const installCmd = {
14
- pnpm: "RUN corepack enable && pnpm install --frozen-lockfile",
15
- npm: "RUN npm ci",
16
- yarn: "RUN yarn install --frozen-lockfile"
17
- }[pkgManager];
18
- const lockfile = {
19
- pnpm: "pnpm-lock.yaml",
20
- npm: "package-lock.json",
21
- yarn: "yarn.lock"
22
- }[pkgManager];
23
- const runBuild = {
24
- pnpm: "RUN pnpm theo build",
25
- npm: "RUN npx theo build",
26
- yarn: "RUN yarn theo build"
27
- }[pkgManager];
28
- const startCmd = {
29
- pnpm: 'CMD ["pnpm", "theo", "start"]',
30
- npm: 'CMD ["npx", "theo", "start"]',
31
- yarn: 'CMD ["yarn", "theo", "start"]'
32
- }[pkgManager];
33
- return [
34
- "# Generated by Theo",
35
- "# Multi-stage build for production",
36
- "",
37
- "# Stage 1: Build",
38
- "FROM node:22-alpine AS builder",
39
- "WORKDIR /app",
40
- `COPY package.json ${lockfile} ./`,
41
- installCmd,
42
- "COPY . .",
43
- runBuild,
44
- "",
45
- "# Stage 2: Production",
46
- "FROM node:22-alpine AS runner",
47
- "WORKDIR /app",
48
- "ENV NODE_ENV=production",
49
- "COPY --from=builder /app/.theokit ./.theokit",
50
- "COPY --from=builder /app/server ./server",
51
- "COPY --from=builder /app/theo.config.ts ./theo.config.ts",
52
- "COPY --from=builder /app/package.json ./package.json",
53
- `COPY --from=builder /app/${lockfile} ./${lockfile}`,
54
- "COPY --from=builder /app/node_modules ./node_modules",
55
- "",
56
- "EXPOSE 3000",
57
- startCmd,
58
- ""
59
- ].join("\n");
60
- }
61
- function generateDockerignore() {
62
- return [
63
- "node_modules",
64
- ".git",
65
- ".theokit",
66
- "dist",
67
- ".env",
68
- ".env.*",
69
- "!.env.example",
70
- "*.log",
71
- ".DS_Store",
72
- ".vscode",
73
- ".idea",
74
- "Dockerfile",
75
- ".dockerignore",
76
- ""
77
- ].join("\n");
78
- }
79
- async function dockerCommand(options) {
80
- const cwd = process.cwd();
81
- const dockerfilePath = resolve(cwd, "Dockerfile");
82
- const dockerignorePath = resolve(cwd, ".dockerignore");
83
- if (existsSync(dockerfilePath) && !options?.force) {
84
- console.log("\n \u26A0 Dockerfile already exists. Use --force to overwrite.\n");
85
- return;
86
- }
87
- const pkgManager = detectPkgManager(cwd);
88
- writeFileSync(dockerfilePath, generateDockerfile(pkgManager));
89
- writeFileSync(dockerignorePath, generateDockerignore());
90
- console.log(`
91
- \u2713 Generated Dockerfile (${pkgManager})`);
92
- console.log(` \u2713 Generated .dockerignore`);
93
- console.log(`
94
- Next steps:`);
95
- console.log(` docker build -t my-app .`);
96
- console.log(` docker run -p 3000:3000 my-app
97
- `);
98
- }
99
- export {
100
- dockerCommand
101
- };
102
- //# sourceMappingURL=docker-LZZB4D5E.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/commands/docker.ts"],"sourcesContent":["import { existsSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nfunction detectPkgManager(cwd: string): 'pnpm' | 'npm' | 'yarn' {\n if (existsSync(resolve(cwd, 'pnpm-lock.yaml'))) return 'pnpm'\n if (existsSync(resolve(cwd, 'yarn.lock'))) return 'yarn'\n return 'npm'\n}\n\nfunction generateDockerfile(pkgManager: 'pnpm' | 'npm' | 'yarn'): string {\n const installCmd = {\n pnpm: 'RUN corepack enable && pnpm install --frozen-lockfile',\n npm: 'RUN npm ci',\n yarn: 'RUN yarn install --frozen-lockfile',\n }[pkgManager]\n\n const lockfile = {\n pnpm: 'pnpm-lock.yaml',\n npm: 'package-lock.json',\n yarn: 'yarn.lock',\n }[pkgManager]\n\n const runBuild = {\n pnpm: 'RUN pnpm theo build',\n npm: 'RUN npx theo build',\n yarn: 'RUN yarn theo build',\n }[pkgManager]\n\n const startCmd = {\n pnpm: 'CMD [\"pnpm\", \"theo\", \"start\"]',\n npm: 'CMD [\"npx\", \"theo\", \"start\"]',\n yarn: 'CMD [\"yarn\", \"theo\", \"start\"]',\n }[pkgManager]\n\n return [\n '# Generated by Theo',\n '# Multi-stage build for production',\n '',\n '# Stage 1: Build',\n 'FROM node:22-alpine AS builder',\n 'WORKDIR /app',\n `COPY package.json ${lockfile} ./`,\n installCmd,\n 'COPY . .',\n runBuild,\n '',\n '# Stage 2: Production',\n 'FROM node:22-alpine AS runner',\n 'WORKDIR /app',\n 'ENV NODE_ENV=production',\n 'COPY --from=builder /app/.theokit ./.theokit',\n 'COPY --from=builder /app/server ./server',\n 'COPY --from=builder /app/theo.config.ts ./theo.config.ts',\n 'COPY --from=builder /app/package.json ./package.json',\n `COPY --from=builder /app/${lockfile} ./${lockfile}`,\n 'COPY --from=builder /app/node_modules ./node_modules',\n '',\n 'EXPOSE 3000',\n startCmd,\n '',\n ].join('\\n')\n}\n\nfunction generateDockerignore(): string {\n return [\n 'node_modules',\n '.git',\n '.theokit',\n 'dist',\n '.env',\n '.env.*',\n '!.env.example',\n '*.log',\n '.DS_Store',\n '.vscode',\n '.idea',\n 'Dockerfile',\n '.dockerignore',\n '',\n ].join('\\n')\n}\n\n// eslint-disable-next-line @typescript-eslint/require-await -- CLI surface contract is async; sync today is implementation detail\nexport async function dockerCommand(options?: { force?: boolean }): Promise<void> {\n const cwd = process.cwd()\n const dockerfilePath = resolve(cwd, 'Dockerfile')\n const dockerignorePath = resolve(cwd, '.dockerignore')\n\n if (existsSync(dockerfilePath) && !options?.force) {\n console.log('\\n ⚠ Dockerfile already exists. Use --force to overwrite.\\n')\n return\n }\n\n const pkgManager = detectPkgManager(cwd)\n writeFileSync(dockerfilePath, generateDockerfile(pkgManager))\n writeFileSync(dockerignorePath, generateDockerignore())\n\n console.log(`\\n ✓ Generated Dockerfile (${pkgManager})`)\n console.log(` ✓ Generated .dockerignore`)\n console.log(`\\n Next steps:`)\n console.log(` docker build -t my-app .`)\n console.log(` docker run -p 3000:3000 my-app\\n`)\n}\n"],"mappings":";;;;AAA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