@lunora/cli 1.0.0-alpha.122 → 1.0.0-alpha.124

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/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{runCli as s}from"./packem_shared/COMMANDS-P8RHe9Zp.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{runCli as s}from"./packem_shared/COMMANDS-DY2j27E4.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -571,8 +571,10 @@ type CiProvider = "github" | "gitlab";
571
571
  type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
572
572
  /** True when `manager` is on PATH — probed by running `<manager> --version`. Injectable for tests. */
573
573
  type PackageManagerProbe = (manager: PackageManager) => boolean;
574
+ /** The per-framework auth-UI registry items (`auth-ui` resolves to one of these). */
575
+ type AuthUiItem = "auth-ui-angular" | "auth-ui-react" | "auth-ui-solid" | "auth-ui-svelte" | "auth-ui-vue";
574
576
  /** A registry item a feature can install. */
575
- type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | "mail";
577
+ type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | AuthUiItem | "mail";
576
578
  /** A single file the item scaffolds into the project. */
577
579
  interface RegistryFile {
578
580
  /** Source path inside the item dir (e.g. `schema.ts`). */
@@ -686,7 +688,7 @@ interface AddCommandResult {
686
688
  * sub-prompt or alias; every other value IS the registry item name applied
687
689
  * directly (`storage` → the `storage` registry item, etc.).
688
690
  */
689
- type StackFeature = "ai" | "auth" | "backup" | "browser" | "cloudflare-access" | "crons" | "email" | "flags" | "hyperdrive" | "payment" | "presence" | "queue" | "storage" | "workflow";
691
+ type StackFeature = "ai" | "auth" | "auth-ui" | "backup" | "browser" | "cloudflare-access" | "crons" | "email" | "flags" | "hyperdrive" | "payment" | "presence" | "queue" | "storage" | "workflow";
690
692
  /** Customize a resolved manifest before it is written (e.g. inject the chosen R2 bucket name). */
691
693
  type OfferTransformManifest = (manifest: RegistryManifest) => RegistryManifest;
692
694
  /**
@@ -727,6 +729,12 @@ interface OfferDeps {
727
729
  preselected?: ReadonlyArray<StackFeature>;
728
730
  /** The new project's name — seeds smart defaults like the `project-uploads` bucket name. */
729
731
  projectName: string;
732
+ /**
733
+ * Resolve which per-framework auth-UI item (`auth-ui-react|vue|…`) fits the
734
+ * scaffolded project. Injected by the CLI (detected from the template's deps);
735
+ * defaults to `auth-ui-react` when absent so this module stays pure/testable.
736
+ */
737
+ resolveAuthUiItem?: () => string;
730
738
  /** Single-select among the auth providers (TTY-backed in production). */
731
739
  select: (message: string, options: ReadonlyArray<{
732
740
  description?: string;
package/dist/index.d.ts CHANGED
@@ -571,8 +571,10 @@ type CiProvider = "github" | "gitlab";
571
571
  type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
572
572
  /** True when `manager` is on PATH — probed by running `&lt;manager> --version`. Injectable for tests. */
573
573
  type PackageManagerProbe = (manager: PackageManager) => boolean;
574
+ /** The per-framework auth-UI registry items (`auth-ui` resolves to one of these). */
575
+ type AuthUiItem = "auth-ui-angular" | "auth-ui-react" | "auth-ui-solid" | "auth-ui-svelte" | "auth-ui-vue";
574
576
  /** A registry item a feature can install. */
575
- type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | "mail";
577
+ type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | AuthUiItem | "mail";
576
578
  /** A single file the item scaffolds into the project. */
577
579
  interface RegistryFile {
578
580
  /** Source path inside the item dir (e.g. `schema.ts`). */
@@ -686,7 +688,7 @@ interface AddCommandResult {
686
688
  * sub-prompt or alias; every other value IS the registry item name applied
687
689
  * directly (`storage` → the `storage` registry item, etc.).
688
690
  */
689
- type StackFeature = "ai" | "auth" | "backup" | "browser" | "cloudflare-access" | "crons" | "email" | "flags" | "hyperdrive" | "payment" | "presence" | "queue" | "storage" | "workflow";
691
+ type StackFeature = "ai" | "auth" | "auth-ui" | "backup" | "browser" | "cloudflare-access" | "crons" | "email" | "flags" | "hyperdrive" | "payment" | "presence" | "queue" | "storage" | "workflow";
690
692
  /** Customize a resolved manifest before it is written (e.g. inject the chosen R2 bucket name). */
691
693
  type OfferTransformManifest = (manifest: RegistryManifest) => RegistryManifest;
692
694
  /**
@@ -727,6 +729,12 @@ interface OfferDeps {
727
729
  preselected?: ReadonlyArray<StackFeature>;
728
730
  /** The new project's name — seeds smart defaults like the `project-uploads` bucket name. */
729
731
  projectName: string;
732
+ /**
733
+ * Resolve which per-framework auth-UI item (`auth-ui-react|vue|…`) fits the
734
+ * scaffolded project. Injected by the CLI (detected from the template's deps);
735
+ * defaults to `auth-ui-react` when absent so this module stays pure/testable.
736
+ */
737
+ resolveAuthUiItem?: () => string;
730
738
  /** Single-select among the auth providers (TTY-backed in production). */
731
739
  select: (message: string, options: ReadonlyArray<{
732
740
  description?: string;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{COMMANDS as o,VERSION as n,runCli as a}from"./packem_shared/COMMANDS-P8RHe9Zp.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as x}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as u,runDevCommand as s}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as T}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as c}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{M as $,q as rr,k as er}from"./packem_shared/commands-BhX2Bo9B.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,c as insertSchemaExtension,h as pail,j as parseManifest,u as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,s as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,T as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
1
+ import{COMMANDS as o,VERSION as n,runCli as a}from"./packem_shared/COMMANDS-DY2j27E4.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as x}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as u,runDevCommand as s}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as T}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as c}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{M as $,q as rr,k as er}from"./packem_shared/commands-B1SpMXov.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,c as insertSchemaExtension,h as pail,j as parseManifest,u as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,s as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,T as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
@@ -1 +1 @@
1
- import{existsSync as g}from"node:fs";import{findWranglerFile as w}from"@lunora/config";import{join as v,basename as f}from"@visulima/path";import{i as y}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as h,r as b,d as k,s as $}from"../packem_shared/output-format-D7cKB-O5.mjs";import{C as S,B as T}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{o as j,n as C,i as U,a as c,u as x,d as l,b as B,r as L,c as m,e as W,f as u,g as q,h as F,p as M,l as R,j as A}from"../packem_shared/storage-DOvAKGi4.mjs";import{M as D}from"../packem_shared/commands-BhX2Bo9B.mjs";const H=r=>{const o=r.trim().toLowerCase();return F.find(e=>e.value===o||e.label.toLowerCase()===o||o==="auth0"&&e.value==="auth-auth0"||o==="clerk"&&e.value==="auth-clerk")?.value},J=async r=>{if(r.provider!==void 0&&r.provider!==""){const e=H(r.provider);return e===void 0?(r.logger.warn(`add: unknown --provider "${r.provider}" — using "${u}" (email & password).`),u):e}if(r.yes===!0)return u;const o=r.promptSelect??((e,a,s)=>T(e,a,s));return q(o)},d=r=>r.promptText??((o,e)=>S(o,e)),z=async r=>{const o=f(r.cwd??process.cwd());if(r.bucket!==void 0&&r.bucket!==""){const e=U(r.bucket);if(e!==void 0)return e;const a=c(o);return r.logger.warn(`add: "${r.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${a}".`),a}return r.yes===!0?c(o):x(d(r),o)},E=async r=>{const o=e=>{r.logger.warn(`add: ${e}`)};if(r.mailTo!==void 0&&r.mailTo!=="")return l(r.mailTo,o);if(r.yes!==!0)return l(await d(r)(B,{placeholder:"you@yourdomain.com"}),o)},G=async r=>{const o=f(r.cwd??process.cwd());if(r.db!==void 0&&r.db!==""){const e=L(r.db);if(e!==void 0)return e;const a=m(o);return r.logger.warn(`add: "${r.db}" isn't a usable D1 database name — using "${a}".`),a}return r.yes===!0?m(o):W(d(r),o)},I=async(r,o)=>r.kind==="auth"?[await J(o)]:r.kind==="email"?[C]:[r.item],K=async r=>{const o=r.cwd??process.cwd(),e=r.feature===void 0?void 0:j(r.feature);if(e===void 0)return r.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!g(v(o,"lunora"))||w(o)===void 0)return r.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};const a=await I(e,r),s=[];if(a.includes("storage")){const t=await z(r);s.push(i=>M(i,t))}if(a.includes("mail")){const t=await E(r);t!==void 0&&s.push(i=>R(i,t))}if(a.some(t=>t==="auth"||t.startsWith("auth-"))){const t=await G(r);s.push(i=>A(i,t))}const n=s.length>0?t=>{let i=t;for(const p of s)i=p(i);return i}:void 0;return{code:(await D({allowUnsafeSource:r.allowUnsafeSource,cwd:o,from:r.from,logger:r.logger,names:[...a],ref:r.ref,source:r.source,transformManifest:n,yes:!0})).code,items:a}},_=y(async({argument:r,cwd:o,logger:e,options:a})=>{const s=h("add",a.format);if(s!==void 0)return e.error(s),{code:1};const n=$(a.format,e),t=await K({allowUnsafeSource:a.allowUnsafeSource===!0,bucket:a.bucket,cwd:o,db:a.db,feature:r[0],from:a.from,logger:n,mailTo:a.mailTo,provider:a.provider,ref:a.ref,source:a.source,yes:a.yes===!0});return b(a.format)&&k({code:t.code,items:t.items}),{code:t.code}});export{_ as execute,K as runAddFeature};
1
+ import{existsSync as y,readFileSync as $}from"node:fs";import{findWranglerFile as b}from"@lunora/config";import{join as p,basename as h}from"@visulima/path";import{i as k}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S,r as T,d as j,s as U}from"../packem_shared/output-format-D7cKB-O5.mjs";import{B as g,C as x}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as C,r as M,l as R,i as q,o as l,u as B,a as m,b as D,c as F,e as f,f as L,g as d,n as N,h as W,s as u,j as A,k as O,p as G,m as J,q as K}from"../packem_shared/storage-BHSN9Vgb.mjs";import{M as P}from"../packem_shared/commands-B1SpMXov.mjs";const Q=r=>{const e=r.trim().toLowerCase();return O.find(a=>a.value===e||a.label.toLowerCase()===e||e==="auth0"&&a.value==="auth-auth0"||e==="clerk"&&a.value==="auth-clerk")?.value},w=r=>{try{const e=JSON.parse($(p(r,"package.json"),"utf8"));return{...e.dependencies,...e.devDependencies}}catch{return{}}},V=async r=>{const e=r.cwd??process.cwd(),a=W(w(e));return a!==void 0?a:r.yes===!0?(r.logger.warn(`add: couldn't detect your framework — using "${u}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),u):await(r.promptSelect??((o,s,n)=>g(o,s,n)))("Which framework is your app?",A,{default:u})??u},X=async r=>{if(r.provider!==void 0&&r.provider!==""){const a=Q(r.provider);return a===void 0?(r.logger.warn(`add: unknown --provider "${r.provider}" — using "${d}" (email & password).`),d):a}if(r.yes===!0)return d;const e=r.promptSelect??((a,o,s)=>g(a,o,s));return N(e)},c=r=>r.promptText??((e,a)=>x(e,a)),Y=async r=>{const e=h(r.cwd??process.cwd());if(r.bucket!==void 0&&r.bucket!==""){const a=q(r.bucket);if(a!==void 0)return a;const o=l(e);return r.logger.warn(`add: "${r.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${o}".`),o}return r.yes===!0?l(e):B(c(r),e)},Z=async r=>{const e=a=>{r.logger.warn(`add: ${a}`)};if(r.mailTo!==void 0&&r.mailTo!=="")return m(r.mailTo,e);if(r.yes!==!0)return m(await c(r)(D,{placeholder:"you@yourdomain.com"}),e)},z=async r=>{const e=h(r.cwd??process.cwd());if(r.db!==void 0&&r.db!==""){const a=F(r.db);if(a!==void 0)return a;const o=f(e);return r.logger.warn(`add: "${r.db}" isn't a usable D1 database name — using "${o}".`),o}return r.yes===!0?f(e):L(c(r),e)},E=async(r,e)=>r.kind==="auth"?[await X(e)]:r.kind==="auth-ui"?[await V(e)]:r.kind==="email"?[R]:[r.item],H=async r=>{const e=r.cwd??process.cwd(),a=r.feature===void 0?void 0:C(r.feature);if(a===void 0)return r.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!y(p(e,"lunora"))||b(e)===void 0)return r.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(a.kind==="auth-ui"&&M(w(e)))return r.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const o=await E(a,r),s=[];if(o.includes("storage")){const t=await Y(r);s.push(i=>G(i,t))}if(o.includes("mail")){const t=await Z(r);t!==void 0&&s.push(i=>J(i,t))}if(o.some(t=>t==="auth"||t.startsWith("auth-"))){const t=await z(r);s.push(i=>K(i,t))}const n=s.length>0?t=>{let i=t;for(const v of s)i=v(i);return i}:void 0;return{code:(await P({allowUnsafeSource:r.allowUnsafeSource,cwd:e,from:r.from,logger:r.logger,names:[...o],ref:r.ref,source:r.source,transformManifest:n,yes:!0})).code,items:o}},ir=k(async({argument:r,cwd:e,logger:a,options:o})=>{const s=S("add",o.format);if(s!==void 0)return a.error(s),{code:1};const n=U(o.format,a),t=await H({allowUnsafeSource:o.allowUnsafeSource===!0,bucket:o.bucket,cwd:e,db:o.db,feature:r[0],from:o.from,logger:n,mailTo:o.mailTo,provider:o.provider,ref:o.ref,source:o.source,yes:o.yes===!0});return T(o.format)&&j({code:t.code,items:t.items}),{code:t.code}});export{ir as execute,H as runAddFeature};
@@ -1 +1 @@
1
- import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as c,k as f,q as a}from"../packem_shared/commands-BhX2Bo9B.mjs";const i=n(({argument:u,cwd:s,logger:o,options:e})=>{const r=u[0],t=u.slice(1);return r==="add"?c({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,diff:e.diff===!0,dryRun:e.dryRun===!0,from:e.from,json:e.json===!0,logger:o,names:t,overwrite:e.overwrite===!0,ref:e.ref,source:e.source,yes:e.yes===!0}):r==="list"?c({cwd:s,from:e.from,json:e.json===!0,list:!0,logger:o,names:[],ref:e.ref,source:e.source}):r==="view"?f({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,from:e.from,logger:o,names:t,ref:e.ref,source:e.source}):r==="build"?a({check:e.check===!0,from:e.from,logger:o,out:e.out}):(o.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{i as execute};
1
+ import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as c,k as f,q as a}from"../packem_shared/commands-B1SpMXov.mjs";const i=n(({argument:u,cwd:s,logger:o,options:e})=>{const r=u[0],t=u.slice(1);return r==="add"?c({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,diff:e.diff===!0,dryRun:e.dryRun===!0,from:e.from,json:e.json===!0,logger:o,names:t,overwrite:e.overwrite===!0,ref:e.ref,source:e.source,yes:e.yes===!0}):r==="list"?c({cwd:s,from:e.from,json:e.json===!0,list:!0,logger:o,names:[],ref:e.ref,source:e.source}):r==="view"?f({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,from:e.from,logger:o,names:t,ref:e.ref,source:e.source}):r==="build"?a({check:e.check===!0,from:e.from,logger:o,out:e.out}):(o.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{i as execute};
@@ -1,4 +1,4 @@
1
- import{VERSION as J}from"../packem_shared/COMMANDS-P8RHe9Zp.mjs";import{i as W}from"../packem_shared/command-Bjv4VmYA.mjs";import{existsSync as u,readFileSync as y,realpathSync as D,statSync as T,writeFileSync as z,chmodSync as I,renameSync as H,unlinkSync as K,mkdirSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as G,readLiveDevServerState as b}from"@lunora/config";import{join as s,dirname as V,relative as Z}from"@visulima/path";import{P as B,M as Q}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{stringify as X}from"smol-toml";import{modify as x,applyEdits as E,parse as Y}from"jsonc-parser";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const m=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),$=o=>o.transport==="http"?{type:"http",url:o.url}:m(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:m(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:m(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):m(o),io=o=>o.transport==="http"?{url:o.url}:m(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...m(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>X({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),h=[{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:$,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],C=h.map(o=>o.id),uo=o=>h.find(t=>t.id===o.toLowerCase()),v=(o,t)=>{let e=o,r;try{e=D(o),r=T(e).mode}catch{}const n=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(n,t,"utf8"),r!==void 0&&I(n,r),H(n,e)}catch(a){try{K(n)}catch{}throw a}},R={formattingOptions:{insertSpaces:!0,tabSize:4}},k=o=>{const t=[],e=Y(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},g=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),j=(o,t,e)=>{if(!g(o))return;const r=o[t];return g(r)?r[e]:void 0},N=o=>{if(!u(o.path))return"absent";let t;try{t=y(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=k(t);return e.length>0||!g(r)?"invalid":j(r,o.key,o.name)===void 0?"absent":"present"},mo=o=>N(o)==="present",fo=o=>{const{entry:t,force:e=!1,key:r,name:n,path:a}=o;if(!u(a))return q(V(a),{recursive:!0}),v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
1
+ import{VERSION as J}from"../packem_shared/COMMANDS-DY2j27E4.mjs";import{i as W}from"../packem_shared/command-Bjv4VmYA.mjs";import{existsSync as u,readFileSync as y,realpathSync as D,statSync as T,writeFileSync as z,chmodSync as I,renameSync as H,unlinkSync as K,mkdirSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as G,readLiveDevServerState as b}from"@lunora/config";import{join as s,dirname as V,relative as Z}from"@visulima/path";import{P as B,M as Q}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{stringify as X}from"smol-toml";import{modify as x,applyEdits as E,parse as Y}from"jsonc-parser";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const m=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),$=o=>o.transport==="http"?{type:"http",url:o.url}:m(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:m(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:m(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):m(o),io=o=>o.transport==="http"?{url:o.url}:m(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...m(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>X({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),h=[{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:$,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],C=h.map(o=>o.id),uo=o=>h.find(t=>t.id===o.toLowerCase()),v=(o,t)=>{let e=o,r;try{e=D(o),r=T(e).mode}catch{}const n=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(n,t,"utf8"),r!==void 0&&I(n,r),H(n,e)}catch(a){try{K(n)}catch{}throw a}},R={formattingOptions:{insertSpaces:!0,tabSize:4}},k=o=>{const t=[],e=Y(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},g=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),j=(o,t,e)=>{if(!g(o))return;const r=o[t];return g(r)?r[e]:void 0},N=o=>{if(!u(o.path))return"absent";let t;try{t=y(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=k(t);return e.length>0||!g(r)?"invalid":j(r,o.key,o.name)===void 0?"absent":"present"},mo=o=>N(o)==="present",fo=o=>{const{entry:t,force:e=!1,key:r,name:n,path:a}=o;if(!u(a))return q(V(a),{recursive:!0}),v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
2
2
  `),{action:"created",path:a};const i=y(a,"utf8");if(i.trim().length===0)return v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
3
3
  `),{action:"created",path:a};const{errors:l,value:c}=k(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:a};if(!g(c))return{action:"invalid",error:"the file's root is not a JSON object",path:a};const f=c[r];if(f!==void 0&&!g(f))return{action:"invalid",error:`"${r}" is not an object`,path:a};if(j(c,r,n)!==void 0&&!e)return{action:"skipped",path:a};try{const d=x(i,[r,n],t,R);d.length>0&&v(a,E(i,d))}catch(d){return{action:"invalid",error:d instanceof Error?d.message:String(d),path:a}}return{action:"updated",path:a}},go=o=>{const{key:t,name:e,path:r}=o;if(!u(r))return{action:"absent",path:r};let n;try{n=y(r,"utf8")}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}const{errors:a,value:i}=k(n);if(a.length>0)return{action:"invalid",error:`parse error at offset ${String(a[0]?.offset??0)}`,path:r};if(j(i,t,e)===void 0)return{action:"absent",path:r};try{const l=x(n,[t,e],void 0,R);l.length>0&&v(r,E(n,l))}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}return{action:"removed",path:r}},ho=["global","project"],p=(o,t)=>{const e=Z(t,o);return e.length>0&&!e.startsWith("..")?e:o},vo=(o,t)=>{const e=o.paths(t);return ho.flatMap(r=>{const n=e[r];return n===void 0?[]:[{client:o,path:n,scope:r}]})},yo=(o,t,e,r)=>{const n=o.paths(t),a=e==="global"?"project":"global",i=n[e]??(r?void 0:n[a]);if(i!==void 0)return{client:o,path:i,scope:n[e]===void 0?a:e}},$o=o=>h.filter(t=>Object.values(t.paths(o)).some(e=>u(e))),U=(o,t,e,r)=>{if(o.length===0)return t();const n=[];for(const a of o){const i=uo(a);if(i===void 0){e.error(`mcp ${r}: unknown client "${a}". Known clients: ${C.join(", ")}.`);return}n.push(i)}return n},bo=o=>o.client.format==="json",wo="https://lunora.sh/mcp",_="lunora-docs",M="lunora",ko=o=>u(s(o,"lunora"))&&G(o)!==void 0,jo=o=>{const{args:t,command:e}=Q(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},So=o=>({transport:"http",url:o}),Oo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),A=(o,t,e)=>yo(o,Oo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),xo=(o,t,e)=>{const r=A(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:n}=r,a=o.buildEntry(t.spec);if(e.print===!0){const c=p(n,e.cwd);return e.force!==!0&&mo({key:o.key,name:t.name,path:n})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:n}):(e.logger.info(`${o.label} → ${c}
4
4
  ${JSON.stringify({[o.key]:{[t.name]:a}},void 0,4)}`),{action:"printed",path:n})}const i=fo({entry:a,force:e.force===!0,key:o.key,name:t.name,path:n}),l=p(n,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:n}},Eo=(o,t,e)=>{const r=A(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${p(r,e.cwd)}
@@ -1,4 +1,4 @@
1
- import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as k,readdirSync as X,rmSync as _,mkdtempSync as Y,lstatSync as $e,cpSync as W,renameSync as Me}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Ce,isInteractive as g,LUNA_ART as Le,LUNA_NAME as Se,LUNA_SIGNOFF as Ae,paintAnswer as Ne,BADGES as f}from"@lunora/config";import{walkSync as _e}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Ie}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Re,applyEdits as Te}from"jsonc-parser";import{join as E,dirname as Oe}from"node:path";import{i as je}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Be,d as Ee,k as Pe}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import De from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as ze,L as se,M as Ve}from"../packem_shared/commands-BhX2Bo9B.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{Y as Ue,h as He,M as We,C as ne,U as qe,i as le,X as ce,B as D,H as Fe,W as Ke,Q as de,I as Je,t as Qe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import{n as pe,u as Ge,p as Xe,b as Ye,d as Ze,l as et,g as tt,e as at,j as rt}from"../packem_shared/storage-DOvAKGi4.mjs";import ot from"node:dns/promises";const st=`name: Deploy
1
+ import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as b,readdirSync as X,rmSync as I,mkdtempSync as Y,lstatSync as Me,cpSync as W,renameSync as Le}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Se,isInteractive as g,LUNA_ART as Ae,LUNA_NAME as Ne,LUNA_SIGNOFF as Ie,paintAnswer as _e,BADGES as f}from"@lunora/config";import{walkSync as Re}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Te}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Oe,applyEdits as je}from"jsonc-parser";import{join as E,dirname as Be}from"node:path";import{i as Ee}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Pe,d as De,k as ze}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import Ue from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as Ve,L as se,M as He}from"../packem_shared/commands-B1SpMXov.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{Y as We,h as qe,M as Fe,C as ne,U as Ke,i as le,X as ce,B as D,H as Je,W as Qe,Q as de,I as Ge,t as Xe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{l as pe,u as Ye,p as Ze,b as et,a as tt,m as at,n as rt,f as ue,q as he,h as ot}from"../packem_shared/storage-BHSN9Vgb.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import st from"node:dns/promises";const it=`name: Deploy
2
2
 
3
3
  on:
4
4
  push:
@@ -52,7 +52,7 @@ jobs:
52
52
  cache: pnpm
53
53
  - run: pnpm install --frozen-lockfile
54
54
  - run: pnpm exec lunora deploy --preview
55
- `,it=`stages:
55
+ `,nt=`stages:
56
56
  - deploy
57
57
 
58
58
  # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
@@ -87,16 +87,16 @@ preview:
87
87
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
88
88
  script:
89
89
  - pnpm exec lunora deploy --preview
90
- `,ue={github:{content:st,file:E(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{content:it,file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},nt=e=>e==="github"||e==="gitlab",lt=(e,t,a={})=>{const r=ue[t],o=E(e,r.file);return h(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(Oe(o),{recursive:!0}),m(o,r.content,"utf8"),{path:o,skipped:!1,written:!0})},ct=(e,t,a,r={})=>{const o=ue[t];try{const s=lt(e,t,r);return s.skipped?a.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`):(a.success(`--ci ${t}: wrote ${o.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`)),s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:E(e,o.file),skipped:!1,written:!1}}},dt={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid"},pt=e=>{const t=Ce(e);return{...t,adapter:dt[t.framework]}},N="lunora()",F='import { lunora } from "@lunora/vite";',ut=/\blunora\s*\(/u,ht='"@lunora/vite"',mt="'@lunora/vite'",gt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()!==v.CallExpression)continue;const r=a.asKindOrThrow(v.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===v.ObjectLiteralExpression)return o.asKindOrThrow(v.ObjectLiteralExpression)}},vt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()===v.ObjectLiteralExpression)return a.asKindOrThrow(v.ObjectLiteralExpression)}},ft=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0});return gt(t)??vt(t)},wt=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}).getImportDeclarations();if(t.length===0)return 0;const a=t[t.length-1];return a===void 0?0:a.getEnd()},yt=(e,t)=>{const a=wt(t);a===0?e.prepend(`${F}
90
+ `,me={github:{content:it,file:E(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{content:nt,file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},lt=e=>e==="github"||e==="gitlab",ct=(e,t,a={})=>{const r=me[t],o=E(e,r.file);return h(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(Be(o),{recursive:!0}),m(o,r.content,"utf8"),{path:o,skipped:!1,written:!0})},dt=(e,t,a,r={})=>{const o=me[t];try{const s=ct(e,t,r);return s.skipped?a.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`):(a.success(`--ci ${t}: wrote ${o.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`)),s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:E(e,o.file),skipped:!1,written:!1}}},pt={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid"},ut=e=>{const t=Se(e);return{...t,adapter:pt[t.framework]}},N="lunora()",F='import { lunora } from "@lunora/vite";',ht=/\blunora\s*\(/u,mt='"@lunora/vite"',gt="'@lunora/vite'",vt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()!==v.CallExpression)continue;const r=a.asKindOrThrow(v.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===v.ObjectLiteralExpression)return o.asKindOrThrow(v.ObjectLiteralExpression)}},ft=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()===v.ObjectLiteralExpression)return a.asKindOrThrow(v.ObjectLiteralExpression)}},wt=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0});return vt(t)??ft(t)},yt=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}).getImportDeclarations();if(t.length===0)return 0;const a=t[t.length-1];return a===void 0?0:a.getEnd()},bt=(e,t)=>{const a=yt(t);a===0?e.prepend(`${F}
91
91
  `):e.appendLeft(a,`
92
- ${F}`)},bt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0)e.appendLeft(i,` plugins: [${N}] `);else{const n=s[0];n!==void 0&&e.appendLeft(n.getStart(),`plugins: [${N}],
93
- `)}return}const r=a.getDescendantsOfKind(v.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,N);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${N}, `)}},he=e=>{if(ut.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=ft(e);if(t===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new De(e);return e.includes(ht)||e.includes(mt)||yt(a,e),bt(a,t),{changed:!0,code:a.toString()}},xt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,kt=/404|not found|could not find|no such/u,$t=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return kt.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:xt.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},I=async(e,t,a)=>{if(g()){await He(f[e],t,a);return}if(process.stdout.write(`
92
+ ${F}`)},xt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0)e.appendLeft(i,` plugins: [${N}] `);else{const n=s[0];n!==void 0&&e.appendLeft(n.getStart(),`plugins: [${N}],
93
+ `)}return}const r=a.getDescendantsOfKind(v.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,N);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${N}, `)}},ge=e=>{if(ht.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=wt(e);if(t===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new Ue(e);return e.includes(mt)||e.includes(gt)||bt(a,e),xt(a,t),{changed:!0,code:a.toString()}},kt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,$t=/404|not found|could not find|no such/u,Ct=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return $t.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:kt.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},_=async(e,t,a)=>{if(g()){await qe(f[e],t,a);return}if(process.stdout.write(`
94
94
  `),a===void 0||a===""){q(e,t);return}const r=a.split(`
95
- `).map(o=>Ne(o)).join(`
95
+ `).map(o=>_e(o)).join(`
96
96
  `);q(e,`${t}
97
- ${r}`)},Mt=async e=>{if(g()){await Ue();return}e.info(`
98
- ${Le}
99
- ${Se}: ${Ae}`)},me=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],K=me.map(e=>e.value),Ct=e=>e==="email"?pe:e,Lt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))K.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${K.join(" | ")}; skipping.`);return a},St=async e=>{const t=await tt(e.select),a=await at(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>rt(r,a)}},At=async e=>{const t=await e.text(Ye,{placeholder:"you@yourdomain.com"}),a=Ze(t,r=>{e.logger.warn(r)});return{label:"email",names:[pe],transformManifest:a===void 0?void 0:r=>et(r,a)}},Nt=async e=>{const t=await Ge(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>Xe(a,t)}},_t={auth:St,email:At,storage:Nt},J=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>({label:r,names:[Ct(r)]})));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",me,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=_t[r];a.push(o?await o(e):{label:r,names:[r]})}await e.applyAll(a)},A="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",C=`/* The welcome page is a full-bleed starter — reset the browser's default
97
+ ${r}`)},Mt=async e=>{if(g()){await We();return}e.info(`
98
+ ${Ae}
99
+ ${Ne}: ${Ie}`)},ve=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],K=ve.map(e=>e.value),Lt=e=>e==="email"?pe:e,St=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))K.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${K.join(" | ")}; skipping.`);return a},At=async e=>{const t=await rt(e.select),a=await ue(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>he(r,a)}},Nt=async e=>{const t=await e.text(et,{placeholder:"you@yourdomain.com"}),a=tt(t,r=>{e.logger.warn(r)});return{label:"email",names:[pe],transformManifest:a===void 0?void 0:r=>at(r,a)}},It=async(e,t)=>{const a=e.resolveAuthUiItem?.()??"auth-ui-react";if(t)return{label:"auth-ui",names:[a]};const r=await ue(e.text,e.projectName);return{label:"auth-ui",names:[a],transformManifest:o=>he(o,r)}},_t=async e=>{const t=await Ye(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>Ze(a,t)}},Rt={auth:At,"auth-ui":async(e,t)=>It(e,t.includes("auth")),email:Nt,storage:_t},J=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>{const o=r==="auth-ui"?e.resolveAuthUiItem?.()??"auth-ui-react":Lt(r);return{label:r,names:[o]}}));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",ve,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=Rt[r];a.push(o?await o(e,t):{label:r,names:[r]})}await e.applyAll(a)},A="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",M=`/* The welcome page is a full-bleed starter — reset the browser's default
100
100
  body margin/padding so it sits flush; everything else is scoped under
