@lunora/cli 1.0.0-alpha.32 → 1.0.0-alpha.320

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 (122) 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 +960 -370
  5. package/dist/index.d.ts +960 -370
  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 +2 -22
  11. package/dist/packem_chunks/handler12.mjs +1 -192
  12. package/dist/packem_chunks/handler13.mjs +1 -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 +3 -80
  16. package/dist/packem_chunks/handler17.mjs +1 -43
  17. package/dist/packem_chunks/handler18.mjs +1 -105
  18. package/dist/packem_chunks/handler19.mjs +7 -170
  19. package/dist/packem_chunks/handler2.mjs +1 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -94
  21. package/dist/packem_chunks/handler21.mjs +3 -94
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +1 -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 +10 -0
  27. package/dist/packem_chunks/handler3.mjs +1 -204
  28. package/dist/packem_chunks/handler4.mjs +1 -33
  29. package/dist/packem_chunks/handler5.mjs +1 -49
  30. package/dist/packem_chunks/handler6.mjs +1 -91
  31. package/dist/packem_chunks/handler7.mjs +3 -42
  32. package/dist/packem_chunks/handler8.mjs +1 -174
  33. package/dist/packem_chunks/handler9.mjs +1 -315
  34. package/dist/packem_chunks/planDevCommand.mjs +7 -541
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +7 -594
  37. package/dist/packem_chunks/runInitCommand.mjs +162 -1430
  38. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  39. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  40. package/dist/packem_shared/COMMANDS-DdaAWPtr.mjs +1 -0
  41. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BgMPHEoe.mjs +1 -0
  42. package/dist/packem_shared/EXIT_CODE-08cwt3MK.mjs +1 -0
  43. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  44. package/dist/packem_shared/admin-url-BhF5ufg1.mjs +1 -0
  45. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  46. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  47. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  48. package/dist/packem_shared/cli-DOpChqUe.mjs +2 -0
  49. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  50. package/dist/packem_shared/command-Mmxzxyr5.mjs +1 -0
  51. package/dist/packem_shared/commands-CNqednoX.mjs +13 -0
  52. package/dist/packem_shared/createLogger-Cl18I8AX.mjs +2 -0
  53. package/dist/packem_shared/createRecordingSpawner-sS7LEN7x.mjs +1 -0
  54. package/dist/packem_shared/deploy-target-DCWwiuAe.mjs +1 -0
  55. package/dist/packem_shared/diffSnapshots-WWwx-KvZ.mjs +5 -0
  56. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  57. package/dist/packem_shared/import-D7qdpSmJ.mjs +12 -0
  58. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  59. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  60. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  61. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  62. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  63. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  64. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  65. package/dist/packem_shared/render-lunora-error--4tmM6mt.mjs +3 -0
  66. package/dist/packem_shared/resolve-DUCSc7jQ.mjs +5 -0
  67. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  68. package/dist/packem_shared/runAddCommand-Cf2q2y27.mjs +1 -0
  69. package/dist/packem_shared/runExportCommand-DxsJHYZt.mjs +5 -0
  70. package/dist/packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs +11 -0
  71. package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +1 -0
  72. package/dist/packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs +1 -0
  73. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  74. package/dist/packem_shared/storage-J4xhM4FU.mjs +1 -0
  75. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  76. package/dist/packem_shared/vectorize-metadata-dXpl2_Ar.mjs +1 -0
  77. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  78. package/dist/packem_shared/wrangler-secrets-C9lJnd5N.mjs +1 -0
  79. package/package.json +39 -19
  80. package/skills/README.md +35 -17
  81. package/skills/lunora/SKILL.md +123 -9
  82. package/skills/lunora-create-package/SKILL.md +4 -3
  83. package/skills/lunora-deploy/SKILL.md +42 -11
  84. package/skills/lunora-functions/SKILL.md +120 -15
  85. package/skills/lunora-migration-helper/SKILL.md +74 -21
  86. package/skills/lunora-performance-audit/SKILL.md +78 -9
  87. package/skills/lunora-quickstart/SKILL.md +93 -27
  88. package/skills/lunora-realtime/SKILL.md +73 -39
  89. package/skills/lunora-setup-auth/SKILL.md +33 -6
  90. package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
  91. package/skills/lunora-setup-hyperdrive-global/SKILL.md +5 -0
  92. package/skills/lunora-setup-mail/SKILL.md +34 -28
  93. package/skills/lunora-setup-scheduler/SKILL.md +18 -14
  94. package/skills/lunora-setup-storage/SKILL.md +182 -25
  95. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  96. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  97. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  98. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  99. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  100. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  101. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  102. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  103. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  104. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  105. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  106. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  107. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  108. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  109. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  110. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  111. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  112. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  113. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  114. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  115. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  116. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  117. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  118. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  119. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  120. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  121. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  122. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,41 +1 @@
