@lunora/cli 1.0.0-alpha.39 → 1.0.0-alpha.390

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/bin.mjs +2 -10
  4. package/dist/index.d.mts +1019 -374
  5. package/dist/index.d.ts +1019 -374
  6. package/dist/index.mjs +1 -19
  7. package/dist/packem_chunks/dispatch.mjs +1 -0
  8. package/dist/packem_chunks/handler.mjs +1 -160
  9. package/dist/packem_chunks/handler10.mjs +1 -16
  10. package/dist/packem_chunks/handler11.mjs +1 -22
  11. package/dist/packem_chunks/handler12.mjs +1 -192
  12. package/dist/packem_chunks/handler13.mjs +3 -131
  13. package/dist/packem_chunks/handler14.mjs +1 -65
  14. package/dist/packem_chunks/handler15.mjs +1 -58
  15. package/dist/packem_chunks/handler16.mjs +1 -80
  16. package/dist/packem_chunks/handler17.mjs +7 -43
  17. package/dist/packem_chunks/handler18.mjs +1 -105
  18. package/dist/packem_chunks/handler19.mjs +1 -170
  19. package/dist/packem_chunks/handler2.mjs +1 -114
  20. package/dist/packem_chunks/handler20.mjs +3 -94
  21. package/dist/packem_chunks/handler21.mjs +3 -94
  22. package/dist/packem_chunks/handler22.mjs +1 -0
  23. package/dist/packem_chunks/handler23.mjs +2 -0
  24. package/dist/packem_chunks/handler24.mjs +2 -0
  25. package/dist/packem_chunks/handler25.mjs +99 -0
  26. package/dist/packem_chunks/handler26.mjs +9 -0
  27. package/dist/packem_chunks/handler27.mjs +1 -0
  28. package/dist/packem_chunks/handler3.mjs +1 -204
  29. package/dist/packem_chunks/handler4.mjs +3 -33
  30. package/dist/packem_chunks/handler5.mjs +1 -49
  31. package/dist/packem_chunks/handler6.mjs +1 -91
  32. package/dist/packem_chunks/handler7.mjs +1 -42
  33. package/dist/packem_chunks/handler8.mjs +2 -174
  34. package/dist/packem_chunks/handler9.mjs +1 -315
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +11 -594
  37. package/dist/packem_chunks/runDevCommand.mjs +2 -0
  38. package/dist/packem_chunks/runInitCommand.mjs +164 -1432
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-JClcR9JT.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
  43. package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
  44. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  45. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  46. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  47. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  48. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  49. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  50. package/dist/packem_shared/cli-DwEpuZm9.mjs +2 -0
  51. package/dist/packem_shared/cli-manifest-CRet0egA.mjs +1 -0
  52. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  53. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  54. package/dist/packem_shared/command-CAXl2A1S.mjs +1 -0
  55. package/dist/packem_shared/commands-DgUDxkA8.mjs +13 -0
  56. package/dist/packem_shared/createLogger-Cl18I8AX.mjs +2 -0
  57. package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
  58. package/dist/packem_shared/deploy-target-DCWwiuAe.mjs +1 -0
  59. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  60. package/dist/packem_shared/docker-AqLAkOyY.mjs +1 -0
  61. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  62. package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
  63. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  64. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  65. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  66. package/dist/packem_shared/mcp-config-file-CcDTeXIq.mjs +2 -0
  67. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  68. package/dist/packem_shared/output-format-B4eQHi5y.mjs +2 -0
  69. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  70. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  71. package/dist/packem_shared/plan-Dl57T11P.mjs +5 -0
  72. package/dist/packem_shared/planDevCommand-D8sm56hO.mjs +1 -0
  73. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  74. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  75. package/dist/packem_shared/render-lunora-error-C3OJY5wk.mjs +2 -0
  76. package/dist/packem_shared/resolve-BrsV4Qyc.mjs +5 -0
  77. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  78. package/dist/packem_shared/runAddCommand-DTvfp4h2.mjs +1 -0
  79. package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
  80. package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
  81. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  82. package/dist/packem_shared/secret-key-6bCftsxj.mjs +1 -0
  83. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  84. package/dist/packem_shared/storage-DWhTX8eS.mjs +1 -0
  85. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  86. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  87. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  88. package/dist/packem_shared/wrangler-secrets-3chIVv3H.mjs +1 -0
  89. package/package.json +39 -19
  90. package/skills/README.md +35 -17
  91. package/skills/lunora/SKILL.md +154 -64
  92. package/skills/lunora-create-package/SKILL.md +97 -84
  93. package/skills/lunora-deploy/SKILL.md +175 -105
  94. package/skills/lunora-functions/SKILL.md +362 -56
  95. package/skills/lunora-migration-helper/SKILL.md +162 -137
  96. package/skills/lunora-performance-audit/SKILL.md +137 -95
  97. package/skills/lunora-quickstart/SKILL.md +137 -136
  98. package/skills/lunora-realtime/SKILL.md +140 -99
  99. package/skills/lunora-setup-auth/SKILL.md +162 -102
  100. package/skills/lunora-setup-hyperdrive/SKILL.md +114 -97
  101. package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
  102. package/skills/lunora-setup-mail/SKILL.md +85 -113
  103. package/skills/lunora-setup-scheduler/SKILL.md +132 -96
  104. package/skills/lunora-setup-storage/SKILL.md +189 -95
  105. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  106. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  107. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  108. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  109. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  110. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  111. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  112. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  113. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  114. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  115. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  116. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  117. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  118. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  119. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  120. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  121. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  122. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  123. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  124. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  125. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  126. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  127. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  128. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  129. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  130. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  131. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  132. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  133. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -0,0 +1,12 @@