101
101
  .lunora-welcome (collision-safe). */
102
102
  body {
@@ -201,7 +201,7 @@ body {
201
201
  .lunora-welcome .lw-foot { text-align: center; padding-top: 26px; font-family: var(--mono); font-size: 11px; letter-spacing: .1em; text-transform: uppercase; color: var(--t-faint); }
202
202
 
203
203
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
204
- `,It=`import { useEffect, useState } from "react";
204
+ `,Tt=`import { useEffect, useState } from "react";
205
205
 
206
206
  type Theme = "dark" | "light";
207
207
 
@@ -362,7 +362,7 @@ export default function App() {
362
362
  </div>
363
363
  );
364
364
  }
365
- `,Rt=`<script setup lang="ts">
365
+ `,Ot=`<script setup lang="ts">
366
366
  import { onMounted, ref } from "vue";
367
367
 
368
368
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -518,7 +518,7 @@ const toggle = (): void => {
518
518
  </div>
519
519
  </div>
520
520
  </template>
521
- `,Tt=`import { createSignal, onMount } from "solid-js";
521
+ `,jt=`import { createSignal, onMount } from "solid-js";
522
522
 
523
523
  export default function App() {
524
524
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -677,7 +677,7 @@ export default function App() {
677
677
  </div>
678
678
  );
679
679
  }
680
- `,Ot=`<script lang="ts">
680
+ `,Bt=`<script lang="ts">
681
681
  import { onMount } from "svelte";
682
682
 
683
683
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -835,7 +835,7 @@ export default function App() {
835
835
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
836
836
  </div>
837
837
  </div>
838
- `,jt=`import "./style.css";
838
+ `,Et=`import "./style.css";
839
839
 
840
840
  import { LunoraClient } from "lunorash/client";
841
841
 
@@ -1002,7 +1002,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1002
1002
  client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
1003
1003
  count.textContent = String(result.messages.length);
1004
1004
  });
1005
- `,R="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Bt=`import "./index.css";
1005
+ `,R="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Pt=`import "./index.css";
1006
1006
 
1007
1007
  import { LunoraProvider } from "@lunora/react";
1008
1008
  import { LunoraClient } from "lunorash/client";
@@ -1030,7 +1030,7 @@ createRoot(root).render(
1030
1030
  </LunoraProvider>
1031
1031
  </StrictMode>,
1032
1032
  );
1033
- `,Et=`import "./style.css";
1033
+ `,Dt=`import "./style.css";
1034
1034
 
1035
1035
  import { createLunora } from "@lunora/vue";
1036
1036
  import { LunoraClient } from "lunorash/client";
@@ -1041,7 +1041,7 @@ import App from "./App.vue";
1041
1041
  // Provide one LunoraClient at the app root via the Vue plugin form.
1042
1042
  ${R}
1043
1043
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1044
- `,Pt=`import "./index.css";
1044
+ `,zt=`import "./index.css";
1045
1045
 
1046
1046
  import { LunoraContext } from "@lunora/solid";
1047
1047
  import { LunoraClient } from "lunorash/client";
@@ -1061,7 +1061,7 @@ render(
1061
1061
  ),
1062
1062
  root!,
1063
1063
  );