1
- import { existsSync, rmSync } from 'node:fs';
2
- import { join } from '@visulima/path';
3
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
4
- import { b as tuiConfirm } from '../packem_shared/tui-prompts-BjEN8XgP.mjs';
5
-
6
- const runResetCommand = async (options) => {
7
- const cwd = options.cwd ?? process.cwd();
8
- const targets = [join(cwd, ".wrangler", "state")];
9
- if (options.all) {
10
- targets.push(join(cwd, ".lunora-cache"));
11
- }
12
- if (!options.yes) {
13
- const isTty = process.stdin.isTTY;
14
- if (!isTty && options.confirm === void 0) {
15
- options.logger.error("reset: stdin is not a TTY — re-run with --yes to confirm deleting .wrangler/state");
16
- return { code: 1, removed: [] };
17
- }
18
- const confirmer = options.confirm ?? tuiConfirm;
19
- const confirmed = await confirmer("This will delete .wrangler/state. Continue?");
20
- if (!confirmed) {
21
- options.logger.info("reset: aborted");
22
- return { code: 1, removed: [] };
23
- }
24
- }
25
- const removed = [];
26
- for (const target of targets) {
27
- if (existsSync(target)) {
28
- rmSync(target, { force: true, recursive: true });
29
- removed.push(target);
30
- options.logger.success(`removed ${target}`);
31
- } else {
32
- options.logger.info(`skipped (not present): ${target}`);
33
- }
34
- }
35
- return { code: 0, removed };
36
- };
37
- const execute = defineHandler(
38
- ({ cwd, logger, options }) => runResetCommand({ all: options.all === true, cwd, logger, yes: options.yes === true })
39
- );
40
-
41
- export { execute, runResetCommand };
1
+ import{existsSync as m,rmSync as d}from"node:fs";import{join as n,relative as f}from"@visulima/path";import{d as a}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as s}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{b as l}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";const u=async e=>{const o=e.cwd??process.cwd(),t=[n(o,".wrangler","state")];if(e.all&&t.push(n(o,".lunora-cache")),!e.yes){const r=t.map(i=>f(o,i)).join(" and ");if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error(`reset: stdin is not a TTY — re-run with --yes to confirm deleting ${r}`),{code:s.USAGE,removed:[]};if(!await(e.confirm??l)(`This will delete ${r}. Continue?`))return e.logger.info("reset: aborted"),{code:s.CANCELLED,removed:[]}}const c=[];for(const r of t)m(r)?(d(r,{force:!0,recursive:!0}),c.push(r),e.logger.success(`removed ${r}`)):e.logger.info(`skipped (not present): ${r}`);return{code:0,removed:c}},E=a(({cwd:e,logger:o,options:t})=>u({all:t.all===!0,cwd:e,logger:o,yes:t.yes===!0}));export{E as execute,u as runResetCommand};
@@ -1,68 +1 @@
1
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
2
- import { r as resolveWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
3
-
4
- const parseArgsJson = (raw) => {
5
- if (raw === void 0 || raw.length === 0) {
6
- return {};
7
- }
8
- try {
9
- return JSON.parse(raw);
10
- } catch (error) {
11
- const message = error instanceof Error ? error.message : String(error);
12
- throw new Error(`failed to parse --args as JSON: ${message}`, { cause: error });
13
- }
14
- };
15
- const TRAILING_SLASH = /\/$/u;
16
- const runRpcCommand = async (options) => {
17
- const resolvedUrl = resolveWorkerUrl({ cwd: options.cwd ?? process.cwd(), url: options.url });
18
- const baseUrl = (resolvedUrl ?? "http://localhost:8787").replace(TRAILING_SLASH, "");
19
- const requestUrl = `${baseUrl}/_lunora/rpc`;
20
- const fetchImpl = options.fetchImpl ?? globalThis.fetch;
21
- if (typeof fetchImpl !== "function") {
22
- throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");
23
- }
24
- let parsedArgs;
25
- try {
26
- parsedArgs = parseArgsJson(options.args);
27
- } catch (error) {
28
- const message = error instanceof Error ? error.message : String(error);
29
- options.logger.error(message);
30
- return { body: void 0, code: 1, requestUrl };
31
- }
32
- const payload = {
33
- args: parsedArgs,
34
- functionPath: options.functionPath
35
- };
36
- if (options.shard !== void 0) {
37
- payload.shardKey = options.shard;
38
- }
39
- options.logger.info(`POST ${requestUrl} -> ${options.functionPath}`);
40
- const response = await fetchImpl(requestUrl, {
41
- body: JSON.stringify(payload),
42
- headers: { "content-type": "application/json" },
43
- method: "POST"
44
- });
45
- const text = await response.text();
46
- let body;
47
- try {
48
- body = JSON.parse(text);
49
- } catch {
50
- body = text;
51
- }
52
- options.logger.info(JSON.stringify(body, void 0, 2));
53
- return {
54
- body,
55
- code: response.ok ? 0 : 1,
56
- requestUrl
57
- };
58
- };
59
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
60
- const functionPath = argument[0];
61
- if (!functionPath) {
62
- logger.error("missing function path. Usage: lunora run <functionPath> [--args <json>]");
63
- return { code: 1 };
64
- }
65
- return runRpcCommand({ args: options.args, cwd, functionPath, logger, shard: options.shard, url: options.url });
66
- });
67
-
68
- export { execute, runRpcCommand };
1
+ import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as N,a as _}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as U}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as u,exitCodeForStatus as p}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{r as E}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const y=(r,a="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(t){const s=t instanceof Error?t.message:String(t);throw new h("INTERNAL",`failed to parse ${a} as JSON: ${s}`,{cause:t})}if(typeof e!="object"||e===null||Array.isArray(e))throw new h("INTERNAL",`${a} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},P=/\/$/u,T="__lunora_admin__:runAs",I="__lunora_admin__:",O=async(r,a)=>{const e=await r.text();let t;try{t=JSON.parse(e)}catch{t=e}return a.info(JSON.stringify(t,void 0,2)),t},$=(r,a)=>{const e=a.body?.error?.code;a.runAs||a.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},k=({args:r,claims:a,options:e,runAs:t})=>{const s=t?{args:{args:r,functionPath:e.functionPath,identity:a,userId:e.as},functionPath:T}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(s.shardKey=e.shard),s},R=({cwd:r,logger:a,needsBearer:e,url:t})=>e?N(t,a,r):(E({cwd:r,url:t})??_(r)).replace(P,""),w=({args:r,claims:a},e)=>{try{return{args:y(r),claims:a===void 0?void 0:y(a,"--claims")}}catch(t){e.error(t instanceof Error?t.message:String(t));return}},D=async r=>{const a=r.cwd??process.cwd(),{logger:e}=r,t=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!t){const d="--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch.";return e.error(d),{body:void 0,code:u.USAGE,error:d,requestUrl:r.url??""}}const s=t||r.functionPath.startsWith(I),n=R({cwd:a,logger:e,needsBearer:s,url:r.url});if(n===void 0)return{body:void 0,code:u.USAGE,error:"could not resolve a usable worker URL",requestUrl:r.url??""};const o=`${n}/_lunora/rpc`,i=r.fetchImpl??globalThis.fetch;if(typeof i!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");const f=w(r,e);if(f===void 0)return{body:void 0,code:u.USAGE,error:"could not parse --args / --claims as JSON",requestUrl:o};const{source:v,token:l}=s?S({cwd:a,token:r.token,url:n}):{};if(s&&l===void 0){const d="admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)";return e.error(d),{body:void 0,code:u.AUTH,error:d,requestUrl:o}}l!==void 0&&e.debug?.(`admin bearer from ${b(v)}`);const g={"content-type":"application/json",...l===void 0?{}:{authorization:`Bearer ${l}`}},A=k({args:f.args,claims:f.claims,options:r,runAs:t});e.info(`POST ${o} -> ${r.functionPath}${t?` (as ${r.as??""})`:""}`);const c=await i(o,{body:JSON.stringify(A),headers:g,method:"POST"}),m=await O(c,e);return $(e,{body:m,runAs:t,status:c.status}),{body:m,code:c.ok?0:p(c.status),error:c.ok?void 0:`${r.functionPath} failed: HTTP ${String(c.status)}`,requestUrl:o}},j=U(async({argument:r,cwd:a,format:e,logger:t,options:s})=>{const n=r[0];if(!n){const i="missing function path. Usage: lunora run <functionPath> [--args <json>]";return t.error(i),{code:u.USAGE,error:i}}const o=await D({args:s.args,as:s.as,claims:s.claims,cwd:a,format:e,functionPath:n,logger:t,shard:s.shard,token:s.token,url:s.url});return{code:o.code,data:{functionPath:n,requestUrl:o.requestUrl,result:o.body},error:o.error}});export{j as execute,O as readAndLogBody,D as runRpcCommand};
@@ -0,0 +1 @@
1
+ import{C as i,R as m,V as p,r as s}from"./cli-DOpChqUe.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error--4tmM6mt.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
@@ -0,0 +1 @@
1
+ import"./admin-token-VdUnvnKW.mjs";import"./admin-url-BhF5ufg1.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import{D as a,r as I}from"./import-D7qdpSmJ.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,I as runImportCommand};
@@ -0,0 +1 @@
1
+ import{isLunoraError as S,getCatalogEntry as _}from"@lunora/errors";const E={SUCCESS:0,FAILURE:1,USAGE:2,AUTH:3,PERMISSION:4,NOT_FOUND:5,CONFLICT:6,RATE_LIMITED:7,UNAVAILABLE:8,MISSING_DEPENDENCY:9,CANCELLED:130},U=new Map([[400,E.USAGE],[401,E.AUTH],[403,E.PERMISSION],[404,E.NOT_FOUND],[405,E.USAGE],[409,E.CONFLICT],[413,E.USAGE],[421,E.UNAVAILABLE],[422,E.USAGE],[429,E.RATE_LIMITED],[502,E.UNAVAILABLE],[503,E.UNAVAILABLE],[504,E.UNAVAILABLE],[507,E.USAGE]]),I=new Map([["CODEGEN_DIAGNOSTIC",E.USAGE],["CRON_EXPR_INVALID",E.USAGE],["CRON_EXPR_NOT_STATIC",E.USAGE],["CRON_NAME_NOT_STATIC",E.USAGE],["CRON_NON_STATIC_FN",E.USAGE],["CRON_NON_STATIC_VALUE",E.USAGE],["CRON_SCHEDULE_INVALID",E.USAGE],["CRON_SCHEDULE_NOT_STATIC",E.USAGE],["DUPLICATE_AGENT_BINDING",E.USAGE],["DUPLICATE_AGENT_CLASS",E.USAGE],["DUPLICATE_AGENT_NAME",E.USAGE],["DUPLICATE_CRON_NAME",E.USAGE],["DUPLICATE_MIGRATION_ID",E.USAGE],["DUPLICATE_QUEUE_BINDING",E.USAGE],["DUPLICATE_QUEUE_NAME",E.USAGE],["DUPLICATE_WORKFLOW_CLASS",E.USAGE],["LOCAL_DEPENDENCY_MISSING",E.MISSING_DEPENDENCY],["MIGRATION_ID_NOT_STATIC",E.USAGE],["NAMESPACE_COLLISION",E.USAGE],["SCHEMA_SNAPSHOT_PARSE",E.USAGE]]),N=A=>A===void 0?E.FAILURE:U.get(A)??E.FAILURE,T=A=>I.get(A)??N(_(A)?.status),L=A=>S(A)?I.get(A.code)??N(A.status):E.FAILURE,G=A=>"refused"in A;export{E as EXIT_CODE,T as exitCodeForCode,L as exitCodeForError,N as exitCodeForStatus,G as isRefusal};
@@ -0,0 +1 @@
1
+ import{readFileSync as c}from"node:fs";import{join as v}from"node:path";import{DEV_VARS_FILE as i,parseDevVariableEntries as u}from"@lunora/config";const n="LUNORA_ADMIN_TOKEN",f=new Set(["127.0.0.1","::1","[::1]","localhost"]),a=e=>{if(e===void 0||e==="")return!0;try{return f.has(new URL(e).hostname)}catch{return!1}},d=e=>{let r;try{r=c(v(e,i),"utf8")}catch{return}const o=u(r).find(t=>t.key===n);return o?.value===""?void 0:o?.value},A=({cwd:e,token:r,url:o})=>{if(r!==void 0&&r!=="")return{source:"flag",token:r};const t=process.env[n];if(t!==void 0&&t!=="")return{source:"env",token:t};if(!a(o))return{};const s=d(e);return s===void 0?{}:{source:"dev-vars",token:s}},E=({prod:e,url:r})=>e===!0||r===""||!a(r),_=e=>e==="flag"?"--token":e==="env"?n:i;export{_ as d,A as r,E as t};
@@ -0,0 +1 @@
1
+ import{readLiveDevServerState as a}from"@lunora/config";const l=new Set(["127.0.0.1","::1","[::1]","localhost"]),i=/\/$/u,n="http://localhost:8787",c=r=>r===void 0?n:a(r)?.url??n,d=r=>r.replace(i,""),u=(r,o,s)=>{const e=r??c(s);let t;try{t=new URL(e)}catch{o.error(`invalid --url: ${e}`);return}if(!l.has(t.hostname)&&t.protocol!=="https:"){o.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return d(e)};export{c as a,d as n,u as r};
@@ -0,0 +1,2 @@
1
+ import{mkdirSync as a,writeFileSync as g}from"node:fs";import{findWranglerFile as f,readWranglerJsonc as l,buildBindingManifest as m}from"@lunora/config/cloudflare";import{isAbsolute as c,resolve as h,dirname as u}from"@visulima/path";const v=r=>{const n=f(r),e=n===void 0?void 0:l(n).parsed;return e===void 0?{error:`no readable wrangler config in ${r}. The binding manifest is derived from it, and an empty one would tell a deployer this Worker needs nothing.`}:{manifest:m(e)}},y=r=>{const{destination:n,dev:e,logger:s,projectRoot:d}=r,t=v(d);if(t.manifest===void 0)return{error:t.error};const i={...t.manifest,...e===void 0?{}:{dev:e}},o=c(n)?n:h(d,n);return a(u(o),{recursive:!0}),g(o,`${JSON.stringify(i,void 0,2)}
2
+ `,"utf8"),s.success(`binding manifest written to ${o} (${i.bindings.length.toString()} bindings, ${i.crons.length.toString()} crons)`),i.unknown.length>0&&s.warn(`binding manifest does not model these wrangler sections: ${i.unknown.join(", ")}. Anything they bind must be provisioned by hand — please report them so the manifest can cover them.`),{}};export{v as d,y as w};
@@ -0,0 +1 @@
1
+ import{b as e,c as l}from"./catalog-CahzmDLV.mjs";import"./parseManifest-CwPTKdtS.mjs";export{e as buildRegistryIndex,l as collectCatalog};
@@ -0,0 +1 @@
1
+ import{existsSync as a,readFileSync as o,readdirSync as p,statSync as d}from"node:fs";import{join as s}from"@visulima/path";import u from"./parseManifest-CwPTKdtS.mjs";const m=/[\u0000-\u0008\u000A-\u001F\u007F-\u009F\u202A-\u202E\u2066-\u2069]/gu,n=i=>i.replaceAll(m,""),c=i=>p(i).filter(r=>{const t=s(i,r);return d(t).isDirectory()&&a(s(t,"registry.json"))}),y=i=>{const r=s(i,"index.json");if(a(r)){const t=JSON.parse(o(r,"utf8"));if(Array.isArray(t.items))return t.items.filter(e=>typeof e=="object"&&e!==null&&typeof e.name=="string").map(e=>({description:e.description===void 0?void 0:n(e.description),name:n(e.name)}))}return c(i).map(t=>{const e=JSON.parse(o(s(i,t,"registry.json"),"utf8"));return{description:e.description===void 0?void 0:n(e.description),name:n(t)}})},A=i=>({items:c(i).map(t=>{const e=u(JSON.parse(o(s(i,t,"registry.json"),"utf8")),t);return{...e.description===void 0?{}:{description:e.description},name:e.name,...e.title===void 0?{}:{title:e.title}}}).toSorted((t,e)=>t.name.localeCompare(e.name))});export{A as b,y as c,n as s};
@@ -0,0 +1,2 @@
1
+ import{mkdirSync as A,readFileSync as S,lstatSync as D,writeFileSync as B}from"node:fs";import{join as m,dirname as y}from"node:path";import{fileURLToPath as E}from"node:url";import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{O as i,r as P}from"./render-lunora-error--4tmM6mt.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as U}from"@lunora/codegen";import{exitCodeForError as M,EXIT_CODE as W}from"./EXIT_CODE-08cwt3MK.mjs";import{setCommandLogger as v,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{homedir as J}from"node:os";import{addArgsFor as F,detectPackageManager as K}from"@lunora/config";const H={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},i]},b="lunora.advisor.map.json",$={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${b})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},i,{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${b})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},V={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[i]},G={argument:{description:"create | list | restore <id|file> | retention | prune | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) to a directory or an R2 bucket, plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup list --format json","Same, as a single JSON document on stdout"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},i,{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a destructive step without prompting: a production pitr --restore, or backup prune",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},q={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},i,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},z={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},i,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},l]},Y={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String},{...i,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},Q={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},i,{description:"After the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},l,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},X={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{...i,description:"Output format: pretty (default) or json (`list` only)"},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},Z={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},ee={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},te={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"doctor",options:[i]},re={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",name:"prod",type:Boolean},i,{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},oe={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},i,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ne={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{...i,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ae={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},i,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ie={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},i,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},se={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | react-router | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | auth-ui | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},le={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --format json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},i,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},de={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean},i]},pe={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},ce={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},i,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},ue={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},me={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate status backfill-names --format json","Same, as a single JSON document on stdout"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/dispatch.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},i,{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},ge={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},he={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{...i,description:"Output format: pretty (default) or json (add plan / list)"},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},fe={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},ye={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ve={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},i,{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},be={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${U.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},we={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},i,{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},ke={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},i,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Se={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},xe=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const s=r[a]??0,c=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Re=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const s=xe(e,a);s<o&&(o=s,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ce=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ne=1440*60*1e3,Oe=1500,Ae="0.0.0",De=/^v/u,Be=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(De,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},w=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ee=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},Le=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],s=o[n];if(a===void 0||s===void 0)return a===void 0?-1:1;if(a!==s)return Ee(a,s)}return 0},Ie=(e,t)=>{const r=w(e),o=w(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return Le(g(e).prerelease,g(t).prerelease)},je=e=>{const t=g(e).prerelease.split(".")[0]??"";return Be.has(t)?t:"latest"},Te=(e,t)=>Ie(t,e)>0,_e=(e,t,r)=>t-e<r,Pe=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${a.join(" ")}\``},R=e=>m(e,"lunora-cli-update.json"),Ue=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:m(J(),".cache"),r=m(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Me=e=>{try{const t=JSON.parse(S(R(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},k=(e,t)=>{try{const r=R(e);try{if(D(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
2
+ `,"utf8")}catch{}},We=async(e,t)=>{try{const r=await e(Ce(t),{signal:AbortSignal.timeout(Oe)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Je=(e,t,r)=>e===Ae||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Fe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Je(e.current,t,r))return;const o=e.cacheDir??Ue(t),n=(e.now??Date.now)(),a=e.ttlMs??Ne,s=je(e.current),c=Me(o),O=c?.tag??"latest",h=c!==void 0&&O===s?c:void 0;let u=h?.latest;if(h===void 0||!_e(h.checkedAt,n,a)){const f=await We(e.fetchImpl??globalThis.fetch,s);f===void 0?k(o,{checkedAt:n,latest:e.current,tag:s}):(u=f,k(o,{checkedAt:n,latest:f,tag:s}))}u!==void 0&&Te(e.current,u)&&e.logger.warn(Pe(e.current,u,s,e.manager))},Ke=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],He=8,$e=()=>{try{let e=y(E(import.meta.url));for(let t=0;t<He;t+=1){try{const o=JSON.parse(S(m(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},C=$e(),Ve=[se,H,Z,z,$,q,Q,Y,ge,pe,X,ce,ve,le,fe,me,ne,ae,we,de,G,oe,ke,ie,te,re,V,Se,ee,he,ye,ue,be],N=[...Ve,_,T],mt=N.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Ge=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),qe=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:Ge(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),ze=e=>{const t={value:0},r=j("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:C});for(const o of N)r.addCommand(qe(o));return{cli:r,exitCode:t}},Ye=/Command "(?<name>[^"]+)" not found/u,Qe=e=>{const t=x(),r=e instanceof Error?e.message:String(e),o=Ye.exec(r);if(!o?.groups)return L(e)||I(r)!==void 0?t.error(P(e)):t.error(r),M(e);const n=o.groups.name??"",a=Re(n,Ke);return t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),W.USAGE},Xe=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),gt=async(e={})=>{const{cli:t,exitCode:r}=ze(e);e.logger!==void 0&&v(Xe(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Qe(n)}finally{v(void 0)}let o;try{o=K(process.cwd())}catch{}return await Fe({current:C,logger:x(),manager:o}),r.value};export{Ke as C,b as D,mt as R,C as V,gt as r};
@@ -0,0 +1,3 @@
1
+ import{findLunoraSolution as i}from"@lunora/codegen";import{VisulimaError as s,renderError as a}from"@visulima/error";const d=n=>n.body.split(`
2
+ `).filter(e=>!e.startsWith("```")).join(`
3
+ `).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),l={filterStacktrace:()=>!1,hideErrorCodeView:!0},g=(n,e)=>{const r=n instanceof Error?n.message:String(n),o=i(r),t=new s({hint:o?[o.header,"",d(o)]:void 0,message:e===void 0?`codegen failed: ${r}`:`codegen failed (${e}): ${r}`,name:"CodegenError"});return t.stack="",a(t,l)},f=n=>{const e=i(n);if(e===void 0)return;const r=new s({hint:[d(e)],message:e.header,name:"Hint"});return r.stack="",a(r,l)};export{g as a,f as r};
@@ -0,0 +1 @@
1
+ import{isLunoraError as d,findSolutionByMessage as p}from"@lunora/errors";import{EXIT_CODE as i,exitCodeForError as g}from"./EXIT_CODE-08cwt3MK.mjs";import{createLogger as f}from"./createLogger-Cl18I8AX.mjs";import{p as u,l as E,r as C,a as L}from"./render-lunora-error--4tmM6mt.mjs";import{P as F}from"./prompt-cancelled-BvsNxg_Q.mjs";const m=(s,r)=>{s!=="json"||r.delegated===!0||L({code:r.code,data:r.data,error:r.error})},N=s=>async r=>{const t=f(),a=u(r.commandName,r.options.format);if("error"in a){t.error(a.error),r.process.exit(i.USAGE);return}const{format:o}=a;try{const e=await s({argument:r.argument,cwd:r.process.cwd,format:o,logger:E(o,t),options:r.options});m(o,e),r.process.exit(e.code)}catch(e){if(e instanceof F){r.process.exit(i.CANCELLED);return}const n=e instanceof Error?e.message:String(e),c=g(e);t.error(d(e)||p(n)!==void 0?C(e):n),m(o,{code:c,error:n}),r.process.exit(c)}};export{N as d};
@@ -0,0 +1,13 @@
1
+ import{existsSync as $,readFileSync as k,writeFileSync as y,mkdirSync as R,lstatSync as _}from"node:fs";import{join as g,relative as T,dirname as b}from"@visulima/path";import{EXIT_CODE as m}from"./EXIT_CODE-08cwt3MK.mjs";import{p as V,d as M,e as q,s as j,f as B,g as J,h as H,j as X,k as P,c as Y,l as z}from"./resolve-DUCSc7jQ.mjs";import{s as u,c as Q,b as Z}from"./catalog-CahzmDLV.mjs";import{findWranglerFile as K,readWranglerJsonc as ee}from"@lunora/config/cloudflare";import{LunoraError as N}from"@lunora/errors";import{insertSchemaExtension as re}from"./insertSchemaExtension-DuiV6cba.mjs";import{createHash as te}from"node:crypto";import{installArgsFor as ne,detectPackageManager as se}from"@lunora/config";const A=1,oe=".lunora-registry.json",G=e=>g(e,"lunora",oe),ie=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,x=e=>te("sha256").update(e).digest("hex"),ae=e=>{const t=G(e);if(!$(t))return{items:{},version:A};try{const n=JSON.parse(k(t,"utf8"));if(ie(n))return{items:n.items,version:A}}catch{}return{items:{},version:A}},ce=(e,t)=>{y(G(e),`${JSON.stringify(t,void 0,2)}
2
+ `,"utf8")},C=(e,t,n,o)=>{const r=e.items[t]??{files:{}};e.items[t]=r,r.files[n]=x(o)},de=(e,t,n)=>e.items[t]?.files[n],F=3,I=e=>e===""?[]:e.split(`
3
+ `),ue=(e,t)=>{const n=I(e),o=I(t);let r=0;for(;r<n.length&&r<o.length&&n[r]===o[r];)r+=1;let s=n.length,i=o.length;for(;s>r&&i>r&&n[s-1]===o[i-1];)s-=1,i-=1;if(r===s&&r===i)return[];const a=[];for(let c=Math.max(0,r-F);c<r;c+=1)a.push(` ${n[c]??""}`);for(let c=r;c<s;c+=1)a.push(`- ${n[c]??""}`);for(let c=r;c<i;c+=1)a.push(`+ ${o[c]??""}`);for(let c=i;c<Math.min(o.length,i+F);c+=1)a.push(` ${o[c]??""}`);return a},fe=/\.[cm]?[jt]sx?$/u,L=(e,t,n,o)=>{const r=g(e,t.from);if(_(r).isSymbolicLink())throw new N("INTERNAL",`registry item "${o}": refusing to read "${t.from}" — it is a symlink, not a regular file`);const s=k(r,"utf8");return n&&fe.test(t.to)?q(s):s},le=e=>`import { defineSchema } from "${e?"lunorash/server":"@lunora/server"}";
4
+
5
+ export default defineSchema({});
6
+ `,me=(e,t,n,o,r,s,i)=>{const a=g(o,"lunora","schema.ts");if(s)return r.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:a};const c=g(o,e.to);$(c)||(R(b(c),{recursive:!0}),y(c,L(n,e,i,t),"utf8"));const d=$(a)?k(a,"utf8"):le(i),f=re(d,t);if(f.ok)return R(b(a),{recursive:!0}),y(a,f.text,"utf8"),r.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:a};if(f.reason==="already-applied")return r.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:a};throw f.reason==="invalid-identifier"?new N("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new N("INTERNAL",`schema-extension merge failed for "${t}": ${f.reason}`)},pe=(e,t,n,o,r)=>{const s=ue(t,n);if(s.length===0){r.info(`= ${e.to} (unchanged)`);return}r.info(`${o?"~":"+"} ${e.to}`);for(const i of s)r.info(` ${i}`)},he=(e,t,n,o,r,s,i,a)=>{const c=g(o,e.to),d=L(n,e,a,t),f=$(c),l=f?k(c,"utf8"):"",p=S=>(R(b(c),{recursive:!0}),y(c,d,"utf8"),C(s,t,e.to,d),r.success(`${S}: ${e.to}`),{kind:"written",path:c});if(i.diff)return pe(e,l,d,f,r),{kind:"skipped",path:c};if(!f)return p("write");const v=x(l);if(v===x(d))return C(s,t,e.to,d),r.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:c};if(i.overwrite)return p("overwrite");const h=de(s,t,e.to);return h===void 0?(r.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:c}):h===v?p("update"):h===x(d)?(r.warn(`skip (locally edited): ${e.to}`),{kind:"skipped",path:c}):(y(`${c}.new`,d,"utf8"),r.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:c})},ge=(e,t,n,o,r,s,i={},a=!1)=>e.merge==="schema-extension"?me(e,t,n,o,r,i.diff===!0,a):he(e,t,n,o,r,s,i,a),U=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],$e=e=>{const t=K(e);if(t===void 0)return;const{parsed:n}=ee(t);return typeof n?.main=="string"?n.main:void 0},ye=e=>{const t=$e(e),n=t===void 0?U:[t,...U];for(const o of n){const r=g(e,o);if(!$(r))continue;const s=k(r,"utf8");if(!s.includes("createShardDO(")){if(o===t)break;continue}return{entryPath:r,main:o,source:s}}},ve=(e,t,n)=>{const o=T(b(e),g(t,"lunora",n)).replaceAll("\\","/");return o.startsWith(".")?o:`./${o}`},we=(e,t)=>{for(const n of e){const r=`Add \`export * from "${`./lunora/${n.module}.js`}"\` to your worker entry`,s=n.comment?` (${n.comment})`:"";t.warn(`${r}${s}`)}return 0},ke=(e,t,n,o)=>{const r=[];for(const s of e){const i=ve(t,n,s.module),a=i.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${a}\.js["']`,"u").test(o)||(s.comment&&r.push(`
7
+ // ${s.comment}`),r.push(`export * from "${i}.js";`))}return r},Se=(e,t,n,o)=>{if(e.length===0)return 0;const r=ye(t);if(r===void 0)return we(e,n);const s=ke(e,r.entryPath,t,r.source);if(s.length===0)return 0;if(o){for(const a of s)a!==""&&n.info(`~ entrypoint: ${a}`);return s.length}const i=r.source.endsWith(`
8
+ `)?"":`
9
+ `;return y(r.entryPath,`${r.source}${i}${s.join(`
10
+ `)}
11
+ `,"utf8"),n.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${T(t,r.entryPath)}`),s.length},D=(e,t,n,o={})=>{const r=[],s=[],i=[],a=[],c=ae(t),d=V(t);try{for(const{directory:f,manifest:l}of e){for(const v of l.files){const h=ge(v,l.name,f,t,n,c,o,d);(h.kind==="written"?r:s).push(h.path)}if(l.entrypointReexports!==void 0&&Se(l.entrypointReexports,t,n,o.diff===!0),o.diff)continue;const p=M(l,t,n,d,o.pinnedVersions);i.push(...p.deps),a.push(...p.bindings)}}finally{!o.diff&&Object.keys(c.items).length>0&&ce(t,c)}return{bindings:a,deps:i,skipped:s,written:r}},E=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),De=(e,t,n,o,r)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const i=s.value;return{...s,value:i.map(a=>typeof a=="object"&&a!==null&&a[n.key]===n.value?{...a,[o]:r}:a)}})}:e,W=(e,t,n)=>{const o=t.title??t.description;e.info(`plan: ${u(t.name)}${o?` — ${u(o)}`:""}`);for(const r of t.files)e.info(` file ${u(r.to)} (${u(r.merge)})`);for(const[r,s]of Object.entries(t.deps??{}))e.info(` dep ${u(r)}@${u(P(s,n,r))}`);for(const[r,s]of Object.entries(t.devDependencies??{}))e.info(` dev ${u(r)}@${u(P(s,n,r))}`);for(const r of t.bindings??[])e.info(` bind ${u(r.path.join("."))} = ${u(JSON.stringify(r.value))}`);for(const r of t.envVars??[]){const s=r.secret?" (secret)":` = ${u(JSON.stringify(r.value??""))}`;e.info(` env ${u(r.name)}${s}`)}for(const r of t.entrypointReexports??[]){const s=`./lunora/${u(r.module)}`,i=r.comment?` // ${u(r.comment)}`:"";e.info(` entry ${s}${i}`)}},xe=e=>e.map(({manifest:t})=>({bindings:(t.bindings??[]).map(n=>({path:n.path.join("."),value:n.value})),deps:Object.keys(t.deps??{}),devDependencies:Object.keys(t.devDependencies??{}),entrypointReexports:(t.entrypointReexports??[]).map(n=>({module:n.module,...n.comment?{comment:n.comment}:{}})),envVars:(t.envVars??[]).map(n=>({name:n.name,...n.secret?{secret:!0}:{value:n.value??""}})),files:t.files.map(n=>({merge:n.merge,to:n.to})),name:t.name,requires:t.requires??[],title:t.title})),be=e=>{try{const{args:t,command:n}=ne(se(e));return`${n} ${t.join(" ")}`}catch{return"<your-package-manager> install"}},Ee=(e,t,n,o,r,s)=>{r.success(`add complete: ${String(n)} written, ${String(o)} skipped`),r.info("next steps:"),r.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&r.info(` ${be(s)} # install newly-added dependencies`);for(const{manifest:i}of e)i.docs&&r.info(`${u(i.name)}: ${u(i.docs)}`)},Ae=async e=>{const t=E(),n=j("list",e);if(n)return e.logger.error(n),{...t,code:m.USAGE,error:n};const{logger:o}=e;let r=()=>{};try{const s=await X(e);r=s.cleanup;const i=Q(s.root);if(e.format==="json")return{...t,data:{items:i}};o.info(`available registry items (${String(i.length)}):`);for(const a of i)o.info(` ${a.name}${a.description?` — ${a.description}`:""}`);return t}catch(s){const i=u(`list failed: ${s instanceof Error?s.message:String(s)}`);return o.error(i),{...t,code:1,error:i}}finally{r()}},Te=async e=>{const t=e.cwd??process.cwd(),n=E();if(e.list)return Ae(e);const{logger:o}=e;if(e.names.length===0){const i="add requires at least one item name. Usage: lunora registry add <name> [...names]";return o.error(i),{...n,code:m.USAGE,error:i}}const r=j("add",e);if(r)return o.error(r),{...n,code:m.USAGE,error:r};let s=[];try{const{cleanups:i,items:a}=await B(e.names,e);s=i;const{transformManifest:c}=e,d=c?a.map(w=>({...w,manifest:c(w.manifest)})):a,f=await J(d.map(w=>w.manifest));for(const{manifest:w}of d)W(o,w,f);const l={items:xe(d)};if(e.dryRun)return o.info("dry-run: stopping before any files are written"),{...n,data:l};if(e.diff)return D(d,t,o,{diff:!0}),o.info("diff: preview only — re-run without --diff to apply"),{...n,data:l};const p=await H(d,e);if(!p.ok)return p.reason==="declined"?{...n,code:m.CANCELLED,data:l,error:"registry add: the package.json change was declined"}:{...n,code:m.USAGE,data:l,error:"registry add: stdin is not a TTY — re-run with --yes to confirm"};const{bindings:v,deps:h,skipped:S,written:O}=D(d,t,o,{overwrite:e.overwrite,pinnedVersions:f});return Ee(d,h,O.length,S.length,o,t),{bindings:v,code:0,data:l,deps:h,skipped:S,written:O}}catch(i){const a=u(`add failed: ${i instanceof Error?i.message:String(i)}`);return o.error(a),{...n,code:1,error:a}}finally{for(const i of s)i()}},Je=async e=>{const t=E();if(e.names.length===0){const r="view requires an item name. Usage: lunora registry view <name>";return e.logger.error(r),{...t,code:m.USAGE,error:r}}const n=j("view",e);if(n)return e.logger.error(n),{...t,code:m.USAGE,error:n};const o=[];try{for(const r of e.names){const{cleanup:s,directory:i}=await Y(r,e);o.push(s);const a=z(i,r);W(e.logger,a,await J([a]));for(const c of a.files){e.logger.info(`--- ${u(c.to)} (${u(c.merge)}) ---`);const d=L(i,c,!1,r);for(const f of d.split(`
12
+ `))e.logger.info(u(f))}}return t}catch(r){return e.logger.error(u(`view failed: ${r instanceof Error?r.message:String(r)}`)),{...t,code:1}}finally{for(const r of o)r()}},Ge=async e=>{const t=E(),n=e.from;if(n===void 0){const s="registry build requires --from <registry root>";return e.logger.error(s),{...t,code:m.USAGE,error:s}}if(!$(n)){const s=`registry root not found: ${n}`;return e.logger.error(s),{...t,code:m.NOT_FOUND,error:s}}const o=Z(n),r=e.out??g(n,"index.json");if(e.check){const s=$(r)?JSON.parse(k(r,"utf8")):{items:[]};if(JSON.stringify(s.items??[])!==JSON.stringify(o.items)){const a=`registry: ${r} is stale — run \`lunora registry build\` to regenerate it`;return e.logger.error(a),{...t,code:m.USAGE,error:a}}return e.logger.success(`registry: ${r} is up to date (${String(o.items.length)} items)`),t}return y(r,`${JSON.stringify({$schema:"./schema/registry.schema.json",...o},void 0,4)}
13
+ `,"utf8"),e.logger.success(`registry: wrote ${r} (${String(o.items.length)} items)`),t};export{Ge as a,Je as b,Te as r,De as s};
@@ -0,0 +1,2 @@
1
+ import{STEP_BADGE_NAMES as i,LunoraReporter as u}from"@lunora/config";import{JsonReporter as d}from"@visulima/pail/reporter/json";import{createPail as l}from"@visulima/pail/server";let n,c=!1,a;const P=r=>{a=r},p=()=>{if(c)return!0;const r=process.env.LUNORA_LOG_JSON;return r==="1"||r==="true"},f=r=>new r,m=()=>[f(p()?d:u)],_=()=>{c||(c=!0,n=void 0)},L=Object.fromEntries(i.map(r=>[r,{label:r,logLevel:"informational"}])),g=new WeakSet,E=r=>g.has(r),t=()=>(n??=l({reporters:m(),scope:["lunora"],stderr:process.stderr,stdout:process.stdout,types:L}),n),v=()=>{if(a!==void 0)return a;const r={debug:e=>{t().debug(e)},error:e=>{t().error(e)},info:e=>{t().info(e)},success:e=>{t().success(e)},warn:e=>{t().warn(e)}};return g.add(r),r},O=()=>{const r=(o,s)=>{process.stderr.write(`${o} ${s}
2
+ `)},e={debug:o=>{r("debug",o)},error:o=>{r("error",o)},info:o=>{r("info ",o)},success:o=>{r("ok ",o)},warn:o=>{r("warn ",o)}};return g.add(e),e},R=new Proxy({},{get(r,e){const o=t(),s=o[e];return typeof s=="function"?s.bind(o):s}}),J=(r,e)=>{t()[r](e)};export{v as createLogger,O as createStderrLogger,_ as forceJsonLogging,E as isProcessStreamLogger,J as logStep,R as pail,P as setCommandLogger};
@@ -0,0 +1 @@
1
+ import{spawn as S}from"node:child_process";import{LunoraError as f}from"@lunora/errors";const w=/[\s"%&<>^|]/u,m=/(\\*)"/gu,E=/(\\+)$/u,h=(t,s,a=process.platform)=>{if(a!=="win32"||t===process.execPath)return{args:[...s],command:t,shell:!1};const o=e=>e===""?'""':w.test(e)?`"${e.replaceAll(m,String.raw`$1$1\"`).replace(E,"$1$1")}"`:e;return{args:s.map(e=>o(e)),command:o(t),shell:!0}},_=t=>new Promise((s,a)=>{const o=typeof t.input=="string",e=t.captureStdout===!0,u=t.captureStdoutSilently===!0;let i="inherit";e||u?i="pipe":t.stdoutToStderr&&(i=2);const c=h(t.command,t.args),r=S(c.command,c.args,{cwd:t.cwd??process.cwd(),env:t.env?{...process.env,...t.env}:process.env,shell:c.shell,stdio:[o?"pipe":"inherit",i,t.captureStderr===!0?"pipe":"inherit"]});let p="",d="";t.captureStderr===!0&&r.stderr&&r.stderr.on("data",n=>{d+=n.toString("utf8"),process.stderr.write(n)}),(e||u)&&r.stdout&&r.stdout.on("data",n=>{p+=n.toString("utf8"),e&&process.stdout.write(n)}),r.on("error",n=>{if(n.code==="ENOENT"){a(new f("LOCAL_DEPENDENCY_MISSING",`\`${t.command}\` is not installed or not on your PATH — nothing was run.`,{cause:n}));return}a(n)}),r.on("exit",(n,l)=>{s({code:n??(l?1:0),stderr:t.captureStderr===!0?d:void 0,stdout:e||u?p:void 0})}),o&&r.stdin&&(r.stdin.on("error",()=>{}),r.stdin.end(t.input))}),A=(t=0)=>{const s=[];return{calls:s,spawner:o=>(s.push({descriptor:o}),Promise.resolve({code:t}))}};export{A as createRecordingSpawner,_ as defaultSpawner,h as spawnShellCompat};
@@ -0,0 +1 @@
1
+ import{LunoraError as a}from"@lunora/errors";import{deployTargetIds as s,DEFAULT_DEPLOY_TARGET as i,resolveTargetOrThrow as g,isRunnableTarget as c,runnableTargetIds as l}from"@lunora/config";const o=["both","none","openapi","openrpc"],p=o.join(" | "),f=r=>{if(!(typeof r!="string"||r.length===0)){if(o.includes(r))return r;throw new a("INTERNAL",`invalid --api-spec "${r}" — expected one of: ${p}`)}},T=(()=>{const r=s();return r.length>1?`${r.join(" | ")} (default ${i})`:r.join(" | ")})(),A={description:`Deploy target: ${T}. Also settable as "target" in lunora.config.*`,name:"target",type:String},d=(r,t)=>{try{return{target:g(r,t)}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},h=(r,t)=>{const e=d(r,t);if(e.target===void 0)return e;if(!c(e.target)){const n=l();return{error:`deploy target "${e.target}" has no command-line toolchain, so the Lunora CLI cannot deploy or serve it — it can only generate for it (\`lunora codegen --target ${e.target}\`). Deployable targets: ${n.join(", ")}`}}return e};export{p as A,A as T,h as a,f as p,d as r};
@@ -0,0 +1,5 @@
1
+ import{quoteIdentifier as a,sqlAffinityForKind as $,frameworkColumnDdl as y,OCC_VERSION_COLUMN as T,MAX_D1_TABLE_COLUMNS as d,columnRef as g,physicalIndexName as c}from"@lunora/d1/dialect";import{LunoraError as E}from"@lunora/errors";const v=e=>$(e),f=(e,i)=>{const o=[a(e),i.sqlType];return i.nullable||o.push("NOT NULL"),o.join(" ")},L=e=>{const i=Object.entries(e.columns).map(([s,r])=>` ${f(s,r)}`),o=[...y(),`${a(T)} INTEGER`],n=o.length+i.length;if(n>d)throw new E("VALIDATION_ERROR",`table "${e.name}" needs ${String(n)} columns, over D1's ${String(d)}-column limit — split the table, or move the extra fields into one object field`);const t=[...o.map(s=>` ${s}`),...i].join(`,
2
+ `);return`CREATE TABLE IF NOT EXISTS ${a(e.name)} (
3
+ ${t}
4
+ );`},O=e=>`DROP TABLE IF EXISTS ${a(e)};`,C=(e,i,o)=>`ALTER TABLE ${a(e)} ADD COLUMN ${f(i,o)};`,m=(e,i)=>{const o=i.fields.map(t=>g(t)).join(", ");return`CREATE ${i.unique?"UNIQUE ":""}INDEX IF NOT EXISTS ${c(e,i.name)} ON ${a(e)} (${o});`},N=(e,i)=>`DROP INDEX IF EXISTS ${c(e,i)};`,u=e=>e.field===void 0?void 0:JSON.stringify({...e.field,optional:void 0}),I="https://lunora.sh/docs/concepts/migrations#relaxing-not-null-on-a-d1-table",S=(e,i,o,n,t)=>{const s=u(o),r=u(n);if(o.sqlType!==n.sqlType)t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${i}: ${o.sqlType} → ${n.sqlType} (write SQL manually)`});else if(s!==void 0&&r!==void 0&&s!==r){const l=o.field?.kind===n.field?.kind?`${String(n.field?.kind)} shape/constraints changed`:`${String(o.field?.kind)} → ${String(n.field?.kind)}`;t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${i}: ${l} (write SQL manually)`})}if(o.nullable!==n.nullable){const l=n.nullable?`rebuild the table — ${I}`:"write SQL manually";t.push({kind:"columnTypeChange",summary:`nullability change on ${e}.${i}: ${o.nullable?"NULL":"NOT NULL"} → ${n.nullable?"NULL":"NOT NULL"} (${l})`})}},b=(e,i,o,n,t)=>{for(const[s,r]of Object.entries(o)){const l=i[s];if(l===void 0){n.push({kind:"addColumn",sql:C(e,s,r),summary:`ADD COLUMN ${e}.${s}`});continue}S(e,s,l,r,t)}for(const s of Object.keys(i))o[s]===void 0&&t.push({kind:"dropColumn",summary:`DROP COLUMN ${e}.${s} (SQLite drop-column requires careful migration — write SQL manually)`})},q=(e,i,o,n,t)=>{for(const[s,r]of Object.entries(o)){const l=i[s];if(l===void 0){n.push({kind:"createIndex",sql:m(e,r),summary:`CREATE INDEX ${s} ON ${e}`});continue}(!(l.fields.length===r.fields.length&&l.fields.every((p,h)=>p===r.fields[h]))||l.unique!==r.unique)&&t.push({kind:"indexRename",summary:`index ${s} changed on ${e} — drop+create manually if intentional`})}for(const s of Object.keys(i))o[s]===void 0&&n.push({kind:"dropIndex",sql:N(e,s),summary:`DROP INDEX ${s}`})},D=(e,i,o)=>{o.push({kind:"createTable",sql:L(i),summary:`CREATE TABLE ${e}`});for(const n of Object.values(i.indexes))o.push({kind:"createIndex",sql:m(e,n),summary:`CREATE INDEX ${n.name} ON ${e}`})},w=(e,i)=>{const o=e?.tables??{},n=[],t=[];for(const[s,r]of Object.entries(i.tables)){const l=o[s];if(l===void 0){D(s,r,n);continue}b(s,l.columns,r.columns,n,t),q(s,l.indexes,r.indexes,n,t)}for(const s of Object.keys(o))i.tables[s]===void 0&&n.push({kind:"dropTable",sql:O(s),summary:`DROP TABLE ${s}`});return{empty:n.length===0&&t.length===0,entries:n,unsupported:t}},x=(e,i,o)=>{const n=[`-- Lunora migration: ${e}`,`-- Generated at ${o}`,"-- This file was produced by `lunora migrate generate`. Review carefully before applying.",""];for(const t of i.entries)n.push(`-- ${t.summary}`,t.sql,"");if(i.unsupported.length>0){n.push("-- ---------------------------------------------------------------","-- The following deltas are NOT auto-generated in v0.1.","-- Write the appropriate SQL below by hand:","--");for(const t of i.unsupported)n.push(`-- * ${t.summary}`);n.push("-- ---------------------------------------------------------------","")}return i.empty&&n.push("-- No changes detected. Re-running `lunora migrate generate` will overwrite this file.",""),n.join(`
5
+ `)};export{w as diffSnapshots,C as renderAddColumn,m as renderCreateIndex,L as renderCreateTable,N as renderDropIndex,O as renderDropTable,x as renderMigrationFile,v as validatorKindToSqlType};
@@ -0,0 +1 @@
1
+ import{spawnSync as r}from"node:child_process";const s=()=>{try{return r("docker",["info"],{stdio:"ignore"}).status===0}catch{return!1}},t=()=>{if(typeof process.env.BUILDKIT_HOST!="string"||process.env.BUILDKIT_HOST.length===0)return!1;try{return r("railpack",["--version"],{stdio:"ignore"}).status===0}catch{return!1}};export{t as a,s as i};
@@ -0,0 +1,12 @@
1
+ import{createReadStream as N}from"node:fs";import{open as Ye,stat as k,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}from"./admin-url-BhF5ufg1.mjs";import{EXIT_CODE as $,isRefusal as et}from"./EXIT_CODE-08cwt3MK.mjs";import{join as b,resolve as U,basename as p,dirname as pe,relative as tt,sep as rt}from"node:path";import{createInterface as F}from"node:readline";import nt from"adm-zip";import{i as ye}from"./path-containment-CgxYZggb.mjs";import{Transform as st}from"node:stream";import{createInflateRaw as ot,crc32 as it}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{parse as at}from"csv-parse/sync";import{parse as be}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as ct}from"@lunora/runtime";import{S as B,a as dt,I as lt}from"./shared-D-zCOmgY.mjs";import{createHash as ut}from"node:crypto";const ft=67324752,O=30,ht=26,gt=28,se=0,mt=8,pt=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)!==ft)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+O+n.readUInt16LE(ht)+n.readUInt16LE(gt)}finally{await r.close()}},oe=e=>{let t=0;return new st({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=it(r,t),s(void 0,r)}})},yt=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!==mt)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 pt(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=ot(),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("_"),bt=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"},wt=async e=>{const t=await k(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new nt(e);return{kind:"zip",storagePrefix:bt(r),zip:r,zipPath:e}}},$t=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 k(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},St=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},vt=async e=>{const t=e.kind==="directory"?await $t(e.root):St(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 yt(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()}},Nt=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,Et=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))}},Tt=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"],At=e=>Ne.includes(e),It=/^\\x([\dA-Fa-f]*)$/,ae=/^[+-]?\d+$/,Ee=/[+-]\d{2}$/,Te=/(?:Z|[+-]\d{2}:\d{2})$/i,Ae=/^\+/,_t=/e/i,Rt=/e/i,Ot=e=>{const[t="0",r="0"]=e.split(Rt),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=(_t.test(e.trim())?Ot(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},kt=(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=It.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 kt(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}},xt="auth.",Ct=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),jt=String.raw`\N`,_e=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===jt?null:e,Pt=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),Ut=async(e,t)=>Se(e,t,{authFiles:Pt(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(xt),tableNameOf:r=>p(r,".csv")},async r=>x(r,{withFileTypes:!0})),Ft=(e,t,r)=>{const n=t?.idColumn??"id",s=t?.types??{},o={};let i=!1;for(const[a,c]of Object.entries(e)){if(Ct.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},Mt=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=Ft(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}},zt=async function*(e,t,r,n,s){yield*Le("supabase",s,t,r,n),yield*ve(e,r,n,o=>Mt(o,t))},Dt=/^\d+$/,Bt=/[+-]\d{2}$/,M=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&Dt.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Bt.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},Jt=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]}},Vt=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]}},Ht=(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=Jt(n),i=Vt(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}},Gt=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}},Wt=(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 at(t,{cast:_e,columns:!0,skipEmptyLines:!0})},Xt=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},Yt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Oe(V(e,r)),s=await Xt(e,t.auth?.identitiesFile);return n.map(o=>Ht(o,s.get(o.id??"")??[]))},Kt=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=>Gt(i))},Le=async function*(e,t,r,n,s){if(r?.auth?.file===void 0)return;const o=e==="supabase"?await Yt(t,r):await Kt(t,r);n.info(`auth: ${String(o.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Wt(o,s))yield i},le=/\.(?:nd)?json$/i,ke=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},qt=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},Zt=(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")},Qt=(e,t)=>{const r=typeof e=="string"?Date.parse(e):qt(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},er=(e,t)=>typeof e=="string"?e:Zt(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 Qt(e.timestampValue,t);if(e.bytesValue!==void 0)return er(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 ke(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)}`)},tr=new Set(["createTime","fields","name","readTime","updateTime"]),rr=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},nr=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>tr.has(r))&&!rr(t)},z=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,xe(n,`${t}.${r}`)])),sr=(e,t,r,n)=>{const s=nr(e),o=z(s?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?ke(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}},or=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})),ir=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()}},ar=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: [...] }\``)},cr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?ir(e.file):await ar(e.file);let s=0;for await(const o of n)yield sr(o.raw,o.fallbackId,r,`${e.table}[${String(s)}]`),s+=1},dr=async function*(e,t,r,n,s){yield*Le("firebase",s,t,r,n),yield*ve(e,r,n,o=>cr(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},lr=(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(!At(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}},ur=(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`)}},fr=(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,lr(n,`${t}: tables.${r}`)]))}},hr=(e,t)=>{const r=H(e,t),n=A(r,"keyPrefix",t),{auth:s,tables:o}=r;return ur(s,t),{auth:s,keyPrefix:n,tables:fr(o,t)}},je=e=>b("lunora",`import-${e}.json`),gr=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 hr(i,s)},mr=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}},pr=8,yr=24*1048576,br=1e3,wr=/^[\dA-F]{64}$/i,$r=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},Sr=/^[\d+/A-Z]{43}=$/i,vr=e=>wr.test(e)?e.toLowerCase():Sr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,Nr=(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=vr(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"||!$r(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(Nr(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=ct,C=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,W=async(e,t)=>await mr(async r=>{const n=`${e.baseUrl}${B}?prefix=${encodeURIComponent(t)}&limit=${String(br)}${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}}),Er=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},Tr=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${B}?key=${encodeURIComponent(t)}${C(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,Ar=async(e,t,r,n,s)=>{const o=`${e.baseUrl}${dt}?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 Tr(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?Er(e,t,r,n):Ar(e,t,r,n,s)},Ir=e=>{const t=[];let r=[],n=0;for(const s of e)r.length>0&&(r.length>=pr||n+s.size>yr)&&(t.push(r),r=[],n=0),r.push(s),n+=s.size;return r.length>0&&t.push(r),t},_r=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 Nt(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 Ir(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*Rr(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*Or(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*Rr(e,o,s)}}const Wn=["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 gr(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 Ut(e.file,n)}:{collections:await or(e.file,n),kind:"firebase",mapping:n}},kr=async e=>{if(!await k(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},xr=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},Cr=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return Lr(e,e.from,t);const r=await wt(e.file),n=r===void 0?void 0:await vt(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 kr(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 xr(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},L=b("lunora","import-convex.json"),jr=(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}},Pr=async(e,t)=>{const r=b(e,L);let n;try{n=await v(r,"utf8")}catch(o){if(o.code==="ENOENT"){t.info(`no ${L} 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 jr(s,r)},Ur=(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})}},Fr=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(Ur(a,t.table,o),n,t.table);for(const{column:d}of c)s.includes(d)||s.push(d)}return s},Mr=async(e,t,r)=>{const n={};for(const s of t){if(we(s.table))continue;const o=await Fr(e,s,r);o.length>0&&(n[s.table]=o)}return n},zr=async(e,t,r)=>{const n=b(t,L),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)}},Dr=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 Mr(e,t,i)};return await zr(a,r,n),a},S=20,Br=(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`)},Jr=(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 ${L} 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),Vr=(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,Hr=/^\\x[\dA-Fa-f]*$/,Gr=/^[+-]?\d+$/,Wr=/^[+-]?\d+\.\d+$/,Xr=/^\{.*\}$/,Yr=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,Kr=[["bytea-base64",e=>Hr.test(e)],["timestamp-ms",e=>Yr.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Gr.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>Wr.test(e)],[e=>e.every(t=>Xr.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],qr=e=>{if(e.length!==0){for(const[t,r]of Kr)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},Zr=(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)}},Qr=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(Zr(o,t),n+=1,n>=fe)break;r.destroy();const s={};for(const[o,i]of t){const a=qr(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)}},en=async(e,t,r)=>{const n={};for(const o of e){const i=await Qr(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},tn=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`),rn=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},nn=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,sn=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),on=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 on(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}},an=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)}/${sn(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},cn=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:tt(t,a).split(rt).join("/")})}};return await n(t),r},dn=async(e,t,r,n,s)=>{const o=await t.bytes(),i=ut("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 nn(r.cwd,r.source,{key:a,path:t.path,size:o.length}),a},ln=(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 rn(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=ln(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 dn(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=/^\/+/,un=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,fn=/[#?]/u,hn=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},gn=e=>{const t=un.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(fn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},mn=(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=gn(e);return o===void 0?void 0:t.get(o)??t.get(o.replace(ge,""))},pn=500,yn=9e5,bn=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 k(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??globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${lt}`,token:r}},wn=(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}:{}}),$n=(e,t,r,n)=>{switch(e.kind){case"convex":return Or(e.snapshot,e.tables,t.logger,r,n);case"firebase":return dr(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return zt(e.tables,e.mapping,t.logger,n,t.file);default:return N(t.file,{encoding:"utf8"})}},Sn=async(e,t,r)=>{switch(e.kind){case"convex":return Dr(e.snapshot,e.tables,t,r);case"firebase":return tn(e.collections,t,r);case"supabase":return en(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},vn=async(e,t,r,n)=>{const s=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return he(e,await cn(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 an({serviceKey:i,url:c},e.fetchImpl,r.logger);return he(e,d,{cwd:n,keyPrefix:s,source:t.kind},r.logger)},Nn=(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=mn(c,r);d===void 0?s.add(`${t}.${a}: ${c}`):i[a]=d}return i},En=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:hn(r);return Tt({remapDocument:n===void 0||t===void 0?void 0:(s,o)=>Nn(s,o,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},Tn=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){return n.error(`import failed part-way through: ${a instanceof Error?a.message:String(a)}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)"),a}},An=async(e,t,r,n)=>{const s=await Pr(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 _r(e,t.snapshot,o,s?.keyPrefix??"",n);return n.info(`storage map: ${String(i.size)} blobs mapped`),{mapping:s,storageIdMap:i}},In=async(e,t,r,n)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return An(e,t,n,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const s=await vn(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}},_n=(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)},Rn=async(e,t,r)=>await Sn(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},Xn=async e=>{const t=e.cwd??process.cwd(),r=await Cr(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 Rn(r,t,e);const n=await bn(e);if(et(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??pn,d=await In({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=$n(r,e,u!==void 0,Y),j=Et({batchSize:c,fetchImpl:o,maxBatchBytes:yn,requestUrl:i,token:a}),Be=En({report:y,source:r,storageColumns:m,storageIdMap:u,table:e.table,transferredPaths:h,unresolvedPaths:g}),K=await Tn(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?Br(e.logger,Y,{conflicts:q,inserted:ee}):0,Ge=u!==void 0&&Jr(e.logger,y,e.verify===!0),We=Vr(e.logger,g,e.verify===!0),_=Object.values(ee).reduce((E,Xe)=>E+Xe,0),R=wn(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)),_n(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{pn as D,Wn as I,Pe as M,C as b,W as l,Xn as r,Ue as u};
@@ -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 @@
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 @@
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};