1
+ import{createReadStream as N}from"node:fs";import{open as Ye,stat as L,readdir as x,realpath as ne,readFile as v,mkdir as D,writeFile as me,appendFile as Ke}from"node:fs/promises";import{t as qe,r as Ze}from"./admin-token-VdUnvnKW.mjs";import{r as Qe,a as et}from"./admin-url-DJB8P6Jh.mjs";import{EXIT_CODE as $,isRefusal as tt}from"./EXIT_CODE-D_XCixv8.mjs";import{join as b,resolve as U,basename as p,dirname as pe,relative as rt,sep as nt}from"node:path";import{createInterface as F}from"node:readline";import st from"adm-zip";import{i as ye}from"./path-containment-CgxYZggb.mjs";import{Transform as ot}from"node:stream";import{createInflateRaw as it,crc32 as at}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{parse as ct}from"csv-parse/sync";import{parse as be}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as dt}from"@lunora/runtime";import{S as B,a as lt,I as ut}from"./shared-D-zCOmgY.mjs";import{createHash as ft}from"node:crypto";const ht=67324752,O=30,gt=26,mt=28,se=0,pt=8,yt=async(e,t)=>{const r=await Ye(e,"r");try{const n=Buffer.alloc(O),{bytesRead:s}=await r.read(n,0,O,t);if(s<O||n.readUInt32LE(0)!==ht)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+O+n.readUInt16LE(gt)+n.readUInt16LE(mt)}finally{await r.close()}},oe=e=>{let t=0;return new ot({flush(r){if(t===e.header.crc){r();return}r(new Error(`${e.entryName} failed its CRC check — the archive is corrupt or truncated (expected ${String(e.header.crc)}, read ${String(t)})`))},transform(r,n,s){t=at(r,t),s(void 0,r)}})},bt=async(e,t)=>{const{compressedSize:r,encrypted:n,method:s,offset:o}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(s!==se&&s!==pt)throw new Error(`${t.entryName} uses unsupported compression method ${String(s)} — re-create the archive with standard deflate`);if(r===0){if(t.header.size>0||t.header.crc!==0)throw new Error(`${t.entryName} declares 0 compressed bytes but ${String(t.header.size)} uncompressed with CRC ${String(t.header.crc)} — the archive is corrupt`);return}const i=await yt(e,o),a=N(e,{end:i+r-1,start:i});if(s===se){const l=oe(t);return a.on("error",u=>l.destroy(u)),a.pipe(l)}const c=it(),d=oe(t);return a.on("error",l=>c.destroy(l)),c.on("error",l=>d.destroy(l)),a.pipe(c).pipe(d)},T="_storage",we=e=>e.startsWith("_"),wt=e=>{for(const t of e.getEntries()){const n=t.entryName.replaceAll("\\","/").split("/");if(n.length>=2&&n[n.length-2]==="_storage")return n.slice(0,-1).join("/")}return"_storage"},$t=async e=>{const t=await L(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new st(e);return{kind:"zip",storagePrefix:wt(r),zip:r,zipPath:e}}},St=async e=>{const t=[];for(const r of await x(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=b(e,r.name,"documents.jsonl");(await L(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},vt=e=>{const t=[];for(const r of e.getEntries()){if(r.isDirectory)continue;const n=r.entryName.replaceAll("\\","/"),s=n.split("/");s.length>=2&&s[s.length-1]==="documents.jsonl"&&t.push({file:n,table:s[s.length-2]})}return t},Nt=async e=>{const t=e.kind==="directory"?await St(e.root):vt(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},J=async function*(e,t){if(e.kind==="directory"){for await(const o of F({crlfDelay:Number.POSITIVE_INFINITY,input:N(t.file,{encoding:"utf8"})}))yield o;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await bt(e.zipPath,r);if(n===void 0)return;const s=F({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const o of s)yield o}finally{s.close(),n.destroy()}},Et=async(e,t)=>{if(e.kind==="directory"){const n=await ne(b(e.root,"_storage")),s=await ne(U(n,t)).catch(()=>{});if(s===void 0||!ye(n,s))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return v(s)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},P=207,Tt=e=>{const t={conflicts:0,errors:[],failed:[],inserted:{},received:0,warnings:[]};let r=[],n=0;const s=a=>{for(const[c,d]of Object.entries(a.inserted??{}))t.inserted[c]=(t.inserted[c]??0)+d;t.errors.push(...a.errors??[]),t.failed.push(...a.failed??[]),t.conflicts+=a.conflicts??0,t.received+=a.received??0;for(const c of a.warnings??[])t.warnings.includes(c)||t.warnings.push(c)},o=async()=>{if(r.length===0)return;const a=r.join(`
2
+ `);r=[],n=0;const c=await e.fetchImpl(e.requestUrl,{body:a,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!c.ok&&c.status!==P){const l=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`import batch failed (HTTP ${String(c.status)}): ${l}`)}const d=await c.json();s(d),c.status===P&&(d.failed??[]).length===0&&t.failed.push({message:`the endpoint answered ${String(P)} without naming the failed shards`,shardKey:"<unknown>",timedOut:!1})};return{flush:o,push:async a=>{const c=Buffer.byteLength(a)+1;r.length>0&&n+c>e.maxBatchBytes&&await o(),r.push(a),n+=c,r.length>=e.batchSize&&await o()},totals:t}},$e=(e,t,r,n)=>{const s=[],o=[];let i=0;const a=l=>n?.[r]?.includes(l)===!0,c=(l,u,h=!1)=>{if(Array.isArray(l))return l.map(g=>c(g,u,h));if(l!==null&&typeof l=="object"){const g=l;if(typeof g.$storage=="string"){const m=g.$storage,y=t.get(m);return y===void 0?(o.push({column:u,storageId:m,table:r}),l):(i+=1,y)}return Object.fromEntries(Object.entries(g).map(([m,y])=>[m,c(y,u)]))}return typeof l=="string"&&t.has(l)?a(u)?(i+=1,t.get(l)??l):(s.push({column:u,storageId:l,table:r}),l):(h&&typeof l=="string"&&l.length>0&&a(u)&&n!==void 0&&o.push({column:u,storageId:l,table:r}),l)},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,c(u,l,!0)]));return{ambiguous:s,document:d,rewritten:i,unmigrated:o}},ie=(e,t,r)=>{for(const n of r){const s=`${n.table}\0${n.column}\0${n.storageId}`;t.has(s)||(t.add(s),e.push(n))}},At=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:s,table:o}=e,i=new Set,a=new Set,c=(u,h)=>{let g;try{g=JSON.parse(u)}catch(m){const y=m instanceof Error?m.message:String(m);throw new f("INTERNAL",`invalid JSON on line ${String(h)}: ${y}`,{cause:m})}return JSON.stringify({doc:g,table:o})},d=(u,h)=>{let g;try{g=JSON.parse(u)}catch(y){throw new f("INTERNAL",`line ${String(h)}: import envelope is not valid JSON — ${y instanceof Error?y.message:String(y)}`,{cause:y})}const m=g===null||typeof g!="object"||Array.isArray(g)?void 0:g;if(m===void 0||typeof m.table!="string")throw new f("INTERNAL",`line ${String(h)}: import envelope is missing a string \`table\``);return m},l=u=>{if(u.doc!==null&&typeof u.doc=="object"&&!Array.isArray(u.doc)){let h=u.doc;if(s!==void 0){const g=$e(h,s,u.table,n);h=g.document,r.rewritten+=g.rewritten,ie(r.ambiguous,i,g.ambiguous),ie(r.unmigrated,a,g.unmigrated)}return JSON.stringify({...u,doc:t===void 0?h:t(h,u.table)})}return JSON.stringify(u)};return(u,h)=>{const g=u.trim();if(g.length===0)return;if(o!==void 0)return c(g,h);const m=d(g,h);return s===void 0&&t===void 0?g:l(m)}},Se=async(e,t,r,n)=>{const s=await n(e).catch(()=>{});if(s===void 0)throw new f("INTERNAL",`${e} is not a readable directory`);const o=new Map;for(const[d,l]of Object.entries(t?.tables??{}))l.file!==void 0&&o.set(p(l.file),d);const i=s.filter(d=>d.isFile()&&r.matches(d.name)&&!r.authFiles.has(d.name)).map(d=>({file:b(e,d.name),table:o.get(d.name)??r.tableNameOf(d.name)}));if(i.length===0)throw new f("INTERNAL",`${e} ${r.emptyMessage}`);const a=new Set(i.map(d=>p(d.file))),c=[...o].filter(([d])=>!a.has(d));if(c.length>0)throw new f("INTERNAL",`${e}: the mapping names ${String(c.length)} file(s) that are not importable from this directory — ${c.map(([d,l])=>`\`${d}\` (table \`${l}\`)`).join(", ")}. Check the name and that the file is one this source reads.`);return i.toSorted((d,l)=>d.table.localeCompare(l.table))},ve=async function*(e,t,r,n){for(const s of e){r.has(s.table)||r.set(s.table,0),t.info(`reading ${p(s.file)} → ${s.table}`);for await(const o of n(s))r.set(s.table,(r.get(s.table)??0)+1),yield`${JSON.stringify({doc:o,table:s.table})}
3
+ `}},Ne=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],It=e=>Ne.includes(e),_t=/^\\x([\dA-Fa-f]*)$/,ae=/^[+-]?\d+$/,Ee=/[+-]\d{2}$/,Te=/(?:Z|[+-]\d{2}:\d{2})$/i,Ae=/^\+/,Rt=/e/i,Ot=/e/i,kt=e=>{const[t="0",r="0"]=e.split(Ot),n=Number(r),s=t.startsWith("-"),[o="0",i=""]=(s?t.slice(1):t).replace(Ae,"").split("."),a=`${o}${i}`,c=o.length+n;let d;return c<=0?d=`0.${"0".repeat(-c)}${a}`:c>=a.length?d=`${a}${"0".repeat(c-a.length)}`:d=`${a.slice(0,c)}.${a.slice(c)}`,s?`-${d}`:d},Lt=/^0+(?=\d)/,ce=e=>{const r=(Rt.test(e.trim())?kt(e.trim()):e.trim()).replace(Ae,""),n=r.startsWith("-"),[s="0",o=""]=(n?r.slice(1):r).split("."),i=s.replace(Lt,"");let a=o.length;for(;a>0&&o[a-1]==="0";)a-=1;const c=o.slice(0,a),d=c.length>0?`${i}.${c}`:i;return n&&Number(d)!==0?`-${d}`:d},w=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},de=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),s=Ee.test(n)?`${n}:00`:n,o=Te.test(s)?s:`${s}Z`,i=Date.parse(o);return Number.isNaN(i)&&w(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),i},xt=(e,t)=>{(!t.startsWith("{")||!t.endsWith("}"))&&w(e,"text-array",t,"not a Postgres array literal (expected `{…}`)");const r=t.slice(1,-1);if(r.length===0)return[];r.includes("{")&&w(e,"text-array",t,"nested arrays are not supported — map the column to `json` instead");const n=[];let s="",o=!1,i=!1,a=!1;const c=()=>{n.push(!i&&s==="NULL"?null:s),s="",i=!1};for(const d of r)a?(s+=d,a=!1):d==="\\"?a=!0:d==='"'?(o=!o,i=!0):d===","&&!o?c():s+=d;return c(),n},Ie=(e,t,r)=>{if(r===null)return null;switch(t){case"boolean":return["1","t","TRUE","true"].includes(r)?!0:["0","f","FALSE","false"].includes(r)?!1:w(e,t,r,"not a Postgres boolean literal");case"bytea-base64":{const n=_t.exec(r);if(n===null)return w(e,t,r,"not `bytea` hex output (expected a leading `\\x`) — set `bytea_output = 'hex'` before dumping");const s=n[1];return s.length%2!==0?w(e,t,r,"has an odd number of hex digits, so the dump is truncated — re-export the column"):Buffer.from(s,"hex").toString("base64")}case"int8-string":return ae.test(r)?r:w(e,t,r,"not an integer");case"json":try{return JSON.parse(r)}catch(n){return w(e,t,r,`invalid JSON — ${n instanceof Error?n.message:String(n)}`)}case"number":{const n=Number(r);if(r.trim().length===0||!Number.isFinite(n))return w(e,t,r,"not a finite number");if(ae.test(r)){if(!Number.isSafeInteger(n))return w(e,t,r,"exceeds Number.MAX_SAFE_INTEGER — map this column to `int8-string` to keep it lossless")}else if(ce(String(n))!==ce(r))return w(e,t,r,"has more precision than a JS number holds — map this column to `int8-string` or `json` to keep it lossless");return n}case"text-array":return xt(e,r);case"timestamp-iso":{de(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),s=Ee.test(n)?`${n}:00`:n;return Te.test(s)?s:`${s}Z`}case"timestamp-ms":return de(e,t,r);default:return r}},Ct="auth.",jt=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),Pt=String.raw`\N`,_e=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===Pt?null:e,Ut=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),Ft=async(e,t)=>Se(e,t,{authFiles:Ut(t),emptyMessage:"holds no .csv files — export each table with `COPY <table> TO STDOUT WITH CSV HEADER` first",matches:r=>r.toLowerCase().endsWith(".csv")&&!r.toLowerCase().startsWith(Ct),tableNameOf:r=>p(r,".csv")},async r=>x(r,{withFileTypes:!0})),Mt=(e,t,r)=>{const n=t?.idColumn??"id",s=t?.types??{},o={};let i=!1;for(const[a,c]of Object.entries(e)){if(jt.has(a.toLowerCase()))throw new f("INTERNAL",`${r}.${a} is credential material — this looks like an auth dump being imported as a table. Name it under \`auth\` in the mapping instead; passwords are never migrated.`);const d=s[a],l=d===void 0?c:Ie(a,d,c);if(a===n){if(c===null)throw new f("INTERNAL",`id column \`${n}\` is NULL — every row needs an id to preserve`);o._id=c,i=!0}else{if(a==="_id")throw new f("INTERNAL",`${r}: source column \`_id\` collides with the reserved id field. Rename it in the source, or map it via \`tables.${r}.idColumn\` if it IS the id.`);o[a]=l}}if(!i)throw new f("INTERNAL",`${r}: no \`${n}\` column to preserve as the id (columns present: ${Object.keys(e).join(", ")}). Set \`tables.${r}.idColumn\` in the mapping.`);return o},zt=async function*(e,t){const r=t?.tables?.[e.table],n=N(e.file).pipe(be({cast:_e,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let s=0;const o=n[Symbol.asyncIterator]();for(;;){let i,a;try{if(i=await o.next(),i.done===!0)return;s+=1,a=Mt(i.value,r,e.table)}catch(c){throw new f("INTERNAL",`${p(e.file)} row ${String(s+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},Dt=async function*(e,t,r,n,s){yield*ke("supabase",s,t,r,n),yield*ve(e,r,n,o=>zt(o,t))},Bt=/^\d+$/,Jt=/[+-]\d{2}$/,M=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&Bt.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Jt.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},Re=e=>{if(typeof e=="string")try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}return e!==null&&typeof e=="object"?e:void 0},Vt=e=>{const t=Re(e);if(t!==void 0){for(const r of["name","full_name","user_name","preferred_username"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Ht=e=>{const t=Re(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Gt=(e,t)=>{const{id:r}=e;if(typeof r!="string"||r.length===0)throw new f("INTERNAL","auth row is missing `id` — every user needs an id to preserve");const n=e.raw_user_meta_data,s={_id:r,email:e.email??null,emailVerified:typeof e.email_confirmed_at=="string"&&e.email_confirmed_at.length>0,id:r},o=Vt(n),i=Ht(n),a=M(e.created_at),c=M(e.updated_at);return o!==void 0&&(s.name=o),i!==void 0&&(s.image=i),a!==void 0&&(s.createdAt=a),c!==void 0&&(s.updatedAt=c),{accounts:t.map(l=>{const u=typeof l.provider=="string"?l.provider:"unknown",h=typeof l.provider_id=="string"?l.provider_id:r,g=`${r}:${u}:${h}`;return{_id:g,accountId:h,id:g,providerId:u,userId:r}}),user:s}},Wt=e=>{const t=e.localId;if(typeof t!="string"||t.length===0)throw new f("INTERNAL","auth row is missing `localId` — every user needs an id to preserve");const r={_id:t,email:e.email??null,emailVerified:e.emailVerified===!0,id:t},n=M(e.createdAt);return typeof e.displayName=="string"&&(r.name=e.displayName),typeof e.photoUrl=="string"&&(r.image=e.photoUrl),n!==void 0&&(r.createdAt=n),{accounts:(e.providerUserInfo??[]).filter(o=>typeof o.providerId=="string"&&o.providerId!=="password").map(o=>{const i=o.providerId,a=o.rawId??o.federatedId??t,c=`${t}:${i}:${a}`;return{_id:c,accountId:a,id:c,providerId:i,userId:t}}),user:r}},Xt=(e,t)=>{const r=new Map,n=[],s=[];for(const{accounts:o,user:i}of e){const a=typeof i.email=="string"?i.email.toLowerCase():void 0;if(a!==void 0&&a.length>0){const c=r.get(a);c===void 0?r.set(a,String(i._id)):n.push(`${a} (ids ${c} and ${String(i._id)})`)}s.push(`${JSON.stringify({doc:i,table:"user"})}
4
+ `),t.set("user",(t.get("user")??0)+1);for(const c of o)s.push(`${JSON.stringify({doc:c,table:"account"})}
5
+ `),t.set("account",(t.get("account")??0)+1)}if(n.length>0)throw new f("INTERNAL",`auth import found ${String(n.length)} duplicate email(s), which would merge distinct users: ${n.slice(0,10).join("; ")}${n.length>10?" …":""}`);return s},V=(e,t)=>b(e,p(t)),Oe=async e=>{const t=await v(e,"utf8");return ct(t,{cast:_e,columns:!0,skipEmptyLines:!0})},Yt=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Oe(V(e,t))){const s=n.user_id;typeof s=="string"&&r.set(s,[...r.get(s)??[],n])}return r},Kt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Oe(V(e,r)),s=await Yt(e,t.auth?.identitiesFile);return n.map(o=>Gt(o,s.get(o.id??"")??[]))},qt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=V(e,r);let s;try{s=JSON.parse(await v(n,"utf8"))}catch(i){throw new f("INTERNAL",`${p(n)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}const o=Array.isArray(s)?s:s.users??[];if(!Array.isArray(o))throw new f("INTERNAL",`${p(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return o.map(i=>Wt(i))},ke=async function*(e,t,r,n,s){if(r?.auth?.file===void 0)return;const o=e==="supabase"?await Kt(t,r):await qt(t,r);n.info(`auth: ${String(o.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Xt(o,s))yield i},le=/\.(?:nd)?json$/i,Le=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Zt=e=>{const t=Number(e.seconds??0),r=e.nanos??0;return Number.isFinite(t)&&Number.isFinite(r)?t*1e3+Math.floor(r/1e6):Number.NaN},Qt=(e,t)=>{const r=Array.isArray(e)?e:e.data;if(!Array.isArray(r))throw new f("INTERNAL",`${t}: \`bytesValue\` ${JSON.stringify(e)} is neither base64 nor a byte array`);return Buffer.from(r).toString("base64")},er=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Zt(e);if(Number.isNaN(r))throw new f("INTERNAL",`${t}: \`timestampValue\` ${JSON.stringify(e)} is neither an RFC-3339 string nor a \`{ seconds, nanos }\` protobuf timestamp`);return r},tr=(e,t)=>typeof e=="string"?e:Qt(e,t),xe=(e,t)=>{if("nullValue"in e)return null;if(e.stringValue!==void 0)return e.stringValue;if(e.booleanValue!==void 0)return e.booleanValue;if(e.integerValue!==void 0){const r=String(e.integerValue),n=Number(r);return Number.isSafeInteger(n)?n:r}if(e.doubleValue!==void 0)return Number(e.doubleValue);if(e.timestampValue!==void 0)return er(e.timestampValue,t);if(e.bytesValue!==void 0)return tr(e.bytesValue,t);if(e.geoPointValue!==void 0)return{latitude:e.geoPointValue.latitude??0,longitude:e.geoPointValue.longitude??0};if(e.referenceValue!==void 0)return Le(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>xe(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return z(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},rr=new Set(["createTime","fields","name","readTime","updateTime"]),nr=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]?.endsWith("Value")===!0},sr=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>rr.has(r))&&!nr(t)},z=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,xe(n,`${t}.${r}`)])),or=(e,t,r,n)=>{const s=sr(e),o=z(s?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?Le(i):t;if(a===void 0)throw new f("INTERNAL",`${n}: no document id — expected a \`name\`/\`__name__\` resource path, or a document keyed by its id`);const c=r?.types??{};for(const[d,l]of Object.entries(c)){const u=o[d];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${d}: a \`${l}\` reshape needs a scalar, but this field decoded to an object or array`);o[d]=Ie(d,l,u===null?null:String(u))}}return{...o,_id:a}},ir=async(e,t)=>Se(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[p(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>le.test(r),tableNameOf:r=>r.replace(le,"")},async r=>x(r,{withFileTypes:!0})),ar=async function*(e){const t=F({crlfDelay:Number.POSITIVE_INFINITY,input:N(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const s=n.trim();if(s.length!==0)try{yield{raw:JSON.parse(s)}}catch(o){throw new f("INTERNAL",`${p(e)} line ${String(r)}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}}}finally{t.close()}},cr=async e=>{const t=await v(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${p(e)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(r!==null&&typeof r=="object"&&Array.isArray(r.documents))return r.documents.map(n=>({raw:n}));if(Array.isArray(r))return r.map(n=>({raw:n}));if(r!==null&&typeof r=="object")return Object.entries(r).map(([n,s])=>({fallbackId:n,raw:s}));throw new f("INTERNAL",`${p(e)}: expected an object, an array, or \`{ documents: [...] }\``)},dr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?ar(e.file):await cr(e.file);let s=0;for await(const o of n)yield or(o.raw,o.fallbackId,r,`${e.table}[${String(s)}]`),s+=1},lr=async function*(e,t,r,n,s){yield*ke("firebase",s,t,r,n),yield*ve(e,r,n,o=>dr(o,t))},I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),H=(e,t)=>{if(!I(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},A=(e,t,r)=>{const n=e[t];if(n!==void 0&&typeof n!="string")throw new f("INTERNAL",`${r}: \`${t}\` must be a string`);return n},Ce=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(s=>typeof s!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},ur=(e,t)=>{const r=H(e,t),n=A(r,"file",t),s=A(r,"idColumn",t),o=Ce(r,"storageColumns",t),{types:i}=r;if(i!==void 0){if(!I(i))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(i))if(!It(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${Ne.join(", ")}`)}return{file:n,idColumn:s,storageColumns:o,types:i}},fr=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])A(e,r,`${t}: auth`)}},hr=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,ur(n,`${t}: tables.${r}`)]))}},gr=(e,t)=>{const r=H(e,t),n=A(r,"keyPrefix",t),{auth:s,tables:o}=r;return fr(s,t),{auth:s,keyPrefix:n,tables:hr(o,t)}},je=e=>b("lunora",`import-${e}.json`),mr=async(e,t,r)=>{const n=je(t),s=b(e,n);let o;try{o=await v(s,"utf8")}catch(a){if(a.code==="ENOENT"){r.info(`no ${n} found — every column is copied through untouched (run with --scan to generate one)`);return}throw a}let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${s}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return gr(i,s)},pr=async e=>{const t=[];let r;for(;;){const n=await e(r);if(t.push(...Array.isArray(n.records)?n.records:[]),n.truncated!==!0||typeof n.cursor!="string"||n.cursor.length===0)return t;if(n.cursor===r)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");r=n.cursor}},yr=8,br=24*1048576,wr=1e3,$r=/^[\dA-F]{64}$/i,Sr=e=>{for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t)??0;if(r<32||r===127)return!1}return!0},vr=/^[\d+/A-Z]{43}=$/i,Nr=e=>$r.test(e)?e.toLowerCase():vr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,Er=(e,t)=>{const r=JSON.parse(e),n=r._id;if(typeof n!="string"||n.length===0||n.includes("/")||n.includes("\\"))throw new f("INTERNAL",`${t}: \`_id\` must be a path-free non-empty string`);if(typeof r.sha256!="string")throw new f("INTERNAL",`${t}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const s=Nr(r.sha256);if(s===void 0)throw new f("INTERNAL",`${t}: \`sha256\` is neither base16 nor base64 SHA-256 (${r.sha256})`);if(typeof r.size!="number"||!Number.isInteger(r.size)||r.size<0)throw new f("INTERNAL",`${t}: \`size\` must be a non-negative integer`);if(r.contentType!==void 0&&(typeof r.contentType!="string"||!Sr(r.contentType)))throw new f("INTERNAL",`${t}: \`contentType\` must be a string with no control characters`);return{contentType:typeof r.contentType=="string"?r.contentType:void 0,id:n,sha256:s,size:r.size}},G=async(e,t,r)=>{const n=[];try{let s=0;for await(const o of J(e,t)){const i=o.trim();s+=1,i.length>0&&n.push(Er(i,`_storage/documents.jsonl line ${String(s)}`))}}catch(s){const o=s instanceof Error?s.message:String(s);throw r.error(`failed to read _storage metadata: ${o}`),s}return n},Pe=dt,C=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,W=async(e,t)=>await pr(async r=>{const n=`${e.baseUrl}${B}?prefix=${encodeURIComponent(t)}&limit=${String(wr)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}${C(e)}`,s=await e.fetchImpl(n,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!s.ok){const i=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(s.status)}): ${i}`)}const o=await s.json();return{cursor:o.cursor,records:o.objects,truncated:o.truncated}}),Tr=async(e,t,r,n)=>{const s=`${e.baseUrl}${B}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${C(e)}`,o=await e.fetchImpl(s,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!o.ok){const a=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(o.status)}): ${a}`)}const i=await o.json();if(i.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${i.sha256??"none"}`);return t},Ar=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${B}?key=${encodeURIComponent(t)}${C(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,Ir=async(e,t,r,n,s)=>{const o=`${e.baseUrl}${lt}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${C(e)}`,i=await e.fetchImpl(o,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const m=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(Pe)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(i.status)}): ${m}`)}const{url:a}=await i.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const m=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${m}`)}const l=(await W(e,t)).find(m=>m.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const u=l.size!==void 0&&l.size!==n.size,h=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(u||h){const m=await Ar(e,t);throw new f("INTERNAL",`post-upload verification failed: expected sha256=${n.sha256} size=${String(n.size)}, got sha256=${l.sha256??"none"} size=${String(l.size??"none")}${m?" (the object was removed)":` — AND the object could not be removed: delete ${t} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[l.size===void 0?"size":void 0,l.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&s.warn(`blob ${t} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),t},Ue=async(e,t,r,n,s)=>{if(r.length!==n.size)throw new f("INTERNAL",`blob ${n.id} is ${String(r.length)} bytes on disk but the export declares ${String(n.size)}`);return r.length<=Pe?Tr(e,t,r,n):Ir(e,t,r,n,s)},_r=e=>{const t=[];let r=[],n=0;for(const s of e)r.length>0&&(r.length>=yr||n+s.size>br)&&(t.push(r),r=[],n=0),r.push(s),n+=s.size;return r.length>0&&t.push(r),t},Rr=async(e,t,r,n,s)=>{const o=await G(t,r,s),i=new Map,a=await W(e,n),c=new Map(a.map(u=>[u.key,u])),d=[];for(const u of o){const h=`${n}${u.sha256}`;c.get(h)?.size===u.size?i.set(u.id,h):d.push(u)}s.info(`migrating ${String(d.length)} storage blobs${i.size>0?` (${String(i.size)} already present)`:""}...`);const l=async u=>{try{const h=await Et(t,u.id);i.set(u.id,await Ue(e,`${n}${u.sha256}`,h,u,s))}catch(h){const g=h instanceof Error?h.message:String(h);throw s.error(`failed to upload blob ${u.id}: ${g}`),h}};for(const u of _r(d)){const g=(await Promise.allSettled(u.map(m=>l(m)))).find(m=>m.status==="rejected");if(g!==void 0)throw g.reason}return s.success(`migrated ${String(d.length)} storage blobs`),i};async function*Or(e,t,r){let n=0;for await(const s of J(e,t)){const o=s.trim();if(n+=1,o.length===0)continue;let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${t.table}/documents.jsonl line ${String(n)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}r.set(t.table,(r.get(t.table)??0)+1),yield`${JSON.stringify({doc:i,table:t.table})}
6
+ `}}async function*kr(e,t,r,n,s){for(const o of t){if(we(o.table)){o.table===T&&!n&&r.warn(`skipping "${T}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}s.has(o.table)||s.set(o.table,0),yield*Or(e,o,s)}}const Xn=["firebase","supabase"],Lr=async(e,t,r)=>{if(e.withStorage===!0&&t==="firebase"&&e.storageDir===void 0)return e.logger.error("--with-storage on Firebase needs --storage-dir — download the bucket first with `gcloud storage cp -r gs://<bucket> <dir>`."),{kind:"invalid"};if(e.table!==void 0)return e.logger.error(`--table cannot be combined with --from ${t} — each row's table comes from its source file.`),{kind:"invalid"};const n=await mr(r,t,e.logger),s=Object.values(n?.tables??{}).some(o=>(o.storageColumns??[]).length>0);return e.verify===!0&&e.withStorage!==!0&&s?(e.logger.error("--verify with `storageColumns` declared requires --with-storage — otherwise every storage path stays unmigrated and only row counts would be checked."),{kind:"invalid"}):t==="supabase"?{kind:"supabase",mapping:n,tables:await Ft(e.file,n)}:{collections:await ir(e.file,n),kind:"firebase",mapping:n}},xr=async e=>{if(!await L(e.file).then(()=>!0,()=>!1))return!1;for(const[r,n]of[["--scan",e.scan],["--verify",e.verify],["--with-storage",e.withStorage]])if(n===!0)return e.logger.error(`${r} requires a Convex export directory or .zip snapshot — ${e.file} is not one.`),!0;return!1},Cr=async(e,t,r)=>{const n=t.find(o=>o.table===T);if(n===void 0)return r.logger.error("--verify cannot check file references: this export has no `_storage` table, so it was taken without `--include-file-storage`. Re-export with that flag and pass --with-storage, or drop --verify."),!0;const s=await G(e,n,r.logger);return s.length>0?(r.logger.error(`--verify on an export carrying ${String(s.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),!0):!1},jr=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return Lr(e,e.from,t);const r=await $t(e.file),n=r===void 0?void 0:await Nt(r);return r!==void 0&&n===void 0?(e.logger.error(`${e.file} is a ${r.kind==="zip"?".zip":"directory"} but holds no <table>/documents.jsonl — expected a \`npx convex export --path\` snapshot, or pass an NDJSON file.`),{kind:"invalid"}):r===void 0||n===void 0?await xr(e)?{kind:"invalid"}:{kind:"ndjson"}:e.table!==void 0?(e.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{kind:"invalid"}):e.verify===!0&&e.withStorage!==!0&&await Cr(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},k=b("lunora","import-convex.json"),Pr=(e,t)=>{const r=H(e,t),n=A(r,"keyPrefix",t),s=r.storageColumns;if(s!==void 0){if(!I(s))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const o of Object.keys(s))Ce(s,o,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:s}},Ur=async(e,t)=>{const r=b(e,k);let n;try{n=await v(r,"utf8")}catch(o){if(o.code==="ENOENT"){t.info(`no ${k} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw o}let s;try{s=JSON.parse(n)}catch(o){throw new f("INTERNAL",`${r}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}return Pr(s,r)},Fr=(e,t,r)=>{try{return JSON.parse(e)}catch(n){throw new f("INTERNAL",`${t}/documents.jsonl line ${String(r)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}},Mr=async(e,t,r)=>{const n=new Map([...r].map(i=>[i,i])),s=[];let o=0;for await(const i of J(e,t)){const a=i.trim();if(o+=1,a.length===0)continue;const{ambiguous:c}=$e(Fr(a,t.table,o),n,t.table);for(const{column:d}of c)s.includes(d)||s.push(d)}return s},zr=async(e,t,r)=>{const n={};for(const s of t){if(we(s.table))continue;const o=await Mr(e,s,r);o.length>0&&(n[s.table]=o)}return n},Dr=async(e,t,r)=>{const n=b(t,k),s=`${JSON.stringify(e,void 0,4)}
7
+ `;await D(b(t,"lunora"),{recursive:!0});try{await me(n,s,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(o){if(o.code!=="EEXIST")throw o;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(s)}},Br=async(e,t,r,n)=>{const s=t.find(c=>c.table===T);if(s===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const o=await G(e,s,n),i=new Set(o.map(c=>c.id));n.info(`found ${String(i.size)} storage ids`);const a={keyPrefix:"",storageColumns:await zr(e,t,i)};return await Dr(a,r,n),a},S=20,Jr=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[s,o]of t){const i=r.inserted[s]??0;i<o&&(n+=1,e.error(`verify: ${s} inserted ${String(i)} of ${String(o)} source rows (${String(o-i)} missing)`))}else{const s=[...t.values()].reduce((i,a)=>i+a,0),o=Object.values(r.inserted).reduce((i,a)=>i+a,0)+r.conflicts;o<s&&(n+=1,e.error(`verify: ${String(o)} of ${String(s)} source rows accounted for across all tables (${String(s-o)} missing; ${String(r.conflicts)} already present)`))}return n>0?e.error(`verify: ${String(n)} row-parity check(s) failed`):e.success("verify: all source rows accounted for"),n},ue=(e,t,r)=>{for(const n of t.slice(0,S))e.warn(r(n));t.length>S&&e.warn(`… and ${String(t.length-S)} more`)},Vr=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),ue(e,t.unmigrated,n=>`unmigrated storage reference ${n.table}.${n.column}: ${n.storageId} has no exported blob — re-export with \`npx convex export --include-file-storage\``),ue(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${k} and re-import`),r&&t.unmigrated.length>0?(e.error(`verify: ${String(t.unmigrated.length)} storage reference(s) resolved to no migrated blob`),!0):!1),Hr=(e,t,r)=>{for(const n of[...t].slice(0,S))e.warn(`storage path never transferred: ${n} — left as-is`);return t.size>S&&e.warn(`… and ${String(t.size-S)} more untransferred storage paths`),r&&t.size>0},fe=200,Gr=/^\\x[\dA-Fa-f]*$/,Wr=/^[+-]?\d+$/,Xr=/^[+-]?\d+\.\d+$/,Yr=/^\{.*\}$/,Kr=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,qr=[["bytea-base64",e=>Gr.test(e)],["timestamp-ms",e=>Kr.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Wr.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>Xr.test(e)],[e=>e.every(t=>Yr.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Zr=e=>{if(e.length!==0){for(const[t,r]of qr)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},Qr=(e,t)=>{for(const[r,n]of Object.entries(e)){if(n.length===0)continue;const s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}},en=async e=>{const t=new Map,r=N(e).pipe(be({columns:!0,skipEmptyLines:!0,toLine:fe+1}));let n=0;for await(const o of r)if(Qr(o,t),n+=1,n>=fe)break;r.destroy();const s={};for(const[o,i]of t){const a=Zr(i);a!==void 0&&(s[o]=a)}return s},Fe=async(e,t,r,n)=>{const s=je(r),o=b(t,s),i=`${JSON.stringify(e,void 0,4)}
8
+ `;await D(pe(o),{recursive:!0});try{await me(o,i,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${o} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${o} already exists — leaving it untouched. Candidate mapping:`),n.info(i)}},tn=async(e,t,r)=>{const n={};for(const o of e){const i=await en(o.file);r.info(`${p(o.file)} → ${o.table}: ${String(Object.keys(i).length)} column(s) need a reshape`),n[o.table]={file:p(o.file),idColumn:"id",...Object.keys(i).length>0?{types:i}:{}}}const s={keyPrefix:"",tables:n};return await Fe(s,t,"supabase",r),s},rn=async(e,t,r)=>{const n={};for(const o of e)n[o.table]={file:p(o.file),storageColumns:[]};r.info(`found ${String(e.length)} collection(s) — Firestore values are self-describing, so only storage columns need declaring`);const s={keyPrefix:"",tables:n};return await Fe(s,t,"firebase",r),s},X=e=>b("lunora",`.import-storage-${e}.ndjson`),nn=async(e,t,r)=>{const n=new Map;let s;try{s=await v(b(e,X(t)),"utf8")}catch(i){if(i.code==="ENOENT")return n;throw i}let o=0;for(const i of s.split(`
9
+ `)){const a=i.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):o+=1}catch{o+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${o>0?` (${String(o)} unreadable checkpoint line(s) ignored)`:""}`),n},sn=async(e,t,r)=>{const n=b(e,X(t));await D(pe(n),{recursive:!0}),await Ke(n,`${JSON.stringify(r)}
10
+ `,"utf8")},Me=100,on=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),an=async(e,t,r,n,s)=>{const o=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:Me,offset:s,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!o.ok){const i=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(o.status)}): ${i}`)}return await o.json()},ze=async(e,t,r,n="")=>{const s=[];let o=0;for(;;){const i=await an(e,t,r,n,o);for(const a of i){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?s.push(...await ze(e,t,r,c)):s.push({contentType:a.metadata?.mimetype,name:c})}if(i.length<Me)return s;o+=i.length}},cn=async(e,t,r)=>{const n=await t(`${e.url}/storage/v1/bucket`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!n.ok){const i=await n.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase bucket list failed (HTTP ${String(n.status)}): ${i} — check the project URL and that the key is the service-role key, not the anon key`)}const s=await n.json(),o=[];for(const i of s){const a=await ze(e,i.name,t);r.info(`supabase bucket ${i.name}: ${String(a.length)} object(s)`);for(const c of a){const d=`${i.name}/${c.name}`;o.push({contentType:c.contentType,bytes:async()=>{const l=await t(`${e.url}/storage/v1/object/${encodeURIComponent(i.name)}/${on(c.name)}`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!l.ok){const u=await l.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase download failed for ${d} (HTTP ${String(l.status)}): ${u}`)}if(l.arrayBuffer===void 0)throw new f("INTERNAL","the fetch implementation cannot read response bytes, which the storage transfer requires");return Buffer.from(await l.arrayBuffer())},path:d})}}return o},dn=async e=>{const t=U(e),r=[],n=async s=>{const o=await x(s,{withFileTypes:!0}).catch(()=>{});if(o===void 0)throw new f("INTERNAL",`${e} is not a readable directory — download the bucket first with \`gcloud storage cp -r gs://<bucket> <dir>\``);for(const i of o){const a=U(s,i.name);if(!ye(t,a))throw new f("INTERNAL",`${i.name} resolves outside ${e} — refusing to upload it`);i.isDirectory()?await n(a):i.isFile()&&r.push({bytes:async()=>v(a),path:rt(t,a).split(nt).join("/")})}};return await n(t),r},ln=async(e,t,r,n,s)=>{const o=await t.bytes(),i=ft("sha256").update(o).digest("hex"),a=`${r.keyPrefix}${i}`;if(n.get(a)?.size!==o.length){const c={contentType:t.contentType,id:t.path,sha256:i,size:o.length};await Ue(e,a,o,c,s)}return await sn(r.cwd,r.source,{key:a,path:t.path,size:o.length}),a},un=(e,t)=>{const r=e>500?100:25;return n=>{if(n===e||n%r===0){const s=e===0?100:Math.round(n/e*100);t.info(`transferred ${String(n)}/${String(e)} object(s) (${String(s)}%)`)}}},he=async(e,t,r,n)=>{const s=new Map,o=await nn(r.cwd,r.source,n),i=await W(e,r.keyPrefix),a=new Map(i.map(l=>[l.key,l]));o.size>0&&i.length===0&&n.warn(`the checkpoint records ${String(o.size)} transferred object(s) but the target holds none under \`${r.keyPrefix}\` — re-transferring (a different deployment, a wiped bucket, or a changed keyPrefix)`);const c=un(t.length,n);let d=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const l of t){const u=o.get(l.path);if(u!==void 0&&a.has(u.key)){s.set(l.path,u.key),d+=1,c(d);continue}try{const h=await ln(e,l,r,a,n);s.set(l.path,h)}catch(h){const g=h instanceof Error?h.message:String(h);throw n.error(`failed transferring ${l.path} after ${String(d)} object(s): ${g}`),n.error(`progress is saved — re-run the same command to continue from here (delete ${X(r.source)} to start over)`),h}d+=1,c(d)}return n.success(`transferred ${String(t.length)} object(s) to R2`),s},ge=/^\/+/,fn=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,hn=/[#?]/u,gn=e=>{const t=new Map(e),r=new Map;for(const[n,s]of e){const o=n.indexOf("/");if(o===-1)continue;const i=n.slice(o+1);i.length===0||e.has(i)||r.set(i,r.has(i)?void 0:s)}for(const[n,s]of r)s!==void 0&&t.set(n,s);return t},mn=e=>{const t=fn.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(hn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},pn=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(ge,""),s=t.get(n);if(s!==void 0)return s;const o=mn(e);return o===void 0?void 0:t.get(o)??t.get(o.replace(ge,""))},yn=500,bn=9e5,wn=async e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)"),{refused:$.USAGE};const t=Qe(e.url,e.logger,e.cwd);if(t===void 0)return{refused:$.USAGE};if(qe({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`import bulk-writes ${t}, which is not local. Re-run with --yes to confirm.`),{refused:$.USAGE};const{token:r}=Ze({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:$.AUTH};try{const s=await L(e.file);if(!s.isFile()&&!s.isDirectory())return e.logger.error(`not a file or directory: ${e.file}`),{refused:$.USAGE}}catch(s){const o=s instanceof Error?s.message:String(s);return e.logger.error(`failed to stat ${e.file}: ${o}`),{refused:$.NOT_FOUND}}const n=e.fetchImpl??et;return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${ut}`,token:r}},$n=(e,t,r)=>({conflicts:e.conflicts,errors:e.errors,...e.failed.length>0?{failed:e.failed}:{},inserted:e.inserted,received:e.received,...t===void 0?{}:{storage:{ambiguous:r.ambiguous.slice(0,S),ambiguousTotal:r.ambiguous.length,blobs:t.size,rewritten:r.rewritten,unmigrated:r.unmigrated.slice(0,S),unmigratedTotal:r.unmigrated.length}},...e.warnings.length>0?{warnings:e.warnings}:{}}),Sn=(e,t,r,n)=>{switch(e.kind){case"convex":return kr(e.snapshot,e.tables,t.logger,r,n);case"firebase":return lr(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return Dt(e.tables,e.mapping,t.logger,n,t.file);default:return N(t.file,{encoding:"utf8"})}},vn=async(e,t,r)=>{switch(e.kind){case"convex":return Br(e.snapshot,e.tables,t,r);case"firebase":return rn(e.collections,t,r);case"supabase":return tn(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},Nn=async(e,t,r,n)=>{const s=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return he(e,await dn(r.storageDir),{cwd:n,keyPrefix:s,source:t.kind},r.logger);if(t.kind==="firebase"){r.logger.error("--with-storage needs --storage-dir for a Firebase source: download the bucket first (`gcloud storage cp -r gs://<bucket> ./storage`), then point --storage-dir at it.");return}const o=process.env.SUPABASE_URL,i=process.env.SUPABASE_SERVICE_ROLE_KEY;if(o===void 0||i===void 0){r.logger.error("--with-storage needs SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in the environment (the service-role key, not the anon key), or --storage-dir pointing at an already-downloaded bucket.");return}let a=o.length;for(;a>0&&o[a-1]==="/";)a-=1;const c=o.slice(0,a);if(!c.startsWith("https://")){r.logger.error(`SUPABASE_URL must be https:// — refusing to send the service-role key over ${c.split(":")[0]??"an unknown scheme"}.`);return}const d=await cn({serviceKey:i,url:c},e.fetchImpl,r.logger);return he(e,d,{cwd:n,keyPrefix:s,source:t.kind},r.logger)},En=(e,t,r,n,s)=>{const o=n.mapping?.tables?.[t]?.storageColumns??[];if(o.length===0)return e;const i={...e};for(const a of o){const c=i[a];if(typeof c!="string"||c.length===0)continue;const d=pn(c,r);d===void 0?s.add(`${t}.${a}: ${c}`):i[a]=d}return i},Tn=e=>{const t=e.source.kind==="supabase"||e.source.kind==="firebase"?e.source:void 0,{transferredPaths:r}=e,n=r===void 0||t===void 0?void 0:gn(r);return At({remapDocument:n===void 0||t===void 0?void 0:(s,o)=>En(s,o,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},An=async(e,t,r,n)=>{let s="",o=0;const i=async a=>{o+=1;const c=t(a,o);c!==void 0&&await r.push(c)};try{for await(const a of e){s+=typeof a=="string"?a:a.toString("utf8");let c=s.indexOf(`
11
+ `);for(;c!==-1;)await i(s.slice(0,c)),s=s.slice(c+1),c=s.indexOf(`
12
+ `)}s.length>0&&await i(s),await r.flush();return}catch(a){const c=a instanceof Error?a.message:String(a);return r.totals.received===0?(n.error(`import failed before any batch was acknowledged: ${c}`),n.error("re-run the same command once the worker is reachable (existing rows conflict rather than duplicate)")):(n.error(`import failed part-way through: ${c}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)")),a}},In=async(e,t,r,n)=>{const s=await Ur(r,n),o=t.tables.find(a=>a.table===T);if(o===void 0){n.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}const i=await Rr(e,t.snapshot,o,s?.keyPrefix??"",n);return n.info(`storage map: ${String(i.size)} blobs mapped`),{mapping:s,storageIdMap:i}},_n=async(e,t,r,n)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return In(e,t,n,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const s=await Nn(e,t,r,n);return s===void 0?void 0:{transferredPaths:s}}catch(s){r.logger.error(`storage transfer failed: ${s instanceof Error?s.message:String(s)}`),r.logger.error("no rows were imported — fix the error above and re-run; objects that did transfer are checkpointed and will be skipped");return}},Rn=(e,t)=>{for(const s of t.warnings)e.warn(s);const r=t.received-t.insertedTotal-t.conflicts-t.errorCount;r>0&&e.warn(`${String(r)} of ${String(t.received)} rows were neither inserted, conflicted, nor reported as errors`);const n=`imported ${String(t.insertedTotal)} of ${String(t.received)} rows (${String(t.conflicts)} conflicts, ${String(t.errorCount)} errors)`;t.failed?e.error(n):e.success(n)},On=async(e,t,r)=>await vn(e,t,r.logger)===void 0?{body:void 0,code:$.USAGE,error:"import --scan: the export could not be scanned",inserted:0}:{body:void 0,code:0,inserted:0},Yn=async e=>{const t=e.cwd??process.cwd(),r=await jr(e,t);if(r.kind==="invalid")return{body:void 0,code:$.USAGE,error:`import: could not read ${e.file}`,inserted:0};if(e.scan===!0)return On(r,t,e);const n=await wn(e);if(tt(n))return{body:void 0,code:n.refused,error:"import: could not resolve the worker URL and admin token",inserted:0};const{baseUrl:s,fetchImpl:o,requestUrl:i,token:a}=n,c=e.batchSize??yn,d=await _n({baseUrl:s,fetchImpl:o,token:a},r,e,t);if(d===void 0)return{body:void 0,code:1,error:"import: the storage phase failed — no rows were written",inserted:0};const{mapping:l,storageIdMap:u,transferredPaths:h}=d,g=new Set,m=l?.storageColumns,y={ambiguous:[],rewritten:0,unmigrated:[]};e.logger.info(r.kind==="convex"?`POST ${i} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${i} -> import ${e.file}`);const Y=new Map,De=Sn(r,e,u!==void 0,Y),j=Tt({batchSize:c,fetchImpl:o,maxBatchBytes:bn,requestUrl:i,token:a}),Be=Tn({report:y,source:r,storageColumns:m,storageIdMap:u,table:e.table,transferredPaths:h,unresolvedPaths:g}),K=await An(De,Be,j,e.logger),{conflicts:q,errors:Z,failed:Q,inserted:ee,received:Je,warnings:Ve}=j.totals,He=e.verify===!0&&K===void 0?Jr(e.logger,Y,{conflicts:q,inserted:ee}):0,Ge=u!==void 0&&Vr(e.logger,y,e.verify===!0),We=Hr(e.logger,g,e.verify===!0),_=Object.values(ee).reduce((E,Xe)=>E+Xe,0),R=$n(j.totals,u,y);for(const E of Q)e.logger.error(`import: shard "${E.shardKey}" was never reached${E.timedOut?" (timed out)":""} — its rows were NOT written: ${E.message}`);const te=K!==void 0||Z.length>0||Q.length>0||He>0||Ge||We;e.format!=="json"&&e.logger.info(JSON.stringify(R,void 0,2)),Rn(e.logger,{conflicts:q,errorCount:Z.length,failed:te,insertedTotal:_,received:Je,warnings:Ve});const re={file:e.file,inserted:_,summary:R};return te?{body:R,code:1,data:re,error:`import: ${e.file} did not import cleanly`,inserted:_}:{body:R,code:0,data:re,inserted:_}};export{yn as D,Xn as I,Pe as M,C as b,W as l,Yn as r,Ue as u};
@@ -0,0 +1 @@
1
+ var k={exports:{}},se,er;function H(){if(er)return se;er=1;const i="2.0.0",l=256,n=Number.MAX_SAFE_INTEGER||9007199254740991,t=16,s=l-6;return se={MAX_LENGTH:l,MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:i,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},se}var ne,rr;function B(){return rr||(rr=1,ne=process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...l)=>console.error("SEMVER",...l):()=>{}),ne}var tr;function M(){return tr||(tr=1,(function(i,l){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:t,MAX_LENGTH:s}=H(),h=B();l=i.exports={};const o=l.re=[],f=l.safeRe=[],r=l.src=[],m=l.safeSrc=[],e=l.t={};let a=0;const c="[a-zA-Z0-9-]",R=[["\\s",1],["\\d",s],[c,t]],L=O=>{for(const[q,G]of R)O=O.split(`${q}*`).join(`${q}{0,${G}}`).split(`${q}+`).join(`${q}{1,${G}}`);return O},E=(O,q,G)=>{const j=L(q),y=a++;h(O,y,q),e[O]=y,r[y]=q,m[y]=j,o[y]=new RegExp(q,G?"g":void 0),f[y]=new RegExp(j,G?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*"),E("NUMERICIDENTIFIERLOOSE","\\d+"),E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${c}*`),E("MAINVERSION",`(${r[e.NUMERICIDENTIFIER]})\\.(${r[e.NUMERICIDENTIFIER]})\\.(${r[e.NUMERICIDENTIFIER]})`),E("MAINVERSIONLOOSE",`(${r[e.NUMERICIDENTIFIERLOOSE]})\\.(${r[e.NUMERICIDENTIFIERLOOSE]})\\.(${r[e.NUMERICIDENTIFIERLOOSE]})`),E("PRERELEASEIDENTIFIER",`(?:${r[e.NONNUMERICIDENTIFIER]}|${r[e.NUMERICIDENTIFIER]})`),E("PRERELEASEIDENTIFIERLOOSE",`(?:${r[e.NONNUMERICIDENTIFIER]}|${r[e.NUMERICIDENTIFIERLOOSE]})`),E("PRERELEASE",`(?:-(${r[e.PRERELEASEIDENTIFIER]}(?:\\.${r[e.PRERELEASEIDENTIFIER]})*))`),E("PRERELEASELOOSE",`(?:-?(${r[e.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${r[e.PRERELEASEIDENTIFIERLOOSE]})*))`),E("BUILDIDENTIFIER",`${c}+`),E("BUILD",`(?:\\+(${r[e.BUILDIDENTIFIER]}(?:\\.${r[e.BUILDIDENTIFIER]})*))`),E("FULLPLAIN",`v?${r[e.MAINVERSION]}${r[e.PRERELEASE]}?${r[e.BUILD]}?`),E("FULL",`^${r[e.FULLPLAIN]}$`),E("LOOSEPLAIN",`[v=\\s]*${r[e.MAINVERSIONLOOSE]}${r[e.PRERELEASELOOSE]}?${r[e.BUILD]}?`),E("LOOSE",`^${r[e.LOOSEPLAIN]}$`),E("GTLT","((?:<|>)?=?)"),E("XRANGEIDENTIFIERLOOSE",`${r[e.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),E("XRANGEIDENTIFIER",`${r[e.NUMERICIDENTIFIER]}|x|X|\\*`),E("XRANGEPLAIN",`[v=\\s]*(${r[e.XRANGEIDENTIFIER]})(?:\\.(${r[e.XRANGEIDENTIFIER]})(?:\\.(${r[e.XRANGEIDENTIFIER]})(?:${r[e.PRERELEASE]})?${r[e.BUILD]}?)?)?`),E("XRANGEPLAINLOOSE",`[v=\\s]*(${r[e.XRANGEIDENTIFIERLOOSE]})(?:\\.(${r[e.XRANGEIDENTIFIERLOOSE]})(?:\\.(${r[e.XRANGEIDENTIFIERLOOSE]})(?:${r[e.PRERELEASELOOSE]})?${r[e.BUILD]}?)?)?`),E("XRANGE",`^${r[e.GTLT]}\\s*${r[e.XRANGEPLAIN]}$`),E("XRANGELOOSE",`^${r[e.GTLT]}\\s*${r[e.XRANGEPLAINLOOSE]}$`),E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),E("COERCE",`${r[e.COERCEPLAIN]}(?:$|[^\\d])`),E("COERCEFULL",r[e.COERCEPLAIN]+`(?:${r[e.PRERELEASE]})?(?:${r[e.BUILD]})?(?:$|[^\\d])`),E("COERCERTL",r[e.COERCE],!0),E("COERCERTLFULL",r[e.COERCEFULL],!0),E("LONETILDE","(?:~>?)"),E("TILDETRIM",`(\\s*)${r[e.LONETILDE]}\\s+`,!0),l.tildeTrimReplace="$1~",E("TILDE",`^${r[e.LONETILDE]}${r[e.XRANGEPLAIN]}$`),E("TILDELOOSE",`^${r[e.LONETILDE]}${r[e.XRANGEPLAINLOOSE]}$`),E("LONECARET","(?:\\^)"),E("CARETTRIM",`(\\s*)${r[e.LONECARET]}\\s+`,!0),l.caretTrimReplace="$1^",E("CARET",`^${r[e.LONECARET]}${r[e.XRANGEPLAIN]}$`),E("CARETLOOSE",`^${r[e.LONECARET]}${r[e.XRANGEPLAINLOOSE]}$`),E("COMPARATORLOOSE",`^${r[e.GTLT]}\\s*(${r[e.LOOSEPLAIN]})$|^$`),E("COMPARATOR",`^${r[e.GTLT]}\\s*(${r[e.FULLPLAIN]})$|^$`),E("COMPARATORTRIM",`(\\s*)${r[e.GTLT]}\\s*(${r[e.LOOSEPLAIN]}|${r[e.XRANGEPLAIN]})`,!0),l.comparatorTrimReplace="$1$2$3",E("HYPHENRANGE",`^\\s*(${r[e.XRANGEPLAIN]})\\s+-\\s+(${r[e.XRANGEPLAIN]})\\s*$`),E("HYPHENRANGELOOSE",`^\\s*(${r[e.XRANGEPLAINLOOSE]})\\s+-\\s+(${r[e.XRANGEPLAINLOOSE]})\\s*$`),E("STAR","(<|>)?=?\\s*\\*"),E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(k,k.exports)),k.exports}var ie,sr;function We(){if(sr)return ie;sr=1;const i=Object.freeze({loose:!0}),l=Object.freeze({});return ie=t=>t?typeof t!="object"?i:t:l,ie}var ae,nr;function Br(){if(nr)return ae;nr=1;const i=/^[0-9]+$/,l=(t,s)=>{if(typeof t=="number"&&typeof s=="number")return t===s?0:t<s?-1:1;const h=i.test(t),o=i.test(s);return h&&o&&(t=+t,s=+s),t===s?0:h&&!o?-1:o&&!h?1:t<s?-1:1};return ae={compareIdentifiers:l,rcompareIdentifiers:(t,s)=>l(s,t)},ae}var oe,ir;function _(){if(ir)return oe;ir=1;const i=B(),{MAX_LENGTH:l,MAX_SAFE_INTEGER:n}=H(),{safeRe:t,t:s}=M(),h=We(),{compareIdentifiers:o}=Br(),f=(m,e)=>{const a=e.split(".");if(a.length>m.length)return!1;for(let c=0;c<a.length;c++)if(o(m[c],a[c])!==0)return!1;return!0};class r{constructor(e,a){if(a=h(a),e instanceof r){if(e.loose===!!a.loose&&e.includePrerelease===!!a.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>l)throw new TypeError(`version is longer than ${l} characters`);i("SemVer",e,a),this.options=a,this.loose=!!a.loose,this.includePrerelease=!!a.includePrerelease;const c=e.trim().match(a.loose?t[s.LOOSE]:t[s.FULL]);if(!c)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+c[1],this.minor=+c[2],this.patch=+c[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");c[4]?this.prerelease=c[4].split(".").map(R=>{if(/^[0-9]+$/.test(R)){const L=+R;if(L>=0&&L<n)return L}return R}):this.prerelease=[],this.build=c[5]?c[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(i("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let a=0;do{const c=this.prerelease[a],R=e.prerelease[a];if(i("prerelease compare",a,c,R),c===void 0&&R===void 0)return 0;if(R===void 0)return 1;if(c===void 0)return-1;if(c===R)continue;return o(c,R)}while(++a)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let a=0;do{const c=this.build[a],R=e.build[a];if(i("build compare",a,c,R),c===void 0&&R===void 0)return 0;if(R===void 0)return 1;if(c===void 0)return-1;if(c===R)continue;return o(c,R)}while(++a)}inc(e,a,c){if(e.startsWith("pre")){if(!a&&c===!1)throw new Error("invalid increment argument: identifier is empty");if(a){const R=`-${a}`.match(this.options.loose?t[s.PRERELEASELOOSE]:t[s.PRERELEASE]);if(!R||R[1]!==a)throw new Error(`invalid identifier: ${a}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",a,c);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",a,c);break;case"prepatch":this.prerelease.length=0,this.inc("patch",a,c),this.inc("pre",a,c);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",a,c),this.inc("pre",a,c);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const R=Number(c)?1:0;if(this.prerelease.length===0)this.prerelease=[R];else{let L=this.prerelease.length;for(;--L>=0;)typeof this.prerelease[L]=="number"&&(this.prerelease[L]++,L=-2);if(L===-1){if(a===this.prerelease.join(".")&&c===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(R)}}if(a){let L=[a,R];if(c===!1&&(L=[a]),f(this.prerelease,a)){const E=this.prerelease[a.split(".").length];isNaN(E)&&(this.prerelease=L)}else this.prerelease=L}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return oe=r,oe}var ce,ar;function V(){if(ar)return ce;ar=1;const i=_();return ce=(n,t,s=!1)=>{if(n instanceof i)return n;try{return new i(n,t)}catch(h){if(!s)return null;throw h}},ce}var le,or;function Kr(){if(or)return le;or=1;const i=V();return le=(n,t)=>{const s=i(n,t);return s?s.version:null},le}var ue,cr;function Zr(){if(cr)return ue;cr=1;const i=V();return ue=(n,t)=>{const s=i(n.trim().replace(/^[=v]+/,""),t);return s?s.version:null},ue}var fe,lr;function Jr(){if(lr)return fe;lr=1;const i=_();return fe=(n,t,s,h,o)=>{typeof s=="string"&&(o=h,h=s,s=void 0);try{return new i(n instanceof i?n.version:n,s).inc(t,h,o).version}catch{return null}},fe}var he,ur;function Qr(){if(ur)return he;ur=1;const i=V();return he=(n,t)=>{const s=i(n,null,!0),h=i(t,null,!0),o=s.compare(h);if(o===0)return null;const f=o>0,r=f?s:h,m=f?h:s,e=!!r.prerelease.length;if(!!m.prerelease.length&&!e){if(!m.patch&&!m.minor)return"major";if(m.compareMain(r)===0)return m.minor&&!m.patch?"minor":"patch"}const c=e?"pre":"";return s.major!==h.major?c+"major":s.minor!==h.minor?c+"minor":s.patch!==h.patch?c+"patch":"prerelease"},he}var Ee,fr;function et(){if(fr)return Ee;fr=1;const i=_();return Ee=(n,t)=>new i(n,t).major,Ee}var pe,hr;function rt(){if(hr)return pe;hr=1;const i=_();return pe=(n,t)=>new i(n,t).minor,pe}var Re,Er;function tt(){if(Er)return Re;Er=1;const i=_();return Re=(n,t)=>new i(n,t).patch,Re}var me,pr;function st(){if(pr)return me;pr=1;const i=V();return me=(n,t)=>{const s=i(n,t);return s&&s.prerelease.length?s.prerelease:null},me}var $e,Rr;function U(){if(Rr)return $e;Rr=1;const i=_();return $e=(n,t,s)=>new i(n,s).compare(new i(t,s)),$e}var ve,mr;function nt(){if(mr)return ve;mr=1;const i=U();return ve=(n,t,s)=>i(t,n,s),ve}var Ie,$r;function it(){if($r)return Ie;$r=1;const i=U();return Ie=(n,t)=>i(n,t,!0),Ie}var de,vr;function ze(){if(vr)return de;vr=1;const i=_();return de=(n,t,s)=>{const h=new i(n,s),o=new i(t,s);return h.compare(o)||h.compareBuild(o)},de}var Le,Ir;function at(){if(Ir)return Le;Ir=1;const i=ze();return Le=(n,t)=>n.sort((s,h)=>i(s,h,t)),Le}var Ne,dr;function ot(){if(dr)return Ne;dr=1;const i=ze();return Ne=(n,t)=>n.sort((s,h)=>i(h,s,t)),Ne}var Se,Lr;function Y(){if(Lr)return Se;Lr=1;const i=U();return Se=(n,t,s)=>i(n,t,s)>0,Se}var Oe,Nr;function Ke(){if(Nr)return Oe;Nr=1;const i=U();return Oe=(n,t,s)=>i(n,t,s)<0,Oe}var Te,Sr;function Yr(){if(Sr)return Te;Sr=1;const i=U();return Te=(n,t,s)=>i(n,t,s)===0,Te}var Ae,Or;function Wr(){if(Or)return Ae;Or=1;const i=U();return Ae=(n,t,s)=>i(n,t,s)!==0,Ae}var ge,Tr;function Ze(){if(Tr)return ge;Tr=1;const i=U();return ge=(n,t,s)=>i(n,t,s)>=0,ge}var we,Ar;function Je(){if(Ar)return we;Ar=1;const i=U();return we=(n,t,s)=>i(n,t,s)<=0,we}var qe,gr;function zr(){if(gr)return qe;gr=1;const i=Yr(),l=Wr(),n=Y(),t=Ze(),s=Ke(),h=Je();return qe=(f,r,m,e)=>{switch(r){case"===":return typeof f=="object"&&(f=f.version),typeof m=="object"&&(m=m.version),f===m;case"!==":return typeof f=="object"&&(f=f.version),typeof m=="object"&&(m=m.version),f!==m;case"":case"=":case"==":return i(f,m,e);case"!=":return l(f,m,e);case">":return n(f,m,e);case">=":return t(f,m,e);case"<":return s(f,m,e);case"<=":return h(f,m,e);default:throw new TypeError(`Invalid operator: ${r}`)}},qe}var Pe,wr;function ct(){if(wr)return Pe;wr=1;const i=_(),l=V(),{safeRe:n,t}=M();return Pe=(h,o)=>{if(h instanceof i)return h;if(typeof h=="number"&&(h=String(h)),typeof h!="string")return null;o=o||{};let f=null;if(!o.rtl)f=h.match(o.includePrerelease?n[t.COERCEFULL]:n[t.COERCE]);else{const R=o.includePrerelease?n[t.COERCERTLFULL]:n[t.COERCERTL];let L;for(;(L=R.exec(h))&&(!f||f.index+f[0].length!==h.length);)(!f||L.index+L[0].length!==f.index+f[0].length)&&(f=L),R.lastIndex=L.index+L[1].length+L[2].length;R.lastIndex=-1}if(f===null)return null;const r=f[2],m=f[3]||"0",e=f[4]||"0",a=o.includePrerelease&&f[5]?`-${f[5]}`:"",c=o.includePrerelease&&f[6]?`+${f[6]}`:"";return l(`${r}.${m}.${e}${a}${c}`,o)},Pe}var Ce,qr;function lt(){if(qr)return Ce;qr=1;const i=V(),l=H(),n=_(),t=(f,r,m)=>{if(!l.RELEASE_TYPES.includes(r))return null;const e=s(f,m);return e&&h(e,r)},s=(f,r)=>{const m=f instanceof n?f.version:f;return i(m,r)},h=(f,r)=>{if(o(r))return f.version;switch(f.prerelease=[],r){case"major":f.minor=0,f.patch=0;break;case"minor":f.patch=0;break}return f.format()},o=f=>f.startsWith("pre");return Ce=t,Ce}var De,Pr;function ut(){if(Pr)return De;Pr=1;class i{constructor(){this.max=1e3,this.map=new Map}get(n){const t=this.map.get(n);if(t!==void 0)return this.map.delete(n),this.map.set(n,t),t}delete(n){return this.map.delete(n)}set(n,t){if(!this.delete(n)&&t!==void 0){if(this.map.size>=this.max){const h=this.map.keys().next().value;this.delete(h)}this.map.set(n,t)}return this}}return De=i,De}var Ge,Cr;function X(){if(Cr)return Ge;Cr=1;const i=/\s+/g;class l{constructor(u,I){if(I=s(I),u instanceof l)return u.loose===!!I.loose&&u.includePrerelease===!!I.includePrerelease?u:new l(u.raw,I);if(u instanceof h)return this.raw=u.value,this.set=[[u]],this.formatted=void 0,this;if(this.options=I,this.loose=!!I.loose,this.includePrerelease=!!I.includePrerelease,this.raw=u.trim().replace(i," "),this.set=this.raw.split("||").map(v=>this.parseRange(v.trim())).filter(v=>v.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const v=this.set[0];if(this.set=this.set.filter(S=>!q(S[0])),this.set.length===0)this.set=[v];else if(this.set.length>1){for(const S of this.set)if(S.length===1&&G(S[0])){this.set=[S];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let u=0;u<this.set.length;u++){u>0&&(this.formatted+="||");const I=this.set[u];for(let v=0;v<I.length;v++)v>0&&(this.formatted+=" "),this.formatted+=I[v].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(u){u=u.replace(O,"");const v=((this.options.includePrerelease&&L)|(this.options.loose&&E))+":"+u,S=t.get(v);if(S)return S;const $=this.options.loose,d=$?r[e.HYPHENRANGELOOSE]:r[e.HYPHENRANGE];u=u.replace(d,re(this.options.includePrerelease)),o("hyphen replace",u),u=u.replace(r[e.COMPARATORTRIM],a),o("comparator trim",u),u=u.replace(r[e.TILDETRIM],c),o("tilde trim",u),u=u.replace(r[e.CARETTRIM],R),o("caret trim",u);let g=u.split(" ").map(C=>y(C,this.options)).join(" ").split(/\s+/).map(C=>ee(C,this.options));$&&(g=g.filter(C=>(o("loose invalid filter",C,this.options),!!C.match(r[e.COMPARATORLOOSE])))),o("range list",g);const T=new Map,w=g.map(C=>new h(C,this.options));for(const C of w){if(q(C))return[C];T.set(C.value,C)}T.size>1&&T.has("")&&T.delete("");const F=[...T.values()];return t.set(v,F),F}intersects(u,I){if(!(u instanceof l))throw new TypeError("a Range is required");return this.set.some(v=>j(v,I)&&u.set.some(S=>j(S,I)&&v.every($=>S.every(d=>$.intersects(d,I)))))}test(u){if(!u)return!1;if(typeof u=="string")try{u=new f(u,this.options)}catch{return!1}for(let I=0;I<this.set.length;I++)if(te(this.set[I],u,this.options))return!0;return!1}}Ge=l;const n=ut(),t=new n,s=We(),h=W(),o=B(),f=_(),{safeRe:r,src:m,t:e,comparatorTrimReplace:a,tildeTrimReplace:c,caretTrimReplace:R}=M(),{FLAG_INCLUDE_PRERELEASE:L,FLAG_LOOSE:E}=H(),O=new RegExp(m[e.BUILD],"g"),q=p=>p.value==="<0.0.0-0",G=p=>p.value==="",j=(p,u)=>{let I=!0;const v=p.slice();let S=v.pop();for(;I&&v.length;)I=v.every($=>S.intersects($,u)),S=v.pop();return I},y=(p,u)=>(p=p.replace(r[e.BUILD],""),o("comp",p,u),p=x(p,u),o("caret",p),p=D(p,u),o("tildes",p),p=Z(p,u),o("xrange",p),p=Q(p,u),o("stars",p),p),A=p=>!p||p.toLowerCase()==="x"||p==="*",P=(p,u,I)=>A(p)&&!A(u)||A(u)&&I&&!A(I),D=(p,u)=>p.trim().split(/\s+/).map(I=>N(I,u)).join(" "),N=(p,u)=>{const I=u.loose?r[e.TILDELOOSE]:r[e.TILDE],v=u.includePrerelease?"-0":"";return p.replace(I,(S,$,d,g,T)=>{o("tilde",p,S,$,d,g,T);let w;return A($)?w="":A(d)?w=`>=${$}.0.0${v} <${+$+1}.0.0-0`:A(g)?w=`>=${$}.${d}.0${v} <${$}.${+d+1}.0-0`:T?(o("replaceTilde pr",T),w=`>=${$}.${d}.${g}-${T} <${$}.${+d+1}.0-0`):w=`>=${$}.${d}.${g} <${$}.${+d+1}.0-0`,o("tilde return",w),w})},x=(p,u)=>p.trim().split(/\s+/).map(I=>K(I,u)).join(" "),K=(p,u)=>{o("caret",p,u);const I=u.loose?r[e.CARETLOOSE]:r[e.CARET],v=u.includePrerelease?"-0":"";return p.replace(I,(S,$,d,g,T)=>{o("caret",p,S,$,d,g,T);let w;return A($)?w="":A(d)?w=`>=${$}.0.0${v} <${+$+1}.0.0-0`:A(g)?$==="0"?w=`>=${$}.${d}.0${v} <${$}.${+d+1}.0-0`:w=`>=${$}.${d}.0${v} <${+$+1}.0.0-0`:T?(o("replaceCaret pr",T),$==="0"?d==="0"?w=`>=${$}.${d}.${g}-${T} <${$}.${d}.${+g+1}-0`:w=`>=${$}.${d}.${g}-${T} <${$}.${+d+1}.0-0`:w=`>=${$}.${d}.${g}-${T} <${+$+1}.0.0-0`):(o("no pr"),$==="0"?d==="0"?w=`>=${$}.${d}.${g} <${$}.${d}.${+g+1}-0`:w=`>=${$}.${d}.${g} <${$}.${+d+1}.0-0`:w=`>=${$}.${d}.${g} <${+$+1}.0.0-0`),o("caret return",w),w})},Z=(p,u)=>(o("replaceXRanges",p,u),p.split(/\s+/).map(I=>J(I,u)).join(" ")),J=(p,u)=>{p=p.trim();const I=u.loose?r[e.XRANGELOOSE]:r[e.XRANGE];return p.replace(I,(v,S,$,d,g,T)=>{if(o("xRange",p,v,S,$,d,g,T),P($,d,g))return p;const w=A($),F=w||A(d),C=F||A(g),b=C;return S==="="&&b&&(S=""),T=u.includePrerelease?"-0":"",w?S===">"||S==="<"?v="<0.0.0-0":v="*":S&&b?(F&&(d=0),g=0,S===">"?(S=">=",F?($=+$+1,d=0,g=0):(d=+d+1,g=0)):S==="<="&&(S="<",F?$=+$+1:d=+d+1),S==="<"&&(T="-0"),v=`${S+$}.${d}.${g}${T}`):F?v=`>=${$}.0.0${T} <${+$+1}.0.0-0`:C&&(v=`>=${$}.${d}.0${T} <${$}.${+d+1}.0-0`),o("xRange return",v),v})},Q=(p,u)=>(o("replaceStars",p,u),p.trim().replace(r[e.STAR],"")),ee=(p,u)=>(o("replaceGTE0",p,u),p.trim().replace(r[u.includePrerelease?e.GTE0PRE:e.GTE0],"")),re=p=>(u,I,v,S,$,d,g,T,w,F,C,b)=>(A(v)?I="":A(S)?I=`>=${v}.0.0${p?"-0":""}`:A($)?I=`>=${v}.${S}.0${p?"-0":""}`:d?I=`>=${I}`:I=`>=${I}${p?"-0":""}`,A(w)?T="":A(F)?T=`<${+w+1}.0.0-0`:A(C)?T=`<${w}.${+F+1}.0-0`:b?T=`<=${w}.${F}.${C}-${b}`:p?T=`<${w}.${F}.${+C+1}-0`:T=`<=${T}`,`${I} ${T}`.trim()),te=(p,u,I)=>{for(let v=0;v<p.length;v++)if(!p[v].test(u))return!1;if(u.prerelease.length&&!I.includePrerelease){for(let v=0;v<p.length;v++)if(o(p[v].semver),p[v].semver!==h.ANY&&p[v].semver.prerelease.length>0){const S=p[v].semver;if(S.major===u.major&&S.minor===u.minor&&S.patch===u.patch)return!0}return!1}return!0};return Ge}var ye,Dr;function W(){if(Dr)return ye;Dr=1;const i=Symbol("SemVer ANY");class l{static get ANY(){return i}constructor(e,a){if(a=n(a),e instanceof l){if(e.loose===!!a.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),o("comparator",e,a),this.options=a,this.loose=!!a.loose,this.parse(e),this.semver===i?this.value="":this.value=this.operator+this.semver.version,o("comp",this)}parse(e){const a=this.options.loose?t[s.COMPARATORLOOSE]:t[s.COMPARATOR],c=e.match(a);if(!c)throw new TypeError(`Invalid comparator: ${e}`);this.operator=c[1]!==void 0?c[1]:"",this.operator==="="&&(this.operator=""),c[2]?this.semver=new f(c[2],this.options.loose):this.semver=i}toString(){return this.value}test(e){if(o("Comparator.test",e,this.options.loose),this.semver===i||e===i)return!0;if(typeof e=="string")try{e=new f(e,this.options)}catch{return!1}return h(e,this.operator,this.semver,this.options)}intersects(e,a){if(!(e instanceof l))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new r(e.value,a).test(this.value):e.operator===""?e.value===""?!0:new r(this.value,a).test(e.semver):(a=n(a),a.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!a.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||h(this.semver,"<",e.semver,a)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||h(this.semver,">",e.semver,a)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}}ye=l;const n=We(),{safeRe:t,t:s}=M(),h=zr(),o=B(),f=_(),r=X();return ye}var _e,Gr;function z(){if(Gr)return _e;Gr=1;const i=X();return _e=(n,t,s)=>{try{t=new i(t,s)}catch{return!1}return t.test(n)},_e}var je,yr;function ft(){if(yr)return je;yr=1;const i=X();return je=(n,t)=>new i(n,t).set.map(s=>s.map(h=>h.value).join(" ").trim().split(" ")),je}var Fe,_r;function ht(){if(_r)return Fe;_r=1;const i=_(),l=X();return Fe=(t,s,h)=>{let o=null,f=null,r=null;try{r=new l(s,h)}catch{return null}return t.forEach(m=>{r.test(m)&&(!o||f.compare(m)===-1)&&(o=m,f=new i(o,h))}),o},Fe}var Ue,jr;function Et(){if(jr)return Ue;jr=1;const i=_(),l=X();return Ue=(t,s,h)=>{let o=null,f=null,r=null;try{r=new l(s,h)}catch{return null}return t.forEach(m=>{r.test(m)&&(!o||f.compare(m)===1)&&(o=m,f=new i(o,h))}),o},Ue}var Xe,Fr;function pt(){if(Fr)return Xe;Fr=1;const i=_(),l=X(),n=Y();return Xe=(s,h)=>{s=new l(s,h);let o=new i("0.0.0");if(s.test(o)||(o=new i("0.0.0-0"),s.test(o)))return o;o=null;for(let f=0;f<s.set.length;++f){const r=s.set[f];let m=null;r.forEach(e=>{const a=new i(e.semver.version);switch(e.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!m||n(a,m))&&(m=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),m&&(!o||n(o,m))&&(o=m)}return o&&s.test(o)?o:null},Xe}var Ve,Ur;function Rt(){if(Ur)return Ve;Ur=1;const i=X();return Ve=(n,t)=>{try{return new i(n,t).range||"*"}catch{return null}},Ve}var xe,Xr;function Qe(){if(Xr)return xe;Xr=1;const i=_(),l=W(),{ANY:n}=l,t=X(),s=z(),h=Y(),o=Ke(),f=Je(),r=Ze();return xe=(e,a,c,R)=>{e=new i(e,R),a=new t(a,R);let L,E,O,q,G;switch(c){case">":L=h,E=f,O=o,q=">",G=">=";break;case"<":L=o,E=r,O=h,q="<",G="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(e,a,R))return!1;for(let j=0;j<a.set.length;++j){const y=a.set[j];let A=null,P=null;if(y.forEach(D=>{D.semver===n&&(D=new l(">=0.0.0")),A=A||D,P=P||D,L(D.semver,A.semver,R)?A=D:O(D.semver,P.semver,R)&&(P=D)}),A.operator===q||A.operator===G||(!P.operator||P.operator===q)&&E(e,P.semver))return!1;if(P.operator===G&&O(e,P.semver))return!1}return!0},xe}var be,Vr;function mt(){if(Vr)return be;Vr=1;const i=Qe();return be=(n,t,s)=>i(n,t,">",s),be}var He,xr;function $t(){if(xr)return He;xr=1;const i=Qe();return He=(n,t,s)=>i(n,t,"<",s),He}var Me,br;function vt(){if(br)return Me;br=1;const i=X();return Me=(n,t,s)=>(n=new i(n,s),t=new i(t,s),n.intersects(t,s)),Me}var ke,Hr;function It(){if(Hr)return ke;Hr=1;const i=z(),l=U();return ke=(n,t,s)=>{const h=[];let o=null,f=null;const r=n.sort((c,R)=>l(c,R,s));for(const c of r)i(c,t,s)?(f=c,o||(o=c)):(f&&h.push([o,f]),f=null,o=null);o&&h.push([o,null]);const m=[];for(const[c,R]of h)c===R?m.push(c):!R&&c===r[0]?m.push("*"):R?c===r[0]?m.push(`<=${R}`):m.push(`${c} - ${R}`):m.push(`>=${c}`);const e=m.join(" || "),a=typeof t.raw=="string"?t.raw:String(t);return e.length<a.length?e:t},ke}var Be,Mr;function dt(){if(Mr)return Be;Mr=1;const i=X(),l=W(),{ANY:n}=l,t=z(),s=U(),h=(a,c,R={})=>{if(a===c)return!0;a=new i(a,R),c=new i(c,R);let L=!1;e:for(const E of a.set){for(const O of c.set){const q=r(E,O,R);if(L=L||q!==null,q)continue e}if(L)return!1}return!0},o=[new l(">=0.0.0-0")],f=[new l(">=0.0.0")],r=(a,c,R)=>{if(a===c)return!0;if(a.length===1&&a[0].semver===n){if(c.length===1&&c[0].semver===n)return!0;R.includePrerelease?a=o:a=f}if(c.length===1&&c[0].semver===n){if(R.includePrerelease)return!0;c=f}const L=new Set;let E,O;for(const N of a)N.operator===">"||N.operator===">="?E=m(E,N,R):N.operator==="<"||N.operator==="<="?O=e(O,N,R):L.add(N.semver);if(L.size>1)return null;let q;if(E&&O){if(q=s(E.semver,O.semver,R),q>0)return null;if(q===0&&(E.operator!==">="||O.operator!=="<="))return null}for(const N of L){if(E&&!t(N,String(E),R)||O&&!t(N,String(O),R))return null;for(const x of c)if(!t(N,String(x),R))return!1;return!0}let G,j,y,A,P=O&&!R.includePrerelease&&O.semver.prerelease.length?O.semver:!1,D=E&&!R.includePrerelease&&E.semver.prerelease.length?E.semver:!1;P&&P.prerelease.length===1&&O.operator==="<"&&P.prerelease[0]===0&&(P=!1);for(const N of c){if(A=A||N.operator===">"||N.operator===">=",y=y||N.operator==="<"||N.operator==="<=",E){if(D&&N.semver.prerelease&&N.semver.prerelease.length&&N.semver.major===D.major&&N.semver.minor===D.minor&&N.semver.patch===D.patch&&(D=!1),N.operator===">"||N.operator===">="){if(G=m(E,N,R),G===N&&G!==E)return!1}else if(E.operator===">="&&!N.test(E.semver))return!1}if(O){if(P&&N.semver.prerelease&&N.semver.prerelease.length&&N.semver.major===P.major&&N.semver.minor===P.minor&&N.semver.patch===P.patch&&(P=!1),N.operator==="<"||N.operator==="<="){if(j=e(O,N,R),j===N&&j!==O)return!1}else if(O.operator==="<="&&!N.test(O.semver))return!1}if(!N.operator&&(O||E)&&q!==0)return!1}return!(E&&y&&!O&&q!==0||O&&A&&!E&&q!==0||D||P)},m=(a,c,R)=>{if(!a)return c;const L=s(a.semver,c.semver,R);return L>0?a:L<0||c.operator===">"&&a.operator===">="?c:a},e=(a,c,R)=>{if(!a)return c;const L=s(a.semver,c.semver,R);return L<0?a:L>0||c.operator==="<"&&a.operator==="<="?c:a};return Be=h,Be}var Ye,kr;function Lt(){if(kr)return Ye;kr=1;const i=M(),l=H(),n=_(),t=Br(),s=V(),h=Kr(),o=Zr(),f=Jr(),r=Qr(),m=et(),e=rt(),a=tt(),c=st(),R=U(),L=nt(),E=it(),O=ze(),q=at(),G=ot(),j=Y(),y=Ke(),A=Yr(),P=Wr(),D=Ze(),N=Je(),x=zr(),K=ct(),Z=lt(),J=W(),Q=X(),ee=z(),re=ft(),te=ht(),p=Et(),u=pt(),I=Rt(),v=Qe(),S=mt(),$=$t(),d=vt(),g=It(),T=dt();return Ye={parse:s,valid:h,clean:o,inc:f,diff:r,major:m,minor:e,patch:a,prerelease:c,compare:R,rcompare:L,compareLoose:E,compareBuild:O,sort:q,rsort:G,gt:j,lt:y,eq:A,neq:P,gte:D,lte:N,cmp:x,coerce:K,truncate:Z,Comparator:J,Range:Q,satisfies:ee,toComparators:re,maxSatisfying:te,minSatisfying:p,minVersion:u,validRange:I,outside:v,gtr:S,ltr:$,intersects:d,simplifyRange:g,subset:T,SemVer:n,re:i.re,src:i.src,tokens:i.t,SEMVER_SPEC_VERSION:l.SEMVER_SPEC_VERSION,RELEASE_TYPES:l.RELEASE_TYPES,compareIdentifiers:t.compareIdentifiers,rcompareIdentifiers:t.rcompareIdentifiers},Ye}var Nt=Lt();export{Nt as s};
@@ -0,0 +1,8 @@
1
+ import{Project as m,SyntaxKind as i,Node as a}from"ts-morph";const u=/^[A-Za-z_$][\w$]*$/u,o=t=>`// lunora:add:${t}:start`,l=t=>`// lunora:add:${t}:end`,g=t=>`./${t}/schema`,x=(t,e)=>t.getLocal(e)!==void 0?!0:t.getImportDeclarations().some(r=>r.getDefaultImport()?.getText()===e||r.getNamespaceImport()?.getText()===e||r.getNamedImports().some(n=>(n.getAliasNode()??n.getNameNode()).getText()===e)),E=t=>{for(const e of t)if(e.getExpression().getText()==="defineSchema")return e},$=t=>{let e=t;for(let r=e.getParent();r!==void 0;r=e.getParent())if(a.isPropertyAccessExpression(r)&&r.getExpression()===e)e=r;else if(a.isCallExpression(r)&&r.getExpression()===e)e=r;else break;return e},h=(t,e)=>{if(!u.test(e))return{ok:!1,reason:"invalid-identifier"};if(t.includes(o(e)))return{ok:!1,reason:"already-applied"};const n=new m({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("schema.ts",t,{overwrite:!0});if(x(n,e))return{ok:!1,reason:"already-applied"};const c=n.getDescendantsOfKind(i.CallExpression),s=E(c);if(!s)return{ok:!1,reason:"no-define-schema"};if(s.getArguments()[0]?.getKind()!==i.ObjectLiteralExpression)return{ok:!1,reason:"non-object-argument"};const d=$(s).getEnd(),p=`
2
+ ${o(e)}
3
+ .extend(${e}.extension)
4
+ ${l(e)}
5
+ `;n.insertText(d,p);const f=`${o(e)}
6
+ import { ${e} } from "${g(e)}";
7
+ ${l(e)}
8
+ `;return n.insertText(0,f),{ok:!0,text:n.getFullText()}};export{h as insertSchemaExtension};
@@ -0,0 +1,2 @@
1
+ const n=(s,e)=>{for(const t of s)(t.status==="created"||t.status==="updated")&&e.success(`${t.status} ${t.path} — ${t.tool} now skips Lunora's generated files`),t.status==="failed"&&e.warn(`could not configure ${t.tool} to skip Lunora's generated files: ${t.message??"unknown error"}. Add the entries by hand, or re-run once the path is writable.`),t.status==="manual"&&t.snippet!==void 0&&e.warn(`${t.path} needs an entry so ${t.tool} skips Lunora's generated files — add:
2
+ ${t.snippet}`)};export{n as r};
@@ -0,0 +1,2 @@
1
+ import{existsSync as l,readFileSync as u,mkdirSync as v,realpathSync as E,statSync as b,writeFileSync as M,chmodSync as k,renameSync as x,unlinkSync as $}from"node:fs";import{dirname as h}from"@visulima/path";import{parse as w,modify as O,applyEdits as j}from"jsonc-parser";const g=(t,n)=>{let i=t,r;try{i=E(t),r=b(i).mode}catch{}const o=`${i}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{v(h(i),{recursive:!0}),M(o,n,"utf8"),r!==void 0&&k(o,r),x(o,i)}catch(e){try{$(o)}catch{}throw e}},A={formattingOptions:{insertSpaces:!0,tabSize:4}},d=t=>{const n=[],i=w(t,n,{allowTrailingComma:!0});return{errors:n,value:i}},f=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),p=(t,n,i)=>{if(!f(t))return;const r=t[n];return f(r)?r[i]:void 0},F=t=>{if(!l(t.path))return"absent";let n;try{n=u(t.path,"utf8")}catch{return"invalid"}if(n.trim().length===0)return"absent";const{errors:i,value:r}=d(n);return i.length>0||!f(r)?"invalid":p(r,t.key,t.name)===void 0?"absent":"present"},J=t=>F(t)==="present",S=(t,n,i,r,o)=>{try{const e=O(t,[i,r],o,A);e.length>0&&g(n,j(t,e));return}catch(e){return e instanceof Error?e.message:String(e)}},P=t=>{const{entry:n,force:i=!1,key:r,name:o,path:e}=t,c=l(e)?u(e,"utf8"):"";if(c.trim().length===0)return v(h(e),{recursive:!0}),g(e,`${JSON.stringify({[r]:{[o]:n}},void 0,4)}
2
+ `),{action:"created",path:e};const{errors:s,value:a}=d(c);if(s.length>0)return{action:"invalid",error:`parse error at offset ${String(s[0]?.offset??0)}`,path:e};if(!f(a))return{action:"invalid",error:"the file's root is not a JSON object",path:e};const y=a[r];if(y!==void 0&&!f(y))return{action:"invalid",error:`"${r}" is not an object`,path:e};if(p(a,r,o)!==void 0&&!i)return{action:"skipped",path:e};const m=S(c,e,r,o,n);return m===void 0?{action:"updated",path:e}:{action:"invalid",error:m,path:e}},z=t=>{const{key:n,name:i,path:r}=t;if(!l(r))return{action:"absent",path:r};let o;try{o=u(r,"utf8")}catch(a){return{action:"invalid",error:a instanceof Error?a.message:String(a),path:r}}const{errors:e,value:c}=d(o);if(e.length>0)return{action:"invalid",error:`parse error at offset ${String(e[0]?.offset??0)}`,path:r};if(p(c,n,i)===void 0)return{action:"absent",path:r};const s=S(o,r,n,i,void 0);return s===void 0?{action:"removed",path:r}:{action:"invalid",error:s,path:r}};export{J as h,F as i,z as r,P as u,g as w};
@@ -0,0 +1 @@
1
+ import{spawn as i}from"node:child_process";import{platform as s}from"node:os";import{LunoraError as a}from"@lunora/errors";const d=()=>{const o=s();return o==="darwin"?{args:[],command:"open"}:o==="win32"?{args:["/c","start",""],command:"cmd"}:{args:[],command:"xdg-open"}},f=o=>o.replaceAll(/[!"%&()<>^|]/gu,n=>`%${(n.codePointAt(0)??0).toString(16).toUpperCase()}`),w=o=>new Promise((n,r)=>{const{args:e,command:c}=d(),p=s()==="win32"?f(o):o,t=i(c,[...e,p],{detached:!0,stdio:"ignore"});t.once("error",m=>{r(m)}),t.once("spawn",()=>{t.unref(),n()})}),L=async(o,n={})=>{let r;try{r=new URL(o)}catch{throw new a("INTERNAL",`Invalid URL: ${o}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new a("INTERNAL",`Refusing to open non-http(s) URL: ${o}`);await(n.opener??w)(o)};export{L as o};
@@ -0,0 +1,2 @@
1
+ import{isProcessStreamLogger as o,createStderrLogger as e}from"./createLogger-Cl18I8AX.mjs";const n={description:"Output format: pretty (default) or json",name:"format",type:String},p=(r,t)=>t===void 0?{format:"pretty"}:t==="json"||t==="pretty"?{format:t}:{error:`${r}: unknown --format "${t}" — expected pretty | json`},a=(r,t)=>r==="json"&&o(t)?e():t,i=r=>{process.stdout.write(`${JSON.stringify(r,void 0,2)}
2
+ `)};export{n as O,i as a,a as l,p};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";const d=/[\r\n]/u,w=/^[A-Za-z_]\w*$/u,y=/^[A-Za-z0-9][\w-]*$/u,b=/^[\w.-]+(?:\/[\w.-]+)*$/u,I=(c,s)=>{if(typeof c!="object"||c===null)throw new r("INTERNAL",`registry.json for "${s}" is not an object`);const e=c,{name:n}=e;if(typeof n!="string"||n.length===0)throw new r("INTERNAL",`registry.json for "${s}" is missing a string "name"`);if(!y.test(n))throw new r("INTERNAL",`registry.json for "${s}": name "${n}" must match ${y.source} (letters, digits, "-", "_"; no path separators, "..", or code)`);const g=e.files;if(!Array.isArray(g))throw new TypeError(`registry.json for "${s}" is missing a "files" array`);const A=g.map((t,o)=>{if(typeof t!="object"||t===null)throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}] is not an object`);const i=t,{from:a}=i,{to:f}=i,{merge:p}=i;if(typeof a!="string"||typeof f!="string")throw new TypeError(`registry.json "${s}": files[${String(o)}] needs string "from" and "to"`);if(p!=="create-or-skip"&&p!=="schema-extension")throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}].merge must be "create-or-skip" or "schema-extension"`);for(const[v,l]of[["from",a],["to",f]])if(l.includes("..")||l.startsWith("/"))throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}].${v} "${l}" must be a relative path without ".."`);return{from:a,merge:p,to:f}}),u=t=>typeof t=="object"&&t!==null?t:void 0,h=u(e.deps),m=u(e.devDependencies),$=Array.isArray(e.requires)?e.requires.filter(t=>typeof t=="string"):void 0,E=Array.isArray(e.bindings)?e.bindings.filter(t=>{if(typeof t!="object"||t===null)return!1;const o=t;return Array.isArray(o.path)&&o.path.every(i=>typeof i=="string")}):void 0,j=Array.isArray(e.entrypointReexports)?e.entrypointReexports.filter(t=>typeof t=="object"&&t!==null&&typeof t.module=="string").map(t=>{if(t.module.includes("..")||t.module.startsWith("/")||!b.test(t.module))throw new r("INTERNAL",`registry.json "${s}": entrypointReexports[].module "${t.module}" must be a safe relative module path without path traversal or unsafe characters`);const o={module:t.module};if(typeof t.comment=="string"){if(d.test(t.comment))throw new r("INTERNAL",`registry.json "${s}": entrypointReexports[].comment must not contain a newline`);o.comment=t.comment}return o}):void 0,R=Array.isArray(e.envVars)?e.envVars.filter(t=>typeof t=="object"&&t!==null&&typeof t.name=="string").map(t=>{const o=typeof t.value=="string";if(!w.test(t.name))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].name must match ${w.source} (letters, digits, underscore; no "=" or newline)`);if(o&&d.test(t.value))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].value must not contain a newline`);if(typeof t.description=="string"&&d.test(t.description))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].description must not contain a newline`);return{...typeof t.description=="string"?{description:t.description}:{},name:t.name,secret:typeof t.secret=="boolean"?t.secret:!o,...o?{value:t.value}:{}}}):void 0;return{bindings:E,deps:h,description:typeof e.description=="string"?e.description:void 0,devDependencies:m,docs:typeof e.docs=="string"?e.docs:void 0,entrypointReexports:j,envVars:R,files:A,name:n,requires:$,title:typeof e.title=="string"?e.title:void 0}};export{I as default};
@@ -0,0 +1 @@
1
+ import{sep as t}from"node:path";const m=(s,i,e=t)=>i===s||i.startsWith(s.endsWith(e)?s:`${s}${e}`);export{m as i};
@@ -0,0 +1,5 @@
1
+ import{existsSync as q,mkdirSync as Te,openSync as J,closeSync as X,statSync as Pe,readFileSync as Q,readSync as be}from"node:fs";import{join as C,dirname as _e}from"node:path";import{readServiceBindings as $e}from"@lunora/codegen";import{readLiveDevServerState as N,discoverContainerInfo as Re,streamContainerLogs as Ce,formatLunoraEvent as Ne,updateDevServerState as b,targetRunsOwnDevServer as O,resolveProjectTarget as Z,claimDevServerState as Oe,DEV_HANDOFF_ENV as De,clearDevServerState as y,readDevServerState as D,isDevServerReady as j,detectFramework as ee,readProjectDependencyNames as Ae,DEV_LOG_FILE_ENV as xe,DEV_DAEMON_ENV as Me,detectPackageManager as A,readProjectManifest as Ue,execArgsFor as re,isRecordedProcessCurrent as Ge,DEV_LOG_FILE as Fe,CODEGEN_ENV as te,isCodegenDisabled as je,planToolchainInvocation as Ve,toolchainExecArgs as ne,startCelldDevSession as We,resolveDeployDriver as oe,DEV_VARS_FILE as ie,runScriptCommand as Be,parseDevVariableEntries as Ke}from"@lunora/config";import{warnCloudflareCliConfigOnce as He,findWranglerFile as L,readWranglerJsonc as x,materializeDevWranglerConfig as ze,materializeServiceDevConfigs as Ye}from"@lunora/config/cloudflare";import{createServer as qe}from"node:net";import{networkInterfaces as Je}from"node:os";import{spawn as se,spawnSync as T}from"node:child_process";import{setTimeout as w}from"node:timers/promises";import{EXIT_CODE as ae}from"./EXIT_CODE-D_XCixv8.mjs";import{a as h}from"./output-format-B4eQHi5y.mjs";import{spawnShellCompat as ce,defaultSpawner as Xe}from"./createRecordingSpawner-Ch7zuQQE.mjs";import{isLunoraError as Qe}from"@lunora/errors";import{s as V}from"./index-oHZBGBwB.mjs";import{createInterface as Ze}from"node:readline";const er=12e4,_=250,rr=1e3,tr="LUNORA_DEV_READY_TIMEOUT_MS",nr=e=>{if(e!==void 0)return e;const r=Number(process.env[tr]??"");return Number.isFinite(r)&&r>0?r:er},or=async(e,r)=>{try{const n=AbortSignal.timeout(rr);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?n:AbortSignal.any([r,n])})).body?.cancel(),!0}catch{return!1}},le=async(e,r,n)=>{const t=Date.now()+n.timeoutMs;for(;n.signal?.aborted!==!0;){const o=r(N(e));if(o!==void 0)return o;if(Date.now()>=t)return;try{await w(n.intervalMs??500,void 0,{signal:n.signal})}catch{return}}},W=(e,r)=>{Ze({crlfDelay:Number.POSITIVE_INFINITY,input:e}).on("line",r)},ir=5e3,de=(e,r,n,t)=>{if(e.length===0)return;const o=Ne(e);if(o){t[o.level](`[lunora] ${o.text}`);return}const i=`[${r}] ${e}`;n==="stderr"?t.warn(i):t.info(i)},sr=(e,r,n=process.platform,t=T)=>{try{if(r==="SIGKILL"&&n==="win32"&&e.pid!==void 0){t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"});return}e.kill(r)}catch{}},ue=(e,r,n)=>{const t=e.direct===!0?{args:[...e.args],command:e.command,shell:!1}:ce(e.command,e.args),o=se(t.command,t.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:t.shell,stdio:[e.direct===!0?"ignore":"inherit","pipe","pipe"]});return W(o.stdout,i=>{r(i,"stdout")}),W(o.stderr,i=>{r(i,"stderr")}),{exited:new Promise(i=>{o.on("error",s=>{n?.(s),i(1)}),o.on("exit",(s,a)=>{i(s??(a?1:0))})}),kill:i=>{sr(o,i)}}},pt=(e,r)=>ue(e,(n,t)=>{de(n.trimEnd(),e.tag,t,r)},n=>{r.error(`[${e.tag}] failed to start: ${n.message}`)}),mt=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Re(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(t.length!==0)return Ce({containers:t,onLine:o=>{const i=`[container:${o.name}] ${o.text}`;o.level==="error"?r.warn(i):r.info(i)},onUnavailable:o=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},wt=async e=>{e.readyProbe?.abort(),await e.tunnel?.close(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.(),e.serviceConfigCleanup?.()}catch{}},ht=async e=>await new Promise(r=>{const n={},t=s=>{e.info(`received ${s} — shutting down`),n.sigint&&process.off("SIGINT",n.sigint),n.sigterm&&process.off("SIGTERM",n.sigterm),r(0)},o=()=>{t("SIGINT")},i=()=>{t("SIGTERM")};n.sigint=o,n.sigterm=i,process.on("SIGINT",o),process.on("SIGTERM",i)}),St=async(e,r,n)=>{let t=0,o;const i=l=>{e.kill(l),r?.kill(l)},s=()=>{t+=1,t===1?(n.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),i("SIGTERM"),o=setTimeout(()=>{i("SIGKILL")},ir),o.unref()):i("SIGKILL")},a=()=>{i("SIGTERM")};process.on("SIGINT",s),process.on("SIGTERM",a);const c=await Promise.race([e.exited.then(l=>({code:l,who:"worker"})),...r===void 0?[]:[r.exited.then(l=>({code:l,who:"sidecar"}))]]);return r!==void 0&&(c.who==="sidecar"?(n.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),o&&clearTimeout(o),process.off("SIGINT",s),process.off("SIGTERM",a),c.code},E="2026.9.3",ar="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/",cr=/version (\S+)/u,B=/https:\/\/[\da-z-]+\.trycloudflare\.com/u,lr="1s",dr=5e3,K=async(e,r)=>await Promise.race([e.then(()=>!0),w(r,!1,{ref:!1})]),ur=6e4,fr='Vite answers 403 for hosts it does not know — add `server: { allowedHosts: [".trycloudflare.com"] }` to vite.config if the URL is blocked.',vr=async e=>{const r=`Install or update it: ${ar} (macOS: \`brew install cloudflared\`).`;let n;try{const o=await e({args:["--version"],captureStdoutSilently:!0,command:"cloudflared"});if(o.code!==0)return{message:`\`cloudflared --version\` exited ${String(o.code)}. ${r}`,ok:!1};n=o.stdout??""}catch(o){return Qe(o)&&o.code==="LOCAL_DEPENDENCY_MISSING"?{message:`--tunnel needs \`cloudflared\` ${E} or newer, and it is not on your PATH. ${r}`,ok:!1}:{message:`\`cloudflared --version\` could not run: ${o instanceof Error?o.message:String(o)}. ${r}`,ok:!1}}const t=V.coerce(cr.exec(n)?.[1])?.version;return t===void 0?{ok:!0,version:void 0}:V.gte(t,E)?{ok:!0,version:t}:{message:`--tunnel needs \`cloudflared\` ${E} or newer (protected quick tunnels); found ${t}. ${r}`,ok:!1}},gr=e=>{const r=[],n=[];for(const t of e??[]){const o=t.split(",").map(i=>i.trim()).filter(i=>i.length>0);o.length>0&&(n.push(...o.filter(i=>!i.includes("@"))),r.push(o.join(",")))}return{entries:r,invalid:n}},pr=(e,r)=>["tunnel","--url",e,"--output","json","--grace-period",lr,...r.flatMap(n=>["--allowed-mail",n])],mr=e=>{let r;try{r=JSON.parse(e)}catch{r=void 0}if(typeof r=="object"&&r!==null){const n=r,t=typeof n.message=="string"?n.message:"";return{level:typeof n.level=="string"?n.level:void 0,text:t,url:B.exec(t)?.[0]}}return{level:void 0,text:e,url:B.exec(e)?.[0]}},wr=e=>{e.warn(" ⚠ PUBLIC TUNNEL: anyone with the tunnel URL can reach this dev server — there is no sign-in in front of it."),e.warn(" Protect it with a one-time-PIN email allow-list: lunora dev --tunnel --allow-mail you@example.com"),e.warn(" (repeat --allow-mail, pass a comma-separated list, or allow a whole domain with '*@example.com')")},hr=async(e,r,n,{intervalMs:t,timeoutMs:o=ur}={})=>{const i=await le(e,s=>s?.mode==="vite"?{origin:s.url,ownerPid:s.pid}:void 0,{intervalMs:t,signal:n,timeoutMs:o});return i===void 0&&!n.aborted&&r.warn(`--tunnel: the Vite dev server did not report its URL within ${String(o/1e3)}s — continuing without a tunnel.`),i},Sr=e=>{const{allowMail:r,cwd:n,logger:t}=e,o=r.length===0,i=new AbortController,{signal:s}=i,a=()=>s.aborted,c=e.closeTimeoutMs??dr;let l;const d=()=>{i.abort()};process.once("SIGINT",d),process.once("SIGTERM",d);const v=(async()=>{const u=await vr(e.spawner??Xe);if(!u.ok){t.error(u.message),t.warn("continuing without a tunnel.");return}u.version===void 0&&t.warn(`could not read the cloudflared version — --tunnel needs ${E} or newer; trying anyway.`);const g=e.origin.kind==="fixed"?{origin:e.origin.origin,ownerPid:process.pid}:await hr(n,t,s);if(g===void 0||s.aborted)return;o&&wr(t),t.info(`starting a Cloudflare quick tunnel to ${g.origin}${o?"":" (email one-time-PIN protected)"}…`);let S;const U={failedToStart:!1},Le=k=>{if(k.length===0)return;const p=mr(k);if(p.url!==void 0&&S===void 0){S=p.url,t.success(` ➜ Tunnel: ${p.url}${o?" (PUBLIC)":""}`),o||t.info(` Allowed: ${r.join(", ")} — visitors confirm with a one-time PIN; a session lasts up to 4 hours`),e.origin.kind==="vite"&&t.info(` ${fr}`),b(n,{tunnelUrl:p.url},{expectedPid:g.ownerPid});return}p.level==="error"||p.level==="fatal"?t.warn(`[cloudflared] ${p.text}`):t.debug?.(`[cloudflared] ${p.text}`)},P=(e.startChild??ue)({args:pr(g.origin,r),command:"cloudflared",direct:!0},Le,k=>{U.failedToStart=!0,t.error(`could not start cloudflared (${k.message}) — continuing without a tunnel.`)});l=P;const G=()=>{P.kill("SIGTERM")};s.addEventListener("abort",G,{once:!0});const F=await P.exited;s.removeEventListener("abort",G),l=void 0,S!==void 0&&b(n,{tunnelUrl:void 0},{expectedPid:g.ownerPid}),!(a()||U.failedToStart)&&t.warn(S===void 0?`cloudflared exited (${String(F)}) before a tunnel URL was assigned — continuing without a tunnel.`:`cloudflared exited (${String(F)}) — the tunnel is closed; the dev server keeps running.`)})().catch(u=>{t.error(`--tunnel failed (${u instanceof Error?u.message:String(u)}) — continuing without a tunnel.`)});return{close:async()=>{if(process.off("SIGINT",d),process.off("SIGTERM",d),i.abort(),await K(v,c))return;const u=l;u!==void 0&&(t.warn(`cloudflared did not exit within ${String(c/1e3)}s of SIGTERM — force-killing it.`),u.kill("SIGKILL"),!await K(u.exited,c)&&t.error(`could not confirm that cloudflared stopped — ${o?"the PUBLIC tunnel":"the tunnel"} may still be reachable. Stop the \`cloudflared\` process manually.`))}}},kt=e=>{const{cwd:r,logger:n,plan:t,tunnel:o}=e;if(o!==void 0)return Sr({allowMail:o.allowMail,cwd:r,logger:n,origin:t.flavor==="wrangler"?{kind:"fixed",origin:t.workerOrigin}:{kind:"vite"},spawner:o.spawner,startChild:o.startChild})},kr=(e,r)=>{const n=["dev"];if(e.apiSpec!==void 0&&n.push("--api-spec",e.apiSpec),e.port!==void 0&&n.push("--port",String(e.port)),e.workerPort!==void 0&&n.push("--worker-port",String(e.workerPort)),e.inspectorPort!==void 0&&n.push("--inspector-port",String(e.inspectorPort)),e.emitBindings!==void 0&&n.push("--emit-bindings",e.emitBindings),e.codegen===!1&&n.push("--no-codegen"),e.studio===!1&&n.push("--no-studio"),e.worker===!1&&n.push("--no-worker"),e.target!==void 0&&n.push("--target",e.target),e.tunnel===!0){n.push("--tunnel");for(const t of gr(e.allowMail).entries)n.push("--allow-mail",t)}return r&&n.push("--remote"),e.local===!0&&n.push("--local"),n},Ir=1e4,Er=100,yr=40,I=256*1024,Lr=new Set(["nuxt","sveltekit"]),Tr=["@lunora/rspack","@lunora/vite"],M=e=>{if(Lr.has(ee(e).framework))return"framework-worker";const r=Ae(e);return Tr.some(n=>r.has(n))?"vite":"wrangler"},fe=e=>{const r=A(e),n=Ue(e)?.scripts,t=typeof n=="object"&&n!==null?n.dev:void 0;if(typeof t!="string"||t.trim()===""||t.includes("lunora")){const o=re(r,"vite",["dev"]);return{args:o.args,command:o.command}}return{args:["run","dev"],command:r}},Pr=e=>{Te(_e(e.logPath),{recursive:!0});const r=J(e.logPath,"w",384);let n;const t=ce(e.command,e.args);try{n=se(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{X(r)}return n.unref(),{exited:new Promise(o=>{n.on("error",()=>{o(1)}),n.on("exit",(i,s)=>{o(i??(s?1:0))})}),pid:n.pid}},br=e=>{try{const{size:r}=Pe(e);if(r<=I)return Q(e,"utf8");const n=J(e,"r");try{const t=Buffer.alloc(I),o=be(n,t,0,I,r-I),i=t.toString("utf8",0,o);return i.slice(i.indexOf(`
2
+ `)+1)}finally{X(n)}}catch{return}},ve=(e,r)=>{const n=br(e);if(n===void 0)return[];const t=n.split(`
3
+ `);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},ge=(e,r)=>r?.logFile??C(e,Fe),pe=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},_r=(e,r)=>{He(r,n=>{e.warn(n)})},$r=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),pe(e)},Rr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),r.tunnelUrl!==void 0&&e.info(` Tunnel: ${r.tunnelUrl}`),pe(e)},Cr=3e4,Nr=async(e,r,n,t)=>{const o=await le(e,i=>i?.tunnelUrl,{intervalMs:n,timeoutMs:t});o===void 0?r.warn(" Tunnel: no URL yet — `lunora dev status` shows it once cloudflared reports one; `lunora dev logs` says why if it does not."):r.success(` Tunnel: ${o}`)},Or=async e=>{const{child:r,cwd:n,deadline:t,pollIntervalMs:o,probe:i}=e,s=r.exited.then(a=>({exitCode:a}));for(;Date.now()<t;){const a=N(n);if(a!==void 0&&a.pid!==process.pid&&await i(a.url))return{state:a,status:"ready"};const c=await Promise.race([s,w(o)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},Dr=async e=>{const{cwd:r,logger:n}=e,t=ge(r,void 0),o=nr(e.readyTimeoutMs),i=(e.spawnDetached??Pr)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[Me]:"1",[xe]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),s=await Or({child:i,cwd:r,deadline:Date.now()+o,pollIntervalMs:e.pollIntervalMs??_,probe:e.probe??or});if(s.status==="ready")return Rr(n,s.state),e.tunnel===!0&&s.state.tunnelUrl===void 0&&await Nr(r,n,e.pollIntervalMs??_,e.tunnelUrlTimeoutMs??Cr),{code:0};if(s.status==="exited"){n.error(`dev server exited before becoming ready (exit code ${String(s.exitCode)}). Last output:`);for(const c of ve(t,yr))n.error(` ${c}`);return y(r,i.pid??process.pid),{code:s.exitCode===0?1:s.exitCode}}i.pid!==void 0&&D(r)?.pid===process.pid&&b(r,{logFile:t,pid:i.pid});const a=i.pid===void 0?"":` (pid ${String(i.pid)})`;return n.warn(`dev server did not confirm ready within ${String(Math.round(o/1e3))}s — it may still be compiling${a}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:ae.UNAVAILABLE}},me=e=>e.codegen!==!1&&!je(process.env[te]),we=e=>{const r={...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[te]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},It=async e=>{const{cwd:r,jsonLogs:n,logger:t,options:o,remote:i}=e,s=e.run??Dr,a=M(r),c=a==="vite"&&O(o.target??Z(r))?"wrangler":a,l=c==="wrangler"?`http://localhost:${String(o.workerPort??8787)}`:"http://localhost:5173",d=Oe(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:l});if(!d.ok)return d.existing!==void 0&&$r(t,d.existing),{code:0};const f={[De]:String(process.pid)};_r(t,r);try{return c==="vite"&&o.tunnel!==!0?await s({command:fe(r),cwd:r,env:{...we({...o,remote:i}).env,...f},json:n,logger:t}):await s({command:{args:[process.argv[1]??"lunora",...kr(o,i)],command:process.execPath},cwd:r,env:f,json:n,logger:t,tunnel:o.tunnel===!0})}finally{y(r,process.pid)}},Ar=e=>{try{const r=T("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),n=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(n)&&n>0?n:void 0}catch{return}},xr=(e,r,n=process.platform,t=T)=>{if(n==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(Ar(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Mr=(e,r)=>(r.json?h({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),Ur=async e=>{const{cwd:r,logger:n}=e,t=D(r),o=e.alive??(f=>f===t?.pid&&Ge(t)),i=e.signal??((f,v)=>{process.kill(f,v)}),s=e.pollIntervalMs??_,a=e.stopGraceMs??Ir,c=e.platform??process.platform,l=e.spawnSyncImpl??T;if(t===void 0||!o(t.pid))return t!==void 0&&y(r,t.pid),e.json?h({running:!1,stopped:!1}):n.info("No dev server running."),{code:0};try{i(t.pid,"SIGTERM")}catch{}const d=Date.now()+a;for(;o(t.pid)&&Date.now()<d;)await w(s);return o(t.pid)&&(xr(t,i,c,l),await w(s),o(t.pid))?Mr(t,e):(y(r,t.pid),e.json?h({pid:t.pid,stopped:!0}):n.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},Gr=e=>{const{cwd:r,logger:n}=e,t=N(r);if(t===void 0)return e.json?h({running:!1}):n.info("No dev server running."),{code:0};const o=e.now??Date.now,i=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),s=Number.isFinite(i)?Math.max(0,Math.round((o()-i)/1e3)):void 0;if(e.json)return h({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:j(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,tunnelUrl:t.tunnelUrl,uptimeSeconds:s,url:t.url}),{code:0};const a=[`pid ${String(t.pid)}`,...s===void 0?[]:[`uptime ${String(s)}s`],t.background===!0?"background":"foreground",j(t)?"ready":"starting"];return n.success(`Dev server running at ${t.url} (${a.join(", ")})`),t.studioUrl!==void 0&&n.info(` Studio: ${t.studioUrl}`),t.tunnelUrl!==void 0&&n.info(` Tunnel: ${t.tunnelUrl}`),t.logFile!==void 0&&n.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},Fr=e=>{const{cwd:r,logger:n}=e,t=D(r),o=ge(r,t);if(!q(o))return n.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const i=ve(o,e.lines??Er);return i.length>0&&process.stdout.write(`${i.join(`
4
+ `)}
5
+ `),{code:0}},Et=e=>{const{cwd:r,json:n,lines:t,logger:o,subcommand:i}=e;if(i==="stop")return Ur({cwd:r,json:n,logger:o});if(i==="status")return Gr({cwd:r,json:n,logger:o});if(i==="logs")return Fr({cwd:r,lines:t,logger:o});if(i!==void 0)return o.error(`dev: unknown subcommand "${i}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:ae.USAGE}},yt=(e,r,n)=>O(e)?(r!=="wrangler"&&n.info(`target ${e} runs its own dev server, so lunora dev serves the worker on it — start the frontend's dev server separately`),"wrangler"):r,Lt=async e=>{const{logger:r}=e,n=await(e.start??We)({log:(i,{stream:s,tag:a})=>{de(i,a,s,r)},port:e.port,projectRoot:e.projectRoot});let t=()=>{};const o=new Promise(i=>{t=i});return{exited:Promise.race([o,n.exited]),kill:()=>{n.stop().then(()=>0,()=>1).then(t).catch(()=>{})}}},jr=e=>{const{cwd:r,driver:n,options:t,studioPort:o,workerPort:i}=e,{projectConfig:s,toolchain:a}=n;if(s===void 0||a===void 0)throw new Error(`deploy target "${n.id}" runs its own dev server but ships no config projection or toolchain for it`);if(t.remote===!0)throw new Error(`--remote proxies bindings to Cloudflare; ${n.name} has no remote bindings to proxy to`);t.inspectorPort!==void 0&&t.logger.warn(`--inspector-port is a wrangler dev flag; ${n.name} dev has no inspector to pin`);const{command:c,commit:l,projection:d}=Ve(n,r,"dev",v=>a.dev({configPath:v,extraArgs:["--port",String(i)]}));l(),d!==void 0&&d.dropped.length>0&&t.logger.info(`${n.name} ignores these wrangler keys, so its dev server runs without them: ${d.dropped.join(", ")}`);const f=ne(A(r),c);return{flavor:"wrangler",ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:!1,withheld:[]},runsCodegenWatch:me(t),celldSession:!0,studioEnabled:t.studio!==!1,studioPort:o,workerEnabled:t.worker!==!1,workerOrigin:`http://localhost:${String(i)}`,workerPort:i,wrangler:{args:f.args,command:f.command,cwd:r,tag:c.tool}}},Vr=64,he="127.0.0.1",Wr=65535,Br=(e,r=he)=>new Promise(n=>{const t=qe();t.once("error",()=>{n(!1)}),t.once("listening",()=>{t.close(()=>{n(!0)})}),t.listen(e,r)}),Kr=async(e,r=he,n=Vr)=>{for(let t=e;t<e+n&&t<=Wr;t+=1)if(await Br(t,r))return t;return e},Se=(e=Je)=>Object.values(e()).some(r=>r?.some(n=>n.internal&&n.address==="::1")),$="wrangler.dev.jsonc",R=6173,m=8787,H=5173,ke=()=>{},Hr=(e,r)=>{if(!e.remote&&e.local===!0)return{args:[],plan:{bindings:[],cleanup:ke,enabled:!1,withheld:[]}};const t=(e.materializeDev??ze)({projectRoot:r,remote:e.remote===!0}),i={bindings:t.remoteBindings.map(s=>`${s.binding} (${s.kind})`),cleanup:t.cleanup,enabled:e.remote===!0,reason:t.reason,withheld:t.withheld};return{args:t.configPath===void 0?[]:["--config",t.configPath],plan:i}},Ie=(e,r)=>{const n=[...new Set($e(r).services.map(s=>s.wranglerPath))],{cleanup:t,configPaths:o,withheld:i}=(e.materializeServiceConfigs??Ye)(n,{projectRoot:r});return{args:o.flatMap(s=>["--config",s]),cleanup:t,withheld:i}},zr=(e,r,n)=>{const t=L(e);return r.length===0||t===void 0?[]:[...n.length>0?[]:["--config",t],...r]},Ee=e=>e.local===!0?["--local"]:[],z=e=>x(e).parsed?.dev?.ip,ye=(e,r,n)=>{if(n!==void 0){const o=C(e,n);if(q(o)&&z(o)!==void 0)return[]}const t=L(e);return t!==void 0&&z(t)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},Yr=new Set(["127.0.0.1","::1","[::1]","localhost"]),qr=(e,r)=>{let n;try{n=Q(C(e,ie),"utf8")}catch{return[]}const t=[];for(const o of Ke(n)){let i;try{i=new URL(o.value)}catch{continue}Yr.has(i.hostname)&&i.port===String(r)&&t.push(o.key)}return t},Y=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const n=L(r);if(n!==void 0){const{parsed:i}=x(n);if(typeof i?.dev?.port=="number")return i.dev.port}const t=await(e.findFreePort??Kr)(m);if(t===m)return t;const o=qr(r,m);if(o.length>0)throw new Error(`port ${String(m)} is in use, but ${ie} pins the worker origin to it (${o.join(", ")}). Serving on ${String(t)} would leave those URLs pointing at nothing. Stop whatever holds ${String(m)}, or run \`lunora dev --worker-port ${String(t)}\` and update those values to match.`);return t},Jr=(e,r)=>{if(e.inspectorPort!==void 0)return e.inspectorPort;const n=L(r);if(n===void 0)return;const{parsed:t}=x(n),o=t?.dev?.inspector_port;return typeof o=="number"?o:void 0},Xr=(e,r,n)=>{const t=ye(r,e.hasIpv6Loopback??Se,$),o=oe(e.target??Z(r));if(o.toolchain===void 0)throw new Error(`deploy target "${o.id}" has no dev server to run the worker sidecar`);const i=Ie(e,r),s=o.toolchain.dev({configPath:$,extraArgs:[...t,...Ee(e),"--var","WORKER_ENV:development",...i.args]}),a=ne(n,s);return{cleanup:i.cleanup,sidecar:{args:a.args,command:a.command,cwd:r,tag:"worker"}}},Qr=(e,r)=>{e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${r} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),e.inspectorPort!==void 0&&e.logger.warn(r==="framework-worker"?`--inspector-port does not apply to the ${r} flavor: pin \`dev.inspector_port\` in ${$} — that is the config the worker sidecar runs.`:`--inspector-port does not apply to the ${r} flavor: Vite owns the worker. Pin it in vite.config — \`lunora({ cloudflare: { inspectorPort: ${String(e.inspectorPort)} } })\`.`),e.local===!0&&r==="vite"&&e.logger.warn("--local does not apply to the vite flavor: Vite owns the worker. Turn remote bindings off in vite.config — `lunora({ cloudflare: { remoteBindings: false } })`.")},Zr=e=>{const r=e.cwd??process.cwd(),n=A(r),t=e.flavor??M(r);if(t==="vite"||t==="framework-worker"){const v=fe(r),u=t==="framework-worker"?Xr(e,r,n):void 0,g=u?.sidecar;return Qr(e,t),{runsCodegenWatch:!1,flavor:t,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:ke,enabled:e.remote===!0,withheld:[]},...u?{serviceConfigCleanup:u.cleanup}:{},...g?{sidecar:g}:{},studioEnabled:!1,studioPort:e.port??R,workerEnabled:!0,workerOrigin:`http://localhost:${String(H)}`,workerPort:H,wrangler:{args:v.args,command:v.command,cwd:r,...we(e),tag:"vite"}}}const o=ee(r),i=o.framework==="none"?void 0:`this project uses ${o.framework} — the worker runs inside Vite there. run \`${Be(n,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,s=e.workerPort??m,a=Hr(e,r),c=ye(r,e.hasIpv6Loopback??Se),l=e.inspectorPort===void 0?[]:["--inspector-port",String(e.inspectorPort)],d=Ie(e,r),f=re(n,"wrangler",["dev","--port",String(s),...l,...c,...Ee(e),"--var","WORKER_ENV:development",...a.args,...zr(r,d.args,a.args)]);return{runsCodegenWatch:me(e),flavor:t,frameworkHint:i,ipv4LoopbackForced:c.length>0,remote:{...a.plan,withheld:[...a.plan.withheld,...d.withheld]},serviceConfigCleanup:d.cleanup,studioEnabled:e.studio!==!1,studioPort:e.port??R,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(s)}`,workerPort:s,wrangler:{args:f.args,command:f.command,cwd:r,tag:"wrangler"}}},Tt=async e=>{const r=e.cwd??process.cwd();if(e.target!==void 0&&O(e.target))return jr({cwd:r,driver:oe(e.target),options:e,studioPort:e.port??R,workerPort:await Y(e,r)});const n=e.flavor??M(r),t=n==="wrangler"?await Y(e,r):e.workerPort,o=n==="wrangler"?Jr(e,r):e.inspectorPort;return Zr({...e,cwd:r,flavor:n,inspectorPort:o,workerPort:t})};export{_ as P,Et as a,$r as b,wr as c,or as d,M as e,yt as f,Tt as g,_r as h,kt as i,pt as j,St as k,me as l,Lt as m,gr as n,mt as o,Zr as p,Jr as q,nr as r,It as s,wt as t,Y as u,ht as w};
@@ -0,0 +1 @@
1
+ import{g as r,p as a,q as s,u as l}from"./plan-Dl57T11P.mjs";export{r as buildDevPlan,a as planDevCommand,s as resolveInspectorPort,l as resolveWorkerPort};
@@ -0,0 +1,4 @@
1
+ import{errorAdvisoryNames as a}from"@lunora/codegen";const i=e=>e.strictAdvisories??(process.env.CI!==void 0&&process.env.CI!==""),v=(e,s)=>{const o=e.filter(t=>t.level==="ERROR");return{errorAdvisories:o,names:a(e),shouldBlock:o.length>0&&s}},p=(e,s)=>{if(e.length===0)return{errors:[],warnings:[]};const o=e.map(r=>` [${r.level.toUpperCase()}] ${r.name} — ${r.message}
2
+ ↳ ${r.remediation}`),t=e.filter(r=>r.level==="error").map(r=>r.message),n=e.filter(r=>r.level!=="error").map(r=>r.message),l=`${String(e.length)} platform ${e.length===1?"diagnostic":"diagnostics"}:
3
+ ${o.join(`
4
+ `)}`;return t.length===0?(s.warn(l),{errors:[],warnings:n}):(s.error(l),{errors:t,warnings:n})};export{p as a,v as e,i as r};
@@ -0,0 +1 @@
1
+ class e extends Error{constructor(){super("cancelled"),this.name="PromptCancelledError"}}export{e as P};
@@ -0,0 +1,2 @@
1
+ import{resolveHint as a,isLunoraError as r,flattenHint as c}from"@lunora/errors";import{VisulimaError as d,renderError as m}from"@visulima/error";import{exitCodeForError as h}from"./EXIT_CODE-D_XCixv8.mjs";const f={filterStacktrace:()=>!1,hideErrorCodeView:!0},g=(n,i={})=>{const e=n instanceof Error?n.message:String(n),o=a(r(n)?{code:n.code,hint:n.hint,message:e}:e),t=o===void 0?[]:c(o).split(`
2
+ `);r(n)&&(t.length>0&&t.push(""),t.push(`\`${n.code}\` — exits ${String(h(n))}. Run \`lunora docs exit-codes\` for the table.`));const s=new d({hint:t.length===0?void 0:t,message:i.reason===void 0?e:`${i.reason}: ${e}`,name:n instanceof Error&&n.name.length>0?n.name:"Error"});return s.stack="",m(s,f)};export{g as r};
@@ -0,0 +1,5 @@
1
+ import{existsSync as p,readFileSync as g,writeFileSync as k,mkdtempSync as F,rmSync as w}from"node:fs";import{tmpdir as G}from"node:os";import{LunoraError as h}from"@lunora/errors";import{join as l}from"@visulima/path";import{downloadTemplate as W}from"giget";import{r as y}from"./cli-manifest-CRet0egA.mjs";import{DEV_VARS_FILE as z,parseDevVariableEntries as H,writeDevVariablesFileAtomically as J}from"@lunora/config";import{modify as j,applyEdits as N,parse as K}from"jsonc-parser";import{b as q}from"./tui-prompts-B3YwUhGw.mjs";import Y from"./parseManifest-CwPTKdtS.mjs";const Z="alpha",T="main",X=new Set(["alpha","beta","next"]),Q=/^[\w./@-]+$/,ee=e=>!e.includes("..")&&Q.test(e),O=e=>{if(e==="0.0.0")return Z;const t=e.split("+")[0]??e,n=t.indexOf("-");if(n!==-1){const[s]=t.slice(n+1).split(".");if(s!==void 0&&X.has(s))return s}return T},D=e=>{if(e!==void 0&&e.length>0){if(!ee(e))throw new h("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return O(y())},I="anolilab/lunora",L=/^[0-9a-f]{40}$/iu,B=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,te=new RegExp(String.raw`^v?${B}$`,"u"),ne=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${B}$`,"u"),se=e=>L.test(e)||te.test(e)||ne.test(e),re=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},oe=async(e,t=I)=>{try{const n=await fetch(`https://api.github.com/repos/${t}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...re()},signal:AbortSignal.timeout(1e4)});if(!n.ok)return;const s=await n.json();return typeof s.sha=="string"&&L.test(s.sha)?s.sha:void 0}catch{return}},ie=async(e,t,n)=>{if(se(t))return t;const s=await oe(t,e);return s===void 0?(n.warn(`could not pin ${e}#${t} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),t):(n.info(`pinned ${e}#${t} → ${s}`),s)},ae=async(e,t)=>ie(I,D(e),t),Me=(e=y())=>`@lunora/cli@${e}`,ce="latest",P=(e=y())=>{const t=O(e);return t===T?ce:t},de="https://registry.npmjs.org",ue=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:de;return t.endsWith("/")?t.slice(0,-1):t},fe=async(e,t)=>{try{const n=await fetch(`${ue()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return n.ok?(await n.json())["dist-tags"]?.[t]:void 0}catch{return}},le=async(e,t)=>{const n=new Map;return await Promise.all([...new Set(e)].map(async s=>{const o=await fe(s,t);o!==void 0&&n.set(s,o)})),n},pe=e=>{if(!e.startsWith("workspace:"))return!1;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"},he=(e,t,n)=>{if(!e.startsWith("workspace:"))return e;const s=e.slice(10);return s===""||s==="*"||s==="^"||s==="~"?(n===void 0?void 0:t?.get(n))??P():s},Ue=async e=>{const t=new Set;for(const n of e)for(const s of[n.deps,n.devDependencies])for(const[o,r]of Object.entries(s??{}))pe(r)&&t.add(o);return t.size===0?new Map:le([...t],P())},ge=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),me=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,Fe=e=>e.replaceAll(me,(t,n,s,o)=>`${n}lunorash/${s}${o??""}${n}`),$=(e,t,n,s="dependencies",o=!1,r)=>{const a=Object.entries(e);if(a.length===0)return[];const i=l(t,"package.json");if(!p(i))return n.warn(`package.json not found at ${i} — skipping dependency updates`),[];let d=g(i,"utf8");const c=JSON.parse(d),f=[];for(const[u,M]of a){if(o&&ge.has(u)){n.info(`dep provided by the lunorash umbrella, skipping: ${u}`);continue}if(c.dependencies?.[u]!==void 0||c.devDependencies?.[u]!==void 0){n.info(`dep already present: ${u}`);continue}const U=j(d,[s,u],he(M,r,u),{formattingOptions:{insertSpaces:!0,tabSize:4}});d=N(d,U),f.push(u)}return f.length>0&&(k(i,d,"utf8"),n.success(`added ${String(f.length)} ${s==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${f.join(", ")}`)),f},ye=(e,t,n)=>{if(e.length===0)return[];const s=l(t,z),o=p(s)?g(s,"utf8"):"",r=new Set(H(o).map(c=>c.key)),a=[],i=[],d=[];for(const c of e)c.secret&&i.push(c.name),!r.has(c.name)&&(c.description&&d.push(`# ${c.description}`),d.push(`${c.name}=${c.secret?"":c.value??""}`),a.push(c.name));if(a.length>0){const c=o===""||o.endsWith(`
2
+ `)?o:`${o}
3
+ `;J(s,`${c}${d.join(`
4
+ `)}
5
+ `),n.success(`scaffolded ${String(a.length)} env var(s) into .dev.vars: ${a.join(", ")}`)}return i.length>0&&n.info(`set secret value(s) locally in .dev.vars, then for production: ${i.map(c=>`wrangler secret put ${c}`).join("; ")}`),a},S=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"]),ve=["binding","name","queue","pattern"],E=e=>{if(!(typeof e!="object"||e===null))for(const t of ve){const n=e[t];if(typeof n=="string"&&n.length>0)return`${t}:${n}`}},we=(e,t,n,s)=>{const o=new Set(e.map(i=>JSON.stringify(i))),r=new Set(e.map(i=>E(i)).filter(i=>i!==void 0)),a=[];for(const i of t){if(o.has(JSON.stringify(i)))continue;const d=E(i);if(d!==void 0&&r.has(d)){s.warn(`${d.replace(":"," ")} already exists in ${n} — keeping the project's entry and skipping the registry item's. Reconcile by hand if the item needs different settings.`);continue}d!==void 0&&r.add(d),a.push(i)}return a},b=e=>Array.isArray(e),R=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),$e=(e,t,n,s)=>{const o={};for(const[r,a]of Object.entries(t)){if(!Object.hasOwn(e,r)){o[r]=a;continue}JSON.stringify(e[r])!==JSON.stringify(a)&&s.warn(`${r} already exists in ${n} — keeping the project's value and skipping the registry item's. Reconcile by hand if the item needs different settings.`)}return o},Se=(e,t)=>{let n=K(e);for(const s of t){if(typeof n!="object"||n===null)return;n=n[s]}return n},Ee=(e,t)=>{const n=e[0];return n!==void 0&&S.has(n)?!0:(t.warn(`skipping binding "${e.join(".")}" — only resource bindings (${[...S].join(", ")}) may be written, not exec/entrypoint keys`),!1)},m=Symbol("skip-binding"),be=(e,t,n)=>{const{value:s}=t,o=t.path.join("."),r=Se(e,t.path);if(b(s)){if(!b(r))return s;const a=we(r,s,o,n);return a.length===0?m:[...r,...a]}if(R(s)){if(!R(r))return s;const a=$e(r,s,o,n);return Object.keys(a).length===0?m:{...r,...a}}return s},Re=(e,t,n)=>{if(e.length===0)return[];const o=["wrangler.jsonc","wrangler.json"].map(i=>l(t,i)).find(i=>p(i));if(!o)return n.warn("wrangler.jsonc not found — skipping binding updates"),[];let r=g(o,"utf8");const a=[];for(const i of e){if(!Ee(i.path,n))continue;const d=be(r,i,n);if(d===m)continue;const c=j(r,[...i.path],d,{formattingOptions:{insertSpaces:!0,tabSize:4}});c.length!==0&&(r=N(r,c),a.push(i.path.join(".")))}return a.length>0&&(k(o,r,"utf8"),n.success(`applied ${String(a.length)} binding(s) to ${o}: ${a.join(", ")}`)),a},Ge=(e,t,n,s=!1,o)=>{const r=[],a=[];return e.deps&&r.push(...$(e.deps,t,n,"dependencies",s,o)),e.devDependencies&&r.push(...$(e.devDependencies,t,n,"devDependencies",s,o)),e.bindings&&a.push(...Re(e.bindings,t,n)),e.envVars&&ye(e.envVars,t,n),{bindings:a,deps:r}},v=e=>e.source!==void 0&&e.source.length>0||e.from!==void 0&&e.from.length>0,We=async(e,t)=>{const n=e.some(({manifest:c})=>Object.keys(c.deps??{}).length>0||Object.keys(c.devDependencies??{}).length>0),s=e.some(({manifest:c})=>(c.bindings??[]).length>0),o=v(t);if(!n&&!s&&!o||t.yes)return{ok:!0};const r=[];n&&r.push("add dependencies to package.json"),s&&r.push("write wrangler.jsonc bindings"),o&&r.push(`come from a custom registry source (${String(t.from??t.source)})`);const a=r.join(", ");return!process.stdin.isTTY&&t.confirm===void 0?(t.logger.error(`add: stdin is not a TTY and the requested items ${a} — re-run with --yes to confirm`),{ok:!1,reason:"non-interactive"}):await(t.confirm??q)(`The requested items ${a}. Continue?`)?{ok:!0}:(t.logger.info("add: aborted"),{ok:!1,reason:"declined"})},V="gh:anolilab/lunora/registry",_=/^[A-Za-z0-9][\w-]*$/u,_e=e=>{if(!_.test(e))throw new h("INTERNAL",`invalid registry item name "${e}" — names must match ${_.source} (letters, digits, "-", "_"; no path separators or "..")`)},Ae=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),ke=e=>v(e)&&e.from===void 0&&!e.allowUnsafeSource&&!Ae(e.source??""),ze=(e,t)=>ke(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,C=async(e,t,n)=>{const s=F(l(G(),`lunora-${t}-fetch-`)),o=l(s,t);n.info(`fetching ${e}`);try{const r=await W(e,{cwd:s,dir:o,force:!0,install:!1,silent:!0});return n.info(r.commit?`resolved ${r.source} @ ${r.commit}`:`resolved ${r.source}`),{cleanup:()=>{w(s,{force:!0,recursive:!0})},directory:o}}catch(r){throw w(s,{force:!0,recursive:!0}),r}},A=new WeakMap,x=async e=>{const t=A.get(e);if(t!==void 0)return t;const n=v(e)?Promise.resolve(D(e.ref)):ae(e.ref,e.logger);return A.set(e,n),n},je=async(e,t,n=V)=>{if(_e(e),t.from!==void 0){const o=l(t.from,e);if(!p(o))throw new h("INTERNAL",`registry item not found in local source: ${o}`);return{cleanup:()=>{},directory:o}}const s=t.source??n;return C(`${s}/${e}#${await x(t)}`,"item",t.logger)},He=async e=>{if(e.from!==void 0){if(!p(e.from))throw new h("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??V,{cleanup:n,directory:s}=await C(`${t}#${await x(e)}`,"registry",e.logger);return{cleanup:n,root:s}},Ne=(e,t)=>{const n=JSON.parse(g(l(e,"registry.json"),"utf8"));return Y(n,t)},Je=async(e,t)=>{const n=[],s=[],o=new Set,r=new Set,a=async i=>{if(o.has(i))return;if(r.has(i))throw new h("INTERNAL",`cyclic registry dependency detected at "${i}"`);r.add(i);const{cleanup:d,directory:c}=await je(i,t);s.push(d);const f=Ne(c,i);for(const u of f.requires??[])await a(u);r.delete(i),o.add(i),n.push({directory:c,manifest:f})};try{for(const i of e)await a(i)}catch(i){for(const d of s)d();throw i}return{cleanups:s,items:n}};export{ae as a,je as b,Ge as c,Fe as d,Je as e,Ue as f,We as g,He as h,v as i,he as j,Ne as k,le as l,ie as m,P as n,D as o,Me as r,ze as s};
@@ -0,0 +1 @@
1
+ import{readLinkedProject as n}from"@lunora/config";const v=({cwd:e,env:i,url:o})=>{if(o!==void 0&&o!=="")return o;const r=n(e);if(!(r===void 0||r.env!==i))return r.workerUrl},d=({cwd:e,prod:i,url:o})=>{if(o!==void 0&&o!=="")return o;if(!i)return;const r=n(e);if(!(r===void 0||r.env!==void 0&&r.env!=="production"))return r.workerUrl};export{d as a,v as r};
@@ -0,0 +1 @@
1
+ import"./EXIT_CODE-D_XCixv8.mjs";import"./resolve-BrsV4Qyc.mjs";import"./catalog-CahzmDLV.mjs";import{r as n,a as i,b as t}from"./commands-DgUDxkA8.mjs";export{n as runAddCommand,i as runBuildIndexCommand,t as runRegistryViewCommand};
@@ -0,0 +1,5 @@
1
+ import{randomUUID as x}from"node:crypto";import{createWriteStream as b}from"node:fs";import{unlink as E,rename as S}from"node:fs/promises";import{r as O}from"./admin-token-VdUnvnKW.mjs";import{r as T,a as $}from"./admin-url-DJB8P6Jh.mjs";import{EXIT_CODE as w,isRefusal as U,exitCodeForStatus as N}from"./EXIT_CODE-D_XCixv8.mjs";import{E as k}from"./shared-D-zCOmgY.mjs";const I=e=>{if(e===void 0)return;const r=e.split(",").map(t=>t.trim()).filter(t=>t.length>0);return r.length>0?r:void 0},y=async(e,r)=>{e.write(r)||await new Promise((t,a)=>{let d=o=>{};const n=()=>{e.removeListener("error",d),t()};d=o=>{e.removeListener("drain",n),a(o)},e.once("drain",n),e.once("error",d)})},P=async(e,r)=>{const t=e.getReader(),a=new TextDecoder;let d=0,n=0,o="",c=!1;try{for(;!c;){const i=await t.read();if(c=i.done,i.value===void 0)continue;d+=i.value.length,o+=a.decode(i.value,{stream:!0});let s=o.indexOf(`
2
+ `);for(;s!==-1;){n+=1;const l=`${o.slice(0,s)}
3
+ `;await y(r,l),o=o.slice(s+1),s=o.indexOf(`
4
+ `)}}return o.length>0&&(n+=1,await y(r,`${o}
5
+ `)),{bytes:d,rows:n}}finally{t.releaseLock()}},v=async(e,r)=>{if(r===void 0)return;const t=e;await new Promise(a=>{if(t.closed){a();return}t.once("close",()=>{a()}),t.destroy()});try{await E(r)}catch{}},A=async(e,r,t)=>{await new Promise((d,n)=>{e.end(o=>{const c=o??t();c===void 0?d():n(c)})});const a=t();if(a!==void 0)throw await v(e,r),a},_=async(e,r,t)=>{await A(e,r.stage,t);try{await S(r.stage,r.path)}catch(a){throw await v(e,r.stage),a}},p="export --format json needs a file destination (--out <file>) — with --out - the NDJSON stream already owns stdout.",D=e=>{const r=e.out===void 0||e.out==="-"?void 0:e.out;if(e.format==="json"&&r===void 0){e.logger.error(p);return}return{destination:r}},R=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{refused:w.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:w.USAGE};const{token:t}=O({cwd:e.cwd??process.cwd(),token:e.token,url:r});return t?{fetchImpl:e.fetchImpl??$,requestUrl:`${r}${k}`,tables:I(e.tables),token:t}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:w.AUTH})},H=async e=>{const r=D(e);if(r===void 0)return{bytes:0,code:w.USAGE,error:p,rows:0};const{destination:t}=r,a=R(e);if(U(a))return{bytes:0,code:a.refused,error:"export: could not resolve the worker URL and admin token",rows:0};const{fetchImpl:d,requestUrl:n,tables:o,token:c}=a;e.logger.info(`POST ${n} -> export${o?` (tables: ${o.join(",")})`:""}`);const i=await d(n,{body:JSON.stringify(o?{tables:o}:{}),headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},method:"POST"});if(!i.ok){const u=await i.text(),h=`export failed: HTTP ${String(i.status)}: ${u}`;return e.logger.error(h),{bytes:0,code:N(i.status),error:h,rows:0}}if(!i.body)return e.logger.error("export response carried no body"),{bytes:0,code:1,error:"export response carried no body",rows:0};const s=t===void 0?void 0:{path:t,stage:`${t}.${x()}.partial`},l=s===void 0?process.stdout:b(s.stage,{encoding:"utf8",mode:384});let g;s!==void 0&&l.on("error",u=>{g??=u});let f,m;try{({bytes:f,rows:m}=await P(i.body,l))}catch(u){throw await v(l,s?.stage),u}return s!==void 0&&(await _(l,s,()=>g),e.logger.success(`wrote ${String(m)} rows to ${s.path} (${String(f)} bytes)`)),{bytes:f,code:0,data:t===void 0?void 0:{bytes:f,out:t,rows:m,tables:o},rows:m}};export{H as runExportCommand};
@@ -0,0 +1,11 @@
1
+ import{existsSync as p,mkdirSync as _,writeFileSync as v,mkdtempSync as x,rmSync as F,readFileSync as U}from"node:fs";import{tmpdir as O}from"node:os";import{discoverMigrations as k,discoverSchema as N,readPackageDependencies as D}from"@lunora/codegen";import{isInteractive as P,promptSelect as G,promptText as j}from"@lunora/config";import{LunoraError as T}from"@lunora/errors";import{join as l}from"@visulima/path";import{Project as w}from"ts-morph";import{r as z,t as L}from"./admin-token-VdUnvnKW.mjs";import{r as q,a as H,n as B}from"./admin-url-DJB8P6Jh.mjs";import{isRefusal as W,exitCodeForStatus as J,EXIT_CODE as s}from"./EXIT_CODE-D_XCixv8.mjs";import{diffSnapshots as V,renderMigrationFile as X}from"./diffSnapshots-htqNZT8Q.mjs";import Z from"./schemaIrToSnapshot-BHuNOfgs.mjs";import{runExportCommand as K}from"./runExportCommand-slAq5BCF.mjs";import{r as Q}from"./import-BRM1hs7j.mjs";import{readAndLogBody as Y}from"../packem_chunks/runRpcCommand.mjs";const h="__lunora_reproject__",ee=e=>{if(!e.startsWith(h))return;const r=e.slice(h.length);return r===""?void 0:r},re=".snapshot.json",R=/[^\da-z]+/gu,M=(e,r)=>{let t=0,o=e.length;for(;t<o&&e[t]===r;)t+=1;for(;o>t&&e[o-1]===r;)o-=1;return e.slice(t,o)},te=e=>{const r=M(e.toLowerCase().replaceAll(R,"_"),"_");return r===""?"auto":r},oe=e=>{const r=(t,o=2)=>t.toString().padStart(o,"0");return`${String(e.getUTCFullYear())}${r(e.getUTCMonth()+1)}${r(e.getUTCDate())}${r(e.getUTCHours())}${r(e.getUTCMinutes())}${r(e.getUTCSeconds())}`},ne=e=>{if(p(e))try{const r=U(e,"utf8"),t=JSON.parse(r);if(t.version!==1)throw new T("INTERNAL",`unsupported snapshot version: ${t.version}`);return t}catch(r){const t=r instanceof Error?r.message:String(r);throw new T("INTERNAL",`failed to read ${e}: ${t}`,{cause:r})}},De=e=>{const r=e.cwd??process.cwd(),t=l(r,"lunora","schema.ts");if(!p(t)){const m=`schema not found: ${t} — run \`vis generate lunora-table --name=<name>\` to create one`;return e.logger.error(m),{code:s.NOT_FOUND,empty:!0,error:m,migrationFile:""}}const o=new w({skipAddingFilesFromTsConfig:!0}),a=N(o,t),c=Z(a),n=l(r,"lunora","migrations"),i=l(n,re);let d;try{d=ne(i)}catch(m){const S=m instanceof Error?m.message:String(m);return e.logger.error(S),{code:s.USAGE,empty:!0,error:S,migrationFile:""}}const u=V(d,c);if(u.empty)return e.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const f=(e.now??(()=>new Date))(),y=te(e.name??"auto"),$=`${oe(f)}_${y}.sql`,b=l(n,$);_(n,{recursive:!0});const C=X(y,u,f.toISOString());return v(b,C,"utf8"),v(i,`${JSON.stringify(c,void 0,4)}
2
+ `,"utf8"),e.logger.success(`wrote ${b}`),u.unsupported.length>0&&e.logger.warn(`${String(u.unsupported.length)} unsupported diff(s) — see the comment block in ${$} and write the SQL manually`),{code:0,empty:!1,migrationFile:b}},ae="migrations.ts",I=/^[A-Za-z_]\w*$/u,ie=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),A=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,se=e=>`import { defineMigration } from "${D(e)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,ce="__lunora_admin__:runMigration",de="__lunora_admin__:migrationStatus",le="/_lunora/migrate",ue=e=>M(e.trim().toLowerCase().replaceAll(R,"-"),"-"),me=e=>e.split("-").filter(r=>r.length>0).map((r,t)=>t===0?r:r.charAt(0).toUpperCase()+r.slice(1)).join(""),ge=e=>{const r=l(e,"lunora","schema.ts");if(!p(r))return[];try{const t=new w({skipAddingFilesFromTsConfig:!0});return N(t,r).tables.map(o=>o.name)}catch{return[]}},fe=async e=>e.length>0?G("Which table does this migration iterate?",e.map(r=>({label:r,value:r}))):j("Target table for the migration: "),he=async(e,r)=>{if(r.table!==void 0)return r.table;const t=r.promptTable??(P()?fe:void 0);if(t===void 0){r.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const a=(await t(ge(e)))?.trim();if(a===void 0||a===""){r.logger.error("no table selected — re-run with --table <table>");return}return a},Pe=async e=>{const r=e.cwd??process.cwd(),t=ue(e.name);if(t==="")return e.logger.error(`invalid migration name: "${e.name}" — must contain at least one alphanumeric character`),{code:s.USAGE,file:""};const o=me(t);if(!I.test(o)||ie.has(o))return e.logger.error(`invalid migration name: "${e.name}" derives the export \`${o}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:s.USAGE,file:""};const a=await he(r,e);if(a===void 0)return{code:s.USAGE,file:""};if(!I.test(a))return e.logger.error(`invalid table: "${a}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:s.USAGE,file:""};const c=l(r,"lunora"),n=l(c,ae);let i=p(n)?U(n,"utf8"):"";if(i.includes(`id: "${t}"`)||new RegExp(String.raw`\bexport const ${o}\b`,"u").test(i))return e.logger.error(`a migration with id "${t}" (export \`${o}\`) already exists in ${n}`),{code:s.CONFLICT,file:""};const d=se(r);i.trim()===""?i=`${d}
3
+ `:A.test(i)?i=i.replace(A,d):i=`${d}
4
+ ${i}`;const u=`export const ${o} = defineMigration({
5
+ id: "${t}",
6
+ table: "${a}",
7
+ up: (document) => document,
8
+ });`;return _(c,{recursive:!0}),v(n,`${i.trimEnd()}
9
+
10
+ ${u}
11
+ `,"utf8"),e.logger.success(`scaffolded migration "${t}" in ${n}`),{code:0,file:n}},pe=(e,r)=>{const t=new w({skipAddingFilesFromTsConfig:!0});return k(t,l(e,"lunora")).find(a=>a.id===r)?.table},be=(e,r)=>{const t=ee(r.id);if(t!==void 0)return t;if(r.id.startsWith(h)){r.logger.error(`"${r.id}" names no table — use ${h}<table>`);return}let o;try{o=pe(e,r.id)}catch(a){r.logger.error(a instanceof Error?a.message:String(a));return}if(o===void 0){r.logger.error(`migration "${r.id}" not found under lunora/ — declare it with defineMigration({ id: "${r.id}", ... })`);return}if(o===""){r.logger.error(`migration "${r.id}" must declare \`table\` as a static string literal`);return}return o},ve=e=>{const r=e.cwd??process.cwd();if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)"),{refused:s.USAGE};const t=be(r,e);if(t===void 0)return{refused:s.USAGE};const o=q(e.url,e.logger,e.cwd);if(o===void 0)return{refused:s.USAGE};const{token:a}=z({cwd:r,token:e.token,url:o});return a?(e.subcommand==="up"||e.subcommand==="down")&&L({prod:e.prod,url:o})&&!e.yes?(e.logger.error(`migrate ${e.subcommand} runs the migration against ${o}, which is not local. Re-run with --yes to confirm.`),{refused:s.USAGE}):{fetchImpl:e.fetchImpl??H,requestUrl:`${o}${le}`,table:t,token:a}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:s.AUTH})},we=e=>{if(e===null||typeof e!="object")return;const r=e,t=typeof r.failed=="number"&&r.failed>0?r.failed:0;if(t>0)return`${String(t)} shard(s) could not be reached — their rows were NOT migrated (see the per-shard errors above)`;if(r.status==="failed")return"the migration reported `failed` on at least one shard — see the per-shard results above"},ye=e=>{const r={id:e.id};return e.subcommand==="status"||(r.direction=e.subcommand,e.dryRun&&(r.dryRun=!0),e.batchSize!==void 0&&(r.batchSize=e.batchSize),e.maxBatches!==void 0&&(r.maxBatches=e.maxBatches)),r},Ge=async e=>{const r=ve(e);if(W(r))return{body:void 0,code:r.refused,requestUrl:""};const{fetchImpl:t,requestUrl:o,table:a,token:c}=r,n=e.subcommand==="status"?de:ce,i=ye(e);e.logger.info(`POST ${o} -> ${e.subcommand} ${e.id} (table "${a}")`);const d=await t(o,{body:JSON.stringify({args:i,functionPath:n,table:a}),headers:{authorization:`Bearer ${c}`,"content-type":"application/json"},method:"POST"}),u=await Y(d,e.logger),g=we(u);g!==void 0&&e.logger.error(`migrate ${e.subcommand} "${e.id}": ${g}`);const f=g===void 0?0:1;return{body:u,code:d.ok?f:J(d.status),requestUrl:o}},E=e=>e===void 0?void 0:B(e),je=async e=>{const{logger:r}=e,t=E(e.fromUrl??e.toUrl),o=E(e.toUrl??e.fromUrl);if(t===o){const n="source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database";return r.error(n),{bytes:0,code:s.USAGE,error:n,exported:0,imported:0}}const a=e.out===void 0?x(l(O(),"lunora-d1ps-")):void 0,c=e.out??l(a,"dump.ndjson");try{r.info(`Exporting .global() data from the D1 source (${t??"http://localhost:8787"}) …`);const n=await K({fetchImpl:e.fetchImpl,logger:r,out:c,prod:e.prod,tables:e.tables,token:e.fromToken,url:t});if(n.code!==0)return{bytes:n.bytes,code:n.code,exported:n.rows,imported:0,...n.error===void 0?{}:{error:n.error}};r.info(`Exported ${String(n.rows)} row(s) (${String(n.bytes)} bytes).`),r.info(`Importing into the Hyperdrive target (${o??"http://localhost:8787"}) …`);const i=await Q({batchSize:e.batchSize,fetchImpl:e.fetchImpl,file:c,logger:r,prod:e.prod,token:e.toToken,url:o,yes:e.yes});return i.code!==0?{bytes:n.bytes,code:i.code,exported:n.rows,imported:i.inserted,...i.error===void 0?{}:{error:i.error}}:(i.inserted===n.rows?r.info(`✓ Migrated ${String(n.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):r.warn(`Imported ${String(i.inserted)} of ${String(n.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{bytes:n.bytes,code:0,exported:n.rows,imported:i.inserted})}finally{a!==void 0&&F(a,{force:!0,recursive:!0})}};export{Pe as runMigrateCreateCommand,Ge as runMigrateDataCommand,De as runMigrateGenerateCommand,je as runMigrateToHyperdriveCommand};
@@ -0,0 +1 @@
1
+ import{buildSchemaSnapshot as b,isD1GlobalTable as d}from"@lunora/codegen";import{validatorKindToSqlType as p}from"./diffSnapshots-htqNZT8Q.mjs";const k=new Set(["any","null"]),f=(n,e)=>{const t=e.kindOf(n);return t!==void 0&&k.has(t)||e.nullableOf(n)?!0:t==="union"&&(e.membersOf(n)??[]).some(l=>f(l,e))},m=n=>n.kind==="optional"&&n.inner?m(n.inner):n.kind==="literal"&&n.literalValue==="null"?"null":n.kind,i=n=>n.kind==="optional"&&n.inner?i(n.inner):n,O=n=>f(n,{kindOf:m,membersOf:e=>i(e).members,nullableOf:e=>i(e).column?.notNull===!1}),N=n=>p(n.kind==="optional"&&n.inner?n.inner.kind:n.kind),T=(n,e)=>n.kind==="optional"||O(n)?!0:e===void 0?!1:e.nullable===!0,h=d,y=n=>{const e={},t=b(n,[]);for(const l of n.tables){if(!h(l))continue;const a={};for(const[o,c]of Object.entries(l.shape)){const s=t.tables[l.name]?.fields[o],r={nullable:T(c,s),sqlType:N(c)};a[o]=s===void 0?r:{...r,field:s}}const u={};for(const o of l.indexes)u[o.name]={fields:[...o.fields],name:o.name,unique:o.unique??!1};e[l.name]={columns:a,indexes:u,name:l.name}}return{tables:e,version:1}};export{y as default};
@@ -0,0 +1 @@
1
+ import{r as $,c as E}from"./cloudflare-credentials-BVmZnDZk.mjs";const v=5e3,m=(e,r,t)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${r}", "jurisdiction": "${t}" }`,y=async e=>{const{binding:r,jurisdiction:t,namespace:s}=e,a=`Artifacts namespace "${s}" (binding ${r})`,{accountId:c,token:i}=$(e.environment??process.env,e.accountId);if(i===void 0||c===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts read access) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${a} was not checked against the schema's "${t}".`,verdict:"unchecked"};let n;try{n=await E({accountId:c,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(v)},path:`/artifacts/namespaces/${encodeURIComponent(s)}`})}catch(l){return{message:`the jurisdiction of ${a} could not be read (${l instanceof Error?l.message:String(l)}).`,verdict:"unchecked"}}if(!n.ok&&n.status===404)return{fix:`Create it before the first repo: ${m(c,s,t)}.`,message:`${a} does not exist, and the first repo create() would make it unrestricted — the schema pins data to "${t}".`,verdict:"missing"};if(!n.ok)return{...n.status===401||n.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts read access on account ${c}.`}:{},message:`the jurisdiction of ${a} could not be read (HTTP ${String(n.status)}).`,verdict:"unchecked"};const{result:o}=n.body,d=typeof o=="object"&&o!==null&&"jurisdiction"in o?o.jurisdiction:void 0;return typeof d!="string"?{message:`the jurisdiction of ${a} could not be read (the response carried none).`,verdict:"unchecked"}:d===t?{message:`${a} is in the "${d}" jurisdiction, as the schema pins.`,verdict:"ok"}:{fix:`A namespace's jurisdiction cannot change: create one with ${m(c,"<name>",t)}, point the binding's "namespace" at it, and move the repos over.`,message:`${a} is in the "${d}" jurisdiction, but the schema pins data to "${t}".`,verdict:"mismatch"}},h=100,u=500,g=10,C=5e3,f="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",T=e=>e>=u?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(u)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=u-g?{fix:f,message:`the Cloudflare account has ${String(e)} of ${String(u)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=h-g&&e<=h?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(h)} (Paid: ${String(u)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(h)} Free, ${String(u)} Paid).`,verdict:"ok"},P=async(e={})=>{const{accountId:r,token:t}=$(e.environment??process.env,e.accountId);if(t===void 0||r===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const s=await E({accountId:r,apiToken:t,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(C)},path:"/workers/durable_objects/namespaces?per_page=1"}),a=s.ok?s.body.result_info:void 0,c=typeof a=="object"&&a!==null&&"total_count"in a?a.total_count:void 0;return typeof c!="number"?{message:`the account's Durable Object class count could not be read${s.ok?"":` (HTTP ${String(s.status)})`}.`,verdict:"unchecked"}:T(c)}catch(s){return{message:`the account's Durable Object class count could not be read (${s instanceof Error?s.message:String(s)}).`,verdict:"unchecked"}}},D=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},j=/already (?:exists|indexed)|duplicate/iu,p=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],k=async(e,r)=>{try{return await e(r)}catch(t){return{code:1,stderr:t instanceof Error?t.message:String(t)}}},x=async e=>{const{cwd:r,entries:t,exec:s,logger:a,spawner:c}=e,i=[];for(const n of t){const o=await k(c,{args:[...s.args,...p(n)],captureStderr:!0,command:s.command,cwd:r,stdoutToStderr:!0});if(o.code===0){i.push({entry:n,status:"created"});continue}const d=`${o.stderr??""}${o.stdout??""}`;if(j.test(d)){i.push({entry:n,status:"exists"});continue}i.push({entry:n,error:d.trim()||`exit code ${String(o.code)}`,status:"failed"}),a.warn(`could not create the Vectorize metadata index for "${n.property}" on "${n.index}" — filters on that property will match nothing until it exists. Run: wrangler ${p(n).join(" ")}`)}return i},S=e=>e.endsWith("S")?e.slice(0,-1):e,b=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(r=>r.length>0),_=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),A=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],I=new RegExp(`(?:${[..._,...A.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),O=e=>b(e).some(r=>r==="PUBLIC"||r==="PUBLISHABLE"),w=e=>{if(O(e))return!1;const r=b(e);if(r.some(s=>_.has(S(s))))return!0;const t=S(r.join("_"));return A.some(s=>t===s||t.endsWith(`_${s}`))||I.test(e)};export{P as a,y as b,p as c,x as e,w as i,D as m};
@@ -0,0 +1 @@
1
+ const a="/_lunora/admin/export",o="/_lunora/admin/import",_="/_lunora/admin/storage",n="/_lunora/admin/storage/url";export{a as E,o as I,_ as S,n as a};
@@ -0,0 +1 @@
1
+ import{s}from"./index-oHZBGBwB.mjs";import{s as n}from"./commands-DgUDxkA8.mjs";const c=[{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"}],r="auth",E=async t=>await t("Which auth provider?",c,{default:r})??r,O="mail",g=[{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 1.x + Vite",label:"Solid",value:"auth-ui-solid"},{description:"Solid 2.0 + Vite (@solidjs/web)",label:"Solid 2",value:"auth-ui-solid-v2"},{description:"Analog",label:"Angular",value:"auth-ui-angular"}],j="auth-ui-react",d=t=>Object.hasOwn(t,"react-native")||Object.hasOwn(t,"@lunora/react-native")||Object.hasOwn(t,"expo"),B="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.",h=t=>{if(!(t===void 0||s.validRange(t)===null))return s.minVersion(t)?.major},v=t=>Object.hasOwn(t,"@solidjs/web")||(h(t["solid-js"])??0)>=2,U=t=>{const e=a=>Object.hasOwn(t,a);if(!d(t)){if(v(t))return"auth-ui-solid-v2";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"}},L=t=>{const e=t.trim();if(e==="")return;const a=e.toLowerCase();return a==="auth-ui"||a==="auth-ui-"?{kind:"auth-ui"}:a==="auth"?{kind:"auth"}:a==="email"||a==="mail"?{kind:"email"}:{item:a,kind:"item"}},m=/[^a-z0-9]+/u,u=(t,e,a)=>{let i=t.toLowerCase().split(m).filter(Boolean).join("-").slice(0,a);return i.endsWith("-")&&(i=i.slice(0,-1)),i.length>=e?i:void 0},f="DB",A="Name your D1 database (run `wrangler d1 create` to get its id, then put it in wrangler.jsonc)",o=t=>u(t,1,64),b="lunora-db",_=t=>o(`${t}-db`)??b,M=async(t,e)=>{const a=_(e);return o(await t(A,{default:a,placeholder:a}))??a},R=(t,e)=>n(t,"d1_databases",{key:"binding",value:f},"database_name",e),N="SEND_EMAIL",P="Verified destination email for production delivery (blank = set it later in wrangler.jsonc)",p=t=>{const e=t.trim();if(e.length===0||e.includes(" "))return!1;const a=e.indexOf("@");if(a<=0||a!==e.lastIndexOf("@"))return!1;const i=e.slice(a+1);return i.length>=3&&i.includes(".")&&!i.startsWith(".")&&!i.endsWith(".")},y=(t,e)=>{const a=t.trim();if(a!==""){if(!p(a)){e(`"${a}" doesn't look like an email — leaving the placeholder; set destination_address in wrangler.jsonc.`);return}return a}},V=(t,e)=>n(t,"send_email",{key:"name",value:N},"destination_address",e),I="UPLOADS",S="Name your R2 bucket (you can rename it in wrangler.jsonc later)",l=t=>u(t,3,63),T="lunora-uploads",k=t=>l(`${t}-uploads`)??T,C=async(t,e)=>{const a=k(e);return l(await t(S,{default:a,placeholder:a}))??a},x=(t,e)=>n(t,"r2_buckets",{key:"binding",value:I},"bucket_name",e);export{B as A,r as D,O as E,P as M,o as a,_ as b,M as c,k as d,E as e,U as f,j as g,g as h,d as i,c as j,V as k,R as l,L as n,C as p,y as r,l as s,x as w};
@@ -0,0 +1,4 @@
1
+ import{jsx as n,jsxs as u}from"react/jsx-runtime";import{isInteractive as p,ACCENT as x,LUNA_ART as ce,LUNA_NAME as le,LUNA_SIGNOFF as ae,BADGE_COLUMN_WIDTH as z,badgeWidth as J,badgeLead as se,padBadge as ue}from"@lunora/config";import{render as H}from"@visulima/tui";import{Box as d}from"@visulima/tui/components/box";import{Text as l}from"@visulima/tui/components/text";import{useApp as I}from"@visulima/tui/hooks/use-app";import{useInput as B}from"@visulima/tui/hooks/use-input";import{useInterval as de}from"@visulima/tui/hooks/use-interval";import{CommandPalette as fe}from"@visulima/tui-kit/command-palette";import{ConfirmInput as he}from"@visulima/tui-kit/confirm-input";import{SelectInput as me}from"@visulima/tui-kit/select-input";import{Spinner as pe}from"@visulima/tui-kit/spinner";import{TextInput as ve}from"@visulima/tui-kit/text-input";import{useState as S,useEffect as A}from"react";import{P as K}from"./prompt-cancelled-BvsNxg_Q.mjs";let j=!1;const V=()=>{j||(j=!0,process.getMaxListeners()<64&&process.setMaxListeners(64))},we=({children:e,onCancel:r})=>{const{exit:t}=I();return B((i,o)=>{o.ctrl&&i==="c"&&(r(),t())}),e},Q=e=>e instanceof Error?e:new Error(typeof e=="string"?e:"task failed"),Z=10,xe=8,ee=({spec:e})=>u(l,{children:[n(l,{children:se(e.text)}),n(l,{backgroundColor:e.bg,bold:!0,color:e.fg,children:ue(e.text)})]}),$=({badge:e,message:r})=>e===void 0?n(l,{bold:!0,children:r}):u(d,{children:[n(ee,{spec:e}),n(l,{bold:!0,children:` ${r}`})]}),re=2,T=" ".repeat(z-1),te=e=>" ".repeat(J(e)+1),Ce=e=>e===void 0?re:J(e)+1,D=({badge:e,children:r,message:t})=>u(d,{flexDirection:"column",children:[n($,{badge:e,message:t}),n(d,{flexDirection:"column",marginLeft:Ce(e),children:r})]}),g=({answer:e,badge:r,message:t})=>u(d,{flexDirection:"column",children:[n($,{badge:r,message:t}),e===""?null:n(l,{dimColor:!0,children:`${r===void 0?" ".repeat(re):te(r)}${e}`})]}),R=e=>{const{exit:r}=I(),[t,i]=S(void 0);return A(()=>{t!==void 0&&r()},[t,r]),{answer:t,submit:(o,c)=>{e(o),i(c)}}},Se=({children:e})=>{const{exit:r}=I();return A(()=>{r()},[r]),e},y=async e=>{V(),process.stdout.write(`
2
+ `);const r=H(n(Se,{children:e}));try{await r.waitUntilExit()}catch{}finally{r.unmount()}},Ze=async(e,r,t)=>{if(!p())return;const i=t===void 0||t===""?[]:t.split(`
3
+ `);await y(u(d,{flexDirection:"column",children:[n($,{badge:e,message:r}),i.map(o=>n(l,{dimColor:!0,children:`${te(e)}${o}`},o))]}))},G=async e=>{V(),process.stdout.write(`
4
+ `);const r={value:!1},t=H(n(we,{onCancel:()=>{r.value=!0},children:e}),{exitOnCtrlC:!1});try{await t.waitUntilExit()}finally{t.unmount()}if(r.value)throw new K},E=async(e,r)=>{let t=r;return await G(e(i=>{t=i})),t},ne=e=>e.description===void 0?e.label:`${e.label} — ${e.description}`,U=()=>{const{exit:e}=I();B((r,t)=>{t.escape&&e()})},Ie=({badge:e,finish:r,initialIndex:t,message:i,options:o})=>{const{answer:c,submit:s}=R(r);return U(),c!==void 0?n(g,{answer:c,badge:e,message:i}):n(D,{badge:e,message:i,children:n(me,{accentColor:x,initialIndex:t,items:o.map(a=>({key:a.value,label:ne(a),value:a.value})),limit:Z,onSelect:a=>{s(a.value,o.find(h=>h.value===a.value)?.label??a.value)}})})},be=({badge:e,finish:r,message:t,options:i})=>{const{exit:o}=I(),{answer:c,submit:s}=R(r);return c!==void 0?n(g,{answer:c,badge:e,message:t}):n(D,{badge:e,message:t,children:n(fe,{accentColor:x,autoFocus:!0,commands:i.map(a=>({description:a.description,id:a.value,label:a.label})),limit:Z,onCancel:()=>{o()},onSelect:a=>{s(a,i.find(h=>h.value===a)?.label??a)},placeholder:"Type to filter…"})})},er=async(e,r,t)=>{if(!p()||r.length===0)return t?.default;const{badge:i}=t??{};if(r.length>xe)return E(c=>n(be,{badge:i,finish:c,message:e,options:r}),t?.default);const o=t?.default===void 0?-1:r.findIndex(c=>c.value===t.default);return E(c=>n(Ie,{badge:i,finish:c,initialIndex:o>=0?o:void 0,message:e,options:r}),t?.default)},Te=({badge:e,defaultValue:r,finish:t,message:i,placeholder:o})=>{const{answer:c,submit:s}=R(t);return U(),c!==void 0?n(g,{answer:c,badge:e,message:i}):n(D,{badge:e,message:i,children:n(ve,{defaultValue:r,onSubmit:a=>{const h=a.trim()===""?r:a.trim();s(h,h)},placeholder:o})})},rr=async(e,r)=>{const t=r?.default??"";if(!p())return t;const{badge:i}=r??{};return E(o=>n(Te,{badge:i,defaultValue:t,finish:o,message:e,placeholder:r?.placeholder}),t)},ye=({badge:e,defaults:r,finish:t,message:i,options:o})=>{const{answer:c,submit:s}=R(t),[a,h]=S(0),[m,w]=S(()=>new Set(r));return U(),B((b,v)=>{if(!(c!==void 0||o.length===0)){if(v.upArrow)h(f=>(f-1+o.length)%o.length);else if(v.downArrow)h(f=>(f+1)%o.length);else if(b===" "){const f=o[a];f!==void 0&&w(C=>{const _=new Set(C);return _.has(f.value)?_.delete(f.value):_.add(f.value),_})}else if(v.return){const f=o.filter(C=>m.has(C.value));s(f.map(C=>C.value),f.length>0?f.map(C=>C.label).join(", "):"none")}}}),c!==void 0?n(g,{answer:c,badge:e,message:i}):n(D,{badge:e,message:i,children:u(d,{flexDirection:"column",children:[n(l,{dimColor:!0,children:"space toggles · enter confirms · esc cancels"}),o.map((b,v)=>{const f=v===a;return n(l,{color:f?x:void 0,children:`${f?"▸ ":" "}${m.has(b.value)?"◼":"◻"} ${ne(b)}`},b.value)})]})})},tr=async(e,r,t)=>{const i=t?.defaults??[];if(!p()||r.length===0)return[...i];const{badge:o}=t??{};return E(c=>n(ye,{badge:o,defaults:i,finish:c,message:e,options:r}),[...i])},Ne=({badge:e,defaultYes:r,finish:t,message:i})=>{const{answer:o,submit:c}=R(t);return o!==void 0?n(g,{answer:o,badge:e,message:i}):u(d,{children:[e===void 0?null:n(ee,{spec:e}),n(l,{bold:!0,children:e===void 0?`${i} `:` ${i} `}),n(he,{defaultChoice:r?"confirm":"cancel",onCancel:()=>{c(!1,"No")},onConfirm:()=>{c(!0,"Yes")}})]})},Ee=async(e,r)=>{const t=r?.defaultYes===!0;if(!p())return t;const{badge:i}=r??{};return E(o=>n(Ne,{badge:i,defaultYes:t,finish:o,message:e}),!1)},nr=()=>p()?e=>Ee(e,{defaultYes:!0}):()=>Promise.resolve(!1),W="#c8a8ff",L="#d9c8ff",$e="#6b5b9a",P=({moon:e,prefix:r,suffix:t})=>u(d,{children:[n(l,{color:W,dimColor:!0,children:r}),typeof e=="string"?n(l,{color:L,children:e}):e,t===void 0?null:n(l,{color:W,children:t})]}),X=({left:e,right:r})=>u(l,{color:L,children:[e,n(l,{color:$e,children:"●●"}),r]}),ge=()=>u(d,{flexDirection:"column",paddingX:1,children:[n(P,{moon:".-‐-.",prefix:"· ✦ · ",suffix:" ✦"}),n(P,{moon:n(X,{left:"/",right:"\\"}),prefix:" ✦ · ",suffix:" ·"}),n(P,{moon:n(X,{left:"\\",right:"/"}),prefix:" . ✦ · "}),u(d,{children:[n(l,{bold:!0,color:x,children:" lunora init "}),n(l,{dimColor:!0,children:"· moonrise sequence"}),n(l,{color:L})]})]}),or=async e=>{p()&&await y(u(d,{flexDirection:"column",children:[n(ge,{}),n(d,{paddingX:1,children:n(l,{dimColor:!0,children:e})})]}))},Re=({label:e})=>u(d,{children:[n(l,{color:x,children:n(pe,{type:"dots"})}),u(l,{children:[" ",e]})]}),ir=async(e,r)=>{if(!p())return r();V();const t=H(n(Re,{label:e}));try{return await r()}finally{t.unmount()}},cr=async()=>{p()&&await y(u(d,{paddingX:1,children:[n(l,{color:L,children:ce}),u(d,{flexDirection:"column",marginLeft:2,children:[n(l,{bold:!0,color:x,children:le}),n(l,{children:ae})]})]}))},_e="#06b6d4",M=" ".repeat(9),lr=async e=>{p()&&await y(n(l,{bold:!0,children:`${M}${e}`}))},ar=async e=>{p()&&await y(u(d,{children:[n(l,{color:_e,children:`${T}◼`}),n(l,{children:` ${e}`})]}))},sr=async(e,r,t,i)=>{p()&&await y(u(d,{flexDirection:"column",children:[n($,{badge:e,message:r}),n(d,{flexDirection:"column",marginTop:1,children:t.map(o=>u(l,{children:[`${M}${o.lead} `,n(l,{color:x,children:o.code}),o.tail??""]},o.lead))}),n(d,{flexDirection:"column",marginTop:1,children:i.map(o=>u(l,{children:[`${M}${o.lead} `,n(l,{color:x,children:o.code}),o.tail??""]},o.lead))})]}))},Y="#a855f7",oe="#06b6d4",N=[Y,"#9b51f6","#8a5cf6","#6f86f6","#4aa6ef","#2bb6dd","#12bcd0",oe],O=N.length-2,F=(e,r)=>Array.from({length:Math.max(0,e)},()=>r),q=[...F(N.length-1,Y),...N,...F(N.length-1,oe),...N.toReversed()],k=q.map((e,r)=>{const t=q.slice(r,r+O);return[...t,...F(O-t.length,Y)]}),Ae=" ".repeat(Math.max(0,z-O)),ie=({label:e})=>{const[r,t]=S(0);de(()=>{t(o=>(o+1)%k.length)},90);const i=k[r%k.length]??[];return u(l,{children:[Ae,i.map((o,c)=>n(l,{color:o,children:"█"},c)),` ${e}`]})},De=({label:e,status:r})=>r==="running"?n(l,{color:x,children:`${T}▶ ${e}`}):r==="failed"?n(l,{color:"red",children:`${T}✖ ${e}`}):r==="done"?n(l,{dimColor:!0,children:`${T}■ ${e}`}):n(l,{dimColor:!0,children:`${T}□ ${e}`}),Le=async(e,r,t)=>{const i=[];let o;for(const[c,s]of e.entries()){if(t())break;r(c,"running");try{i.push(await s.run()),r(c,"done")}catch(a){r(c,"failed"),o=a;break}}return{failure:o,results:i}},Pe=(e,r,t,i)=>{let o=!0;return Le(e,(s,a)=>{o&&r(h=>h.map((m,w)=>w===s?a:m))},()=>!o).then(({failure:s,results:a})=>{t(a,s),setTimeout(()=>{o&&i()},400)}).catch(s=>{t([],s)}),()=>{o=!1}},ke=({end:e,onSettle:r,onStart:t,start:i,tasks:o})=>{const{exit:c}=I(),[s,a]=S(()=>o.map(()=>"pending"));A(()=>(t(),Pe(o,a,r,c)),[c,r,t,o]);const h=s.length>0&&s.every(m=>m==="done");return u(d,{flexDirection:"column",children:[h?u(d,{children:[n(l,{bold:!0,color:"green",children:`${T}✔`}),n(l,{bold:!0,color:"green",children:` ${e}`})]}):n(ie,{label:i}),o.map((m,w)=>n(De,{label:m.label,status:s[w]??"pending"},m.label))]})},ur=async(e,r)=>{if(!p()){const s=[];for(const a of e)s.push(await a.run());return s}let t=[],i,o=()=>{},c;try{await G(n(ke,{end:r.end,onSettle:(s,a)=>{t=s,i=a,o()},onStart:()=>{c=new Promise(s=>{o=s})},start:r.start,tasks:e}))}catch(s){throw await c,s}if(i!==void 0)throw Q(i);return t},Me=async(e,r)=>{const t=[];let i;for(const[o,c]of e.entries()){r(o);try{t.push(await c.task())}catch(s){i=s;break}}return{failure:i,values:t}},Oe=({badge:e,done:r,onSettle:t,steps:i})=>{const{exit:o}=I(),[c,s]=S(0),[a,h]=S(!1);return A(()=>{let m=!0,w;return Me(i,v=>{m&&s(v)}).then(({failure:v,values:f})=>{if(m){if(v!==void 0){t({error:v,ok:!1}),o();return}h(!0),w=setTimeout(()=>{m&&(t({ok:!0,values:f}),o())},400)}}).catch(()=>{}),()=>{m=!1,w!==void 0&&clearTimeout(w)}},[o,t,i]),a?n($,{badge:e,message:r}):n(ie,{label:i[c]?.running??""})},dr=async(e,r,t)=>{if(!p()){const o=[];for(const c of r)o.push(await c.task());return o}let i;if(await G(n(Oe,{badge:e,done:t,onSettle:o=>{i=o},steps:r})),i===void 0)throw new K;if(!i.ok)throw Q(i.error);return i.values};export{rr as a,Ee as b,nr as c,cr as d,Ze as e,or as f,tr as g,lr as h,ar as i,sr as j,ur as k,dr as l,er as t,ir as w};
@@ -0,0 +1 @@
1
+ const A="LUNORA_AI_GATEWAY_ID",_="LUNORA_AI_GATEWAY_ACCOUNT_ID",I="LUNORA_AI_GATEWAY_TOKEN",R="LUNORA_AI_PROXY_URL";export{R as A,I as a,A as b,_ as c};
@@ -0,0 +1 @@
1
+ import{findWranglerFile as a,readWranglerJsonc as t}from"@lunora/config/cloudflare";const i=n=>{const e=a(n);if(!e)return;const{parsed:r}=t(e);return typeof r?.name=="string"&&r.name.length>0?r.name:void 0};export{i as r};
@@ -0,0 +1 @@
1
+ import{resolveDeployDriver as c,resolveProjectTarget as d,toolchainExecArgs as l,detectPackageManager as i}from"@lunora/config";import{defaultSpawner as u}from"./createRecordingSpawner-Ch7zuQQE.mjs";const m=async(e,t,o)=>{try{const r=await u({args:t,captureStderr:!0,captureStdoutSilently:!0,command:e,cwd:o});return{code:r.code,stderr:r.stderr??"",stdout:r.stdout??""}}catch(r){return{code:1,stderr:r instanceof Error?r.message:String(r),stdout:""}}},f=e=>{let t;try{t=JSON.parse(e)}catch{return}return Array.isArray(t)?[...t.map(r=>r!==null&&typeof r=="object"?r.name:void 0).filter(r=>typeof r=="string"&&r.length>0)].toSorted((r,a)=>r.localeCompare(a)):void 0},y=async e=>{const t=c(d(e.cwd)),o=t.toolchain?.secretList?.({environment:e.env,temporary:e.temporary});if(o===void 0)return{error:`deploy target "${t.id}" has no secret store to list`,names:[],ok:!1};const{args:r,command:a}=l(i(e.cwd),o),s=await(e.runner??m)(a,r,e.cwd);if(s.code!==0)return{error:s.stderr.trim()||`wrangler secret list exited ${String(s.code)}`,names:[],ok:!1};const n=f(s.stdout);return n===void 0?{error:"could not parse `wrangler secret list --format json` output",names:[],ok:!1}:{names:n,ok:!0}};export{y as l};