1064
- `,Dt=`<script lang="ts">
1064
+ `,Ut=`<script lang="ts">
1065
1065
  import { setLunoraClient } from "@lunora/svelte";
1066
1066
  import { LunoraClient } from "lunorash/client";
1067
1067
 
@@ -1072,7 +1072,7 @@ render(
1072
1072
  <\/script>
1073
1073
 
1074
1074
  <App />
1075
- `,zt=`import "./app.css";
1075
+ `,Vt=`import "./app.css";
1076
1076
 
1077
1077
  import { mount } from "svelte";
1078
1078
 
@@ -1082,7 +1082,7 @@ import Root from "./Root.svelte";
1082
1082
  const app = mount(Root, { target: document.getElementById("app")! });
1083
1083
 
1084
1084
  export default app;
1085
- `,T={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Bt,path:"src/main.tsx"},{contents:It,path:"src/App.tsx"},{contents:C,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:Pt,path:"src/index.tsx"},{contents:Tt,path:"src/App.tsx"},{contents:C,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:Dt,path:"src/Root.svelte"},{contents:zt,path:"src/main.ts"},{contents:Ot,path:"src/App.svelte"},{contents:C,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:jt,path:"src/main.ts"},{contents:C,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:Et,path:"src/main.ts"},{contents:Rt,path:"src/App.vue"},{contents:C,path:"src/style.css"}],label:"Vue"}},z=e=>Object.hasOwn(T,e),Vt=`import type { Middleware } from "lunorash/server";
1085
+ `,T={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Pt,path:"src/main.tsx"},{contents:Tt,path:"src/App.tsx"},{contents:M,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:zt,path:"src/index.tsx"},{contents:jt,path:"src/App.tsx"},{contents:M,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:Ut,path:"src/Root.svelte"},{contents:Vt,path:"src/main.ts"},{contents:Bt,path:"src/App.svelte"},{contents:M,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:Et,path:"src/main.ts"},{contents:M,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:Dt,path:"src/main.ts"},{contents:Ot,path:"src/App.vue"},{contents:M,path:"src/style.css"}],label:"Vue"}},z=e=>Object.hasOwn(T,e),Ht=`import type { Middleware } from "lunorash/server";
1086
1086
  import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1087
1087
  import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1088
1088
  import type { RateLimitConfigMap } from "lunorash/ratelimit";
@@ -1122,7 +1122,7 @@ export const ratelimit = definePlugin("ratelimit", {
1122
1122
  }),
1123
1123
  middleware,
1124
1124
  });
1125
- `,Ut=`import { ratelimit } from "./ratelimit/schema.js";
1125
+ `,Wt=`import { ratelimit } from "./ratelimit/schema.js";
1126
1126
  import { defineSchema, defineTable, v } from "lunorash/server";
1127
1127
 
1128
1128
  export default defineSchema({
@@ -1133,7 +1133,7 @@ export default defineSchema({
1133
1133
  .shardBy("channelId")
1134
1134
  .index("by_channel", ["channelId"]),
1135
1135
  }).extend(ratelimit.extension);
1136
- `,Ht=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1136
+ `,qt=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1137
1137
 
1138
1138
  import { mutation, query, v } from "#lunora/_generated/server.js";
1139
1139
 
@@ -1161,7 +1161,7 @@ export const send = mutation
1161
1161
 
1162
1162
  return { channelId: args.channelId, id, text: args.text };
1163
1163
  });
1164
- `,Wt=`import type { ShardNamespaceLike } from "lunorash/runtime";
1164
+ `,Ft=`import type { ShardNamespaceLike } from "lunorash/runtime";
1165
1165
 
1166
1166
  import { defineApp } from "../lunora/_generated/app.js";
1167
1167
 
@@ -1175,7 +1175,7 @@ const app = defineApp<Env>()
1175
1175
 
1176
1176
  export const ShardDO = app.ShardDO;
1177
1177
  export default app;
