@lunora/cli 1.0.0-alpha.476 → 1.0.0-alpha.478

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -702,9 +702,10 @@ interface DeployCommandOptions {
702
702
  */
703
703
  smokeLauncher?: DevProcessSpawner;
704
704
  /**
705
- * Evaluate every lazy function module in workerd before shipping, so a module that throws on
706
- * load fails the deploy instead of its first caller. Nothing to check for an eager
707
- * registry; `false` (`--no-smoke-load`) skips it. Default on.
705
+ * Evaluate every module the Worker loads on demand in workerd before shipping (lazy function
706
+ * modules, and in any build the auth module and spec documents the generated app loads with
707
+ * `import()`), so a module that throws on load fails the deploy instead of its first request.
708
+ * Nothing to check when there is none; `false` (`--no-smoke-load`) skips it. Default on.
708
709
  */
709
710
  smokeLoad?: boolean;
710
711
  spawner?: Spawner;
package/dist/index.d.ts CHANGED
@@ -702,9 +702,10 @@ interface DeployCommandOptions {
702
702
  */
703
703
  smokeLauncher?: DevProcessSpawner;
704
704
  /**
705
- * Evaluate every lazy function module in workerd before shipping, so a module that throws on
706
- * load fails the deploy instead of its first caller. Nothing to check for an eager
707
- * registry; `false` (`--no-smoke-load`) skips it. Default on.
705
+ * Evaluate every module the Worker loads on demand in workerd before shipping (lazy function
706
+ * modules, and in any build the auth module and spec documents the generated app loads with
707
+ * `import()`), so a module that throws on load fails the deploy instead of its first request.
708
+ * Nothing to check when there is none; `false` (`--no-smoke-load`) skips it. Default on.
708
709
  */
709
710
  smokeLoad?: boolean;
710
711
  spawner?: Spawner;
@@ -1,2 +1,2 @@
1
- import{isLunoraError as _,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import P from"@visulima/cerebro/command/version";import{O as s}from"../packem_shared/output-format-DWe_tkTR.mjs";import{A as m}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{deployTargetIds as U,DEFAULT_DEPLOY_TARGET as M,addArgsFor as W,detectPackageManager as z}from"@lunora/config/cli";import{SDK_LANGUAGES as K}from"@lunora/codegen/sdk";import{r as $}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";import{EXIT_CODE as y,exitCodeForError as F}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{setCommandLogger as k,createLogger as v}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as J}from"../packem_shared/render-lunora-error-JsLelWwR.mjs";import{mkdirSync as q,readFileSync as G,lstatSync as V,writeFileSync as H}from"node:fs";import{homedir as Y}from"node:os";import{join as w}from"node:path";const Q={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("./handler2.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},s]},X={argument:{description:"create <name> | list | revoke <name>",name:"subcommand",type:String},description:"Manage named admin tokens: create one per CI job or teammate, list them, revoke a leaked one",examples:[["lunora admin-token create ci-deploy --prod --url https://app.example.com","Create a token; the secret is printed once"],["lunora admin-token create nightly --expires-days 30","Create a token that stops working after 30 days"],["lunora admin-token list","List tokens with created / last-used / expiry"],["lunora admin-token revoke ci-deploy","Revoke a token (refused everywhere within 30 seconds)"]],group:"Deploy",loader:()=>import("./handler3.mjs").then(e=>({default:e.execute})),name:"admin-token",options:[{description:"For `create` — days until the token expires (default: never)",name:"expires-days",type:Number},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Root admin bearer token (or LUNORA_ADMIN_TOKEN); a named token cannot manage tokens",name:"token",type:String}]},S="lunora.advisor.map.json",Z={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("./handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${S})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},s,{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${S})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},ee={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("./handler4.mjs").then(e=>({default:e.execute})),name:"analyze",options:[s]},te={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup list --format json","Same, as a single JSON document on stdout"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup restore <id> --mode replace --dry-run","Show what restoring over existing rows would add, overwrite and delete"],["lunora backup restore <id> --mode replace","Restore over existing rows: each snapshot table ends up holding exactly its rows"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("./handler24.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"restore: how rows the target already holds are treated — require-empty (default: refuse unless the snapshot's tables are empty) | append | upsert | replace (make each table match the snapshot; STOP all writes to the target first, or a row updated meanwhile is deleted)",name:"mode",type:String},{description:"restore: print what the restore would add, overwrite and delete; write nothing",name:"dry-run",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},s,{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a destructive step without prompting: a production pitr --restore, or backup prune",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},re=(()=>{const e=U();return e.length>1?`${e.join(" | ")} (default ${M})`:e.join(" | ")})(),p={description:`Deploy target: ${re}. Also settable as "target" in lunora.config.*`,name:"target",type:String},oe={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("./handler25.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},s,{description:"Evaluate every lazy function module and import()ed integration SDK in workerd before shipping (default; nothing to check when there are none)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules and import()ed integration SDKs before shipping",name:"no-smoke-load",type:Boolean},{description:"Profile the built Worker's startup CPU and warn when it nears Cloudflare's 1 s limit (default)",name:"startup-check",type:Boolean},{description:"Skip profiling the built Worker's startup CPU",name:"no-startup-check",type:Boolean},{description:"Run the project's vite/rsbuild client build before bundling the Worker (default when wrangler reads its output)",name:"framework-build",type:Boolean},{description:"Skip the vite/rsbuild client build; bundle whatever is already on disk",name:"no-framework-build",type:Boolean},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Project directory to build (default the working directory). A Vite or Rspack plugin with an explicit root must name the same directory.",name:"root",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},p]},ne=[{name:"alerts",summary:"usage alerts that catch a runaway bill",usage:"[status | setup | test]"},{name:"ai-gateway",summary:"create or reuse an AI Gateway for ctx.ai and write its id into wrangler vars",usage:""},{name:"containers",summary:"build and push container images, manage instances (wraps wrangler containers)",usage:"<build|push|images|list|info|delete> [args…]"},{name:"deployments",summary:"deployment history; roll back or promote Worker versions",usage:"list | status | inspect <version-id> | rollback [version-id] | promote <version-id>"},{name:"profile",summary:"capture an on-demand CPU or heap profile (pprof) from the live Worker or one of its Durable Objects",usage:"[worker]"}],C={argument:{description:`${ne.map(e=>e.name).join(" | ")}, then the tool's own arguments`,name:"tool",type:String},description:"Cloudflare-only tools: usage alerts, AI Gateway, containers, deployments, profiling",examples:[["lunora cloudflare","List the tools"],["lunora cloudflare alerts","Show last month's usage and which products have an alert"],["lunora cloudflare alerts setup --email ops@example.com --dry-run","Show the alerts setup would create, without creating them"],["lunora cloudflare alerts setup --email ops@example.com --multiplier 5 --yes","Create or update the alerts at 5x last month"],["lunora cloudflare alerts setup --email ops@example.com --threshold do-duration=500000 --yes","Also alert on Durable Objects duration at a limit you choose"],["lunora cloudflare alerts test","Show what Cloudflare has delivered to your alert destinations"],["lunora cloudflare ai-gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora cloudflare ai-gateway --id my-gateway --no-logs","Use an explicit gateway id, with prompt/response log collection off"],["lunora cloudflare ai-gateway --dry-run","Print what would be created and written, without calling Cloudflare"],["lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push","Build an image and push it to the Cloudflare Registry"],["lunora cloudflare containers images list","List images in your Cloudflare Registry"],["lunora cloudflare containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora cloudflare containers images delete transcoder:v1","Delete an image to free registry storage"],["lunora cloudflare deployments list","Show the 10 most recent deployments"],["lunora cloudflare deployments status","Show the live version and how traffic is split across versions"],["lunora cloudflare deployments inspect <version-id>","View a specific Worker version"],["lunora cloudflare deployments rollback --yes","Roll back to the previous version"],["lunora cloudflare deployments promote <version-id> --yes","Send 100% of traffic to a version"],["lunora cloudflare deployments promote <version-id> --percent 10 --from <live-version-id> --confirm-shared-state --yes","Send 10% of traffic to a version and keep 90% on the live one"],["lunora cloudflare profile","Capture a 10s CPU profile of the latest version into ./<worker>-cpu-<time>.pprof.gz"],["lunora cloudflare profile --type heap --duration-ms 30000 --out heap.pprof.gz","Capture a 30s heap (allocation) profile"],["lunora cloudflare profile --namespace-id <id> --actor-id <64-hex>","Profile one Durable Object instance"]],group:"Deploy",loader:()=>import("./handler32.mjs").then(e=>({default:e.execute})),name:"cloudflare",options:[{description:"alerts setup: email address to notify. Repeatable",lazyMultiple:!0,name:"email",type:String},{description:"alerts setup / test: Cloudflare webhook destination id. Repeatable",lazyMultiple:!0,name:"webhook",type:String},{description:"alerts setup: alert at this many times last month's usage (default 3)",name:"multiplier",type:String},{description:"alerts setup: set one metric's limit yourself, in the product's unit: <metric>=<n>. Repeatable",lazyMultiple:!0,name:"threshold",type:String},{description:"alerts setup: accept the floor for a metric whose usage could not be read",name:"allow-floor",type:Boolean},{description:"alerts setup: replace an updated alert's recipients instead of adding to them",name:"replace-recipients",type:Boolean},{description:"alerts setup / ai-gateway: show the plan without creating, updating or writing anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY). deployments rollback / promote: confirm the traffic change (required)",name:"yes",type:Boolean},{description:"ai-gateway: gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"ai-gateway: collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"ai-gateway: create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"containers build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"containers build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"containers / deployments / profile: Cloudflare environment name",name:"env",type:String},{description:"profile: capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"profile: cpu (default) or heap",name:"type",type:String},{description:"profile: Worker version id to profile (default latest)",name:"version-id",type:String},{description:"profile: file to write the gzip pprof to (default <worker>-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"profile: Durable Object namespace id (with --actor-id)",name:"namespace-id",type:String},{description:"profile: Durable Object instance id, 64 hex characters (with --namespace-id)",name:"actor-id",type:String},{description:"deployments rollback / promote: reason recorded with the change",name:"message",type:String},{description:"deployments promote: share of traffic for the version, a whole number from 1 to 100 (default 100)",name:"percent",type:String},{description:"deployments promote --percent below 100: the live version that keeps the remaining traffic (checked against `deployments status`)",name:"from",type:String},{description:"deployments promote --percent below 100: confirm the two versions can share one Durable Object schema and migrations (required)",name:"confirm-shared-state",type:Boolean},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list and status)"},p]},ae={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("./runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for registered functions (opt-in; default eager)",name:"lazy-functions",type:Boolean},s,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},p]},ie={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_shared/runDeployCommand-CNgOUx91.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Deploy even though the app enables the open-shard option (any value but a literal false; any caller may target any shard). Without it, deploy refuses until shards are gated with `authorizeShard`",name:"allow-open-shards",type:Boolean},{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; nothing is checked and the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Run the project's vite/rsbuild client build before bundling the Worker (default when wrangler reads its output)",name:"framework-build",type:Boolean},{description:"Skip the vite/rsbuild client build; bundle whatever is already on disk",name:"no-framework-build",type:Boolean},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},s,{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Project directory to deploy (default the working directory). A Vite or Rspack plugin with an explicit root must name the same directory.",name:"root",type:String},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Refused: a Worker version shares production state and gets no preview URL — deploy an isolated copy with `lunora preview deploy <name>`",name:"preview",type:Boolean},{description:"Deploy only the app, not the lunora.config services it binds (they deploy first by default)",name:"skip-services",type:Boolean},{description:"Evaluate every lazy function module and import()ed integration SDK in workerd before shipping (default; nothing to check when there are none)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules and import()ed integration SDKs before shipping",name:"no-smoke-load",type:Boolean},p,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean}]},se={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"],["lunora dev --local","Start no remote proxy session, e.g. in CI where a service's `ai` binding has no credentials"],["lunora dev --tunnel","Share the worker on a public *.trycloudflare.com URL (needs cloudflared ≥ 2026.9.3)"],["lunora dev --tunnel --allow-mail you@example.com","Same, but visitors must confirm an allowed email with a one-time PIN"]],group:"Develop",loader:()=>import("./runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for codegen (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},p,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean},{description:"Pass --local to wrangler dev: no remote proxy session, so an `ai` binding (in the app or a service) cannot stop dev from starting without Cloudflare credentials — it fails when called instead",name:"local",type:Boolean},{description:"Share the worker through a Cloudflare quick tunnel (*.trycloudflare.com, needs cloudflared ≥ 2026.9.3). PUBLIC unless --allow-mail is given",name:"tunnel",type:Boolean},{description:"With --tunnel: only these emails get in, after a one-time PIN (passed to cloudflared as --allowed-mail). Repeatable; accepts a comma list and '*@domain'",lazyMultiple:!0,name:"allow-mail",type:String}]},le={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("./handler5.mjs").then(e=>({default:e.execute})),name:"docs"},de={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"],["lunora doctor --fix","Create the D1 databases the config names and mint the local dev secrets"],["lunora doctor --fix --dry-run","Show what --fix would create or write, without doing it"]],group:"Project",loader:()=>import("./handler31.mjs").then(e=>({default:e.execute})),name:"doctor",options:[s,{description:"Resolve what can be resolved: create placeholder D1 databases, mint missing .dev.vars secrets",name:"fix",type:Boolean},{description:"With --fix: print the changes without making them",name:"dry-run",type:Boolean}]},pe={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("./handler6.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},s,{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},ce={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("./handler26.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},s,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ue={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("./handler7.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{...s,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},me={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import backup.ndjson --mode replace --dry-run","Show what restoring a snapshot would add, overwrite and delete, writing nothing"],["lunora import backup.ndjson --mode replace","Make each of the snapshot's tables hold exactly its rows"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("./handler8.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},s,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"How rows the target already holds are treated: append (insert, skip existing _ids) | upsert (overwrite existing _ids) | replace (upsert, then delete the rows of the file's tables the file lacks; STOP all writes to the target first, or a row updated meanwhile is deleted) | require-empty (refuse unless those tables are empty) (default append)",name:"mode",type:String},{description:"Check the file and print what it would add, overwrite and delete; write nothing",name:"dry-run",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},he={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("./handler9.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},s,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},ge={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("./runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | rspack-react | saas | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | auth-ui | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Choose the auth: lunora (better-auth, users in your D1) | clerk | workos | auth0 (the provider owns the session; the Worker verifies its JWT) | none",name:"auth",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},fe={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --format json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("./handler10.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},ye={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("./handler28.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean},s]},ve={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("./handler11.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},we={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("./handler27.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},s,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},p,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},be={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --functions --token $MY_USER_TOKEN","Expose one tool per app function, running as that user (needs apiSpec openrpc)"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("./handler30.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: one tool per app function, from lunora/_generated/openrpc.json, run as the bearer given by --token. Never uses the admin token. Needs apiSpec openrpc",name:"functions",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},ke={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive | hyperdrive-to-d1 [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive | hyperdrive-to-d1) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate status backfill-names --format json","Same, as a single JSON document on stdout"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"],["lunora migrate hyperdrive-to-d1 --from-url https://new --to-url https://old","Roll .global() data back from Hyperdrive to D1"],["lunora migrate hyperdrive-to-d1 --from-url https://new --to-url https://old --tables settings --replace --yes","Roll back, overwriting rows D1 already holds"]],group:"Data",loader:()=>import("./dispatch.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},s,{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"backend migration: source worker URL (defaults to --url)",name:"from-url",type:String},{description:"backend migration: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"backend migration: target worker URL (defaults to --url)",name:"to-url",type:String},{description:"backend migration: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"backend migration: comma-separated .global() tables to move (default: every table, shard-local ones included; required with --replace)",name:"tables",type:String},{description:"backend migration: keep the intermediate NDJSON dump at this path",name:"out",type:String},{description:"backend migration: overwrite rows that already exist in the target with the source's values (needs --tables; default: leave them, report conflicts)",name:"replace",type:Boolean}]},O=[s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}],Se={argument:{description:"status (print the current state instead of pausing)",name:"subcommand",type:String},description:"Pause the deployment: refuse function calls, hold scheduled jobs, skip crons and queue batches",examples:[['lunora pause --reason "incident 42"',"Pause the local dev server"],["lunora pause status","Show whether the deployment is paused"],["lunora pause --prod --url https://app.example.com","Pause production"]],group:"Deploy",loader:()=>import("./handler12.mjs").then(e=>({default:e.executePause})),name:"pause",options:[{description:"A note shown wherever the pause is (Studio, the 503 body)",name:"reason",type:String},...O]},xe={description:"Resume a paused deployment; jobs held while paused run right away",examples:[["lunora resume","Resume the local dev server"],["lunora resume --prod --url https://app.example.com","Resume production"]],group:"Deploy",loader:()=>import("./handler12.mjs").then(e=>({default:e.executeResume})),name:"resume",options:O},Re={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("./handler13.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Evaluate every lazy function module and import()ed integration SDK in workerd before passing (default; nothing to check when there are none)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules and import()ed integration SDKs before passing",name:"no-smoke-load",type:Boolean},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},p]},Ce={argument:{description:"deploy <name> | list | delete <name>",name:"subcommand",type:String},description:"Deploy, list and delete isolated preview copies of the app (own Worker, Durable Objects, D1, KV, R2)",examples:[["lunora preview deploy 123","Deploy preview 123 as its own Worker with its own data, then print its URL"],["lunora preview deploy 123 --seed","Deploy, then fill the preview with `lunora seed` data"],["lunora preview deploy 123 --secret RESEND_API_KEY","Give the preview a secret, read from the environment"],["lunora preview deploy 123 --var AUTH_URL=https://app-preview-123.acme.workers.dev","Override a production var in the preview"],["lunora preview deploy 123 --env production","Plan the preview from env.production's bindings, for an app that declares them only there"],["lunora preview deploy 123 --dry-run","Show the Worker, resources and env block a deploy would use"],["lunora preview list","List the previews on record"],["lunora preview delete 123 --env production","Delete a preview made with --env production, in that environment's account"],["lunora preview delete 123","Delete the preview Worker and every resource recorded for it"]],group:"Deploy",loader:()=>import("./handler29.mjs").then(e=>({default:e.execute})),name:"preview",options:[{description:"deploy: show the plan without calling Cloudflare; delete: read the record and show what would be deleted, changing nothing",name:"dry-run",type:Boolean},{description:"deploy: plan the preview from this Wrangler environment (the top level with env.<name> laid over it), for an app whose bindings live in env.<name>. delete, list: look in that environment's account_id; required (or CLOUDFLARE_ACCOUNT_ID) when an environment names an account other than the top level's",name:"env",type:String},{description:"delete: also look for the preview under the lunora.appId and Worker name of the package.json and wrangler config in this directory, read as data (CI passes a pull request's head files, whose identity the checkout may not share)",name:"head-dir",type:String},s,{description:"deploy: give the preview this secret, with the value of the same-named environment variable. Repeatable; nothing else is copied",lazyMultiple:!0,name:"secret",type:String},{description:"deploy: run `lunora seed` against the preview once it is live",name:"seed",type:Boolean},p,{description:"deploy: set a var in the preview, over production's value (e.g. an auth base URL). KEY=VALUE, repeatable",lazyMultiple:!0,name:"var",type:String}]},Oe={description:"Capture an on-demand CPU or heap profile (pprof) from a running Node-target app",examples:[["lunora profile --target node --url https://app.example.com/__profile","Capture a 10 s CPU profile of the app"],["lunora profile --target node --url http://localhost:3000/__profile --type heap --duration-ms 30000","Capture a 30 s heap profile of a local app"],["lunora profile --target node --url https://app.example.com/__profile --out cpu.pprof.gz","Write the profile to a named file"]],group:"Develop",loader:()=>import("./handler22.mjs").then(e=>({default:e.execute})),name:"profile",options:[{description:"Capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"cpu (default) or heap",name:"type",type:String},{description:"File to write the gzip pprof to (default profile-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"Full URL of the profile route the app mounts createNodeProfileHandler on",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String},p]},Ne={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("./handler15.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{...s,description:"Output format: pretty (default) or json (add plan / list)"},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},Ae={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("./runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},De={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("./handler16.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},Be={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],group:"Develop",loader:()=>import("./runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},s,{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},Ee={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("./handler23.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${K.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},Le={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("./handler14.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Let a required foreign key with no row to point at take a dangling id instead of failing",name:"allow-orphans",type:Boolean},s,{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},_e={argument:{description:"prune",name:"subcommand",type:String},description:"Maintain the shard registry: prune shards that no longer hold any rows of their .shardBy() table",examples:[["lunora shards prune --dry-run","Show which registered shards are empty, without removing anything"],["lunora shards prune","Remove the empty shards from the registry"],["lunora shards prune --tables messages","Only prune the shards listed for `messages`"],["lunora shards prune --prod --url https://app.example.com","Prune production"]],group:"Data",loader:()=>import("./handler17.mjs").then(e=>({default:e.execute})),name:"shards",options:[{description:"Comma-separated .shardBy() tables (default: all of them)",name:"tables",type:String},{description:"Report what would be pruned without changing the registry",name:"dry-run",type:Boolean},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},Ie={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("./handler18.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},s,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},p]},je={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("./handler19.mjs").then(e=>({default:e.execute})),name:"view"},Te={argument:{description:"create <exportName> | send-event <exportName> <instanceId> <eventType>",name:"args",type:String},description:"Start a workflow instance, or send an event to a waiting one",examples:[[`lunora workflow create onboarding --params '{"userId":"u1"}'`,"Start an instance of the `onboarding` workflow"],["lunora workflow create onboarding --id user-u1","Start it under an explicit instance id"],[`lunora workflow send-event onboarding user-u1 approved --payload '{"by":"ada"}'`,"Deliver an `approved` event to a waiting instance"]],group:"Develop",loader:()=>import("./handler20.mjs").then(e=>({default:e.execute})),name:"workflow",options:[{description:"Instance id for `create` (defaults to a generated one)",name:"id",type:String},{description:"JSON-encoded params for `create`",name:"params",type:String},{description:"JSON-encoded event payload for `send-event`",name:"payload",type:String},s,{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN or .dev.vars)",name:"token",type:String}]},Pe=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},N=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Pe(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ue=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Me=1440*60*1e3,We=1500,ze="0.0.0",Ke=/^v/u,$e=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Ke,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},x=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Fe=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},Je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Fe(a,i)}return 0},qe=(e,t)=>{const r=x(e),o=x(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return Je(g(e).prerelease,g(t).prerelease)},Ge=e=>{const t=g(e).prerelease.split(".")[0]??"";return $e.has(t)?t:"latest"},Ve=(e,t)=>qe(t,e)>0,He=(e,t,r)=>t-e<r,Ye=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=W(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},A=e=>w(e,"lunora-cli-update.json"),Qe=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:w(Y(),".cache"),r=w(t,"lunora");try{q(r,{mode:448,recursive:!0})}catch{}return r},Xe=e=>{try{const t=JSON.parse(G(A(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},R=(e,t)=>{try{const r=A(e);try{if(V(r).isSymbolicLink())return}catch{}H(r,`${JSON.stringify(t)}
2
- `,"utf8")}catch{}},Ze=async(e,t)=>{try{const r=await e(Ue(t),{signal:AbortSignal.timeout(We)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},et=(e,t,r)=>e===ze||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,tt=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(et(e.current,t,r))return;const o=e.cacheDir??Qe(t),n=(e.now??Date.now)(),a=e.ttlMs??Me,i=Ge(e.current),l=Xe(o),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let h=d?.latest;if(d===void 0||!He(d.checkedAt,n,a)){const f=await Ze(e.fetchImpl??globalThis.fetch,i);f===void 0?R(o,{checkedAt:n,latest:e.current,tag:i}):(h=f,R(o,{checkedAt:n,latest:f,tag:i}))}h!==void 0&&Ve(e.current,h)&&e.logger.warn(Ye(e.current,h,i,e.manager))},D=["init","add","dev","codegen","build","deploy","prepare","preview","link","cloudflare","logs","run","insights","profile","reset","migrate","export","import","seed","shards","pause","resume","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp","workflow"],B=$(),rt=[ge,Q,se,ae,Z,oe,ie,Re,Ce,ve,C,we,Be,fe,Oe,Ae,ke,ue,me,Le,_e,Se,xe,X,ye,te,ce,Ie,he,de,pe,ee,je,le,Ne,De,be,Ee,Te],E=[...rt,P,T],Bt=E.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),ot=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(r=>u(r))),nt=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:u(e.argument.description??"")}},...e.description===void 0?{}:{description:u(e.description)},...e.examples===void 0?{}:{examples:ot(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(t.description??"")}))}}),at=e=>{const t={value:0},r=j("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:B});for(const o of E)r.addCommand(nt(o));return{cli:r,exitCode:t}},it=/Command "(?<name>[^"]+)" not found/u,b={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},st=new Set((C.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),lt=/^[\w@%+=:,./-]+$/u,dt=e=>lt.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,pt=(e,t)=>{const r=e.indexOf(t);return r===-1?[...e]:[...e.slice(0,r),...e.slice(r+1)]},ct=(e,t)=>e.findIndex((r,o)=>r===t&&(o===0||!st.has(e[o-1]??""))),ut=e=>{const t=N(e,[...D,...Object.keys(b)]);return t!==void 0&&Object.hasOwn(b,t)?t:void 0},L=(e,t,r)=>{const o=ut(e),n=o===void 0?void 0:b[o];if(o===void 0||n===void 0)return;const a=e===o?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=ct(i,n.absorbs);if(d===-1&&r===void 0)return`${a}\`lunora ${o}\` had one subcommand, \`${n.absorbs}\`; it moved to \`lunora ${n.to}\`.`;i=d===-1?i:[...i.slice(0,d),...i.slice(d+1)]}const l=n.absorbs===void 0?o:`${o} ${n.absorbs}`,c=r??["lunora",n.to,...i.map(d=>dt(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},mt=(e,t)=>{const r=v(),o=e instanceof Error?e.message:String(e),n=it.exec(o);if(!n?.groups)return _(e)||I(o)!==void 0?r.error(J(e)):r.error(o),F(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=L(i,pt(t,i));if(l!==void 0)return r.error(l),y.USAGE;const c=N(a,D);return r.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),r.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},ht=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),Et=async(e={})=>{const{cli:t,exitCode:r}=at(e);e.logger!==void 0&&k(ht(e.logger));const o=e.argv??process.argv.slice(2);try{const a=o[0]==="help"&&o[1]!==void 0?L(o[1],o.slice(2),"lunora help cloudflare"):void 0;if(a!==void 0)return v().error(a),y.USAGE;await t.run({shouldExitProcess:!1})}catch(a){return mt(a,o)}finally{k(void 0)}let n;try{n=z(process.cwd())}catch{}return await tt({current:B,logger:v(),manager:n}),r.value};export{D as C,S as D,Bt as R,B as V,ne as a,Et as r};
1
+ import{isLunoraError as I,findSolutionByMessage as _}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import P from"@visulima/cerebro/command/version";import{O as s}from"../packem_shared/output-format-DWe_tkTR.mjs";import{A as m}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{deployTargetIds as U,DEFAULT_DEPLOY_TARGET as M,addArgsFor as W,detectPackageManager as z}from"@lunora/config/cli";import{SDK_LANGUAGES as $}from"@lunora/codegen/sdk";import{r as F}from"../packem_shared/cli-manifest-DoQ_3bzs.mjs";import{EXIT_CODE as y,exitCodeForError as K}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{setCommandLogger as k,createLogger as v}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as J}from"../packem_shared/render-lunora-error-JsLelWwR.mjs";import{mkdirSync as q,readFileSync as G,lstatSync as V,writeFileSync as H}from"node:fs";import{homedir as Y}from"node:os";import{join as w}from"node:path";const Q={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("./handler2.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},s]},X={argument:{description:"create <name> | list | revoke <name>",name:"subcommand",type:String},description:"Manage named admin tokens: create one per CI job or teammate, list them, revoke a leaked one",examples:[["lunora admin-token create ci-deploy --prod --url https://app.example.com","Create a token; the secret is printed once"],["lunora admin-token create nightly --expires-days 30","Create a token that stops working after 30 days"],["lunora admin-token list","List tokens with created / last-used / expiry"],["lunora admin-token revoke ci-deploy","Revoke a token (refused everywhere within 30 seconds)"]],group:"Deploy",loader:()=>import("./handler3.mjs").then(e=>({default:e.execute})),name:"admin-token",options:[{description:"For `create` — days until the token expires (default: never)",name:"expires-days",type:Number},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Root admin bearer token (or LUNORA_ADMIN_TOKEN); a named token cannot manage tokens",name:"token",type:String}]},S="lunora.advisor.map.json",Z={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("./handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${S})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},s,{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${S})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},ee={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("./handler4.mjs").then(e=>({default:e.execute})),name:"analyze",options:[s]},te={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup list --format json","Same, as a single JSON document on stdout"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup restore <id> --mode replace --dry-run","Show what restoring over existing rows would add, overwrite and delete"],["lunora backup restore <id> --mode replace","Restore over existing rows: each snapshot table ends up holding exactly its rows"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("./handler24.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"restore: how rows the target already holds are treated — require-empty (default: refuse unless the snapshot's tables are empty) | append | upsert | replace (make each table match the snapshot; STOP all writes to the target first, or a row updated meanwhile is deleted)",name:"mode",type:String},{description:"restore: print what the restore would add, overwrite and delete; write nothing",name:"dry-run",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},s,{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a destructive step without prompting: a production pitr --restore, or backup prune",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},re=(()=>{const e=U();return e.length>1?`${e.join(" | ")} (default ${M})`:e.join(" | ")})(),p={description:`Deploy target: ${re}. Also settable as "target" in lunora.config.*`,name:"target",type:String},oe={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("./handler25.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},s,{description:"Evaluate the modules the Worker loads on demand (lazy functions, auth, API specs) in workerd before shipping (default)",name:"smoke-load",type:Boolean},{description:"Skip evaluating on-demand modules before shipping",name:"no-smoke-load",type:Boolean},{description:"Profile the built Worker's startup CPU and warn when it nears Cloudflare's 1 s limit (default)",name:"startup-check",type:Boolean},{description:"Skip profiling the built Worker's startup CPU",name:"no-startup-check",type:Boolean},{description:"Run the project's vite/rsbuild client build before bundling the Worker (default when wrangler reads its output)",name:"framework-build",type:Boolean},{description:"Skip the vite/rsbuild client build; bundle whatever is already on disk",name:"no-framework-build",type:Boolean},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Project directory to build (default the working directory). A Vite or Rspack plugin with an explicit root must name the same directory.",name:"root",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},p]},ne=[{name:"alerts",summary:"usage alerts that catch a runaway bill",usage:"[status | setup | test]"},{name:"ai-gateway",summary:"create or reuse an AI Gateway for ctx.ai and write its id into wrangler vars",usage:""},{name:"containers",summary:"build and push container images, manage instances (wraps wrangler containers)",usage:"<build|push|images|list|info|delete> [args…]"},{name:"deployments",summary:"deployment history; roll back or promote Worker versions",usage:"list | status | inspect <version-id> | rollback [version-id] | promote <version-id>"},{name:"profile",summary:"capture an on-demand CPU or heap profile (pprof) from the live Worker or one of its Durable Objects",usage:"[worker]"}],C={argument:{description:`${ne.map(e=>e.name).join(" | ")}, then the tool's own arguments`,name:"tool",type:String},description:"Cloudflare-only tools: usage alerts, AI Gateway, containers, deployments, profiling",examples:[["lunora cloudflare","List the tools"],["lunora cloudflare alerts","Show last month's usage and which products have an alert"],["lunora cloudflare alerts setup --email ops@example.com --dry-run","Show the alerts setup would create, without creating them"],["lunora cloudflare alerts setup --email ops@example.com --multiplier 5 --yes","Create or update the alerts at 5x last month"],["lunora cloudflare alerts setup --email ops@example.com --threshold do-duration=500000 --yes","Also alert on Durable Objects duration at a limit you choose"],["lunora cloudflare alerts test","Show what Cloudflare has delivered to your alert destinations"],["lunora cloudflare ai-gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora cloudflare ai-gateway --id my-gateway --no-logs","Use an explicit gateway id, with prompt/response log collection off"],["lunora cloudflare ai-gateway --dry-run","Print what would be created and written, without calling Cloudflare"],["lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push","Build an image and push it to the Cloudflare Registry"],["lunora cloudflare containers images list","List images in your Cloudflare Registry"],["lunora cloudflare containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora cloudflare containers images delete transcoder:v1","Delete an image to free registry storage"],["lunora cloudflare deployments list","Show the 10 most recent deployments"],["lunora cloudflare deployments status","Show the live version and how traffic is split across versions"],["lunora cloudflare deployments inspect <version-id>","View a specific Worker version"],["lunora cloudflare deployments rollback --yes","Roll back to the previous version"],["lunora cloudflare deployments promote <version-id> --yes","Send 100% of traffic to a version"],["lunora cloudflare deployments promote <version-id> --percent 10 --from <live-version-id> --confirm-shared-state --yes","Send 10% of traffic to a version and keep 90% on the live one"],["lunora cloudflare profile","Capture a 10s CPU profile of the latest version into ./<worker>-cpu-<time>.pprof.gz"],["lunora cloudflare profile --type heap --duration-ms 30000 --out heap.pprof.gz","Capture a 30s heap (allocation) profile"],["lunora cloudflare profile --namespace-id <id> --actor-id <64-hex>","Profile one Durable Object instance"]],group:"Deploy",loader:()=>import("./handler32.mjs").then(e=>({default:e.execute})),name:"cloudflare",options:[{description:"alerts setup: email address to notify. Repeatable",lazyMultiple:!0,name:"email",type:String},{description:"alerts setup / test: Cloudflare webhook destination id. Repeatable",lazyMultiple:!0,name:"webhook",type:String},{description:"alerts setup: alert at this many times last month's usage (default 3)",name:"multiplier",type:String},{description:"alerts setup: set one metric's limit yourself, in the product's unit: <metric>=<n>. Repeatable",lazyMultiple:!0,name:"threshold",type:String},{description:"alerts setup: accept the floor for a metric whose usage could not be read",name:"allow-floor",type:Boolean},{description:"alerts setup: replace an updated alert's recipients instead of adding to them",name:"replace-recipients",type:Boolean},{description:"alerts setup / ai-gateway: show the plan without creating, updating or writing anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY). deployments rollback / promote: confirm the traffic change (required)",name:"yes",type:Boolean},{description:"ai-gateway: gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"ai-gateway: collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"ai-gateway: create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"containers build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"containers build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"containers / deployments / profile: Cloudflare environment name",name:"env",type:String},{description:"profile: capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"profile: cpu (default) or heap",name:"type",type:String},{description:"profile: Worker version id to profile (default latest)",name:"version-id",type:String},{description:"profile: file to write the gzip pprof to (default <worker>-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"profile: Durable Object namespace id (with --actor-id)",name:"namespace-id",type:String},{description:"profile: Durable Object instance id, 64 hex characters (with --namespace-id)",name:"actor-id",type:String},{description:"deployments rollback / promote: reason recorded with the change",name:"message",type:String},{description:"deployments promote: share of traffic for the version, a whole number from 1 to 100 (default 100)",name:"percent",type:String},{description:"deployments promote --percent below 100: the live version that keeps the remaining traffic (checked against `deployments status`)",name:"from",type:String},{description:"deployments promote --percent below 100: confirm the two versions can share one Durable Object schema and migrations (required)",name:"confirm-shared-state",type:Boolean},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list and status)"},p]},ae={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("./runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for registered functions (opt-in; default eager)",name:"lazy-functions",type:Boolean},s,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},p]},ie={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_shared/runDeployCommand-ByBuze9W.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Deploy even though the app enables the open-shard option (any value but a literal false; any caller may target any shard). Without it, deploy refuses until shards are gated with `authorizeShard`",name:"allow-open-shards",type:Boolean},{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; nothing is checked and the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Run the project's vite/rsbuild client build before bundling the Worker (default when wrangler reads its output)",name:"framework-build",type:Boolean},{description:"Skip the vite/rsbuild client build; bundle whatever is already on disk",name:"no-framework-build",type:Boolean},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},s,{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Project directory to deploy (default the working directory). A Vite or Rspack plugin with an explicit root must name the same directory.",name:"root",type:String},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Refused: a Worker version shares production state and gets no preview URL — deploy an isolated copy with `lunora preview deploy <name>`",name:"preview",type:Boolean},{description:"Deploy only the app, not the lunora.config services it binds (they deploy first by default)",name:"skip-services",type:Boolean},{description:"Evaluate the modules the Worker loads on demand (lazy functions, auth, API specs) in workerd before shipping (default)",name:"smoke-load",type:Boolean},{description:"Skip evaluating on-demand modules before shipping",name:"no-smoke-load",type:Boolean},p,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean}]},se={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"],["lunora dev --local","Start no remote proxy session, e.g. in CI where a service's `ai` binding has no credentials"],["lunora dev --tunnel","Share the worker on a public *.trycloudflare.com URL (needs cloudflared ≥ 2026.9.3)"],["lunora dev --tunnel --allow-mail you@example.com","Same, but visitors must confirm an allowed email with a one-time PIN"]],group:"Develop",loader:()=>import("./runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy imports for codegen (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},p,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean},{description:"Pass --local to wrangler dev: no remote proxy session, so an `ai` binding (in the app or a service) cannot stop dev from starting without Cloudflare credentials — it fails when called instead",name:"local",type:Boolean},{description:"Share the worker through a Cloudflare quick tunnel (*.trycloudflare.com, needs cloudflared ≥ 2026.9.3). PUBLIC unless --allow-mail is given",name:"tunnel",type:Boolean},{description:"With --tunnel: only these emails get in, after a one-time PIN (passed to cloudflared as --allowed-mail). Repeatable; accepts a comma list and '*@domain'",lazyMultiple:!0,name:"allow-mail",type:String}]},le={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("./handler5.mjs").then(e=>({default:e.execute})),name:"docs"},de={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"],["lunora doctor --fix","Create the D1 databases the config names and mint the local dev secrets"],["lunora doctor --fix --dry-run","Show what --fix would create or write, without doing it"]],group:"Project",loader:()=>import("./handler31.mjs").then(e=>({default:e.execute})),name:"doctor",options:[s,{description:"Resolve what can be resolved: create placeholder D1 databases, mint missing .dev.vars secrets",name:"fix",type:Boolean},{description:"With --fix: print the changes without making them",name:"dry-run",type:Boolean}]},pe={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("./handler6.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},s,{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},ce={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("./handler26.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},s,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ue={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("./handler7.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{...s,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},me={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import backup.ndjson --mode replace --dry-run","Show what restoring a snapshot would add, overwrite and delete, writing nothing"],["lunora import backup.ndjson --mode replace","Make each of the snapshot's tables hold exactly its rows"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("./handler8.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},s,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"How rows the target already holds are treated: append (insert, skip existing _ids) | upsert (overwrite existing _ids) | replace (upsert, then delete the rows of the file's tables the file lacks; STOP all writes to the target first, or a row updated meanwhile is deleted) | require-empty (refuse unless those tables are empty) (default append)",name:"mode",type:String},{description:"Check the file and print what it would add, overwrite and delete; write nothing",name:"dry-run",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},he={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("./handler9.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},s,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},ge={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("./runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | rspack-react | saas | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | auth-ui | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Choose the auth: lunora (better-auth, users in your D1) | clerk | workos | auth0 (the provider owns the session; the Worker verifies its JWT) | none",name:"auth",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},fe={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --format json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("./handler10.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},ye={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("./handler28.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean},s]},ve={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("./handler11.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},we={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("./handler27.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},s,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},p,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},be={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --functions --token $MY_USER_TOKEN","Expose one tool per app function, running as that user (needs apiSpec openrpc)"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("./handler30.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: one tool per app function, from lunora/_generated/openrpc.json, run as the bearer given by --token. Never uses the admin token. Needs apiSpec openrpc",name:"functions",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},ke={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive | hyperdrive-to-d1 [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive | hyperdrive-to-d1) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate status backfill-names --format json","Same, as a single JSON document on stdout"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"],["lunora migrate hyperdrive-to-d1 --from-url https://new --to-url https://old","Roll .global() data back from Hyperdrive to D1"],["lunora migrate hyperdrive-to-d1 --from-url https://new --to-url https://old --tables settings --replace --yes","Roll back, overwriting rows D1 already holds"]],group:"Data",loader:()=>import("./dispatch.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},s,{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"backend migration: source worker URL (defaults to --url)",name:"from-url",type:String},{description:"backend migration: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"backend migration: target worker URL (defaults to --url)",name:"to-url",type:String},{description:"backend migration: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"backend migration: comma-separated .global() tables to move (default: every table, shard-local ones included; required with --replace)",name:"tables",type:String},{description:"backend migration: keep the intermediate NDJSON dump at this path",name:"out",type:String},{description:"backend migration: overwrite rows that already exist in the target with the source's values (needs --tables; default: leave them, report conflicts)",name:"replace",type:Boolean}]},O=[s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}],Se={argument:{description:"status (print the current state instead of pausing)",name:"subcommand",type:String},description:"Pause the deployment: refuse function calls, hold scheduled jobs, skip crons and queue batches",examples:[['lunora pause --reason "incident 42"',"Pause the local dev server"],["lunora pause status","Show whether the deployment is paused"],["lunora pause --prod --url https://app.example.com","Pause production"]],group:"Deploy",loader:()=>import("./handler12.mjs").then(e=>({default:e.executePause})),name:"pause",options:[{description:"A note shown wherever the pause is (Studio, the 503 body)",name:"reason",type:String},...O]},xe={description:"Resume a paused deployment; jobs held while paused run right away",examples:[["lunora resume","Resume the local dev server"],["lunora resume --prod --url https://app.example.com","Resume production"]],group:"Deploy",loader:()=>import("./handler12.mjs").then(e=>({default:e.executeResume})),name:"resume",options:O},Re={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("./handler13.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Evaluate the modules the Worker loads on demand (lazy functions, auth, API specs) in workerd before passing (default)",name:"smoke-load",type:Boolean},{description:"Skip evaluating on-demand modules before passing",name:"no-smoke-load",type:Boolean},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},p]},Ce={argument:{description:"deploy <name> | list | delete <name>",name:"subcommand",type:String},description:"Deploy, list and delete isolated preview copies of the app (own Worker, Durable Objects, D1, KV, R2)",examples:[["lunora preview deploy 123","Deploy preview 123 as its own Worker with its own data, then print its URL"],["lunora preview deploy 123 --seed","Deploy, then fill the preview with `lunora seed` data"],["lunora preview deploy 123 --secret RESEND_API_KEY","Give the preview a secret, read from the environment"],["lunora preview deploy 123 --var AUTH_URL=https://app-preview-123.acme.workers.dev","Override a production var in the preview"],["lunora preview deploy 123 --env production","Plan the preview from env.production's bindings, for an app that declares them only there"],["lunora preview deploy 123 --dry-run","Show the Worker, resources and env block a deploy would use"],["lunora preview list","List the previews on record"],["lunora preview delete 123 --env production","Delete a preview made with --env production, in that environment's account"],["lunora preview delete 123","Delete the preview Worker and every resource recorded for it"]],group:"Deploy",loader:()=>import("./handler29.mjs").then(e=>({default:e.execute})),name:"preview",options:[{description:"deploy: show the plan without calling Cloudflare; delete: read the record and show what would be deleted, changing nothing",name:"dry-run",type:Boolean},{description:"deploy: plan the preview from this Wrangler environment (the top level with env.<name> laid over it), for an app whose bindings live in env.<name>. delete, list: look in that environment's account_id; required (or CLOUDFLARE_ACCOUNT_ID) when an environment names an account other than the top level's",name:"env",type:String},{description:"delete: also look for the preview under the lunora.appId and Worker name of the package.json and wrangler config in this directory, read as data (CI passes a pull request's head files, whose identity the checkout may not share)",name:"head-dir",type:String},s,{description:"deploy: give the preview this secret, with the value of the same-named environment variable. Repeatable; nothing else is copied",lazyMultiple:!0,name:"secret",type:String},{description:"deploy: run `lunora seed` against the preview once it is live",name:"seed",type:Boolean},p,{description:"deploy: set a var in the preview, over production's value (e.g. an auth base URL). KEY=VALUE, repeatable",lazyMultiple:!0,name:"var",type:String}]},Oe={description:"Capture an on-demand CPU or heap profile (pprof) from a running Node-target app",examples:[["lunora profile --target node --url https://app.example.com/__profile","Capture a 10 s CPU profile of the app"],["lunora profile --target node --url http://localhost:3000/__profile --type heap --duration-ms 30000","Capture a 30 s heap profile of a local app"],["lunora profile --target node --url https://app.example.com/__profile --out cpu.pprof.gz","Write the profile to a named file"]],group:"Develop",loader:()=>import("./handler22.mjs").then(e=>({default:e.execute})),name:"profile",options:[{description:"Capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"cpu (default) or heap",name:"type",type:String},{description:"File to write the gzip pprof to (default profile-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"Full URL of the profile route the app mounts createNodeProfileHandler on",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String},p]},Ne={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("./handler15.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{...s,description:"Output format: pretty (default) or json (add plan / list)"},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},Ae={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("./runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},De={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("./handler16.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},Be={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],group:"Develop",loader:()=>import("./runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},s,{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},Ee={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("./handler23.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${$.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},Le={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("./handler14.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Let a required foreign key with no row to point at take a dangling id instead of failing",name:"allow-orphans",type:Boolean},s,{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},Ie={argument:{description:"prune",name:"subcommand",type:String},description:"Maintain the shard registry: prune shards that no longer hold any rows of their .shardBy() table",examples:[["lunora shards prune --dry-run","Show which registered shards are empty, without removing anything"],["lunora shards prune","Remove the empty shards from the registry"],["lunora shards prune --tables messages","Only prune the shards listed for `messages`"],["lunora shards prune --prod --url https://app.example.com","Prune production"]],group:"Data",loader:()=>import("./handler17.mjs").then(e=>({default:e.execute})),name:"shards",options:[{description:"Comma-separated .shardBy() tables (default: all of them)",name:"tables",type:String},{description:"Report what would be pruned without changing the registry",name:"dry-run",type:Boolean},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},_e={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("./handler18.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${m} (default openapi)`,name:"api-spec",type:String},{description:"Use per-module lazy function imports (opt-in; default eager)",name:"lazy-functions",type:Boolean},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},s,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},p]},je={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("./handler19.mjs").then(e=>({default:e.execute})),name:"view"},Te={argument:{description:"create <exportName> | send-event <exportName> <instanceId> <eventType>",name:"args",type:String},description:"Start a workflow instance, or send an event to a waiting one",examples:[[`lunora workflow create onboarding --params '{"userId":"u1"}'`,"Start an instance of the `onboarding` workflow"],["lunora workflow create onboarding --id user-u1","Start it under an explicit instance id"],[`lunora workflow send-event onboarding user-u1 approved --payload '{"by":"ada"}'`,"Deliver an `approved` event to a waiting instance"]],group:"Develop",loader:()=>import("./handler20.mjs").then(e=>({default:e.execute})),name:"workflow",options:[{description:"Instance id for `create` (defaults to a generated one)",name:"id",type:String},{description:"JSON-encoded params for `create`",name:"params",type:String},{description:"JSON-encoded event payload for `send-event`",name:"payload",type:String},s,{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN or .dev.vars)",name:"token",type:String}]},Pe=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},N=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Pe(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ue=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Me=1440*60*1e3,We=1500,ze="0.0.0",$e=/^v/u,Fe=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace($e,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},x=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ke=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},Je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Ke(a,i)}return 0},qe=(e,t)=>{const r=x(e),o=x(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return Je(g(e).prerelease,g(t).prerelease)},Ge=e=>{const t=g(e).prerelease.split(".")[0]??"";return Fe.has(t)?t:"latest"},Ve=(e,t)=>qe(t,e)>0,He=(e,t,r)=>t-e<r,Ye=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=W(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},A=e=>w(e,"lunora-cli-update.json"),Qe=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:w(Y(),".cache"),r=w(t,"lunora");try{q(r,{mode:448,recursive:!0})}catch{}return r},Xe=e=>{try{const t=JSON.parse(G(A(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},R=(e,t)=>{try{const r=A(e);try{if(V(r).isSymbolicLink())return}catch{}H(r,`${JSON.stringify(t)}
2
+ `,"utf8")}catch{}},Ze=async(e,t)=>{try{const r=await e(Ue(t),{signal:AbortSignal.timeout(We)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},et=(e,t,r)=>e===ze||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,tt=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(et(e.current,t,r))return;const o=e.cacheDir??Qe(t),n=(e.now??Date.now)(),a=e.ttlMs??Me,i=Ge(e.current),l=Xe(o),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let h=d?.latest;if(d===void 0||!He(d.checkedAt,n,a)){const f=await Ze(e.fetchImpl??globalThis.fetch,i);f===void 0?R(o,{checkedAt:n,latest:e.current,tag:i}):(h=f,R(o,{checkedAt:n,latest:f,tag:i}))}h!==void 0&&Ve(e.current,h)&&e.logger.warn(Ye(e.current,h,i,e.manager))},D=["init","add","dev","codegen","build","deploy","prepare","preview","link","cloudflare","logs","run","insights","profile","reset","migrate","export","import","seed","shards","pause","resume","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp","workflow"],B=F(),rt=[ge,Q,se,ae,Z,oe,ie,Re,Ce,ve,C,we,Be,fe,Oe,Ae,ke,ue,me,Le,Ie,Se,xe,X,ye,te,ce,_e,he,de,pe,ee,je,le,Ne,De,be,Ee,Te],E=[...rt,P,T],Bt=E.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),ot=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(r=>u(r))),nt=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:u(e.argument.description??"")}},...e.description===void 0?{}:{description:u(e.description)},...e.examples===void 0?{}:{examples:ot(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(t.description??"")}))}}),at=e=>{const t={value:0},r=j("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:B});for(const o of E)r.addCommand(nt(o));return{cli:r,exitCode:t}},it=/Command "(?<name>[^"]+)" not found/u,b={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},st=new Set((C.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),lt=/^[\w@%+=:,./-]+$/u,dt=e=>lt.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,pt=(e,t)=>{const r=e.indexOf(t);return r===-1?[...e]:[...e.slice(0,r),...e.slice(r+1)]},ct=(e,t)=>e.findIndex((r,o)=>r===t&&(o===0||!st.has(e[o-1]??""))),ut=e=>{const t=N(e,[...D,...Object.keys(b)]);return t!==void 0&&Object.hasOwn(b,t)?t:void 0},L=(e,t,r)=>{const o=ut(e),n=o===void 0?void 0:b[o];if(o===void 0||n===void 0)return;const a=e===o?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=ct(i,n.absorbs);if(d===-1&&r===void 0)return`${a}\`lunora ${o}\` had one subcommand, \`${n.absorbs}\`; it moved to \`lunora ${n.to}\`.`;i=d===-1?i:[...i.slice(0,d),...i.slice(d+1)]}const l=n.absorbs===void 0?o:`${o} ${n.absorbs}`,c=r??["lunora",n.to,...i.map(d=>dt(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},mt=(e,t)=>{const r=v(),o=e instanceof Error?e.message:String(e),n=it.exec(o);if(!n?.groups)return I(e)||_(o)!==void 0?r.error(J(e)):r.error(o),K(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=L(i,pt(t,i));if(l!==void 0)return r.error(l),y.USAGE;const c=N(a,D);return r.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),r.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},ht=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),Et=async(e={})=>{const{cli:t,exitCode:r}=at(e);e.logger!==void 0&&k(ht(e.logger));const o=e.argv??process.argv.slice(2);try{const a=o[0]==="help"&&o[1]!==void 0?L(o[1],o.slice(2),"lunora help cloudflare"):void 0;if(a!==void 0)return v().error(a),y.USAGE;await t.run({shouldExitProcess:!1})}catch(a){return mt(a,o)}finally{k(void 0)}let n;try{n=z(process.cwd())}catch{}return await tt({current:B,logger:v(),manager:n}),r.value};export{D as C,S as D,Bt as R,B as V,ne as a,Et as r};
@@ -1,24 +1,24 @@
1
- import{mkdirSync as hr,writeFileSync as X,existsSync as b,readFileSync as E,readdirSync as K,statSync as Re,rmSync as oe,mkdtempSync as ot,realpathSync as st}from"node:fs";import{dirname as j,join as p,resolve as I,relative as L,sep as x,extname as it}from"node:path";import{PROJECT_CONFIG_FILENAMES as at,isTestPath as ye,discoverMigrations as ct,readServiceBindings as Te,runCodegen as dt}from"@lunora/codegen";import{readLinkedProject as _e,discoverSchemaInfo as Ce,resolveSchemaDirectory as M,startDevProcess as lt,acceptsConnection as ut,resolveTargetOrThrow as we,detectFramework as ft,DEFAULT_BUNDLE_META_PATH as gt,STRICT_ADVISORIES_ENV as ht,LAZY_FUNCTIONS_ENV as mt,BUNDLE_META_PATH_ENV as pt,BUILD_TARGET_ENV as vt,BUILD_ROOT_ENV as yt,canonicalPath as wt,COMPOSED_WORKER_ENTRY as He,discoverContainerInfo as mr,D1_PLACEHOLDER_ID as qe,writeLinkedProject as kt,DEV_VARS_FILE as N,parseDevVariableEntries as pr,secretSourcesFromBindings as bt,inferLunoraBindings as vr,requiredSecrets as $t,mintableSecretKeysFor as St,generateSecretValue as Et,upsertDevVariableLine as At,writeDevVariablesFileAtomically as Rt,isPlaceholderValue as Tt,ensureGitignoreEntries as _t,resolveLazyFunctions as ce,resolveDeployDriver as de,MissingBuildOutputError as Ct,clearApiSpecMarker as It,createDiscoveryCache as Pt,planToolchainInvocation as yr,probeCelldToolchain as jt,runPostCodegenHook as Ot,readApiSpecMarker as Dt}from"@lunora/config";import{findWranglerFile as O,readWranglerJsonc as P,HYPERDRIVE_PLACEHOLDER_ID as wr,applyModify as kr,bindingsNeedingDatabase as Nt,mergeWranglerEnvironment as le,warnCloudflareCliConfigOnce as Lt,validateWranglerProject as xt,wranglerCodegenInputs as Mt,reconcileWranglerBindings as Ft,reconcileWranglerCompatibilityDate as Ut,reconcileWranglerCrons as Bt,describePreservedCrons as Wt}from"@lunora/config/cloudflare";import{Spinner as Ht}from"@visulima/spinner";import{r as qt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Gt,r as Vt,a as Kt}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Ie,a as zt,e as Jt}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Yt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as Xt,m as Qt,g as Zt,i as br,d as en,b as rn}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{w as tn}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as nn}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Pe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as on}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as sn}from"node:child_process";import{createHash as an,randomUUID as $r}from"node:crypto";import{setTimeout as cn}from"node:timers/promises";import{stripVTControlCharacters as dn}from"node:util";import{toolchainExecArgs as z,detectPackageManager as F,execArgsFor as je}from"@lunora/config/cli";import{r as Sr,c as Er}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as ln}from"../packem_shared/free-port-DjbFhaaT.mjs";import{ts as k,Project as Ar,SyntaxKind as y,Node as $}from"ts-morph";import{l as V}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as un}from"@lunora/container";import{a as fn,i as gn}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as H}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{a as Oe}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{p as hn,H as mn,a as pn,r as vn,c as yn,b as wn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as kn,openShardAccess as Ge}from"@lunora/advisor";import{join as A,relative as J,dirname as Rr}from"@visulima/path";import{runMigrateDataCommand as bn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as $n}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Sn}from"../packem_shared/wrangler-secrets-C9siMBwN.mjs";const En=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),An=20,Ve=e=>`${e.from} -${e.kind}-> ${e.to}`,ee=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},Rn=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>Ve(i)),s=r.edges.map(i=>Ve(i));return{addedEdges:ee(o,s),addedModules:ee(t,n),removedEdges:ee(s,o),removedModules:ee(n,t)}},re=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,An).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Tn=e=>{const r=[...re("+","modules added",e.addedModules),...re("-","modules removed",e.removedModules),...re("+","edges added",e.addedEdges),...re("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{mkdirSync as Ae,writeFileSync as Y,existsSync as b,readFileSync as S,readdirSync as V,statSync as Re,rmSync as ne,mkdtempSync as ut,realpathSync as ft}from"node:fs";import{dirname as A,join as v,resolve as C,relative as O,sep as N,extname as gt}from"node:path";import{PROJECT_CONFIG_FILENAMES as ht,isTestPath as ye,discoverMigrations as mt,readServiceBindings as Te,runCodegen as pt}from"@lunora/codegen";import{readLinkedProject as Ce,discoverSchemaInfo as _e,resolveSchemaDirectory as L,startDevProcess as vt,acceptsConnection as yt,resolveTargetOrThrow as we,detectFramework as wt,DEFAULT_BUNDLE_META_PATH as kt,STRICT_ADVISORIES_ENV as bt,LAZY_FUNCTIONS_ENV as $t,BUNDLE_META_PATH_ENV as St,BUILD_TARGET_ENV as Et,BUILD_ROOT_ENV as At,canonicalPath as Rt,COMPOSED_WORKER_ENTRY as Ve,discoverContainerInfo as yr,D1_PLACEHOLDER_ID as Ke,writeLinkedProject as Tt,DEV_VARS_FILE as D,parseDevVariableEntries as wr,secretSourcesFromBindings as Ct,inferLunoraBindings as kr,requiredSecrets as _t,mintableSecretKeysFor as It,generateSecretValue as Pt,upsertDevVariableLine as jt,writeDevVariablesFileAtomically as Ot,isPlaceholderValue as Dt,ensureGitignoreEntries as Nt,resolveLazyFunctions as ce,resolveDeployDriver as de,MissingBuildOutputError as Lt,clearApiSpecMarker as xt,createDiscoveryCache as Ft,planToolchainInvocation as br,probeCelldToolchain as Mt,runPostCodegenHook as Ut,readApiSpecMarker as Bt}from"@lunora/config";import{findWranglerFile as j,readWranglerJsonc as I,HYPERDRIVE_PLACEHOLDER_ID as $r,applyModify as Sr,mergeWranglerEnvironment as le,bindingsNeedingDatabase as Wt,warnCloudflareCliConfigOnce as Ht,validateWranglerProject as qt,wranglerCodegenInputs as Gt,reconcileWranglerBindings as Vt,reconcileWranglerCompatibilityDate as Kt,reconcileWranglerCrons as zt,describePreservedCrons as Jt}from"@lunora/config/cloudflare";import{Spinner as Yt}from"@visulima/spinner";import{r as Xt}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as Qt,r as Zt,a as en}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{r as Ie,a as rn,e as tn}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as nn}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{e as on,m as sn,g as an,i as Er,d as cn,b as dn}from"../packem_shared/vectorize-metadata-DK61NmVx.mjs";import{w as ln}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as un}from"../packem_shared/command-BpMv2n0o.mjs";import{r as Pe}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as fn}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as k}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{spawn as Ar,spawnSync as gn}from"node:child_process";import{createHash as hn,randomUUID as Rr}from"node:crypto";import{setTimeout as mn}from"node:timers/promises";import{stripVTControlCharacters as pn}from"node:util";import{toolchainExecArgs as K,detectPackageManager as x,execArgsFor as je}from"@lunora/config/cli";import{ts as y,Project as Tr,SyntaxKind as w,Node as $}from"ts-morph";import{r as Cr,c as _r}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{f as vn}from"../packem_shared/free-port-DjbFhaaT.mjs";import{l as G}from"../packem_shared/js-literal-FWLi94Lh.mjs";import{containerBuildTag as yn}from"@lunora/container";import{a as wn,i as kn}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as W}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{a as Oe}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{p as bn,H as $n,a as Sn,r as En,c as An,b as Rn}from"../packem_shared/health-probe-BLnoq_oC.mjs";import{runAdvisor as Tn,openShardAccess as ze}from"@lunora/advisor";import{join as E,relative as z,dirname as Ir}from"@visulima/path";import{runMigrateDataCommand as Cn}from"../packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs";import{c as _n}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as In}from"../packem_shared/wrangler-secrets-C9siMBwN.mjs";const Pn=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),jn=20,Je=e=>`${e.from} -${e.kind}-> ${e.to}`,Z=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},On=(e,r)=>{const t=e.modules.map(i=>i.name),n=r.modules.map(i=>i.name),o=e.edges.map(i=>Je(i)),s=r.edges.map(i=>Je(i));return{addedEdges:Z(o,s),addedModules:Z(t,n),removedEdges:Z(s,o),removedModules:Z(n,t)}},ee=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,jn).map(s=>` ${e} ${s}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Dn=e=>{const r=[...ee("+","modules added",e.addedModules),...ee("-","modules removed",e.removedModules),...ee("+","edges added",e.addedEdges),...ee("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
2
  ${r.join(`
3
- `)}`},_n=(e,r)=>p(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Cn=e=>{if(b(e))try{const r=JSON.parse(E(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},In=e=>{const{cwd:r,environment:t,logger:n}=e,o=_n(r,t),s=Cn(o),i=e.current??(s===void 0?void 0:En);if(i===void 0)return;const a=s===void 0?void 0:Tn(Rn(s,i));return a!==void 0&&n.info(a),()=>{try{hr(j(o),{recursive:!0}),X(o,`${JSON.stringify(i,void 0,2)}
4
- `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Pn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=_e(r),i=s?.workerName??Pe(r),a=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),a===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${a}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},jn=/\/index$/u,On=/[^\dA-Za-z]/gu,Dn=e=>e.replace(jn,"").split("/").map(r=>r.replaceAll(On,"_")),Nn=e=>Dn(e).join("_"),Ln=/[^a-z0-9-]/gu,xn=/-$/u,Ke=7,Mn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Ln,"-");if(n===t&&n.length<=r)return n;const o=an("sha256").update(t).digest("hex").slice(0,Ke-1);return`${n.slice(0,r-Ke).replace(xn,"")}-${o}`},Fn=32,Tr=15e3,Un=5432,Bn=3306,Wn=/[^A-Za-z0-9]/gu,Y=e=>`LUNORA_${e.replaceAll(Wn,"_").toUpperCase()}_URL`,Hn=e=>{const r=new Map;for(const t of e){const n=Y(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},qn=(e,r)=>Mn(`${e}-${r}`,Fn),ze=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Gn=e=>e==="mysql"?Bn:Un,Vn=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?Gn(ze(t)):Number(r.port),scheme:ze(t),user:decodeURIComponent(r.username)}}catch{return}},Kn=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},_r=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===wr?[{binding:n,index:t}]:[]}),se=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},zn=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,Jn=["scheme","host","port","database","user"],Yn=e=>e==="postgresql"?"postgres":e,Je=(e,r)=>{const t=zn(r);return e==="scheme"?Yn(t):t},Ye=50,Xn=async(e,r)=>{for(let t=1;t<=Ye;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${se(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(i=>i.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ye)} pages, so "${r}" can't be shown to be absent`)},Qn=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await Xn(e,r);if(typeof s?.id=="string"){const c=Jn.filter(d=>Je(d,s.origin?.[d])!==Je(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${se(l)})`);return{id:s.id,reused:!0}}const i=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!i.ok)throw new Error(`creating it failed (${se(i)})`);const{id:a}=typeof i.body.result=="object"&&i.body.result!==null?i.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},Zn=(e,r,t,n)=>r===void 0&&n?`${Y(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${Y(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,eo=async(e,r)=>{const t=qn(e.workerName,e.binding),{id:n,reused:o}=await Qn(async(s,i)=>Er({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Tr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:kr(r,[...e.path,e.index,"id"],n)}},ro=e=>e===void 0||e===""?void 0:e,De=e=>{const r=p(j(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(E(r,"utf8"));return typeof t=="string"?I(j(r),t):void 0}catch{return}},to=(e,r,t,n,o)=>{const s=De(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=P(s)}catch{return}const a=_r(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&X(s,kr(i.text,["hyperdrive",a.index,"id"],t),"utf8")},no=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},Ne=(e,r)=>{const t=O(e),n=t===void 0?void 0:P(t).parsed;if(t===void 0||n===void 0)return;const o=r===void 0?void 0:n.env?.[r],s=_r(r===void 0?n.hyperdrive:o?.hyperdrive);return s.length===0?void 0:{accountId:o?.account_id??n.account_id,entries:s,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:no(n,r),wranglerPath:t}},oo=(e,r,t)=>{const n=Hn(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:s,supplied:i}of e){const a=Zn(o,s,r,i);if(a!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${a} A real deploy stops here.`);else if(a!==void 0){const c=`deploy blocked: ${a}`;return t.logger.error(c),c}}},so=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(i){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${i instanceof Error?i.message:String(i)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${se(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},io=async(e,r)=>{const t=O(e.cwd),n=t===void 0?void 0:P(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=Sr(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>Er({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Tr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==wr&&await so(a,l,d,e.logger)}},ao=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await io(e,r);const t=Ne(e.cwd,e.wranglerEnvironment);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:i,token:a}=Sr(r,t.accountId),c=n.map(({binding:d})=>{const u=r[Y(d)]??"";return{binding:d,origin:Vn(u),supplied:u!==""}}),l=oo(c,a!==void 0&&i!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:u,index:f}]of n.entries()){const h=c[d]?.origin;if(!(h===void 0||a===void 0||i===void 0))try{const{id:g,text:v}=await eo({accountId:i,binding:u,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:f,logger:e.logger,origin:h,path:o,token:a,workerName:t.workerName,wranglerPath:s},E(s,"utf8"));X(s,v,"utf8"),to(s,u,g,{built:ro(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(g){const v=g instanceof Error?g.message:String(g),m=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${Kn(v,c[d]?.origin)}`;return e.logger.error(m),m}}},co=(e,r)=>{const t=Ne(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${Y(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},lo=(e,r)=>{const t=Ne(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},Cr=async(e,r,t,n,o="create")=>{if(n!=="cloudflare")return;if(t==="prepare")return co(e,r);if(r.temporary===!0)return lo(e,r);const s=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},i=Ce(e,M(e),r.discoveryCache);return i.error!==void 0&&r.logger.warn(`could not read the schema (${i.error}), so Hyperdrive configs are set up with query caching off.`),ao({checkOnly:o==="check",cwd:e,disableCaching:i.error!==void 0||i.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:s,logger:r.logger,wranglerEnvironment:r.env})},he=[".ts",".tsx",".mts",".js",".mjs"],uo=/^[a-z]+:/u,Xe=/\.[cm]?js$/u,fo=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!uo.test(e),go=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),ho=e=>e.split(x).some(r=>r==="_generated"||r==="node_modules"),mo=e=>e.split(x).includes("node_modules"),Qe=(e,r)=>{const t=I(j(e),r),n=Xe.test(t)?t.replace(Xe,""):void 0;return[t,...n===void 0?[]:he.map(s=>`${n}${s}`),...he.map(s=>`${t}${s}`),...he.map(s=>p(t,`index${s}`))].find(s=>b(s)&&Re(s).isFile())},po=/^lunora\.config\.[cm]?[jt]s$/u,ke=e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)for(const[r,t]of Object.entries(e)){const n=r==="types"?void 0:ke(t);if(n!==void 0)return n}},vo=(e,r)=>{let t;try{t=JSON.parse(E(p(e,"package.json"),"utf8")).imports}catch{return}const n=ke(t?.[r]);if(n!==void 0)return n;for(const[o,s]of Object.entries(t??{})){const[i="",a=""]=o.split("*"),c=ke(s);if(c!==void 0&&o.includes("*")&&r.startsWith(i)&&r.endsWith(a)&&r.length>=o.length-1){const l=r.slice(i.length,r.length-a.length);return c.replaceAll("*",()=>l)}}},yo=(e,r)=>{const t=p(e,r,"_generated"),n=K(e).find(o=>po.test(o));return[...b(t)?K(t).filter(o=>o.endsWith(".ts")).map(o=>p(t,o)):[],...n===void 0?[]:[p(e,n)]]},wo=e=>{const r=k.findConfigFile(e,n=>k.sys.fileExists(n));if(r===void 0)return!1;const t=k.readConfigFile(r,n=>k.sys.readFile(n));return k.parseJsonConfigFileContent(t.config??{},k.sys,j(r)).options.verbatimModuleSyntax===!0},Ze=e=>e!==void 0&&(k.isNamedImports(e)||k.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),ko=(e,r)=>{if(k.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===k.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&Ze(t?.namedBindings))&&k.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(k.isExportDeclaration(e))return!(e.isTypeOnly||!r&&Ze(e.exportClause))&&e.moduleSpecifier!==void 0&&k.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},bo=e=>{if(!k.isCallExpression(e)||e.expression.kind!==k.SyntaxKind.ImportKeyword)return;const[r]=e.arguments;return r!==void 0&&k.isStringLiteralLike(r)?r.text:void 0},$o=(e,r)=>{const t=k.createSourceFile(e,E(e,"utf8"),k.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=bo(i),c=a??ko(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&fo(a)&&n.push(a),k.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},So=(e,r)=>{for(let t=e;;t=j(t)){if(b(p(t,"node_modules",r,"package.json")))return!0;if(j(t)===t)return!1}},Eo=(e,r,t)=>{const n=wo(e),o=new Set,s=new Set,i=r!==void 0&&b(I(e,r))?[I(e,r)]:yo(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!mo(L(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=$o(a,n);if(!ho(L(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return Qe(a,d)??[];const u=vo(e,d);return u===void 0?[]:Qe(p(e,"package.json"),u)??[]}))}return[...s].filter(a=>So(e,go(a))).toSorted((a,c)=>a.localeCompare(c))},Ao=18787,er=3,be=12e4,Ro=5e3,W=10,Ir=new Set([".js",".mjs",".mts",".ts",".tsx"]),To=/\(void 0\)|is not a function|before initialization|of undefined/u,_o=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",Co=e=>{const r=M(e),t=new Map;let n;try{n=K(p(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=it(o);Ir.has(s)&&!o.split(x).some(i=>i==="_generated"||i==="node_modules")&&t.set(Nn(o.slice(0,-s.length).split(x).join("/")),p(r,o))}return t},rr=e=>To.test(e)?`
5
- hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",Io=(e,r)=>{const t=Co(e),n=new Map,o=[];for(const{deferred:s,functionPath:i,message:a}of r){if(s!==void 0){o.push(` ${i.slice(s.length+1)} (${s}): ${a}${rr(a)}`);continue}const c=i.lastIndexOf(":"),l=i.slice(0,c),d=`${l}\0${a}`,u=n.get(d)??{exports:[],message:a,namespace:l};u.exports.push(i.slice(c+1)),n.set(d,u)}return[...[...n.values()].map(({exports:s,message:i,namespace:a})=>` ${t.get(a)??a} (${s.join(", ")}): ${i}${rr(i)}`),...o]},te=e=>{for(const r of Ir)for(const t of[`${e}${r}`,p(e,`index${r}`)])if(b(t))return t},Po=(e,r)=>{const t=p(e,r,"_generated"),n=a=>{try{return E(p(t,a),"utf8")}catch{return""}},o=n("app.ts"),s=[],i=(a,c)=>{c!==void 0&&s.push({file:c,kind:a,label:L(e,c).split(x).join("/")})};return o.includes('import("./queues.js")')&&i("queue",te(p(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&i("workflow",te(p(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&i("agent",te(p(e,r,"agents"))),s},jo=/\.[cm]?js$/u,Oo=/(?:await|=>|return|[=[,])\s*import\(\s*"([^"]+)"\s*\)(?!\s*\.(?!(?:then|catch|finally)\b))/gu,Do=(e,r,t)=>{const n=p(e,r,"_generated"),o=new Set(t.map(a=>a.file)),s=[];let i;try{i=K(n).filter(a=>a.endsWith(".mjs")&&a!=="functions.ts")}catch{return s}for(const a of i.toSorted((c,l)=>c.localeCompare(l)))for(const c of E(p(n,a),"utf8").matchAll(Oo)){const l=c[1]??"",d=l.startsWith("."),u=d?te(I(n,l.replace(jo,""))):l;u!==void 0&&!o.has(u)&&(o.add(u),s.push({file:u,kind:"module",label:d?L(e,u).split(x).join("/"):l}))}return s};class C extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const No=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,Pr=(e,r,t)=>{const n=t??O(e),o=n===void 0?void 0:P(n).parsed;if(o===void 0)return{durableObjectClasses:[],hasContainers:!1,main:void 0,workflowClasses:[]};const{merged:s}=le(o,r),i=a=>[...new Set(a.flatMap(c=>c?.script_name===void 0&&typeof c?.class_name=="string"&&No.test(c.class_name)?[c.class_name]:[]))];return{durableObjectClasses:i(s.durable_objects?.bindings??[]),hasContainers:(s.containers??[]).length>0,main:s.main,workflowClasses:i(s.workflows??[])}},Lo=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{durableObjectClasses:s,hasContainers:i,main:a,workflowClasses:c}=Pr(t,n,r),l=e??a,d=r??O(t);let u;if(d!==void 0&&De(d)!==void 0)u={stubs:{durableObjects:s,workflows:c}};else if(typeof l=="string"&&!l.startsWith("virtual:")&&b(I(t,l)))u={main:l};else return{skip:"the Worker entry is not a file on disk"};if(i)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const f=Nt(t,process.env,n,r);return f.length>0?{skip:`the Hyperdrive binding ${f.join(", ")} has no local database for wrangler dev`}:{base:u,configFile:d}},xo=/The Workers runtime failed to start|Build failed with \d+ error/u,Mo=/\[ERROR\]|Uncaught/u,tr=e=>{const r=e.map(o=>dn(o).trim()).filter(o=>o!==""),t=r.filter(o=>Mo.test(o)),n=t.length>0?t.slice(0,10):r.slice(-10);return n.length===0?"":`
3
+ `)}`},Nn=(e,r)=>v(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Ln=e=>{if(b(e))try{const r=JSON.parse(S(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},xn=e=>{const{cwd:r,environment:t,logger:n}=e,o=Nn(r,t),s=Ln(o),i=e.current??(s===void 0?void 0:Pn);if(i===void 0)return;const a=s===void 0?void 0:Dn(On(s,i));return a!==void 0&&n.info(a),()=>{try{Ae(A(o),{recursive:!0}),Y(o,`${JSON.stringify(i,void 0,2)}
4
+ `,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Fn=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const s=Ce(r),i=s?.workerName??Pe(r),a=e.url??s?.workerUrl;n.success("deploy complete"),n.info(` worker: ${i??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),a===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${a}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},Mn=/\/index$/u,Un=/[^\dA-Za-z]/gu,Bn=e=>e.replace(Mn,"").split("/").map(r=>r.replaceAll(Un,"_")),Wn=e=>Bn(e).join("_"),Hn=/[^a-z0-9-]/gu,qn=/-$/u,Ye=7,Gn=(e,r)=>{const t=e.toLowerCase(),n=t.replaceAll(Hn,"-");if(n===t&&n.length<=r)return n;const o=hn("sha256").update(t).digest("hex").slice(0,Ye-1);return`${n.slice(0,r-Ye).replace(qn,"")}-${o}`},Vn=32,Pr=15e3,Kn=5432,zn=3306,Jn=/[^A-Za-z0-9]/gu,J=e=>`LUNORA_${e.replaceAll(Jn,"_").toUpperCase()}_URL`,Yn=e=>{const r=new Map;for(const t of e){const n=J(t),o=r.get(n);if(o!==void 0)return{bindings:[o,t],variable:n};r.set(n,t)}},Xn=(e,r)=>Gn(`${e}-${r}`,Vn),Xe=e=>e==="postgresql"?"postgres":e==="mariadb"?"mysql":e,Qn=e=>e==="mysql"?zn:Kn,Zn=e=>{try{const r=new URL(e),t=r.protocol.slice(0,-1),n=decodeURIComponent(r.pathname.slice(1));return!["mariadb","mysql","postgres","postgresql"].includes(t)||r.hostname===""||n===""?void 0:{database:n,host:r.hostname,password:decodeURIComponent(r.password),port:r.port===""?Qn(Xe(t)):Number(r.port),scheme:Xe(t),user:decodeURIComponent(r.username)}}catch{return}},eo=(e,r)=>{const t=typeof r?.password=="string"?r.password:"",n=t===""?[]:[t,JSON.stringify(t).slice(1,-1),encodeURIComponent(t)];let o=e;for(const s of n)o=o.replaceAll(s,"<redacted>");return o.split(" ").map(s=>s.includes("://")?"<url>":s).join(" ")},jr=e=>(Array.isArray(e)?e:[]).flatMap((r,t)=>{const{binding:n,id:o}=typeof r=="object"&&r!==null?r:{};return typeof n=="string"&&o===$r?[{binding:n,index:t}]:[]}),oe=e=>{let r="";try{const{errors:t}=JSON.parse(e.text);r=(t??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return r===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${r}`},ro=e=>typeof e=="string"||typeof e=="number"?e.toString():void 0,to=["scheme","host","port","database","user"],no=e=>e==="postgresql"?"postgres":e,Qe=(e,r)=>{const t=ro(r);return e==="scheme"?no(t):t},Ze=50,oo=async(e,r)=>{for(let t=1;t<=Ze;t+=1){const n=await e(t===1?"/hyperdrive/configs":`/hyperdrive/configs?page=${String(t)}`);if(!n.ok)throw new Error(`listing Hyperdrive configs failed (${oe(n)})`);if(!Array.isArray(n.body.result))throw new TypeError("the listing of Hyperdrive configs had no result list");const o=n.body.result.find(i=>i.name===r),s=typeof n.body.result_info=="object"&&n.body.result_info!==null?n.body.result_info:{};if(o!==void 0||typeof s.total_pages!="number"||t>=s.total_pages)return o}throw new Error(`the listing of Hyperdrive configs has more than ${String(Ze)} pages, so "${r}" can't be shown to be absent`)},so=async(e,r,t,n)=>{const o=n?{caching:{disabled:!0}}:{},s=await oo(e,r);if(typeof s?.id=="string"){const c=to.filter(d=>Qe(d,s.origin?.[d])!==Qe(d,t[d]));if(c.length>0)throw new Error(`a Hyperdrive config named "${r}" already exists for a different origin, or one that can't be confirmed (${c.join(", ")}). Delete it, or rename the Worker, so the binding does not reach the wrong database.`);const l=await e(`/hyperdrive/configs/${encodeURIComponent(s.id)}`,{body:JSON.stringify({origin:t,...o}),method:"PATCH"});if(!l.ok)throw new Error(`updating its credentials failed (${oe(l)})`);return{id:s.id,reused:!0}}const i=await e("/hyperdrive/configs",{body:JSON.stringify({name:r,origin:t,...o}),method:"POST"});if(!i.ok)throw new Error(`creating it failed (${oe(i)})`);const{id:a}=typeof i.body.result=="object"&&i.body.result!==null?i.body.result:{};if(typeof a!="string")throw new TypeError("the response carried no id");return{id:a,reused:!1}},io=(e,r,t,n)=>r===void 0&&n?`${J(e)} is set but is not a usable connection string for the "${e}" Hyperdrive binding: it needs a postgres://, postgresql:// or mysql:// scheme, a host and a database name, with any special characters percent-encoded.`:r===void 0?`the "${e}" Hyperdrive binding has no config yet. Set ${J(e)} to its postgres:// or mysql:// connection string and Lunora creates the config, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`:t?void 0:`creating the "${e}" Hyperdrive config needs CLOUDFLARE_API_TOKEN (Hyperdrive: Edit) and CLOUDFLARE_ACCOUNT_ID, or run \`wrangler hyperdrive create\` and put its id in wrangler.jsonc.`,ao=async(e,r)=>{const t=Xn(e.workerName,e.binding),{id:n,reused:o}=await so(async(s,i)=>_r({accountId:e.accountId,apiToken:e.token,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...i,signal:AbortSignal.timeout(Pr)},path:s}),t,e.origin,e.disableCaching);return e.logger.success(`${o?"reusing":"created"} Hyperdrive config "${t}" for ${e.binding} → ${e.wranglerPath}`),{id:n,text:Sr(r,[...e.path,e.index,"id"],n)}},co=e=>e===void 0||e===""?void 0:e,De=e=>{const r=v(A(e),".wrangler","deploy","config.json");try{const{configPath:t}=JSON.parse(S(r,"utf8"));return typeof t=="string"?C(A(r),t):void 0}catch{return}},lo=(e,r,t,n,o)=>{const s=De(e);if(s===void 0||s===e)return;if(n.built!==n.deployed){o.warn(`the build output ${s} was made for ${n.built===void 0?"the default environment":`"${n.built}"`}, not ${n.deployed===void 0?"the default environment":`"${n.deployed}"`}, so the "${r}" Hyperdrive id was not written there. Build with CLOUDFLARE_ENV set to the environment you deploy, then deploy again.`);return}let i;try{i=I(s)}catch{return}const a=jr(i.parsed?.hyperdrive).find(c=>c.binding===r);a!==void 0&&Y(s,Sr(i.text,["hyperdrive",a.index,"id"],t),"utf8")},uo=(e,r)=>{const t=typeof e.name=="string"&&e.name!==""?e.name:"lunora";if(r===void 0)return t;const n=e.env?.[r]?.name;return typeof n=="string"&&n!==""?n:`${t}-${r}`},Ne=(e,r,t)=>{const n=t??j(e),o=n===void 0?void 0:I(n).parsed;if(n===void 0||o===void 0)return;const s=r===void 0?void 0:o.env?.[r],i=jr(r===void 0?o.hyperdrive:s?.hyperdrive);return i.length===0?void 0:{accountId:s?.account_id??o.account_id,entries:i,path:r===void 0?["hyperdrive"]:["env",r,"hyperdrive"],workerName:uo(o,r),wranglerPath:n}},fo=(e,r,t)=>{const n=Yn(e.map(({binding:o})=>o));if(n!==void 0){const o=`deploy blocked: the Hyperdrive bindings ${n.bindings.map(s=>`"${s}"`).join(" and ")} both read ${n.variable} and would share one config. Rename one so their names differ in letters or digits, not only in punctuation.`;return t.logger.error(o),o}for(const{binding:o,origin:s,supplied:i}of e){const a=io(o,s,r,i);if(a!==void 0&&t.dryRun===!0)t.logger.warn(`dry run: ${a} A real deploy stops here.`);else if(a!==void 0){const c=`deploy blocked: ${a}`;return t.logger.error(c),c}}},go=async(e,r,t,n)=>{let o;try{o=await e(`/hyperdrive/configs/${encodeURIComponent(t)}`)}catch(i){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${i instanceof Error?i.message:String(i)}).`);return}if(!o.ok){n.warn(`could not check whether the "${r}" Hyperdrive config has query caching off (${oe(o)}).`);return}const{caching:s}=typeof o.body.result=="object"&&o.body.result!==null?o.body.result:{};s?.disabled!==!0&&n.warn(`the "${r}" Hyperdrive config has query caching on, so .global() tables would read rows up to 75 s old. Run \`wrangler hyperdrive update ${t} --caching-disabled\`.`)},ho=async(e,r)=>{const t=e.wranglerPath??j(e.cwd),n=t===void 0?void 0:I(t).parsed,o=e.wranglerEnvironment===void 0?n:n?.env?.[e.wranglerEnvironment],{accountId:s,token:i}=Cr(r,o?.account_id??n?.account_id);if(s===void 0||i===void 0)return;const a=async(c,l)=>_r({accountId:s,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{...l,signal:AbortSignal.timeout(Pr)},path:c});for(const c of Array.isArray(o?.hyperdrive)?o.hyperdrive:[]){const{binding:l,id:d}=typeof c=="object"&&c!==null?c:{};typeof l=="string"&&typeof d=="string"&&d!==$r&&await go(a,l,d,e.logger)}},mo=async e=>{const r=e.environment??process.env;e.disableCaching===!0&&e.checkOnly!==!0&&e.dryRun!==!0&&await ho(e,r);const t=Ne(e.cwd,e.wranglerEnvironment,e.wranglerPath);if(t===void 0)return;const{entries:n,path:o,wranglerPath:s}=t,{accountId:i,token:a}=Cr(r,t.accountId),c=n.map(({binding:d})=>{const u=r[J(d)]??"";return{binding:d,origin:Zn(u),supplied:u!==""}}),l=fo(c,a!==void 0&&i!==void 0,e);if(l!==void 0)return l;if(!(e.dryRun===!0||e.checkOnly===!0))for(const[d,{binding:u,index:f}]of n.entries()){const g=c[d]?.origin;if(!(g===void 0||a===void 0||i===void 0))try{const{id:h,text:m}=await ao({accountId:i,binding:u,disableCaching:e.disableCaching===!0,fetch:e.fetch,index:f,logger:e.logger,origin:g,path:o,token:a,workerName:t.workerName,wranglerPath:s},S(s,"utf8"));Y(s,m,"utf8"),lo(s,u,h,{built:co(r.CLOUDFLARE_ENV),deployed:e.wranglerEnvironment},e.logger)}catch(h){const m=h instanceof Error?h.message:String(h),p=`deploy blocked: the "${u}" Hyperdrive config could not be set up: ${eo(m,c[d]?.origin)}`;return e.logger.error(p),p}}},po=(e,r)=>{const t=Ne(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`prepare blocked: the "${t}" Hyperdrive binding still has its placeholder id. Run \`lunora deploy\` with ${J(t)} set to create the config, or put the id from \`wrangler hyperdrive create\` in wrangler.jsonc.`;return r.logger.error(n),n},vo=(e,r)=>{const t=Ne(e,r.env)?.entries[0]?.binding;if(t===void 0)return;const n=`deploy blocked: the "${t}" Hyperdrive binding has no config, and a --temporary deploy cannot create one: it would be made in your account while the Worker goes to a temporary one, which a temporary account has no database for. Deploy without --temporary.`;return r.logger.error(n),n},ue=async(e,r,t,n,o="create",s)=>{if(n!=="cloudflare")return;if(t==="prepare")return po(e,r);if(r.temporary===!0)return vo(e,r);const i=r.clientBuildEnvironment===void 0?void 0:{...process.env,CLOUDFLARE_ENV:r.clientBuildEnvironment},a=_e(e,L(e),r.discoveryCache);return a.error!==void 0&&r.logger.warn(`could not read the schema (${a.error}), so Hyperdrive configs are set up with query caching off.`),mo({checkOnly:o==="check",cwd:e,disableCaching:a.error!==void 0||a.info?.hasHyperdriveGlobalTable===!0,dryRun:r.dryRun,environment:i,logger:r.logger,wranglerEnvironment:r.env,wranglerPath:s})},me=[".ts",".tsx",".mts",".js",".mjs"],yo=/^[a-z]+:/u,er=/\.[cm]?js$/u,wo=e=>!e.startsWith(".")&&!e.startsWith("/")&&!e.startsWith("#")&&!yo.test(e),ko=e=>e.split("/").slice(0,e.startsWith("@")?2:1).join("/"),bo=e=>e.split(N).some(r=>r==="_generated"||r==="node_modules"),$o=e=>e.split(N).includes("node_modules"),rr=(e,r)=>{const t=C(A(e),r),n=er.test(t)?t.replace(er,""):void 0;return[t,...n===void 0?[]:me.map(s=>`${n}${s}`),...me.map(s=>`${t}${s}`),...me.map(s=>v(t,`index${s}`))].find(s=>b(s)&&Re(s).isFile())},So=/^lunora\.config\.[cm]?[jt]s$/u,ke=e=>{if(typeof e=="string")return e;if(typeof e=="object"&&e!==null)for(const[r,t]of Object.entries(e)){const n=r==="types"?void 0:ke(t);if(n!==void 0)return n}},Eo=(e,r)=>{let t;try{t=JSON.parse(S(v(e,"package.json"),"utf8")).imports}catch{return}const n=ke(t?.[r]);if(n!==void 0)return n;for(const[o,s]of Object.entries(t??{})){const[i="",a=""]=o.split("*"),c=ke(s);if(c!==void 0&&o.includes("*")&&r.startsWith(i)&&r.endsWith(a)&&r.length>=o.length-1){const l=r.slice(i.length,r.length-a.length);return c.replaceAll("*",()=>l)}}},Ao=(e,r)=>{const t=v(e,r,"_generated"),n=V(e).find(o=>So.test(o));return[...b(t)?V(t).filter(o=>o.endsWith(".ts")).map(o=>v(t,o)):[],...n===void 0?[]:[v(e,n)]]},Ro=e=>{const r=y.findConfigFile(e,n=>y.sys.fileExists(n));if(r===void 0)return!1;const t=y.readConfigFile(r,n=>y.sys.readFile(n));return y.parseJsonConfigFileContent(t.config??{},y.sys,A(r)).options.verbatimModuleSyntax===!0},tr=e=>e!==void 0&&(y.isNamedImports(e)||y.isNamedExports(e))&&e.elements.length>0&&e.elements.every(r=>r.isTypeOnly),To=(e,r)=>{if(y.isImportDeclaration(e)){const{importClause:t}=e;return!(t?.phaseModifier===y.SyntaxKind.TypeKeyword||!r&&t?.name===void 0&&tr(t?.namedBindings))&&y.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0}if(y.isExportDeclaration(e))return!(e.isTypeOnly||!r&&tr(e.exportClause))&&e.moduleSpecifier!==void 0&&y.isStringLiteral(e.moduleSpecifier)?e.moduleSpecifier.text:void 0},Co=e=>{if(!y.isCallExpression(e)||e.expression.kind!==y.SyntaxKind.ImportKeyword)return;const[r]=e.arguments;return r!==void 0&&y.isStringLiteralLike(r)?r.text:void 0},_o=(e,r)=>{const t=y.createSourceFile(e,S(e,"utf8"),y.ScriptTarget.Latest,!1),n=[],o=[],s=i=>{const a=Co(i),c=a??To(i,r);c?.startsWith(".")||c?.startsWith("#")?o.push(c):a!==void 0&&wo(a)&&n.push(a),y.forEachChild(i,s)};return s(t),{dynamicPackages:n,relative:o}},Io=(e,r)=>{for(let t=e;;t=A(t)){if(b(v(t,"node_modules",r,"package.json")))return!0;if(A(t)===t)return!1}},Po=(e,r,t)=>{const n=Ro(e),o=new Set,s=new Set,i=r!==void 0&&b(C(e,r))?[C(e,r)]:Ao(e,t);for(let a=i.shift();a!==void 0;a=i.shift())if(!o.has(a)&&!$o(O(e,a))){o.add(a);const{dynamicPackages:c,relative:l}=_o(a,n);if(!bo(O(e,a)))for(const d of c)s.add(d);i.push(...l.flatMap(d=>{if(!d.startsWith("#"))return rr(a,d)??[];const u=Eo(e,d);return u===void 0?[]:rr(v(e,"package.json"),u)??[]}))}return[...s].filter(a=>Io(e,ko(a))).toSorted((a,c)=>a.localeCompare(c))},jo=18787,nr=3,be=12e4,Oo=5e3,B=10,Or=new Set([".js",".mjs",".mts",".ts",".tsx"]),Do=/\(void 0\)|is not a function|before initialization|of undefined/u,No=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&(e.deferred===void 0||["agent","module","queue","workflow"].includes(e.deferred))&&typeof e.message=="string",Lo=e=>{const r=L(e),t=new Map;let n;try{n=V(v(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const s=gt(o);Or.has(s)&&!o.split(N).some(i=>i==="_generated"||i==="node_modules")&&t.set(Wn(o.slice(0,-s.length).split(N).join("/")),v(r,o))}return t},or=e=>Do.test(e)?`
5
+ hint: if this module is part of a circular import, an import it reads is still undefined while it evaluates`:"",xo=(e,r)=>{const t=Lo(e),n=new Map,o=[];for(const{deferred:s,functionPath:i,message:a}of r){if(s!==void 0){o.push(` ${i.slice(s.length+1)} (${s}): ${a}${or(a)}`);continue}const c=i.lastIndexOf(":"),l=i.slice(0,c),d=`${l}\0${a}`,u=n.get(d)??{exports:[],message:a,namespace:l};u.exports.push(i.slice(c+1)),n.set(d,u)}return[...[...n.values()].map(({exports:s,message:i,namespace:a})=>` ${t.get(a)??a} (${s.join(", ")}): ${i}${or(i)}`),...o]},re=e=>{for(const r of Or)for(const t of[`${e}${r}`,v(e,`index${r}`)])if(b(t))return t},Fo=(e,r)=>{const t=v(e,r,"_generated"),n=a=>{try{return S(v(t,a),"utf8")}catch{return""}},o=n("app.ts"),s=[],i=(a,c)=>{c!==void 0&&s.push({file:c,kind:a,label:O(e,c).split(N).join("/")})};return o.includes('import("./queues.js")')&&i("queue",re(v(t,"queues"))),n("workflows.mjs").includes('import("../workflows.js")')&&i("workflow",re(v(e,r,"workflows"))),(n("agents.mjs").includes('import("../agents.js")')||o.includes('import("../agents.js")'))&&i("agent",re(v(e,r,"agents"))),s},Mo=/\.[cm]?js$/u,Uo=(e,r)=>{const t=[],n=o=>{if(y.isCallExpression(o)&&o.expression.kind===y.SyntaxKind.ImportKeyword){const[s]=o.arguments;s!==void 0&&y.isStringLiteralLike(s)&&t.push(s.text)}y.forEachChild(o,n)};return n(y.createSourceFile(e,r,y.ScriptTarget.Latest,!1,y.ScriptKind.TS)),t},Bo=(e,r,t)=>{const n=v(e,r,"_generated"),o=new Set(t.map(a=>a.file)),s=[];let i;try{i=V(n).filter(a=>a.endsWith(".mjs")&&a!=="functions.ts")}catch{return s}for(const a of i.toSorted((c,l)=>c.localeCompare(l)))for(const c of Uo(v(n,a),S(v(n,a),"utf8"))){const l=c.startsWith("."),d=l?re(C(n,c.replace(Mo,""))):c;d!==void 0&&!o.has(d)&&(o.add(d),s.push({file:d,kind:"module",label:l?O(e,d).split(N).join("/"):c}))}return s};class _ extends Error{skipped;constructor(r,t=!1){super(r),this.skipped=t}}const sr=/^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u,Dr=(e,r,t)=>{const n=t??j(e),o=n===void 0?void 0:I(n).parsed;if(o===void 0)return{assetsDirectory:void 0,durableObjectClasses:[],entrypointClasses:[],hasContainers:!1,main:void 0,workflowClasses:[]};const{merged:s}=le(o,r),i=d=>[...new Set(d.flatMap(u=>u?.script_name===void 0&&typeof u?.class_name=="string"&&sr.test(u.class_name)?[u.class_name]:[]))],a=s.exports??{},c=d=>Object.entries(a).flatMap(([u,f])=>f?.type===d&&(f.state===void 0||f.state==="created")&&sr.test(u)?[u]:[]),l=s.assets?.directory;return{assetsDirectory:l===void 0||n===void 0?void 0:C(A(n),l),durableObjectClasses:[...new Set([...i(s.durable_objects?.bindings??[]),...c("durable-object")])],entrypointClasses:c("worker"),hasContainers:(s.containers??[]).length>0,main:s.main,workflowClasses:[...new Set([...i(s.workflows??[]),...c("workflow")])]}},Wo=({composedEntry:e,configPath:r,cwd:t,environment:n,toolchain:o})=>{if(o.devServer!=="workerd")return{skip:"this deploy target does not run on workerd"};const{assetsDirectory:s,durableObjectClasses:i,entrypointClasses:a,hasContainers:c,main:l,workflowClasses:d}=Dr(t,n,r),u=e??l,f=r??j(t);let g;if(f!==void 0&&De(f)!==void 0)g={stubs:{durableObjects:i,entrypoints:a,workflows:d}};else if(typeof u=="string"&&!u.startsWith("virtual:")&&b(C(t,u)))g={main:u};else return{skip:"the Worker entry is not a file on disk"};const h=s!==void 0&&!b(s);if(c)return{skip:"the project declares containers, which `wrangler dev` would build locally before the real container build"};const m=Wt(t,process.env,n,r);return m.length>0?{skip:`the Hyperdrive binding ${m.join(", ")} has no local database for wrangler dev`}:{base:g,configFile:f,missingAssets:h}},Ho=/The Workers runtime failed to start|Build failed with \d+ error/u,qo=/\[ERROR\]|Uncaught/u,ir=e=>{const r=e.map(o=>pn(o).trim()).filter(o=>o!==""),t=r.filter(o=>qo.test(o)),n=t.length>0?t.slice(0,10):r.slice(-10);return n.length===0?"":`
6
6
  ${n.map(o=>` ${o}`).join(`
7
- `)}`},$e=async e=>{const{deadline:r,output:t,pending:n,port:o,query:s,startupFailed:i}=e,a=await fetch(`http://127.0.0.1:${String(o)}/_lunora/__smoke_load?${s}`,{signal:AbortSignal.any([AbortSignal.timeout(Math.max(0,r-Date.now())),i])}).catch(d=>{throw i.aborted?new C(`the smoke Worker's runtime did not start, so nothing was evaluated:${tr(t)}
8
- Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new C(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String(be/1e3)}s, so its runtime did not start:${tr(t)}
9
- Pass --no-smoke-load to ship anyway.`:`the smoke Worker did not finish evaluating ${n} within ${String(be/1e3)}s — it may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):d});if(a.status>=500)throw new C(`the smoke Worker booted but failed while ${n===void 0?"answering a request that evaluates nothing":`evaluating ${n}`} (HTTP ${String(a.status)}). Pass --no-smoke-load to ship anyway.`);const c=await a.text().catch(()=>"");let l;try{l=JSON.parse(c)}catch{l=void 0}return{body:typeof l=="object"&&l!==null?l:void 0,response:a,text:c}},Se=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new C(`the smoke Worker answered with something other than the probe's result (HTTP ${String(e.status)}, ${t}${n===""?"":`: ${n}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},nr=async(e,r)=>{const t=await $e(e),n=t.body?.message;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw Se(t.response,t.text);return n},Fo=async e=>{const{deferred:r,functions:t,integrationModules:n,runId:o,...s}=e,i=await $e({...s,pending:void 0,query:"step=ping"});if(typeof i.body?.run!="string")throw Se(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await $e({...s,pending:"the lazy function modules",query:"step=functions"}),{checked:u,failures:f}=d.body??{};if(d.body?.run!==o||typeof u!="number"||!Array.isArray(f)||!f.every(h=>_o(h)))throw Se(d.response,d.text);a=u,c=f}for(const[d,u]of r.entries()){const f=await nr({...s,pending:`${u.kind} module ${u.label}`,query:`step=deferred&index=${String(d)}`},o);f!==void 0&&c.push({deferred:u.kind,functionPath:`${u.kind}:${u.label}`,message:f})}const l=[];for(const d of n){const u=await nr({...s,pending:`import(${JSON.stringify(d)})`,query:new URLSearchParams({specifier:d,step:"integration"}).toString()},o);u!==void 0&&l.push({message:u,specifier:d})}return{checked:a,deferredChecked:r.length,failures:c,integrations:{checked:n.length,failures:l}}},Ee=(e,r)=>{try{process.kill(-e,r)}catch{}},or=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Uo=e=>{const r=()=>{Ee(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},me=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;Ee(r,"SIGTERM");const t=Date.now()+Ro;for(;or(r)&&Date.now()<t;)await cn(50);or(r)&&Ee(r,"SIGKILL")},Bo=e=>lt(e).catch(async r=>{if(!await ut(e.port))throw r}),Wo=({checked:e,deferredChecked:r,integrations:t})=>[`${String(e)} lazy function(s)`,...r>0?[`${String(r)} deferred module(s)`]:[],...t.checked>0?[`${String(t.checked)} integration module(s) loaded with import()`]:[]].join(" and "),Ho=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${Wo(r)} evaluate cleanly`);return}const a=Io(e,s),c=a.length>W?[` …and ${String(a.length-W)} more module(s)`]:[];throw new C([...s.length===0?[]:[`${String(s.length)} of ${o===0?`${String(n)} lazy function(s)`:`${String(n+o)} lazy module(s)`} fail to load:`,...a.slice(0,W),...c],...i.failures.length===0?[]:[`${String(i.failures.length)} of ${String(i.checked)} integration module(s) fail to load in workerd (each would fail its first use instead):`,...i.failures.slice(0,W).map(({message:l,specifier:d})=>` import("${d}"): ${l}`),...i.failures.length>W?[` …and ${String(i.failures.length-W)} more integration module(s)`]:[]],"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
10
- `))},qo=(e,r,t)=>{if(e instanceof C&&!e.skipped)return t.error(e.message),e.message;if(e instanceof C){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
7
+ `)}`},Le=async e=>{const{deadline:r,output:t,pending:n,port:o,query:s,startupFailed:i}=e,a=await fetch(`http://127.0.0.1:${String(o)}/_lunora/__smoke_load?${s}`,{signal:AbortSignal.any([AbortSignal.timeout(Math.max(0,r-Date.now())),i])}).catch(d=>{throw i.aborted?new _(`the smoke Worker's runtime did not start, so nothing was evaluated:${ir(t)}
8
+ Fix the entry, or pass --no-smoke-load to ship anyway.`):d instanceof Error&&d.name==="TimeoutError"?new _(n===void 0?`the smoke Worker accepted the connection but answered no request within ${String(be/1e3)}s, so its runtime did not start:${ir(t)}
9
+ Pass --no-smoke-load to ship anyway.`:`the smoke Worker did not finish evaluating ${n} within ${String(be/1e3)}s — it may be awaiting something that never settles. Pass --no-smoke-load to ship anyway.`):d});if(a.status>=500)throw new _(`the smoke Worker booted but failed while ${n===void 0?"answering a request that evaluates nothing":`evaluating ${n}`} (HTTP ${String(a.status)}). Pass --no-smoke-load to ship anyway.`);const c=await a.text().catch(()=>"");let l;try{l=JSON.parse(c)}catch{l=void 0}return{body:typeof l=="object"&&l!==null?l:void 0,response:a,text:c}},xe=(e,r)=>{const t=e.headers.get("content-type")??"no content type",n=r.replaceAll(/\s+/gu," ").trim().slice(0,120);return new _(`the smoke Worker answered with something other than the probe's result (HTTP ${String(e.status)}, ${t}${n===""?"":`: ${n}`}). A route that does not send /_lunora/* to the Worker first answers with the app's assets, so check run_worker_first. Pass --no-smoke-load to ship anyway.`)},Nr=(e,r)=>typeof e=="string"&&e!==r,$e=Symbol("another run's Worker"),ar=async(e,r)=>{const t=await Le(e),n=t.body?.message;if(Nr(t.body?.run,r))return $e;if(t.body?.run!==r||n!==void 0&&typeof n!="string")throw xe(t.response,t.text);return n},Go=async(e,r)=>{const t=await Le({...e,pending:"the lazy function modules",query:"step=functions"}),{checked:n,failures:o}=t.body??{};if(!Nr(t.body?.run,r)){if(t.body?.run!==r||typeof n!="number"||!Array.isArray(o)||!o.every(s=>No(s)))throw xe(t.response,t.text);return{checked:n,failures:o}}},Vo=async e=>{const{deferred:r,functions:t,integrationModules:n,runId:o,...s}=e,i=await Le({...s,pending:void 0,query:"step=ping"});if(typeof i.body?.run!="string")throw xe(i.response,i.text);if(i.body.run!==o)return;let a=0,c=[];if(t){const d=await Go(s,o);if(d===void 0)return;a=d.checked,c=d.failures}for(const[d,u]of r.entries()){const f=await ar({...s,pending:`${u.kind} module ${u.label}`,query:`step=deferred&index=${String(d)}`},o);if(f===$e)return;f!==void 0&&c.push({deferred:u.kind,functionPath:`${u.kind}:${u.label}`,message:f})}const l=[];for(const d of n){const u=await ar({...s,pending:`import(${JSON.stringify(d)})`,query:new URLSearchParams({specifier:d,step:"integration"}).toString()},o);if(u===$e)return;u!==void 0&&l.push({message:u,specifier:d})}return{checked:a,deferredChecked:r.length,failures:c,integrations:{checked:n.length,failures:l}}},Se=(e,r)=>{try{process.kill(-e,r)}catch{}},cr=e=>{try{return process.kill(-e,0),!0}catch{return!1}},Lr=e=>({args:["/pid",String(e),"/T","/F"],command:v(process.env.SystemRoot??String.raw`C:\Windows`,"System32","taskkill.exe")}),Ko=e=>{const r=()=>{if(process.platform==="win32"){const{args:o,command:s}=Lr(e);gn(s,o,{stdio:"ignore"});return}Se(e,"SIGKILL")},t=o=>{r(),process.kill(process.pid,o)},n=()=>{process.removeListener("exit",r),process.removeListener("SIGINT",t),process.removeListener("SIGTERM",t)};return process.once("exit",r),process.once("SIGINT",t),process.once("SIGTERM",t),n},zo=e=>new Promise(r=>{const{args:t,command:n}=Lr(e),o=Ar(n,t,{stdio:"ignore",windowsHide:!0});o.once("error",()=>{r()}),o.once("exit",()=>{r()})}),se=async e=>{if(e===void 0)return;e.dispose();const{pid:r}=e;if(process.platform==="win32"){await zo(r);return}Se(r,"SIGTERM");const t=Date.now()+Oo;for(;cr(r)&&Date.now()<t;)await mn(50);cr(r)&&Se(r,"SIGKILL")},Jo=(e,r,t)=>[e?"lazy function modules":void 0,r===0?void 0:`${String(r)} deferred module(s)`,t===0?void 0:`${String(t)} integration module(s)`].filter(n=>n!==void 0).join(", "),Yo=async(e,r)=>{if(process.platform==="win32"){try{await se(r)}finally{await e.stop()}return}try{await e.stop()}finally{await se(r)}},Xo=e=>vt(e).catch(async r=>{if(!await yt(e.port))throw r}),Qo=({checked:e,deferredChecked:r,integrations:t})=>[`${String(e)} lazy function(s)`,...r>0?[`${String(r)} deferred module(s)`]:[],...t.checked>0?[`${String(t.checked)} integration module(s) loaded with import()`]:[]].join(" and "),Zo=(e,r,t)=>{const{checked:n,deferredChecked:o,failures:s,integrations:i}=r;if(s.length===0&&i.failures.length===0){t.success(`${Qo(r)} evaluate cleanly`);return}const a=xo(e,s),c=a.length>B?[` …and ${String(a.length-B)} more module(s)`]:[];throw new _([...s.length===0?[]:[`${String(s.length)} of ${o===0?`${String(n)} lazy function(s)`:`${String(n+o)} lazy module(s)`} fail to load:`,...a.slice(0,B),...c],...i.failures.length===0?[]:[`${String(i.failures.length)} of ${String(i.checked)} integration module(s) fail to load in workerd (each would fail its first use instead):`,...i.failures.slice(0,B).map(({message:l,specifier:d})=>` import("${d}"): ${l}`),...i.failures.length>B?[` …and ${String(i.failures.length-B)} more integration module(s)`]:[]],"Fix the module, or pass --no-smoke-load to ship anyway."].join(`
10
+ `))},es=(e,r,t)=>{if(e instanceof _&&!e.skipped)return t.error(e.message),e.message;if(e instanceof _){t.warn(`smoke-load skipped: ${e.message}`);return}const n=r.slice(-5).join(`
11
11
  `),o=`the smoke Worker did not start (${e instanceof Error?e.message:String(e)})${n===""?"":`
12
- ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding or a missing assets directory). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},Go=e=>{try{return hr(p(e,".lunora"),{recursive:!0}),ot(p(e,".lunora","smoke-"))}catch(r){throw new C(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},Vo=(e,r)=>{if("main"in r)return`export * from ${V(I(e,r.main))};`;const{durableObjects:t,workflows:n}=r.stubs;return['import { DurableObject, WorkflowEntrypoint } from "cloudflare:workers";',...t.map(o=>`export class ${o} extends DurableObject {}`),...n.map(o=>`export class ${o} extends WorkflowEntrypoint { async run() {} }`)].join(`
13
- `)},Ko=async e=>{const{base:r,configPath:t,cwd:n,deferred:o,directory:s,environment:i,functionsFile:a,integrationModules:c,preferred:l,toolchain:d}=e;try{const u=p(s,"entry.ts"),f=$r(),h=c.map(S=>` [${V(S)}, () => import(${V(S)})],`).join(`
14
- `);X(u,`${Vo(n,r)}
15
- ${a===void 0?"":`import { loadAllFunctions } from ${V(a)};
12
+ ${n}`}. Either the entry fails when it loads, or local wrangler cannot run the project (a remote-only binding). Fix whichever it is, or pass --no-smoke-load to ship anyway.`;return t.error(o),o},rs=e=>{try{return Ae(v(e,".lunora"),{recursive:!0}),ut(v(e,".lunora","smoke-"))}catch(r){throw new _(`could not create a directory for the check (${r instanceof Error?r.message:String(r)})`,!0)}},ts=(e,r)=>{if("main"in r)return`export * from ${G(C(e,r.main))};`;const{durableObjects:t,entrypoints:n,workflows:o}=r.stubs,s=new Set,i=(a,c)=>a==="default"||s.has(a)?[]:(s.add(a),[`export class ${a} ${c}`]);return['import { DurableObject, WorkerEntrypoint, WorkflowEntrypoint } from "cloudflare:workers";',...t.flatMap(a=>i(a,"extends DurableObject {}")),...n.flatMap(a=>i(a,"extends WorkerEntrypoint {}")),...o.flatMap(a=>i(a,"extends WorkflowEntrypoint { async run() {} }"))].join(`
13
+ `)},ns=async e=>{const{base:r,configPath:t,cwd:n,deferred:o,directory:s,environment:i,functionsFile:a,integrationModules:c,missingAssets:l,preferred:d,toolchain:u}=e;try{const f=v(s,"entry.ts"),g=Rr();l&&Ae(v(s,"assets"),{recursive:!0});const h=c.map(P=>` [${G(P)}, () => import(${G(P)})],`).join(`
14
+ `),m="stubs"in r&&r.stubs.entrypoints.includes("default");Y(f,`${ts(n,r)}
15
+ ${a===void 0?"":`import { loadAllFunctions } from ${G(a)};
16
16
  `}
17
- const runId = ${JSON.stringify(f)};
17
+ const runId = ${JSON.stringify(g)};
18
18
 
19
19
  // Deferred event modules, evaluated one per request so a module that throws on import blocks like a function module does.
20
20
  const deferred = [
21
- ${o.map(S=>` () => import(${V(S.file)}),`).join(`
21
+ ${o.map(P=>` () => import(${G(P.file)}),`).join(`
22
22
  `)}
23
23
  ];
24
24
 
@@ -26,7 +26,7 @@ const integrationLoaders = new Map<string, () => Promise<unknown>>([
26
26
  ${h}
27
27
  ]);
28
28
 
29
- export default {
29
+ const smokeProbe = {
30
30
  async fetch(request: Request) {
31
31
  const url = new URL(request.url);
32
32
  const step = url.searchParams.get("step");
@@ -53,5 +53,11 @@ export default {
53
53
  return Response.json({ run: runId });
54
54
  },
55
55
  };
56
- `);const g=await ln(l),{args:v,command:m}=z(F(n),d.dev({configPath:t===void 0?void 0:L(n,t),environment:i,extraArgs:[L(n,u),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(g),"--persist-to",L(n,p(s,"state"))]}));return{args:v,command:m,port:g,runId:f}}catch(u){throw new C(`could not prepare the check (${u instanceof Error?u.message:String(u)})`,!0)}},zo=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=M(t),c=p(t,a,"_generated","functions.ts"),l=b(c)&&E(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Po(t,a);if(!l&&u.length===0)return;const f=[...u,...Do(t,a,u)],h=Lo(e);if("skip"in h){s.warn(`smoke-load skipped: ${h.skip}, so lazy modules and import()ed integration modules are not evaluated before deploy`);return}const{base:g,configFile:v}=h,m=Eo(t,r??Pr(t,n,e.configPath).main,a),S=[];let D,R;const q=Date.now()+be,T=process.platform!=="win32",tt=(U,Q,Z)=>{const B=sn(U,[...Q],{cwd:Z.cwd,detached:T,shell:Z.shell,stdio:["ignore","pipe","pipe"]});return T&&B.pid!==void 0&&(R={dispose:Uo(B.pid),pid:B.pid}),B};try{D=Go(t),s.info(d===void 0?"smoke-loading import()ed integration modules in workerd":"smoke-loading lazy function modules in workerd");let U=Ao;for(let Q=0;Q<er;Q+=1){const{args:Z,command:B,port:ge,runId:nt}=await Ko({base:g,configPath:v,cwd:t,deferred:f,directory:D,environment:n,functionsFile:d,integrationModules:m,preferred:U,toolchain:i}),Be=new AbortController;U=ge+1;const We=await Bo({args:Z,command:B,cwd:t,spawn:o??tt,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:G=>{S.push(G),xo.test(G)&&Be.abort()},port:ge,readyTimeoutMs:Math.max(0,q-Date.now()),shell:process.platform==="win32"});if(We===void 0){await me(R),R=void 0;continue}try{const G=await Fo({deadline:q,deferred:f,functions:d!==void 0,integrationModules:m,output:S,port:ge,runId:nt,startupFailed:Be.signal});if(G!==void 0){Ho(t,G,s);return}}finally{await We.stop(),await me(R),R=void 0}}throw new C(`the smoke port was answered by other runs on all ${String(er)} attempts`,!0)}catch(U){return qo(U,S,s)}finally{if(await me(R),D!==void 0)try{oe(D,{force:!0,recursive:!0})}catch{}}},Jo=(e,r)=>r===void 0?e:I(e,r),Yo=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??fn)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??H,t=[];for(const n of e.targets){const o=un(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=je(F(e.cwd),"wrangler",["containers","push",o]),a={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(a);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},Xo=new Set(["0.0.0.0","[::1]","[::]","localhost"]),Qo=[".local",".localhost"],Zo=["[fc","[fd"],es=/^\[fe[89ab][0-9a-f]:/u,rs=/^[a-z]+:\/\//u,sr=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},ir="[::ffff:",ts=e=>{if(!e.startsWith(ir)||!e.endsWith("]"))return;const r=e.slice(ir.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},jr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},ns=e=>{const r=e.toLowerCase(),t=ts(r);return t!==void 0?sr(t):Xo.has(r)||Qo.some(n=>r.endsWith(n))||Zo.some(n=>r.startsWith(n))||es.test(r)||sr(r)},Or=e=>{const r=O(e);return r===void 0?void 0:P(r).parsed},Dr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},ie=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},os=e=>{const r=e.replace(rs,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ie(r.slice(t),"*");return o==="/"?n:`${n}${o}`},ar=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[os(n)]:[]}),ss=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),i=o.startsWith("*");if(!(!(i?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${ie(r,"/")}/`.startsWith(s)))return s.length*1e6+(i?0:5e5)+o.length},is=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Nr=(e,r)=>{const t=ar(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const i=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:is(i)?ar(i):t}});return[{id:"top",label:"production",routes:t},...o]},as=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Nr(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=ss(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const i=Math.max(...s.map(c=>c.score)),a=s.filter(c=>c.score===i);return a.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:a[0]?.block.label??"production"}},ne=e=>Gt(`${e.origin}${e.pathname}`),cs=(e,r,t,n,o)=>{const s=_e(e),i=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(i===void 0)return;if(s?.env===r)return ne(i)===ne(t)?null:`${n}: this checkout is linked to ${ne(i)}${o}`;const a=`${ie(i.pathname,"/")}/`;if(i.origin!==t.origin||!`${ie(t.pathname,"/")}/`.startsWith(a))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},Lr=(e,r,t,n,o,s)=>{const i=as(e,r,t,n);if(i.kind==="other")return`${o}: wrangler routes it to ${i.label}, not this deploy${s}`;if(i.kind==="own")return;const a=Nr(e,r);if(a.every(l=>l.routes.length===0))return;const c=a.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},ds=(e,r,t,n,o,s)=>{const i=Or(e);if(t.endsWith(".workers.dev")){const a=Dr(i,r);return a!==void 0&&t.split(".")[0]!==a?`${o}: this deploy ships the Worker "${a}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return Lr(i,r,t,n,o,s)},ls=(e,r,t,n,o)=>{const s=Or(e),i=jr(t.hostname);if(i.endsWith(".workers.dev")){const a=Dr(s,r);return a===void 0||i.split(".")[0]===a?void 0:`${n}: this deploy ships the Worker "${a}", not the one the link names${o}`}return Lr(s,r,i,t.pathname,n,o)},us=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${ne(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,i=jr(n.hostname);if(ns(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=cs(e,r,n,o,s);return a===void 0?ds(e,r,i,n.pathname,o,s):a??ls(e,r,n,o,s)},xr=e=>{const t=[O(e),p(e,"package.json"),p(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,E(n,"utf8")]);return()=>{for(const[n,o]of t)E(n,"utf8")!==o&&X(n,o,"utf8")}},fs=(e,r=$r())=>I(e,".lunora",`vite-bundle-meta-${r}.json`),Mr="LUNORA_CLIENT_BUILD",gs="virtual:lunora/worker",Ae=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(p(e,`${r}.config.${t}`))),Fr=e=>Ae(e,"rsbuild")?"rsbuild":Ae(e,"vite")?"vite":void 0,hs=e=>Ae(e,"vite")?"vite":Fr(e),ms=e=>{try{const{scripts:r}=JSON.parse(E(p(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},ue=(e,r)=>{if(process.env[Mr]==="1")return;const t=O(e),n=t===void 0?void 0:P(t).parsed,o=n?.main===gs,s=(o?hs(e):Fr(e))??(ms(e)?"script":void 0);if(s===void 0)return;const i=r===void 0?void 0:n?.env?.[r]?.assets?.directory,a=n?.assets?.directory??i;return o||ft(e).class!=="C"||a!==void 0?s:void 0},ps=async(e,r,t)=>{const n=t.spawner??H,o=F(e),s=r==="script"?{args:["run","build"],command:o}:je(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const i=xr(e),a=t.bundleMetaPath??fs(e);oe(p(e,gt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[yt]:wt(e),[vt]:t.target,[pt]:a,...t.lazyFunctions?{[mt]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[ht]:"0"}:{},[Mr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{i(),t.bundleMetaPath===void 0&&oe(a,{force:!0})}},fe=(e,r,t)=>r!==!1&&ue(e,t)!==void 0,vs=(e,r,t)=>fe(e,r,t)&&ue(e,t)!=="script",Le=e=>{const r=e.frameworkBuild===!1?void 0:ue(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{we(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=we(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},Ur=async e=>{const r=e.frameworkBuild===!1?void 0:ue(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??we(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return ps(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},cr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,xe=(e,r)=>{const t=O(e);if(!t)return;const{parsed:n}=P(t);if(n===void 0)return;const{error:o,merged:s}=le(n,r),i=o===void 0?s:n,{containers:a,d1_databases:c,vars:l}=i;return{containers:cr(a),d1_databases:cr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},ys=/^127(?:\.\d{1,3}){3}$/,ws=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||ys.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},ks=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),bs=(e,r,t,n="deploy",o)=>{const s=(xe(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&ks(a.image));if(s.length===0||t())return;const i=`${n} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Me=e=>b(A(e,He))?He:void 0,$s=(e,r,t="deploy",n)=>{for(const o of mr(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,a=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!b(A(e,c.path)));if(a!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${a.path}" that does not exist. Create it or fix the \`${a.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(s?.kind==="build"&&!b(A(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},Ss=(e,r)=>r==="celld"?typeof e=="string"&&e!==qe&&Xt(e):r==="cloudflare"&&e===qe,Es=(e,r,t)=>(xe(e,t)?.d1_databases??[]).find(n=>Ss(n.database_id,r)),As=e=>{if(!e.migrate||e.dryRun)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},Rs=(e,r,t,n,o)=>{const s=Es(e,n,o);if(s===void 0)return;const i=`${t} blocked: the "${s.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${s.database_id??""}")`,a=n==="celld"?`${i}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${i}. Run \`lunora doctor --fix\` to create the database and write its id into wrangler.jsonc, or run \`wrangler d1 create <name>\` and paste the id in yourself.`;return r.error(a),a},Ts=(e,r,t="deploy",n)=>{const o=xe(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&ws(a)).map(([a])=>a).toSorted((a,c)=>a.localeCompare(c));if(s.length===0)return;const i=`${t} blocked: ${s.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},_s=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...at],Br=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,Wr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Hr="allowUnauthenticatedShardAccess",Cs=/[\\/]/u,qr=new Set(["_generated","build","dist","node_modules"]),Gr=(e,r)=>{const t=J(e,r).split(Cs);return Br.test(r)&&!Wr.test(r)&&!ye(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!qr.has(n))},dr=(e,r,t)=>{const{parsed:n}=P(r);if(n===void 0)return[];const{error:o,merged:s}=le(n,t),{main:i}=o===void 0?s:n,a=typeof i=="string"?A(Rr(r),i):void 0;return a!==void 0&&b(a)&&Gr(e,a)?[a]:[]},Fe=e=>e===void 0?!1:e.getKind()===y.FalseKeyword?!0:$.isParenthesizedExpression(e)||$.isAsExpression(e)||$.isSatisfiesExpression(e)||$.isTypeAssertion(e)||$.isNonNullExpression(e)?Fe(e.getExpression()):!1,Is=e=>{try{return Re(e).isFile()}catch{return!1}},Ps=new Set(["ELOOP","ENOENT","ENOTDIR"]),ae=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Ps.has(n)||t.push(e)},js=(e,r)=>{try{return Re(e)}catch(t){ae(e,t,r);return}},Vr=(e,r)=>{try{return E(e,"utf8")}catch(t){ae(e,t,r);return}},Kr=(e,r,t,n=new Set)=>{let o;try{o=st(r)}catch(i){return ae(r,i,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=K(r)}catch(i){return ae(r,i,t),[]}return s.flatMap(i=>{const a=A(r,i),c=js(a,t);if(c===void 0)return[];const l=J(e,a).split(x).join("/");return c.isDirectory()?qr.has(i)||i.startsWith(".")||ye(`${l}/`)?[]:Kr(e,a,t,n):c.isFile()&&Br.test(i)&&!Wr.test(i)&&!ye(l)?[a]:[]})},Os=e=>{const r=$.isComputedPropertyName(e)?e.getExpression():e;return $.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Ds=/\.(?:[cm]?js|jsx)$/u,Ns=(e,r)=>{if(!r.startsWith("."))return;const t=I(Rr(e),r),n=t.replace(Ds,"");return[t,...pe.map(s=>`${t}${s}`),...pe.map(s=>A(t,`index${s}`)),...pe.map(s=>`${n}${s}`)].find(s=>Is(s))},Ls=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},xs=e=>{const r=e.getModuleReference();if(!$.isExternalModuleReference(r))return;const t=r.getExpression();return $.isStringLiteral(t)?t.getLiteralValue():void 0},Ms=(e,r,t,n)=>{const o=new Set(e),s=[...e],i=[];for(let a=0;a<s.length;a+=1){const c=s[a]??"",l=Vr(c,n);if(l===void 0)continue;const d=r.createSourceFile(J(t,c),l,{overwrite:!0}),u=[...d.getImportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getExportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getDescendantsOfKind(y.ImportEqualsDeclaration).map(f=>xs(f)),...d.getDescendantsOfKind(y.CallExpression).map(f=>Ls(f))].filter(f=>f!==void 0);for(const f of u){const h=Ns(c,f);h!==void 0&&Gr(t,h)&&!o.has(h)&&(o.add(h),i.push(h),s.push(h))}}return i},Fs=e=>{const r=e.getArgumentExpression();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Us=e=>$.isPropertyAccessExpression(e)?e.getName():$.isElementAccessExpression(e)?Fs(e):void 0,Bs=new Set([y.AmpersandAmpersandEqualsToken,y.AmpersandEqualsToken,y.AsteriskAsteriskEqualsToken,y.AsteriskEqualsToken,y.BarBarEqualsToken,y.BarEqualsToken,y.CaretEqualsToken,y.EqualsToken,y.GreaterThanGreaterThanEqualsToken,y.GreaterThanGreaterThanGreaterThanEqualsToken,y.LessThanLessThanEqualsToken,y.MinusEqualsToken,y.PercentEqualsToken,y.PlusEqualsToken,y.QuestionQuestionEqualsToken,y.SlashEqualsToken]),Ws=e=>{const r=e.getOperatorToken().getKind();return!Bs.has(r)||Us(e.getLeft())!==Hr?!1:r!==y.EqualsToken||!Fe(e.getRight())},Hs=(e,r,t)=>{const n=[],o=[...new Set([M(e),"src"])].filter(u=>b(A(e,u))),s=O(e),i=[..._s.map(u=>A(e,u)).filter(u=>b(u)),...s===void 0?[]:dr(e,s,r),...t.flatMap(u=>dr(e,u,r))],a=new Ar({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>Kr(A(e,u),A(e,u),n));return{sites:[...new Set([...c,...i,...Ms([...i,...c],a,e,n)])].flatMap(u=>{const f=Vr(u,n);if(f===void 0)return[];const h=a.createSourceFile(J(e,u),f,{overwrite:!0}),g=[...h.getDescendantsOfKind(y.PropertyAssignment),...h.getDescendantsOfKind(y.ShorthandPropertyAssignment),...h.getDescendantsOfKind(y.GetAccessor),...h.getDescendantsOfKind(y.MethodDeclaration)].filter(m=>{const S=$.isPropertyAssignment(m)&&Fe(m.getInitializer());return Os(m.getNameNode())===Hr&&!S}).map(m=>m.getStartLineNumber()),v=h.getDescendantsOfKind(y.BinaryExpression).filter(m=>Ws(m)).map(m=>m.getStartLineNumber());return[...g,...v].map(m=>({file:J(e,u),line:m}))}),unreadable:n}},qs=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=Hs(e,o,s),c=kn({openShardAccess:i,schema:{tables:[]}},{lints:[Ge]});if(c.length===0&&a.length===0)return;const l=[];if(c.length>0){const u=c.map(f=>`${String(f.metadata.file)}:${String(f.metadata.line)}`).join(", ");l.push(`${u} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(a.length>0&&l.push(`could not read ${a.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${Ge.remediation}`;return r.error(d),d},Gs=(e,r,t,n)=>{const o=qs(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:w.USAGE,error:o}},Vs=(e,r,t,n)=>{const o=Rs(e,r.logger,t,n,r.env);if(o!==void 0)return{code:w.USAGE,error:o};const s=Ts(e,r.logger,t,r.env);if(s!==void 0)return{code:w.USAGE,error:s};const i=$s(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:w.USAGE,error:i};const a=bs(e,r.logger,r.dockerAvailable??gn,t,r.env);return a===void 0?void 0:{code:w.MISSING_DEPENDENCY,error:a}},Ks=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,zs=/https:\/\/[^\s"'<>]+/u,Js=e=>{if(e===void 0)return;const r=Ks.exec(e);return r?r[0]:zs.exec(e)?.[0]},lr=e=>e===void 0?"":` (--env ${e})`,Ys=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=_e(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${lr(s.env)}, but this deploy published ${o}${lr(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(n??(()=>new Date().toISOString()))();kt(e,{env:r,linkedAt:i,workerName:Pe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Xs=async(e,r)=>{const t=new Ar({skipAddingFilesFromTsConfig:!0}),n=A(r,"lunora");let o;try{o=ct(t,n)}catch(s){const i=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},a=await bn(i);if(a.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),a.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},Qs=async(e,r)=>{const{info:t}=Ce(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=Qt(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:a.index,property:a.property,type:c})}if(o.length===0)return;const i=(await Zt({cwd:r,entries:o,exec:je(F(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??H})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},ur=5,Zs=2e3,ei=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Oe({cwd:r,env:e.env});if(n===void 0){const s="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(s),{error:s,ok:!1,url:""}}const o=await hn({attempts:ur,baseUrl:n,delayMs:Zs,fetchImpl:e.healthFetch,paths:[mn,pn],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(ur)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},ri=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await Qs(e,r);const i=e.migrate?await Xs(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},ti=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:i,validation:a})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:Js(i),workerName:Pe(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:a};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),Ys({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await ei(n,e,c.url);if(l?.error!==void 0)return{code:w.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a};const d=n.isolatedPreview===!0?void 0:o;return{...await ri(n,e,r,a,d,t),deployment:c,healthCheck:l}},ni=(e,r,t)=>{const n=A(e,N);if(!b(n))return;let o;try{o=pr(E(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${N} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${N} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},zr=async(e,r)=>{let t=[];try{t=bt(await vr({cache:r,projectRoot:e,schemaDir:M(e)}))}catch{}const n=[...new Set($t(t).map(s=>s.key))];let o=[];try{const s=A(e,N);b(s)&&(o=pr(E(s,"utf8")).map(i=>i.key).filter(i=>br(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:St(t)}},oi=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??H,i=F(e),a=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=t.map(f=>({key:f,value:Et()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const f=z(i,d({environment:r.env,temporary:r.temporary})),h=await s({args:f.args,command:f.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(g=>[g.key,g.value])))});if(h.code===0){for(const{key:g}of l)o.success(`generated + pushed ${g}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(h.code)}); retrying one key at a time`)}const u=[];for(const{key:f,value:h}of l){const g=c({environment:r.env,key:f,temporary:r.temporary}),v=z(i,g),m=await s({args:v.args,command:v.command,cwd:e,input:h});if(m.code!==0)return o.error(`failed to push secret ${f} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${f}${a}\`.`),{minted:u,ok:!1};u.push({key:f,value:h}),o.success(`generated + pushed ${f}`)}return{minted:u,ok:!0}},si=/^[\w-]+$/u,fr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],ii=(e,r)=>{try{const t=_t(e,fr);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${fr.join("` and `")}\` by hand before committing.`)}},ai=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!si.test(r.env)){r.logger.warn(`${n}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?N:`${N}.${r.env}`;ii(e,r.logger);const s=A(e,o);let i=b(s)?E(s,"utf8"):"";for(const a of t)i=At(i,a.key,a.value);return Rt(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${N} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},ci=/^<[^>]+>$/u,di=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const u=n[d];if(typeof u!="string")return!0;const f=u.trim();return f===""||ci.test(f)?!0:br(d)&&Tt(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await zr(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${N} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const l=a.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},li=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return di(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Sn)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const a=new Set(i.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await zr(e,r.discoveryCache),u=[...l,...c].filter(g=>!a.has(g));if(u.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${u.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const g of u.filter(v=>!d.has(v)))o.warn(`required secret ${g} is not set on the target — set it with: wrangler secret put ${g}${s}`);const f=u.filter(g=>d.has(g));if(f.length===0)return{};if(await(r.secretConfirm??$n())(`${String(f.length)} required secret(s) not set on the target (${f.join(", ")}). Generate strong values and push them now?`)){const{minted:g,ok:v}=await oi(e,r,f,n),m=ai(e,r,g);return v?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return o.warn(`${String(f.length)} required secret(s) not set on the target: ${f.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${s}\`.`),{}},Jr=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,ui=async(e,r)=>{if(r.dryRun===!0)return;const t=mr(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await Yo({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},fi=(e,r,t)=>{if(t!==void 0)try{const n=Bt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Wt(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},gi=async(e,r,t,n,o,s)=>{try{de(n);const i=await vr({cache:s,projectRoot:e,schemaDir:M(e)}),a=Ft(e,i,{environment:o,target:n}),c=a.wranglerPath??"wrangler.jsonc";if(a.added.length>0&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${c}`),a.updated.length>0&&r.success(`updated bindings: ${a.updated.join(", ")} → ${c}`),a.devConfig!==void 0){const{added:l,path:d,updated:u}=a.devConfig;r.success(`dev sidecar bindings: ${[...l,...u].join(", ")} → ${d}`)}for(const l of a.warnings)r.warn(l)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=Ut(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}fi(e,r,t)},hi=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new Ht({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=dt({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Mt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=zt(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:h,names:g,shouldBlock:v}=Jt(u.advisories,c);if(v){const S=`${h.length.toString()} ERROR-level ${h.length===1?"advisory":"advisories"} (${g.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(S),{error:S}}const m=l?await Ot({cwd:e,logger:t,spawner:i,stdoutToStderr:a}):void 0;return m?.error!==void 0?{error:m.error}:{result:u}}catch(u){d?.failed("codegen failed");const f=u instanceof Error?u.message:String(u);return t.error(`codegen failed: ${f}`),{error:`codegen failed: ${f}`}}},gr="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",mi=(e,r)=>({dryRun:r.dryRun,entry:Me(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,outFile:r.outFile,preview:r.preview,temporary:r.temporary}),Yr=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=mi(e,r);return yr(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},pi=(e,r,t)=>{const n=Yr(e,r,t),o=Me(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},_={problems:[],wranglerPath:void 0},ve=(e,r)=>({code:w.USAGE,descriptor:void 0,error:e,validation:_,...r}),vi=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},yi=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=pi(e,r,t),i=z(F(e),s);return{args:i.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:i.command,cwd:e,stdoutToStderr:n&&!o}},Ue=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},wi=(e,r)=>Ue(r)===void 0?Te(e).services.map(t=>t.wranglerPath):[],Xr=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:ce(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:Ie(r),target:t.id}),ki=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:Ue(r);if(o!==void 0||n===void 0){const s=e.map(i=>i.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},Qr=(e,r)=>{for(const t of e){const n=Le(r(j(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},bi=(e,r,t)=>{const{error:n,services:o}=Te(e);if(n!==void 0||o.length===0)return;const s=de(t);if(s.toolchain===void 0||Ue(r)!==void 0)return;const i=r.skipCodegen===!0?!1:r.frameworkBuild,a=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return Qr(a,c=>Xr(c,r,s,i,H))},Zr=(e,r,t)=>{const n=e.cwd??process.cwd(),o=on(n,e.target);if(o.target===void 0){const a=o.error??"unknown deploy target";return e.logger.error(a),{kind:"refused",error:a,validation:_}}if(e.preview===!0)return e.logger.error(gr),{kind:"refused",code:w.USAGE,error:gr,validation:_};try{Yr(n,e,de(o.target))}catch(a){if(!(t&&a instanceof Ct&&fe(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=a instanceof Error?a.message:String(a);return e.logger.error(c),{kind:"refused",error:c,validation:_}}}const s=e.openShardGatePassed===!0?void 0:Gs(n,e,r,wi(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:_};const i=bi(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:w.USAGE,error:i,validation:_}):{kind:"ok",target:o.target}},$i=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Dt(r):void 0),Si=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??jt)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},et=(e,r)=>{const t=Oe({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:us(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Vt(t,r.logger,e),s=o===void 0?void 0:qt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??Kt,token:s}}},Ei=(e,r,t)=>async n=>{const o=et(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:wn({changes:n,tables:t.schemaTables,target:o.target})},Ai=(e,r)=>async t=>{const n=et(e,r);return"reason"in n?n.reason:yn({changes:t,now:Date.now(),target:n.target})},Ri=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Ei(r,t,n),countExpiringRows:Ai(r,t)}:{},Ti=async(e,r)=>{const t=e.cwd??process.cwd(),n=Jr(e),o=Ie(e),s={problems:[],wranglerPath:void 0},i=Zr(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await Si(e,a,r);if(c!==void 0)return e.logger.error(c),{code:w.MISSING_DEPENDENCY,error:c,target:a,validation:s};let l;if(!e.skipCodegen){const v=await hi(t,n,e.logger,$i(e,t),ce(e.lazyFunctions),a,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(v.error!==void 0)return{error:v.error,target:a,validation:_};l=v.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const v=await vn({allowDrift:e.allowSchemaDrift===!0,...Ri(r,t,e,l),codegen:l,command:r,logger:e.logger});if(v.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:v.reason},target:a,validation:s};d=v.rebless}const u=l&&In({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await gi(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache);const f=await Cr(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:_};const h=Vs(t,e,r,a);if(h!==void 0)return{code:h.code,error:h.error,target:a,validation:_};const g=xt({environment:e.env,projectRoot:t});return vi(g,e.logger)?{error:"wrangler validation failed",target:a,validation:g}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:g}},_i=e=>{oe(p(e,".wrangler","deploy","config.json"),{force:!0})},Ci=async(e,r,t)=>{const n=Le(e);if(n!==void 0)return{built:!1,error:n};const o=fe(e.cwd,r,t);return o&&_i(e.cwd),{built:o,error:await Ur(e)}},Ii=(e,r,t)=>r||t===!1?De(e):void 0,Pi=async(e,r,t,n)=>{const{error:o,services:s}=Te(e);if(o!==void 0)return{code:w.FAILURE,error:o};if(s.length===0)return;const i=ki(s,r,t);if(i===void 0)return;const a=F(e),c=[...new Map(s.map(f=>[f.wranglerPath,f])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=f=>Xr(f,r,t,l,n),u=Qr(c,d);if(u!==void 0)return r.logger.error(u),{code:w.USAGE,error:u};for(const f of c){const h=j(f.wranglerPath),g=d(h),{built:v,error:m}=await Ci(g,l,r.env);if(m!==void 0){const T=`service ${f.name} (${f.worker}): ${m}`;return r.logger.error(T),{code:w.FAILURE,error:T}}const S=Ii(f.wranglerPath,v,l);let D;try{D=yr(t,h,"deploy",T=>i.deploy({configPath:T??S??f.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(T){return{code:w.FAILURE,error:`service ${f.name} (${f.worker}): ${T instanceof Error?T.message:String(T)}`}}D.commit();const R=z(a,D.command);r.logger.info(`deploying service ${f.name} (${f.worker}) via ${R.command} ${R.args.join(" ")}`);const q=await n({args:R.args,command:R.command,cwd:h,stdoutToStderr:r.format==="json"});if(q.code!==0)return{code:w.FAILURE,error:`service ${f.name} (${f.worker}): ${R.command} ${R.args.join(" ")} exited ${String(q.code)} — stopping before the app`}}},ji=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:P(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await rn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Oi=e=>e.dryRun!==!0&&e.temporary!==!0,Di=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",Ni=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},Li=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=Ni(o);r.error(s),n.push(s)}return n},rt=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const c=(le(a,n).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),l=c.length===0?void 0:Ce(e,M(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(g=>[g.namespace,g])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(g=>`"${g.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(n===void 0?void 0:a.env?.[n]?.account_id)??a.account_id,f=await Promise.all(d.map(async g=>en({...g,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),h=Li(f,o,i);return h.length===0?void 0:h.join(`
57
- `)},xi=async(e,r,t,n,o,s)=>{const i=Oi(r)?await rt(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(i!==void 0)return{code:w.FAILURE,error:i};const a=await Cr(e,r,"deploy",o);return a!==void 0?{code:w.FAILURE,error:a}:Pi(e,r,t,n)},Mi=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return zo({composedEntry:Me(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},Fi=async e=>{const r={...e,discoveryCache:e.discoveryCache??Pt()},t=r.cwd??process.cwd(),n=Jr(r),o=await Ti(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:w.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const m=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ve(o.error,{...m,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,i=de(o.target),a=As(r)??await rt(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Di(r))??await Mi(t,r,i,s.wranglerPath);if(a!==void 0)return ve(a);const c=i.toolchain?.prebuildsContainerImages===!0?await ui(t,r):void 0;if(c!==void 0)return ve(c);ni(t,r.logger,i),Lt(t,m=>{r.logger.warn(m)}),await ji(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await li(t,r,n,i);if(l!==void 0)return r.logger.error(l),{code:w.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const u=r.spawner??H,f=await xi(t,r,i,u,o.target,s.wranglerPath);if(f!==void 0)return{code:f.code,descriptor:void 0,error:f.error,mintedSecretsFile:d,validation:s};const h=yi(t,r,i);r.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const g=await u(h);return h.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:h,mintedSecretsFile:d,validation:s}:{...await ti({...o,cwd:t,descriptor:h,mintedSecretsFile:d,options:r,stdout:g.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Ui=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:Ie(e),lazyFunctions:ce(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Le(n);if(o!==void 0)return r.error(o),{code:w.USAGE,descriptor:void 0,error:o,validation:_};It(t);const s=await Ur(n);if(s!==void 0)return r.error(s),{code:w.FAILURE,descriptor:void 0,error:s,validation:_}},Bi=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return fe(e,t,r.env)?r.env:void 0},Wi=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=Zr(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??w.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await Ui(e);if(o!==void 0)return o;const s=e.dryRun===!0?xr(t):void 0;let i;try{if(i=await Fi({...e,clientBuildEnvironment:Bi(t,e),clientBuildRan:vs(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=tn({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});a!==void 0&&(r.error(a),i={...i,code:w.USAGE})}}finally{s?.()}return e.format==="json"||i.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&Pn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},Ea=nn(async({cwd:e,format:r,logger:t,options:n})=>{const o=Jo(e,n.root),s=await Wi({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:Yt(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:ce(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Oe({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{Ti as a,gi as b,Mn as c,xr as d,zr as e,Ea as f,Jo as p,Wi as r,Mi as s,fs as v};
56
+
57
+ ${m?`export default class extends WorkerEntrypoint {
58
+ fetch(request: Request) {
59
+ return smokeProbe.fetch(request);
60
+ }
61
+ }`:"export default smokeProbe;"}
62
+ `);const p=await vn(d),{args:R,command:H}=K(x(n),u.dev({configPath:t===void 0?void 0:O(n,t),environment:i,extraArgs:[O(n,f),"--local","--local-protocol","http","--ip","127.0.0.1","--port",String(p),"--persist-to",O(n,v(s,"state")),...l?["--assets",O(n,v(s,"assets"))]:[]]}));return{args:R,command:H,port:p,runId:g}}catch(f){throw new _(`could not prepare the check (${f instanceof Error?f.message:String(f)})`,!0)}},os=async e=>{const{composedEntry:r,cwd:t,environment:n,launcher:o,logger:s,toolchain:i}=e,a=L(t),c=v(t,a,"_generated","functions.ts"),l=b(c)&&S(c,"utf8").includes("export const loadAllFunctions"),d=l?c:void 0,u=Fo(t,a),f=[...u,...Bo(t,a,u)],g=Po(t,r??Dr(t,n,e.configPath).main,a);if(!l&&f.length===0&&g.length===0)return;const h=Wo(e);if("skip"in h){s.warn(`smoke-load skipped: ${h.skip}, so the modules the Worker loads on demand are not evaluated before deploy`);return}const{base:m,configFile:p,missingAssets:R}=h,H=[];let P,F;const He=Date.now()+be,ct=process.platform!=="win32",dt=(M,X,Q)=>{const U=Ar(M,[...X],{cwd:Q.cwd,detached:ct,shell:Q.shell,stdio:["ignore","pipe","pipe"]});return U.pid!==void 0&&(F={dispose:Ko(U.pid),pid:U.pid}),U};try{P=rs(t),s.info(`smoke-loading ${Jo(d!==void 0,f.length,g.length)} in workerd`);let M=jo;for(let X=0;X<nr;X+=1){const{args:Q,command:U,port:he,runId:lt}=await ns({base:m,configPath:p,cwd:t,deferred:f,directory:P,environment:n,functionsFile:d,integrationModules:g,missingAssets:R,preferred:M,toolchain:i}),qe=new AbortController;M=he+1;const Ge=await Xo({args:Q,command:U,cwd:t,spawn:o??dt,label:"wrangler dev (smoke-load)",notFound:"`wrangler` was not found",onLine:q=>{H.push(q),Ho.test(q)&&qe.abort()},port:he,readyTimeoutMs:Math.max(0,He-Date.now()),shell:process.platform==="win32"});if(Ge===void 0){await se(F),F=void 0;continue}try{const q=await Vo({deadline:He,deferred:f,functions:d!==void 0,integrationModules:g,output:H,port:he,runId:lt,startupFailed:qe.signal});if(q!==void 0){Zo(t,q,s);return}}finally{await Yo(Ge,F),F=void 0}}throw new _(`the smoke port was answered by other runs on all ${String(nr)} attempts`,!0)}catch(M){return es(M,H,s)}finally{if(await se(F),P!==void 0)try{ne(P,{force:!0,recursive:!0})}catch{}}},ss=(e,r)=>r===void 0?e:C(e,r),is=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??wn)()){const n="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(n),{builtTags:[],code:1,error:n}}const r=e.spawner??W,t=[];for(const n of e.targets){const o=yn(n.exportName),s={args:["build",n.buildDir,"--name",o],command:"railpack",cwd:e.cwd},i=je(x(e.cwd),"wrangler",["containers","push",o]),a={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${n.exportName}" → ${o} from ${n.buildDir}`);const c=await r(s);if(c.code!==0){const d=`railpack build failed for container "${n.exportName}" (${n.buildDir})`;return e.logger.error(d),{builtTags:t,code:c.code,error:d}}e.logger.info(`railpack: pushing ${o} to the Cloudflare Registry`);const l=await r(a);if(l.code!==0){const d=`wrangler containers push failed for "${n.exportName}" (${o})`;return e.logger.error(d),{builtTags:t,code:l.code,error:d}}t.push(o)}return{builtTags:t,code:0}},as=new Set(["0.0.0.0","[::1]","[::]","localhost"]),cs=[".local",".localhost"],ds=["[fc","[fd"],ls=/^\[fe[89ab][0-9a-f]:/u,us=/^[a-z]+:\/\//u,dr=e=>{const r=e.split(".").map(Number);if(r.length!==4||r.some(o=>!Number.isInteger(o)))return!1;const[t=-1,n=-1]=r;return t===0||t===127||t===100&&n>=64&&n<=127||t===198&&(n===18||n===19)||t===10||t===192&&n===168||t===172&&n>=16&&n<=31||t===169&&n===254},lr="[::ffff:",fs=e=>{if(!e.startsWith(lr)||!e.endsWith("]"))return;const r=e.slice(lr.length,-1);if(r.includes("."))return r;const[t=0,n=0]=r.split(":").map(o=>Number.parseInt(o,16));return[Math.floor(t/256),t%256,Math.floor(n/256),n%256].join(".")},xr=e=>{let r=e.length;for(;r>0&&e[r-1]===".";)r-=1;return e.slice(0,r).toLowerCase()},gs=e=>{const r=e.toLowerCase(),t=fs(r);return t!==void 0?dr(t):as.has(r)||cs.some(n=>r.endsWith(n))||ds.some(n=>r.startsWith(n))||ls.test(r)||dr(r)},Fr=e=>{const r=j(e);return r===void 0?void 0:I(r).parsed},Mr=(e,r)=>{const t=typeof e?.name=="string"&&e.name!==""?e.name:void 0;if(r===void 0)return t;const n=e?.env?.[r]?.name;return typeof n=="string"&&n!==""?n:t===void 0?void 0:`${t}-${r}`},ie=(e,r)=>{let t=e.length;for(;t>0&&e[t-1]===r;)t-=1;return e.slice(0,t)},hs=e=>{const r=e.replace(us,""),t=r.indexOf("/"),n=(t===-1?r:r.slice(0,t)).toLowerCase(),o=t===-1?"":ie(r.slice(t),"*");return o==="/"?n:`${n}${o}`},ur=e=>[e?.route,...Array.isArray(e?.routes)?e.routes:[]].flatMap(t=>{const n=typeof t=="string"?t:t?.pattern;return typeof n=="string"&&n!==""?[hs(n)]:[]}),ms=(e,r,t)=>{const n=t.indexOf("/"),o=n===-1?t:t.slice(0,n),s=n===-1?"":t.slice(n),i=o.startsWith("*");if(!(!(i?e.endsWith(o.slice(1)):e===o)||s!==""&&!`${ie(r,"/")}/`.startsWith(s)))return s.length*1e6+(i?0:5e5)+o.length},ps=e=>e!==void 0&&(Object.hasOwn(e,"route")||Object.hasOwn(e,"routes")),Ur=(e,r)=>{const t=ur(e),o=[...new Set([...Object.keys(e?.env??{}),...r===void 0?[]:[r]])].map(s=>{const i=e?.env?.[s];return{id:`env:${s}`,label:`--env ${s}`,routes:ps(i)?ur(i):t}});return[{id:"top",label:"production",routes:t},...o]},vs=(e,r,t,n)=>{const o=r===void 0?"top":`env:${r}`,s=Ur(e,r).flatMap(c=>c.routes.flatMap(l=>{const d=ms(t,n,l);return d===void 0?[]:[{block:c,score:d}]}));if(s.length===0)return{kind:"none"};const i=Math.max(...s.map(c=>c.score)),a=s.filter(c=>c.score===i);return a.some(c=>c.block.id===o)?{kind:"own"}:{kind:"other",label:a[0]?.block.label??"production"}},te=e=>Qt(`${e.origin}${e.pathname}`),ys=(e,r,t,n,o)=>{const s=Ce(e),i=s?.workerUrl!==void 0&&URL.canParse(s.workerUrl)?new URL(s.workerUrl):void 0;if(i===void 0)return;if(s?.env===r)return te(i)===te(t)?null:`${n}: this checkout is linked to ${te(i)}${o}`;const a=`${ie(i.pathname,"/")}/`;if(i.origin!==t.origin||!`${ie(t.pathname,"/")}/`.startsWith(a))return;const c=s?.env===void 0?"production":`--env ${s.env}`;return`${n}: this checkout links it to ${c}, not this deploy${o}`},Br=(e,r,t,n,o,s)=>{const i=vs(e,r,t,n);if(i.kind==="other")return`${o}: wrangler routes it to ${i.label}, not this deploy${s}`;if(i.kind==="own")return;const a=Ur(e,r);if(a.every(l=>l.routes.length===0))return;const c=a.find(l=>l.id===(r===void 0?"top":`env:${r}`))?.routes??[];return`${o}: this deploy${s} routes to ${c.length===0?"no declared route":c.join(", ")}, not ${t}`},ws=(e,r,t,n,o,s)=>{const i=Fr(e);if(t.endsWith(".workers.dev")){const a=Mr(i,r);return a!==void 0&&t.split(".")[0]!==a?`${o}: this deploy ships the Worker "${a}"${s}`:`${o}: no link ties this *.workers.dev host to your account${s}; run \`lunora link --url https://${t}${r===void 0?"":` --env ${r}`}\` once the Worker is deployed, then deploy again (or confirm the drift yourself with --allow-schema-drift)`}return Br(i,r,t,n,o,s)},ks=(e,r,t,n,o)=>{const s=Fr(e),i=xr(t.hostname);if(i.endsWith(".workers.dev")){const a=Mr(s,r);return a===void 0||i.split(".")[0]===a?void 0:`${n}: this deploy ships the Worker "${a}", not the one the link names${o}`}return Br(s,r,i,t.pathname,n,o)},bs=(e,r,t)=>{let n;try{n=new URL(t)}catch{return`refused ${t} as the deployment to read rows from: it is not a URL`}const o=`refused ${te(n)} as the deployment to read rows from`,s=r===void 0?"":` (--env ${r})`,i=xr(n.hostname);if(gs(i))return`${o}: it is a local or private address, not the worker this deploy ships to`;const a=ys(e,r,n,o,s);return a===void 0?ws(e,r,i,n.pathname,o,s):a??ks(e,r,n,o,s)},Wr=e=>{const t=[j(e),v(e,"package.json"),v(e,"wrangler.dev.jsonc")].filter(n=>n!==void 0&&b(n)).map(n=>[n,S(n,"utf8")]);return()=>{for(const[n,o]of t)S(n,"utf8")!==o&&Y(n,o,"utf8")}},$s=(e,r=Rr())=>C(e,".lunora",`vite-bundle-meta-${r}.json`),Hr="LUNORA_CLIENT_BUILD",Ss="virtual:lunora/worker",Ee=(e,r)=>["ts","mts","cts","js","mjs","cjs"].some(t=>b(v(e,`${r}.config.${t}`))),qr=e=>Ee(e,"rsbuild")?"rsbuild":Ee(e,"vite")?"vite":void 0,Es=e=>Ee(e,"vite")?"vite":qr(e),As=e=>{try{const{scripts:r}=JSON.parse(S(v(e,"package.json"),"utf8"));return typeof r?.build=="string"&&r.build!==""}catch{return!1}},fe=(e,r)=>{if(process.env[Hr]==="1")return;const t=j(e),n=t===void 0?void 0:I(t).parsed,o=n?.main===Ss,s=(o?Es(e):qr(e))??(As(e)?"script":void 0);if(s===void 0)return;const i=r===void 0?void 0:n?.env?.[r]?.assets?.directory,a=n?.assets?.directory??i;return o||wt(e).class!=="C"||a!==void 0?s:void 0},Rs=async(e,r,t)=>{const n=t.spawner??W,o=x(e),s=r==="script"?{args:["run","build"],command:o}:je(o,r,["build"]);t.logger.info(`running ${r} build before bundling the Worker`);const i=Wr(e),a=t.bundleMetaPath??$s(e);ne(v(e,kt),{force:!0});try{const c=await n({args:s.args,command:s.command,cwd:e,env:{[At]:Rt(e),[Et]:t.target,[St]:a,...t.lazyFunctions?{[$t]:"1"}:{},...t.environment===void 0?{}:{CLOUDFLARE_ENV:t.environment},...t.strictAdvisories===!1?{[bt]:"0"}:{},[Hr]:"1"},stdoutToStderr:t.outputJson});return c.code===0?void 0:`${r} build failed with exit code ${String(c.code)}`}finally{i(),t.bundleMetaPath===void 0&&ne(a,{force:!0})}},ge=(e,r,t)=>r!==!1&&fe(e,t)!==void 0,Ts=(e,r,t)=>ge(e,r,t)&&fe(e,t)!=="script",Fe=e=>{const r=e.frameworkBuild===!1?void 0:fe(e.cwd,e.environment);if(r===void 0||r==="script")return;if(e.apiSpec!==void 0)return`--api-spec is read from the ${r} plugin config when the client build runs; set it there, or pass --no-framework-build`;if(e.target!==void 0)try{we(e.cwd,e.target)}catch(n){return n instanceof Error?n.message:String(n)}let t;try{t=we(e.cwd)}catch(n){return`the project's configured target cannot be used, and the ${r} plugin reads it: ${n instanceof Error?n.message:String(n)}`}if(e.target!==void 0&&e.target!==t)return`this run targets "${e.target}", but the project's target is "${t}", which the ${r} plugin reads; set it in the project config, or pass --no-framework-build`},Gr=async e=>{const r=e.frameworkBuild===!1?void 0:fe(e.cwd,e.environment);if(r===void 0)return;let t;try{t=e.target??we(e.cwd)}catch(n){return n instanceof Error?n.message:String(n)}return Rs(e.cwd,r,{bundleMetaPath:e.bundleMetaPath,environment:e.environment,strictAdvisories:e.strictAdvisories,lazyFunctions:e.lazyFunctions,logger:e.logger,outputJson:e.outputJson,spawner:e.spawner,target:t})},fr=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,Me=(e,r,t=j(e))=>{if(!t)return;const{parsed:n}=I(t);if(n===void 0)return;const{error:o,merged:s}=le(n,r),i=o===void 0?s:n,{containers:a,d1_databases:c,vars:l}=i;return{containers:fr(a),d1_databases:fr(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},Cs=/^127(?:\.\d{1,3}){3}$/,_s=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||Cs.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Is=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ps=(e,r,t,n="deploy",o)=>{const s=(Me(e,o)?.containers??[]).filter(a=>typeof a?.image=="string"&&Is(a.image));if(s.length===0||t())return;const i=`${n} blocked: wrangler.jsonc declares ${String(s.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Ue=e=>b(E(e,Ve))?Ve:void 0,js=(e,r,t="deploy",n)=>{for(const o of yr(e,"lunora",n).containers){const s=o.schedulingPolicy===void 0?o.image:void 0,a=[...s?.kind==="dockerfile"?[{field:"image",path:s.dockerfilePath}]:[],...Object.entries(o.schedulingPolicy==="durable_object"?o.images??{}:{}).flatMap(([c,l])=>l.kind==="dockerfile"?[{field:`images["${c}"]`,path:l.dockerfilePath}]:[])].find(c=>!b(E(e,c.path)));if(a!==void 0){const c=`${t} blocked: container "${o.exportName}" references a Dockerfile at "${a.path}" that does not exist. Create it or fix the \`${a.field}\` path in lunora/containers.ts.`;return r.error(c),c}if(s?.kind==="build"&&!b(E(e,s.buildDir))){const c=`${t} blocked: container "${o.exportName}" references a Railpack build directory "${s.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(c),c}}},Os=(e,r)=>r==="celld"?typeof e=="string"&&e!==Ke&&on(e):r==="cloudflare"&&e===Ke,Ds=(e,r,t,n)=>(Me(e,t,n)?.d1_databases??[]).find(o=>Os(o.database_id,r)),Ns=e=>{if(!e.migrate||e.dryRun)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},Vr=(e,r,t,n,o,s)=>{const i=Ds(e,n,o,s);if(i===void 0)return;const a=`${t} blocked: the "${i.binding??"<unnamed>"}" D1 binding has a placeholder database_id ("${i.database_id??""}")`,c=s===void 0?"Run `lunora doctor --fix` to create the database and write its id into wrangler.jsonc, or run `wrangler d1 create <name>` and paste the id in yourself.":`Run \`wrangler d1 create <name>\` and put the returned database_id in ${s}.`,l=n==="celld"?`${a}, which celld would use as the database's identity. Set database_id to the database celld should use, then ${t} again.`:`${a}. ${c}`;return r.error(l),l},Ls=(e,r,t="deploy",n)=>{const o=Me(e,n)?.vars;if(!o)return;const s=Object.entries(o).filter(([,a])=>typeof a=="string"&&_s(a)).map(([a])=>a).toSorted((a,c)=>a.localeCompare(c));if(s.length===0)return;const i=`${t} blocked: ${s.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},xs=["vite.config.ts","vite.config.mts","vite.config.cts","vite.config.js","vite.config.mjs","vite.config.cjs",...ht],Kr=/\.(?:[cm]?[jt]s|tsx|jsx)$/u,zr=/\.(?:test|spec)\.[cm]?[jt]sx?$/u,Jr="allowUnauthenticatedShardAccess",Fs=/[\\/]/u,Yr=new Set(["_generated","build","dist","node_modules"]),Xr=(e,r)=>{const t=z(e,r).split(Fs);return Kr.test(r)&&!zr.test(r)&&!ye(t.join("/"))&&t.every(n=>n===".."||!n.startsWith(".")&&!Yr.has(n))},gr=(e,r,t)=>{const{parsed:n}=I(r);if(n===void 0)return[];const{error:o,merged:s}=le(n,t),{main:i}=o===void 0?s:n,a=typeof i=="string"?E(Ir(r),i):void 0;return a!==void 0&&b(a)&&Xr(e,a)?[a]:[]},Be=e=>e===void 0?!1:e.getKind()===w.FalseKeyword?!0:$.isParenthesizedExpression(e)||$.isAsExpression(e)||$.isSatisfiesExpression(e)||$.isTypeAssertion(e)||$.isNonNullExpression(e)?Be(e.getExpression()):!1,Ms=e=>{try{return Re(e).isFile()}catch{return!1}},Us=new Set(["ELOOP","ENOENT","ENOTDIR"]),ae=(e,r,t)=>{const n=r instanceof Error&&"code"in r&&typeof r.code=="string"?r.code:"";Us.has(n)||t.push(e)},Bs=(e,r)=>{try{return Re(e)}catch(t){ae(e,t,r);return}},Qr=(e,r)=>{try{return S(e,"utf8")}catch(t){ae(e,t,r);return}},Zr=(e,r,t,n=new Set)=>{let o;try{o=ft(r)}catch(i){return ae(r,i,t),[]}if(n.has(o))return[];n.add(o);let s;try{s=V(r)}catch(i){return ae(r,i,t),[]}return s.flatMap(i=>{const a=E(r,i),c=Bs(a,t);if(c===void 0)return[];const l=z(e,a).split(N).join("/");return c.isDirectory()?Yr.has(i)||i.startsWith(".")||ye(`${l}/`)?[]:Zr(e,a,t,n):c.isFile()&&Kr.test(i)&&!zr.test(i)&&!ye(l)?[a]:[]})},Ws=e=>{const r=$.isComputedPropertyName(e)?e.getExpression():e;return $.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r)?r.getLiteralValue():e.getText()},pe=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"],Hs=/\.(?:[cm]?js|jsx)$/u,qs=(e,r)=>{if(!r.startsWith("."))return;const t=C(Ir(e),r),n=t.replace(Hs,"");return[t,...pe.map(s=>`${t}${s}`),...pe.map(s=>E(t,`index${s}`)),...pe.map(s=>`${n}${s}`)].find(s=>Ms(s))},Gs=e=>{if(e.getExpression().getText()!=="require")return;const[r]=e.getArguments();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Vs=e=>{const r=e.getModuleReference();if(!$.isExternalModuleReference(r))return;const t=r.getExpression();return $.isStringLiteral(t)?t.getLiteralValue():void 0},Ks=(e,r,t,n)=>{const o=new Set(e),s=[...e],i=[];for(let a=0;a<s.length;a+=1){const c=s[a]??"",l=Qr(c,n);if(l===void 0)continue;const d=r.createSourceFile(z(t,c),l,{overwrite:!0}),u=[...d.getImportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getExportDeclarations().map(f=>f.getModuleSpecifierValue()),...d.getDescendantsOfKind(w.ImportEqualsDeclaration).map(f=>Vs(f)),...d.getDescendantsOfKind(w.CallExpression).map(f=>Gs(f))].filter(f=>f!==void 0);for(const f of u){const g=qs(c,f);g!==void 0&&Xr(t,g)&&!o.has(g)&&(o.add(g),i.push(g),s.push(g))}}return i},zs=e=>{const r=e.getArgumentExpression();return r!==void 0&&($.isStringLiteral(r)||$.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},Js=e=>$.isPropertyAccessExpression(e)?e.getName():$.isElementAccessExpression(e)?zs(e):void 0,Ys=new Set([w.AmpersandAmpersandEqualsToken,w.AmpersandEqualsToken,w.AsteriskAsteriskEqualsToken,w.AsteriskEqualsToken,w.BarBarEqualsToken,w.BarEqualsToken,w.CaretEqualsToken,w.EqualsToken,w.GreaterThanGreaterThanEqualsToken,w.GreaterThanGreaterThanGreaterThanEqualsToken,w.LessThanLessThanEqualsToken,w.MinusEqualsToken,w.PercentEqualsToken,w.PlusEqualsToken,w.QuestionQuestionEqualsToken,w.SlashEqualsToken]),Xs=e=>{const r=e.getOperatorToken().getKind();return!Ys.has(r)||Js(e.getLeft())!==Jr?!1:r!==w.EqualsToken||!Be(e.getRight())},Qs=(e,r,t)=>{const n=[],o=[...new Set([L(e),"src"])].filter(u=>b(E(e,u))),s=j(e),i=[...xs.map(u=>E(e,u)).filter(u=>b(u)),...s===void 0?[]:gr(e,s,r),...t.flatMap(u=>gr(e,u,r))],a=new Tr({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}),c=o.flatMap(u=>Zr(E(e,u),E(e,u),n));return{sites:[...new Set([...c,...i,...Ks([...i,...c],a,e,n)])].flatMap(u=>{const f=Qr(u,n);if(f===void 0)return[];const g=a.createSourceFile(z(e,u),f,{overwrite:!0}),h=[...g.getDescendantsOfKind(w.PropertyAssignment),...g.getDescendantsOfKind(w.ShorthandPropertyAssignment),...g.getDescendantsOfKind(w.GetAccessor),...g.getDescendantsOfKind(w.MethodDeclaration)].filter(p=>{const R=$.isPropertyAssignment(p)&&Be(p.getInitializer());return Ws(p.getNameNode())===Jr&&!R}).map(p=>p.getStartLineNumber()),m=g.getDescendantsOfKind(w.BinaryExpression).filter(p=>Xs(p)).map(p=>p.getStartLineNumber());return[...h,...m].map(p=>({file:z(e,u),line:p}))}),unreadable:n}},Zs=(e,r,t,n,o,s)=>{if(t!=="deploy")return;const{sites:i,unreadable:a}=Qs(e,o,s),c=Tn({openShardAccess:i,schema:{tables:[]}},{lints:[ze]});if(c.length===0&&a.length===0)return;const l=[];if(c.length>0){const u=c.map(f=>`${String(f.metadata.file)}:${String(f.metadata.line)}`).join(", ");l.push(`${u} enable the open-shard option (any value but a literal false), so any caller may target any shard.`)}if(a.length>0&&l.push(`could not read ${a.join(", ")}, so the open-shard option cannot be ruled out there.`),n){r.warn(`deploying past the open-shard gate (--allow-open-shards): ${l.join(" ")}`);return}const d=`deploy blocked (open_shard_access): ${l.join(" ")} ${ze.remediation}`;return r.error(d),d},ei=(e,r,t,n)=>{const o=Zs(e,r.logger,t,r.allowOpenShards===!0,r.env,n);return o===void 0?void 0:{code:k.USAGE,error:o}},ri=(e,r,t,n)=>{const o=Vr(e,r.logger,t,n,r.env);if(o!==void 0)return{code:k.USAGE,error:o};const s=Ls(e,r.logger,t,r.env);if(s!==void 0)return{code:k.USAGE,error:s};const i=js(e,r.logger,t,r.discoveryCache);if(i!==void 0)return{code:k.USAGE,error:i};const a=Ps(e,r.logger,r.dockerAvailable??kn,t,r.env);return a===void 0?void 0:{code:k.MISSING_DEPENDENCY,error:a}},ti=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ni=/https:\/\/[^\s"'<>]+/u,oi=e=>{if(e===void 0)return;const r=ti.exec(e);return r?r[0]:ni.exec(e)?.[0]},hr=e=>e===void 0?"":` (--env ${e})`,si=({cwd:e,env:r,logger:t,now:n,url:o})=>{if(o!==void 0)try{const s=Ce(e);if(s!==void 0){if(s.workerUrl===o&&s.env===r)return;t.warn(`link: .lunora/project.json records ${s.workerUrl??"(no url)"}${hr(s.env)}, but this deploy published ${o}${hr(r)}. Keeping the recorded value — run \`lunora link --url ${o}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(n??(()=>new Date().toISOString()))();Tt(e,{env:r,linkedAt:i,workerName:Pe(e),workerUrl:o}),t.success(`link: recorded ${o} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},ii=async(e,r)=>{const t=new Tr({skipAddingFilesFromTsConfig:!0}),n=E(r,"lunora");let o;try{o=mt(t,n)}catch(s){const i=s instanceof Error?s.message:String(s);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(o.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(o.length)} migration(s) against deployed worker`);for(const s of o){e.logger.info(`--migrate: up "${s.id}" (table "${s.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:s.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},a=await Cn(i);if(a.code!==0)return e.logger.error(`--migrate: migration "${s.id}" failed — see output above`),a.code;e.logger.success(`--migrate: "${s.id}" applied`)}return 0},ai=async(e,r)=>{const{info:t}=_e(r,"lunora",e.discoveryCache),n=t?.vectorMetadata??[];if(n.length===0)return;const o=[];for(const a of n){const c=sn(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}o.push({index:a.index,property:a.property,type:c})}if(o.length===0)return;const i=(await an({cwd:r,entries:o,exec:je(x(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??W})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(o.length)}`)},mr=5,ci=2e3,di=async(e,r,t)=>{if(e.healthCheck!==!0)return;const n=t??Oe({cwd:r,env:e.env});if(n===void 0){const s="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(s),{error:s,ok:!1,url:""}}const o=await bn({attempts:mr,baseUrl:n,delayMs:ci,fetchImpl:e.healthFetch,paths:[$n,Sn],sleep:e.healthSleep});return o.error===void 0?(e.logger.success(`health check ok (${o.url})`),{ok:!0,url:o.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(mr)} attempt(s) — ${o.error}`),{error:o.error,ok:!1,url:o.url})},li=async(e,r,t,n,o,s)=>{e.isolatedPreview!==!0&&await ai(e,r);const i=e.migrate?await ii(e,r):0;return i===0&&o?.(),{code:i,descriptor:t,mintedSecretsFile:s,validation:n}},ui=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:n,reblessSchemaBaseline:o,recordArchitecture:s,stdout:i,validation:a})=>{const c={deployedAt:new Date().toISOString(),dryRun:n.dryRun===!0,env:n.env,url:n.dryRun===!0?void 0:oi(i),workerName:Pe(e)};if(n.dryRun===!0)return n.healthCheck===!0&&n.logger.warn("--health-check skipped: a dry run publishes nothing"),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:a};n.temporary!==!0&&n.isolatedPreview!==!0&&(s?.(),si({cwd:e,env:n.env,logger:n.logger,url:c.url}));const l=await di(n,e,c.url);if(l?.error!==void 0)return{code:k.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a};const d=n.isolatedPreview===!0?void 0:o;return{...await li(n,e,r,a,d,t),deployment:c,healthCheck:l}},fi=(e,r,t)=>{const n=E(e,D);if(!b(n))return;let o;try{o=wr(S(n,"utf8")).length}catch{return}if(o===0)return;const s=t.toolchain?.secretPut!==void 0;r.warn(s?`Note: \`lunora deploy\` does not push secrets. ${D} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${t.name} deploys read no secrets. ${D} has ${String(o)} key(s) that only the dev server sees; a key the app reads from env must be a \`vars\` entry in the deployed config, one it loads from a secret manager at runtime need not.`)},et=async(e,r)=>{let t=[];try{t=Ct(await kr({cache:r,projectRoot:e,schemaDir:L(e)}))}catch{}const n=[...new Set(_t(t).map(s=>s.key))];let o=[];try{const s=E(e,D);b(s)&&(o=wr(S(s,"utf8")).map(i=>i.key).filter(i=>Er(i)))}catch{}return{fromLocal:o.filter(s=>!n.includes(s)),fromPackages:n,mintableKeys:It(t)}},gi=async(e,r,t,n)=>{const{logger:o}=r,s=r.spawner??W,i=x(e),a=r.env===void 0?"":` --env ${r.env}`,c=n.toolchain?.secretPut;if(c===void 0)return o.error(`deploy target "${n.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=t.map(f=>({key:f,value:Pt()})),d=n.toolchain?.secretBulk;if(d!==void 0&&l.length>=2){const f=K(i,d({environment:r.env,temporary:r.temporary})),g=await s({args:f.args,command:f.command,cwd:e,input:JSON.stringify(Object.fromEntries(l.map(h=>[h.key,h.value])))});if(g.code===0){for(const{key:h}of l)o.success(`generated + pushed ${h}`);return{minted:l,ok:!0}}o.warn(`bulk secret push failed (exit ${String(g.code)}); retrying one key at a time`)}const u=[];for(const{key:f,value:g}of l){const h=c({environment:r.env,key:f,temporary:r.temporary}),m=K(i,h),p=await s({args:m.args,command:m.command,cwd:e,input:g});if(p.code!==0)return o.error(`failed to push secret ${f} (exit ${String(p.code)}); set it manually with \`wrangler secret put ${f}${a}\`.`),{minted:u,ok:!1};u.push({key:f,value:g}),o.success(`generated + pushed ${f}`)}return{minted:u,ok:!0}},hi=/^[\w-]+$/u,pr=[".dev.vars",".dev.vars.*","!.dev.vars.example"],mi=(e,r)=>{try{const t=Nt(e,pr);t.length>0&&r.info(`.gitignore: added ${t.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${pr.join("` and `")}\` by hand before committing.`)}},pi=(e,r,t)=>{if(t.length===0)return;const n=t.map(a=>a.key).join(", ");if(r.env!==void 0&&!hi.test(r.env)){r.logger.warn(`${n}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const o=r.env===void 0?D:`${D}.${r.env}`;mi(e,r.logger);const s=E(e,o);let i=b(s)?S(s,"utf8"):"";for(const a of t)i=jt(i,a.key,a.value);return Ot(s,i),r.logger.success(r.env===void 0?`${n}: value(s) recorded in ${o}`:`${n}: value(s) recorded in ${o} (kept separate from ${D} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),o},vi=/^<[^>]+>$/u,yi=async(e,r,t)=>{let n;try{n=t.projectConfig?.(e,"deploy").vars??{}}catch(d){return{error:d instanceof Error?d.message:String(d)}}const o=d=>{const u=n[d];if(typeof u!="string")return!0;const f=u.trim();return f===""||vi.test(f)?!0:Er(d)&&Dt(u)},s=d=>Object.hasOwn(n,d)?`${d} (empty or a placeholder)`:d,{fromLocal:i,fromPackages:a}=await et(e,r.discoveryCache),c=i.filter(d=>o(d));c.length>0&&r.logger.warn(`${D} key(s) not set in the wrangler vars: ${c.map(d=>s(d)).join(", ")}. ${t.name} has no secret store: a key the app reads from env must be a \`vars\` entry; one it loads from a secret manager at runtime need not.`);const l=a.filter(d=>o(d));return l.length===0?{}:{error:`missing required secret(s) in the wrangler vars: ${l.map(d=>s(d)).join(", ")}. ${t.name} has no secret store and Lunora reads these from env, so each must be a real \`vars\` value in the config the deploy ships — write it there from your secret manager at deploy time rather than committing it. Add them, then re-deploy.`}},wi=async(e,r,t,n)=>{if(r.dryRun===!0||r.isolatedPreview===!0)return{};if(n.toolchain?.secretList===void 0)return yi(e,r,n);const{logger:o}=r,s=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??In)({cwd:e,env:r.env,target:n.id,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const a=new Set(i.names),{fromLocal:c,fromPackages:l,mintableKeys:d}=await et(e,r.discoveryCache),u=[...l,...c].filter(h=>!a.has(h));if(u.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${u.join(", ")}. Set them with \`wrangler secret put <KEY>${s}\` (or \`lunora env generate --set\` then \`lunora env push --yes${s}\`), then re-deploy.`};for(const h of u.filter(m=>!d.has(m)))o.warn(`required secret ${h} is not set on the target — set it with: wrangler secret put ${h}${s}`);const f=u.filter(h=>d.has(h));if(f.length===0)return{};if(await(r.secretConfirm??_n())(`${String(f.length)} required secret(s) not set on the target (${f.join(", ")}). Generate strong values and push them now?`)){const{minted:h,ok:m}=await gi(e,r,f,n),p=pi(e,r,h);return m?{mintedSecretsFile:p}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:p}}return o.warn(`${String(f.length)} required secret(s) not set on the target: ${f.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${s}\`.`),{}},rt=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,ki=async(e,r)=>{if(r.dryRun===!0)return;const t=yr(e,"lunora",r.discoveryCache).containers.flatMap(o=>o.schedulingPolicy===void 0&&o.image.kind==="build"?[{buildDir:o.image.buildDir,exportName:o.exportName}]:[]);if(t.length===0)return;const n=await is({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return n.code===0?void 0:n.error??"railpack build failed"},bi=(e,r,t)=>{if(t!==void 0)try{const n=zt(e,t);n.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${n.wranglerPath??"wrangler.jsonc"}`);for(const s of n.warnings)r.warn(s);const o=Jt(n.preserved);o!==void 0&&r.info(o)}catch(n){const o=n instanceof Error?n.message:String(n);r.warn(`cron trigger sync skipped: ${o}`)}},$i=async(e,r,t,n,o,s)=>{try{de(n);const i=await kr({cache:s,projectRoot:e,schemaDir:L(e)}),a=Vt(e,i,{environment:o,target:n}),c=a.wranglerPath??"wrangler.jsonc";if(a.added.length>0&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${c}`),a.updated.length>0&&r.success(`updated bindings: ${a.updated.join(", ")} → ${c}`),a.devConfig!==void 0){const{added:l,path:d,updated:u}=a.devConfig;r.success(`dev sidecar bindings: ${[...l,...u].join(", ")} → ${d}`)}for(const l of a.warnings)r.warn(l)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=Kt(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}bi(e,r,t)},Si=async(e,r,t,n,o,s,i,a,c,l)=>{let d;r?(d=new Yt({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const u=pt({apiSpec:n,dryRun:!l,lazyFunctions:o,projectRoot:e,target:s,...Gt(e)});d?.succeed("codegen complete"),d||t.success("codegen complete");const f=rn(u.platformDiagnostics,t);if(f.errors.length>0)return{error:f.errors.join("; ")};const{errorAdvisories:g,names:h,shouldBlock:m}=tn(u.advisories,c);if(m){const R=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${h.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return t.error(R),{error:R}}const p=l?await Ut({cwd:e,logger:t,spawner:i,stdoutToStderr:a}):void 0;return p?.error!==void 0?{error:p.error}:{result:u}}catch(u){d?.failed("codegen failed");const f=u instanceof Error?u.message:String(u);return t.error(`codegen failed: ${f}`),{error:`codegen failed: ${f}`}}},vr="--preview is not supported: Cloudflare gives a Worker that implements a Durable Object no version preview URL, and a version shares production's Durable Objects, D1 and R2. Deploy an isolated copy with `lunora preview deploy <name>` (its own Worker, Durable Object namespace, D1, R2 and KV; `lunora preview delete <name>` removes it), or validate without publishing with `--dry-run`.",Ei=(e,r)=>({dryRun:r.dryRun,entry:Ue(e),environment:r.env,outDir:r.outDir,secretsFile:r.secretsFile,outFile:r.outFile,preview:r.preview,temporary:r.temporary}),tt=(e,r,t)=>{const{toolchain:n}=t;if(n===void 0)throw new Error(`deploy target "${t.id}" has no command-line toolchain`);const o=Ei(e,r);return br(t,e,"deploy",s=>n.deploy({...o,configPath:s}))},Ai=(e,r,t)=>{const n=tt(e,r,t),o=Ue(e);return o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),n.commit(),n.projection!==void 0&&n.projection.dropped.length>0&&r.logger.warn(`${t.name} ignores these wrangler keys, so they were left out of ${n.projection.configPath}: ${n.projection.dropped.join(", ")}`),n.command},T={problems:[],wranglerPath:void 0},ve=(e,r)=>({code:k.USAGE,descriptor:void 0,error:e,validation:T,...r}),Ri=(e,r)=>{for(const t of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${t}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},Ti=(e,r,t)=>{const n=r.format==="json",o=r.dryRun!==!0,s=Ai(e,r,t),i=K(x(e),s);return{args:i.args,captureStdout:o&&!n,captureStdoutSilently:o&&n,command:i.command,cwd:e,stdoutToStderr:n&&!o}},We=e=>{if(e.skipServices===!0)return"--skip-services";if(e.isolatedPreview===!0)return"a preview never deploys services: they are production's Workers";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ci=(e,r)=>We(r)===void 0?Te(e).services.map(t=>t.wranglerPath):[],nt=(e,r,t,n,o)=>({cwd:e,environment:r.env,frameworkBuild:n,lazyFunctions:ce(r.lazyFunctions),logger:r.logger,outputJson:r.format==="json"||r.clientBuildOutputJson===!0,spawner:o,strictAdvisories:Ie(r),target:t.id}),_i=(e,r,t)=>{const{toolchain:n}=t,o=n===void 0?`target "${t.id}" has no deploy command`:We(r);if(o!==void 0||n===void 0){const s=e.map(i=>i.worker).join(", ");r.logger.warn(`services not deployed (${o??""}): ${s} — deploy them yourself if the app calls anything new`);return}return n},ot=(e,r)=>{for(const t of e){const n=Fe(r(A(t.wranglerPath)));if(n!==void 0)return`service ${t.name} (${t.worker}): ${n}`}},Ii=(e,r,t)=>{const{error:n,services:o}=Te(e);if(n!==void 0||o.length===0)return;const s=de(t);if(s.toolchain===void 0||We(r)!==void 0)return;const i=r.skipCodegen===!0?!1:r.frameworkBuild,a=[...new Map(o.map(c=>[c.wranglerPath,c])).values()];return ot(a,c=>nt(c,r,s,i,W))},st=(e,r,t)=>{const n=e.cwd??process.cwd(),o=fn(n,e.target);if(o.target===void 0){const a=o.error??"unknown deploy target";return e.logger.error(a),{kind:"refused",error:a,validation:T}}if(e.preview===!0)return e.logger.error(vr),{kind:"refused",code:k.USAGE,error:vr,validation:T};try{tt(n,e,de(o.target))}catch(a){if(!(t&&a instanceof Lt&&ge(n,e.skipCodegen===!0?!1:e.frameworkBuild,e.env))){const c=a instanceof Error?a.message:String(a);return e.logger.error(c),{kind:"refused",error:c,validation:T}}}const s=e.openShardGatePassed===!0?void 0:ei(n,e,r,Ci(n,e));if(s!==void 0)return{kind:"refused",code:s.code,error:s.error,validation:T};const i=Ii(n,e,o.target);return i!==void 0?(e.logger.error(i),{kind:"refused",code:k.USAGE,error:i,validation:T}):{kind:"ok",target:o.target}},Pi=(e,r)=>e.apiSpec??(e.clientBuildRan===!0?Bt(r):void 0),ji=async(e,r,t)=>{if(r!=="celld")return;const n=await(e.celldToolchain??Mt)({dryRun:t==="prepare"||e.dryRun===!0,env:process.env,purpose:"deploy"});for(const o of n.warnings)e.logger.warn(o);return n.errors.length>0?n.errors.join("; "):void 0},it=(e,r)=>{const t=Oe({cwd:e,env:r.env,url:r.migrateUrl}),n=t===void 0?void 0:bs(e,r.env,t);if(n!==void 0)return{reason:n};const o=t===void 0?void 0:Zt(t,r.logger,e),s=o===void 0?void 0:Xt({cwd:e,token:r.migrateToken,url:o}).token;return{target:o===void 0||!s?void 0:{baseUrl:o,fetchImpl:r.fetchImpl??en,token:s}}},Oi=(e,r,t)=>async n=>{const o=it(e,r);return"reason"in o?{kind:"inconclusive",reason:o.reason}:Rn({changes:n,tables:t.schemaTables,target:o.target})},Di=(e,r)=>async t=>{const n=it(e,r);return"reason"in n?n.reason:An({changes:t,now:Date.now(),target:n.target})},Ni=(e,r,t,n)=>e==="deploy"?{checkStoredRows:Oi(r,t,n),countExpiringRows:Di(r,t)}:{},Li=async(e,r)=>{const t=e.cwd??process.cwd(),n=rt(e),o=Ie(e),s={problems:[],wranglerPath:void 0},i=st(e,r,!1);if(i.kind==="refused")return{code:i.code,error:i.error,validation:i.validation};const{target:a}=i,c=await ji(e,a,r);if(c!==void 0)return e.logger.error(c),{code:k.MISSING_DEPENDENCY,error:c,target:a,validation:s};let l;if(!e.skipCodegen){const m=await Si(t,n,e.logger,Pi(e,t),ce(e.lazyFunctions),a,e.spawner,e.format==="json",o,e.clientBuildRan!==!0);if(m.error!==void 0)return{error:m.error,target:a,validation:T};l=m.result,e.discoveryCache?.clear()}let d;if(l!==void 0){const m=await En({allowDrift:e.allowSchemaDrift===!0,...Ni(r,t,e,l),codegen:l,command:r,logger:e.logger});if(m.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:m.reason},target:a,validation:s};d=m.rebless}const u=l&&xn({current:l.architecture,cwd:t,environment:e.env,logger:e.logger});await $i(t,e.logger,l?.cronTriggers,a,e.env,e.discoveryCache);const f=await ue(t,e,r,a,"check");if(f!==void 0)return{error:f,target:a,validation:T};const g=ri(t,e,r,a);if(g!==void 0)return{code:g.code,error:g.error,target:a,validation:T};const h=qt({environment:e.env,projectRoot:t});return Ri(h,e.logger)?{error:"wrangler validation failed",target:a,validation:h}:{codegen:l,reblessSchemaBaseline:d,recordArchitecture:u,target:a,validation:h}},xi=e=>{ne(v(e,".wrangler","deploy","config.json"),{force:!0})},Fi=async(e,r,t)=>{const n=Fe(e);if(n!==void 0)return{built:!1,error:n};const o=ge(e.cwd,r,t);return o&&xi(e.cwd),{built:o,error:await Gr(e)}},Mi=(e,r,t)=>r||t===!1?De(e):void 0,Ui=async(e,r,t)=>{const n=A(e);return Vr(n,r.logger,"deploy",t.id,r.env,e)??ue(n,r,"deploy",t.id,"check",e)},Bi=(e,r,t,n)=>ue(A(e),{...t,clientBuildEnvironment:r?t.env:void 0},"deploy",n.id,"create",e),Wi=async(e,r,t,n,o)=>{const s=[];for(const i of e){const{built:a,error:c}=await Fi(r(A(i.wranglerPath)),t,n);if(c!==void 0){const l=`service ${i.name} (${i.worker}): ${c}`;return o.error(l),{builds:s,failure:{code:k.FAILURE,error:l}}}s.push(a)}return{builds:s}},Hi=async(e,r,t)=>{const{driver:n,frameworkBuild:o,manager:s,options:i,spawner:a,toolchain:c}=t,l=A(e.wranglerPath),d=await Bi(e.wranglerPath,r,i,n);if(d!==void 0)return{code:k.FAILURE,error:`service ${e.name} (${e.worker}): ${d}`};const u=Mi(e.wranglerPath,r,o);let f;try{f=br(n,l,"deploy",m=>c.deploy({configPath:m??u??e.wranglerPath,dryRun:i.dryRun===!0,environment:i.env}))}catch(m){return{code:k.FAILURE,error:`service ${e.name} (${e.worker}): ${m instanceof Error?m.message:String(m)}`}}f.commit();const g=K(s,f.command);i.logger.info(`deploying service ${e.name} (${e.worker}) via ${g.command} ${g.args.join(" ")}`);const h=await a({args:g.args,command:g.command,cwd:l,stdoutToStderr:i.format==="json"});if(h.code!==0)return{code:k.FAILURE,error:`service ${e.name} (${e.worker}): ${g.command} ${g.args.join(" ")} exited ${String(h.code)} — stopping before the app`}},qi=async(e,r,t,n)=>{const{error:o,services:s}=Te(e);if(o!==void 0)return{code:k.FAILURE,error:o};if(s.length===0)return;const i=_i(s,r,t);if(i===void 0)return;const a=x(e),c=[...new Map(s.map(m=>[m.wranglerPath,m])).values()],l=r.skipCodegen===!0?!1:r.frameworkBuild,d=m=>nt(m,r,t,l,n),u=ot(c,d);if(u!==void 0)return r.logger.error(u),{code:k.USAGE,error:u};for(const m of c){const p=await Ui(m.wranglerPath,r,t);if(p!==void 0)return{code:k.USAGE,error:`service ${m.name} (${m.worker}): ${p}`}}const{builds:f,failure:g}=await Wi(c,d,l,r.env,r.logger);if(g!==void 0)return g;const h={driver:t,frameworkBuild:l,manager:a,options:r,spawner:n,toolchain:i};for(const[m,p]of c.entries()){const R=await Hi(p,f[m]===!0,h);if(R!==void 0)return R}},Gi=async(e,r,t,n)=>{if(r!=="cloudflare")return;const o=e===void 0?void 0:I(e).parsed,s=(t===void 0?void 0:o?.env?.[t]?.account_id)??o?.account_id,i=await dn({accountId:s});(i.verdict==="near"||i.verdict==="full")&&n.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Vi=e=>e.dryRun!==!0&&e.temporary!==!0,Ki=e=>e.temporary===!0?"temporary":e.dryRun===!0?"preview":"defer",zi=e=>{const r=e.fix===void 0?e.message:`${e.message} ${e.fix}`;return e.verdict==="unchecked"?`${r} The deploy stops until it can be checked, as a namespace made by the first repo is unrestricted.`:r},Ji=(e,r,t)=>{const n=[];for(const o of e)if(o.verdict==="ok")o.changesAccount===!0&&r.info(o.message);else if(o.verdict==="unchecked"&&t==="preview")r.warn(`dry run: ${o.message}${o.fix===void 0?"":` ${o.fix}`} A real deploy stops here.`);else{const s=zi(o);r.error(s),n.push(s)}return n},at=async(e,r,t,n,o,s,i)=>{const a=t==="cloudflare"&&r!==void 0?I(r).parsed:void 0;if(a===void 0)return;const c=(le(a,n).merged.artifacts??[]).flatMap(h=>typeof h?.binding=="string"&&typeof h.namespace=="string"?[{binding:h.binding,namespace:h.namespace}]:[]),l=c.length===0?void 0:_e(e,L(e),s).info?.jurisdiction;if(l===void 0)return;const d=[...new Map(c.map(h=>[h.namespace,h])).values()];if(i==="temporary"){o.warn(`--temporary deploys to a throwaway account, so the jurisdiction ("${l}") of Artifacts namespace ${d.map(h=>`"${h.namespace}"`).join(", ")} was not checked: it is created there on first use, in no jurisdiction.`);return}const u=(n===void 0?void 0:a.env?.[n]?.account_id)??a.account_id,f=await Promise.all(d.map(async h=>cn({...h,accountId:u,create:i==="create",jurisdiction:l,missingOk:i==="defer"||i==="preview"}))),g=Ji(f,o,i);return g.length===0?void 0:g.join(`
63
+ `)},Yi=async(e,r,t,n,o,s)=>{const i=Vi(r)?await at(e,s,o,r.env,r.logger,r.discoveryCache,"create"):void 0;if(i!==void 0)return{code:k.FAILURE,error:i};const a=await ue(e,r,"deploy",o);return a!==void 0?{code:k.FAILURE,error:a}:qi(e,r,t,n)},Xi=async(e,r,t,n)=>{if(!(r.smokeLoad===!1||t.toolchain===void 0))return os({composedEntry:Ue(e),configPath:n,cwd:e,environment:r.env,launcher:r.smokeLauncher,logger:r.logger,toolchain:t.toolchain})},Qi=async e=>{const r={...e,discoveryCache:e.discoveryCache??Ft()},t=r.cwd??process.cwd(),n=rt(r),o=await Li(r,r.commandName??"deploy");if(o.error!==void 0){if(o.validation.problems.length>0)return{code:k.USAGE,descriptor:void 0,error:o.error,validation:o.validation};const p=o.schemaDrift===void 0?void 0:{schemaDrift:o.schemaDrift};return ve(o.error,{...p,...o.code===void 0?{}:{code:o.code}})}const{validation:s}=o,i=de(o.target),a=Ns(r)??await at(t,s.wranglerPath,o.target,r.env,r.logger,r.discoveryCache,Ki(r))??await Xi(t,r,i,s.wranglerPath);if(a!==void 0)return ve(a);const c=i.toolchain?.prebuildsContainerImages===!0?await ki(t,r):void 0;if(c!==void 0)return ve(c);fi(t,r.logger,i),Ht(t,p=>{r.logger.warn(p)}),await Gi(s.wranglerPath,o.target,r.env,r.logger);const{error:l,mintedSecretsFile:d}=await wi(t,r,n,i);if(l!==void 0)return r.logger.error(l),{code:k.USAGE,descriptor:void 0,error:l,mintedSecretsFile:d,validation:s};const u=r.spawner??W,f=await Yi(t,r,i,u,o.target,s.wranglerPath);if(f!==void 0)return{code:f.code,descriptor:void 0,error:f.error,mintedSecretsFile:d,validation:s};const g=Ti(t,r,i);r.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const h=await u(g);return g.captureStdoutSilently===!0&&h.stdout!==void 0&&h.stdout!==""&&process.stderr.write(h.stdout),h.code!==0?{code:h.code,descriptor:g,mintedSecretsFile:d,validation:s}:{...await ui({...o,cwd:t,descriptor:g,mintedSecretsFile:d,options:r,stdout:h.stdout}),logsAvailable:i.toolchain?.tail!==void 0}},Zi=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n={apiSpec:e.apiSpec,cwd:t,environment:e.env,bundleMetaPath:e.bundleMetaPath,frameworkBuild:e.skipCodegen===!0?!1:e.frameworkBuild,strictAdvisories:Ie(e),lazyFunctions:ce(e.lazyFunctions),logger:r,outputJson:e.format==="json"||e.clientBuildOutputJson===!0,spawner:e.spawner,target:e.target},o=Fe(n);if(o!==void 0)return r.error(o),{code:k.USAGE,descriptor:void 0,error:o,validation:T};xt(t);const s=await Gr(n);if(s!==void 0)return r.error(s),{code:k.FAILURE,descriptor:void 0,error:s,validation:T}},ea=(e,r)=>{const t=r.skipCodegen===!0?!1:r.frameworkBuild;return ge(e,t,r.env)?r.env:void 0},ra=async e=>{const{logger:r}=e,t=e.cwd??process.cwd(),n=st(e,e.commandName??"deploy",!0);if(n.kind==="refused")return{code:n.code??k.USAGE,descriptor:void 0,error:n.error,validation:n.validation};const o=await Zi(e);if(o!==void 0)return o;const s=e.dryRun===!0?Wr(t):void 0;let i;try{if(i=await Qi({...e,clientBuildEnvironment:ea(t,e),clientBuildRan:Ts(t,e.skipCodegen===!0?!1:e.frameworkBuild,e.env),logger:r,openShardGatePassed:!0}),i.code===0&&e.emitBindings!==void 0){const{error:a}=ln({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});a!==void 0&&(r.error(a),i={...i,code:k.USAGE})}}finally{s?.()}return e.format==="json"||i.code===0&&e.dryRun!==!0&&e.isolatedPreview!==!0&&Fn({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:i.logsAvailable===!0,mintedSecretsFile:i.mintedSecretsFile,url:i.deployment?.url}),i},xa=un(async({cwd:e,format:r,logger:t,options:n})=>{const o=ss(e,n.root),s=await ra({allowOpenShards:n.allowOpenShards===!0,allowSchemaDrift:n.allowSchemaDrift===!0,apiSpec:nn(n.apiSpec),frameworkBuild:n.prebuilt===!0?!1:n.frameworkBuild,lazyFunctions:ce(n.lazyFunctions),cwd:o,dryRun:n.dryRun===!0,env:n.env,format:r,healthCheck:n.healthCheck===!0,logger:t,migrate:n.migrate===!0,migrateToken:n.migrateToken,migrateUrl:Oe({cwd:o,env:n.env,url:n.migrateUrl}),migrateYes:n.migrateYes===!0,preview:n.preview===!0,skipCodegen:n.prebuilt===!0,skipServices:n.skipServices===!0,smokeLoad:n.smokeLoad,strictAdvisories:n.strictAdvisories,target:n.target,temporary:n.temporary===!0});return{code:s.code,data:{deployment:s.deployment,healthCheck:s.healthCheck,mintedSecretsFile:s.mintedSecretsFile,schemaDrift:s.schemaDrift,validation:s.validation},error:s.error}});export{Li as a,$i as b,Gn as c,Wr as d,et as e,xa as f,ss as p,ra as r,Xi as s,$s as v};
@@ -0,0 +1 @@
1
+ import"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./platform-diagnostics-Cn2g6Jh-.mjs";import"./api-spec-lYyq4vL6.mjs";import{f as D,b as x,r as y,a as P,s as b}from"../packem_chunks/handler.mjs";import"./vectorize-metadata-DK61NmVx.mjs";import"./binding-manifest-file-CQ1eQYy1.mjs";import"./command-BpMv2n0o.mjs";import"./deploy-target-resolve-BTCW1Iv4.mjs";import"./EXIT_CODE-DQVhSE-1.mjs";import"./resolve-target-BRvw8Pf7.mjs";import"./health-probe-BLnoq_oC.mjs";import"./createRecordingSpawner-DchLi0gR.mjs";export{D as execute,x as provisionBindings,y as runDeployCommand,P as runPreDeployPipeline,b as smokeLoadDeferredModules};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.476",
3
+ "version": "1.0.0-alpha.478",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -1 +0,0 @@
1
- import"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./platform-diagnostics-Cn2g6Jh-.mjs";import"./api-spec-lYyq4vL6.mjs";import{f,b as x,r as D,a as L,s as P}from"../packem_chunks/handler.mjs";import"./vectorize-metadata-DK61NmVx.mjs";import"./binding-manifest-file-CQ1eQYy1.mjs";import"./command-BpMv2n0o.mjs";import"./deploy-target-resolve-BTCW1Iv4.mjs";import"./EXIT_CODE-DQVhSE-1.mjs";import"./resolve-target-BRvw8Pf7.mjs";import"./health-probe-BLnoq_oC.mjs";import"./createRecordingSpawner-DchLi0gR.mjs";export{f as execute,x as provisionBindings,D as runDeployCommand,L as runPreDeployPipeline,P as smokeLoadLazyModules};