@lunora/cli 1.0.0-alpha.437 → 1.0.0-alpha.439
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/packem_chunks/cli.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler25.mjs +1 -1
- package/dist/packem_chunks/runDevCommand.mjs +2 -2
- package/dist/packem_shared/{runDeployCommand-DsFzrpXY.mjs → runDeployCommand-CwgnRrbK.mjs} +1 -1
- package/dist/packem_shared/vectorize-metadata-DOB1akh6.mjs +2 -0
- package/package.json +10 -10
- package/dist/packem_shared/vectorize-metadata-BDrKVEF4.mjs +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isLunoraError as L,findSolutionByMessage as j}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import _ from"@visulima/cerebro/command/completion";import T 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 P,DEFAULT_DEPLOY_TARGET as U,addArgsFor as M,detectPackageManager as W}from"@lunora/config/cli";import{SDK_LANGUAGES as z}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-D_XCixv8.mjs";import{setCommandLogger as k,createLogger as v}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as J}from"../packem_shared/render-lunora-error-B6893vbU.mjs";import{mkdirSync as K,readFileSync as G,lstatSync as V,writeFileSync as H}from"node:fs";import{homedir as q}from"node:os";import{join as b}from"node:path";const Y={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]},S="lunora.advisor.map.json",Q={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("./handler18.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}]},X={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("./handler3.mjs").then(e=>({default:e.execute})),name:"analyze",options:[s]},Z={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 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("./handler22.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:"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}]},ee=(()=>{const e=P();return e.length>1?`${e.join(" | ")} (default ${U})`:e.join(" | ")})(),p={description:`Deploy target: ${ee}. Also settable as "target" in lunora.config.*`,name:"target",type:String},te={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("./handler19.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 in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before shipping",name:"no-smoke-load",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]},oe=[{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 | 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]"}],R={argument:{description:`${oe.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 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 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("./handler28.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},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list only)"},p]},re={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]},ne={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-DsFzrpXY.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; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",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:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",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 in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function 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},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ae={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}]},ie={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("./handler4.mjs").then(e=>({default:e.execute})),name:"docs"},se={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("./handler25.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}]},le={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("./handler5.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}]},de={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("./handler23.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}]},pe={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("./handler6.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}]},ce={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 ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("./handler7.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:"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}]},ue={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("./handler8.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}]},me={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 | 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:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},he={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("./handler9.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}]},ge={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("./handler26.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]},fe={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("./handler10.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}]},ye={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("./handler24.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}]},ve={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("./handler27.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}]},be={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) 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"]],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:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},we={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("./handler11.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 in workerd before passing (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function 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,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ke={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("./handler20.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]},Se={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("./handler12.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}]},xe={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}]},Ce={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("./handler13.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}]},Re={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}]},Oe={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("./handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${z.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}]},Ne={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}]},Ae={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("./handler15.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}]},Be={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("./handler16.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]},De={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("./handler17.mjs").then(e=>({default:e.execute})),name:"view"},Ee=(e,t)=>{const o=Array.from({length:t.length+1},(r,n)=>n);for(let r=1;r<=e.length;r+=1){let n=o[0]??0;o[0]=r;for(let a=1;a<=t.length;a+=1){const i=o[a]??0,l=e[r-1]===t[a-1]?0:1;o[a]=Math.min((o[a-1]??0)+1,i+1,n+l),n=i}}return o[t.length]??0},O=(e,t)=>{let o,r=Number.POSITIVE_INFINITY;for(const a of t){const i=Ee(e,a);i<r&&(r=i,o=a)}const n=Math.max(2,Math.ceil(e.length/3));return o!==void 0&&r<=n?o:void 0},Le=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,je=1440*60*1e3,Ie=1500,_e="0.0.0",Te=/^v/u,Pe=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Te,""),o=t.indexOf("-");return o===-1?{core:t,prerelease:""}:{core:t.slice(0,o),prerelease:t.slice(o+1)}},x=e=>{const[t,o,r]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,o??0,r??0]},Ue=(e,t)=>{const o=Number.parseInt(e,10),r=Number.parseInt(t,10);return String(o)===e&&String(r)===t?o>r?1:-1:e>t?1:-1},Me=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const o=e.split("."),r=t.split(".");for(let n=0;n<Math.max(o.length,r.length);n+=1){const a=o[n],i=r[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Ue(a,i)}return 0},We=(e,t)=>{const o=x(e),r=x(t);for(let n=0;n<3;n+=1)if((o[n]??0)!==(r[n]??0))return(o[n]??0)>(r[n]??0)?1:-1;return Me(g(e).prerelease,g(t).prerelease)},ze=e=>{const t=g(e).prerelease.split(".")[0]??"";return Pe.has(t)?t:"latest"},$e=(e,t)=>We(t,e)>0,Fe=(e,t,o)=>t-e<o,Je=(e,t,o="latest",r)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(r===void 0)return`${n} — add @lunora/cli@${o} as a dev dependency to update`;const{args:a,command:i}=M(r,[`@lunora/cli@${o}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},N=e=>b(e,"lunora-cli-update.json"),Ke=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:b(q(),".cache"),o=b(t,"lunora");try{K(o,{mode:448,recursive:!0})}catch{}return o},Ge=e=>{try{const t=JSON.parse(G(N(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:o,latest:r}=t;if(typeof r=="string"&&typeof o=="number"){const{tag:n}=t;return{checkedAt:o,latest:r,...typeof n=="string"?{tag:n}:{}}}}}catch{}},C=(e,t)=>{try{const o=N(e);try{if(V(o).isSymbolicLink())return}catch{}H(o,`${JSON.stringify(t)}
|
|
1
|
+
import{isLunoraError as L,findSolutionByMessage as j}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import _ from"@visulima/cerebro/command/completion";import T 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 P,DEFAULT_DEPLOY_TARGET as U,addArgsFor as M,detectPackageManager as W}from"@lunora/config/cli";import{SDK_LANGUAGES as z}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-D_XCixv8.mjs";import{setCommandLogger as k,createLogger as v}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as J}from"../packem_shared/render-lunora-error-B6893vbU.mjs";import{mkdirSync as K,readFileSync as G,lstatSync as V,writeFileSync as H}from"node:fs";import{homedir as q}from"node:os";import{join as b}from"node:path";const Y={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]},S="lunora.advisor.map.json",Q={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("./handler18.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}]},X={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("./handler3.mjs").then(e=>({default:e.execute})),name:"analyze",options:[s]},Z={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 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("./handler22.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:"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}]},ee=(()=>{const e=P();return e.length>1?`${e.join(" | ")} (default ${U})`:e.join(" | ")})(),p={description:`Deploy target: ${ee}. Also settable as "target" in lunora.config.*`,name:"target",type:String},te={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("./handler19.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 in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function modules before shipping",name:"no-smoke-load",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]},oe=[{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 | 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]"}],R={argument:{description:`${oe.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 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 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("./handler28.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},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list only)"},p]},re={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]},ne={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-CwgnRrbK.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; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",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:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",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 in workerd before shipping (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function 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},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ae={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}]},ie={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("./handler4.mjs").then(e=>({default:e.execute})),name:"docs"},se={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("./handler25.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}]},le={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("./handler5.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}]},de={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("./handler23.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}]},pe={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("./handler6.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}]},ce={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 ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("./handler7.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:"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}]},ue={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("./handler8.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}]},me={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 | 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:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},he={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("./handler9.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}]},ge={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("./handler26.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]},fe={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("./handler10.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}]},ye={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("./handler24.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}]},ve={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("./handler27.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}]},be={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) 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"]],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:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},we={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("./handler11.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 in workerd before passing (default; nothing to check for an eager registry)",name:"smoke-load",type:Boolean},{description:"Skip evaluating lazy function 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,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ke={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("./handler20.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]},Se={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("./handler12.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}]},xe={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}]},Ce={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("./handler13.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}]},Re={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}]},Oe={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("./handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${z.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}]},Ne={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}]},Ae={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("./handler15.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}]},Be={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("./handler16.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]},De={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("./handler17.mjs").then(e=>({default:e.execute})),name:"view"},Ee=(e,t)=>{const o=Array.from({length:t.length+1},(r,n)=>n);for(let r=1;r<=e.length;r+=1){let n=o[0]??0;o[0]=r;for(let a=1;a<=t.length;a+=1){const i=o[a]??0,l=e[r-1]===t[a-1]?0:1;o[a]=Math.min((o[a-1]??0)+1,i+1,n+l),n=i}}return o[t.length]??0},O=(e,t)=>{let o,r=Number.POSITIVE_INFINITY;for(const a of t){const i=Ee(e,a);i<r&&(r=i,o=a)}const n=Math.max(2,Math.ceil(e.length/3));return o!==void 0&&r<=n?o:void 0},Le=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,je=1440*60*1e3,Ie=1500,_e="0.0.0",Te=/^v/u,Pe=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Te,""),o=t.indexOf("-");return o===-1?{core:t,prerelease:""}:{core:t.slice(0,o),prerelease:t.slice(o+1)}},x=e=>{const[t,o,r]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,o??0,r??0]},Ue=(e,t)=>{const o=Number.parseInt(e,10),r=Number.parseInt(t,10);return String(o)===e&&String(r)===t?o>r?1:-1:e>t?1:-1},Me=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const o=e.split("."),r=t.split(".");for(let n=0;n<Math.max(o.length,r.length);n+=1){const a=o[n],i=r[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Ue(a,i)}return 0},We=(e,t)=>{const o=x(e),r=x(t);for(let n=0;n<3;n+=1)if((o[n]??0)!==(r[n]??0))return(o[n]??0)>(r[n]??0)?1:-1;return Me(g(e).prerelease,g(t).prerelease)},ze=e=>{const t=g(e).prerelease.split(".")[0]??"";return Pe.has(t)?t:"latest"},$e=(e,t)=>We(t,e)>0,Fe=(e,t,o)=>t-e<o,Je=(e,t,o="latest",r)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(r===void 0)return`${n} — add @lunora/cli@${o} as a dev dependency to update`;const{args:a,command:i}=M(r,[`@lunora/cli@${o}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},N=e=>b(e,"lunora-cli-update.json"),Ke=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:b(q(),".cache"),o=b(t,"lunora");try{K(o,{mode:448,recursive:!0})}catch{}return o},Ge=e=>{try{const t=JSON.parse(G(N(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:o,latest:r}=t;if(typeof r=="string"&&typeof o=="number"){const{tag:n}=t;return{checkedAt:o,latest:r,...typeof n=="string"?{tag:n}:{}}}}}catch{}},C=(e,t)=>{try{const o=N(e);try{if(V(o).isSymbolicLink())return}catch{}H(o,`${JSON.stringify(t)}
|
|
2
2
|
`,"utf8")}catch{}},Ve=async(e,t)=>{try{const o=await e(Le(t),{signal:AbortSignal.timeout(Ie)});if(!o.ok)return;const r=await o.json(),n=r!==null&&typeof r=="object"?r.version:void 0;return typeof n=="string"?n:void 0}catch{return}},He=(e,t,o)=>e===_e||!o||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,qe=async e=>{const t=e.env??process.env,o=e.isTTY??process.stdout.isTTY;if(He(e.current,t,o))return;const r=e.cacheDir??Ke(t),n=(e.now??Date.now)(),a=e.ttlMs??je,i=ze(e.current),l=Ge(r),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let h=d?.latest;if(d===void 0||!Fe(d.checkedAt,n,a)){const f=await Ve(e.fetchImpl??globalThis.fetch,i);f===void 0?C(r,{checkedAt:n,latest:e.current,tag:i}):(h=f,C(r,{checkedAt:n,latest:f,tag:i}))}h!==void 0&&$e(e.current,h)&&e.logger.warn(Je(e.current,h,i,e.manager))},A=["init","add","dev","codegen","build","deploy","prepare","link","cloudflare","logs","run","insights","profile","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],B=$(),Ye=[me,Y,ae,re,Q,te,ne,we,fe,R,ye,Re,he,ke,xe,be,pe,ce,Ne,Ae,ge,Z,de,Be,ue,se,le,X,De,ie,Se,Ce,ve,Oe],D=[...Ye,T,_],Ct=D.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Qe=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(o=>u(o))),Xe=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:Qe(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(t.description??"")}))}}),Ze=e=>{const t={value:0},o=I("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:r=>{t.value=typeof r=="number"?r:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:B});for(const r of D)o.addCommand(Xe(r));return{cli:o,exitCode:t}},et=/Command "(?<name>[^"]+)" not found/u,w={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},tt=new Set((R.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),ot=/^[\w@%+=:,./-]+$/u,rt=e=>ot.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,nt=(e,t)=>{const o=e.indexOf(t);return o===-1?[...e]:[...e.slice(0,o),...e.slice(o+1)]},at=(e,t)=>e.findIndex((o,r)=>o===t&&(r===0||!tt.has(e[r-1]??""))),it=e=>{const t=O(e,[...A,...Object.keys(w)]);return t!==void 0&&Object.hasOwn(w,t)?t:void 0},E=(e,t,o)=>{const r=it(e),n=r===void 0?void 0:w[r];if(r===void 0||n===void 0)return;const a=e===r?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=at(i,n.absorbs);if(d===-1&&o===void 0)return`${a}\`lunora ${r}\` 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?r:`${r} ${n.absorbs}`,c=o??["lunora",n.to,...i.map(d=>rt(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},st=(e,t)=>{const o=v(),r=e instanceof Error?e.message:String(e),n=et.exec(r);if(!n?.groups)return L(e)||j(r)!==void 0?o.error(J(e)):o.error(r),F(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=E(i,nt(t,i));if(l!==void 0)return o.error(l),y.USAGE;const c=O(a,A);return o.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),o.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},lt=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)}}),Rt=async(e={})=>{const{cli:t,exitCode:o}=Ze(e);e.logger!==void 0&&k(lt(e.logger));const r=e.argv??process.argv.slice(2);try{const a=r[0]==="help"&&r[1]!==void 0?E(r[1],r.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 st(a,r)}finally{k(void 0)}let n;try{n=W(process.cwd())}catch{}return await qe({current:B,logger:v(),manager:n}),o.value};export{A as C,S as D,Ct as R,B as V,oe as a,Rt as r};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{mkdirSync as xe,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as kr,readdirSync as Me,realpathSync as br,statSync as Fe}from"node:fs";import{dirname as M,join as k,resolve as j,relative as Z,extname as Sr,sep as oe}from"node:path";import{PROJECT_CONFIG_FILENAMES as $r,isTestPath as ae,discoverMigrations as Er,readServiceBindings as le,runCodegen as Ar}from"@lunora/codegen";import{readLinkedProject as Ue,resolveSchemaDirectory as I,startDevProcess as Tr,acceptsConnection as Rr,resolveTargetOrThrow as se,detectFramework as Dr,DEFAULT_BUNDLE_META_PATH as _r,STRICT_ADVISORIES_ENV as Pr,LAZY_FUNCTIONS_ENV as Nr,BUNDLE_META_PATH_ENV as Cr,BUILD_TARGET_ENV as Or,BUILD_ROOT_ENV as jr,canonicalPath as Ir,COMPOSED_WORKER_ENTRY as be,discoverContainerInfo as Be,D1_PLACEHOLDER_ID as Se,writeLinkedProject as Lr,discoverSchemaInfo as He,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as xr,inferLunoraBindings as Ve,requiredSecrets as Mr,mintableSecretKeysFor as Fr,generateSecretValue as Ur,upsertDevVariableLine as Br,writeDevVariablesFileAtomically as Hr,isPlaceholderValue as Gr,ensureGitignoreEntries as Vr,resolveLazyFunctions as z,resolveDeployDriver as J,MissingBuildOutputError as qr,clearApiSpecMarker as Wr,createDiscoveryCache as Kr,planToolchainInvocation as qe,probeCelldToolchain as zr,runPostCodegenHook as Jr,readApiSpecMarker as Yr}from"@lunora/config";import{bindingsNeedingDatabase as Xr,findWranglerFile as L,readWranglerJsonc as N,mergeWranglerEnvironment as Y,applyModify as We,HYPERDRIVE_PLACEHOLDER_ID as Qr,warnCloudflareCliConfigOnce as Zr,validateWranglerProject as et,wranglerCodegenInputs as rt,reconcileWranglerBindings as tt,reconcileWranglerCompatibilityDate as nt,reconcileWranglerCrons as ot,describePreservedCrons as at}from"@lunora/config/cloudflare";import{Spinner as st}from"@visulima/spinner";import{r as ue,a as it,e as ct}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as dt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{i as lt,m as ut,g as gt,c as Ke,f as ft,e as mt}from"../packem_shared/vectorize-metadata-
|
|
1
|
+
import{mkdirSync as xe,writeFileSync as H,existsSync as S,readFileSync as A,rmSync as W,mkdtempSync as kr,readdirSync as Me,realpathSync as br,statSync as Fe}from"node:fs";import{dirname as M,join as k,resolve as j,relative as Z,extname as Sr,sep as oe}from"node:path";import{PROJECT_CONFIG_FILENAMES as $r,isTestPath as ae,discoverMigrations as Er,readServiceBindings as le,runCodegen as Ar}from"@lunora/codegen";import{readLinkedProject as Ue,resolveSchemaDirectory as I,startDevProcess as Tr,acceptsConnection as Rr,resolveTargetOrThrow as se,detectFramework as Dr,DEFAULT_BUNDLE_META_PATH as _r,STRICT_ADVISORIES_ENV as Pr,LAZY_FUNCTIONS_ENV as Nr,BUNDLE_META_PATH_ENV as Cr,BUILD_TARGET_ENV as Or,BUILD_ROOT_ENV as jr,canonicalPath as Ir,COMPOSED_WORKER_ENTRY as be,discoverContainerInfo as Be,D1_PLACEHOLDER_ID as Se,writeLinkedProject as Lr,discoverSchemaInfo as He,DEV_VARS_FILE as P,parseDevVariableEntries as Ge,secretSourcesFromBindings as xr,inferLunoraBindings as Ve,requiredSecrets as Mr,mintableSecretKeysFor as Fr,generateSecretValue as Ur,upsertDevVariableLine as Br,writeDevVariablesFileAtomically as Hr,isPlaceholderValue as Gr,ensureGitignoreEntries as Vr,resolveLazyFunctions as z,resolveDeployDriver as J,MissingBuildOutputError as qr,clearApiSpecMarker as Wr,createDiscoveryCache as Kr,planToolchainInvocation as qe,probeCelldToolchain as zr,runPostCodegenHook as Jr,readApiSpecMarker as Yr}from"@lunora/config";import{bindingsNeedingDatabase as Xr,findWranglerFile as L,readWranglerJsonc as N,mergeWranglerEnvironment as Y,applyModify as We,HYPERDRIVE_PLACEHOLDER_ID as Qr,warnCloudflareCliConfigOnce as Zr,validateWranglerProject as et,wranglerCodegenInputs as rt,reconcileWranglerBindings as tt,reconcileWranglerCompatibilityDate as nt,reconcileWranglerCrons as ot,describePreservedCrons as at}from"@lunora/config/cloudflare";import{Spinner as st}from"@visulima/spinner";import{r as ue,a as it,e as ct}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as dt}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{i as lt,m as ut,g as gt,c as Ke,f as ft,e as mt}from"../packem_shared/vectorize-metadata-DOB1akh6.mjs";import{w as ht}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as vt}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as ge}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{a as pt}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as y}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{spawn as yt}from"node:child_process";import{randomUUID as ze,createHash as wt}from"node:crypto";import{setTimeout as kt}from"node:timers/promises";import{toolchainExecArgs as F,detectPackageManager as C,execArgsFor as fe}from"@lunora/config/cli";import{f as bt}from"../packem_shared/free-port-DjbFhaaT.mjs";import{containerBuildTag as St}from"@lunora/container";import{a as $t,i as Et}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as x}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{r as Je}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as At,H as Tt,a as Rt,r as Dt}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{runAdvisor as _t,openShardAccess as $e}from"@lunora/advisor";import{join as b,relative as U,dirname as Ye}from"@visulima/path";import{Project as Xe,SyntaxKind as p,Node as w}from"ts-morph";import{r as Pt,c as Nt}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{runMigrateDataCommand as Ct}from"../packem_shared/runMigrateGenerateCommand-rZdsVcFj.mjs";import{c as Ot}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as jt}from"../packem_shared/wrangler-secrets-DlSlWvRH.mjs";const It=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Lt=20,Ee=e=>`${e.from} -${e.kind}-> ${e.to}`,V=(e,r)=>{const t=new Set(e);return r.filter(n=>!t.has(n)).toSorted((n,o)=>n.localeCompare(o))},xt=(e,r)=>{const t=e.modules.map(s=>s.name),n=r.modules.map(s=>s.name),o=e.edges.map(s=>Ee(s)),a=r.edges.map(s=>Ee(s));return{addedEdges:V(o,a),addedModules:V(t,n),removedEdges:V(a,o),removedModules:V(n,t)}},q=(e,r,t)=>{if(t.length===0)return[];const n=t.slice(0,Lt).map(a=>` ${e} ${a}`),o=t.length-n.length;return[`${r}:`,...n,...o>0?[` … and ${o.toString()} more`]:[]]},Mt=e=>{const r=[...q("+","modules added",e.addedModules),...q("-","modules removed",e.removedModules),...q("+","edges added",e.addedEdges),...q("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}`},Ft=(e,r)=>k(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),Ut=e=>{if(S(e))try{const r=JSON.parse(A(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Bt=e=>{const{cwd:r,environment:t,logger:n}=e,o=Ft(r,t),a=Ut(o),s=e.current??(a===void 0?void 0:It);if(s===void 0)return;const i=a===void 0?void 0:Mt(xt(a,s));return i!==void 0&&n.info(i),()=>{try{xe(M(o),{recursive:!0}),H(o,`${JSON.stringify(s,void 0,2)}
|
|
4
4
|
`,"utf8")}catch(c){n.warn(`could not record the deployed architecture at ${o}: ${c instanceof Error?c.message:String(c)}`)}}},Ht=e=>{const{cwd:r,env:t,logger:n,mintedSecretsFile:o}=e;try{const a=Ue(r),s=a?.workerName??ge(r),i=e.url??a?.workerUrl;n.success("deploy complete"),n.info(` worker: ${s??"(see wrangler output above)"}`),t!==void 0&&n.info(` env: ${t}`),i===void 0?n.info(" url: run `lunora link --url <https://your-worker>` to record it"):n.info(` url: ${i}`),o!==void 0&&n.info(` secrets: generated value(s) recorded in ${o}`),e.logsAvailable&&n.info(" logs: lunora logs")}catch{}},Gt=/\/index$/u,Vt=/[^\dA-Za-z]/gu,qt=e=>e.replace(Gt,"").split("/").map(r=>r.replaceAll(Vt,"_")),Wt=e=>qt(e).join("_"),Kt=18787,Ae=3,Qe=12e4,zt=5e3,ee=10,Jt=new Set([".js",".mjs",".mts",".ts",".tsx"]),Yt=/\(void 0\)|is not a function|before initialization|of undefined/u,Xt=e=>typeof e=="object"&&e!==null&&typeof e.functionPath=="string"&&typeof e.message=="string",Qt=e=>{const r=I(e),t=new Map;let n;try{n=Me(k(e,r),{recursive:!0,encoding:"utf8"})}catch{return t}for(const o of n){const a=Sr(o);Jt.has(a)&&!o.split(oe).some(s=>s==="_generated"||s==="node_modules")&&t.set(Wt(o.slice(0,-a.length).split(oe).join("/")),k(r,o))}return t},Zt=(e,r)=>{const t=Qt(e),n=new Map;for(const{functionPath:o,message:a}of r){const s=o.lastIndexOf(":"),i=o.slice(0,s),c=`${i}\0${a}`,d=n.get(c)??{exports:[],message:a,namespace:i};d.exports.push(o.slice(s+1)),n.set(c,d)}return[...n.values()].map(({exports:o,message:a,namespace:s})=>{const i=Yt.test(a)?`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as v,readFileSync as R,realpathSync as y}from"node:fs";import{join as f}from"node:path";import{readProjectTarget as p,DEFAULT_TARGET as m,readServiceBindings as D}from"@lunora/codegen";import{DEV_VARS_FILE as g,parseDevVariableEntries as S,D1_PLACEHOLDER_ID as N,isPlaceholderValue as I,readProjectDependencies as T,discoverSchemaInfo as U,inferLunoraBindings as P,resolveSchemaDirectory as B,probeCelldToolchain as F}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as h,resolveObservabilitySampling as G,findWranglerFile as L,readWranglerJsonc as j,buildBindingManifest as M,validateWranglerProject as V,UNEXPORTED_CLASS_MARKER as k,detectCloudflareCliConfig as W,collectExportGaps as K}from"@lunora/config/cloudflare";import{a as H,i as z,b as J,c as q,m as Y,d as X,e as Q,f as Z}from"../packem_shared/vectorize-metadata-BDrKVEF4.mjs";import{r as ee,d as ne}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as E}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as oe}from"../packem_shared/command-CB4JM-Jl.mjs";import{i as te}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as _,a as x,b}from"../packem_shared/variables-CPYyJtsL.mjs";const re=(r,o)=>{const e=new Set,n=s=>{for(const[i,c]of Object.entries(s??{}))typeof c=="string"&&c.trim().length>0&&e.add(i)};n(r.vars);for(const s of Object.values(r.env??{}))n(s.vars);const t=f(o,g);if(v(t))try{n(Object.fromEntries(S(R(t,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},se=(r,o,e,n)=>{if(r===void 0||!e)return;const t=re(r,o),s=t.has(_),i=r.ai?.binding;!s&&(typeof i!="string"||i.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${_} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),t.has(x)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${x} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!t.has(b)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${b} into wrangler vars.`,level:"info",message:`no ${b} in vars or ${g} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},ae=(r,o,e)=>{if(r===void 0||!o)return;const n=[];(r.compatibility_flags??[]).includes(h)||n.push("the top level");for(const[t,s]of Object.entries(r.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(h)&&n.push(`env.${t}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${h}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${h} compatibility flag — workersCimdFetch() refuses to build without it.`})},$=r=>{const{logs:o,traces:e}=G(r);return Object.entries({logs:o,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},ie=(r,o)=>{if(r===void 0)return;const e=[],n=$(r.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[t,s]of Object.entries(r.env??{})){if(s.observability===void 0)continue;const i=$(s.observability);i.length>0&&e.push(`${i.join(" + ")} (env.${t})`)}e.length!==0&&o.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},C={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},A=["Argo Smart Routing","Log Explorer"],ce=r=>{const o=[["top level",r],...Object.entries(r.env??{}).flatMap(([n,t])=>t?[[`env.${n}`,t]]:[])],e=new Map;for(const[n,t]of o)for(const s of M(t).bindings)C[s.type]!==void 0&&e.set(s.type,[...e.get(s.type)??[],n]);return e},le=(r,o)=>{if((p(r)??m)!=="cloudflare")return;const e=L(r),n=e===void 0?void 0:j(e).parsed;if(n!==void 0)for(const[t,s]of ce(n)){const i=C[t]??t;o.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${i} is bound (${s.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}o.push({code:"paid-product-unknown",level:"info",message:`enablement of ${A.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${A.length>1?"them":"it"}.`})},de=(r,o)=>{for(const e of D(r).services)for(const n of e.publicScopes){const t=n===""?"":` (env.${n})`;o.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${t}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${t}; a custom domain set elsewhere would also be public.`})}},O=r=>{const o=L(r);if(o===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=j(o);return{parsed:e,path:o}},ue=(r,o,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(o===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:t}=V({projectRoot:r});for(const c of t.errors.filter(a=>a.includes(k)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of t.warnings.filter(a=>a.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:c});const s=c=>c.includes(k)||c.includes("SHARD");for(const c of t.errors.filter(a=>!s(a)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:c});for(const c of t.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const i=t.errors.find(c=>c.includes("SHARD"));i===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:i})},fe=(r,o)=>{v(f(r,"lunora.json"))&&o.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},pe=(r,o)=>{const e=W(r);e!==void 0&&o.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},me=(r,o)=>{r===void 0||r.limits?.cpu_ms!==void 0||o.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},he=(r,o)=>{const e=(r?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&o.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},ge=(r,o)=>{const{error:e,info:n}=U(r,"lunora");if(e!==void 0){o.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const t of n?.vectorMetadata??[]){const s=Y(t.kind);if(s===void 0){o.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${t.index}" declares metadata "${t.property}", whose type Vectorize cannot filter on.`});continue}o.push({code:"vector-metadata-index-required",fix:`wrangler ${X({index:t.index,property:t.property,type:s}).join(" ")}`,level:"info",message:`vector index "${t.index}" filters on metadata "${t.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ve=(r,o,e)=>{if(o===void 0)return;const n=(p(r)??m)==="celld",t=(o.d1_databases??[]).filter(Boolean);for(const s of t){const i=typeof s.database_id=="string"?s.database_id:"";if(n?z(i)&&i!==N:J(i)){const a=typeof s.binding=="string"&&s.binding.length>0?s.binding:"<unnamed>";e.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${a}" has a placeholder database_id ("${i||"<empty>"}").`})}}},be=(r,o)=>{if(r===void 0)return;const e=(r.send_email??[]).filter(Boolean);for(const n of e){const t=typeof n.destination_address=="string"?n.destination_address:"";if(t!==""&&I(t)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";o.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${t}").`})}}},we=(r,o)=>{const e=f(r,g);if(!v(e))return;let n;try{n=R(e,"utf8")}catch{return}const t=S(n).filter(s=>q(s.key)&&I(s.value)).map(s=>s.key);t.length>0&&o.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${g} has unfilled secret value(s): ${t.join(", ")}.`})},ye=(r,o)=>{const{source:e}=ee({cwd:r});e===void 0?o.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):o.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ne(e)}).`})},ke=async(r,o)=>{try{return await P({projectRoot:r,schemaDir:B(r)})}catch(e){o.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},_e=(r,o)=>{const e=K(r),n=[...r.containers.map(t=>({...t,kind:"container"})),...r.workflows.map(t=>({...t,kind:"workflow"})),...r.agents.map(t=>({...t,kind:"agent"}))];for(const t of n.filter(s=>s.exported))o.push({code:"declared-export-ok",level:"pass",message:`${t.kind} "${t.exportName}" is exported by the worker entry.`});for(const t of e)o.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${t.module}"\` to your worker entry (or re-run \`vis generate lunora-${t.kind}\`).`,level:"fail",message:`${t.kind} "${t.exportName}" is declared but ${t.className} is not exported by the worker entry.`})},xe=/^[\^~><= ]+/u,$e=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ae=r=>{const o=r.replace(xe,"").trim(),e=$e.exec(o);if(!e?.groups)return;const{channel:n,core:t,counter:s}=e.groups;return{channel:n??"",core:t??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:o}},Re=(r,o)=>{const e=T(r),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=Ae(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const t=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),i=new Set(n.map(a=>a.version.channel));if(s.size>1){o.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${t(n)}.`});return}if(i.size>1){o.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...i].map(a=>a===""?"stable":a).join(" + ")}): ${t(n)}.`});return}const c=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(c.length>1){const a=Math.min(...c),l=Math.max(...c);o.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&a===l?`Lunora packages are all at ${[...i][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${t(n)}.`})}},Se=[f("@lunora","cli"),"lunorash"],Ie=(r,o,e)=>{if(o===void 0)return;const n=[];for(const s of Se){const i=f(r,"node_modules",s);if(v(i))try{n.push(y(i))}catch{}}if(n.length===0)return;let t;try{t=y(o)}catch{return}n.some(s=>te(s,t))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${n.join(", ")}).`})},Le={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},je=r=>{const o=new Map,e=(n,t)=>{const s=E(n);s!==void 0&&o.set(s,[...o.get(s)??[],t])};e(r?.account_id,"top level");for(const[n,t]of Object.entries(r?.env??{}))e(t?.account_id,`env.${n}`);return o},Ee=async(r,o,e,n)=>{if((p(r)??m)!=="cloudflare")return;const s=E((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...je(o)],i=s.length===0?[[void 0,[]]]:s,c=await Promise.all(i.map(async([a,l])=>({accountId:a,blocks:l,budget:await Q({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of c)n.push({...Le[d.verdict],message:c.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},Ce="CELLD_BUCKET is not set — a live `lunora deploy` needs it to name the fleet bucket; `lunora dev` and a dry run do not.",Oe=async(r,o,e)=>{if((p(r)??m)!=="celld")return;const n={...process.env,...o.environment},t=await F({dryRun:!0,env:n,purpose:"deploy"}),s=(n.CELLD_BUCKET??"").trim()===""?[...t.warnings,Ce]:t.warnings;for(const i of t.errors)e.push({code:"celld-toolchain-missing",level:"fail",message:i});for(const i of s)e.push({code:"celld-toolchain-warn",level:"warn",message:i});t.errors.length===0&&s.length===0&&e.push({code:"celld-toolchain-ok",level:"pass",message:"celld, esbuild and CELLD_BUCKET are in place for a deploy."})},De={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},Ne=async(r,o,e,n,t)=>{if(e===void 0||o===void 0||(p(r)??m)!=="cloudflare")return;const s=[["",o],...Object.entries(o.env??{}).map(([a,l])=>[`env.${a}: `,l])],i=new Map;for(const[a,l]of s){const d=l.account_id??o.account_id;for(const u of l.artifacts??[]){const w=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!i.has(w)&&i.set(w,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const c=await Promise.all([...i.values()].map(async({label:a,...l})=>({check:await Z({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:a})));for(const{check:a,label:l}of c)t.push({...De[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Te=async r=>{const o=r.cwd??process.cwd(),e=[],{parsed:n,path:t}=O(o);ue(o,n,t,e),pe(o,e),ve(o,n,e),be(n,e),me(n,e),he(n,e),ie(n,e),we(o,e),ye(o,e),Re(o,e),ge(o,e),fe(o,e),Ie(o,r.executablePath??process.argv[1],e),de(o,e),le(o,e);const s=await ke(o,e);s!==void 0&&_e(s,e),se(n,o,s?.usesAi===!0,e),await Oe(o,r,e),await Ee(o,n,r,e),await Ne(o,n,s?.jurisdiction,r,e),ae(n,s?.usesCimdWorkers===!0,e);const i={fail:0,info:0,pass:0,warn:0};for(const a of e)i[a.level]+=1;const c=i.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:i}},Ue={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Pe=(r,o)=>{o.info("lunora doctor — project preflight");for(const t of r.findings){const s=`[${Ue[t.level]}] ${t.message}`;t.level==="fail"?o.error(s):t.level==="warn"?o.warn(s):o.info(s),t.fix!==void 0&&t.level!=="pass"&&o.info(` fix: ${t.fix}`)}const{fail:e,warn:n}=r.summary;e>0?o.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?o.warn(`0 failures, ${String(n)} warning(s).`):o.success("all checks passed.")},Be=async r=>{const{logger:o}=r,e=await Te({...r});return Pe(e,o),e},Xe=oe(async({cwd:r,format:o,logger:e,options:n})=>{if(n.fix===!0){const{path:s}=O(r),i=await H({configPath:s,cwd:r,dryRun:n.dryRun===!0,logger:e});for(const c of i.applied)e.info(`fix: ${c}`);for(const c of i.skipped)e.warn(`not fixed: ${c}`)}const t=await Be({cwd:r,format:o,logger:e});return{code:t.code,data:{findings:t.findings,summary:t.summary}}});export{Xe as execute,Te as runDoctor,Be as runDoctorCommand};
|
|
1
|
+
import{existsSync as v,readFileSync as R,realpathSync as y}from"node:fs";import{join as f}from"node:path";import{readProjectTarget as p,DEFAULT_TARGET as m,readServiceBindings as D}from"@lunora/codegen";import{DEV_VARS_FILE as g,parseDevVariableEntries as S,D1_PLACEHOLDER_ID as N,isPlaceholderValue as I,readProjectDependencies as T,discoverSchemaInfo as U,inferLunoraBindings as P,resolveSchemaDirectory as B,probeCelldToolchain as F}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as h,resolveObservabilitySampling as G,findWranglerFile as L,readWranglerJsonc as j,buildBindingManifest as M,validateWranglerProject as V,UNEXPORTED_CLASS_MARKER as k,detectCloudflareCliConfig as W,collectExportGaps as K}from"@lunora/config/cloudflare";import{a as H,i as z,b as J,c as q,m as Y,d as X,e as Q,f as Z}from"../packem_shared/vectorize-metadata-DOB1akh6.mjs";import{r as ee,d as ne}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as E}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as oe}from"../packem_shared/command-CB4JM-Jl.mjs";import{i as te}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as _,a as x,b}from"../packem_shared/variables-CPYyJtsL.mjs";const re=(r,o)=>{const e=new Set,n=s=>{for(const[i,c]of Object.entries(s??{}))typeof c=="string"&&c.trim().length>0&&e.add(i)};n(r.vars);for(const s of Object.values(r.env??{}))n(s.vars);const t=f(o,g);if(v(t))try{n(Object.fromEntries(S(R(t,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},se=(r,o,e,n)=>{if(r===void 0||!e)return;const t=re(r,o),s=t.has(_),i=r.ai?.binding;!s&&(typeof i!="string"||i.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${_} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),t.has(x)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${x} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!t.has(b)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${b} into wrangler vars.`,level:"info",message:`no ${b} in vars or ${g} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},ae=(r,o,e)=>{if(r===void 0||!o)return;const n=[];(r.compatibility_flags??[]).includes(h)||n.push("the top level");for(const[t,s]of Object.entries(r.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(h)&&n.push(`env.${t}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${h}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${h} compatibility flag — workersCimdFetch() refuses to build without it.`})},$=r=>{const{logs:o,traces:e}=G(r);return Object.entries({logs:o,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},ie=(r,o)=>{if(r===void 0)return;const e=[],n=$(r.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[t,s]of Object.entries(r.env??{})){if(s.observability===void 0)continue;const i=$(s.observability);i.length>0&&e.push(`${i.join(" + ")} (env.${t})`)}e.length!==0&&o.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},C={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},A=["Argo Smart Routing","Log Explorer"],ce=r=>{const o=[["top level",r],...Object.entries(r.env??{}).flatMap(([n,t])=>t?[[`env.${n}`,t]]:[])],e=new Map;for(const[n,t]of o)for(const s of M(t).bindings)C[s.type]!==void 0&&e.set(s.type,[...e.get(s.type)??[],n]);return e},le=(r,o)=>{if((p(r)??m)!=="cloudflare")return;const e=L(r),n=e===void 0?void 0:j(e).parsed;if(n!==void 0)for(const[t,s]of ce(n)){const i=C[t]??t;o.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${i} is bound (${s.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}o.push({code:"paid-product-unknown",level:"info",message:`enablement of ${A.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${A.length>1?"them":"it"}.`})},de=(r,o)=>{for(const e of D(r).services)for(const n of e.publicScopes){const t=n===""?"":` (env.${n})`;o.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${t}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${t}; a custom domain set elsewhere would also be public.`})}},O=r=>{const o=L(r);if(o===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=j(o);return{parsed:e,path:o}},ue=(r,o,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(o===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:t}=V({projectRoot:r});for(const c of t.errors.filter(a=>a.includes(k)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of t.warnings.filter(a=>a.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:c});const s=c=>c.includes(k)||c.includes("SHARD");for(const c of t.errors.filter(a=>!s(a)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:c});for(const c of t.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const i=t.errors.find(c=>c.includes("SHARD"));i===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:i})},fe=(r,o)=>{v(f(r,"lunora.json"))&&o.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},pe=(r,o)=>{const e=W(r);e!==void 0&&o.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},me=(r,o)=>{r===void 0||r.limits?.cpu_ms!==void 0||o.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},he=(r,o)=>{const e=(r?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&o.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},ge=(r,o)=>{const{error:e,info:n}=U(r,"lunora");if(e!==void 0){o.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const t of n?.vectorMetadata??[]){const s=Y(t.kind);if(s===void 0){o.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${t.index}" declares metadata "${t.property}", whose type Vectorize cannot filter on.`});continue}o.push({code:"vector-metadata-index-required",fix:`wrangler ${X({index:t.index,property:t.property,type:s}).join(" ")}`,level:"info",message:`vector index "${t.index}" filters on metadata "${t.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ve=(r,o,e)=>{if(o===void 0)return;const n=(p(r)??m)==="celld",t=(o.d1_databases??[]).filter(Boolean);for(const s of t){const i=typeof s.database_id=="string"?s.database_id:"";if(n?z(i)&&i!==N:J(i)){const a=typeof s.binding=="string"&&s.binding.length>0?s.binding:"<unnamed>";e.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${a}" has a placeholder database_id ("${i||"<empty>"}").`})}}},be=(r,o)=>{if(r===void 0)return;const e=(r.send_email??[]).filter(Boolean);for(const n of e){const t=typeof n.destination_address=="string"?n.destination_address:"";if(t!==""&&I(t)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";o.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${t}").`})}}},we=(r,o)=>{const e=f(r,g);if(!v(e))return;let n;try{n=R(e,"utf8")}catch{return}const t=S(n).filter(s=>q(s.key)&&I(s.value)).map(s=>s.key);t.length>0&&o.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${g} has unfilled secret value(s): ${t.join(", ")}.`})},ye=(r,o)=>{const{source:e}=ee({cwd:r});e===void 0?o.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):o.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ne(e)}).`})},ke=async(r,o)=>{try{return await P({projectRoot:r,schemaDir:B(r)})}catch(e){o.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},_e=(r,o)=>{const e=K(r),n=[...r.containers.map(t=>({...t,kind:"container"})),...r.workflows.map(t=>({...t,kind:"workflow"})),...r.agents.map(t=>({...t,kind:"agent"}))];for(const t of n.filter(s=>s.exported))o.push({code:"declared-export-ok",level:"pass",message:`${t.kind} "${t.exportName}" is exported by the worker entry.`});for(const t of e)o.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${t.module}"\` to your worker entry (or re-run \`vis generate lunora-${t.kind}\`).`,level:"fail",message:`${t.kind} "${t.exportName}" is declared but ${t.className} is not exported by the worker entry.`})},xe=/^[\^~><= ]+/u,$e=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ae=r=>{const o=r.replace(xe,"").trim(),e=$e.exec(o);if(!e?.groups)return;const{channel:n,core:t,counter:s}=e.groups;return{channel:n??"",core:t??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:o}},Re=(r,o)=>{const e=T(r),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=Ae(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const t=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),i=new Set(n.map(a=>a.version.channel));if(s.size>1){o.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${t(n)}.`});return}if(i.size>1){o.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...i].map(a=>a===""?"stable":a).join(" + ")}): ${t(n)}.`});return}const c=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(c.length>1){const a=Math.min(...c),l=Math.max(...c);o.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&a===l?`Lunora packages are all at ${[...i][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${t(n)}.`})}},Se=[f("@lunora","cli"),"lunorash"],Ie=(r,o,e)=>{if(o===void 0)return;const n=[];for(const s of Se){const i=f(r,"node_modules",s);if(v(i))try{n.push(y(i))}catch{}}if(n.length===0)return;let t;try{t=y(o)}catch{return}n.some(s=>te(s,t))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${n.join(", ")}).`})},Le={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},je=r=>{const o=new Map,e=(n,t)=>{const s=E(n);s!==void 0&&o.set(s,[...o.get(s)??[],t])};e(r?.account_id,"top level");for(const[n,t]of Object.entries(r?.env??{}))e(t?.account_id,`env.${n}`);return o},Ee=async(r,o,e,n)=>{if((p(r)??m)!=="cloudflare")return;const s=E((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...je(o)],i=s.length===0?[[void 0,[]]]:s,c=await Promise.all(i.map(async([a,l])=>({accountId:a,blocks:l,budget:await Q({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of c)n.push({...Le[d.verdict],message:c.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},Ce="CELLD_BUCKET is not set — a live `lunora deploy` needs it to name the fleet bucket; `lunora dev` and a dry run do not.",Oe=async(r,o,e)=>{if((p(r)??m)!=="celld")return;const n={...process.env,...o.environment},t=await F({dryRun:!0,env:n,purpose:"deploy"}),s=(n.CELLD_BUCKET??"").trim()===""?[...t.warnings,Ce]:t.warnings;for(const i of t.errors)e.push({code:"celld-toolchain-missing",level:"fail",message:i});for(const i of s)e.push({code:"celld-toolchain-warn",level:"warn",message:i});t.errors.length===0&&s.length===0&&e.push({code:"celld-toolchain-ok",level:"pass",message:"celld, esbuild and CELLD_BUCKET are in place for a deploy."})},De={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},Ne=async(r,o,e,n,t)=>{if(e===void 0||o===void 0||(p(r)??m)!=="cloudflare")return;const s=[["",o],...Object.entries(o.env??{}).map(([a,l])=>[`env.${a}: `,l])],i=new Map;for(const[a,l]of s){const d=l.account_id??o.account_id;for(const u of l.artifacts??[]){const w=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!i.has(w)&&i.set(w,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const c=await Promise.all([...i.values()].map(async({label:a,...l})=>({check:await Z({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:a})));for(const{check:a,label:l}of c)t.push({...De[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Te=async r=>{const o=r.cwd??process.cwd(),e=[],{parsed:n,path:t}=O(o);ue(o,n,t,e),pe(o,e),ve(o,n,e),be(n,e),me(n,e),he(n,e),ie(n,e),we(o,e),ye(o,e),Re(o,e),ge(o,e),fe(o,e),Ie(o,r.executablePath??process.argv[1],e),de(o,e),le(o,e);const s=await ke(o,e);s!==void 0&&_e(s,e),se(n,o,s?.usesAi===!0,e),await Oe(o,r,e),await Ee(o,n,r,e),await Ne(o,n,s?.jurisdiction,r,e),ae(n,s?.usesCimdWorkers===!0,e);const i={fail:0,info:0,pass:0,warn:0};for(const a of e)i[a.level]+=1;const c=i.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:i}},Ue={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Pe=(r,o)=>{o.info("lunora doctor — project preflight");for(const t of r.findings){const s=`[${Ue[t.level]}] ${t.message}`;t.level==="fail"?o.error(s):t.level==="warn"?o.warn(s):o.info(s),t.fix!==void 0&&t.level!=="pass"&&o.info(` fix: ${t.fix}`)}const{fail:e,warn:n}=r.summary;e>0?o.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?o.warn(`0 failures, ${String(n)} warning(s).`):o.success("all checks passed.")},Be=async r=>{const{logger:o}=r,e=await Te({...r});return Pe(e,o),e},Xe=oe(async({cwd:r,format:o,logger:e,options:n})=>{if(n.fix===!0){const{path:s}=O(r),i=await H({configPath:s,cwd:r,dryRun:n.dryRun===!0,logger:e});for(const c of i.applied)e.info(`fix: ${c}`);for(const c of i.skipped)e.warn(`not fixed: ${c}`)}const t=await Be({cwd:r,format:o,logger:e});return{code:t.code,data:{findings:t.findings,summary:t.summary}}});export{Xe as execute,Te as runDoctor,Be as runDoctorCommand};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{readServiceBindings as re,createCodegenProject as te,refreshCodegenProject as ne,findTsconfig as oe,projectConfigCandidatePaths as ae,PROJECT_CONFIG_FILENAMES as ie,runCodegen as V}from"@lunora/codegen";import{runPostCodegenHook as se,resolveLazyFunctions as k,detectAgentRules as B,updateDevServerState as z,readDevServerState as ce,DEV_DAEMON_ENV as G,detectAiAgent as de,readProjectRemotePreference as le,readLiveDevServerState as X,createDiscoveryCache as ue,DEV_HANDOFF_ENV as D,clearDevServerState as fe,claimDevServerState as ge,DEV_LOG_FILE_ENV as ve,
|
|
1
|
+
import{readServiceBindings as re,createCodegenProject as te,refreshCodegenProject as ne,findTsconfig as oe,projectConfigCandidatePaths as ae,PROJECT_CONFIG_FILENAMES as ie,runCodegen as V}from"@lunora/codegen";import{runPostCodegenHook as se,resolveLazyFunctions as k,detectAgentRules as B,updateDevServerState as z,readDevServerState as ce,DEV_DAEMON_ENV as G,detectAiAgent as de,readProjectRemotePreference as le,readLiveDevServerState as X,createDiscoveryCache as ue,DEV_HANDOFF_ENV as D,clearDevServerState as fe,claimDevServerState as ge,DEV_LOG_FILE_ENV as ve,secretSourcesFromBindings as me,inferLunoraBindings as we,resolveSchemaDirectory as he,ensureDevVarsExample as ye,ensureDevVariables as Se,isInteractive as pe,DEV_VARS_FILE as $,DEV_VARS_EXAMPLE_FILE as Ee,fillDevSecrets as be,DEV_BINDINGS_FILE as _e,DEV_STATE_FILE as J,writeCelldDevProjection as ke,claimAgentRulesHint as Pe,AGENT_RULES_HINT as Ce}from"@lunora/config";import{wranglerCodegenInputs as Y,resolveRemoteEnabled as Re,startLocalHyperdrive as De,describeWithheld as Te}from"@lunora/config/cloudflare";import{p as $e}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{w as Ae}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as Oe,watch as A,readFileSync as Fe,statSync as Ie}from"node:fs";import{join as P,dirname as K}from"node:path";import{STUDIO_WRITE_TEMP_SUFFIX as Le,consumeStudioWrite as O,loadStudioAssets as F,studioAssetsStamp as I,createStudioDocumentCache as je,renderStudioHtml as Ne,resolveAdminToken as Me,requestPathname as L,transportRejectionReason as j,SCHEMA_EDIT_ENDPOINT as We,POLICY_SCAFFOLD_ENDPOINT as He,SEED_ENDPOINT as xe,sendStudioDocument as Ue,serveJsonHandler as Ve,isStandaloneModulePath as Be,readStandaloneAsset as ze,assetContentType as Ge,handleSchemaEditRequest as Xe,handlePolicyScaffoldRequest as Je,handleSeedRequest as Ye,applyStudioAssetCache as Ke}from"@lunora/config/studio-host";import{ts as N}from"ts-morph";import{a as Qe}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as Ze}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as qe}from"../packem_shared/command-CB4JM-Jl.mjs";import{a as er}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as C}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{forceJsonLogging as rr}from"../packem_shared/createLogger-4TujevyB.mjs";import{createServer as tr,request as nr}from"node:http";import{connect as or}from"node:net";import{pipeline as ar}from"node:stream";import{c as ir}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as sr}from"node:timers/promises";import{r as cr,d as dr,P as lr,a as ur,b as T,c as fr,s as gr,n as Q,e as vr,f as mr,g as wr,h as hr,i as M,w as yr,j as Sr,k as pr,t as Er,l as br,m as _r,o as kr}from"../packem_shared/plan-lzllz0Cn.mjs";import{b as Pr}from"./handler.mjs";const Cr=100,Rr=/(?:\.[cm]?[jt]sx?|(?:^|[/\\])tsconfig(?:\..+)?\.json)$/u,Dr=300,W=/[/\\]/u,H=e=>{try{return Fe(e,"utf8")}catch{return""}},Tr=e=>{try{const{mtimeMs:r,size:n}=Ie(e);return`${String(r)}:${String(n)}`}catch{return""}},$r=["pnpm-lock.yaml","package-lock.json","yarn.lock","bun.lock","node_modules/.modules.yaml","node_modules/.package-lock.json","node_modules/.yarn-integrity"],Z=e=>{const r=K(e);return r===e?[e]:[e,...Z(r)]},Ar=e=>{const r={...N.sys,onUnRecoverableConfigFileDiagnostic:()=>{},readDirectory:()=>[]},n=N.getParsedCommandLineOfConfigFile(e,{},r);return n===void 0?"":JSON.stringify(n.options)},Or=(e,r)=>{const n=oe(r),o=[...new Set([...ae(r),...ie.map(s=>P(e,s))])].map(s=>`${s}
|
|
2
2
|
${H(s)}`),i=Z(e).flatMap(s=>$r.map(a=>`${P(s,a)}
|
|
3
3
|
${Tr(P(s,a))}`));return[n===void 0?"":`${n}
|
|
4
4
|
${H(n)}
|
|
5
5
|
${Ar(n)}`,...o,...i].join("\0")},Fr=(e,r)=>{let n,t;return{drop:()=>{n=void 0},get:()=>{const o=Or(e,r);return n===void 0||o!==t?(t=o,n=te(r)):ne(n,r),n}}},Ir=(e,r,n,t)=>{const{apiSpec:o,lazyFunctions:i,logger:l,projectRoot:s,target:a}=e;try{const u=V({apiSpec:o,lazyFunctions:k(i),lunoraDirectory:r,project:t.get(),projectRoot:s,target:a,...Y(s)});l.success(`codegen: wrote ${r}/_generated (${n})`),Ze(u.platformDiagnostics,l)}catch(u){return t.drop(),l.error(Qe(u,n)),!1}return!0},Lr=e=>{const r=e.lunoraDirectory??"lunora",n=P(e.projectRoot,r),t=e.debounceMs??Cr;let o=!1,i=!1,l=!1,s,a=0,u=Promise.resolve();const b=Fr(e.projectRoot,n);let w;const c=new Promise(v=>{w=v}),d=(v,m)=>{o||(s={codegen:m||s?.codegen===!0,reason:v},!i&&(i=!0,u=(async()=>{try{for(;s!==void 0;){const h=s;if(s=void 0,!(h.codegen&&!Ir(e,r,h.reason,b))){l=!0;try{(await se({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(a=Date.now())}finally{l=!1}}}}catch(h){e.logger.error(`codegen watch: ${h instanceof Error?h.message:String(h)}`)}finally{i=!1,w()}})()))};d("startup",!0);const f=v=>(e.logger.warn(`codegen watch unavailable (${v}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,s=void 0,u),ready:c,watchAvailable:!1});let g,y;if(!Oe(n))return f(`no such directory: ${n}`);const S=new Set;let p=!1;const _=(v,m)=>{if(l||Date.now()-a<Dr){g&&(clearTimeout(g),g=void 0);let h=!1;for(const E of[...S,v])E!==void 0&&O(E)&&(h=!0);S.clear(),p=!1,h&&d(`change: ${m}`,!1);return}v===void 0?p=!0:S.add(v),g&&clearTimeout(g),g=setTimeout(()=>{const h=[...S].map(ee=>O(ee)),E=p||h.includes(!1);S.clear(),p=!1,d(`change: ${m}`,E)},t)},R=[];try{y=A(n,{recursive:!0},(v,m)=>{if(typeof m!="string"){_(void 0,"?");return}m.split(W).includes("_generated")||m.endsWith(Le)||_(P(n,m),m)});for(const v of re(e.projectRoot).services)if(v.rpcEntrypoint!==void 0){const m=A(K(v.wranglerPath),{recursive:!0},(h,E)=>{typeof E=="string"&&Rr.test(E)&&!E.split(W).includes("node_modules")&&_(void 0,E)});m.on("error",h=>{e.logger.warn(`codegen watch: stopped watching service "${v.name}" (${h.message})`),m.close()}),R.push(m)}}catch(v){y?.close();for(const m of R)m.close();return f(v instanceof Error?v.message:String(v))}const q=y;return{close:()=>{o=!0,s=void 0,g&&clearTimeout(g),q.close();for(const v of R)v.close();return u},ready:c,watchAvailable:!0}},x="/_lunora",jr=3e4,U=(e,r,n,t=jr)=>{const o=nr({headers:{...e.headers,host:n.host},hostname:n.hostname,method:e.method,path:e.url,port:n.port},i=>{o.setTimeout(0),r.writeHead(i.statusCode??502,i.headers),ar(i,r,()=>{})});o.setTimeout(t,()=>{o.destroy(new Error(`no response within ${String(t)}ms`))}),o.on("error",i=>{if(r.headersSent){r.destroy();return}r.statusCode=i.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${i.message})`)}),r.on("close",()=>{r.writableFinished||o.destroy()}),e.pipe(o)},Nr=5e3,Mr=(e,r,n,t)=>{const o=or({host:t.hostname,port:Number(t.port)},()=>{o.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[l,s]of Object.entries(e.headers))if(l!=="host")for(const a of Array.isArray(s)?s:[s])a!==void 0&&i.push(`${l}: ${a}`);i.push(`host: ${t.host}`,"",""),o.write(i.join(`\r
|
|
6
|
-
`)),n.length>0&&o.write(n),o.pipe(r),r.pipe(o)});o.setTimeout(Nr,()=>o.destroy()),o.on("error",()=>r.destroy()),r.on("error",()=>o.destroy())},Wr=async e=>{const r=e.host??"127.0.0.1",n=r==="127.0.0.1"||r==="localhost"||r==="::1",t=new URL(e.workerOrigin);let o=F(e.logger,import.meta.url),i=I(import.meta.url);const l=je(e.cwd,()=>Buffer.from(Ne({adminToken:n?Me(e.cwd):void 0,basePath:"/",dataEditable:n,rulesInstalled:B(e.cwd).installed,runAsIdentity:n,schemaEditable:n,scriptSrc:"/studio.js",styleHref:"/styles.css"}))),s=(c,d,f,g,y)=>{Ke(c,d,y,i)||(d.statusCode=200,d.setHeader("Content-Type",g),d.end(f))},a=(c,d,f)=>{c.statusCode=d,c.setHeader("Content-Type","text/plain"),c.end(f)},u=(c,d,f,g)=>{if(n){Ve(c,d,f,e.cwd,{apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions)});return}a(d,403,g)},b=(c,d,f)=>{const g=c==="/styles.css",y=Be(c);if(!g&&!y)return!1;const S=I(import.meta.url);if(S!==i&&(o=F(e.logger,import.meta.url),i=S),o===void 0)return a(f,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return s(d,f,o.styles,"text/css; charset=utf-8","styles.css"),!0;const p=c.slice(c.lastIndexOf("/")+1),_=ze(p,import.meta.url);return _===void 0?(a(f,404,"Not found"),!0):(s(d,f,_,Ge(p),p),!0)};l();const w=tr((c,d)=>{const f=L(c.url??"/");if(n){const y=j(c,e.logger);if(y!==void 0){a(d,403,y);return}}if(f.startsWith(x)){if(!n){a(d,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}U(c,d,t);return}if(f===We){u(c,d,Xe,"Lunora schema editing is only available on loopback hosts in dev.");return}if(f===He){u(c,d,Je,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(f===xe){u(c,d,Ye,"Lunora data seeding is only available on loopback hosts in dev.");return}if(b(f,c,d))return;const g=c.headers["sec-fetch-mode"];if(n&&typeof g=="string"&&g!=="navigate"){U(c,d,t);return}Ue(d,l())});return w.on("upgrade",(c,d,f)=>{if(!n||j(c,e.logger)!==void 0){d.destroy();return}L(c.url??"").startsWith(x)?Mr(c,d,f,t):d.destroy()}),await new Promise((c,d)=>{w.once("error",f=>{f.code==="EADDRINUSE"?d(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:f})):d(f)}),w.listen(e.port,r,()=>{c()})}),{close:()=>new Promise(c=>{w.close(()=>{c()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},Hr=async e=>{const{cwd:r,logger:n,origin:t,signal:o}=e,i=e.probe??dr,l=cr(e.readyTimeoutMs),s=Date.now()+l,a=()=>o.aborted;for(;!a()&&Date.now()<s;){let u=!1;try{u=await i(t,o)}catch{}if(a()||Date.now()>=s)break;if(u)return z(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),ce(r)?.readyAt!==void 0;try{await sr(lr,void 0,{signal:o})}catch{}}return a()||n.warn(`server did not answer on ${t} within ${String(Math.round(l/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},xr=(e,r,n,t)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),n!==void 0&&e.info(` ➜ Studio: ${n}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),t!==void 0&&e.info(` ➜ Supervisor: ${t} (needs) · ${J} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):r.remote.reason!==void 0&&e.warn(` ➜ Remote: requested but inactive (${r.remote.reason}) — running fully local`));for(const o of r.remote.withheld)e.warn(` ➜ ${Te(o)}`);e.info("")},Ur=(e,r)=>{B(r).installed||!Pe()||(e.info(` ⓘ ${Ce}`),e.info(""))},Vr=async(e,r,n)=>{try{const o=await me({cache:n,projectRoot:r,schemaDir:we(r)}),i=he(o),l=(e.ensureExample??ye)(r,i);if(l.length>0){const s=i.map(a=>a.includes(":")?`${a.replace(":"," (")})`:a);e.logger.info(`Updated .dev.vars.example with secrets for: ${s.join(", ")} (${l.join(", ")})`)}}catch{}(await(e.ensureEnv??Se)({confirm:ir(),cwd:r,info:o=>{e.logger.info(o)}})).status==="declined"&&!pe()&&e.logger.info(`hint: ${$} was not scaffolded (non-interactive run). Copy ${Ee} → ${$} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??be)({cwd:r,info:o=>{e.logger.info(o)}})}catch{}},Br=(e,r,n,t,o)=>{if(e.flavor!=="wrangler")return;t!==void 0&&z(r,{studioUrl:t});let i;try{i=kr(r,n)}catch{}return xr(n,e,t,o),i},zr=(e,r)=>{const n=Number(process.env[D]),t=ge(r,{background:process.env[G]==="1",logFile:process.env[ve],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(n)&&n>0?{supersedePid:n}:void 0);return t.ok?void 0:t.existing},Gr=e=>{const{cwd:r,destination:n,logger:t,plan:o}=e,i=n!==void 0,l=n??_e,s=Ae({destination:l,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:J},logger:i?t:{...t,success:()=>{},warn:()=>{}},projectRoot:r});return s.error!==void 0?i?s:(t.debug?.(`skipped the default binding manifest: ${s.error}`),{}):{written:l}},Xr=async(e,r,n,t)=>{if(r.studioEnabled)try{return await(e.startStudio??Wr)({apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),cwd:n,logger:{warnOnce:o=>{t.warn(o)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(o){t.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},Jr=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(t=>t!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},Yr=(e,r,n,t,o)=>{if(!(e.sidecar===void 0||!br(r)))try{V({apiSpec:r.apiSpec,lazyFunctions:k(r.lazyFunctions),lunoraDirectory:"lunora",projectRoot:n,target:o,...Y(n)})}catch(i){t.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},Kr=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,Qr=(e,r)=>{e.ipv4LoopbackForced&&r.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override.")},Zr=async(e,r,n,t)=>{if(e.celldSession!==!0||e.workerEnabled)return!0;try{for(const o of await(r.writeCelldProjection??ke)({projectRoot:n}))t.warn(o);return!0}catch(o){return t.error(`could not write the celld projection: ${o instanceof Error?o.message:String(o)}`),!1}},qr=async(e,r,n,t,o)=>{try{return e.celldSession===!0?await _r({logger:o,port:e.workerPort,projectRoot:t,start:r.startCelldSession}):n(e.wrangler,o)}catch(i){o.error(`could not start the worker: ${i instanceof Error?i.message:String(i)}`);return}},et=async(e,r,n)=>{const t=await(e.startHyperdrive??De)({onWarning:o=>{n.warn(o)},projectRoot:r});return t!==void 0&&t.bindings.length>0&&n.info(`Hyperdrive ${t.bindings.join(", ")}: embedded Postgres (PGlite), data in .wrangler/state/lunora-pglite. Set CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING> to use your own.`),t},rt=async e=>{const{logger:r}=e,n=ue(),t=e.cwd??process.cwd(),o=e.flavor??vr(t),i=er(t,e.target);if(i.target===void 0)throw new Error(i.error??"unknown deploy target");const{target:l}=i,s=mr(l,o,r);s==="wrangler"&&await Pr(t,r,void 0,l,void 0,n);const a=await wr({...e,flavor:s,target:l}),u={remoteCleanup:a.remote.cleanup,serviceConfigCleanup:a.serviceConfigCleanup};try{const b=Number(process.env[D]),w=X(t);if(w!==void 0&&w.pid!==process.pid&&w.pid!==b)return T(r,w),{code:0,plan:a};const c=zr(a,t);if(c!==void 0)return T(r,c),{code:0,plan:a};(a.flavor==="vite"||a.flavor==="framework-worker")&&(a.wrangler.env={...a.wrangler.env,[D]:String(process.pid)}),a.workerEnabled&&l==="cloudflare"&&(u.hyperdrive=await et(e,t,r)),await Vr(e,t,n),r.info(Kr(a)),hr(r,t),Qr(a,r),a.runsCodegenWatch&&(u.codegen=(e.startCodegen??Lr)({apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),jsonLogs:e.jsonLogs,logger:r,projectRoot:t,target:l})),u.studio=await Xr(e,a,t,r);const d=Gr({cwd:t,destination:e.emitBindings,logger:r,plan:a});if(d.error!==void 0)return r.error(d.error),{code:C.USAGE,plan:a};await u.codegen?.ready;const f=u.studio?.url;a.frameworkHint!==void 0&&r.warn(a.frameworkHint);const g=()=>{a.flavor==="wrangler"&&(u.readyProbe=new AbortController,Hr({cwd:t,logger:r,origin:a.workerOrigin,probe:e.probeReady,signal:u.readyProbe.signal}))};if(!await Zr(a,e,t,r))return{code:C.FAILURE,plan:a};if(!a.workerEnabled)return g(),r.info(Jr(a)),u.tunnel=M({cwd:t,logger:r,plan:a,tunnel:e.tunnel}),{code:await(e.waitForInterrupt??yr)(r),plan:a};Yr(a,e,t,r,l);const y=e.startWorker??Sr,S=await qr(a,e,y,t,r);if(S===void 0)return{code:C.FAILURE,plan:a};const p=a.sidecar===void 0?void 0:y(a.sidecar,r);return g(),u.containerLogs=Br(a,t,r,f,d.written),u.tunnel=M({cwd:t,logger:r,plan:a,tunnel:e.tunnel}),Ur(r,t),{code:await pr(S,p,r),plan:a}}finally{u.readyProbe?.abort(),fe(t,process.pid),await Er(u)}},tt=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),nt=e=>{if(e.local===!0&&e.remote===!0)return"`--local` and `--remote` are mutually exclusive — pass at most one.";const{entries:r,invalid:n}=Q(e.allowMail);if(n.length>0)return`\`--allow-mail\` takes email addresses or '*@domain' — not ${n.map(t=>`"${t}"`).join(", ")}.`;if(r.length>0&&e.tunnel!==!0)return"`--allow-mail` only applies to a tunnel — add `--tunnel`."},ot=e=>e.tunnel===!0?{allowMail:Q(e.allowMail).entries}:void 0,Rt=qe(async({argument:e,cwd:r,logger:n,options:t})=>{const o=t.json===!0,i=ur({cwd:r,json:o,lines:t.lines,logger:n,subcommand:e[0]});if(i!==void 0)return i;const l=process.env[G]==="1",s=l?void 0:de(),a=o||s!==void 0;a&&rr(),s!==void 0&&t.background!==!0&&n.info(`AI agent detected (${s.name} via ${s.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const u=nt(t);if(u!==void 0)return n.error(`dev: ${u}`),{code:C.USAGE};const b=ot(t),w=t.local===!0?!1:Re({configPreference:le(r),envValue:process.env.LUNORA_REMOTE,flag:t.remote});if(!l&&(t.background===!0||s!==void 0)){const c=X(r);return c!==void 0?(T(n,c),{code:0}):(b?.allowMail.length===0&&fr(n),gr({cwd:r,jsonLogs:a,logger:n,options:t,remote:w}))}return rt({apiSpec:$e(t.apiSpec),cwd:r,emitBindings:t.emitBindings,inspectorPort:t.inspectorPort,lazyFunctions:k(t.lazyFunctions),jsonLogs:a,local:t.local,logger:n,port:t.port,remote:w,target:t.target,tunnel:b,workerPort:t.workerPort,...tt(t)})});export{nt as devFlagConflict,Rt as execute,tt as negatableDevFlags,rt as runDevCommand};
|
|
6
|
+
`)),n.length>0&&o.write(n),o.pipe(r),r.pipe(o)});o.setTimeout(Nr,()=>o.destroy()),o.on("error",()=>r.destroy()),r.on("error",()=>o.destroy())},Wr=async e=>{const r=e.host??"127.0.0.1",n=r==="127.0.0.1"||r==="localhost"||r==="::1",t=new URL(e.workerOrigin);let o=F(e.logger,import.meta.url),i=I(import.meta.url);const l=je(e.cwd,()=>Buffer.from(Ne({adminToken:n?Me(e.cwd):void 0,basePath:"/",dataEditable:n,rulesInstalled:B(e.cwd).installed,runAsIdentity:n,schemaEditable:n,scriptSrc:"/studio.js",styleHref:"/styles.css"}))),s=(c,d,f,g,y)=>{Ke(c,d,y,i)||(d.statusCode=200,d.setHeader("Content-Type",g),d.end(f))},a=(c,d,f)=>{c.statusCode=d,c.setHeader("Content-Type","text/plain"),c.end(f)},u=(c,d,f,g)=>{if(n){Ve(c,d,f,e.cwd,{apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions)});return}a(d,403,g)},b=(c,d,f)=>{const g=c==="/styles.css",y=Be(c);if(!g&&!y)return!1;const S=I(import.meta.url);if(S!==i&&(o=F(e.logger,import.meta.url),i=S),o===void 0)return a(f,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return s(d,f,o.styles,"text/css; charset=utf-8","styles.css"),!0;const p=c.slice(c.lastIndexOf("/")+1),_=ze(p,import.meta.url);return _===void 0?(a(f,404,"Not found"),!0):(s(d,f,_,Ge(p),p),!0)};l();const w=tr((c,d)=>{const f=L(c.url??"/");if(n){const y=j(c,e.logger);if(y!==void 0){a(d,403,y);return}}if(f.startsWith(x)){if(!n){a(d,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}U(c,d,t);return}if(f===We){u(c,d,Xe,"Lunora schema editing is only available on loopback hosts in dev.");return}if(f===He){u(c,d,Je,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(f===xe){u(c,d,Ye,"Lunora data seeding is only available on loopback hosts in dev.");return}if(b(f,c,d))return;const g=c.headers["sec-fetch-mode"];if(n&&typeof g=="string"&&g!=="navigate"){U(c,d,t);return}Ue(d,l())});return w.on("upgrade",(c,d,f)=>{if(!n||j(c,e.logger)!==void 0){d.destroy();return}L(c.url??"").startsWith(x)?Mr(c,d,f,t):d.destroy()}),await new Promise((c,d)=>{w.once("error",f=>{f.code==="EADDRINUSE"?d(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:f})):d(f)}),w.listen(e.port,r,()=>{c()})}),{close:()=>new Promise(c=>{w.close(()=>{c()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},Hr=async e=>{const{cwd:r,logger:n,origin:t,signal:o}=e,i=e.probe??dr,l=cr(e.readyTimeoutMs),s=Date.now()+l,a=()=>o.aborted;for(;!a()&&Date.now()<s;){let u=!1;try{u=await i(t,o)}catch{}if(a()||Date.now()>=s)break;if(u)return z(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),ce(r)?.readyAt!==void 0;try{await sr(lr,void 0,{signal:o})}catch{}}return a()||n.warn(`server did not answer on ${t} within ${String(Math.round(l/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},xr=(e,r,n,t)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),n!==void 0&&e.info(` ➜ Studio: ${n}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),t!==void 0&&e.info(` ➜ Supervisor: ${t} (needs) · ${J} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):r.remote.reason!==void 0&&e.warn(` ➜ Remote: requested but inactive (${r.remote.reason}) — running fully local`));for(const o of r.remote.withheld)e.warn(` ➜ ${Te(o)}`);e.info("")},Ur=(e,r)=>{B(r).installed||!Pe()||(e.info(` ⓘ ${Ce}`),e.info(""))},Vr=async(e,r,n)=>{let t;try{t=me(await we({cache:n,projectRoot:r,schemaDir:he(r)}))}catch{}if(t!==void 0)try{const i=(e.ensureExample??ye)(r,t);if(i.length>0){const l=t.map(s=>s.includes(":")?`${s.replace(":"," (")})`:s);e.logger.info(`Updated .dev.vars.example with secrets for: ${l.join(", ")} (${i.join(", ")})`)}}catch{}(await(e.ensureEnv??Se)({confirm:ir(),cwd:r,info:i=>{e.logger.info(i)}})).status==="declined"&&!pe()&&e.logger.info(`hint: ${$} was not scaffolded (non-interactive run). Copy ${Ee} → ${$} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??be)({cwd:r,secretSources:t,info:i=>{e.logger.info(i)}})}catch{}},Br=(e,r,n,t,o)=>{if(e.flavor!=="wrangler")return;t!==void 0&&z(r,{studioUrl:t});let i;try{i=kr(r,n)}catch{}return xr(n,e,t,o),i},zr=(e,r)=>{const n=Number(process.env[D]),t=ge(r,{background:process.env[G]==="1",logFile:process.env[ve],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(n)&&n>0?{supersedePid:n}:void 0);return t.ok?void 0:t.existing},Gr=e=>{const{cwd:r,destination:n,logger:t,plan:o}=e,i=n!==void 0,l=n??_e,s=Ae({destination:l,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:J},logger:i?t:{...t,success:()=>{},warn:()=>{}},projectRoot:r});return s.error!==void 0?i?s:(t.debug?.(`skipped the default binding manifest: ${s.error}`),{}):{written:l}},Xr=async(e,r,n,t)=>{if(r.studioEnabled)try{return await(e.startStudio??Wr)({apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),cwd:n,logger:{warnOnce:o=>{t.warn(o)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(o){t.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},Jr=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(t=>t!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},Yr=(e,r,n,t,o)=>{if(!(e.sidecar===void 0||!br(r)))try{V({apiSpec:r.apiSpec,lazyFunctions:k(r.lazyFunctions),lunoraDirectory:"lunora",projectRoot:n,target:o,...Y(n)})}catch(i){t.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},Kr=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,Qr=(e,r)=>{e.ipv4LoopbackForced&&r.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override.")},Zr=async(e,r,n,t)=>{if(e.celldSession!==!0||e.workerEnabled)return!0;try{for(const o of await(r.writeCelldProjection??ke)({projectRoot:n}))t.warn(o);return!0}catch(o){return t.error(`could not write the celld projection: ${o instanceof Error?o.message:String(o)}`),!1}},qr=async(e,r,n,t,o)=>{try{return e.celldSession===!0?await _r({logger:o,port:e.workerPort,projectRoot:t,start:r.startCelldSession}):n(e.wrangler,o)}catch(i){o.error(`could not start the worker: ${i instanceof Error?i.message:String(i)}`);return}},et=async(e,r,n)=>{const t=await(e.startHyperdrive??De)({onWarning:o=>{n.warn(o)},projectRoot:r});return t!==void 0&&t.bindings.length>0&&n.info(`Hyperdrive ${t.bindings.join(", ")}: embedded Postgres (PGlite), data in .wrangler/state/lunora-pglite. Set CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING> to use your own.`),t},rt=async e=>{const{logger:r}=e,n=ue(),t=e.cwd??process.cwd(),o=e.flavor??vr(t),i=er(t,e.target);if(i.target===void 0)throw new Error(i.error??"unknown deploy target");const{target:l}=i,s=mr(l,o,r);s==="wrangler"&&await Pr(t,r,void 0,l,void 0,n);const a=await wr({...e,flavor:s,target:l}),u={remoteCleanup:a.remote.cleanup,serviceConfigCleanup:a.serviceConfigCleanup};try{const b=Number(process.env[D]),w=X(t);if(w!==void 0&&w.pid!==process.pid&&w.pid!==b)return T(r,w),{code:0,plan:a};const c=zr(a,t);if(c!==void 0)return T(r,c),{code:0,plan:a};(a.flavor==="vite"||a.flavor==="framework-worker")&&(a.wrangler.env={...a.wrangler.env,[D]:String(process.pid)}),a.workerEnabled&&l==="cloudflare"&&(u.hyperdrive=await et(e,t,r)),await Vr(e,t,n),r.info(Kr(a)),hr(r,t),Qr(a,r),a.runsCodegenWatch&&(u.codegen=(e.startCodegen??Lr)({apiSpec:e.apiSpec,lazyFunctions:k(e.lazyFunctions),jsonLogs:e.jsonLogs,logger:r,projectRoot:t,target:l})),u.studio=await Xr(e,a,t,r);const d=Gr({cwd:t,destination:e.emitBindings,logger:r,plan:a});if(d.error!==void 0)return r.error(d.error),{code:C.USAGE,plan:a};await u.codegen?.ready;const f=u.studio?.url;a.frameworkHint!==void 0&&r.warn(a.frameworkHint);const g=()=>{a.flavor==="wrangler"&&(u.readyProbe=new AbortController,Hr({cwd:t,logger:r,origin:a.workerOrigin,probe:e.probeReady,signal:u.readyProbe.signal}))};if(!await Zr(a,e,t,r))return{code:C.FAILURE,plan:a};if(!a.workerEnabled)return g(),r.info(Jr(a)),u.tunnel=M({cwd:t,logger:r,plan:a,tunnel:e.tunnel}),{code:await(e.waitForInterrupt??yr)(r),plan:a};Yr(a,e,t,r,l);const y=e.startWorker??Sr,S=await qr(a,e,y,t,r);if(S===void 0)return{code:C.FAILURE,plan:a};const p=a.sidecar===void 0?void 0:y(a.sidecar,r);return g(),u.containerLogs=Br(a,t,r,f,d.written),u.tunnel=M({cwd:t,logger:r,plan:a,tunnel:e.tunnel}),Ur(r,t),{code:await pr(S,p,r),plan:a}}finally{u.readyProbe?.abort(),fe(t,process.pid),await Er(u)}},tt=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),nt=e=>{if(e.local===!0&&e.remote===!0)return"`--local` and `--remote` are mutually exclusive — pass at most one.";const{entries:r,invalid:n}=Q(e.allowMail);if(n.length>0)return`\`--allow-mail\` takes email addresses or '*@domain' — not ${n.map(t=>`"${t}"`).join(", ")}.`;if(r.length>0&&e.tunnel!==!0)return"`--allow-mail` only applies to a tunnel — add `--tunnel`."},ot=e=>e.tunnel===!0?{allowMail:Q(e.allowMail).entries}:void 0,Rt=qe(async({argument:e,cwd:r,logger:n,options:t})=>{const o=t.json===!0,i=ur({cwd:r,json:o,lines:t.lines,logger:n,subcommand:e[0]});if(i!==void 0)return i;const l=process.env[G]==="1",s=l?void 0:de(),a=o||s!==void 0;a&&rr(),s!==void 0&&t.background!==!0&&n.info(`AI agent detected (${s.name} via ${s.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const u=nt(t);if(u!==void 0)return n.error(`dev: ${u}`),{code:C.USAGE};const b=ot(t),w=t.local===!0?!1:Re({configPreference:le(r),envValue:process.env.LUNORA_REMOTE,flag:t.remote});if(!l&&(t.background===!0||s!==void 0)){const c=X(r);return c!==void 0?(T(n,c),{code:0}):(b?.allowMail.length===0&&fr(n),gr({cwd:r,jsonLogs:a,logger:n,options:t,remote:w}))}return rt({apiSpec:$e(t.apiSpec),cwd:r,emitBindings:t.emitBindings,inspectorPort:t.inspectorPort,lazyFunctions:k(t.lazyFunctions),jsonLogs:a,local:t.local,logger:n,port:t.port,remote:w,target:t.target,tunnel:b,workerPort:t.workerPort,...tt(t)})});export{nt as devFlagConflict,Rt as execute,tt as negatableDevFlags,rt as runDevCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./platform-diagnostics-Cn2g6Jh-.mjs";import"./api-spec-lYyq4vL6.mjs";import{e as u,b as y,r as x,a as D,s as L}from"../packem_chunks/handler.mjs";import"./vectorize-metadata-
|
|
1
|
+
import"./platform-diagnostics-Cn2g6Jh-.mjs";import"./api-spec-lYyq4vL6.mjs";import{e as u,b as y,r as x,a as D,s as L}from"../packem_chunks/handler.mjs";import"./vectorize-metadata-DOB1akh6.mjs";import"./binding-manifest-file-CQ1eQYy1.mjs";import"./command-CB4JM-Jl.mjs";import"./deploy-target-resolve-BTCW1Iv4.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./resolve-target-C_ZloTvd.mjs";import"./health-probe-Bw9JFfIy.mjs";import"./createRecordingSpawner-01ZngIwK.mjs";export{u as execute,y as provisionBindings,x as runDeployCommand,D as runPreDeployPipeline,L as smokeLoadLazyModules};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as A,c as g}from"./cloudflare-credentials-BVmZnDZk.mjs";import{spawnSync as x}from"node:child_process";import{readFileSync as p,writeFileSync as P,existsSync as w}from"node:fs";import{join as E}from"node:path";import{DEV_VARS_FILE as u,parseDevVariableEntries as k,upsertDevVariableLine as N,generateSecretValue as L,writeDevVariablesFileAtomically as F,isPlaceholderValue as y,isMintableSecretKey as K,mintableSecretKeysFor as U,secretSourcesFromBindings as M,inferLunoraBindings as W,resolveSchemaDirectory as V}from"@lunora/config";import{modify as B,applyEdits as Y,parse as z}from"jsonc-parser";import{r as H}from"./admin-token-VdUnvnKW.mjs";import{defaultSpawner as G}from"./createRecordingSpawner-01ZngIwK.mjs";import{toolchainExecArgs as J,detectPackageManager as X}from"@lunora/config/cli";const b=5e3,D=(e,t,s)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${t}", "jurisdiction": "${s}" }`,q=e=>{let t="";try{const{errors:s}=JSON.parse(e.text);t=(s??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return t===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${t}`},Q=async(e,t,s)=>{const{jurisdiction:n,namespace:r}=e;try{const a=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{body:JSON.stringify({jurisdiction:n,namespace:r}),method:"POST",signal:AbortSignal.timeout(b)},path:"/artifacts/namespaces"});return a.ok?{}:{reason:q(a)}}catch(a){return{reason:a instanceof Error?a.message:String(a)}}},Z=async(e,t,s)=>{const n=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(b)},path:`/artifacts/namespaces/${encodeURIComponent(e.namespace)}`}).catch(()=>{}),r=n?.ok===!0?n.body.result:void 0;return typeof r=="object"&&r!==null&&"jurisdiction"in r?r.jurisdiction:void 0},j=(e,t,s,n)=>({fix:`A namespace's jurisdiction cannot change: create one with ${D(e,"<name>",s)}, point the binding's "namespace" at it, and move the repos over.`,message:`${t} is in the "${n}" jurisdiction, but the schema pins data to "${s}".`,verdict:"mismatch"}),ee=async(e,t,s,n)=>{const{jurisdiction:r,namespace:a}=e;let i;if(e.create===!0){if(i=(await Q(e,t,s)).reason,i===void 0)return{changesAccount:!0,message:`created ${n} in the "${r}" jurisdiction, as the schema pins.`,verdict:"ok"};const l=await Z(e,t,s);if(l===r)return{message:`${n} is in the "${r}" jurisdiction, as the schema pins.`,verdict:"ok"};if(typeof l=="string")return j(t,n,r,l)}if(e.missingOk===!0)return{changesAccount:!0,message:`${n} does not exist yet; it will be created in the "${r}" jurisdiction just before the deploy.`,verdict:"ok"};const c=i===void 0?"":` (${i})`,o=e.create===!0?` and could not be created${c}`:"";return{fix:`Create it before the first repo: ${D(t,a,r)}.`,message:`${n} does not exist${o}, and the first repo create() would make it unrestricted — the schema pins data to "${r}".`,verdict:"missing"}},De=async e=>{const{binding:t,jurisdiction:s,namespace:n}=e,r=`Artifacts namespace "${n}" (binding ${t})`,{accountId:a,token:i}=A(e.environment??process.env,e.accountId);if(i===void 0||a===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts edit access, which creating a missing namespace needs) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${r} was not checked against the schema's "${s}".`,verdict:"unchecked"};let c;try{c=await g({accountId:a,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(b)},path:`/artifacts/namespaces/${encodeURIComponent(n)}`})}catch(l){return{message:`the jurisdiction of ${r} could not be read (${l instanceof Error?l.message:String(l)}).`,verdict:"unchecked"}}if(!c.ok&&c.status===404)return ee(e,a,i,r);if(!c.ok)return{...c.status===401||c.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts edit access on account ${a}.`}:{},message:`the jurisdiction of ${r} could not be read (HTTP ${String(c.status)}).`,verdict:"unchecked"};const{result:o}=c.body,d=typeof o=="object"&&o!==null&&"jurisdiction"in o?o.jurisdiction:void 0;return typeof d!="string"?{message:`the jurisdiction of ${r} could not be read (the response carried none).`,verdict:"unchecked"}:d===s?{message:`${r} is in the "${d}" jurisdiction, as the schema pins.`,verdict:"ok"}:j(a,r,s,d)},m=100,f=500,S=10,te=5e3,h="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",ne=e=>e>=f?{fix:h,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(f)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=f-S?{fix:h,message:`the Cloudflare account has ${String(e)} of ${String(f)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=m-S&&e<=m?{fix:h,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(m)} (Paid: ${String(f)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(m)} Free, ${String(f)} Paid).`,verdict:"ok"},je=async(e={})=>{const{accountId:t,token:s}=A(e.environment??process.env,e.accountId);if(s===void 0||t===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const n=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(te)},path:"/workers/durable_objects/namespaces?per_page=1"}),r=n.ok?n.body.result_info:void 0,a=typeof r=="object"&&r!==null&&"total_count"in r?r.total_count:void 0;return typeof a!="number"?{message:`the account's Durable Object class count could not be read${n.ok?"":` (HTTP ${String(n.status)})`}.`,verdict:"unchecked"}:ne(a)}catch(n){return{message:`the account's Durable Object class count could not be read (${n instanceof Error?n.message:String(n)}).`,verdict:"unchecked"}}},$=e=>e.endsWith("S")?e.slice(0,-1):e,T=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(t=>t.length>0),C=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),O=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],re=new RegExp(`(?:${[...C,...O.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),se=e=>T(e).some(t=>t==="PUBLIC"||t==="PUBLISHABLE"),ae=e=>{if(se(e))return!1;const t=T(e);if(t.some(n=>C.has($(n))))return!0;const s=$(t.join("_"));return O.some(n=>s===n||s.endsWith(`_${n}`))||re.test(e)},R=e=>{const t=e.trim();return t===""||t.startsWith("<")&&t.endsWith(">")},ie=/replace[-_\s]?(?:with|me)(?![a-z])/iu,Te=e=>R(e)||ie.test(e),ce=e=>R(e)||e.trim().toLowerCase().includes("replace"),I=/\r?\n/u,oe=async(e,t)=>{const{args:s,command:n}=J(X(t),{args:e,tool:"wrangler"});try{const r=await G({args:s,captureStderr:!0,captureStdoutSilently:!0,command:n,cwd:t});return{code:r.code,stderr:r.stderr??"",stdout:r.stdout??""}}catch(r){return{code:1,stderr:r instanceof Error?r.message:String(r),stdout:""}}},v=async(e,t)=>{const s=await e(["d1","list","--json"],t);if(s.code!==0)return;let n;try{n=JSON.parse(s.stdout)}catch{return}if(!Array.isArray(n))return;const r=new Map;for(const a of n)typeof a.name=="string"&&typeof a.uuid=="string"&&r.set(a.name,a.uuid);return r},de=e=>{const t=z(e);return(Array.isArray(t?.d1_databases)?t.d1_databases:[]).flatMap((n,r)=>{if(n===null||typeof n!="object")return[];const a=n,i=typeof a.database_id=="string"?a.database_id:"";return ce(i)?[{binding:typeof a.binding=="string"&&a.binding!==""?a.binding:"<unnamed>",index:r,name:typeof a.database_name=="string"&&a.database_name!==""?a.database_name:void 0}]:[]})},ue=async(e,t,s,n)=>{const r=await v(s,t.cwd);if(r===void 0){n.skipped.push(`D1 "${e.binding}": could not run \`wrangler d1 list --json\`. Check that wrangler is installed in this project and logged in (\`wrangler login\`), then retry.`);return}const a=r.get(e.name);if(a!==void 0)return a;if(t.dryRun){n.applied.push(`would run \`wrangler d1 create ${e.name}\` and write its id into ${e.binding}`);return}const i=await s(["d1","create",e.name],t.cwd);if(i.code!==0){const d=i.stderr.trim()||`exit ${String(i.code)}`;n.skipped.push(`D1 "${e.binding}": \`wrangler d1 create ${e.name}\` failed: ${d}`);return}const o=(await v(s,t.cwd))?.get(e.name);return o===void 0&&n.skipped.push(`D1 "${e.binding}": created ${e.name} but could not read back its id.`),o},le=async(e,t)=>{if(e.configPath===void 0)return;const s=e.runner??oe,n=p(e.configPath,"utf8"),r=de(n);let a=n;for(const i of r){if(i.name===void 0){t.skipped.push(`D1 "${i.binding}" has no database_name, so there is no database to create or reuse.`);continue}const c=await ue({...i,name:i.name},e,s,t);if(c!==void 0){const o=B(a,["d1_databases",i.index,"database_id"],c,{formattingOptions:{eol:`
|
|
2
|
+
`,insertSpaces:!0,tabSize:4}});a=Y(a,o),t.applied.push(`${i.binding}: database_id set to the id of D1 "${i.name}"`)}}!e.dryRun&&a!==n&&P(e.configPath,a)},fe=e=>{const t=x("git",["check-ignore","-q",u],{cwd:e,stdio:"ignore"});if(t.status===0)return!0;if(t.status===1)return!1;const s=E(e,".gitignore");return w(s)&&p(s,"utf8").split(I).some(n=>n.trim()===u)},me=async(e,t)=>{try{return U(M(await W({projectRoot:e,schemaDir:V(e)})))}catch{t.skipped.push(`${u}: could not read the project's bindings, so the relay key was not checked against its role.`);return}},ge=(e,t,s,n,r)=>{const a=[],i=new Set(t.split(I).flatMap(c=>{const[o]=k(c);return o!==void 0&&!y(o.value)?[o.key]:[]}));H({cwd:e}).source===void 0&&!i.has("LUNORA_ADMIN_TOKEN")&&a.push("LUNORA_ADMIN_TOKEN");for(const c of s)!ae(c.key)||!y(c.value)||i.has(c.key)||(K(c.key,c.value,r)?a.push(c.key):n.skipped.push(`${u}: ${c.key} is a provider key and cannot be minted here; fill it in by hand.`));return a},he=async(e,t)=>{const s=E(e.cwd,u),n=w(s)?p(s,"utf8"):"",r=ge(e.cwd,n,k(n),t,await me(e.cwd,t));if(r.length===0)return;if(!fe(e.cwd)){t.skipped.push(`${u} is not in .gitignore, so no secret is written there. Add \`${u}\` to .gitignore first.`);return}if(e.dryRun){t.applied.push(`would mint ${r.join(", ")} into ${u}`);return}let a=n;for(const i of r)a=N(a,i,L());F(s,a),t.applied.push(`minted ${r.join(", ")} into ${u}`)},Ce=async e=>{const t={applied:[],skipped:[]};return await le(e,t),await he(e,t),t},Oe=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},pe=/already (?:exists|indexed)|duplicate/iu,_=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],be=async(e,t)=>{try{return await e(t)}catch(s){return{code:1,stderr:s instanceof Error?s.message:String(s)}}},Re=async e=>{const{cwd:t,entries:s,exec:n,logger:r,spawner:a}=e,i=[];for(const c of s){const o=await be(a,{args:[...n.args,..._(c)],captureStderr:!0,command:n.command,cwd:t,stdoutToStderr:!0});if(o.code===0){i.push({entry:c,status:"created"});continue}const d=`${o.stderr??""}${o.stdout??""}`;if(pe.test(d)){i.push({entry:c,status:"exists"});continue}i.push({entry:c,error:d.trim()||`exit code ${String(o.code)}`,status:"failed"}),r.warn(`could not create the Vectorize metadata index for "${c.property}" on "${c.index}" — filters on that property will match nothing until it exists. Run: wrangler ${_(c).join(" ")}`)}return i};export{Ce as a,ce as b,ae as c,_ as d,je as e,De as f,Re as g,Te as i,Oe as m};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/cli",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.439",
|
|
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",
|
|
@@ -58,22 +58,22 @@
|
|
|
58
58
|
"@bomb.sh/tab": "0.0.22",
|
|
59
59
|
"@lunora/advisor": "1.0.0-alpha.260",
|
|
60
60
|
"@lunora/bindings": "1.0.0-alpha.136",
|
|
61
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
62
|
-
"@lunora/config": "1.0.0-alpha.
|
|
61
|
+
"@lunora/codegen": "1.0.0-alpha.361",
|
|
62
|
+
"@lunora/config": "1.0.0-alpha.415",
|
|
63
63
|
"@lunora/container": "1.0.0-alpha.93",
|
|
64
64
|
"@lunora/d1": "1.0.0-alpha.210",
|
|
65
65
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
66
66
|
"@lunora/mcp": "1.0.0-alpha.265",
|
|
67
67
|
"@lunora/runtime": "1.0.0-alpha.242",
|
|
68
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
69
|
-
"@visulima/cerebro": "
|
|
68
|
+
"@lunora/seed": "1.0.0-alpha.259",
|
|
69
|
+
"@visulima/cerebro": "4.0.1",
|
|
70
70
|
"@visulima/error": "6.1.0",
|
|
71
|
-
"@visulima/fs": "
|
|
72
|
-
"@visulima/pail": "
|
|
73
|
-
"@visulima/path": "
|
|
71
|
+
"@visulima/fs": "7.0.0",
|
|
72
|
+
"@visulima/pail": "6.0.0",
|
|
73
|
+
"@visulima/path": "5.0.0",
|
|
74
74
|
"@visulima/spinner": "1.0.1",
|
|
75
|
-
"@visulima/tui": "
|
|
76
|
-
"@visulima/tui-kit": "1.0.
|
|
75
|
+
"@visulima/tui": "5.0.0",
|
|
76
|
+
"@visulima/tui-kit": "1.0.34",
|
|
77
77
|
"adm-zip": "0.6.1",
|
|
78
78
|
"csv-parse": "7.0.3",
|
|
79
79
|
"giget": "3.3.1",
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{r as A,c as g}from"./cloudflare-credentials-BVmZnDZk.mjs";import{spawnSync as x}from"node:child_process";import{readFileSync as p,writeFileSync as P,existsSync as E}from"node:fs";import{join as w}from"node:path";import{DEV_VARS_FILE as l,parseDevVariableEntries as k,upsertDevVariableLine as N,generateSecretValue as L,writeDevVariablesFileAtomically as U,isPlaceholderValue as S,isMintableSecretKey as K}from"@lunora/config";import{modify as F,applyEdits as M,parse as W}from"jsonc-parser";import{r as V}from"./admin-token-VdUnvnKW.mjs";import{defaultSpawner as Y}from"./createRecordingSpawner-01ZngIwK.mjs";import{toolchainExecArgs as B,detectPackageManager as z}from"@lunora/config/cli";const b=5e3,D=(e,t,s)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${t}", "jurisdiction": "${s}" }`,H=e=>{let t="";try{const{errors:s}=JSON.parse(e.text);t=(s??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return t===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${t}`},G=async(e,t,s)=>{const{jurisdiction:n,namespace:r}=e;try{const a=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{body:JSON.stringify({jurisdiction:n,namespace:r}),method:"POST",signal:AbortSignal.timeout(b)},path:"/artifacts/namespaces"});return a.ok?{}:{reason:H(a)}}catch(a){return{reason:a instanceof Error?a.message:String(a)}}},J=async(e,t,s)=>{const n=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(b)},path:`/artifacts/namespaces/${encodeURIComponent(e.namespace)}`}).catch(()=>{}),r=n?.ok===!0?n.body.result:void 0;return typeof r=="object"&&r!==null&&"jurisdiction"in r?r.jurisdiction:void 0},j=(e,t,s,n)=>({fix:`A namespace's jurisdiction cannot change: create one with ${D(e,"<name>",s)}, point the binding's "namespace" at it, and move the repos over.`,message:`${t} is in the "${n}" jurisdiction, but the schema pins data to "${s}".`,verdict:"mismatch"}),X=async(e,t,s,n)=>{const{jurisdiction:r,namespace:a}=e;let i;if(e.create===!0){if(i=(await G(e,t,s)).reason,i===void 0)return{changesAccount:!0,message:`created ${n} in the "${r}" jurisdiction, as the schema pins.`,verdict:"ok"};const u=await J(e,t,s);if(u===r)return{message:`${n} is in the "${r}" jurisdiction, as the schema pins.`,verdict:"ok"};if(typeof u=="string")return j(t,n,r,u)}if(e.missingOk===!0)return{changesAccount:!0,message:`${n} does not exist yet; it will be created in the "${r}" jurisdiction just before the deploy.`,verdict:"ok"};const c=i===void 0?"":` (${i})`,o=e.create===!0?` and could not be created${c}`:"";return{fix:`Create it before the first repo: ${D(t,a,r)}.`,message:`${n} does not exist${o}, and the first repo create() would make it unrestricted — the schema pins data to "${r}".`,verdict:"missing"}},_e=async e=>{const{binding:t,jurisdiction:s,namespace:n}=e,r=`Artifacts namespace "${n}" (binding ${t})`,{accountId:a,token:i}=A(e.environment??process.env,e.accountId);if(i===void 0||a===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts edit access, which creating a missing namespace needs) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${r} was not checked against the schema's "${s}".`,verdict:"unchecked"};let c;try{c=await g({accountId:a,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(b)},path:`/artifacts/namespaces/${encodeURIComponent(n)}`})}catch(u){return{message:`the jurisdiction of ${r} could not be read (${u instanceof Error?u.message:String(u)}).`,verdict:"unchecked"}}if(!c.ok&&c.status===404)return X(e,a,i,r);if(!c.ok)return{...c.status===401||c.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts edit access on account ${a}.`}:{},message:`the jurisdiction of ${r} could not be read (HTTP ${String(c.status)}).`,verdict:"unchecked"};const{result:o}=c.body,d=typeof o=="object"&&o!==null&&"jurisdiction"in o?o.jurisdiction:void 0;return typeof d!="string"?{message:`the jurisdiction of ${r} could not be read (the response carried none).`,verdict:"unchecked"}:d===s?{message:`${r} is in the "${d}" jurisdiction, as the schema pins.`,verdict:"ok"}:j(a,r,s,d)},m=100,f=500,$=10,q=5e3,h="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",Q=e=>e>=f?{fix:h,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(f)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=f-$?{fix:h,message:`the Cloudflare account has ${String(e)} of ${String(f)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=m-$&&e<=m?{fix:h,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(m)} (Paid: ${String(f)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(m)} Free, ${String(f)} Paid).`,verdict:"ok"},Ae=async(e={})=>{const{accountId:t,token:s}=A(e.environment??process.env,e.accountId);if(s===void 0||t===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const n=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(q)},path:"/workers/durable_objects/namespaces?per_page=1"}),r=n.ok?n.body.result_info:void 0,a=typeof r=="object"&&r!==null&&"total_count"in r?r.total_count:void 0;return typeof a!="number"?{message:`the account's Durable Object class count could not be read${n.ok?"":` (HTTP ${String(n.status)})`}.`,verdict:"unchecked"}:Q(a)}catch(n){return{message:`the account's Durable Object class count could not be read (${n instanceof Error?n.message:String(n)}).`,verdict:"unchecked"}}},y=e=>e.endsWith("S")?e.slice(0,-1):e,T=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(t=>t.length>0),C=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),O=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],Z=new RegExp(`(?:${[...C,...O.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),ee=e=>T(e).some(t=>t==="PUBLIC"||t==="PUBLISHABLE"),te=e=>{if(ee(e))return!1;const t=T(e);if(t.some(n=>C.has(y(n))))return!0;const s=y(t.join("_"));return O.some(n=>s===n||s.endsWith(`_${n}`))||Z.test(e)},R=e=>{const t=e.trim();return t===""||t.startsWith("<")&&t.endsWith(">")},ne=/replace[-_\s]?(?:with|me)(?![a-z])/iu,Ee=e=>R(e)||ne.test(e),re=e=>R(e)||e.trim().toLowerCase().includes("replace"),I=/\r?\n/u,se=async(e,t)=>{const{args:s,command:n}=B(z(t),{args:e,tool:"wrangler"});try{const r=await Y({args:s,captureStderr:!0,captureStdoutSilently:!0,command:n,cwd:t});return{code:r.code,stderr:r.stderr??"",stdout:r.stdout??""}}catch(r){return{code:1,stderr:r instanceof Error?r.message:String(r),stdout:""}}},v=async(e,t)=>{const s=await e(["d1","list","--json"],t);if(s.code!==0)return;let n;try{n=JSON.parse(s.stdout)}catch{return}if(!Array.isArray(n))return;const r=new Map;for(const a of n)typeof a.name=="string"&&typeof a.uuid=="string"&&r.set(a.name,a.uuid);return r},ae=e=>{const t=W(e);return(Array.isArray(t?.d1_databases)?t.d1_databases:[]).flatMap((n,r)=>{if(n===null||typeof n!="object")return[];const a=n,i=typeof a.database_id=="string"?a.database_id:"";return re(i)?[{binding:typeof a.binding=="string"&&a.binding!==""?a.binding:"<unnamed>",index:r,name:typeof a.database_name=="string"&&a.database_name!==""?a.database_name:void 0}]:[]})},ie=async(e,t,s,n)=>{const r=await v(s,t.cwd);if(r===void 0){n.skipped.push(`D1 "${e.binding}": could not run \`wrangler d1 list --json\`. Check that wrangler is installed in this project and logged in (\`wrangler login\`), then retry.`);return}const a=r.get(e.name);if(a!==void 0)return a;if(t.dryRun){n.applied.push(`would run \`wrangler d1 create ${e.name}\` and write its id into ${e.binding}`);return}const i=await s(["d1","create",e.name],t.cwd);if(i.code!==0){const d=i.stderr.trim()||`exit ${String(i.code)}`;n.skipped.push(`D1 "${e.binding}": \`wrangler d1 create ${e.name}\` failed: ${d}`);return}const o=(await v(s,t.cwd))?.get(e.name);return o===void 0&&n.skipped.push(`D1 "${e.binding}": created ${e.name} but could not read back its id.`),o},ce=async(e,t)=>{if(e.configPath===void 0)return;const s=e.runner??se,n=p(e.configPath,"utf8"),r=ae(n);let a=n;for(const i of r){if(i.name===void 0){t.skipped.push(`D1 "${i.binding}" has no database_name, so there is no database to create or reuse.`);continue}const c=await ie({...i,name:i.name},e,s,t);if(c!==void 0){const o=F(a,["d1_databases",i.index,"database_id"],c,{formattingOptions:{eol:`
|
|
2
|
-
`,insertSpaces:!0,tabSize:4}});a=M(a,o),t.applied.push(`${i.binding}: database_id set to the id of D1 "${i.name}"`)}}!e.dryRun&&a!==n&&P(e.configPath,a)},oe=e=>{const t=x("git",["check-ignore","-q",l],{cwd:e,stdio:"ignore"});if(t.status===0)return!0;if(t.status===1)return!1;const s=w(e,".gitignore");return E(s)&&p(s,"utf8").split(I).some(n=>n.trim()===l)},de=(e,t,s,n)=>{const r=[],a=new Set(t.split(I).flatMap(i=>{const[c]=k(i);return c!==void 0&&!S(c.value)?[c.key]:[]}));V({cwd:e}).source===void 0&&!a.has("LUNORA_ADMIN_TOKEN")&&r.push("LUNORA_ADMIN_TOKEN");for(const i of s)!te(i.key)||!S(i.value)||a.has(i.key)||(K(i.key,i.value)?r.push(i.key):n.skipped.push(`${l}: ${i.key} is a provider key and cannot be minted here; fill it in by hand.`));return r},ue=(e,t)=>{const s=w(e.cwd,l),n=E(s)?p(s,"utf8"):"",r=de(e.cwd,n,k(n),t);if(r.length===0)return;if(!oe(e.cwd)){t.skipped.push(`${l} is not in .gitignore, so no secret is written there. Add \`${l}\` to .gitignore first.`);return}if(e.dryRun){t.applied.push(`would mint ${r.join(", ")} into ${l}`);return}let a=n;for(const i of r)a=N(a,i,L());U(s,a),t.applied.push(`minted ${r.join(", ")} into ${l}`)},we=async e=>{const t={applied:[],skipped:[]};return await ce(e,t),ue(e,t),t},ke=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},le=/already (?:exists|indexed)|duplicate/iu,_=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],fe=async(e,t)=>{try{return await e(t)}catch(s){return{code:1,stderr:s instanceof Error?s.message:String(s)}}},De=async e=>{const{cwd:t,entries:s,exec:n,logger:r,spawner:a}=e,i=[];for(const c of s){const o=await fe(a,{args:[...n.args,..._(c)],captureStderr:!0,command:n.command,cwd:t,stdoutToStderr:!0});if(o.code===0){i.push({entry:c,status:"created"});continue}const d=`${o.stderr??""}${o.stdout??""}`;if(le.test(d)){i.push({entry:c,status:"exists"});continue}i.push({entry:c,error:d.trim()||`exit code ${String(o.code)}`,status:"failed"}),r.warn(`could not create the Vectorize metadata index for "${c.property}" on "${c.index}" — filters on that property will match nothing until it exists. Run: wrangler ${_(c).join(" ")}`)}return i};export{we as a,re as b,te as c,_ as d,Ae as e,_e as f,De as g,Ee as i,ke as m};
|