1178
- `,qt=`{
1178
+ `,Kt=`{
1179
1179
  "$schema": "node_modules/wrangler/config-schema.json",
1180
1180
  "name": "__NAME__",
1181
1181
  "main": "src/server.ts",
@@ -1187,23 +1187,23 @@ export default app;
1187
1187
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1188
1188
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1189
1189
  }
1190
- `,Ft=[".wrangler",".env",".env.*","!.env.example",".lunora/",".lunora-cache","lunora/_generated"],Kt=`# Lunora endpoint for the browser client.
1190
+ `,Jt=[".wrangler",".env",".env.*","!.env.example",".lunora/",".lunora-cache","lunora/_generated"],Qt=`# Lunora endpoint for the browser client.
1191
1191
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1192
1192
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1193
1193
  #
1194
1194
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1195
- `,Jt={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},b=(e,t,a,r)=>{const o=p(e,t);L($(o),{recursive:!0}),m(o,a,"utf8"),r.push(o)},Qt=/\r?\n/,Gt=e=>{const t=p(e,".gitignore"),a=h(t)?k(t,"utf8"):"",r=Ft.filter(s=>!a.split(Qt).includes(s));if(r.length===0)return;const o=a.length>0&&!a.endsWith(`
1195
+ `,Gt={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},x=(e,t,a,r)=>{const o=p(e,t);L($(o),{recursive:!0}),m(o,a,"utf8"),r.push(o)},Xt=/\r?\n/,Yt=e=>{const t=p(e,".gitignore"),a=h(t)?b(t,"utf8"):"",r=Jt.filter(s=>!a.split(Xt).includes(s));if(r.length===0)return;const o=a.length>0&&!a.endsWith(`
1196
1196
  `)?`
1197
1197
  `:"";m(t,`${a}${o}
1198
1198
  # Lunora
1199
1199
  ${r.join(`
1200
1200
  `)}
1201
- `,"utf8")},ge=e=>e==="lunorash"||e.startsWith("@lunora/"),ve=(e,t,a,r)=>ge(e)?r?.get(e)??a:t,x=(e,t,a,r)=>({...e,[t]:ve(t,a,r)}),Q=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ve(r,o,t,a)])),Xt=async(e,t,a,r)=>{const o=p(e,"package.json"),s=JSON.parse(k(o,"utf8"));let i=x(s.dependencies??{},"lunorash",r,r);i=x(i,"@lunora/ratelimit",r,r),a.adapter.startsWith("@lunora/")&&(i=x(i,a.adapter,r,r));for(const[u,l]of Object.entries(a.extraDependencies??{}))i=x(i,u,l,r);let n=x(s.devDependencies??{},"@lunora/vite",r,r);n=x(n,"@lunora/studio",r,r);for(const[u,l]of Object.entries(Jt))n=x(n,u,l,r);const c=[...Object.keys(i),...Object.keys(n)].filter(u=>ge(u)),d=await re(c,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=Q(i,r,d),s.devDependencies=Q(n,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},m(o,`${JSON.stringify(s,void 0,4)}
1202
- `,"utf8")},Yt=(e,t)=>{const a=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"].map(o=>p(e,o)).find(o=>h(o));if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=he(k(a,"utf8"));r.changed&&m(a,r.code,"utf8")},Zt=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,i=[];b(s,p("lunora","ratelimit","schema.ts"),Vt,i),b(s,p("lunora","schema.ts"),Ut,i),b(s,p("lunora","messages.ts"),Ht,i),b(s,p("src","server.ts"),Wt,i),b(s,"wrangler.jsonc",qt.replaceAll("__NAME__",o),i),b(s,".env.example",Kt,i);for(const n of t.files)b(s,n.path,n.contents,i);return Yt(s,r),await Xt(s,o,t,a),Gt(s),i},ea=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ta=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],G=e=>e[Math.floor(Math.random()*e.length)],aa=()=>`${G(ea)}-${G(ta)}`,ra=async()=>ot.lookup("github.com").then(()=>!0,()=>!1),oa=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,fe=e=>{const t=oa.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},sa=async e=>{const t=fe(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},we=async e=>e.isLocal||!(e.source===void 0||fe(e.source)!==void 0)?!0:await ra()?e.source!==void 0&&await sa(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},ia=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),na=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],la=`import { defineConfig } from "vite";
1201
+ `,"utf8")},fe=e=>e==="lunorash"||e.startsWith("@lunora/"),we=(e,t,a,r)=>fe(e)?r?.get(e)??a:t,k=(e,t,a,r)=>({...e,[t]:we(t,a,r)}),Q=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,we(r,o,t,a)])),Zt=async(e,t,a,r)=>{const o=p(e,"package.json"),s=JSON.parse(b(o,"utf8"));let i=k(s.dependencies??{},"lunorash",r,r);i=k(i,"@lunora/ratelimit",r,r),a.adapter.startsWith("@lunora/")&&(i=k(i,a.adapter,r,r));for(const[u,l]of Object.entries(a.extraDependencies??{}))i=k(i,u,l,r);let n=k(s.devDependencies??{},"@lunora/vite",r,r);n=k(n,"@lunora/studio",r,r);for(const[u,l]of Object.entries(Gt))n=k(n,u,l,r);const c=[...Object.keys(i),...Object.keys(n)].filter(u=>fe(u)),d=await re(c,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=Q(i,r,d),s.devDependencies=Q(n,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},m(o,`${JSON.stringify(s,void 0,4)}
1202
+ `,"utf8")},ea=(e,t)=>{const a=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"].map(o=>p(e,o)).find(o=>h(o));if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=ge(b(a,"utf8"));r.changed&&m(a,r.code,"utf8")},ta=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,i=[];x(s,p("lunora","ratelimit","schema.ts"),Ht,i),x(s,p("lunora","schema.ts"),Wt,i),x(s,p("lunora","messages.ts"),qt,i),x(s,p("src","server.ts"),Ft,i),x(s,"wrangler.jsonc",Kt.replaceAll("__NAME__",o),i),x(s,".env.example",Qt,i);for(const n of t.files)x(s,n.path,n.contents,i);return ea(s,r),await Zt(s,o,t,a),Yt(s),i},aa=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ra=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],G=e=>e[Math.floor(Math.random()*e.length)],oa=()=>`${G(aa)}-${G(ra)}`,sa=async()=>st.lookup("github.com").then(()=>!0,()=>!1),ia=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,ye=e=>{const t=ia.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},na=async e=>{const t=ye(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},be=async e=>e.isLocal||!(e.source===void 0||ye(e.source)!==void 0)?!0:await sa()?e.source!==void 0&&await na(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},la=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),ca=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],da=`import { defineConfig } from "vite";
1203
1203
  import { lunora } from "@lunora/vite";
1204
1204
 
1205
1205
  export default defineConfig({ plugins: [lunora()] });
1206
- `,ca=`import { defineSchema, defineTable, v } from "@lunora/server";
1206
+ `,pa=`import { defineSchema, defineTable, v } from "@lunora/server";
1207
1207
 
1208
1208
  export default defineSchema({
1209
1209
  messages: defineTable({
@@ -1213,7 +1213,7 @@ export default defineSchema({
1213
1213
  .shardBy("channelId")
1214
1214
  .index("by_channel", ["channelId"]),
1215
1215
  });
1216
- `,da=`import { mutation, query, v } from "./_generated/server";
1216
+ `,ua=`import { mutation, query, v } from "./_generated/server";
1217
1217
 
1218
1218
  export const list = query
1219
1219
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1226,8 +1226,8 @@ export const send = mutation
1226
1226
  .mutation(async ({ args }) => {
1227
1227
  return { channelId: args.channelId, text: args.text };
1228
1228
  });
1229
- `,pa="gh:anolilab/lunora/templates",ua=e=>{const t=e.lastIndexOf(".");return t===-1?!1:ia.has(e.slice(t))},ha=(e,t)=>e.replaceAll("{{name}}",t),ye=e=>e==="lunorash"||e.startsWith("@lunora/"),ma=async(e,t)=>{const a=new Set;for(const r of e)if(S(r)==="package.json")try{const o=JSON.parse(k(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const i of Object.keys(o[s]??{}))ye(i)&&a.add(i)}catch{}return re(a,t)},ga=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const i of Object.keys(r[s]??{})){if(!ye(i))continue;const n=a.get(i)??t,c=Re(o,[s,i],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Te(o,c)}return o},va=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","workerd"],fa=["cpu-features","protobufjs","ssh2"],wa="pnpm-workspace.yaml",ya=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...va.map(e=>` '${e}': true`),...fa.map(e=>` '${e}': false`),""].join(`
1230
- `),V=e=>{const t=[];for(const a of _e(e,{includeDirs:!1,includeFiles:!0}))$e(a.path).isSymbolicLink()||t.push(a.path);return t},be=async(e,t,a)=>{const r=V(e),o=[],s=se(),i=await ma(r,s);for(const n of r){const c=Ie(e,n),d=p(t,c);L($(d),{recursive:!0});const u=k(n);let l=ua(n)?ha(u.toString("utf8"),a):void 0;l!==void 0&&S(n)==="package.json"&&(l=ga(l,s,i)),l===void 0?m(d,u):m(d,l,"utf8"),o.push(d)}return o},j=(e,t,a)=>t!==void 0&&t.length>0?t:`${pa}/${e}#${oe(a)}`,ba=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),M=(e,t)=>{e.info(`[dry-run] would ${t}`)},U=(e,t,a)=>{g()&&process.stdout.write(`
1231
- `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},xa=(e,t)=>`${e} ${e==="npm"?"install":"add"} ${t.join(" ")}`,xe=e=>{let t=B(e);for(;;){if(h(p(t,"pnpm-workspace.yaml")))return!0;const a=p(t,"package.json");if(h(a))try{if(JSON.parse(k(a,"utf8")).workspaces!==void 0)return!0}catch{}const r=$(t);if(r===t)return!1;t=r}},ka=e=>{let t=B(e);for(;;){if(h(p(t,".git")))return!0;const a=$(t);if(a===t)return!1;t=a}},$a=async(e,t)=>{if(e.yes===!0||!g()||ka($(t)))return;if(!await le(y.git,{badge:f.git,defaultYes:!1})){await ce("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){M(e.logger,"initialize a git repository");return}const a=e.spawner??ie;(await Fe("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await I("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Ma=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Pe(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const s=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await Ke(f.next,y.nextHeader,o,s);return}const i=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);i.push("",...s.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await I("next",y.nextHeader,i.join(`
1232
- `))},Ca=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),La=async(e,t)=>{if(!Ca(e)||xe($(t)))return;const a=Be(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>le(y.install,{badge:f.deps,defaultYes:!0})))()){await ce("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await D(y.packageManager,a.map(d=>({label:d,value:d})),{badge:f.deps,default:r})??r),e.dryRun===!0){M(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,wa);h(d)||m(d,ya(),"utf8")}const s=e.spawner??ie,{args:i,command:n}=Ee(o);await I("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,command:n,cwd:t});if(c.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(c.code)} — run it yourself in ${S(t)}/.`);return}return await I("deps",`Dependencies installed with ${o}.`),o},Sa=async(e,t,a,r,o)=>{const s=p(e,t);if(!h(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const i=await be(s,a,r);return U(o,i,a),{code:0,files:i,target:a}},Aa=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:i}=e,n=Y(p(Z(),"lunora-init-fetch-")),c=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await ze(r,t),u=j(i,o,d);let l,w=[];await de([{label:`${i} template fetched`,run:async()=>{l=await ee(u,{cwd:n,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await be(c,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const H=V(c);return g()&&process.stdout.write(`
1233
- `),t.info(l?.commit?`template: ${l.source} @ ${l.commit} (${String(H.length)} files)`:`template: ${l?.source??u} (${String(H.length)} files)`),U(t,w,s),{code:0,files:w,target:s}}catch(d){if(d instanceof P)throw d;const{hints:u,message:l}=$t(d,{ref:oe(r),remote:j(i,o,r),templateType:i});t.error(l);for(const w of u)t.warn(w);return{code:1,files:[],target:s}}finally{_(n,{force:!0,recursive:!0})}},Na=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&Me(a,p(e,`.${t.slice(1)}`))}},_a=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,i=T[t],n=Y(p(Z(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=p(o,`template-${i.createViteTemplate}`),!h(c)))return a.error(`create-vite base not found on disk: ${c}`),{code:1,files:[],target:s};const d=async()=>{if(c!==void 0){W(c,s,{recursive:!0});return}const l=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${i.createViteTemplate}#main`;await ee(w,{cwd:n,dir:l,force:!0,install:!1,silent:!0}),Na(l),W(l,s,{recursive:!0})};let u=[];return await de([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{u=await Zt({adapter:i,distTag:se(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),U(a,u,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof P)throw c;const d=c instanceof Error?c.message:String(c);return a.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{_(n,{force:!0,recursive:!0})}},Ia=(e,t)=>{const a=p(e,"vite.config.ts");try{m(a,la,"utf8")}catch(r){const o=r instanceof Error?r.message:String(r);return t.error(`init --in-place: could not write ${a}: ${o}`),{code:1,files:[],target:e}}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Ra=(e,t,a)=>{let r;try{r=k(e,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not read ${e}: ${i}`),{code:1,files:[],target:t}}const o=he(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{m(e,o.code,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not write ${e}: ${i}`),{code:1,files:[],target:t}}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Ta=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),m(r,ca,"utf8"),o.push(r);const s=p(a,"messages.ts");h(s)||(m(s,da,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const i=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${i}`)}return o},Oa=(e,t,a)=>{const{adapter:r,class:o,framework:s}=e;a.info(""),a.info(`detected framework: ${s} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${xa(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${s} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},ja=e=>{for(const t of na){const a=p(e,t);if(h(a))return a}},Ba=(e,t,a)=>{const r=ja(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ia(e,a):Ra(r,e,a)},Ea=(e,t)=>{const a=pt(e),r=Ba(e,a.framework,t);if(r.code!==0)return r;const o=Ta(e,t);return Oa(a,te(e),t),{code:0,files:[...r.files,...o],target:e}},Pa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),Da=async(e,t)=>{const a=Pa(e),r=e.add===void 0?[]:Lt(e.add,s=>{e.logger.warn(s)}),o={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return M(e.logger,`add ${s.map(l=>l.label).join(", ")}`),!0;const i=[],n=g()?{error:l=>{i.push({level:"error",message:l})},info:()=>{},success:()=>{},warn:l=>{i.push({level:"warn",message:l})}}:e.logger,c=s.map(l=>({running:`adding ${l.label}…`,task:()=>Ve({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...l.names],ref:e.ref,source:e.registrySource,transformManifest:l.transformManifest,yes:!0})})),d=`added ${s.map(l=>l.label).join(", ")}`,u=await Qe(f.add,c,d);for(const{level:l,message:w}of i)e.logger[l](w);return u.every(l=>l.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,n)=>Je(s,i,{...n,badge:f.add})),preselected:r.length>0?r:void 0,projectName:S(t),select:e.prompt?.select??((s,i,n)=>D(s,i,{...n,badge:f.add})),text:e.prompt?.text??((s,i)=>ne(s,{...i,badge:f.add}))};if(r.length>0){await J(o);return}g()&&await qe(y.extras),await J(o)},O="react",ke=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],za=Object.keys(T).join("|"),Va=ke.filter(e=>!z(e.value)).map(e=>e.value).join("|"),Ua=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},Ha=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:O,kind:"overlay"}:Ua(await D(y.framework,ke,{badge:f.tmpl,default:O})??O),Wa=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${za}>\` for an SPA, or \`-t <${Va}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},qa=async(e,t,a,r)=>z(t)?await we({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),_a({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(T).join(", ")}.`),{code:1,files:[],target:r}),Fa=async(e,t,a,r)=>e.from!==void 0?await Sa(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ba(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await we({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Aa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},Ka=async(e,t,a)=>{await We("realtime backend on Cloudflare Workers + Durable Objects");const r=Wa(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=aa(),s=e.name??await ne(y.name,{badge:f.dir,default:o,placeholder:o}),i=await Ha(e),n=s.trim();if(n.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const c=B(t,n),d=h(c);if(d&&X(c).length>0)return e.logger.error(`target directory not empty: ${c}`),{code:1,files:[],target:c};if(e.dryRun===!0){const u=i.kind==="overlay"?`the ${i.framework} create-vite overlay`:`the ${i.templateType} template`;return M(e.logger,`scaffold ${u} into ${c}`),{code:0,files:[],target:c}}return a(c,d),i.kind==="overlay"?qa(e,i.framework,n,c):Fa(e,i.templateType,n,c)},Ja=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of X(a))_(p(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},Qa=async(e,t,a)=>e.inPlace!==!0?Ka(e,t,a):e.dryRun===!0?(M(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):Ea(t,e.logger),Ga=async(e,t,a)=>{await Da(e,t.target);const r=e.inPlace===!0?void 0:await La(e,t.target);if(e.inPlace!==!0){await $a(e,t.target);const o=r??te(t.target);await Ma(S(t.target),r,o,xe(a)),await Mt(e.logger)}},Xa=(e,t,a)=>{if(!(t.code!==0||e.ci===void 0)){if(e.dryRun===!0){M(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}ct(e.inPlace===!0?a:t.target,e.ci,e.logger)}},Ya=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await Qa(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await Ga(e,r,t))}catch(o){if(o instanceof P)return Ja(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return Xa(e,r,t),r},Za=e=>e==="analog"||e==="astro"||e==="expo"||e==="next"||e==="nuxt"||e==="react-router"||e==="standalone"||e==="sveltekit"||e==="tanstack-start-react"||e==="tanstack-start-solid",er=(e,t)=>{if(e!==void 0){if(nt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},br=je(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&Za(r.template)?r.template:void 0;return Ya({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:er(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{br as execute,Za as isTemplate,j as resolveTemplateSource,Ya as runInitCommand};
1229
+ `,ha="gh:anolilab/lunora/templates",ma=e=>{const t=e.lastIndexOf(".");return t===-1?!1:la.has(e.slice(t))},ga=(e,t)=>e.replaceAll("{{name}}",t),xe=e=>e==="lunorash"||e.startsWith("@lunora/"),va=async(e,t)=>{const a=new Set;for(const r of e)if(S(r)==="package.json")try{const o=JSON.parse(b(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const i of Object.keys(o[s]??{}))xe(i)&&a.add(i)}catch{}return re(a,t)},fa=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const i of Object.keys(r[s]??{})){if(!xe(i))continue;const n=a.get(i)??t,c=Oe(o,[s,i],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=je(o,c)}return o},wa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],ya=["cpu-features","protobufjs","ssh2"],ba="pnpm-workspace.yaml",xa=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...wa.map(e=>` '${e}': true`),...ya.map(e=>` '${e}': false`),""].join(`
1230
+ `),U=e=>{const t=[];for(const a of Re(e,{includeDirs:!1,includeFiles:!0}))Me(a.path).isSymbolicLink()||t.push(a.path);return t},ke=async(e,t,a)=>{const r=U(e),o=[],s=se(),i=await va(r,s);for(const n of r){const c=Te(e,n),d=p(t,c);L($(d),{recursive:!0});const u=b(n);let l=ma(n)?ga(u.toString("utf8"),a):void 0;l!==void 0&&S(n)==="package.json"&&(l=fa(l,s,i)),l===void 0?m(d,u):m(d,l,"utf8"),o.push(d)}return o},j=(e,t,a)=>t!==void 0&&t.length>0?t:`${ha}/${e}#${oe(a)}`,ka=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),C=(e,t)=>{e.info(`[dry-run] would ${t}`)},V=(e,t,a)=>{g()&&process.stdout.write(`
1231
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},$a=(e,t)=>`${e} ${e==="npm"?"install":"add"} ${t.join(" ")}`,$e=e=>{let t=B(e);for(;;){if(h(p(t,"pnpm-workspace.yaml")))return!0;const a=p(t,"package.json");if(h(a))try{if(JSON.parse(b(a,"utf8")).workspaces!==void 0)return!0}catch{}const r=$(t);if(r===t)return!1;t=r}},Ca=e=>{let t=B(e);for(;;){if(h(p(t,".git")))return!0;const a=$(t);if(a===t)return!1;t=a}},Ma=async(e,t)=>{if(e.yes===!0||!g()||Ca($(t)))return;if(!await le(y.git,{badge:f.git,defaultYes:!1})){await ce("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){C(e.logger,"initialize a git repository");return}const a=e.spawner??ie;(await Je("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await _("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},La=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:ze(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const s=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await Qe(f.next,y.nextHeader,o,s);return}const i=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);i.push("",...s.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await _("next",y.nextHeader,i.join(`
1232
+ `))},Sa=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),Aa=async(e,t)=>{if(!Sa(e)||$e($(t)))return;const a=Pe(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>le(y.install,{badge:f.deps,defaultYes:!0})))()){await ce("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await D(y.packageManager,a.map(d=>({label:d,value:d})),{badge:f.deps,default:r})??r),e.dryRun===!0){C(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,ba);h(d)||m(d,xa(),"utf8")}const s=e.spawner??ie,{args:i,command:n}=De(o);await _("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,command:n,cwd:t});if(c.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(c.code)} — run it yourself in ${S(t)}/.`);return}return await _("deps",`Dependencies installed with ${o}.`),o},Na=async(e,t,a,r,o)=>{const s=p(e,t);if(!h(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const i=await ke(s,a,r);return V(o,i,a),{code:0,files:i,target:a}},Ia=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:i}=e,n=Y(p(Z(),"lunora-init-fetch-")),c=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await Ve(r,t),u=j(i,o,d);let l,w=[];await de([{label:`${i} template fetched`,run:async()=>{l=await ee(u,{cwd:n,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await ke(c,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const H=U(c);return g()&&process.stdout.write(`
1233
+ `),t.info(l?.commit?`template: ${l.source} @ ${l.commit} (${String(H.length)} files)`:`template: ${l?.source??u} (${String(H.length)} files)`),V(t,w,s),{code:0,files:w,target:s}}catch(d){if(d instanceof P)throw d;const{hints:u,message:l}=Ct(d,{ref:oe(r),remote:j(i,o,r),templateType:i});t.error(l);for(const w of u)t.warn(w);return{code:1,files:[],target:s}}finally{I(n,{force:!0,recursive:!0})}},_a=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&Le(a,p(e,`.${t.slice(1)}`))}},Ra=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,i=T[t],n=Y(p(Z(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=p(o,`template-${i.createViteTemplate}`),!h(c)))return a.error(`create-vite base not found on disk: ${c}`),{code:1,files:[],target:s};const d=async()=>{if(c!==void 0){W(c,s,{recursive:!0});return}const l=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${i.createViteTemplate}#main`;await ee(w,{cwd:n,dir:l,force:!0,install:!1,silent:!0}),_a(l),W(l,s,{recursive:!0})};let u=[];return await de([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{u=await ta({adapter:i,distTag:se(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),V(a,u,s),{code:0,files:[...U(s)],target:s}}catch(c){if(c instanceof P)throw c;const d=c instanceof Error?c.message:String(c);return a.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{I(n,{force:!0,recursive:!0})}},Ta=(e,t)=>{const a=p(e,"vite.config.ts");try{m(a,da,"utf8")}catch(r){const o=r instanceof Error?r.message:String(r);return t.error(`init --in-place: could not write ${a}: ${o}`),{code:1,files:[],target:e}}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Oa=(e,t,a)=>{let r;try{r=b(e,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not read ${e}: ${i}`),{code:1,files:[],target:t}}const o=ge(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{m(e,o.code,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not write ${e}: ${i}`),{code:1,files:[],target:t}}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},ja=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),m(r,pa,"utf8"),o.push(r);const s=p(a,"messages.ts");h(s)||(m(s,ua,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const i=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${i}`)}return o},Ba=(e,t,a)=>{const{adapter:r,class:o,framework:s}=e;a.info(""),a.info(`detected framework: ${s} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${$a(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${s} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},Ea=e=>{for(const t of ca){const a=p(e,t);if(h(a))return a}},Pa=(e,t,a)=>{const r=Ea(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ta(e,a):Oa(r,e,a)},Da=(e,t)=>{const a=ut(e),r=Pa(e,a.framework,t);if(r.code!==0)return r;const o=ja(e,t);return Ba(a,te(e),t),{code:0,files:[...r.files,...o],target:e}},za=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),Ua=async(e,t)=>{const a=za(e),r=e.add===void 0?[]:St(e.add,s=>{e.logger.warn(s)}),o={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return C(e.logger,`add ${s.map(l=>l.label).join(", ")}`),!0;const i=[],n=g()?{error:l=>{i.push({level:"error",message:l})},info:()=>{},success:()=>{},warn:l=>{i.push({level:"warn",message:l})}}:e.logger,c=s.map(l=>({running:`adding ${l.label}…`,task:()=>He({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...l.names],ref:e.ref,source:e.registrySource,transformManifest:l.transformManifest,yes:!0})})),d=`added ${s.map(l=>l.label).join(", ")}`,u=await Xe(f.add,c,d);for(const{level:l,message:w}of i)e.logger[l](w);return u.every(l=>l.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,n)=>Ge(s,i,{...n,badge:f.add})),preselected:r.length>0?r:void 0,projectName:S(t),resolveAuthUiItem:()=>{try{const s=JSON.parse(b(p(t,"package.json"),"utf8"));return ot({...s.dependencies,...s.devDependencies})??"auth-ui-react"}catch{return"auth-ui-react"}},select:e.prompt?.select??((s,i,n)=>D(s,i,{...n,badge:f.add})),text:e.prompt?.text??((s,i)=>ne(s,{...i,badge:f.add}))};if(r.length>0){await J(o);return}g()&&await Ke(y.extras),await J(o)},O="react",Ce=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],Va=Object.keys(T).join("|"),Ha=Ce.filter(e=>!z(e.value)).map(e=>e.value).join("|"),Wa=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},qa=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:O,kind:"overlay"}:Wa(await D(y.framework,Ce,{badge:f.tmpl,default:O})??O),Fa=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${Va}>\` for an SPA, or \`-t <${Ha}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},Ka=async(e,t,a,r)=>z(t)?await be({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),Ra({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(T).join(", ")}.`),{code:1,files:[],target:r}),Ja=async(e,t,a,r)=>e.from!==void 0?await Na(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ka(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await be({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Ia({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},Qa=async(e,t,a)=>{await Fe("realtime backend on Cloudflare Workers + Durable Objects");const r=Fa(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=oa(),s=e.name??await ne(y.name,{badge:f.dir,default:o,placeholder:o}),i=await qa(e),n=s.trim();if(n.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const c=B(t,n),d=h(c);if(d&&X(c).length>0)return e.logger.error(`target directory not empty: ${c}`),{code:1,files:[],target:c};if(e.dryRun===!0){const u=i.kind==="overlay"?`the ${i.framework} create-vite overlay`:`the ${i.templateType} template`;return C(e.logger,`scaffold ${u} into ${c}`),{code:0,files:[],target:c}}return a(c,d),i.kind==="overlay"?Ka(e,i.framework,n,c):Ja(e,i.templateType,n,c)},Ga=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of X(a))I(p(a,o),{force:!0,recursive:!0});else I(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},Xa=async(e,t,a)=>e.inPlace!==!0?Qa(e,t,a):e.dryRun===!0?(C(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):Da(t,e.logger),Ya=async(e,t,a)=>{await Ua(e,t.target);const r=e.inPlace===!0?void 0:await Aa(e,t.target);if(e.inPlace!==!0){await Ma(e,t.target);const o=r??te(t.target);await La(S(t.target),r,o,$e(a)),await Mt(e.logger)}},Za=(e,t,a)=>{if(!(t.code!==0||e.ci===void 0)){if(e.dryRun===!0){C(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}dt(e.inPlace===!0?a:t.target,e.ci,e.logger)}},er=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await Xa(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await Ya(e,r,t))}catch(o){if(o instanceof P)return Ga(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return Za(e,r,t),r},tr=e=>e==="analog"||e==="astro"||e==="expo"||e==="next"||e==="nuxt"||e==="react-router"||e==="standalone"||e==="sveltekit"||e==="tanstack-start-react"||e==="tanstack-start-solid",ar=(e,t)=>{if(e!==void 0){if(lt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},kr=Ee(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&tr(r.template)?r.template:void 0;return er({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:ar(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{kr as execute,tr as isTemplate,j as resolveTemplateSource,er as runInitCommand};
@@ -0,0 +1,3 @@
1
+ import{mkdirSync as x,readFileSync as f,lstatSync as O,writeFileSync as N}from"node:fs";import{join as d,dirname as g}from"node:path";import{fileURLToPath as R}from"node:url";import{resolveHint as B,isLunoraError as v,flattenHint as A,findSolutionByMessage as L}from"@lunora/errors";import{createCerebro as D}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import E from"@visulima/cerebro/command/version";import{p as s}from"./api-spec-BENwiyUa.mjs";import{createLogger as b}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as j,renderError as I}from"@visulima/error";import{homedir as P}from"node:os";const T={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("../packem_chunks/handler.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},{description:"Output format: pretty (default) or json",name:"format",type:String}]},_={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("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},$={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) 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 restore <id>","Restore a snapshot by id"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{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 production pitr --restore (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}]},U={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"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String}]},M={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String}]},W={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},J={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","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate (deploy even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{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},{description:"Output format: pretty (default) or json",name:"format",type:String},{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:"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:"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 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}]},K={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},q={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)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},{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:"Emit machine-readable JSON log lines (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:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},F={argument:{description:"Optional path under the docs site (e.g. addons/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 addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},H={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},V={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"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{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}]},G={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"]],group:"Data",loader:()=>import("../packem_chunks/handler10.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},{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}]},Y={argument:{description:"Source NDJSON file",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{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}]},z={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},Q={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 --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("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",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 | 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}]},X={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 --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("../packem_chunks/handler13.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},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{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}]},Z={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("../packem_chunks/handler22.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 (default true; --no-procedures to skip)",name:"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}]},ee={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("../packem_chunks/handler14.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}]},te={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("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{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}]},re={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"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.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: 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)",name:"token",type:String}]},oe={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 d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.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},{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}]},ne={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("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate (proceed even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ae={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 --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler16.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},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{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}]},ie={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("../packem_chunks/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}]},se={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)"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{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}]},le={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"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String}]},pe={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"]],group:"Data",loader:()=>import("../packem_chunks/handler18.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:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{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}]},de={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"]],group:"Deploy",loader:()=>import("../packem_chunks/handler19.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: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean}]},ce={description:"Open the Lunora studio in your browser (local dev by default, --remote for production)",examples:[["lunora view","Open the studio for local dev"],["lunora view --remote","Open the deployed studio"]],group:"Project",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},ue={filterStacktrace:()=>!1,hideErrorCodeView:!0},me=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=B(v(e)?{code:e.code,hint:e.hint,message:r}:r),n=new j({hint:o===void 0?void 0:A(o).split(`
2
+ `),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",I(n,ue)},ge=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},he=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ge(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},ye=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,fe=1440*60*1e3,ve=1500,be="0.0.0",we=/^v/u,ke=new Set(["alpha","beta","next"]),c=e=>{const t=e.trim().replace(we,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},h=e=>{const[t,r,o]=c(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Se=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},xe=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Se(a,i)}return 0},Oe=(e,t)=>{const r=h(e),o=h(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return xe(c(e).prerelease,c(t).prerelease)},Ne=e=>{const t=c(e).prerelease.split(".")[0]??"";return ke.has(t)?t:"latest"},Re=(e,t)=>Oe(t,e)>0,Be=(e,t,r)=>t-e<r,Ae=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,w=e=>d(e,"lunora-cli-update.json"),Le=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:d(P(),".cache"),r=d(t,"lunora");try{x(r,{mode:448,recursive:!0})}catch{}return r},De=e=>{try{const t=JSON.parse(f(w(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},y=(e,t)=>{try{const r=w(e);try{if(O(r).isSymbolicLink())return}catch{}N(r,`${JSON.stringify(t)}
3
+ `,"utf8")}catch{}},Ce=async(e,t)=>{try{const r=await e(ye(t),{signal:AbortSignal.timeout(ve)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Ee=(e,t,r)=>e===be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,je=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ee(e.current,t,r))return;const o=e.cacheDir??Le(t),n=(e.now??Date.now)(),a=e.ttlMs??fe,i=Ne(e.current),l=De(o),S=l?.tag??"latest",u=l!==void 0&&S===i?l:void 0;let p=u?.latest;if(u===void 0||!Be(u.checkedAt,n,a)){const m=await Ce(e.fetchImpl??globalThis.fetch,i);m===void 0?y(o,{checkedAt:n,latest:e.current,tag:i}):(p=m,y(o,{checkedAt:n,latest:m,tag:i}))}p!==void 0&&Re(e.current,p)&&e.logger.warn(Ae(e.current,p,i))},Ie=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Pe=8,Te=()=>{try{let e=g(R(import.meta.url));for(let t=0;t<Pe;t+=1){try{const o=JSON.parse(f(d(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=g(e);if(r===e)break;e=r}}catch{}return"0.0.0"},k=Te(),_e=[Q,T,q,M,U,J,W,ne,ee,K,te,le,X,ie,oe,G,Y,pe,Z,$,de,z,H,V,_,ce,F,ae,se,re],$e=e=>{const t={value:0},r=D("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:k});for(const o of _e)r.addCommand(o);return r.addCommand(E),r.addCommand(C),{cli:r,exitCode:t}},Ue=/Command "(?<name>[^"]+)" not found/u,Me=e=>{const t=b(),r=e instanceof Error?e.message:String(e),o=Ue.exec(r);if(!o?.groups){v(e)||L(r)!==void 0?t.error(me(e)):t.error(r);return}const n=o.groups.name??"",a=he(n,Ie);t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation.")},Xe=async(e={})=>{const{cli:t,exitCode:r}=$e(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Me(o),1}return await je({current:k,logger:b()}),r.value};export{Ie as COMMANDS,k as VERSION,Xe as runCli};
@@ -1,19 +1,19 @@
1
- import{existsSync as g,readFileSync as m,writeFileSync as h,mkdirSync as k,mkdtempSync as ee,rmSync as O}from"node:fs";import{dirname as w,join as l,relative as P}from"@visulima/path";import{DEV_VARS_FILE as te,parseDevVariableEntries as re,findWranglerFile as ne,readWranglerJsonc as oe}from"@lunora/config";import{modify as q,applyEdits as L,parse as se}from"jsonc-parser";import{fileURLToPath as ie}from"node:url";import{LunoraError as v}from"@lunora/errors";import{i as ae}from"./tui-prompts-CCt3jm1k.mjs";import{collectCatalog as ce,buildRegistryIndex as ue}from"./buildRegistryIndex-DwySASBu.mjs";import{insertSchemaExtension as fe}from"./insertSchemaExtension-DZReBZ4_.mjs";import{createHash as de}from"node:crypto";import{tmpdir as le}from"node:os";import{downloadTemplate as pe}from"giget";import ge from"./parseManifest-x3WsxKHz.mjs";const me="alpha",W="main",$e=new Set(["alpha","beta","next"]),he=/^[\w./@-]+$/,ye=e=>!e.includes("..")&&he.test(e),z=()=>{try{let e=w(ie(import.meta.url));for(let t=0;t<6;t+=1){const r=l(e,"package.json");if(g(r)){const o=JSON.parse(m(r,"utf8"));if(o.name==="@lunora/cli"&&typeof o.version=="string")return o.version}const n=w(e);if(n===e)break;e=n}}catch{}return"0.0.0"},M=e=>{if(e==="0.0.0")return me;const t=e.split("+")[0]??e,r=t.indexOf("-");if(r!==-1){const[n]=t.slice(r+1).split(".");if(n!==void 0&&$e.has(n))return n}return W},U=e=>{if(e!==void 0&&e.length>0){if(!ye(e))throw new v("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return M(z())},j="anolilab/lunora",V=/^[0-9a-f]{40}$/iu,B=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,ve=new RegExp(String.raw`^v?${B}$`,"u"),we=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${B}$`,"u"),be=e=>V.test(e)||ve.test(e)||we.test(e),Se=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},ke=async e=>{try{const t=await fetch(`https://api.github.com/repos/${j}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...Se()},signal:AbortSignal.timeout(1e4)});if(!t.ok)return;const r=await t.json();return typeof r.sha=="string"&&V.test(r.sha)?r.sha:void 0}catch{return}},je=async(e,t)=>{const r=U(e);if(be(r))return r;const n=await ke(r);return n===void 0?(t.warn(`could not pin ${j}#${r} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),r):(t.info(`pinned ${j}#${r} → ${n}`),n)},xe="latest",Ne=(e=z())=>{const t=M(e);return t===W?xe:t},Oe="https://registry.npmjs.org",Re=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:Oe;return t.endsWith("/")?t.slice(0,-1):t},Ae=async(e,t)=>{try{const r=await fetch(`${Re()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return r.ok?(await r.json())["dist-tags"]?.[t]:void 0}catch{return}},kt=async(e,t)=>{const r=new Map;return await Promise.all([...new Set(e)].map(async n=>{const o=await Ae(n,t);o!==void 0&&r.set(n,o)})),r},Ee=e=>{if(!e.startsWith("workspace:"))return e;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"?Ne():t},Te=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),_e=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,Je=e=>{const t=l(e,"package.json");if(!g(t))return!1;try{const r=JSON.parse(m(t,"utf8"));return r.dependencies?.lunorash!==void 0||r.devDependencies?.lunorash!==void 0}catch{return!1}},De=e=>e.replaceAll(_e,(t,r,n,o)=>`${r}lunorash/${n}${o??""}${r}`),R=(e,t,r,n="dependencies",o=!1)=>{const s=Object.entries(e);if(s.length===0)return[];const c=l(t,"package.json");if(!g(c))return r.warn(`package.json not found at ${c} — skipping dependency updates`),[];let a=m(c,"utf8");const i=JSON.parse(a),u=[];for(const[f,d]of s){if(o&&Te.has(f)){r.info(`dep provided by the lunorash umbrella, skipping: ${f}`);continue}if(i.dependencies?.[f]!==void 0||i.devDependencies?.[f]!==void 0){r.info(`dep already present: ${f}`);continue}const p=q(a,[n,f],Ee(d),{formattingOptions:{insertSpaces:!0,tabSize:4}});a=L(a,p),u.push(f)}return u.length>0&&(h(c,a,"utf8"),r.success(`added ${String(u.length)} ${n==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${u.join(", ")}`)),u},Ie=(e,t,r)=>{if(e.length===0)return[];const n=l(t,te),o=g(n)?m(n,"utf8"):"",s=new Set(re(o).map(u=>u.key)),c=[],a=[],i=[];for(const u of e)u.secret&&a.push(u.name),!s.has(u.name)&&(u.description&&i.push(`# ${u.description}`),i.push(`${u.name}=${u.secret?"":u.value??""}`),c.push(u.name));if(c.length>0){const u=o===""||o.endsWith(`
1
+ import{existsSync as g,readFileSync as m,writeFileSync as y,mkdirSync as j,mkdtempSync as ee,rmSync as O}from"node:fs";import{dirname as w,join as l,relative as P}from"@visulima/path";import{DEV_VARS_FILE as te,parseDevVariableEntries as re,findWranglerFile as ne,readWranglerJsonc as oe}from"@lunora/config";import{modify as q,applyEdits as L,parse as se}from"jsonc-parser";import{fileURLToPath as ie}from"node:url";import{LunoraError as v}from"@lunora/errors";import{i as ae}from"./tui-prompts-CCt3jm1k.mjs";import{collectCatalog as ce,buildRegistryIndex as ue}from"./buildRegistryIndex-DwySASBu.mjs";import{insertSchemaExtension as de}from"./insertSchemaExtension-DZReBZ4_.mjs";import{createHash as fe}from"node:crypto";import{tmpdir as le}from"node:os";import{downloadTemplate as pe}from"giget";import ge from"./parseManifest-x3WsxKHz.mjs";const me="alpha",W="main",$e=new Set(["alpha","beta","next"]),he=/^[\w./@-]+$/,ye=e=>!e.includes("..")&&he.test(e),z=()=>{try{let e=w(ie(import.meta.url));for(let t=0;t<6;t+=1){const r=l(e,"package.json");if(g(r)){const o=JSON.parse(m(r,"utf8"));if(o.name==="@lunora/cli"&&typeof o.version=="string")return o.version}const n=w(e);if(n===e)break;e=n}}catch{}return"0.0.0"},M=e=>{if(e==="0.0.0")return me;const t=e.split("+")[0]??e,r=t.indexOf("-");if(r!==-1){const[n]=t.slice(r+1).split(".");if(n!==void 0&&$e.has(n))return n}return W},U=e=>{if(e!==void 0&&e.length>0){if(!ye(e))throw new v("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return M(z())},x="anolilab/lunora",V=/^[0-9a-f]{40}$/iu,B=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,ve=new RegExp(String.raw`^v?${B}$`,"u"),we=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${B}$`,"u"),be=e=>V.test(e)||ve.test(e)||we.test(e),ke=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},Se=async e=>{try{const t=await fetch(`https://api.github.com/repos/${x}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...ke()},signal:AbortSignal.timeout(1e4)});if(!t.ok)return;const r=await t.json();return typeof r.sha=="string"&&V.test(r.sha)?r.sha:void 0}catch{return}},je=async(e,t)=>{const r=U(e);if(be(r))return r;const n=await Se(r);return n===void 0?(t.warn(`could not pin ${x}#${r} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),r):(t.info(`pinned ${x}#${r} → ${n}`),n)},xe="latest",Ne=(e=z())=>{const t=M(e);return t===W?xe:t},Oe="https://registry.npmjs.org",Re=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:Oe;return t.endsWith("/")?t.slice(0,-1):t},Ae=async(e,t)=>{try{const r=await fetch(`${Re()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return r.ok?(await r.json())["dist-tags"]?.[t]:void 0}catch{return}},St=async(e,t)=>{const r=new Map;return await Promise.all([...new Set(e)].map(async n=>{const o=await Ae(n,t);o!==void 0&&r.set(n,o)})),r},Ee=e=>{if(!e.startsWith("workspace:"))return e;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"?Ne():t},Te=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),_e=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,Je=e=>{const t=l(e,"package.json");if(!g(t))return!1;try{const r=JSON.parse(m(t,"utf8"));return r.dependencies?.lunorash!==void 0||r.devDependencies?.lunorash!==void 0}catch{return!1}},De=e=>e.replaceAll(_e,(t,r,n,o)=>`${r}lunorash/${n}${o??""}${r}`),R=(e,t,r,n="dependencies",o=!1)=>{const s=Object.entries(e);if(s.length===0)return[];const c=l(t,"package.json");if(!g(c))return r.warn(`package.json not found at ${c} — skipping dependency updates`),[];let a=m(c,"utf8");const i=JSON.parse(a),u=[];for(const[d,f]of s){if(o&&Te.has(d)){r.info(`dep provided by the lunorash umbrella, skipping: ${d}`);continue}if(i.dependencies?.[d]!==void 0||i.devDependencies?.[d]!==void 0){r.info(`dep already present: ${d}`);continue}const p=q(a,[n,d],Ee(f),{formattingOptions:{insertSpaces:!0,tabSize:4}});a=L(a,p),u.push(d)}return u.length>0&&(y(c,a,"utf8"),r.success(`added ${String(u.length)} ${n==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${u.join(", ")}`)),u},Ie=(e,t,r)=>{if(e.length===0)return[];const n=l(t,te),o=g(n)?m(n,"utf8"):"",s=new Set(re(o).map(u=>u.key)),c=[],a=[],i=[];for(const u of e)u.secret&&a.push(u.name),!s.has(u.name)&&(u.description&&i.push(`# ${u.description}`),i.push(`${u.name}=${u.secret?"":u.value??""}`),c.push(u.name));if(c.length>0){const u=o===""||o.endsWith(`
2
2
  `)?o:`${o}
3
- `;h(n,`${u}${i.join(`
3
+ `;y(n,`${u}${i.join(`
4
4
  `)}
5
- `,"utf8"),r.success(`scaffolded ${String(c.length)} env var(s) into .dev.vars: ${c.join(", ")}`)}return a.length>0&&r.info(`set secret value(s) locally in .dev.vars, then for production: ${a.map(u=>`wrangler secret put ${u}`).join("; ")}`),c},A=new Set(["ai","analytics_engine_datasets","browser","d1_databases","durable_objects","hyperdrive","kv_namespaces","mtls_certificates","queues","r2_buckets","send_email","services","vars","vectorize","version_metadata","workflows"]),Pe=(e,t,r)=>{if(e.length===0)return[];const n=["wrangler.jsonc","wrangler.json"].map(i=>l(t,i)).find(i=>g(i));if(!n)return r.warn("wrangler.jsonc not found — skipping binding updates"),[];let o=m(n,"utf8");const s=[],c=i=>Array.isArray(i),a=i=>{let u=se(o);for(const f of i){if(typeof u!="object"||u===null)return;u=u[f]}return u};for(const i of e){const u=i.path[0];if(u===void 0||!A.has(u)){r.warn(`skipping binding "${i.path.join(".")}" — only resource bindings (${[...A].join(", ")}) may be written, not exec/entrypoint keys`);continue}let{value:f}=i;if(c(f)){const p=a(i.path);if(c(p)){const $=new Set(p.map(y=>JSON.stringify(y)));f=[...p,...f.filter(y=>!$.has(JSON.stringify(y)))]}}const d=q(o,[...i.path],f,{formattingOptions:{insertSpaces:!0,tabSize:4}});d.length!==0&&(o=L(o,d),s.push(i.path.join(".")))}return s.length>0&&(h(n,o,"utf8"),r.success(`applied ${String(s.length)} binding(s) to ${n}: ${s.join(", ")}`)),s},qe=(e,t,r,n=!1)=>{const o=[],s=[];return e.deps&&o.push(...R(e.deps,t,r,"dependencies",n)),e.devDependencies&&o.push(...R(e.devDependencies,t,r,"devDependencies",n)),e.bindings&&s.push(...Pe(e.bindings,t,r)),e.envVars&&Ie(e.envVars,t,r),{bindings:s,deps:o}},Le=async(e,t)=>{const r=e.some(({manifest:i})=>Object.keys(i.deps??{}).length>0||Object.keys(i.devDependencies??{}).length>0),n=e.some(({manifest:i})=>(i.bindings??[]).length>0),o=t.source!==void 0&&t.source.length>0;if(!r&&!n&&!o||t.yes)return!0;const s=[];r&&s.push("add dependencies to package.json"),n&&s.push("write wrangler.jsonc bindings"),o&&s.push(`come from a non-default source (${String(t.source)})`);const c=s.join(", ");if(!process.stdin.isTTY&&t.confirm===void 0)return t.logger.error(`add: stdin is not a TTY and the requested items ${c} — re-run with --yes to confirm`),!1;const a=await(t.confirm??ae)(`The requested items ${c}. Continue?`);return a||t.logger.info("add: aborted"),a},S=1,We=".lunora-registry.json",F=e=>l(e,"lunora",We),ze=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,x=e=>de("sha256").update(e).digest("hex"),Me=e=>{const t=F(e);if(!g(t))return{items:{},version:S};try{const r=JSON.parse(m(t,"utf8"));if(ze(r))return{items:r.items,version:S}}catch{}return{items:{},version:S}},Ue=(e,t)=>{h(F(e),`${JSON.stringify(t,void 0,2)}
6
- `,"utf8")},E=(e,t,r,n)=>{const o=e.items[t],s=o??{files:{}};o===void 0&&(e.items[t]=s),s.files[r]=x(n)},Ve=(e,t,r)=>e.items[t]?.files[r],T=e=>e===""?[]:e.split(`
7
- `),Be=(e,t)=>{const r=T(e),n=T(t);let o=0;for(;o<r.length&&o<n.length&&r[o]===n[o];)o+=1;let s=r.length,c=n.length;for(;s>o&&c>o&&r[s-1]===n[c-1];)s-=1,c-=1;if(o===s&&o===c)return[];const a=[];for(let i=Math.max(0,o-3);i<o;i+=1)a.push(` ${r[i]??""}`);for(let i=o;i<s;i+=1)a.push(`- ${r[i]??""}`);for(let i=o;i<c;i+=1)a.push(`+ ${n[i]??""}`);for(let i=c;i<Math.min(n.length,c+3);i+=1)a.push(` ${n[i]??""}`);return a},Fe=/\.[cm]?[jt]sx?$/u,H=(e,t,r)=>{const n=m(l(e,t.from),"utf8");return r&&Fe.test(t.to)?De(n):n},He=(e,t,r,n,o,s,c)=>{const a=l(n,"lunora","schema.ts");if(s)return o.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:a};const i=l(n,e.to);g(i)||(k(w(i),{recursive:!0}),h(i,H(r,e,c),"utf8"));const u=c?"lunorash/server":"@lunora/server",f=g(a)?m(a,"utf8"):`import { defineSchema } from "${u}";
5
+ `,"utf8"),r.success(`scaffolded ${String(c.length)} env var(s) into .dev.vars: ${c.join(", ")}`)}return a.length>0&&r.info(`set secret value(s) locally in .dev.vars, then for production: ${a.map(u=>`wrangler secret put ${u}`).join("; ")}`),c},A=new Set(["ai","analytics_engine_datasets","browser","d1_databases","durable_objects","hyperdrive","kv_namespaces","mtls_certificates","queues","r2_buckets","send_email","services","vars","vectorize","version_metadata","workflows"]),Pe=(e,t,r)=>{if(e.length===0)return[];const n=["wrangler.jsonc","wrangler.json"].map(i=>l(t,i)).find(i=>g(i));if(!n)return r.warn("wrangler.jsonc not found — skipping binding updates"),[];let o=m(n,"utf8");const s=[],c=i=>Array.isArray(i),a=i=>{let u=se(o);for(const d of i){if(typeof u!="object"||u===null)return;u=u[d]}return u};for(const i of e){const u=i.path[0];if(u===void 0||!A.has(u)){r.warn(`skipping binding "${i.path.join(".")}" — only resource bindings (${[...A].join(", ")}) may be written, not exec/entrypoint keys`);continue}let{value:d}=i;if(c(d)){const p=a(i.path);if(c(p)){const $=new Set(p.map(h=>JSON.stringify(h)));d=[...p,...d.filter(h=>!$.has(JSON.stringify(h)))]}}const f=q(o,[...i.path],d,{formattingOptions:{insertSpaces:!0,tabSize:4}});f.length!==0&&(o=L(o,f),s.push(i.path.join(".")))}return s.length>0&&(y(n,o,"utf8"),r.success(`applied ${String(s.length)} binding(s) to ${n}: ${s.join(", ")}`)),s},qe=(e,t,r,n=!1)=>{const o=[],s=[];return e.deps&&o.push(...R(e.deps,t,r,"dependencies",n)),e.devDependencies&&o.push(...R(e.devDependencies,t,r,"devDependencies",n)),e.bindings&&s.push(...Pe(e.bindings,t,r)),e.envVars&&Ie(e.envVars,t,r),{bindings:s,deps:o}},Le=async(e,t)=>{const r=e.some(({manifest:i})=>Object.keys(i.deps??{}).length>0||Object.keys(i.devDependencies??{}).length>0),n=e.some(({manifest:i})=>(i.bindings??[]).length>0),o=t.source!==void 0&&t.source.length>0;if(!r&&!n&&!o||t.yes)return!0;const s=[];r&&s.push("add dependencies to package.json"),n&&s.push("write wrangler.jsonc bindings"),o&&s.push(`come from a non-default source (${String(t.source)})`);const c=s.join(", ");if(!process.stdin.isTTY&&t.confirm===void 0)return t.logger.error(`add: stdin is not a TTY and the requested items ${c} — re-run with --yes to confirm`),!1;const a=await(t.confirm??ae)(`The requested items ${c}. Continue?`);return a||t.logger.info("add: aborted"),a},S=1,We=".lunora-registry.json",F=e=>l(e,"lunora",We),ze=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,b=e=>fe("sha256").update(e).digest("hex"),Me=e=>{const t=F(e);if(!g(t))return{items:{},version:S};try{const r=JSON.parse(m(t,"utf8"));if(ze(r))return{items:r.items,version:S}}catch{}return{items:{},version:S}},Ue=(e,t)=>{y(F(e),`${JSON.stringify(t,void 0,2)}
6
+ `,"utf8")},E=(e,t,r,n)=>{const o=e.items[t],s=o??{files:{}};o===void 0&&(e.items[t]=s),s.files[r]=b(n)},Ve=(e,t,r)=>e.items[t]?.files[r],T=e=>e===""?[]:e.split(`
7
+ `),Be=(e,t)=>{const r=T(e),n=T(t);let o=0;for(;o<r.length&&o<n.length&&r[o]===n[o];)o+=1;let s=r.length,c=n.length;for(;s>o&&c>o&&r[s-1]===n[c-1];)s-=1,c-=1;if(o===s&&o===c)return[];const a=[];for(let i=Math.max(0,o-3);i<o;i+=1)a.push(` ${r[i]??""}`);for(let i=o;i<s;i+=1)a.push(`- ${r[i]??""}`);for(let i=o;i<c;i+=1)a.push(`+ ${n[i]??""}`);for(let i=c;i<Math.min(n.length,c+3);i+=1)a.push(` ${n[i]??""}`);return a},Fe=/\.[cm]?[jt]sx?$/u,H=(e,t,r)=>{const n=m(l(e,t.from),"utf8");return r&&Fe.test(t.to)?De(n):n},He=(e,t,r,n,o,s,c)=>{const a=l(n,"lunora","schema.ts");if(s)return o.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:a};const i=l(n,e.to);g(i)||(j(w(i),{recursive:!0}),y(i,H(r,e,c),"utf8"));const u=c?"lunorash/server":"@lunora/server",d=g(a)?m(a,"utf8"):`import { defineSchema } from "${u}";
8
8
 
9
9
  export const schema = defineSchema({});
10
- `,d=fe(f,t);if(d.ok)return k(w(a),{recursive:!0}),h(a,d.text,"utf8"),o.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:a};if(d.reason==="already-applied")return o.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:a};throw d.reason==="invalid-identifier"?new v("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new v("INTERNAL",`schema-extension merge failed for "${t}": ${d.reason}`)},Ge=(e,t,r,n,o)=>{const s=Be(t,r);if(s.length===0){o.info(`= ${e.to} (unchanged)`);return}o.info(`${n?"~":"+"} ${e.to}`);for(const c of s)o.info(` ${c}`)},Ze=(e,t,r,n,o,s,c,a)=>{const i=l(n,e.to),u=H(r,e,a),f=g(i),d=f?m(i,"utf8"):"",p=X=>(k(w(i),{recursive:!0}),h(i,u,"utf8"),E(s,t,e.to,u),o.success(`${X}: ${e.to}`),{kind:"written",path:i});if(c.diff)return Ge(e,d,u,f,o),{kind:"skipped",path:i};if(!f)return p("write");const $=x(d);if($===x(u))return E(s,t,e.to,u),o.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:i};if(c.overwrite)return p("overwrite");const y=Ve(s,t,e.to);return y===void 0?(o.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:i}):y===$?p("update"):(h(`${i}.new`,u,"utf8"),o.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:i})},Ce=(e,t,r,n,o,s,c={},a=!1)=>e.merge==="schema-extension"?He(e,t,r,n,o,c.diff===!0,a):Ze(e,t,r,n,o,s,c,a),_=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Ke=e=>{const t=ne(e);if(t===void 0)return;const{parsed:r}=oe(t);return typeof r?.main=="string"?r.main:void 0},Ye=e=>{const t=Ke(e),r=t===void 0?_:[t,..._];for(const n of r){const o=l(e,n);if(!g(o))continue;const s=m(o,"utf8");if(!s.includes("createShardDO(")){if(n===t)break;continue}return{entryPath:o,main:n,source:s}}},Qe=(e,t,r)=>{const n=P(w(e),l(t,"lunora",r)).replaceAll("\\","/");return n.startsWith(".")?n:`./${n}`},Xe=(e,t)=>{for(const r of e){const n=`Add \`export * from "${`./lunora/${r.module}.js`}"\` to your worker entry`,o=r.comment?` (${r.comment})`:"";t.warn(`${n}${o}`)}return 0},et=(e,t,r,n)=>{const o=[];for(const s of e){const c=Qe(t,r,s.module),a=c.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${a}\.js["']`,"u").test(n)||(s.comment&&o.push(`
10
+ `,f=de(d,t);if(f.ok)return j(w(a),{recursive:!0}),y(a,f.text,"utf8"),o.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:a};if(f.reason==="already-applied")return o.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:a};throw f.reason==="invalid-identifier"?new v("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new v("INTERNAL",`schema-extension merge failed for "${t}": ${f.reason}`)},Ge=(e,t,r,n,o)=>{const s=Be(t,r);if(s.length===0){o.info(`= ${e.to} (unchanged)`);return}o.info(`${n?"~":"+"} ${e.to}`);for(const c of s)o.info(` ${c}`)},Ze=(e,t,r,n,o,s,c,a)=>{const i=l(n,e.to),u=H(r,e,a),d=g(i),f=d?m(i,"utf8"):"",p=X=>(j(w(i),{recursive:!0}),y(i,u,"utf8"),E(s,t,e.to,u),o.success(`${X}: ${e.to}`),{kind:"written",path:i});if(c.diff)return Ge(e,f,u,d,o),{kind:"skipped",path:i};if(!d)return p("write");const $=b(f);if($===b(u))return E(s,t,e.to,u),o.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:i};if(c.overwrite)return p("overwrite");const h=Ve(s,t,e.to);return h===void 0?(o.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:i}):h===$?p("update"):h===b(u)?(o.warn(`skip (locally edited): ${e.to}`),{kind:"skipped",path:i}):(y(`${i}.new`,u,"utf8"),o.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:i})},Ce=(e,t,r,n,o,s,c={},a=!1)=>e.merge==="schema-extension"?He(e,t,r,n,o,c.diff===!0,a):Ze(e,t,r,n,o,s,c,a),_=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Ke=e=>{const t=ne(e);if(t===void 0)return;const{parsed:r}=oe(t);return typeof r?.main=="string"?r.main:void 0},Ye=e=>{const t=Ke(e),r=t===void 0?_:[t,..._];for(const n of r){const o=l(e,n);if(!g(o))continue;const s=m(o,"utf8");if(!s.includes("createShardDO(")){if(n===t)break;continue}return{entryPath:o,main:n,source:s}}},Qe=(e,t,r)=>{const n=P(w(e),l(t,"lunora",r)).replaceAll("\\","/");return n.startsWith(".")?n:`./${n}`},Xe=(e,t)=>{for(const r of e){const n=`Add \`export * from "${`./lunora/${r.module}.js`}"\` to your worker entry`,o=r.comment?` (${r.comment})`:"";t.warn(`${n}${o}`)}return 0},et=(e,t,r,n)=>{const o=[];for(const s of e){const c=Qe(t,r,s.module),a=c.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${a}\.js["']`,"u").test(n)||(s.comment&&o.push(`
11
11
  // ${s.comment}`),o.push(`export * from "${c}.js";`))}return o},tt=(e,t,r,n)=>{if(e.length===0)return 0;const o=Ye(t);if(o===void 0)return Xe(e,r);const s=et(e,o.entryPath,t,o.source);if(s.length===0)return 0;if(n){for(const a of s)a!==""&&r.info(`~ entrypoint: ${a}`);return s.length}const c=o.source.endsWith(`
12
12
  `)?"":`
13
- `;return h(o.entryPath,`${o.source}${c}${s.join(`
13
+ `;return y(o.entryPath,`${o.source}${c}${s.join(`
14
14
  `)}
15
- `,"utf8"),r.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${P(t,o.entryPath)}`),s.length},J=(e,t,r,n={})=>{const o=[],s=[],c=[],a=[],i=Me(t),u=Je(t);for(const{directory:f,manifest:d}of e){for(const $ of d.files){const y=Ce($,d.name,f,t,r,i,n,u);(y.kind==="written"?o:s).push(y.path)}if(d.entrypointReexports!==void 0&&tt(d.entrypointReexports,t,r,n.diff===!0),n.diff)continue;const p=qe(d,t,r,u);c.push(...p.deps),a.push(...p.bindings)}return!n.diff&&Object.keys(i.items).length>0&&Ue(t,i),{bindings:a,deps:c,skipped:s,written:o}},G="gh:anolilab/lunora/registry",D=/^[A-Za-z0-9][\w-]*$/u,rt=e=>{if(!D.test(e))throw new v("INTERNAL",`invalid registry item name "${e}" — names must match ${D.source} (letters, digits, "-", "_"; no path separators or "..")`)},nt=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),ot=e=>e.from===void 0&&e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!nt(e.source),N=(e,t)=>ot(t)?`${e}: refusing --source ${String(t.source)} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`:void 0,Z=async(e,t,r)=>{const n=ee(l(le(),`lunora-${t}-fetch-`)),o=l(n,t);r.info(`fetching ${e}`);try{const s=await pe(e,{cwd:n,dir:o,force:!0,install:!1,silent:!0});return r.info(s.commit?`resolved ${s.source} @ ${s.commit}`:`resolved ${s.source}`),{cleanup:()=>{O(n,{force:!0,recursive:!0})},directory:o}}catch(s){throw O(n,{force:!0,recursive:!0}),s}},I=new WeakMap,C=async e=>{const t=I.get(e);if(t!==void 0)return t;const r=e.source!==void 0&&e.source.length>0?Promise.resolve(U(e.ref)):je(e.ref,e.logger);return I.set(e,r),r},K=async(e,t)=>{if(rt(e),t.from!==void 0){const n=l(t.from,e);if(!g(n))throw new v("INTERNAL",`registry item not found in local source: ${n}`);return{cleanup:()=>{},directory:n}}const r=t.source??G;return Z(`${r}/${e}#${await C(t)}`,"item",t.logger)},st=async e=>{if(e.from!==void 0){if(!g(e.from))throw new v("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??G,{cleanup:r,directory:n}=await Z(`${t}#${await C(e)}`,"registry",e.logger);return{cleanup:r,root:n}},Y=(e,t)=>{const r=JSON.parse(m(l(e,"registry.json"),"utf8"));return ge(r,t)},it=async(e,t)=>{const r=[],n=[],o=new Set,s=new Set,c=async a=>{if(o.has(a))return;if(s.has(a))throw new v("INTERNAL",`cyclic registry dependency detected at "${a}"`);s.add(a);const{cleanup:i,directory:u}=await K(a,t);n.push(i);const f=Y(u,a);for(const d of f.requires??[])await c(d);s.delete(a),o.add(a),r.push({directory:u,manifest:f})};try{for(const a of e)await c(a)}catch(a){for(const i of n)i();throw a}return{cleanups:n,items:r}},b=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),jt=(e,t,r,n,o)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const c=s.value;return{...s,value:c.map(a=>typeof a=="object"&&a!==null&&a[r.key]===r.value?{...a,[n]:o}:a)}})}:e,Q=(e,t)=>{const r=t.title??t.description;e.info(`plan: ${t.name}${r?` — ${r}`:""}`);for(const n of t.files)e.info(` file ${n.to} (${n.merge})`);for(const[n,o]of Object.entries(t.deps??{}))e.info(` dep ${n}@${o}`);for(const[n,o]of Object.entries(t.devDependencies??{}))e.info(` dev ${n}@${o}`);for(const n of t.bindings??[])e.info(` bind ${n.path.join(".")} = ${JSON.stringify(n.value)}`);for(const n of t.envVars??[]){const o=n.secret?" (secret)":` = ${JSON.stringify(n.value??"")}`;e.info(` env ${n.name}${o}`)}for(const n of t.entrypointReexports??[]){const o=`./lunora/${n.module}`,s=n.comment?` // ${n.comment}`:"";e.info(` entry ${o}${s}`)}},at=e=>{const t=e.map(({manifest:r})=>({bindings:(r.bindings??[]).map(n=>({path:n.path.join("."),value:n.value})),deps:Object.keys(r.deps??{}),devDependencies:Object.keys(r.devDependencies??{}),entrypointReexports:(r.entrypointReexports??[]).map(n=>({module:n.module,...n.comment?{comment:n.comment}:{}})),envVars:(r.envVars??[]).map(n=>({name:n.name,...n.secret?{secret:!0}:{value:n.value??""}})),files:r.files.map(n=>({merge:n.merge,to:n.to})),name:r.name,requires:r.requires??[],title:r.title}));process.stdout.write(`${JSON.stringify({items:t},void 0,2)}
16
- `)},ct=(e,t,r,n,o)=>{o.success(`add complete: ${String(r)} written, ${String(n)} skipped`),o.info("next steps:"),o.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&o.info(" pnpm install # install newly-added dependencies");for(const{manifest:s}of e)s.docs&&o.info(`${s.name}: ${s.docs}`)},ut=async e=>{const t=b(),r=N("list",e);if(r)return e.logger.error(r),{...t,code:1};let n=()=>{};try{const o=await st(e);n=o.cleanup;const s=ce(o.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
17
- `),t;e.logger.info(`available registry items (${String(s.length)}):`);for(const c of s)e.logger.info(` ${c.name}${c.description?` — ${c.description}`:""}`);return t}catch(o){return e.logger.error(`list failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{n()}},xt=async e=>{const t=e.cwd??process.cwd(),r=b();if(e.list)return ut(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...r,code:1};const n=N("add",e);if(n)return e.logger.error(n),{...r,code:1};let o=[];try{const{cleanups:s,items:c}=await it(e.names,e);o=s;const{transformManifest:a}=e,i=a?c.map($=>({...$,manifest:a($.manifest)})):c;for(const{manifest:$}of i)Q(e.logger,$);if(e.json&&at(i),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),r;if(e.diff)return J(i,t,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),r;if(!await Le(i,e))return{...r,code:1};const{bindings:u,deps:f,skipped:d,written:p}=J(i,t,e.logger,{overwrite:e.overwrite});return ct(i,f,p.length,d.length,e.logger),{bindings:u,code:0,deps:f,skipped:d,written:p}}catch(s){return e.logger.error(`add failed: ${s instanceof Error?s.message:String(s)}`),{...r,code:1}}finally{for(const s of o)s()}},Nt=async e=>{const t=b();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...t,code:1};const r=N("view",e);if(r)return e.logger.error(r),{...t,code:1};const n=[];try{for(const o of e.names){const{cleanup:s,directory:c}=await K(o,e);n.push(s);const a=Y(c,o);Q(e.logger,a);for(const i of a.files){e.logger.info(`--- ${i.to} (${i.merge}) ---`);const u=m(l(c,i.from),"utf8");for(const f of u.split(`
18
- `))e.logger.info(f)}}return t}catch(o){return e.logger.error(`view failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{for(const o of n)o()}},Ot=async e=>{const t=b(),r=e.from;if(r===void 0)return e.logger.error("registry build requires --from <registry root>"),{...t,code:1};if(!g(r))return e.logger.error(`registry root not found: ${r}`),{...t,code:1};const n=ue(r),o=e.out??l(r,"index.json");if(e.check){const s=g(o)?JSON.parse(m(o,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(n.items)?(e.logger.error(`registry: ${o} is stale — run \`lunora registry build\` to regenerate it`),{...t,code:1}):(e.logger.success(`registry: ${o} is up to date (${String(n.items.length)} items)`),t)}return h(o,`${JSON.stringify({$schema:"./schema/registry.schema.json",...n},void 0,4)}
19
- `,"utf8"),e.logger.success(`registry: wrote ${o} (${String(n.items.length)} items)`),t};export{Ne as L,xt as M,kt as P,ut as R,je as b,jt as d,U as g,Nt as k,Ot as q};
15
+ `,"utf8"),r.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${P(t,o.entryPath)}`),s.length},J=(e,t,r,n={})=>{const o=[],s=[],c=[],a=[],i=Me(t),u=Je(t);for(const{directory:d,manifest:f}of e){for(const $ of f.files){const h=Ce($,f.name,d,t,r,i,n,u);(h.kind==="written"?o:s).push(h.path)}if(f.entrypointReexports!==void 0&&tt(f.entrypointReexports,t,r,n.diff===!0),n.diff)continue;const p=qe(f,t,r,u);c.push(...p.deps),a.push(...p.bindings)}return!n.diff&&Object.keys(i.items).length>0&&Ue(t,i),{bindings:a,deps:c,skipped:s,written:o}},G="gh:anolilab/lunora/registry",D=/^[A-Za-z0-9][\w-]*$/u,rt=e=>{if(!D.test(e))throw new v("INTERNAL",`invalid registry item name "${e}" — names must match ${D.source} (letters, digits, "-", "_"; no path separators or "..")`)},nt=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),ot=e=>e.from===void 0&&e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!nt(e.source),N=(e,t)=>ot(t)?`${e}: refusing --source ${String(t.source)} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`:void 0,Z=async(e,t,r)=>{const n=ee(l(le(),`lunora-${t}-fetch-`)),o=l(n,t);r.info(`fetching ${e}`);try{const s=await pe(e,{cwd:n,dir:o,force:!0,install:!1,silent:!0});return r.info(s.commit?`resolved ${s.source} @ ${s.commit}`:`resolved ${s.source}`),{cleanup:()=>{O(n,{force:!0,recursive:!0})},directory:o}}catch(s){throw O(n,{force:!0,recursive:!0}),s}},I=new WeakMap,C=async e=>{const t=I.get(e);if(t!==void 0)return t;const r=e.source!==void 0&&e.source.length>0?Promise.resolve(U(e.ref)):je(e.ref,e.logger);return I.set(e,r),r},K=async(e,t)=>{if(rt(e),t.from!==void 0){const n=l(t.from,e);if(!g(n))throw new v("INTERNAL",`registry item not found in local source: ${n}`);return{cleanup:()=>{},directory:n}}const r=t.source??G;return Z(`${r}/${e}#${await C(t)}`,"item",t.logger)},st=async e=>{if(e.from!==void 0){if(!g(e.from))throw new v("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??G,{cleanup:r,directory:n}=await Z(`${t}#${await C(e)}`,"registry",e.logger);return{cleanup:r,root:n}},Y=(e,t)=>{const r=JSON.parse(m(l(e,"registry.json"),"utf8"));return ge(r,t)},it=async(e,t)=>{const r=[],n=[],o=new Set,s=new Set,c=async a=>{if(o.has(a))return;if(s.has(a))throw new v("INTERNAL",`cyclic registry dependency detected at "${a}"`);s.add(a);const{cleanup:i,directory:u}=await K(a,t);n.push(i);const d=Y(u,a);for(const f of d.requires??[])await c(f);s.delete(a),o.add(a),r.push({directory:u,manifest:d})};try{for(const a of e)await c(a)}catch(a){for(const i of n)i();throw a}return{cleanups:n,items:r}},k=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),jt=(e,t,r,n,o)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const c=s.value;return{...s,value:c.map(a=>typeof a=="object"&&a!==null&&a[r.key]===r.value?{...a,[n]:o}:a)}})}:e,Q=(e,t)=>{const r=t.title??t.description;e.info(`plan: ${t.name}${r?` — ${r}`:""}`);for(const n of t.files)e.info(` file ${n.to} (${n.merge})`);for(const[n,o]of Object.entries(t.deps??{}))e.info(` dep ${n}@${o}`);for(const[n,o]of Object.entries(t.devDependencies??{}))e.info(` dev ${n}@${o}`);for(const n of t.bindings??[])e.info(` bind ${n.path.join(".")} = ${JSON.stringify(n.value)}`);for(const n of t.envVars??[]){const o=n.secret?" (secret)":` = ${JSON.stringify(n.value??"")}`;e.info(` env ${n.name}${o}`)}for(const n of t.entrypointReexports??[]){const o=`./lunora/${n.module}`,s=n.comment?` // ${n.comment}`:"";e.info(` entry ${o}${s}`)}},at=e=>{const t=e.map(({manifest:r})=>({bindings:(r.bindings??[]).map(n=>({path:n.path.join("."),value:n.value})),deps:Object.keys(r.deps??{}),devDependencies:Object.keys(r.devDependencies??{}),entrypointReexports:(r.entrypointReexports??[]).map(n=>({module:n.module,...n.comment?{comment:n.comment}:{}})),envVars:(r.envVars??[]).map(n=>({name:n.name,...n.secret?{secret:!0}:{value:n.value??""}})),files:r.files.map(n=>({merge:n.merge,to:n.to})),name:r.name,requires:r.requires??[],title:r.title}));process.stdout.write(`${JSON.stringify({items:t},void 0,2)}
16
+ `)},ct=(e,t,r,n,o)=>{o.success(`add complete: ${String(r)} written, ${String(n)} skipped`),o.info("next steps:"),o.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&o.info(" pnpm install # install newly-added dependencies");for(const{manifest:s}of e)s.docs&&o.info(`${s.name}: ${s.docs}`)},ut=async e=>{const t=k(),r=N("list",e);if(r)return e.logger.error(r),{...t,code:1};let n=()=>{};try{const o=await st(e);n=o.cleanup;const s=ce(o.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
17
+ `),t;e.logger.info(`available registry items (${String(s.length)}):`);for(const c of s)e.logger.info(` ${c.name}${c.description?` — ${c.description}`:""}`);return t}catch(o){return e.logger.error(`list failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{n()}},xt=async e=>{const t=e.cwd??process.cwd(),r=k();if(e.list)return ut(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...r,code:1};const n=N("add",e);if(n)return e.logger.error(n),{...r,code:1};let o=[];try{const{cleanups:s,items:c}=await it(e.names,e);o=s;const{transformManifest:a}=e,i=a?c.map($=>({...$,manifest:a($.manifest)})):c;for(const{manifest:$}of i)Q(e.logger,$);if(e.json&&at(i),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),r;if(e.diff)return J(i,t,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),r;if(!await Le(i,e))return{...r,code:1};const{bindings:u,deps:d,skipped:f,written:p}=J(i,t,e.logger,{overwrite:e.overwrite});return ct(i,d,p.length,f.length,e.logger),{bindings:u,code:0,deps:d,skipped:f,written:p}}catch(s){return e.logger.error(`add failed: ${s instanceof Error?s.message:String(s)}`),{...r,code:1}}finally{for(const s of o)s()}},Nt=async e=>{const t=k();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...t,code:1};const r=N("view",e);if(r)return e.logger.error(r),{...t,code:1};const n=[];try{for(const o of e.names){const{cleanup:s,directory:c}=await K(o,e);n.push(s);const a=Y(c,o);Q(e.logger,a);for(const i of a.files){e.logger.info(`--- ${i.to} (${i.merge}) ---`);const u=m(l(c,i.from),"utf8");for(const d of u.split(`
18
+ `))e.logger.info(d)}}return t}catch(o){return e.logger.error(`view failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{for(const o of n)o()}},Ot=async e=>{const t=k(),r=e.from;if(r===void 0)return e.logger.error("registry build requires --from <registry root>"),{...t,code:1};if(!g(r))return e.logger.error(`registry root not found: ${r}`),{...t,code:1};const n=ue(r),o=e.out??l(r,"index.json");if(e.check){const s=g(o)?JSON.parse(m(o,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(n.items)?(e.logger.error(`registry: ${o} is stale — run \`lunora registry build\` to regenerate it`),{...t,code:1}):(e.logger.success(`registry: ${o} is up to date (${String(n.items.length)} items)`),t)}return y(o,`${JSON.stringify({$schema:"./schema/registry.schema.json",...n},void 0,4)}
19
+ `,"utf8"),e.logger.success(`registry: wrote ${o} (${String(n.items.length)} items)`),t};export{Ne as L,xt as M,St as P,ut as R,je as b,jt as d,U as g,Nt as k,Ot as q};
@@ -1 +1 @@
1
- import"node:fs";import"@visulima/path";import{M as d,q as i,R as s,k as t}from"./commands-BhX2Bo9B.mjs";import"./buildRegistryIndex-DwySASBu.mjs";export{d as runAddCommand,i as runBuildIndexCommand,s as runListCommand,t as runRegistryViewCommand};
1
+ import"node:fs";import"@visulima/path";import{M as d,q as i,R as s,k as t}from"./commands-B1SpMXov.mjs";import"./buildRegistryIndex-DwySASBu.mjs";export{d as runAddCommand,i as runBuildIndexCommand,s as runListCommand,t as runRegistryViewCommand};
@@ -0,0 +1 @@
1
+ import{d as r}from"./commands-B1SpMXov.mjs";const o=[{description:"Email + password on better-auth (default)",label:"Email & password",value:"auth"},{description:"Clerk-hosted auth",label:"Clerk",value:"auth-clerk"},{description:"Auth0 (OIDC)",label:"Auth0",value:"auth-auth0"}],n="auth",O=async a=>await a("Which auth provider?",o,{default:n})??n,S="mail",y=[{description:"Next, react-router, TanStack Start, Astro islands",label:"React",value:"auth-ui-react"},{description:"Nuxt, Vue + Vite",label:"Vue",value:"auth-ui-vue"},{description:"SvelteKit, Svelte + Vite",label:"Svelte",value:"auth-ui-svelte"},{description:"TanStack Start Solid, Solid + Vite",label:"Solid",value:"auth-ui-solid"},{description:"Analog",label:"Angular",value:"auth-ui-angular"}],x="auth-ui-react",d=a=>Object.hasOwn(a,"react-native")||Object.hasOwn(a,"@lunora/react-native")||Object.hasOwn(a,"expo"),_=a=>{const e=t=>Object.hasOwn(a,t);if(!d(a)){if(e("@lunora/react"))return"auth-ui-react";if(e("@lunora/vue"))return"auth-ui-vue";if(e("@lunora/svelte"))return"auth-ui-svelte";if(e("@lunora/solid"))return"auth-ui-solid";if(e("@lunora/angular"))return"auth-ui-angular";if(e("react")||e("next"))return"auth-ui-react";if(e("vue")||e("nuxt"))return"auth-ui-vue";if(e("svelte")||e("@sveltejs/kit"))return"auth-ui-svelte";if(e("solid-js"))return"auth-ui-solid";if(e("@angular/core"))return"auth-ui-angular"}},A=a=>{const e=a.trim();if(e==="")return;const t=e.toLowerCase();return t==="auth-ui"||t==="auth-ui-"?{kind:"auth-ui"}:t==="auth"?{kind:"auth"}:t==="email"||t==="mail"?{kind:"email"}:{item:t,kind:"item"}},c=/[^a-z0-9]+/u,u=(a,e,t)=>{let i=a.toLowerCase().split(c).filter(Boolean).join("-").slice(0,t);return i.endsWith("-")&&(i=i.slice(0,-1)),i.length>=e?i:void 0},h="DB",v="Name your D1 database (run `wrangler d1 create` to get its id, then put it in wrangler.jsonc)",l=a=>u(a,1,64),f="lunora-db",b=a=>l(`${a}-db`)??f,V=async(a,e)=>{const t=b(e);return l(await a(v,{default:t,placeholder:t}))??t},C=(a,e)=>r(a,"d1_databases",{key:"binding",value:h},"database_name",e),m="SEND_EMAIL",D="Verified destination email for production delivery (blank = set it later in wrangler.jsonc)",p=a=>{const e=a.trim();if(e.length===0||e.includes(" "))return!1;const t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@"))return!1;const i=e.slice(t+1);return i.length>=3&&i.includes(".")&&!i.startsWith(".")&&!i.endsWith(".")},N=(a,e)=>{const t=a.trim();if(t!==""){if(!p(t)){e(`"${t}" doesn't look like an email — leaving the placeholder; set destination_address in wrangler.jsonc.`);return}return t}},E=(a,e)=>r(a,"send_email",{key:"name",value:m},"destination_address",e),$="UPLOADS",g="Name your R2 bucket (you can rename it in wrangler.jsonc later)",s=a=>u(a,3,63),k="lunora-uploads",w=a=>s(`${a}-uploads`)??k,L=async(a,e)=>{const t=w(e);return s(await a(g,{default:t,placeholder:t}))??t},W=(a,e)=>r(a,"r2_buckets",{key:"binding",value:$},"bucket_name",e);export{N as a,D as b,l as c,A as d,b as e,V as f,n as g,_ as h,s as i,y as j,o as k,S as l,E as m,O as n,w as o,W as p,C as q,d as r,x as s,L as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.122",
3
+ "version": "1.0.0-alpha.124",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -56,7 +56,7 @@
56
56
  "@lunora/codegen": "1.0.0-alpha.75",
57
57
  "@lunora/config": "1.0.0-alpha.101",
58
58
  "@lunora/container": "1.0.0-alpha.17",
59
- "@lunora/d1": "1.0.0-alpha.49",
59
+ "@lunora/d1": "1.0.0-alpha.50",
60
60
  "@lunora/errors": "1.0.0-alpha.9",
61
61
  "@lunora/mcp": "1.0.0-alpha.49",
62
62
  "@lunora/runtime": "1.0.0-alpha.44",
@@ -1,3 +0,0 @@
1
- import{mkdirSync as x,readFileSync as f,lstatSync as O,writeFileSync as N}from"node:fs";import{join as d,dirname as g}from"node:path";import{fileURLToPath as R}from"node:url";import{resolveHint as B,isLunoraError as v,flattenHint as A,findSolutionByMessage as L}from"@lunora/errors";import{createCerebro as D}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import E from"@visulima/cerebro/command/version";import{p as s}from"./api-spec-BENwiyUa.mjs";import{createLogger as b}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as j,renderError as I}from"@visulima/error";import{homedir as P}from"node:os";const T={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 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("../packem_chunks/handler.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},{description:"Output format: pretty (default) or json",name:"format",type:String}]},_={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("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},$={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) 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 restore <id>","Restore a snapshot by id"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{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 production pitr --restore (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}]},U={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"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String}]},M={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String}]},W={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},J={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","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate (deploy even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{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},{description:"Output format: pretty (default) or json",name:"format",type:String},{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:"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:"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 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}]},K={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},q={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)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},{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:"Emit machine-readable JSON log lines (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:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},F={argument:{description:"Optional path under the docs site (e.g. addons/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 addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},H={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},V={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"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{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}]},G={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"]],group:"Data",loader:()=>import("../packem_chunks/handler10.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},{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}]},Y={argument:{description:"Source NDJSON file",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{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}]},z={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},Q={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 --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("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",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 | 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}]},X={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 --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("../packem_chunks/handler13.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},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{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}]},Z={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("../packem_chunks/handler22.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 (default true; --no-procedures to skip)",name:"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}]},ee={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("../packem_chunks/handler14.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}]},te={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("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{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}]},re={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"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.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: 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)",name:"token",type:String}]},oe={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 d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.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},{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}]},ne={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("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate (proceed even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ae={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 --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler16.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},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{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}]},ie={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("../packem_chunks/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}]},se={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)"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{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}]},le={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"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String}]},pe={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"]],group:"Data",loader:()=>import("../packem_chunks/handler18.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:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{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}]},de={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"]],group:"Deploy",loader:()=>import("../packem_chunks/handler19.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: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean}]},ce={description:"Open the Lunora studio in your browser (local dev by default, --remote for production)",examples:[["lunora view","Open the studio for local dev"],["lunora view --remote","Open the deployed studio"]],group:"Project",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},ue={filterStacktrace:()=>!1,hideErrorCodeView:!0},me=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=B(v(e)?{code:e.code,hint:e.hint,message:r}:r),n=new j({hint:o===void 0?void 0:A(o).split(`
2
- `),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",I(n,ue)},ge=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},he=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ge(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},ye=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,fe=1440*60*1e3,ve=1500,be="0.0.0",we=/^v/u,ke=new Set(["alpha","beta","next"]),c=e=>{const t=e.trim().replace(we,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},h=e=>{const[t,r,o]=c(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Se=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},xe=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Se(a,i)}return 0},Oe=(e,t)=>{const r=h(e),o=h(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return xe(c(e).prerelease,c(t).prerelease)},Ne=e=>{const t=c(e).prerelease.split(".")[0]??"";return ke.has(t)?t:"latest"},Re=(e,t)=>Oe(t,e)>0,Be=(e,t,r)=>t-e<r,Ae=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,w=e=>d(e,"lunora-cli-update.json"),Le=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:d(P(),".cache"),r=d(t,"lunora");try{x(r,{mode:448,recursive:!0})}catch{}return r},De=e=>{try{const t=JSON.parse(f(w(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},y=(e,t)=>{try{const r=w(e);try{if(O(r).isSymbolicLink())return}catch{}N(r,`${JSON.stringify(t)}
3
- `,"utf8")}catch{}},Ce=async(e,t)=>{try{const r=await e(ye(t),{signal:AbortSignal.timeout(ve)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Ee=(e,t,r)=>e===be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,je=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ee(e.current,t,r))return;const o=e.cacheDir??Le(t),n=(e.now??Date.now)(),a=e.ttlMs??fe,i=Ne(e.current),l=De(o),S=l?.tag??"latest",u=l!==void 0&&S===i?l:void 0;let p=u?.latest;if(u===void 0||!Be(u.checkedAt,n,a)){const m=await Ce(e.fetchImpl??globalThis.fetch,i);m===void 0?y(o,{checkedAt:n,latest:e.current,tag:i}):(p=m,y(o,{checkedAt:n,latest:m,tag:i}))}p!==void 0&&Re(e.current,p)&&e.logger.warn(Ae(e.current,p,i))},Ie=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Pe=8,Te=()=>{try{let e=g(R(import.meta.url));for(let t=0;t<Pe;t+=1){try{const o=JSON.parse(f(d(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=g(e);if(r===e)break;e=r}}catch{}return"0.0.0"},k=Te(),_e=[Q,T,q,M,U,J,W,ne,ee,K,te,le,X,ie,oe,G,Y,pe,Z,$,de,z,H,V,_,ce,F,ae,se,re],$e=e=>{const t={value:0},r=D("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:k});for(const o of _e)r.addCommand(o);return r.addCommand(E),r.addCommand(C),{cli:r,exitCode:t}},Ue=/Command "(?<name>[^"]+)" not found/u,Me=e=>{const t=b(),r=e instanceof Error?e.message:String(e),o=Ue.exec(r);if(!o?.groups){v(e)||L(r)!==void 0?t.error(me(e)):t.error(r);return}const n=o.groups.name??"",a=he(n,Ie);t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation.")},Xe=async(e={})=>{const{cli:t,exitCode:r}=$e(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Me(o),1}return await je({current:k,logger:b()}),r.value};export{Ie as COMMANDS,k as VERSION,Xe as runCli};
@@ -1 +0,0 @@
1
- import{d as s}from"./commands-BhX2Bo9B.mjs";const d=/[^a-z0-9]+/u,r=(e,t,a)=>{let n=e.toLowerCase().split(d).filter(Boolean).join("-").slice(0,a);return n.endsWith("-")&&(n=n.slice(0,-1)),n.length>=t?n:void 0},u="DB",c="Name your D1 database (run `wrangler d1 create` to get its id, then put it in wrangler.jsonc)",l=e=>r(e,1,64),h="lunora-db",m=e=>l(`${e}-db`)??h,y=async(e,t)=>{const a=m(t);return l(await e(c,{default:a,placeholder:a}))??a},_=(e,t)=>s(e,"d1_databases",{key:"binding",value:u},"database_name",t),f=[{description:"Email + password on better-auth (default)",label:"Email & password",value:"auth"},{description:"Clerk-hosted auth",label:"Clerk",value:"auth-clerk"},{description:"Auth0 (OIDC)",label:"Auth0",value:"auth-auth0"}],i="auth",j=async e=>await e("Which auth provider?",f,{default:i})??i,C="mail",D=e=>{const t=e.trim();if(t==="")return;const a=t.toLowerCase();return a==="auth"?{kind:"auth"}:a==="email"||a==="mail"?{kind:"email"}:{item:a,kind:"item"}},p="SEND_EMAIL",A="Verified destination email for production delivery (blank = set it later in wrangler.jsonc)",$=e=>{const t=e.trim();if(t.length===0||t.includes(" "))return!1;const a=t.indexOf("@");if(a<=0||a!==t.lastIndexOf("@"))return!1;const n=t.slice(a+1);return n.length>=3&&n.includes(".")&&!n.startsWith(".")&&!n.endsWith(".")},E=(e,t)=>{const a=e.trim();if(a!==""){if(!$(a)){t(`"${a}" doesn't look like an email — leaving the placeholder; set destination_address in wrangler.jsonc.`);return}return a}},L=(e,t)=>s(e,"send_email",{key:"name",value:p},"destination_address",t),b="UPLOADS",k="Name your R2 bucket (you can rename it in wrangler.jsonc later)",o=e=>r(e,3,63),g="lunora-uploads",w=e=>o(`${e}-uploads`)??g,O=async(e,t)=>{const a=w(t);return o(await e(k,{default:a,placeholder:a}))??a},W=(e,t)=>s(e,"r2_buckets",{key:"binding",value:b},"bucket_name",t);export{w as a,A as b,m as c,E as d,y as e,i as f,j as g,f as h,o as i,_ as j,L as l,C as n,D as o,W as p,l as r,O as u};