@lunora/cli 1.0.0-alpha.48 → 1.0.0-alpha.481

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 (146) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +3 -1
  3. package/dist/bin.mjs +3 -10
  4. package/dist/cli.d.mts +31 -0
  5. package/dist/cli.d.ts +31 -0
  6. package/dist/cli.mjs +1 -0
  7. package/dist/index.d.mts +1168 -416
  8. package/dist/index.d.ts +1168 -416
  9. package/dist/index.mjs +1 -19
  10. package/dist/packem_chunks/cli.mjs +2 -0
  11. package/dist/packem_chunks/dispatch.mjs +1 -0
  12. package/dist/packem_chunks/handler.mjs +61 -157
  13. package/dist/packem_chunks/handler10.mjs +2 -16
  14. package/dist/packem_chunks/handler11.mjs +1 -22
  15. package/dist/packem_chunks/handler12.mjs +1 -192
  16. package/dist/packem_chunks/handler13.mjs +1 -131
  17. package/dist/packem_chunks/handler14.mjs +3 -65
  18. package/dist/packem_chunks/handler15.mjs +1 -58
  19. package/dist/packem_chunks/handler16.mjs +1 -80
  20. package/dist/packem_chunks/handler17.mjs +1 -43
  21. package/dist/packem_chunks/handler18.mjs +1 -105
  22. package/dist/packem_chunks/handler19.mjs +1 -170
  23. package/dist/packem_chunks/handler2.mjs +1 -114
  24. package/dist/packem_chunks/handler20.mjs +1 -94
  25. package/dist/packem_chunks/handler21.mjs +7 -94
  26. package/dist/packem_chunks/handler22.mjs +1 -0
  27. package/dist/packem_chunks/handler23.mjs +3 -0
  28. package/dist/packem_chunks/handler24.mjs +3 -0
  29. package/dist/packem_chunks/handler25.mjs +2 -0
  30. package/dist/packem_chunks/handler26.mjs +1 -0
  31. package/dist/packem_chunks/handler27.mjs +2 -0
  32. package/dist/packem_chunks/handler28.mjs +99 -0
  33. package/dist/packem_chunks/handler29.mjs +3 -0
  34. package/dist/packem_chunks/handler3.mjs +1 -204
  35. package/dist/packem_chunks/handler30.mjs +15 -0
  36. package/dist/packem_chunks/handler31.mjs +1 -0
  37. package/dist/packem_chunks/handler32.mjs +1 -0
  38. package/dist/packem_chunks/handler4.mjs +1 -33
  39. package/dist/packem_chunks/handler5.mjs +1 -49
  40. package/dist/packem_chunks/handler6.mjs +3 -91
  41. package/dist/packem_chunks/handler7.mjs +1 -42
  42. package/dist/packem_chunks/handler8.mjs +1 -174
  43. package/dist/packem_chunks/handler9.mjs +1 -315
  44. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  45. package/dist/packem_chunks/runDevCommand.mjs +8 -0
  46. package/dist/packem_chunks/runInitCommand.mjs +423 -1447
  47. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  48. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  49. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck9tABfr.mjs +1 -0
  50. package/dist/packem_shared/EXIT_CODE-DQVhSE-1.mjs +1 -0
  51. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  52. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  53. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  54. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  55. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  56. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  57. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  58. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  59. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  60. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  61. package/dist/packem_shared/command-BpMv2n0o.mjs +1 -0
  62. package/dist/packem_shared/commands-CkuCMUP_.mjs +13 -0
  63. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  64. package/dist/packem_shared/createRecordingSpawner-DchLi0gR.mjs +1 -0
  65. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  66. package/dist/packem_shared/diffSnapshots-Y1G8am6C.mjs +7 -0
  67. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  68. package/dist/packem_shared/export-rows-EzdNDYpa.mjs +3 -0
  69. package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
  70. package/dist/packem_shared/health-probe-BLnoq_oC.mjs +13 -0
  71. package/dist/packem_shared/import-3Y59Ry9F.mjs +13 -0
  72. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  73. package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
  74. package/dist/packem_shared/js-literal-FWLi94Lh.mjs +1 -0
  75. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  76. package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
  77. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  78. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  79. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  80. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  81. package/dist/packem_shared/plan-pog5AvMk.mjs +5 -0
  82. package/dist/packem_shared/planDevCommand-Bl6OrwXm.mjs +1 -0
  83. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  84. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  85. package/dist/packem_shared/render-lunora-error-JsLelWwR.mjs +2 -0
  86. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  87. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  88. package/dist/packem_shared/runAddCommand-gThKW-ZB.mjs +1 -0
  89. package/dist/packem_shared/runDeployCommand-ByBuze9W.mjs +1 -0
  90. package/dist/packem_shared/runExportCommand-_PtkJJDT.mjs +5 -0
  91. package/dist/packem_shared/runMigrateGenerateCommand-CguLEIZp.mjs +11 -0
  92. package/dist/packem_shared/schemaIrToSnapshot-Ck7DSPdf.mjs +1 -0
  93. package/dist/packem_shared/shared-CV7ESvuj.mjs +2 -0
  94. package/dist/packem_shared/storage-3GOIFVZm.mjs +1 -0
  95. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  96. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  97. package/dist/packem_shared/vectorize-metadata-DK61NmVx.mjs +2 -0
  98. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  99. package/dist/packem_shared/wrangler-secrets-C9siMBwN.mjs +1 -0
  100. package/package.json +45 -19
  101. package/skills/README.md +36 -17
  102. package/skills/lunora/SKILL.md +158 -65
  103. package/skills/lunora-cloudflare-audit/SKILL.md +164 -0
  104. package/skills/lunora-create-package/SKILL.md +98 -84
  105. package/skills/lunora-deploy/SKILL.md +212 -102
  106. package/skills/lunora-functions/SKILL.md +367 -60
  107. package/skills/lunora-migration-helper/SKILL.md +194 -149
  108. package/skills/lunora-performance-audit/SKILL.md +137 -95
  109. package/skills/lunora-quickstart/SKILL.md +136 -136
  110. package/skills/lunora-realtime/SKILL.md +219 -97
  111. package/skills/lunora-setup-auth/SKILL.md +203 -101
  112. package/skills/lunora-setup-hyperdrive/SKILL.md +153 -110
  113. package/skills/lunora-setup-hyperdrive-global/SKILL.md +152 -94
  114. package/skills/lunora-setup-mail/SKILL.md +87 -113
  115. package/skills/lunora-setup-scheduler/SKILL.md +133 -97
  116. package/skills/lunora-setup-storage/SKILL.md +189 -95
  117. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  118. package/dist/packem_chunks/runDeployCommand.mjs +0 -594
  119. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  120. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  121. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  122. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  123. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  124. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  125. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  126. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  127. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  128. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  129. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  130. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  131. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  132. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  133. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  134. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  135. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  136. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  137. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  138. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  139. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  140. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  141. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  142. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  143. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  144. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  145. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  146. 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-BpMv2n0o.mjs";import{EXIT_CODE as s}from"../packem_shared/EXIT_CODE-DQVhSE-1.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 _,b as N,a as U}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as P}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as i,exitCodeForStatus as E}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{a as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const y=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const s=a instanceof Error?a.message:String(a);throw new h("INTERNAL",`failed to parse ${t} as JSON: ${s}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new h("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},O=/\/$/u,$="__lunora_admin__:runAs",T="__lunora_admin__:",k=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},p=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.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")},R=({args:r,claims:t,options:e,runAs:a})=>{const s=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:$}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(s.shardKey=e.shard),s},w=({cwd:r,logger:t,needsBearer:e,url:a})=>e?_(a,t,r):(I({cwd:r,url:a})??N(r)).replace(O,""),D=({args:r,claims:t},e)=>{try{return{args:y(r),claims:t===void 0?void 0:y(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},J=async r=>{const t=r.cwd??process.cwd(),{logger:e}=r,a=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!a){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:i.USAGE,error:d,requestUrl:r.url??""}}const s=a||r.functionPath.startsWith(T),n=w({cwd:t,logger:e,needsBearer:s,url:r.url});if(n===void 0)return{body:void 0,code:i.USAGE,error:"could not resolve a usable worker URL",requestUrl:r.url??""};const o=`${n}/_lunora/rpc`,u=r.fetchImpl??U,m=D(r,e);if(m===void 0)return{body:void 0,code:i.USAGE,error:"could not parse --args / --claims as JSON",requestUrl:o};const{source:g,token:l}=s?S({cwd:t,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:i.AUTH,error:d,requestUrl:o}}l!==void 0&&e.debug?.(`admin bearer from ${b(g)}`);const v={"content-type":"application/json",...l===void 0?{}:{authorization:`Bearer ${l}`}},A=R({args:m.args,claims:m.claims,options:r,runAs:a});e.info(`POST ${o} -> ${r.functionPath}${a?` (as ${r.as??""})`:""}`);const c=await u(o,{body:JSON.stringify(A),headers:v,method:"POST"}),f=await k(c,e);return p(e,{body:f,runAs:a,status:c.status}),{body:f,code:c.ok?0:E(c.status),error:c.ok?void 0:`${r.functionPath} failed: HTTP ${String(c.status)}`,requestUrl:o}},j=P(async({argument:r,cwd:t,format:e,logger:a,options:s})=>{const n=r[0];if(!n){const u="missing function path. Usage: lunora run <functionPath> [--args <json>]";return a.error(u),{code:i.USAGE,error:u}}const o=await J({args:s.args,as:s.as,claims:s.claims,cwd:t,format:e,functionPath:n,logger:a,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,k as readAndLogBody,J as runRpcCommand};
@@ -0,0 +1 @@
1
+ import"./shared-CV7ESvuj.mjs";import"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./EXIT_CODE-DQVhSE-1.mjs";import"./tui-prompts-B3YwUhGw.mjs";import{D as I,r as T}from"./import-3Y59Ry9F.mjs";export{I as DEFAULT_IMPORT_BATCH_SIZE,T as runImportCommand};
@@ -0,0 +1 @@
1
+ import{isLunoraError as S,getCatalogEntry as U}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},_=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_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],["INDEX_FIELD_NESTED_PATH",E.USAGE],["LOCAL_DEPENDENCY_MISSING",E.MISSING_DEPENDENCY],["MIGRATION_ID_NOT_STATIC",E.USAGE],["NAMESPACE_COLLISION",E.USAGE],["PUBLISHED_FUNCTION_UNSUPPORTED",E.USAGE],["PUBLISHED_FUNCTION_VISIBILITY_UNKNOWN",E.USAGE],["SCHEMA_SNAPSHOT_PARSE",E.USAGE]]),N=A=>A===void 0?E.FAILURE:_.get(A)??E.FAILURE,T=A=>I.get(A)??N(U(A)?.status),L=A=>S(A)?I.get(A.code)??N(A.status):E.FAILURE,O=A=>"refused"in A;export{E as EXIT_CODE,T as exitCodeForCode,L as exitCodeForError,N as exitCodeForStatus,O 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 c}from"@lunora/config";import{LunoraError as i}from"@lunora/errors";const a=new Set(["127.0.0.1","::1","[::1]","localhost"]),h=/\/$/u,n="http://localhost:8787",l=r=>r===void 0?n:c(r)?.url??n,u=r=>r.replace(h,""),v=(r,s,e)=>{const o=r??l(e);let t;try{t=new URL(o)}catch{s.error(`invalid --url: ${o}`);return}if(!a.has(t.hostname)&&t.protocol!=="https:"){s.error(`refusing to send the admin bearer over ${t.protocol}// to ${t.hostname} — use https for non-localhost targets`);return}return u(o)},f=async(r,s)=>{try{return await fetch(r,s)}catch(e){if(!(e instanceof TypeError))throw e;const o=e.cause instanceof Error?e.cause.message:e.message,t=a.has(new URL(r).hostname)?" — is the dev server running? Start it, or pass --url to point at the worker":"";throw new i("INTERNAL",`could not reach ${r} (${o})${t}`,{cause:e})}};export{f as a,l as b,u as n,v as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";const n=["both","none","openapi","openrpc"],p=n.join(" | "),t=o=>{if(!(typeof o!="string"||o.length===0)){if(n.includes(o))return o;throw new r("INTERNAL",`invalid --api-spec "${o}" — expected one of: ${p}`)}};export{p as A,t as p};
@@ -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
+ const _=R=>R.length>256?`${R.slice(0,256)}… (truncated)`:R;export{_ as c};
@@ -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 @@
1
+ import{fileURLToPath as s}from"node:url";import{readProjectManifest as e}from"@lunora/config/cli";import{findUpSync as a}from"@visulima/fs";import{dirname as t}from"@visulima/path";const m=(i=t(s(import.meta.url)))=>{const o=a(n=>e(n)?.name==="@lunora/cli"?"package.json":void 0,{cwd:i});return o===void 0?void 0:t(o)};let r;const p=()=>{if(r===void 0){const i=m(),o=i===void 0?void 0:e(i)?.version;r=typeof o=="string"&&o!==""?o:"0.0.0"}return r};export{m as f,p as r};
@@ -0,0 +1 @@
1
+ const i="https://api.cloudflare.com/client/v4/accounts",u=async({accountId:t,apiToken:a,fetch:e,init:o,path:l})=>{const n=await(e??globalThis.fetch.bind(globalThis))(`${i}/${encodeURIComponent(t)}${l}`,{...o,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}}),c=await n.text();let s;try{s=JSON.parse(c)}catch{return{ok:!1,status:n.status,text:c}}return!n.ok||typeof s!="object"||s===null||s.success===!1?{ok:!1,status:n.status,text:c}:{body:s,ok:!0}},r=t=>typeof t=="string"&&t.trim().length>0?t.trim():void 0,d=(t,a)=>{const e=r(t.CLOUDFLARE_ACCOUNT_ID)??r(a),o=r(t.CLOUDFLARE_API_TOKEN);return{...e===void 0?{}:{accountId:e},...o===void 0?{}:{token:o}}};export{u as c,r as n,d 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 p,findSolutionByMessage as d}from"@lunora/errors";import{EXIT_CODE as c,exitCodeForError as f}from"./EXIT_CODE-DQVhSE-1.mjs";import{createLogger as g}from"./createLogger-4TujevyB.mjs";import{p as u,l as E,a as C}from"./output-format-DWe_tkTR.mjs";import{P as L}from"./prompt-cancelled-BvsNxg_Q.mjs";import{r as F}from"./render-lunora-error-JsLelWwR.mjs";const m=(t,r)=>{t!=="json"||r.delegated===!0||C({code:r.code,data:r.data,error:r.error})},O=t=>async r=>{const s=g(),a=u(r.commandName,r.options.format);if("error"in a){s.error(a.error),r.process.exit(c.USAGE);return}const{format:o}=a;try{const e=await t({argument:r.argument,cwd:r.process.cwd,format:o,logger:E(o,s),options:r.options});m(o,e),r.process.exit(e.code)}catch(e){if(e instanceof L){r.process.exit(c.CANCELLED);return}const n=e instanceof Error?e.message:String(e),i=f(e);s.error(p(e)||d(n)!==void 0?F(e):n),m(o,{code:i,error:n}),r.process.exit(i)}};export{O 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-DQVhSE-1.mjs";import{c as V,d as M,s as j,e as q,f as J,g as B,h as H,j as P,b as X,k as Y}from"./resolve-Bdc9KEUv.mjs";import{s as u,c as z,b as Q}from"./catalog-CahzmDLV.mjs";import{projectUsesUmbrella as Z}from"@lunora/config";import{findWranglerFile as K,readWranglerJsonc as ee}from"@lunora/config/cloudflare";import{LunoraError as N}from"@lunora/errors";import{insertSchemaExtension as re}from"./insertSchemaExtension-CbTH3lCQ.mjs";import{createHash as te}from"node:crypto";import{installArgsFor as ne,detectPackageManager as se}from"@lunora/config/cli";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)?M(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=Z(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=V(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:[]}),Te=(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 H(e);r=s.cleanup;const i=z(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()}},Je=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 q(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 B(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()}},Ge=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 X(r,e);o.push(s);const a=Y(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()}},We=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=Q(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{We as a,Ge as b,Je as r,Te as s};
@@ -0,0 +1,2 @@
1
+ import{STEP_BADGE_NAMES as i,LunoraReporter as u}from"@lunora/config/cli";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 C}from"node:child_process";import{StringDecoder as v}from"node:string_decoder";import{LunoraError as g}from"@lunora/errors";const D=/[\s"%&<>^|]/u,L=500,N=e=>{let i="",r=0;for(const o of e)o==="\\"?r+=1:(i+=o==='"'?`${"\\".repeat(r*2+1)}"`:`${"\\".repeat(r)}${o}`,r=0);return i+"\\".repeat(r*2)},_=(e,i,r=process.platform)=>{if(r!=="win32"||e===process.execPath)return{args:[...i],command:e,shell:!1};const o=s=>s===""?'""':D.test(s)?`"${N(s)}"`:s;return{args:i.map(s=>o(s)),command:o(e),shell:!0}},x=e=>new Promise((i,r)=>{const o=typeof e.input=="string",s=e.captureStdout===!0,a=e.captureStdoutSilently===!0;let u="inherit";s||a?u="pipe":e.stdoutToStderr&&(u=2);const c=e.captureStderr===!0||e.captureStderrSilently===!0,d=_(e.command,e.args),t=C(d.command,d.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:d.shell,detached:e.timeoutMs!==void 0&&process.platform!=="win32",stdio:[o?"pipe":"inherit",u,c?"pipe":"inherit"]}),p=e.timeoutMs===void 0?void 0:setTimeout(()=>{process.platform==="win32"||t.pid===void 0?t.kill("SIGKILL"):process.kill(-t.pid,"SIGKILL")},e.timeoutMs),f=new v("utf8"),m=new v("utf8");let w="",S="";c&&t.stderr&&t.stderr.on("data",n=>{S+=m.write(n),e.captureStderr===!0&&process.stderr.write(n)}),(s||a)&&t.stdout&&t.stdout.on("data",n=>{w+=f.write(n),s&&process.stdout.write(n)});let l=!1;t.on("error",n=>{if(clearTimeout(p),l=!0,n.code==="ENOENT"){r(new g("LOCAL_DEPENDENCY_MISSING",`\`${e.command}\` is not installed or not on your PATH — nothing was run.`,{cause:n}));return}r(n)});let h=0,T;const E=()=>{l||(l=!0,clearTimeout(T),clearTimeout(p),i({code:h,stderr:c?S+m.end():void 0,stdout:s||a?w+f.end():void 0}))};t.on("exit",(n,I)=>{h=n??(I?1:0),T=setTimeout(()=>{t.stdout?.destroy(),t.stderr?.destroy(),E()},L)}),t.on("close",E),o&&t.stdin&&(t.stdin.on("error",()=>{}),t.stdin.end(e.input))}),P=(e=0)=>{const i=[];return{calls:i,spawner:o=>(i.push({descriptor:o}),Promise.resolve({code:e}))}};export{P as createRecordingSpawner,x as defaultSpawner,_ as spawnShellCompat};
@@ -0,0 +1 @@
1
+ import{resolveTargetOrThrow as n}from"@lunora/config";import{isRunnableTarget as a,runnableTargetIds as s}from"@lunora/config/cli";const g=(e,t)=>{try{return{target:n(e,t)}}catch(r){return{error:r instanceof Error?r.message:String(r)}}},c=(e,t)=>{const r=g(e,t);if(r.target===void 0)return r;if(!a(r.target)){const o=s();return{error:`deploy target "${r.target}" has no command-line toolchain, so the Lunora CLI cannot deploy or serve it — it can only generate for it (\`lunora codegen --target ${r.target}\`). Deployable targets: ${o.join(", ")}`}}return r};export{c as a,g as r};
@@ -0,0 +1,7 @@
1
+ import{quoteIdentifier as a,sqlAffinityForKind as h,frameworkColumnDdl as y,OCC_VERSION_COLUMN as T,MAX_D1_TABLE_COLUMNS as d,columnRef as E,physicalIndexName as c}from"@lunora/d1/dialect";import{LunoraError as L}from"@lunora/errors";const A=e=>h(e),f=(e,i)=>{const s=[a(e),i.sqlType];return i.nullable||s.push("NOT NULL"),s.join(" ")},g=e=>{const i=Object.entries(e.columns).map(([o,r])=>` ${f(o,r)}`),s=[...y(),`${a(T)} INTEGER`],n=s.length+i.length;if(n>d)throw new L("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=[...s.map(o=>` ${o}`),...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,s)=>{const n=`ALTER TABLE ${a(e)} ADD COLUMN ${f(i,{...s,nullable:!0})};`;return s.nullable?n:`${n}
5
+ -- ${a(e)}.${a(i)} is required, so rows written before it read NULL. Backfill them:
6
+ -- UPDATE ${a(e)} SET ${a(i)} = <value> WHERE ${a(i)} IS NULL;`},p=(e,i)=>{const s=i.fields.map(t=>E(t)).join(", ");return`CREATE ${i.unique?"UNIQUE ":""}INDEX IF NOT EXISTS ${c(e,i.name)} ON ${a(e)} (${s});`},S=(e,i)=>`DROP INDEX IF EXISTS ${c(e,i)};`,u=e=>e.field===void 0?void 0:JSON.stringify({...e.field,optional:void 0,refined:void 0}),I="https://lunora.sh/docs/concepts/migrations#relaxing-not-null-on-a-d1-table",b=(e,i,s,n,t)=>{const o=u(s),r=u(n);if(s.sqlType!==n.sqlType)t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${i}: ${s.sqlType} → ${n.sqlType} (write SQL manually)`});else if(o!==void 0&&r!==void 0&&o!==r){const l=s.field?.kind===n.field?.kind?`${String(n.field?.kind)} shape/constraints changed`:`${String(s.field?.kind)} → ${String(n.field?.kind)}`;t.push({kind:"columnTypeChange",summary:`column type change on ${e}.${i}: ${l} (write SQL manually)`})}if(s.nullable!==n.nullable){const l=n.nullable?`rebuild the table — ${I}`:"write SQL manually";t.push({kind:"columnTypeChange",summary:`nullability change on ${e}.${i}: ${s.nullable?"NULL":"NOT NULL"} → ${n.nullable?"NULL":"NOT NULL"} (${l})`})}},q=(e,i,s,n,t)=>{for(const[o,r]of Object.entries(s)){const l=i[o];if(l===void 0){n.push({kind:"addColumn",sql:C(e,o,r),summary:`ADD COLUMN ${e}.${o}`});continue}b(e,o,l,r,t)}for(const o of Object.keys(i))s[o]===void 0&&t.push({kind:"dropColumn",summary:`DROP COLUMN ${e}.${o} (SQLite drop-column requires careful migration — write SQL manually)`})},N=(e,i,s,n,t)=>{for(const[o,r]of Object.entries(s)){const l=i[o];if(l===void 0){n.push({kind:"createIndex",sql:p(e,r),summary:`CREATE INDEX ${o} ON ${e}`});continue}(!(l.fields.length===r.fields.length&&l.fields.every((m,$)=>m===r.fields[$]))||l.unique!==r.unique)&&t.push({kind:"indexRename",summary:`index ${o} changed on ${e} — drop+create manually if intentional`})}for(const o of Object.keys(i))s[o]===void 0&&n.push({kind:"dropIndex",sql:S(e,o),summary:`DROP INDEX ${o}`})},D=(e,i,s)=>{s.push({kind:"createTable",sql:g(i),summary:`CREATE TABLE ${e}`});for(const n of Object.values(i.indexes))s.push({kind:"createIndex",sql:p(e,n),summary:`CREATE INDEX ${n.name} ON ${e}`})},w=(e,i)=>{const s=e?.tables??{},n=[],t=[];for(const[o,r]of Object.entries(i.tables)){const l=s[o];if(l===void 0){D(o,r,n);continue}q(o,l.columns,r.columns,n,t),N(o,l.indexes,r.indexes,n,t)}for(const o of Object.keys(s))i.tables[o]===void 0&&n.push({kind:"dropTable",sql:O(o),summary:`DROP TABLE ${o}`});return{empty:n.length===0&&t.length===0,entries:n,unsupported:t}},U=(e,i,s)=>{const n=[`-- Lunora migration: ${e}`,`-- Generated at ${s}`,"-- 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(`
7
+ `)};export{w as diffSnapshots,C as renderAddColumn,p as renderCreateIndex,g as renderCreateTable,S as renderDropIndex,O as renderDropTable,U as renderMigrationFile,A 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,3 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{E as y,c as N}from"./shared-CV7ESvuj.mjs";const g=async(l,f,h)=>{const n=await l.fetchImpl(`${l.baseUrl}${y}`,{body:JSON.stringify({tables:f}),headers:{authorization:`Bearer ${l.token}`,"content-type":"application/json"},method:"POST"});if(!n.ok)throw new r("INTERNAL",`reading the deployment's rows failed (HTTP ${String(n.status)})`);if(!n.body)throw new r("INTERNAL","reading the deployment's rows failed: the export response carried no body");const s=n.body.getReader(),w=new TextDecoder;let t="",i=0;const c=N(),p=o=>{if(i+=1,o.trim().length===0)return!0;const a=`reading the deployment's rows failed: export line ${String(i)} (${String(o.length)} characters) is not a { table, doc } row`;let e;try{e=JSON.parse(o)}catch{throw new r("INTERNAL",a)}try{if(!c.read(e))return!0}catch{throw new r("INTERNAL",`reading the deployment's rows failed: export line ${String(i)} follows the export's end marker`)}if(e===null||typeof e.table!="string"||e.doc===null||typeof e.doc!="object")throw new r("INTERNAL",a);return h({doc:e.doc,table:e.table})!==!1};try{for(;;){const{done:a,value:e}=await s.read();if(a)break;t+=w.decode(e,{stream:!0});let d=t.indexOf(`
2
+ `);for(;d!==-1;){const m=t.slice(0,d);if(t=t.slice(d+1),!p(m)){await s.cancel().catch(()=>{});return}d=t.indexOf(`
3
+ `)}}if(t.trim().length>0)throw new r("INTERNAL",`reading the deployment's rows failed: the export ended inside line ${String(i+1)}`);const o=c.problem();if(o!==void 0)throw new r("INTERNAL",`reading the deployment's rows failed: ${o}`)}finally{s.releaseLock()}};export{g as f};
@@ -0,0 +1 @@
1
+ import{createServer as s}from"node:net";const c=64,r="127.0.0.1",i=65535,a=(o,e=r)=>new Promise(n=>{const t=s();t.once("error",()=>{n(!1)}),t.once("listening",()=>{t.close(()=>{n(!0)})}),t.listen(o,e)}),l=async(o,e=r,n=c)=>{for(let t=o;t<o+n&&t<=i;t+=1)if(await a(t,e))return t;return o};export{l as f};
@@ -0,0 +1,13 @@
1
+ import{existsSync as F,readFileSync as L,writeFileSync as P}from"node:fs";import{parseSchemaSnapshot as H,SchemaSnapshotParseError as B,evaluateSchemaDrift as q,serializeSchemaSnapshot as I}from"@lunora/codegen";import{decodeWire as y}from"@lunora/wire";import{f as S}from"./export-rows-EzdNDYpa.mjs";const D=new Set(["addedRequiredField","changedFieldKind","changedFieldShape","fieldOptionalToRequired","removedField"]),R=e=>e.table!==void 0&&(e.uniqueOn!==void 0||e.field!==void 0&&D.has(e.type)),E=10,O=e=>e.kind==="id"||e.kind==="storage"||[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(t=>t!==void 0&&O(t)),f=e=>e===null?"null":Array.isArray(e)?"array":e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"bytes":typeof e,b=e=>f(e)==="object",V=/^-?\d+n$/u,K=/\$\{/u,T=e=>{const t=e.trim(),r=t[0];if(t.length>=2&&(r==="'"||r==="`")&&t.endsWith(r)){const n=t.slice(1,-1);return n.includes("\\")||K.test(n)||r==="'"&&n.includes("'")?void 0:{value:n}}if(V.test(t))return{value:BigInt(t.slice(0,-1))};try{return{value:JSON.parse(t)}}catch{return}},m=e=>typeof e=="number"&&Number.isFinite(e),w=(e,t)=>m(e)&&Math.abs(e)<=t,A={any:()=>!0,bigint:e=>typeof e=="bigint",boolean:e=>typeof e=="boolean",bytes:e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),date:m,geoPoint:e=>b(e)&&w(e.lat,90)&&w(e.lng,180),id:e=>typeof e=="string",null:e=>e===null,number:m,storage:e=>typeof e=="string",string:e=>typeof e=="string",timestamp:m},p=(e,t,r)=>{if(t!==void 0)for(const[n,o]of e){const s=g(o,t,r(n));if(s!==void 0)return s}},M={array:(e,t,r)=>Array.isArray(e)?p(e.map((n,o)=>[String(o),n]),t.inner,n=>`${r}[${n}]`):[r,`expected array, found ${f(e)}`],literal:(e,t,r)=>e===T(t.literalValue??"")?.value?void 0:[r,`expected the literal ${t.literalValue??"?"}, found a different ${f(e)}`],object:(e,t,r)=>b(e)?G(e,t.shape??{},`${r}.`):[r,`expected object, found ${f(e)}`],record:(e,t,r)=>b(e)?p(Object.keys(e).map(n=>[n,n]),t.keyType,()=>`${r}[*]`)??p(Object.entries(e),t.valueType,()=>`${r}[*]`):[r,`expected record, found ${f(e)}`],union:(e,t,r)=>(t.members??[]).some(n=>g(e,n,r)===void 0)?void 0:[r,`matches no member of the union (found ${f(e)})`]},W=(e,t,r,n)=>n(e)?typeof e=="string"&&t.stringMaxLength!==void 0&&e.length>t.stringMaxLength?[r,`longer than ${String(t.stringMaxLength)} characters`]:void 0:[r,`expected ${t.kind}, found ${f(e)}`],g=(e,t,r)=>{if(e===null&&t.column?.notNull===!1)return;if(t.kind==="optional")return e===void 0||t.inner===void 0?void 0:g(e,t.inner,r);const n=A[t.kind];if(e===void 0)return n?.(e)===!0?void 0:[r,"required, but missing"];if(n!==void 0)return W(e,t,r,n);const o=M[t.kind];return o===void 0?[r,`has a \`${t.kind}\` validator this check does not know`]:o(e,t,r)},G=(e,t,r)=>{if(Object.keys(e).some(n=>!Object.hasOwn(t,n)))return[`${r}*`,"holds a property the schema does not declare"];for(const[n,o]of Object.entries(t)){const s=g(e[n],o,`${r}${n}`);if(s!==void 0)return s}},x=(e,t)=>{if(e.sourceText!==void 0||e.unmodelledRefinement===!0||e.unresolvedShape===!0||e.hasRefinement===!0&&e.stringMaxLength===void 0)return`${t} has a validator or refinement that cannot be checked outside the worker`;if(e.kind==="literal"&&T(e.literalValue??"")===void 0)return`${t} is a \`v.literal()\` whose value is not a plain literal, so rows cannot be compared to it outside the worker`;if(e.kind==="from")return`${t} is a \`v.from()\` schema, which cannot be checked outside the worker`;if(e.kind!=="optional"&&A[e.kind]===void 0&&M[e.kind]===void 0)return`${t} has a \`${e.kind}\` validator this check does not know`;const r=[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})];for(const n of r){const o=n===void 0?void 0:x(n,t);if(o!==void 0)return o}},J=(e,t,r,n)=>{const o=y(n[t]);return e.shardMode==="global"&&o===null&&r.kind==="optional"&&r.column?.notNull!==!1?void 0:o},U=(e,t)=>{const r=o=>t[o]===void 0||e.table.shardMode==="global"&&t[o]===null,n=e.removed.find(o=>!r(o));if(n!==void 0)return[n,"is no longer declared, but the row still holds it"];for(const[o,s]of e.validated){const a=g(J(e.table,o,s,t),s,o);if(a!==void 0)return a}},k=e=>typeof e=="boolean"?e?"n:1":"n:0":typeof e=="number"||typeof e=="bigint"?`n:${e.toString()}`:typeof e=="string"?`s:${e}`:`j:${JSON.stringify(e)}`,z=(e,t,r)=>{const n=typeof e.table.shardMode=="object"?k(y(t[e.table.shardMode.field])):"",o=typeof t._id=="string"?t._id:"(no _id)";for(const s of e.unique){const a=s.map(c=>y(t[c]));if(a.some(c=>c==null))continue;const d=JSON.stringify([e.table.name,s,n,a.map(c=>k(c))]),i=r.get(d);if(i===void 0)r.set(d,o);else return[s.join(" + "),i]}},Y=(e,t)=>{if(t.length===0||t.some(r=>e.table.shape[r]===void 0))return`the unique constraint on ${e.table.name} names a field the current schema does not declare`;e.unique.push(t)},Q=(e,t)=>{if(t.uniqueOn!==void 0)return Y(e,t.uniqueOn);const{field:r}=t;if(r===void 0)return`"${t.summary}" is not something stored rows can confirm`;const n=e.table.shape[r];if(t.type==="removedField"||n===void 0){e.removed.push(r);return}const o=(t.type==="changedFieldKind"||t.type==="changedFieldShape")&&O(n)?`${t.table}.${r} now references a different table or bucket, which a stored id cannot show`:x(n,`${t.table}.${r}`);return o===void 0&&e.validated.push([r,n]),o},X=(e,t)=>{const r=new Map;for(const n of e){if(!R(n))return{reason:`"${n.summary}" is not something stored rows can confirm`};const o=t.get(n.table);if(o===void 0)return{reason:`table ${n.table} is not in the current schema`};const s=r.get(n.table)??{removed:[],table:o,unique:[],validated:[]};r.set(n.table,s);const a=Q(s,n);if(a!==void 0)return{reason:a}}return{plans:r}},me=async e=>{const t=X(e.changes,new Map(e.tables.map(i=>[i.name,i])));if("reason"in t)return{kind:"inconclusive",reason:t.reason};const{plans:r}=t;if(e.target===void 0)return{kind:"inconclusive",reason:"no deployed worker to read the stored rows from — pass --migrate-url (or record one with `lunora link`) and set LUNORA_ADMIN_TOKEN"};const n=[...r.keys()].toSorted((i,c)=>i.localeCompare(c)),o=[],s=new Map;let a=0,d=!1;try{await S(e.target,n,i=>{const c=r.get(i.table);if(c===void 0)return;a+=1;const l=z(c,i.doc,s),h=l===void 0?U(c,i.doc):[l[0],`duplicates ${l[1]}`];if(h!==void 0){if(o.length===E)return d=!0,!1;o.push({field:h[0],id:typeof i.doc._id=="string"?i.doc._id:"(no _id)",reason:h[1],table:i.table})}})}catch(i){return{kind:"inconclusive",reason:i instanceof Error?i.message:String(i)}}return o.length===0?{kind:"conforms",rows:a,tables:n}:{failures:o,kind:"fails",rows:a,truncated:d}},Z=e=>[`${String(e.failures.length)}${e.truncated?"+":""} stored row(s) do not fit the new schema${e.truncated?` (the first ${String(E)} shown)`:""}:`,...e.failures.map(t=>` - ${t.table} ${t.id}: ${t.field} ${t.reason}`)].join(`
2
+ `),$=(e,t,r)=>{const n=e[t];return typeof n=="number"&&n<r},pe=async e=>{const t=new Map;for(const n of e.changes)n.table!==void 0&&n.expiry!==void 0&&t.set(n.table,n.expiry);if(e.target===void 0)return"no deployed worker to read the stored rows from";const r=new Map([...t.keys()].map(n=>[n,0]));try{await S(e.target,[...t.keys()].toSorted((n,o)=>n.localeCompare(o)),n=>{const o=t.get(n.table);if(o===void 0||!$(n.doc,o.field,e.now-(o.after??0)))return;const{previous:s}=o;s!==void 0&&$(n.doc,s.field,e.now-(s.after??0))||r.set(n.table,(r.get(n.table)??0)+1)})}catch(n){return n instanceof Error?n.message:String(n)}return r},ee=e=>{if(!F(e))return{status:"absent"};let t;try{t=L(e,"utf8")}catch{return{status:"corrupt"}}try{const r=H(t);return r===void 0?{status:"corrupt"}:{snapshot:r,status:"ok"}}catch(r){if(r instanceof B)return{status:"corrupt"};throw r}},te=(e,t)=>{P(e,I(t),"utf8")},ne=e=>{const t=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or delete it: the next run captures a fresh baseline from the current schema, checking nothing against the old one.`;return e.readOnly||e.logger.error(t),{blocked:!0,changes:[],reason:t}},re=(e,t,r)=>e!==void 0?` — ${String(e)} stored row(s) are past the new cutoff and are deleted on the next sweep`:typeof t=="string"?` (the affected rows could not be counted: ${t})`:r?"":" (the affected rows are counted by `lunora deploy`, which reads the deployed worker)",oe=async(e,t)=>{const r=e.filter(o=>o.expiry!==void 0);if(r.length===0)return"";if(t.readOnly||t.countExpiringRows===void 0)return`
3
+
4
+ The rows the next sweep would delete were not counted: \`lunora ${t.command??"prepare"}\` does not read a deployment; \`lunora deploy\` counts them.`;const n=await t.countExpiringRows(r);return typeof n=="string"?`
5
+
6
+ The rows the next sweep would delete could not be counted: ${n}.`:`
7
+
8
+ ${r.map(o=>`Next sweep would delete ${String(n.get(o.table??"")??0)} stored row(s) of ${o.table??"?"}, which are past the new cutoff.`).join(`
9
+ `)}`},_=async(e,t)=>{if(t.readOnly)return;const r=e.filter(s=>s.warning===!0),n=r.filter(s=>s.expiry!==void 0),o=n.length>0&&t.countExpiringRows!==void 0?await t.countExpiringRows(n):void 0;for(const s of r){const a=typeof o=="object"&&s.table!==void 0?o.get(s.table):void 0,d=s.expiry===void 0?"":re(a,o,t.countExpiringRows!==void 0);t.logger.warn(`schema-drift warning: ${s.summary}${d}`)}},se=(e,t)=>(t.readOnly||t.logger.warn(`schema baseline left at its committed shape — --allow-schema-drift overrides this run only: ${t.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason}),ie=e=>e?.kind==="fails"?`
10
+
11
+ ${Z(e)}`:e?.kind==="inconclusive"?`
12
+
13
+ The stored rows were not checked: ${e.reason}.`:"",ae=async(e,t)=>{const r=e.uncovered.filter(o=>R(o));if(!(!(r.length>0&&r.length===e.uncovered.length)||t.readOnly))return t.checkStoredRows===void 0?{kind:"inconclusive",reason:`\`lunora ${t.command??"prepare"}\` does not read a deployment; run \`lunora deploy\`, which checks the stored rows first`}:t.checkStoredRows(r)},ce=async(e,t)=>{const r=await ae(e,t);if(r?.kind==="conforms")return t.logger.success(`schema-drift gate: all ${String(r.rows)} stored row(s) of ${r.tables.join(", ")} fit the new schema — the change needs no backfill`),await _(e.changes,t),{blocked:!1,changes:e.changes,reason:e.reason,rebless:t.rebless};const n=`${e.reason}${ie(r)}${await oe(e.uncovered,t)}`;return t.readOnly||t.logger.error(n),{blocked:!0,changes:e.changes,reason:n}},ye=async e=>{const{allowDrift:t,checkStoredRows:r,codegen:n,command:o,countExpiringRows:s,logger:a,readOnly:d=!1}=e,i=n.schemaSnapshotPath,c=ee(i),l={checkStoredRows:r,command:o,countExpiringRows:s,logger:a,readOnly:d,rebless:()=>{te(i,n.schemaSnapshot)},snapshotPath:i};if(c.status==="corrupt")return ne(l);const h=C=>q({allowDrift:C,baseline:c.status==="ok"?c.snapshot:void 0,command:o,current:n.schemaSnapshot,indexReferences:n.indexReferences,migrations:n.migrations}),u=h(t);if(u.blocked)return ce(u,l);const N=t&&u.changes.length>0&&h(!1).blocked;return u.changes.length>0?(d||a.info(u.reason),N?se(u,l):(await _(u.changes,l),{blocked:!1,changes:u.changes,reason:u.reason,rebless:d?void 0:l.rebless})):{blocked:!1,changes:u.changes,reason:u.reason}},j="/_lunora/health",be="/_lunora/health/ready",de=(e,t=j)=>(e.endsWith("/")?e.slice(0,-1):e)+t,v=async(e,t,r)=>{let n={error:`health probe failed: no health path configured for ${e}`,url:e};for(const[o,s]of t.entries()){const a=de(e,s);let d;try{d=await r(a)}catch(i){const c=i instanceof Error?i.message:String(i);return{error:`health probe failed: could not reach ${a} (${c})`,url:a}}if(d.ok)return{url:a};if(n={error:`health probe failed: ${a} returned HTTP ${String(d.status)}`,url:a},d.status!==404||o===t.length-1)return n}return n},le=async e=>new Promise(t=>{setTimeout(t,e)}),we=async({attempts:e=1,baseUrl:t,delayMs:r=2e3,fetchImpl:n,paths:o=[j],sleep:s=le,timeoutMs:a=1e4})=>{const d=n??(l=>fetch(l,{signal:AbortSignal.timeout(a)})),i=Math.max(1,e);let c=await v(t,o,d);for(let l=1;l<i&&c.error!==void 0;l+=1)await s(r),c=await v(t,o,d);return c};export{be as H,j as a,me as b,pe as c,we as p,ye as r};
@@ -0,0 +1,13 @@
1
+ import{createReadStream as I}from"node:fs";import{open as yt,stat as F,readdir as M,realpath as we,readFile as T,mkdir as Z,writeFile as Le,appendFile as wt}from"node:fs/promises";import{S as Q,b as bt,I as $t,c as vt}from"./shared-CV7ESvuj.mjs";import{t as St,r as Nt}from"./admin-token-VdUnvnKW.mjs";import{r as Et,a as Tt}from"./admin-url-DJB8P6Jh.mjs";import{EXIT_CODE as v,isRefusal as At}from"./EXIT_CODE-DQVhSE-1.mjs";import{b as It}from"./tui-prompts-B3YwUhGw.mjs";import{join as w,resolve as G,basename as y,dirname as xe,relative as Rt,sep as _t}from"node:path";import{createInterface as W}from"node:readline";import Ot from"adm-zip";import{i as Ue}from"./path-containment-CgxYZggb.mjs";import{Transform as kt}from"node:stream";import{createInflateRaw as Lt,crc32 as xt}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{f as Ut}from"./export-rows-EzdNDYpa.mjs";import{parse as Ct}from"csv-parse/sync";import{parse as Ce}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as Pt}from"@lunora/runtime";import{createHash as jt}from"node:crypto";const Ft=67324752,P=30,Mt=26,Dt=28,be=0,zt=8,Bt=async(e,t)=>{const r=await yt(e,"r");try{const n=Buffer.alloc(P),{bytesRead:o}=await r.read(n,0,P,t);if(o<P||n.readUInt32LE(0)!==Ft)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+P+n.readUInt16LE(Mt)+n.readUInt16LE(Dt)}finally{await r.close()}},$e=e=>{let t=0;return new kt({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,o){t=xt(r,t),o(void 0,r)}})},Jt=async(e,t)=>{const{compressedSize:r,encrypted:n,method:o,offset:s}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(o!==be&&o!==zt)throw new Error(`${t.entryName} uses unsupported compression method ${String(o)} — 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 Bt(e,s),a=I(e,{end:i+r-1,start:i});if(o===be){const l=$e(t);return a.on("error",u=>l.destroy(u)),a.pipe(l)}const c=Lt(),d=$e(t);return a.on("error",l=>c.destroy(l)),c.on("error",l=>d.destroy(l)),a.pipe(c).pipe(d)},A="_storage",Pe=e=>e.startsWith("_"),Vt=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"},Ht=async e=>{const t=await F(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new Ot(e);return{kind:"zip",storagePrefix:Vt(r),zip:r,zipPath:e}}},qt=async e=>{const t=[];for(const r of await M(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=w(e,r.name,"documents.jsonl");(await F(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},Gt=e=>{const t=[];for(const r of e.getEntries()){if(r.isDirectory)continue;const n=r.entryName.replaceAll("\\","/"),o=n.split("/");o.length>=2&&o[o.length-1]==="documents.jsonl"&&t.push({file:n,table:o[o.length-2]})}return t},Wt=async e=>{const t=e.kind==="directory"?await qt(e.root):Gt(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},ee=async function*(e,t){if(e.kind==="directory"){for await(const s of W({crlfDelay:Number.POSITIVE_INFINITY,input:I(t.file,{encoding:"utf8"})}))yield s;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await Jt(e.zipPath,r);if(n===void 0)return;const o=W({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const s of o)yield s}finally{o.close(),n.destroy()}},Yt=async(e,t)=>{if(e.kind==="directory"){const n=await we(w(e.root,"_storage")),o=await we(G(n,t)).catch(()=>{});if(o===void 0||!Ue(n,o))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return T(o)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},q=207,te=e=>{const t={conflicts:0,deleted:0,errors:[],failed:[],inserted:{},received:0,replaced:0,warnings:[]};let r=[],n=0;const o=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.deleted+=a.deleted??0,t.received+=a.received??0,t.replaced+=a.replaced??0;for(const c of a.warnings??[])t.warnings.includes(c)||t.warnings.push(c)},s=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!==q){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();o(d),c.status===q&&(d.failed??[]).length===0&&t.failed.push({message:`the endpoint answered ${String(q)} without naming the failed shards`,shardKey:"<unknown>",timedOut:!1})};return{flush:s,push:async a=>{const c=Buffer.byteLength(a)+1;r.length>0&&n+c>e.maxBatchBytes&&await s(),r.push(a),n+=c,r.length>=e.batchSize&&await s()},totals:t}},Kt=["append","replace","require-empty","upsert"],Do=(e,t)=>e===void 0?t:Kt.find(r=>r===e),D=e=>e==="upsert"||e==="replace",ve=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,Xt=(e,t)=>{let r;try{r=JSON.parse(t)}catch{return}const n=ve(r),o=n?.table,s=ve(n?.doc)?._id;if(typeof o!="string")return;let i=e.get(o);i===void 0&&(i={duplicates:0,ids:new Set,rows:0,unkeyed:0},e.set(o,i)),i.rows+=1,typeof s=="string"?(i.ids.has(s)&&(i.duplicates+=1),i.ids.add(s)):i.unkeyed+=1},Zt=async(e,t,r,n=!0)=>{const o=new Map;if(r==="replace"){const i=[...t].find(([,a])=>a.unkeyed>0);if(i!==void 0)throw new f("INTERNAL",`--mode replace needs every row to carry an _id: ${String(i[1].unkeyed)} row(s) of ${i[0]} have none`)}for(const[i,a]of t)o.set(i,{add:a.rows-a.duplicates,delete:0,existing:a.duplicates,matched:0,source:a.rows,table:i,target:0});const s=[];return await Ut(e,[...t.keys()],i=>{const a=o.get(i.table);if(a===void 0)return;a.target+=1;const c=i.doc._id;typeof c=="string"&&t.get(i.table)?.ids.has(c)===!0?(a.existing+=1,a.matched+=1,a.add-=1):r==="replace"&&(a.delete+=1,n&&s.push(i))}),{deletions:s,tables:[...o.values()].toSorted((i,a)=>i.table.localeCompare(a.table))}},Qt=(e,t,r)=>{const n=D(r)?"replaced":"left unchanged";e.info(`import plan (--mode ${r}):`);for(const o of t.tables){const s=[`${String(o.add)} to add`,`${String(o.existing)} ${n}`];r==="replace"&&s.push(`${String(o.delete)} to delete`),e.info(` ${o.table}: ${String(o.source)} in file, ${String(o.target)} stored — ${s.join(", ")}`)}},er=(e,t)=>D(t)&&e.tables.some(r=>r.matched>0||r.delete>0),je=(e,t,r,n)=>{const o=[],s=[];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 p=g.$storage,m=t.get(p);return m===void 0?(s.push({column:u,storageId:p,table:r}),l):(i+=1,m)}return Object.fromEntries(Object.entries(g).map(([p,m])=>[p,c(m,u)]))}return typeof l=="string"&&t.has(l)?a(u)?(i+=1,t.get(l)??l):(o.push({column:u,storageId:l,table:r}),l):(h&&typeof l=="string"&&l.length>0&&a(u)&&n!==void 0&&s.push({column:u,storageId:l,table:r}),l)},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,c(u,l,!0)]));return{ambiguous:o,document:d,rewritten:i,unmigrated:s}},Se=(e,t,r)=>{for(const n of r){const o=`${n.table}\0${n.column}\0${n.storageId}`;t.has(o)||(t.add(o),e.push(n))}},tr=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:o,table:s}=e,i=new Set,a=new Set,c=(u,h)=>{let g;try{g=JSON.parse(u)}catch(p){const m=p instanceof Error?p.message:String(p);throw new f("INTERNAL",`invalid JSON on line ${String(h)}: ${m}`,{cause:p})}return JSON.stringify({doc:g,table:s})},d=(u,h)=>{let g;try{g=JSON.parse(u)}catch(m){throw new f("INTERNAL",`line ${String(h)}: import envelope is not valid JSON — ${m instanceof Error?m.message:String(m)}`,{cause:m})}const p=g===null||typeof g!="object"||Array.isArray(g)?void 0:g;if(p===void 0||typeof p.table!="string")throw new f("INTERNAL",`line ${String(h)}: import envelope is missing a string \`table\``);return p},l=u=>{if(u.doc!==null&&typeof u.doc=="object"&&!Array.isArray(u.doc)){let h=u.doc;if(o!==void 0){const g=je(h,o,u.table,n);h=g.document,r.rewritten+=g.rewritten,Se(r.ambiguous,i,g.ambiguous),Se(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(s!==void 0)return c(g,h);const p=d(g,h);return o===void 0&&t===void 0?g:l(p)}},Fe=async(e,t,r,n)=>{const o=await n(e).catch(()=>{});if(o===void 0)throw new f("INTERNAL",`${e} is not a readable directory`);const s=new Map;for(const[d,l]of Object.entries(t?.tables??{}))l.file!==void 0&&s.set(y(l.file),d);const i=o.filter(d=>d.isFile()&&r.matches(d.name)&&!r.authFiles.has(d.name)).map(d=>({file:w(e,d.name),table:s.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=>y(d.file))),c=[...s].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))},Me=async function*(e,t,r,n){for(const o of e){r.has(o.table)||r.set(o.table,0),t.info(`reading ${y(o.file)} → ${o.table}`);for await(const s of n(o))r.set(o.table,(r.get(o.table)??0)+1),yield`${JSON.stringify({doc:s,table:o.table})}
3
+ `}},De=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],rr=e=>De.includes(e),nr=/^\\x([\dA-Fa-f]*)$/,Ne=/^[+-]?\d+$/,ze=/[+-]\d{2}$/,Be=/(?:Z|[+-]\d{2}:\d{2})$/i,Je=/^\+/,or=/e/i,sr=/e/i,ir=e=>{const[t="0",r="0"]=e.split(sr),n=Number(r),o=t.startsWith("-"),[s="0",i=""]=(o?t.slice(1):t).replace(Je,"").split("."),a=`${s}${i}`,c=s.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)}`,o?`-${d}`:d},ar=/^0+(?=\d)/,Ee=e=>{const r=(or.test(e.trim())?ir(e.trim()):e.trim()).replace(Je,""),n=r.startsWith("-"),[o="0",s=""]=(n?r.slice(1):r).split("."),i=o.replace(ar,"");let a=s.length;for(;a>0&&s[a-1]==="0";)a-=1;const c=s.slice(0,a),d=c.length>0?`${i}.${c}`:i;return n&&Number(d)!==0?`-${d}`:d},b=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},Te=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),o=ze.test(n)?`${n}:00`:n,s=Be.test(o)?o:`${o}Z`,i=Date.parse(s);return Number.isNaN(i)&&b(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),i},cr=(e,t)=>{(!t.startsWith("{")||!t.endsWith("}"))&&b(e,"text-array",t,"not a Postgres array literal (expected `{…}`)");const r=t.slice(1,-1);if(r.length===0)return[];r.includes("{")&&b(e,"text-array",t,"nested arrays are not supported — map the column to `json` instead");const n=[];let o="",s=!1,i=!1,a=!1;const c=()=>{n.push(!i&&o==="NULL"?null:o),o="",i=!1};for(const d of r)a?(o+=d,a=!1):d==="\\"?a=!0:d==='"'?(s=!s,i=!0):d===","&&!s?c():o+=d;return c(),n},Ve=(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:b(e,t,r,"not a Postgres boolean literal");case"bytea-base64":{const n=nr.exec(r);if(n===null)return b(e,t,r,"not `bytea` hex output (expected a leading `\\x`) — set `bytea_output = 'hex'` before dumping");const o=n[1];return o.length%2!==0?b(e,t,r,"has an odd number of hex digits, so the dump is truncated — re-export the column"):Buffer.from(o,"hex").toString("base64")}case"int8-string":return Ne.test(r)?r:b(e,t,r,"not an integer");case"json":try{return JSON.parse(r)}catch(n){return b(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 b(e,t,r,"not a finite number");if(Ne.test(r)){if(!Number.isSafeInteger(n))return b(e,t,r,"exceeds Number.MAX_SAFE_INTEGER — map this column to `int8-string` to keep it lossless")}else if(Ee(String(n))!==Ee(r))return b(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 cr(e,r);case"timestamp-iso":{Te(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),o=ze.test(n)?`${n}:00`:n;return Be.test(o)?o:`${o}Z`}case"timestamp-ms":return Te(e,t,r);default:return r}},dr="auth.",lr=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),ur=String.raw`\N`,He=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===ur?null:e,fr=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>y(t))),hr=async(e,t)=>Fe(e,t,{authFiles:fr(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(dr),tableNameOf:r=>y(r,".csv")},async r=>M(r,{withFileTypes:!0})),gr=(e,t,r)=>{const n=t?.idColumn??"id",o=t?.types??{},s={};let i=!1;for(const[a,c]of Object.entries(e)){if(lr.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=o[a],l=d===void 0?c:Ve(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`);s._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.`);s[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 s},pr=async function*(e,t){const r=t?.tables?.[e.table],n=I(e.file).pipe(Ce({cast:He,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let o=0;const s=n[Symbol.asyncIterator]();for(;;){let i,a;try{if(i=await s.next(),i.done===!0)return;o+=1,a=gr(i.value,r,e.table)}catch(c){throw new f("INTERNAL",`${y(e.file)} row ${String(o+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},mr=async function*(e,t,r,n,o){yield*We("supabase",o,t,r,n),yield*Me(e,r,n,s=>pr(s,t))},yr=/^\d+$/,wr=/[+-]\d{2}$/,Y=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&yr.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(wr.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},qe=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},br=e=>{const t=qe(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]}},$r=e=>{const t=qe(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},vr=(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,o={_id:r,email:e.email??null,emailVerified:typeof e.email_confirmed_at=="string"&&e.email_confirmed_at.length>0,id:r},s=br(n),i=$r(n),a=Y(e.created_at),c=Y(e.updated_at);return s!==void 0&&(o.name=s),i!==void 0&&(o.image=i),a!==void 0&&(o.createdAt=a),c!==void 0&&(o.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:o}},Sr=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=Y(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(s=>typeof s.providerId=="string"&&s.providerId!=="password").map(s=>{const i=s.providerId,a=s.rawId??s.federatedId??t,c=`${t}:${i}:${a}`;return{_id:c,accountId:a,id:c,providerId:i,userId:t}}),user:r}},Nr=(e,t)=>{const r=new Map,n=[],o=[];for(const{accounts:s,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)})`)}o.push(`${JSON.stringify({doc:i,table:"user"})}
4
+ `),t.set("user",(t.get("user")??0)+1);for(const c of s)o.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 o},re=(e,t)=>w(e,y(t)),Ge=async e=>{const t=await T(e,"utf8");return Ct(t,{cast:He,columns:!0,skipEmptyLines:!0})},Er=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Ge(re(e,t))){const o=n.user_id;typeof o=="string"&&r.set(o,[...r.get(o)??[],n])}return r},Tr=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ge(re(e,r)),o=await Er(e,t.auth?.identitiesFile);return n.map(s=>vr(s,o.get(s.id??"")??[]))},Ar=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=re(e,r);let o;try{o=JSON.parse(await T(n,"utf8"))}catch(i){throw new f("INTERNAL",`${y(n)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}const s=Array.isArray(o)?o:o.users??[];if(!Array.isArray(s))throw new f("INTERNAL",`${y(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return s.map(i=>Sr(i))},We=async function*(e,t,r,n,o){if(r?.auth?.file===void 0)return;const s=e==="supabase"?await Tr(t,r):await Ar(t,r);n.info(`auth: ${String(s.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of Nr(s,o))yield i},Ae=/\.(?:nd)?json$/i,Ye=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Ir=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},Rr=(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")},_r=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Ir(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},Or=(e,t)=>typeof e=="string"?e:Rr(e,t),Ke=(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 _r(e.timestampValue,t);if(e.bytesValue!==void 0)return Or(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 Ye(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Ke(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return K(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},kr=new Set(["createTime","fields","name","readTime","updateTime"]),Lr=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},xr=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>kr.has(r))&&!Lr(t)},K=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ke(n,`${t}.${r}`)])),Ur=(e,t,r,n)=>{const o=xr(e),s=K(o?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?Ye(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=s[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`);s[d]=Ve(d,l,u===null?null:String(u))}}return{...s,_id:a}},Cr=async(e,t)=>Fe(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[y(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>Ae.test(r),tableNameOf:r=>r.replace(Ae,"")},async r=>M(r,{withFileTypes:!0})),Pr=async function*(e){const t=W({crlfDelay:Number.POSITIVE_INFINITY,input:I(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const o=n.trim();if(o.length!==0)try{yield{raw:JSON.parse(o)}}catch(s){throw new f("INTERNAL",`${y(e)} line ${String(r)}: invalid JSON — ${s instanceof Error?s.message:String(s)}`,{cause:s})}}}finally{t.close()}},jr=async e=>{const t=await T(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${y(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,o])=>({fallbackId:n,raw:o}));throw new f("INTERNAL",`${y(e)}: expected an object, an array, or \`{ documents: [...] }\``)},Fr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?Pr(e.file):await jr(e.file);let o=0;for await(const s of n)yield Ur(s.raw,s.fallbackId,r,`${e.table}[${String(o)}]`),o+=1},Mr=async function*(e,t,r,n,o){yield*We("firebase",o,t,r,n),yield*Me(e,r,n,s=>Fr(s,t))},k=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ne=(e,t)=>{if(!k(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},O=(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},Xe=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},Dr=(e,t)=>{const r=ne(e,t),n=O(r,"file",t),o=O(r,"idColumn",t),s=Xe(r,"storageColumns",t),{types:i}=r;if(i!==void 0){if(!k(i))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(i))if(!rr(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${De.join(", ")}`)}return{file:n,idColumn:o,storageColumns:s,types:i}},zr=(e,t)=>{if(e!==void 0){if(!k(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])O(e,r,`${t}: auth`)}},Br=(e,t)=>{if(e!==void 0){if(!k(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Dr(n,`${t}: tables.${r}`)]))}},Jr=(e,t)=>{const r=ne(e,t),n=O(r,"keyPrefix",t),{auth:o,tables:s}=r;return zr(o,t),{auth:o,keyPrefix:n,tables:Br(s,t)}},Ze=e=>w("lunora",`import-${e}.json`),Vr=async(e,t,r)=>{const n=Ze(t),o=w(e,n);let s;try{s=await T(o,"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(s)}catch(a){throw new f("INTERNAL",`${o}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return Jr(i,o)},Hr=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}},qr=8,Gr=24*1048576,Wr=1e3,Yr=/^[\dA-F]{64}$/i,Kr=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},Xr=/^[\d+/A-Z]{43}=$/i,Zr=e=>Yr.test(e)?e.toLowerCase():Xr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,Qr=(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 o=Zr(r.sha256);if(o===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"||!Kr(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:o,size:r.size}},z=async(e,t,r)=>{const n=[];try{let o=0;for await(const s of ee(e,t)){const i=s.trim();o+=1,i.length>0&&n.push(Qr(i,`_storage/documents.jsonl line ${String(o)}`))}}catch(o){const s=o instanceof Error?o.message:String(o);throw r.error(`failed to read _storage metadata: ${s}`),o}return n},Qe=Pt,B=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,oe=async(e,t)=>await Hr(async r=>{const n=`${e.baseUrl}${Q}?prefix=${encodeURIComponent(t)}&limit=${String(Wr)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}${B(e)}`,o=await e.fetchImpl(n,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!o.ok){const i=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(o.status)}): ${i}`)}const s=await o.json();return{cursor:s.cursor,records:s.objects,truncated:s.truncated}}),en=async(e,t,r,n)=>{const o=`${e.baseUrl}${Q}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${B(e)}`,s=await e.fetchImpl(o,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!s.ok){const a=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(s.status)}): ${a}`)}const i=await s.json();if(i.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${i.sha256??"none"}`);return t},tn=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${Q}?key=${encodeURIComponent(t)}${B(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,rn=async(e,t,r,n,o)=>{const s=`${e.baseUrl}${bt}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${B(e)}`,i=await e.fetchImpl(s,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const p=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(Qe)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(i.status)}): ${p}`)}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 p=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${p}`)}const l=(await oe(e,t)).find(p=>p.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 p=await tn(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")}${p?" (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&&o.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},et=async(e,t,r,n,o)=>{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<=Qe?en(e,t,r,n):rn(e,t,r,n,o)},nn=e=>{const t=[];let r=[],n=0;for(const o of e)r.length>0&&(r.length>=qr||n+o.size>Gr)&&(t.push(r),r=[],n=0),r.push(o),n+=o.size;return r.length>0&&t.push(r),t},X=(e,t)=>`${e}${t.sha256}`,on=async(e,t,r,n)=>{const o=await z(e,t,n);return new Map(o.map(s=>[s.id,X(r,s)]))},sn=async(e,t,r,n,o)=>{const s=await z(t,r,o),i=new Map,a=await oe(e,n),c=new Map(a.map(u=>[u.key,u])),d=[];for(const u of s){const h=X(n,u);c.get(h)?.size===u.size?i.set(u.id,h):d.push(u)}o.info(`migrating ${String(d.length)} storage blobs${i.size>0?` (${String(i.size)} already present)`:""}...`);const l=async u=>{try{const h=await Yt(t,u.id);i.set(u.id,await et(e,X(n,u),h,u,o))}catch(h){const g=h instanceof Error?h.message:String(h);throw o.error(`failed to upload blob ${u.id}: ${g}`),h}};for(const u of nn(d)){const g=(await Promise.allSettled(u.map(p=>l(p)))).find(p=>p.status==="rejected");if(g!==void 0)throw g.reason}return o.success(`migrated ${String(d.length)} storage blobs`),i};async function*an(e,t,r){let n=0;for await(const o of ee(e,t)){const s=o.trim();if(n+=1,s.length===0)continue;let i;try{i=JSON.parse(s)}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*cn(e,t,r,n,o){for(const s of t){if(Pe(s.table)){s.table===A&&!n&&r.warn(`skipping "${A}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}o.has(s.table)||o.set(s.table,0),yield*an(e,s,o)}}const zo=["firebase","supabase"],dn=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 Vr(r,t,e.logger),o=Object.values(n?.tables??{}).some(s=>(s.storageColumns??[]).length>0);return e.verify===!0&&e.withStorage!==!0&&o?(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 hr(e.file,n)}:{collections:await Cr(e.file,n),kind:"firebase",mapping:n}},ln=async e=>{if(!await F(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},un=async(e,t,r)=>{const n=t.find(s=>s.table===A);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 o=await z(e,n,r.logger);return o.length>0?(r.logger.error(`--verify on an export carrying ${String(o.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),!0):!1},fn=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return dn(e,e.from,t);const r=await Ht(e.file),n=r===void 0?void 0:await Wt(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 ln(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 un(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},j=w("lunora","import-convex.json"),hn=(e,t)=>{const r=ne(e,t),n=O(r,"keyPrefix",t),o=r.storageColumns;if(o!==void 0){if(!k(o))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const s of Object.keys(o))Xe(o,s,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:o}},gn=async(e,t)=>{const r=w(e,j);let n;try{n=await T(r,"utf8")}catch(s){if(s.code==="ENOENT"){t.info(`no ${j} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw s}let o;try{o=JSON.parse(n)}catch(s){throw new f("INTERNAL",`${r}: invalid JSON — ${s instanceof Error?s.message:String(s)}`,{cause:s})}return hn(o,r)},pn=(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})}},mn=async(e,t,r)=>{const n=new Map([...r].map(i=>[i,i])),o=[];let s=0;for await(const i of ee(e,t)){const a=i.trim();if(s+=1,a.length===0)continue;const{ambiguous:c}=je(pn(a,t.table,s),n,t.table);for(const{column:d}of c)o.includes(d)||o.push(d)}return o},yn=async(e,t,r)=>{const n={};for(const o of t){if(Pe(o.table))continue;const s=await mn(e,o,r);s.length>0&&(n[o.table]=s)}return n},wn=async(e,t,r)=>{const n=w(t,j),o=`${JSON.stringify(e,void 0,4)}
7
+ `;await Z(w(t,"lunora"),{recursive:!0});try{await Le(n,o,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(s){if(s.code!=="EEXIST")throw s;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(o)}},bn=async(e,t,r,n)=>{const o=t.find(c=>c.table===A);if(o===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const s=await z(e,o,n),i=new Set(s.map(c=>c.id));n.info(`found ${String(i.size)} storage ids`);const a={keyPrefix:"",storageColumns:await yn(e,t,i)};return await wn(a,r,n),a},E=20,$n=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[o,s]of t){const i=r.inserted[o]??0;i<s&&(n+=1,e.error(`verify: ${o} inserted ${String(i)} of ${String(s)} source rows (${String(s-i)} missing)`))}else{const o=[...t.values()].reduce((i,a)=>i+a,0),s=Object.values(r.inserted).reduce((i,a)=>i+a,0)+r.conflicts;s<o&&(n+=1,e.error(`verify: ${String(s)} of ${String(o)} source rows accounted for across all tables (${String(o-s)} 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},Ie=(e,t,r)=>{for(const n of t.slice(0,E))e.warn(r(n));t.length>E&&e.warn(`… and ${String(t.length-E)} more`)},tt=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),Ie(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\``),Ie(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${j} 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),vn=(e,t,r)=>{for(const n of[...t].slice(0,E))e.warn(`storage path never transferred: ${n} — left as-is`);return t.size>E&&e.warn(`… and ${String(t.size-E)} more untransferred storage paths`),r&&t.size>0},Re=200,Sn=/^\\x[\dA-Fa-f]*$/,Nn=/^[+-]?\d+$/,En=/^[+-]?\d+\.\d+$/,Tn=/^\{.*\}$/,An=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,In=[["bytea-base64",e=>Sn.test(e)],["timestamp-ms",e=>An.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Nn.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>En.test(e)],[e=>e.every(t=>Tn.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Rn=e=>{if(e.length!==0){for(const[t,r]of In)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},_n=(e,t)=>{for(const[r,n]of Object.entries(e)){if(n.length===0)continue;const o=t.get(r);o===void 0?t.set(r,[n]):o.push(n)}},On=async e=>{const t=new Map,r=I(e).pipe(Ce({columns:!0,skipEmptyLines:!0,toLine:Re+1}));let n=0;for await(const s of r)if(_n(s,t),n+=1,n>=Re)break;r.destroy();const o={};for(const[s,i]of t){const a=Rn(i);a!==void 0&&(o[s]=a)}return o},rt=async(e,t,r,n)=>{const o=Ze(r),s=w(t,o),i=`${JSON.stringify(e,void 0,4)}
8
+ `;await Z(xe(s),{recursive:!0});try{await Le(s,i,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${s} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${s} already exists — leaving it untouched. Candidate mapping:`),n.info(i)}},kn=async(e,t,r)=>{const n={};for(const s of e){const i=await On(s.file);r.info(`${y(s.file)} → ${s.table}: ${String(Object.keys(i).length)} column(s) need a reshape`),n[s.table]={file:y(s.file),idColumn:"id",...Object.keys(i).length>0?{types:i}:{}}}const o={keyPrefix:"",tables:n};return await rt(o,t,"supabase",r),o},Ln=async(e,t,r)=>{const n={};for(const s of e)n[s.table]={file:y(s.file),storageColumns:[]};r.info(`found ${String(e.length)} collection(s) — Firestore values are self-describing, so only storage columns need declaring`);const o={keyPrefix:"",tables:n};return await rt(o,t,"firebase",r),o},se=e=>w("lunora",`.import-storage-${e}.ndjson`),xn=async(e,t,r)=>{const n=new Map;let o;try{o=await T(w(e,se(t)),"utf8")}catch(i){if(i.code==="ENOENT")return n;throw i}let s=0;for(const i of o.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):s+=1}catch{s+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${s>0?` (${String(s)} unreadable checkpoint line(s) ignored)`:""}`),n},Un=async(e,t,r)=>{const n=w(e,se(t));await Z(xe(n),{recursive:!0}),await wt(n,`${JSON.stringify(r)}
10
+ `,"utf8")},nt=100,Cn=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),Pn=async(e,t,r,n,o)=>{const s=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:nt,offset:o,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!s.ok){const i=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(s.status)}): ${i}`)}return await s.json()},ot=async(e,t,r,n="")=>{const o=[];let s=0;for(;;){const i=await Pn(e,t,r,n,s);for(const a of i){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?o.push(...await ot(e,t,r,c)):o.push({contentType:a.metadata?.mimetype,name:c})}if(i.length<nt)return o;s+=i.length}},jn=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 o=await n.json(),s=[];for(const i of o){const a=await ot(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}`;s.push({contentType:c.contentType,bytes:async()=>{const l=await t(`${e.url}/storage/v1/object/${encodeURIComponent(i.name)}/${Cn(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 s},Fn=async e=>{const t=G(e),r=[],n=async o=>{const s=await M(o,{withFileTypes:!0}).catch(()=>{});if(s===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 s){const a=G(o,i.name);if(!Ue(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()=>T(a),path:Rt(t,a).split(_t).join("/")})}};return await n(t),r},Mn=async(e,t,r,n,o)=>{const s=await t.bytes(),i=jt("sha256").update(s).digest("hex"),a=`${r.keyPrefix}${i}`;if(n.get(a)?.size!==s.length){const c={contentType:t.contentType,id:t.path,sha256:i,size:s.length};await et(e,a,s,c,o)}return await Un(r.cwd,r.source,{key:a,path:t.path,size:s.length}),a},Dn=(e,t)=>{const r=e>500?100:25;return n=>{if(n===e||n%r===0){const o=e===0?100:Math.round(n/e*100);t.info(`transferred ${String(n)}/${String(e)} object(s) (${String(o)}%)`)}}},_e=async(e,t,r,n)=>{const o=new Map,s=await xn(r.cwd,r.source,n),i=await oe(e,r.keyPrefix),a=new Map(i.map(l=>[l.key,l]));s.size>0&&i.length===0&&n.warn(`the checkpoint records ${String(s.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=Dn(t.length,n);let d=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const l of t){const u=s.get(l.path);if(u!==void 0&&a.has(u.key)){o.set(l.path,u.key),d+=1,c(d);continue}try{const h=await Mn(e,l,r,a,n);o.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 ${se(r.source)} to start over)`),h}d+=1,c(d)}return n.success(`transferred ${String(t.length)} object(s) to R2`),o},Oe=/^\/+/,zn=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,Bn=/[#?]/u,Jn=e=>{const t=new Map(e),r=new Map;for(const[n,o]of e){const s=n.indexOf("/");if(s===-1)continue;const i=n.slice(s+1);i.length===0||e.has(i)||r.set(i,r.has(i)?void 0:o)}for(const[n,o]of r)o!==void 0&&t.set(n,o);return t},Vn=e=>{const t=zn.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(Bn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},Hn=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(Oe,""),o=t.get(n);if(o!==void 0)return o;const s=Vn(e);return s===void 0?void 0:t.get(s)??t.get(s.replace(Oe,""))},qn=500,ie=9e5,Gn=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:v.USAGE};const t=Et(e.url,e.logger,e.cwd);if(t===void 0)return{refused:v.USAGE};if(St({prod:e.prod,url:t})&&e.yes!==!0&&e.dryRun!==!0)return e.logger.error(`import bulk-writes ${t}, which is not local. Re-run with --yes to confirm.`),{refused:v.USAGE};const{token:r}=Nt({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:v.AUTH};try{const o=await F(e.file);if(!o.isFile()&&!o.isDirectory())return e.logger.error(`not a file or directory: ${e.file}`),{refused:v.USAGE}}catch(o){const s=o instanceof Error?o.message:String(o);return e.logger.error(`failed to stat ${e.file}: ${s}`),{refused:v.NOT_FOUND}}const n=e.fetchImpl??Tt;return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${$t}`,token:r}},ae=(e,t,r,n)=>({conflicts:e.conflicts,deleted:e.deleted,errors:e.errors,...e.failed.length>0?{failed:e.failed}:{},inserted:e.inserted,...n===void 0?{}:{plan:n.tables},received:e.received,replaced:e.replaced,...t===void 0?{}:{storage:{ambiguous:r.ambiguous.slice(0,E),ambiguousTotal:r.ambiguous.length,blobs:t.size,rewritten:r.rewritten,unmigrated:r.unmigrated.slice(0,E),unmigratedTotal:r.unmigrated.length}},...e.warnings.length>0?{warnings:e.warnings}:{}}),Wn=(e,t,r,n)=>{switch(e.kind){case"convex":return cn(e.snapshot,e.tables,t.logger,r,n);case"firebase":return Mr(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return mr(e.tables,e.mapping,t.logger,n,t.file);default:return I(t.file,{encoding:"utf8"})}},Yn=async(e,t,r)=>{switch(e.kind){case"convex":return bn(e.snapshot,e.tables,t,r);case"firebase":return Ln(e.collections,t,r);case"supabase":return kn(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},Kn=async(e,t,r,n)=>{const o=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return _e(e,await Fn(r.storageDir),{cwd:n,keyPrefix:o,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 s=process.env.SUPABASE_URL,i=process.env.SUPABASE_SERVICE_ROLE_KEY;if(s===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=s.length;for(;a>0&&s[a-1]==="/";)a-=1;const c=s.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 jn({serviceKey:i,url:c},e.fetchImpl,r.logger);return _e(e,d,{cwd:n,keyPrefix:o,source:t.kind},r.logger)},Xn=(e,t,r,n,o)=>{const s=n.mapping?.tables?.[t]?.storageColumns??[];if(s.length===0)return e;const i={...e};for(const a of s){const c=i[a];if(typeof c!="string"||c.length===0)continue;const d=Hn(c,r);d===void 0?o.add(`${t}.${a}: ${c}`):i[a]=d}return i},Zn=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:Jn(r);return tr({remapDocument:n===void 0||t===void 0?void 0:(o,s)=>Xn(o,s,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},Qn=async(e,t,r,n)=>{let o="",s=0;const i=async a=>{s+=1;const c=t(a,s);c!==void 0&&await r.push(c)};try{for await(const a of e){o+=typeof a=="string"?a:a.toString("utf8");let c=o.indexOf(`
11
+ `);for(;c!==-1;)await i(o.slice(0,c)),o=o.slice(c+1),c=o.indexOf(`
12
+ `)}o.length>0&&await i(o),await r.flush();return}catch(a){const c=a instanceof Error?a.message:String(a);return r.totals.received===0?(n.error(`import failed before any batch was acknowledged: ${c}`),n.error("re-run the same command once the worker is reachable (existing rows conflict rather than duplicate)")):(n.error(`import failed part-way through: ${c}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)")),a}},eo=async(e,t,r)=>{if(t.withStorage!==!0||e.kind!=="convex")return{};const n=await gn(r,t.logger),o=e.tables.find(s=>s.table===A);if(o===void 0){t.logger.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}return{mapping:n,storageIdMap:await on(e.snapshot,o,n?.keyPrefix??"",t.logger)}},to=async(e,t,r,n)=>{const o=t.tables.find(i=>i.table===A);if(o===void 0)return;const s=await sn(e,t.snapshot,o,r.mapping?.keyPrefix??"",n);return n.info(`storage map: ${String(s.size)} blobs mapped`),{mapping:r.mapping,storageIdMap:s}},ro=async(e,t,r,n,o)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return to(e,t,o,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const s=await Kn(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}},no=(e,t)=>{for(const s of t.warnings)e.warn(s);const r=t.received-t.insertedTotal-t.replaced-t.conflicts-t.errorCount;r>0&&e.warn(`${String(r)} of ${String(t.received)} rows were neither inserted, replaced, conflicted, nor reported as errors`);const n=`${t.replaced>0?`${String(t.replaced)} replaced, `:""}${t.deleted>0?`${String(t.deleted)} deleted, `:""}`,o=`imported ${String(t.insertedTotal+t.replaced)} of ${String(t.received)} rows (${n}${String(t.conflicts)} conflicts, ${String(t.errorCount)} errors)`;t.failed?e.error(o):e.success(o)},oo=async(e,t,r)=>await Yn(e,t,r.logger)===void 0?{body:void 0,code:v.USAGE,error:"import --scan: the export could not be scanned",inserted:0}:{body:void 0,code:0,inserted:0},so="GLOBAL_DRY_RUN_UNSUPPORTED",io={error:()=>{},info:()=>{},success:()=>{},warn:()=>{}},ao=e=>({...e,logger:io}),ke=async(e,t,r,n,o)=>{const s=new Set,i={ambiguous:[],rewritten:0,unmigrated:[]},a=new Map,c=Wn(t,e,r.storageIdMap!==void 0,a),d=te({batchSize:n.batchSize,fetchImpl:n.fetchImpl,maxBatchBytes:ie,requestUrl:n.requestUrl,token:n.token}),l=Zn({report:i,source:t,storageColumns:r.mapping?.storageColumns,storageIdMap:r.storageIdMap,table:e.table,transferredPaths:r.transferredPaths,unresolvedPaths:s}),u=t.kind==="ndjson"&&e.table===void 0?vt():void 0,h=u===void 0?l:($,N)=>{if($.trim().length>0){let S;try{S=JSON.parse($)}catch{return l($,N)}if(!u.read(S))return}return l($,N)},p=await Qn(c,o===void 0?h:($,N)=>{const S=h($,N);return S!==void 0&&Xt(o,S),S},d,e.logger),m=p===void 0?u?.problem():void 0,L=m===void 0?p:new Error(`${e.file}: ${m}`);return{batcher:d,remapReport:i,sourceRows:a,streamFailure:L,unresolvedPaths:s}},R=e=>e instanceof Error?e.message:typeof e=="string"?e:"an unknown failure",st=e=>{const{conflicts:t,inserted:r}=e.batcher.totals;return t>0||Object.values(r).some(n=>n>0)},co=(e,t,r,n)=>{const o=ae(t.batcher.totals,n,t.remapReport),s=st(t);if(e.format!=="json"&&e.logger.info(JSON.stringify(o,void 0,2)),t.streamFailure!==void 0){const c=R(t.streamFailure);e.logger.error(t.batcher.totals.received===0?`import failed before any batch was acknowledged: ${c}`:`import failed while checking the rows: ${c}`),e.logger.error(s?"rows may already be written by the check; check the shard before running the command again":"no rows were written; re-run the same command once the worker is reachable")}for(const c of t.batcher.totals.failed)e.logger.error(`import: shard "${c.shardKey}" was never reached${c.timedOut?" (timed out)":""} — no rows were written: ${c.message}`);const i=Object.values(t.batcher.totals.inserted).reduce((c,d)=>c+d,0),a=s?`import: ${e.file} was refused, and rows may already be written: ${r}`:`import: ${e.file} was not written: ${r}`;return{body:o,code:1,data:{file:e.file,inserted:i,summary:o},error:a,inserted:i}},lo=(e,t)=>{if(e.streamFailure!==void 0)return`the check stopped early: ${R(e.streamFailure)}`;const{errors:r,failed:n}=e.batcher.totals;if(st(e))return"this worker wrote rows during its check, so it cannot check an import before writing, and some rows may already be written";if(n.length>0)return`${String(n.length)} shard(s) could not be reached to check`;const o=r.filter(i=>i.code!==so);if(o.length>0)return`${String(o.length)} row(s) would be refused`;const s=e.remapReport.unmigrated.length;return t&&s>0?`${String(s)} storage reference(s) resolve to no exported blob`:void 0},uo=(e,t)=>{e.verify===!0&&t.remapReport.unmigrated.length>0&&tt(e.logger,t.remapReport,!0)},fo=(e,t)=>{for(const r of t)e.error(`import: shard "${r.shardKey}" was never reached${r.timedOut?" (timed out)":""} — its rows were NOT written: ${r.message}`)},ho=async(e,t)=>{const r=D(t);try{const n=await e.fetchImpl(`${e.requestUrl}?dryRun=true${r?"&onConflict=replace":""}`,{body:`
13
+ `,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!n.ok)return`the worker at ${e.requestUrl} answered HTTP ${String(n.status)} to the check`;const o=await n.json();return o.dryRun!==!0?`the worker at ${e.requestUrl} predates ?dryRun=true, so it would write the file while checking it; deploy the current runtime and import again`:r&&o.onConflict!=="replace"?`the worker at ${e.requestUrl} predates ?onConflict=replace, so --mode ${t} would overwrite nothing; deploy the current runtime and import again`:t==="replace"&&typeof o.deleted!="number"?`the worker at ${e.requestUrl} cannot delete rows, so --mode replace could not remove the rows the file lacks; deploy the current runtime and import again`:void 0}catch(n){return`the worker at ${e.requestUrl} did not answer the check: ${R(n)}`}},go=(e,t)=>{const r=t?"onConflict=replace":void 0;return{check:`${e}?dryRun=true${r===void 0?"":`&${r}`}`,write:r===void 0?e:`${e}?${r}`}},po=async(e,t,r,n)=>{const o=(c,d)=>(e.logger.error(d),{stop:{body:void 0,code:c,error:d,inserted:0}});let s;try{s=await Zt({baseUrl:t.baseUrl,fetchImpl:t.fetchImpl,token:t.token},r,n,e.dryRun!==!0)}catch(c){return o(1,`import: ${e.file} was not written: ${R(c)}`)}Qt(e.logger,s,n);const i=s.tables.filter(c=>c.target>0);if(n==="require-empty"&&i.length>0){const c=i.map(d=>`${d.table} (${String(d.target)} rows)`).join(", ");return o(1,`import: ${e.file} was not written: --mode require-empty, and the target already holds ${c}. Use --mode replace to make those tables match the file.`)}if(e.dryRun===!0){const c=ae({conflicts:0,deleted:0,errors:[],failed:[],inserted:{},received:0,replaced:0,warnings:[]},void 0,{ambiguous:[],rewritten:0,unmigrated:[]},s);return e.logger.success("dry run: nothing was written"),{stop:{body:c,code:0,data:{file:e.file,inserted:0,summary:c},inserted:0}}}return!er(s,n)||e.yes===!0?{plan:s}:e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json")?o(v.USAGE,`import: --mode ${n} overwrites or deletes stored rows and cannot prompt here; re-run with --yes to confirm`):await(e.confirm??It)(`--mode ${n} overwrites or deletes the stored rows above. Continue?`)?{plan:s}:o(v.CANCELLED,"import: aborted, nothing was written")},mo=async(e,t,r)=>{const n=te({...t,maxBatchBytes:ie,requestUrl:`${t.requestUrl}?deletes=true`});try{for(const o of e.deletions){const s=o.doc._id;typeof s=="string"&&r.get(o.table)?.ids.has(s)===!0||await n.push(JSON.stringify({doc:o.doc,op:"delete",table:o.table}))}return await n.flush(),{batcher:n,failure:void 0}}catch(o){return{batcher:n,failure:o}}},yo=async(e,t,r)=>{if(e===void 0||t!=="replace"||e.deletions.length===0)return;const n=te({...r,maxBatchBytes:ie,requestUrl:`${r.requestUrl}?dryRun=true&deletes=true`});try{for(const s of e.deletions)await n.push(JSON.stringify({doc:s.doc,op:"delete",table:s.table}));await n.flush()}catch(s){return R(s)}if(n.totals.failed.length>0)return`${String(n.totals.failed.length)} shard(s) could not be reached to check the deletes`;const[o]=n.totals.errors;return o===void 0?void 0:`${String(n.totals.errors.length)} planned delete(s) refused, first: ${o.table} ${o.message}`},wo=async(e,t,r,n)=>{if(t===void 0||e.mode!=="replace"||t.deletions.length===0)return{failed:!1};const o=String(t.deletions.length),{totals:s}=r.batcher;if(r.streamFailure!==void 0||r.verifyFailed||s.errors.length>0||s.failed.length>0)return e.logger.error(`--mode replace: the write did not finish cleanly, so the ${o} stored row(s) the file lacks were NOT deleted; fix the errors and re-run the same command`),{failed:!0};e.logger.info(`--mode replace: deleting ${o} stored row(s) the file lacks`);const{batcher:i,failure:a}=await mo(t,n,r.written),{totals:c}=i;return a!==void 0||c.errors.length>0||c.failed.length>0?(e.logger.error(`--mode replace: deleting stopped part-way${a===void 0?"":` (${R(a)})`}; every file row is written, and re-running the same command deletes the rest`),{failed:!0,totals:c}):{failed:!1,totals:c}},bo=(e,t)=>t===void 0?e:{...e,deleted:e.deleted+t.deleted,errors:[...e.errors,...t.errors],failed:[...e.failed,...t.failed]},$o=async(e,t,r,n)=>(n==="append"||n==="upsert"&&e.yes===!0)&&e.dryRun!==!0?{plan:void 0}:po(e,t,r,n),Bo=async e=>{const t=e.cwd??process.cwd(),r=await fn(e,t);if(r.kind==="invalid")return{body:void 0,code:v.USAGE,error:`import: could not read ${e.file}`,inserted:0};if(e.scan===!0)return oo(r,t,e);const n=await Gn(e);if(At(n))return{body:void 0,code:n.refused,error:"import: could not resolve the worker URL and admin token",inserted:0};const{baseUrl:o,fetchImpl:s,token:i}=n,a=e.mode??"append",c=go(n.requestUrl,D(a)),{write:d}=c,u={batchSize:e.batchSize??qn,fetchImpl:s,requestUrl:n.requestUrl,token:i},h=await ho(u,a);if(h!==void 0)return{body:void 0,code:1,error:`import: ${e.file} was not written: ${h}`,inserted:0};const g=await eo(r,e,t);if(g===void 0)return{body:void 0,code:1,error:"import: the storage phase failed — no rows were written",inserted:0};const p=new Map,m=await ke(ao(e),r,g,{...u,requestUrl:c.check},p),L=lo(m,e.verify===!0);if(L!==void 0)return uo(e,m),co(e,m,L,void 0);const $=await $o(e,n,p,a);if("stop"in $)return $.stop;const N=$.plan,S=await yo(N,a,u);if(S!==void 0){const C=`import: ${e.file} was not written: the worker would refuse the deletes --mode replace needs (${S})`;return e.logger.error(C),{body:void 0,code:1,error:C,inserted:0}}const J=await ro({baseUrl:o,fetchImpl:s,token:i},r,e,t,g);if(J===void 0)return{body:void 0,code:1,error:"import: the storage phase failed — no rows were written",inserted:0};const{storageIdMap:ce}=J;e.logger.info(r.kind==="convex"?`POST ${d} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${d} -> import ${e.file}`);const de=new Map,{batcher:_,remapReport:le,sourceRows:it,streamFailure:V,unresolvedPaths:at}=await ke(e,r,J,{...u,requestUrl:d},de),ct=e.verify===!0&&V===void 0?$n(e.logger,it,{conflicts:_.totals.conflicts+_.totals.replaced,inserted:_.totals.inserted}):0,dt=ce!==void 0&&tt(e.logger,le,e.verify===!0),lt=vn(e.logger,at,e.verify===!0),ue=ct>0||dt||lt,fe=await wo(e,N,{batcher:_,streamFailure:V,verifyFailed:ue,written:de},u),he=bo(_.totals,fe.totals),{conflicts:ut,deleted:ft,errors:ge,failed:pe,inserted:ht,received:gt,replaced:H,warnings:pt}=he,x=Object.values(ht).reduce((C,mt)=>C+mt,0),U=ae(he,ce,le,N);fo(e.logger,pe);const me=V!==void 0||ge.length>0||pe.length>0||ue||fe.failed;e.format!=="json"&&e.logger.info(JSON.stringify(U,void 0,2)),no(e.logger,{conflicts:ut,deleted:ft,errorCount:ge.length,failed:me,insertedTotal:x,received:gt,replaced:H,warnings:pt});const ye={file:e.file,inserted:x,summary:U};return me?{body:U,code:1,data:ye,error:`import: ${e.file} did not import cleanly`,inserted:x,replaced:H}:{body:U,code:0,data:ye,inserted:x,replaced:H}};export{qn as D,zo as I,Qe as M,Kt as a,B as b,oe as l,Do as p,Bo as r,et as u};
@@ -0,0 +1 @@
1
+ var k={exports:{}},se,er;function H(){if(er)return se;er=1;const i="2.0.0",l=256,n=Number.MAX_SAFE_INTEGER||9007199254740991,t=16,s=l-6;return se={MAX_LENGTH:l,MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:n,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:i,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},se}var ne,rr;function B(){return rr||(rr=1,ne=process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...l)=>console.error("SEMVER",...l):()=>{}),ne}var tr;function M(){return tr||(tr=1,(function(i,l){const{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:t,MAX_LENGTH:s}=H(),h=B();l=i.exports={};const o=l.re=[],f=l.safeRe=[],r=l.src=[],m=l.safeSrc=[],e=l.t={};let a=0;const c="[a-zA-Z0-9-]",R=[["\\s",1],["\\d",s],[c,t]],L=O=>{for(const[q,G]of R)O=O.split(`${q}*`).join(`${q}{0,${G}}`).split(`${q}+`).join(`${q}{1,${G}}`);return O},E=(O,q,G)=>{const j=L(q),y=a++;h(O,y,q),e[O]=y,r[y]=q,m[y]=j,o[y]=new RegExp(q,G?"g":void 0),f[y]=new RegExp(j,G?"g":void 0)};E("NUMERICIDENTIFIER","0|[1-9]\\d*"),E("NUMERICIDENTIFIERLOOSE","\\d+"),E("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${c}*`),E("MAINVERSION",`(${r[e.NUMERICIDENTIFIER]})\\.(${r[e.NUMERICIDENTIFIER]})\\.(${r[e.NUMERICIDENTIFIER]})`),E("MAINVERSIONLOOSE",`(${r[e.NUMERICIDENTIFIERLOOSE]})\\.(${r[e.NUMERICIDENTIFIERLOOSE]})\\.(${r[e.NUMERICIDENTIFIERLOOSE]})`),E("PRERELEASEIDENTIFIER",`(?:${r[e.NONNUMERICIDENTIFIER]}|${r[e.NUMERICIDENTIFIER]})`),E("PRERELEASEIDENTIFIERLOOSE",`(?:${r[e.NONNUMERICIDENTIFIER]}|${r[e.NUMERICIDENTIFIERLOOSE]})`),E("PRERELEASE",`(?:-(${r[e.PRERELEASEIDENTIFIER]}(?:\\.${r[e.PRERELEASEIDENTIFIER]})*))`),E("PRERELEASELOOSE",`(?:-?(${r[e.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${r[e.PRERELEASEIDENTIFIERLOOSE]})*))`),E("BUILDIDENTIFIER",`${c}+`),E("BUILD",`(?:\\+(${r[e.BUILDIDENTIFIER]}(?:\\.${r[e.BUILDIDENTIFIER]})*))`),E("FULLPLAIN",`v?${r[e.MAINVERSION]}${r[e.PRERELEASE]}?${r[e.BUILD]}?`),E("FULL",`^${r[e.FULLPLAIN]}$`),E("LOOSEPLAIN",`[v=\\s]*${r[e.MAINVERSIONLOOSE]}${r[e.PRERELEASELOOSE]}?${r[e.BUILD]}?`),E("LOOSE",`^${r[e.LOOSEPLAIN]}$`),E("GTLT","((?:<|>)?=?)"),E("XRANGEIDENTIFIERLOOSE",`${r[e.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),E("XRANGEIDENTIFIER",`${r[e.NUMERICIDENTIFIER]}|x|X|\\*`),E("XRANGEPLAIN",`[v=\\s]*(${r[e.XRANGEIDENTIFIER]})(?:\\.(${r[e.XRANGEIDENTIFIER]})(?:\\.(${r[e.XRANGEIDENTIFIER]})(?:${r[e.PRERELEASE]})?${r[e.BUILD]}?)?)?`),E("XRANGEPLAINLOOSE",`[v=\\s]*(${r[e.XRANGEIDENTIFIERLOOSE]})(?:\\.(${r[e.XRANGEIDENTIFIERLOOSE]})(?:\\.(${r[e.XRANGEIDENTIFIERLOOSE]})(?:${r[e.PRERELEASELOOSE]})?${r[e.BUILD]}?)?)?`),E("XRANGE",`^${r[e.GTLT]}\\s*${r[e.XRANGEPLAIN]}$`),E("XRANGELOOSE",`^${r[e.GTLT]}\\s*${r[e.XRANGEPLAINLOOSE]}$`),E("COERCEPLAIN",`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),E("COERCE",`${r[e.COERCEPLAIN]}(?:$|[^\\d])`),E("COERCEFULL",r[e.COERCEPLAIN]+`(?:${r[e.PRERELEASE]})?(?:${r[e.BUILD]})?(?:$|[^\\d])`),E("COERCERTL",r[e.COERCE],!0),E("COERCERTLFULL",r[e.COERCEFULL],!0),E("LONETILDE","(?:~>?)"),E("TILDETRIM",`(\\s*)${r[e.LONETILDE]}\\s+`,!0),l.tildeTrimReplace="$1~",E("TILDE",`^${r[e.LONETILDE]}${r[e.XRANGEPLAIN]}$`),E("TILDELOOSE",`^${r[e.LONETILDE]}${r[e.XRANGEPLAINLOOSE]}$`),E("LONECARET","(?:\\^)"),E("CARETTRIM",`(\\s*)${r[e.LONECARET]}\\s+`,!0),l.caretTrimReplace="$1^",E("CARET",`^${r[e.LONECARET]}${r[e.XRANGEPLAIN]}$`),E("CARETLOOSE",`^${r[e.LONECARET]}${r[e.XRANGEPLAINLOOSE]}$`),E("COMPARATORLOOSE",`^${r[e.GTLT]}\\s*(${r[e.LOOSEPLAIN]})$|^$`),E("COMPARATOR",`^${r[e.GTLT]}\\s*(${r[e.FULLPLAIN]})$|^$`),E("COMPARATORTRIM",`(\\s*)${r[e.GTLT]}\\s*(${r[e.LOOSEPLAIN]}|${r[e.XRANGEPLAIN]})`,!0),l.comparatorTrimReplace="$1$2$3",E("HYPHENRANGE",`^\\s*(${r[e.XRANGEPLAIN]})\\s+-\\s+(${r[e.XRANGEPLAIN]})\\s*$`),E("HYPHENRANGELOOSE",`^\\s*(${r[e.XRANGEPLAINLOOSE]})\\s+-\\s+(${r[e.XRANGEPLAINLOOSE]})\\s*$`),E("STAR","(<|>)?=?\\s*\\*"),E("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),E("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(k,k.exports)),k.exports}var ie,sr;function We(){if(sr)return ie;sr=1;const i=Object.freeze({loose:!0}),l=Object.freeze({});return ie=t=>t?typeof t!="object"?i:t:l,ie}var ae,nr;function Br(){if(nr)return ae;nr=1;const i=/^[0-9]+$/,l=(t,s)=>{if(typeof t=="number"&&typeof s=="number")return t===s?0:t<s?-1:1;const h=i.test(t),o=i.test(s);return h&&o&&(t=+t,s=+s),t===s?0:h&&!o?-1:o&&!h?1:t<s?-1:1};return ae={compareIdentifiers:l,rcompareIdentifiers:(t,s)=>l(s,t)},ae}var oe,ir;function _(){if(ir)return oe;ir=1;const i=B(),{MAX_LENGTH:l,MAX_SAFE_INTEGER:n}=H(),{safeRe:t,t:s}=M(),h=We(),{compareIdentifiers:o}=Br(),f=(m,e)=>{const a=e.split(".");if(a.length>m.length)return!1;for(let c=0;c<a.length;c++)if(o(m[c],a[c])!==0)return!1;return!0};class r{constructor(e,a){if(a=h(a),e instanceof r){if(e.loose===!!a.loose&&e.includePrerelease===!!a.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>l)throw new TypeError(`version is longer than ${l} characters`);i("SemVer",e,a),this.options=a,this.loose=!!a.loose,this.includePrerelease=!!a.includePrerelease;const c=e.trim().match(a.loose?t[s.LOOSE]:t[s.FULL]);if(!c)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+c[1],this.minor=+c[2],this.patch=+c[3],this.major>n||this.major<0)throw new TypeError("Invalid major version");if(this.minor>n||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>n||this.patch<0)throw new TypeError("Invalid patch version");c[4]?this.prerelease=c[4].split(".").map(R=>{if(/^[0-9]+$/.test(R)){const L=+R;if(L>=0&&L<n)return L}return R}):this.prerelease=[],this.build=c[5]?c[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(i("SemVer.compare",this.version,this.options,e),!(e instanceof r)){if(typeof e=="string"&&e===this.version)return 0;e=new r(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof r||(e=new r(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let a=0;do{const c=this.prerelease[a],R=e.prerelease[a];if(i("prerelease compare",a,c,R),c===void 0&&R===void 0)return 0;if(R===void 0)return 1;if(c===void 0)return-1;if(c===R)continue;return o(c,R)}while(++a)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let a=0;do{const c=this.build[a],R=e.build[a];if(i("build compare",a,c,R),c===void 0&&R===void 0)return 0;if(R===void 0)return 1;if(c===void 0)return-1;if(c===R)continue;return o(c,R)}while(++a)}inc(e,a,c){if(e.startsWith("pre")){if(!a&&c===!1)throw new Error("invalid increment argument: identifier is empty");if(a){const R=`-${a}`.match(this.options.loose?t[s.PRERELEASELOOSE]:t[s.PRERELEASE]);if(!R||R[1]!==a)throw new Error(`invalid identifier: ${a}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",a,c);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",a,c);break;case"prepatch":this.prerelease.length=0,this.inc("patch",a,c),this.inc("pre",a,c);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",a,c),this.inc("pre",a,c);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const R=Number(c)?1:0;if(this.prerelease.length===0)this.prerelease=[R];else{let L=this.prerelease.length;for(;--L>=0;)typeof this.prerelease[L]=="number"&&(this.prerelease[L]++,L=-2);if(L===-1){if(a===this.prerelease.join(".")&&c===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(R)}}if(a){let L=[a,R];if(c===!1&&(L=[a]),f(this.prerelease,a)){const E=this.prerelease[a.split(".").length];isNaN(E)&&(this.prerelease=L)}else this.prerelease=L}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return oe=r,oe}var ce,ar;function V(){if(ar)return ce;ar=1;const i=_();return ce=(n,t,s=!1)=>{if(n instanceof i)return n;try{return new i(n,t)}catch(h){if(!s)return null;throw h}},ce}var le,or;function Kr(){if(or)return le;or=1;const i=V();return le=(n,t)=>{const s=i(n,t);return s?s.version:null},le}var ue,cr;function Zr(){if(cr)return ue;cr=1;const i=V();return ue=(n,t)=>{const s=i(n.trim().replace(/^[=v]+/,""),t);return s?s.version:null},ue}var fe,lr;function Jr(){if(lr)return fe;lr=1;const i=_();return fe=(n,t,s,h,o)=>{typeof s=="string"&&(o=h,h=s,s=void 0);try{return new i(n instanceof i?n.version:n,s).inc(t,h,o).version}catch{return null}},fe}var he,ur;function Qr(){if(ur)return he;ur=1;const i=V();return he=(n,t)=>{const s=i(n,null,!0),h=i(t,null,!0),o=s.compare(h);if(o===0)return null;const f=o>0,r=f?s:h,m=f?h:s,e=!!r.prerelease.length;if(!!m.prerelease.length&&!e){if(!m.patch&&!m.minor)return"major";if(m.compareMain(r)===0)return m.minor&&!m.patch?"minor":"patch"}const c=e?"pre":"";return s.major!==h.major?c+"major":s.minor!==h.minor?c+"minor":s.patch!==h.patch?c+"patch":"prerelease"},he}var Ee,fr;function et(){if(fr)return Ee;fr=1;const i=_();return Ee=(n,t)=>new i(n,t).major,Ee}var pe,hr;function rt(){if(hr)return pe;hr=1;const i=_();return pe=(n,t)=>new i(n,t).minor,pe}var Re,Er;function tt(){if(Er)return Re;Er=1;const i=_();return Re=(n,t)=>new i(n,t).patch,Re}var me,pr;function st(){if(pr)return me;pr=1;const i=V();return me=(n,t)=>{const s=i(n,t);return s&&s.prerelease.length?s.prerelease:null},me}var $e,Rr;function U(){if(Rr)return $e;Rr=1;const i=_();return $e=(n,t,s)=>new i(n,s).compare(new i(t,s)),$e}var ve,mr;function nt(){if(mr)return ve;mr=1;const i=U();return ve=(n,t,s)=>i(t,n,s),ve}var Ie,$r;function it(){if($r)return Ie;$r=1;const i=U();return Ie=(n,t)=>i(n,t,!0),Ie}var de,vr;function ze(){if(vr)return de;vr=1;const i=_();return de=(n,t,s)=>{const h=new i(n,s),o=new i(t,s);return h.compare(o)||h.compareBuild(o)},de}var Le,Ir;function at(){if(Ir)return Le;Ir=1;const i=ze();return Le=(n,t)=>n.sort((s,h)=>i(s,h,t)),Le}var Ne,dr;function ot(){if(dr)return Ne;dr=1;const i=ze();return Ne=(n,t)=>n.sort((s,h)=>i(h,s,t)),Ne}var Se,Lr;function Y(){if(Lr)return Se;Lr=1;const i=U();return Se=(n,t,s)=>i(n,t,s)>0,Se}var Oe,Nr;function Ke(){if(Nr)return Oe;Nr=1;const i=U();return Oe=(n,t,s)=>i(n,t,s)<0,Oe}var Te,Sr;function Yr(){if(Sr)return Te;Sr=1;const i=U();return Te=(n,t,s)=>i(n,t,s)===0,Te}var Ae,Or;function Wr(){if(Or)return Ae;Or=1;const i=U();return Ae=(n,t,s)=>i(n,t,s)!==0,Ae}var ge,Tr;function Ze(){if(Tr)return ge;Tr=1;const i=U();return ge=(n,t,s)=>i(n,t,s)>=0,ge}var we,Ar;function Je(){if(Ar)return we;Ar=1;const i=U();return we=(n,t,s)=>i(n,t,s)<=0,we}var qe,gr;function zr(){if(gr)return qe;gr=1;const i=Yr(),l=Wr(),n=Y(),t=Ze(),s=Ke(),h=Je();return qe=(f,r,m,e)=>{switch(r){case"===":return typeof f=="object"&&(f=f.version),typeof m=="object"&&(m=m.version),f===m;case"!==":return typeof f=="object"&&(f=f.version),typeof m=="object"&&(m=m.version),f!==m;case"":case"=":case"==":return i(f,m,e);case"!=":return l(f,m,e);case">":return n(f,m,e);case">=":return t(f,m,e);case"<":return s(f,m,e);case"<=":return h(f,m,e);default:throw new TypeError(`Invalid operator: ${r}`)}},qe}var Pe,wr;function ct(){if(wr)return Pe;wr=1;const i=_(),l=V(),{safeRe:n,t}=M();return Pe=(h,o)=>{if(h instanceof i)return h;if(typeof h=="number"&&(h=String(h)),typeof h!="string")return null;o=o||{};let f=null;if(!o.rtl)f=h.match(o.includePrerelease?n[t.COERCEFULL]:n[t.COERCE]);else{const R=o.includePrerelease?n[t.COERCERTLFULL]:n[t.COERCERTL];let L;for(;(L=R.exec(h))&&(!f||f.index+f[0].length!==h.length);)(!f||L.index+L[0].length!==f.index+f[0].length)&&(f=L),R.lastIndex=L.index+L[1].length+L[2].length;R.lastIndex=-1}if(f===null)return null;const r=f[2],m=f[3]||"0",e=f[4]||"0",a=o.includePrerelease&&f[5]?`-${f[5]}`:"",c=o.includePrerelease&&f[6]?`+${f[6]}`:"";return l(`${r}.${m}.${e}${a}${c}`,o)},Pe}var Ce,qr;function lt(){if(qr)return Ce;qr=1;const i=V(),l=H(),n=_(),t=(f,r,m)=>{if(!l.RELEASE_TYPES.includes(r))return null;const e=s(f,m);return e&&h(e,r)},s=(f,r)=>{const m=f instanceof n?f.version:f;return i(m,r)},h=(f,r)=>{if(o(r))return f.version;switch(f.prerelease=[],r){case"major":f.minor=0,f.patch=0;break;case"minor":f.patch=0;break}return f.format()},o=f=>f.startsWith("pre");return Ce=t,Ce}var De,Pr;function ut(){if(Pr)return De;Pr=1;class i{constructor(){this.max=1e3,this.map=new Map}get(n){const t=this.map.get(n);if(t!==void 0)return this.map.delete(n),this.map.set(n,t),t}delete(n){return this.map.delete(n)}set(n,t){if(!this.delete(n)&&t!==void 0){if(this.map.size>=this.max){const h=this.map.keys().next().value;this.delete(h)}this.map.set(n,t)}return this}}return De=i,De}var Ge,Cr;function X(){if(Cr)return Ge;Cr=1;const i=/\s+/g;class l{constructor(u,I){if(I=s(I),u instanceof l)return u.loose===!!I.loose&&u.includePrerelease===!!I.includePrerelease?u:new l(u.raw,I);if(u instanceof h)return this.raw=u.value,this.set=[[u]],this.formatted=void 0,this;if(this.options=I,this.loose=!!I.loose,this.includePrerelease=!!I.includePrerelease,this.raw=u.trim().replace(i," "),this.set=this.raw.split("||").map(v=>this.parseRange(v.trim())).filter(v=>v.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const v=this.set[0];if(this.set=this.set.filter(S=>!q(S[0])),this.set.length===0)this.set=[v];else if(this.set.length>1){for(const S of this.set)if(S.length===1&&G(S[0])){this.set=[S];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let u=0;u<this.set.length;u++){u>0&&(this.formatted+="||");const I=this.set[u];for(let v=0;v<I.length;v++)v>0&&(this.formatted+=" "),this.formatted+=I[v].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(u){u=u.replace(O,"");const v=((this.options.includePrerelease&&L)|(this.options.loose&&E))+":"+u,S=t.get(v);if(S)return S;const $=this.options.loose,d=$?r[e.HYPHENRANGELOOSE]:r[e.HYPHENRANGE];u=u.replace(d,re(this.options.includePrerelease)),o("hyphen replace",u),u=u.replace(r[e.COMPARATORTRIM],a),o("comparator trim",u),u=u.replace(r[e.TILDETRIM],c),o("tilde trim",u),u=u.replace(r[e.CARETTRIM],R),o("caret trim",u);let g=u.split(" ").map(C=>y(C,this.options)).join(" ").split(/\s+/).map(C=>ee(C,this.options));$&&(g=g.filter(C=>(o("loose invalid filter",C,this.options),!!C.match(r[e.COMPARATORLOOSE])))),o("range list",g);const T=new Map,w=g.map(C=>new h(C,this.options));for(const C of w){if(q(C))return[C];T.set(C.value,C)}T.size>1&&T.has("")&&T.delete("");const F=[...T.values()];return t.set(v,F),F}intersects(u,I){if(!(u instanceof l))throw new TypeError("a Range is required");return this.set.some(v=>j(v,I)&&u.set.some(S=>j(S,I)&&v.every($=>S.every(d=>$.intersects(d,I)))))}test(u){if(!u)return!1;if(typeof u=="string")try{u=new f(u,this.options)}catch{return!1}for(let I=0;I<this.set.length;I++)if(te(this.set[I],u,this.options))return!0;return!1}}Ge=l;const n=ut(),t=new n,s=We(),h=W(),o=B(),f=_(),{safeRe:r,src:m,t:e,comparatorTrimReplace:a,tildeTrimReplace:c,caretTrimReplace:R}=M(),{FLAG_INCLUDE_PRERELEASE:L,FLAG_LOOSE:E}=H(),O=new RegExp(m[e.BUILD],"g"),q=p=>p.value==="<0.0.0-0",G=p=>p.value==="",j=(p,u)=>{let I=!0;const v=p.slice();let S=v.pop();for(;I&&v.length;)I=v.every($=>S.intersects($,u)),S=v.pop();return I},y=(p,u)=>(p=p.replace(r[e.BUILD],""),o("comp",p,u),p=x(p,u),o("caret",p),p=D(p,u),o("tildes",p),p=Z(p,u),o("xrange",p),p=Q(p,u),o("stars",p),p),A=p=>!p||p.toLowerCase()==="x"||p==="*",P=(p,u,I)=>A(p)&&!A(u)||A(u)&&I&&!A(I),D=(p,u)=>p.trim().split(/\s+/).map(I=>N(I,u)).join(" "),N=(p,u)=>{const I=u.loose?r[e.TILDELOOSE]:r[e.TILDE],v=u.includePrerelease?"-0":"";return p.replace(I,(S,$,d,g,T)=>{o("tilde",p,S,$,d,g,T);let w;return A($)?w="":A(d)?w=`>=${$}.0.0${v} <${+$+1}.0.0-0`:A(g)?w=`>=${$}.${d}.0${v} <${$}.${+d+1}.0-0`:T?(o("replaceTilde pr",T),w=`>=${$}.${d}.${g}-${T} <${$}.${+d+1}.0-0`):w=`>=${$}.${d}.${g} <${$}.${+d+1}.0-0`,o("tilde return",w),w})},x=(p,u)=>p.trim().split(/\s+/).map(I=>K(I,u)).join(" "),K=(p,u)=>{o("caret",p,u);const I=u.loose?r[e.CARETLOOSE]:r[e.CARET],v=u.includePrerelease?"-0":"";return p.replace(I,(S,$,d,g,T)=>{o("caret",p,S,$,d,g,T);let w;return A($)?w="":A(d)?w=`>=${$}.0.0${v} <${+$+1}.0.0-0`:A(g)?$==="0"?w=`>=${$}.${d}.0${v} <${$}.${+d+1}.0-0`:w=`>=${$}.${d}.0${v} <${+$+1}.0.0-0`:T?(o("replaceCaret pr",T),$==="0"?d==="0"?w=`>=${$}.${d}.${g}-${T} <${$}.${d}.${+g+1}-0`:w=`>=${$}.${d}.${g}-${T} <${$}.${+d+1}.0-0`:w=`>=${$}.${d}.${g}-${T} <${+$+1}.0.0-0`):(o("no pr"),$==="0"?d==="0"?w=`>=${$}.${d}.${g} <${$}.${d}.${+g+1}-0`:w=`>=${$}.${d}.${g} <${$}.${+d+1}.0-0`:w=`>=${$}.${d}.${g} <${+$+1}.0.0-0`),o("caret return",w),w})},Z=(p,u)=>(o("replaceXRanges",p,u),p.split(/\s+/).map(I=>J(I,u)).join(" ")),J=(p,u)=>{p=p.trim();const I=u.loose?r[e.XRANGELOOSE]:r[e.XRANGE];return p.replace(I,(v,S,$,d,g,T)=>{if(o("xRange",p,v,S,$,d,g,T),P($,d,g))return p;const w=A($),F=w||A(d),C=F||A(g),b=C;return S==="="&&b&&(S=""),T=u.includePrerelease?"-0":"",w?S===">"||S==="<"?v="<0.0.0-0":v="*":S&&b?(F&&(d=0),g=0,S===">"?(S=">=",F?($=+$+1,d=0,g=0):(d=+d+1,g=0)):S==="<="&&(S="<",F?$=+$+1:d=+d+1),S==="<"&&(T="-0"),v=`${S+$}.${d}.${g}${T}`):F?v=`>=${$}.0.0${T} <${+$+1}.0.0-0`:C&&(v=`>=${$}.${d}.0${T} <${$}.${+d+1}.0-0`),o("xRange return",v),v})},Q=(p,u)=>(o("replaceStars",p,u),p.trim().replace(r[e.STAR],"")),ee=(p,u)=>(o("replaceGTE0",p,u),p.trim().replace(r[u.includePrerelease?e.GTE0PRE:e.GTE0],"")),re=p=>(u,I,v,S,$,d,g,T,w,F,C,b)=>(A(v)?I="":A(S)?I=`>=${v}.0.0${p?"-0":""}`:A($)?I=`>=${v}.${S}.0${p?"-0":""}`:d?I=`>=${I}`:I=`>=${I}${p?"-0":""}`,A(w)?T="":A(F)?T=`<${+w+1}.0.0-0`:A(C)?T=`<${w}.${+F+1}.0-0`:b?T=`<=${w}.${F}.${C}-${b}`:p?T=`<${w}.${F}.${+C+1}-0`:T=`<=${T}`,`${I} ${T}`.trim()),te=(p,u,I)=>{for(let v=0;v<p.length;v++)if(!p[v].test(u))return!1;if(u.prerelease.length&&!I.includePrerelease){for(let v=0;v<p.length;v++)if(o(p[v].semver),p[v].semver!==h.ANY&&p[v].semver.prerelease.length>0){const S=p[v].semver;if(S.major===u.major&&S.minor===u.minor&&S.patch===u.patch)return!0}return!1}return!0};return Ge}var ye,Dr;function W(){if(Dr)return ye;Dr=1;const i=Symbol("SemVer ANY");class l{static get ANY(){return i}constructor(e,a){if(a=n(a),e instanceof l){if(e.loose===!!a.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),o("comparator",e,a),this.options=a,this.loose=!!a.loose,this.parse(e),this.semver===i?this.value="":this.value=this.operator+this.semver.version,o("comp",this)}parse(e){const a=this.options.loose?t[s.COMPARATORLOOSE]:t[s.COMPARATOR],c=e.match(a);if(!c)throw new TypeError(`Invalid comparator: ${e}`);this.operator=c[1]!==void 0?c[1]:"",this.operator==="="&&(this.operator=""),c[2]?this.semver=new f(c[2],this.options.loose):this.semver=i}toString(){return this.value}test(e){if(o("Comparator.test",e,this.options.loose),this.semver===i||e===i)return!0;if(typeof e=="string")try{e=new f(e,this.options)}catch{return!1}return h(e,this.operator,this.semver,this.options)}intersects(e,a){if(!(e instanceof l))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new r(e.value,a).test(this.value):e.operator===""?e.value===""?!0:new r(this.value,a).test(e.semver):(a=n(a),a.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!a.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||h(this.semver,"<",e.semver,a)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||h(this.semver,">",e.semver,a)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}}ye=l;const n=We(),{safeRe:t,t:s}=M(),h=zr(),o=B(),f=_(),r=X();return ye}var _e,Gr;function z(){if(Gr)return _e;Gr=1;const i=X();return _e=(n,t,s)=>{try{t=new i(t,s)}catch{return!1}return t.test(n)},_e}var je,yr;function ft(){if(yr)return je;yr=1;const i=X();return je=(n,t)=>new i(n,t).set.map(s=>s.map(h=>h.value).join(" ").trim().split(" ")),je}var Fe,_r;function ht(){if(_r)return Fe;_r=1;const i=_(),l=X();return Fe=(t,s,h)=>{let o=null,f=null,r=null;try{r=new l(s,h)}catch{return null}return t.forEach(m=>{r.test(m)&&(!o||f.compare(m)===-1)&&(o=m,f=new i(o,h))}),o},Fe}var Ue,jr;function Et(){if(jr)return Ue;jr=1;const i=_(),l=X();return Ue=(t,s,h)=>{let o=null,f=null,r=null;try{r=new l(s,h)}catch{return null}return t.forEach(m=>{r.test(m)&&(!o||f.compare(m)===1)&&(o=m,f=new i(o,h))}),o},Ue}var Xe,Fr;function pt(){if(Fr)return Xe;Fr=1;const i=_(),l=X(),n=Y();return Xe=(s,h)=>{s=new l(s,h);let o=new i("0.0.0");if(s.test(o)||(o=new i("0.0.0-0"),s.test(o)))return o;o=null;for(let f=0;f<s.set.length;++f){const r=s.set[f];let m=null;r.forEach(e=>{const a=new i(e.semver.version);switch(e.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!m||n(a,m))&&(m=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),m&&(!o||n(o,m))&&(o=m)}return o&&s.test(o)?o:null},Xe}var Ve,Ur;function Rt(){if(Ur)return Ve;Ur=1;const i=X();return Ve=(n,t)=>{try{return new i(n,t).range||"*"}catch{return null}},Ve}var xe,Xr;function Qe(){if(Xr)return xe;Xr=1;const i=_(),l=W(),{ANY:n}=l,t=X(),s=z(),h=Y(),o=Ke(),f=Je(),r=Ze();return xe=(e,a,c,R)=>{e=new i(e,R),a=new t(a,R);let L,E,O,q,G;switch(c){case">":L=h,E=f,O=o,q=">",G=">=";break;case"<":L=o,E=r,O=h,q="<",G="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(e,a,R))return!1;for(let j=0;j<a.set.length;++j){const y=a.set[j];let A=null,P=null;if(y.forEach(D=>{D.semver===n&&(D=new l(">=0.0.0")),A=A||D,P=P||D,L(D.semver,A.semver,R)?A=D:O(D.semver,P.semver,R)&&(P=D)}),A.operator===q||A.operator===G||(!P.operator||P.operator===q)&&E(e,P.semver))return!1;if(P.operator===G&&O(e,P.semver))return!1}return!0},xe}var be,Vr;function mt(){if(Vr)return be;Vr=1;const i=Qe();return be=(n,t,s)=>i(n,t,">",s),be}var He,xr;function $t(){if(xr)return He;xr=1;const i=Qe();return He=(n,t,s)=>i(n,t,"<",s),He}var Me,br;function vt(){if(br)return Me;br=1;const i=X();return Me=(n,t,s)=>(n=new i(n,s),t=new i(t,s),n.intersects(t,s)),Me}var ke,Hr;function It(){if(Hr)return ke;Hr=1;const i=z(),l=U();return ke=(n,t,s)=>{const h=[];let o=null,f=null;const r=n.sort((c,R)=>l(c,R,s));for(const c of r)i(c,t,s)?(f=c,o||(o=c)):(f&&h.push([o,f]),f=null,o=null);o&&h.push([o,null]);const m=[];for(const[c,R]of h)c===R?m.push(c):!R&&c===r[0]?m.push("*"):R?c===r[0]?m.push(`<=${R}`):m.push(`${c} - ${R}`):m.push(`>=${c}`);const e=m.join(" || "),a=typeof t.raw=="string"?t.raw:String(t);return e.length<a.length?e:t},ke}var Be,Mr;function dt(){if(Mr)return Be;Mr=1;const i=X(),l=W(),{ANY:n}=l,t=z(),s=U(),h=(a,c,R={})=>{if(a===c)return!0;a=new i(a,R),c=new i(c,R);let L=!1;e:for(const E of a.set){for(const O of c.set){const q=r(E,O,R);if(L=L||q!==null,q)continue e}if(L)return!1}return!0},o=[new l(">=0.0.0-0")],f=[new l(">=0.0.0")],r=(a,c,R)=>{if(a===c)return!0;if(a.length===1&&a[0].semver===n){if(c.length===1&&c[0].semver===n)return!0;R.includePrerelease?a=o:a=f}if(c.length===1&&c[0].semver===n){if(R.includePrerelease)return!0;c=f}const L=new Set;let E,O;for(const N of a)N.operator===">"||N.operator===">="?E=m(E,N,R):N.operator==="<"||N.operator==="<="?O=e(O,N,R):L.add(N.semver);if(L.size>1)return null;let q;if(E&&O){if(q=s(E.semver,O.semver,R),q>0)return null;if(q===0&&(E.operator!==">="||O.operator!=="<="))return null}for(const N of L){if(E&&!t(N,String(E),R)||O&&!t(N,String(O),R))return null;for(const x of c)if(!t(N,String(x),R))return!1;return!0}let G,j,y,A,P=O&&!R.includePrerelease&&O.semver.prerelease.length?O.semver:!1,D=E&&!R.includePrerelease&&E.semver.prerelease.length?E.semver:!1;P&&P.prerelease.length===1&&O.operator==="<"&&P.prerelease[0]===0&&(P=!1);for(const N of c){if(A=A||N.operator===">"||N.operator===">=",y=y||N.operator==="<"||N.operator==="<=",E){if(D&&N.semver.prerelease&&N.semver.prerelease.length&&N.semver.major===D.major&&N.semver.minor===D.minor&&N.semver.patch===D.patch&&(D=!1),N.operator===">"||N.operator===">="){if(G=m(E,N,R),G===N&&G!==E)return!1}else if(E.operator===">="&&!N.test(E.semver))return!1}if(O){if(P&&N.semver.prerelease&&N.semver.prerelease.length&&N.semver.major===P.major&&N.semver.minor===P.minor&&N.semver.patch===P.patch&&(P=!1),N.operator==="<"||N.operator==="<="){if(j=e(O,N,R),j===N&&j!==O)return!1}else if(O.operator==="<="&&!N.test(O.semver))return!1}if(!N.operator&&(O||E)&&q!==0)return!1}return!(E&&y&&!O&&q!==0||O&&A&&!E&&q!==0||D||P)},m=(a,c,R)=>{if(!a)return c;const L=s(a.semver,c.semver,R);return L>0?a:L<0||c.operator===">"&&a.operator===">="?c:a},e=(a,c,R)=>{if(!a)return c;const L=s(a.semver,c.semver,R);return L<0?a:L>0||c.operator==="<"&&a.operator==="<="?c:a};return Be=h,Be}var Ye,kr;function Lt(){if(kr)return Ye;kr=1;const i=M(),l=H(),n=_(),t=Br(),s=V(),h=Kr(),o=Zr(),f=Jr(),r=Qr(),m=et(),e=rt(),a=tt(),c=st(),R=U(),L=nt(),E=it(),O=ze(),q=at(),G=ot(),j=Y(),y=Ke(),A=Yr(),P=Wr(),D=Ze(),N=Je(),x=zr(),K=ct(),Z=lt(),J=W(),Q=X(),ee=z(),re=ft(),te=ht(),p=Et(),u=pt(),I=Rt(),v=Qe(),S=mt(),$=$t(),d=vt(),g=It(),T=dt();return Ye={parse:s,valid:h,clean:o,inc:f,diff:r,major:m,minor:e,patch:a,prerelease:c,compare:R,rcompare:L,compareLoose:E,compareBuild:O,sort:q,rsort:G,gt:j,lt:y,eq:A,neq:P,gte:D,lte:N,cmp:x,coerce:K,truncate:Z,Comparator:J,Range:Q,satisfies:ee,toComparators:re,maxSatisfying:te,minSatisfying:p,minVersion:u,validRange:I,outside:v,gtr:S,ltr:$,intersects:d,simplifyRange:g,subset:T,SemVer:n,re:i.re,src:i.src,tokens:i.t,SEMVER_SPEC_VERSION:l.SEMVER_SPEC_VERSION,RELEASE_TYPES:l.RELEASE_TYPES,compareIdentifiers:t.compareIdentifiers,rcompareIdentifiers:t.rcompareIdentifiers},Ye}var Nt=Lt();export{Nt as s};
@@ -0,0 +1,10 @@
1
+ import{Project as $,SyntaxKind as d,Node as u}from"ts-morph";const E=/^[A-Za-z_$][\w$]*$/u,i=t=>`// lunora:add:${t}:start`,p=t=>`// lunora:add:${t}:end`,A=/\/\/ lunora:add:[A-Za-z_$][\w$]*:end/gu,I=/^(?:\s*(?:;|\/\/ lunora:add:[A-Za-z_$][\w$]*:end))*/u,T=t=>`./${t}/schema`,h=(t,e)=>t.getLocal(e)!==void 0?!0:t.getImportDeclarations().some(n=>n.getDefaultImport()?.getText()===e||n.getNamespaceImport()?.getText()===e||n.getNamedImports().some(r=>(r.getAliasNode()??r.getNameNode()).getText()===e)),N=t=>{for(const e of t)if(e.getExpression().getText()==="defineSchema")return e},S=t=>{let e=t;for(let n=e.getParent();n!==void 0;n=e.getParent())if(u.isPropertyAccessExpression(n)&&n.getExpression()===e)e=n;else if(u.isCallExpression(n)&&n.getExpression()===e)e=n;else break;return e},R=(t,e)=>{if(!E.test(e))return{ok:!1,reason:"invalid-identifier"};if(t.includes(i(e)))return{ok:!1,reason:"already-applied"};const r=new $({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("schema.ts",t,{overwrite:!0});if(h(r,e))return{ok:!1,reason:"already-applied"};const m=r.getDescendantsOfKind(d.CallExpression),o=N(m);if(!o)return{ok:!1,reason:"no-define-schema"};if(o.getArguments()[0]?.getKind()!==d.ObjectLiteralExpression)return{ok:!1,reason:"non-object-argument"};const s=S(o).getEnd(),a=I.exec(r.getFullText().slice(s))?.[0]??"",l=a.match(A)??[],c=`
2
+ ${i(e)}
3
+ .extend(${e}.extension)
4
+ ${p(e)}`;if(l.length===0)r.insertText(s,`${c}
5
+ `);else{const g=l.map(x=>`
6
+ ${x}`).join("");r.replaceText([s,s+a.length],`${g}${c}${a.includes(";")?`
7
+ ;`:""}`)}const f=`${i(e)}
8
+ import { ${e} } from "${T(e)}";
9
+ ${p(e)}
10
+ `;return r.insertText(0,f),{ok:!0,text:r.getFullText()}};export{R as insertSchemaExtension};
@@ -0,0 +1 @@
1
+ const t=/[\u003C\u003E\u002F\u2028\u2029]/g,S={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},n=u=>JSON.stringify(u).replaceAll(t,r=>S[r]??r);export{n as l};
@@ -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};