@lunora/cli 1.0.0-alpha.45 → 1.0.0-alpha.451

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 (141) 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 +1096 -386
  8. package/dist/index.d.ts +1096 -386
  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 +17 -158
  13. package/dist/packem_chunks/handler10.mjs +1 -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 +7 -170
  23. package/dist/packem_chunks/handler2.mjs +1 -114
  24. package/dist/packem_chunks/handler20.mjs +2 -94
  25. package/dist/packem_chunks/handler21.mjs +1 -94
  26. package/dist/packem_chunks/handler22.mjs +3 -0
  27. package/dist/packem_chunks/handler23.mjs +3 -0
  28. package/dist/packem_chunks/handler24.mjs +1 -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 +99 -0
  32. package/dist/packem_chunks/handler28.mjs +15 -0
  33. package/dist/packem_chunks/handler29.mjs +1 -0
  34. package/dist/packem_chunks/handler3.mjs +1 -204
  35. package/dist/packem_chunks/handler4.mjs +1 -33
  36. package/dist/packem_chunks/handler5.mjs +3 -49
  37. package/dist/packem_chunks/handler6.mjs +1 -91
  38. package/dist/packem_chunks/handler7.mjs +1 -42
  39. package/dist/packem_chunks/handler8.mjs +1 -174
  40. package/dist/packem_chunks/handler9.mjs +2 -315
  41. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  42. package/dist/packem_chunks/runDevCommand.mjs +6 -0
  43. package/dist/packem_chunks/runInitCommand.mjs +212 -1432
  44. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  45. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  46. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-5xxKz-zB.mjs +1 -0
  47. package/dist/packem_shared/EXIT_CODE-DVjUgIaG.mjs +1 -0
  48. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  49. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  50. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  51. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  52. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  53. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  54. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  55. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  56. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  57. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  58. package/dist/packem_shared/command-B6vu47iR.mjs +1 -0
  59. package/dist/packem_shared/commands-DC3ZX1yk.mjs +13 -0
  60. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  61. package/dist/packem_shared/createRecordingSpawner-01ZngIwK.mjs +1 -0
  62. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  63. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  64. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  65. package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
  66. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  67. package/dist/packem_shared/import-DoAUdyfU.mjs +13 -0
  68. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  69. package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
  70. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  71. package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
  72. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  73. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  74. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  75. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  76. package/dist/packem_shared/plan-BH4ZfiFs.mjs +5 -0
  77. package/dist/packem_shared/planDevCommand-I8-NB_CN.mjs +1 -0
  78. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  79. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  80. package/dist/packem_shared/render-lunora-error-DUo0pA61.mjs +2 -0
  81. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  82. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  83. package/dist/packem_shared/runAddCommand-CTblwN9O.mjs +1 -0
  84. package/dist/packem_shared/runDeployCommand-C5L6ZhGV.mjs +1 -0
  85. package/dist/packem_shared/runExportCommand-DiMCQ-Il.mjs +5 -0
  86. package/dist/packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs +11 -0
  87. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  88. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  89. package/dist/packem_shared/storage-BLLoZRJa.mjs +1 -0
  90. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  91. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  92. package/dist/packem_shared/vectorize-metadata-DOB1akh6.mjs +2 -0
  93. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  94. package/dist/packem_shared/wrangler-secrets-DlSlWvRH.mjs +1 -0
  95. package/package.json +43 -19
  96. package/skills/README.md +36 -17
  97. package/skills/lunora/SKILL.md +158 -65
  98. package/skills/lunora-cloudflare-audit/SKILL.md +163 -0
  99. package/skills/lunora-create-package/SKILL.md +97 -84
  100. package/skills/lunora-deploy/SKILL.md +175 -105
  101. package/skills/lunora-functions/SKILL.md +367 -60
  102. package/skills/lunora-migration-helper/SKILL.md +168 -137
  103. package/skills/lunora-performance-audit/SKILL.md +137 -95
  104. package/skills/lunora-quickstart/SKILL.md +136 -136
  105. package/skills/lunora-realtime/SKILL.md +217 -97
  106. package/skills/lunora-setup-auth/SKILL.md +203 -101
  107. package/skills/lunora-setup-hyperdrive/SKILL.md +138 -109
  108. package/skills/lunora-setup-hyperdrive-global/SKILL.md +125 -92
  109. package/skills/lunora-setup-mail/SKILL.md +85 -113
  110. package/skills/lunora-setup-scheduler/SKILL.md +132 -96
  111. package/skills/lunora-setup-storage/SKILL.md +189 -95
  112. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  113. package/dist/packem_chunks/runDeployCommand.mjs +0 -594
  114. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  115. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  116. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  117. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  118. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  119. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  120. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  121. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  122. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  123. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  124. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  125. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  126. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  127. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  128. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  129. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  130. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  131. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  132. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  133. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  134. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  135. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  136. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  137. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  138. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  139. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  140. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  141. 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-B6vu47iR.mjs";import{EXIT_CODE as s}from"../packem_shared/EXIT_CODE-DVjUgIaG.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-B6vu47iR.mjs";import{EXIT_CODE as i,exitCodeForStatus as E}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{r as I}from"../packem_shared/resolve-target-C_ZloTvd.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"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./EXIT_CODE-DVjUgIaG.mjs";import{D as a,r as I}from"./import-DoAUdyfU.mjs";import"./shared-D-zCOmgY.mjs";export{a as DEFAULT_IMPORT_BATCH_SIZE,I as runImportCommand};
@@ -0,0 +1 @@
1
+ import{isLunoraError as N,getCatalogEntry as _}from"@lunora/errors";const E={SUCCESS:0,FAILURE:1,USAGE:2,AUTH:3,PERMISSION:4,NOT_FOUND:5,CONFLICT:6,RATE_LIMITED:7,UNAVAILABLE:8,MISSING_DEPENDENCY:9,CANCELLED:130},U=new Map([[400,E.USAGE],[401,E.AUTH],[403,E.PERMISSION],[404,E.NOT_FOUND],[405,E.USAGE],[409,E.CONFLICT],[413,E.USAGE],[421,E.UNAVAILABLE],[422,E.USAGE],[429,E.RATE_LIMITED],[502,E.UNAVAILABLE],[503,E.UNAVAILABLE],[504,E.UNAVAILABLE],[507,E.USAGE]]),S=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],["SCHEMA_SNAPSHOT_PARSE",E.USAGE]]),I=A=>A===void 0?E.FAILURE:U.get(A)??E.FAILURE,T=A=>S.get(A)??I(_(A)?.status),L=A=>N(A)?S.get(A.code)??I(A.status):E.FAILURE,O=A=>"refused"in A;export{E as EXIT_CODE,T as exitCodeForCode,L as exitCodeForError,I 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-DVjUgIaG.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-DUo0pA61.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-DVjUgIaG.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 T}from"node:child_process";import{StringDecoder as E}from"node:string_decoder";import{LunoraError as g}from"@lunora/errors";const D=/[\s"%&<>^|]/u,N=500,_=e=>{let a="",r=0;for(const n of e)n==="\\"?r+=1:(a+=n==='"'?`${"\\".repeat(r*2+1)}"`:`${"\\".repeat(r)}${n}`,r=0);return a+"\\".repeat(r*2)},v=(e,a,r=process.platform)=>{if(r!=="win32"||e===process.execPath)return{args:[...a],command:e,shell:!1};const n=s=>s===""?'""':D.test(s)?`"${_(s)}"`:s;return{args:a.map(s=>n(s)),command:n(e),shell:!0}},P=e=>new Promise((a,r)=>{const n=typeof e.input=="string",s=e.captureStdout===!0,u=e.captureStdoutSilently===!0;let i="inherit";s||u?i="pipe":e.stdoutToStderr&&(i=2);const c=v(e.command,e.args),t=T(c.command,c.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:c.shell,stdio:[n?"pipe":"inherit",i,e.captureStderr===!0?"pipe":"inherit"]}),l=new E("utf8"),p=new E("utf8");let f="",w="";e.captureStderr===!0&&t.stderr&&t.stderr.on("data",o=>{w+=p.write(o),process.stderr.write(o)}),(s||u)&&t.stdout&&t.stdout.on("data",o=>{f+=l.write(o),s&&process.stdout.write(o)});let d=!1;t.on("error",o=>{if(d=!0,o.code==="ENOENT"){r(new g("LOCAL_DEPENDENCY_MISSING",`\`${e.command}\` is not installed or not on your PATH — nothing was run.`,{cause:o}));return}r(o)});let m=0,S;const h=()=>{d||(d=!0,clearTimeout(S),a({code:m,stderr:e.captureStderr===!0?w+p.end():void 0,stdout:s||u?f+l.end():void 0}))};t.on("exit",(o,C)=>{m=o??(C?1:0),S=setTimeout(()=>{t.stdout?.destroy(),t.stderr?.destroy(),h()},N)}),t.on("close",h),n&&t.stdin&&(t.stdin.on("error",()=>{}),t.stdin.end(e.input))}),$=(e=0)=>{const a=[];return{calls:a,spawner:n=>(a.push({descriptor:n}),Promise.resolve({code:e}))}};export{$ as createRecordingSpawner,P as defaultSpawner,v 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 v=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}),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,v as validatorKindToSqlType};
@@ -0,0 +1 @@
1
+ import{spawnSync as r}from"node:child_process";const s=()=>{try{return r("docker",["info"],{stdio:"ignore"}).status===0}catch{return!1}},t=()=>{if(typeof process.env.BUILDKIT_HOST!="string"||process.env.BUILDKIT_HOST.length===0)return!1;try{return r("railpack",["--version"],{stdio:"ignore"}).status===0}catch{return!1}};export{t as a,s as i};
@@ -0,0 +1 @@
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 @@
1
+ import{existsSync as p,readFileSync as b,writeFileSync as S}from"node:fs";import{parseSchemaSnapshot as w,SchemaSnapshotParseError as y,evaluateSchemaDrift as k,serializeSchemaSnapshot as H}from"@lunora/codegen";const P=e=>{if(!p(e))return{status:"absent"};let r;try{r=b(e,"utf8")}catch{return{status:"corrupt"}}try{const a=w(r);return a===void 0?{status:"corrupt"}:{snapshot:a,status:"ok"}}catch(a){if(a instanceof y)return{status:"corrupt"};throw a}},v=(e,r)=>{S(e,H(r),"utf8")},$=e=>{const r=`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 pass --update-schema-baseline to regenerate it from the current schema.`;return e.updateBaseline&&!e.readOnly?(e.logger.warn(`schema baseline was unreadable; regenerating from the current schema on success (--update-schema-baseline): ${e.snapshotPath}`),{blocked:!1,changes:[],reason:r,rebless:e.rebless}):(e.readOnly||e.logger.error(r),{blocked:!0,changes:[],reason:r})},O=(e,r)=>(r.readOnly||r.logger.error(e.reason),r.updateBaseline&&!r.readOnly?(r.logger.warn(`schema baseline will be re-blessed despite breaking drift on success (--update-schema-baseline): ${r.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason,rebless:r.rebless}):{blocked:!0,changes:e.changes,reason:e.reason}),E=e=>{const{allowDrift:r,codegen:a,command:h,logger:c,readOnly:i=!1,updateBaseline:t=!1}=e,s=a.schemaSnapshotPath,o=P(s),l={logger:c,readOnly:i,rebless:()=>{v(s,a.schemaSnapshot)},snapshotPath:s,updateBaseline:t};if(o.status==="corrupt")return $(l);const u=m=>k({allowDrift:m,baseline:o.status==="ok"?o.snapshot:void 0,command:h,current:a.schemaSnapshot,migrations:a.migrations}),n=u(r);if(n.blocked)return O(n,l);const g=r&&n.changes.length>0&&u(!1).blocked;return n.changes.length>0?(i||c.info(n.reason),g&&!t?(i||c.warn(`schema baseline left at its committed shape — --allow-schema-drift overrides this run only. Pass --update-schema-baseline to accept the new shape: ${s}`),{blocked:!1,changes:n.changes,reason:n.reason}):{blocked:!1,changes:n.changes,reason:n.reason,rebless:i?void 0:l.rebless}):{blocked:!1,changes:n.changes,reason:n.reason}},f="/_lunora/health",_="/_lunora/health/ready",T=(e,r=f)=>(e.endsWith("/")?e.slice(0,-1):e)+r,d=async(e,r,a)=>{let h={error:`health probe failed: no health path configured for ${e}`,url:e};for(const[c,i]of r.entries()){const t=T(e,i);let s;try{s=await a(t)}catch(o){const l=o instanceof Error?o.message:String(o);return{error:`health probe failed: could not reach ${t} (${l})`,url:t}}if(s.ok)return{url:t};if(h={error:`health probe failed: ${t} returned HTTP ${String(s.status)}`,url:t},s.status!==404||c===r.length-1)return h}return h},A=async e=>new Promise(r=>{setTimeout(r,e)}),F=async({attempts:e=1,baseUrl:r,delayMs:a=2e3,fetchImpl:h,paths:c=[f],sleep:i=A,timeoutMs:t=1e4})=>{const s=h??(u=>fetch(u,{signal:AbortSignal.timeout(t)})),o=Math.max(1,e);let l=await d(r,c,s);for(let u=1;u<o&&l.error!==void 0;u+=1)await i(a),l=await d(r,c,s);return l};export{_ as H,f as a,F as p,E as r};
@@ -0,0 +1,13 @@
1
+ import{createReadStream as E}from"node:fs";import{open as st,stat as L,readdir as x,realpath as ae,readFile as v,mkdir as J,writeFile as $e,appendFile as ot}from"node:fs/promises";import{t as it,r as at}from"./admin-token-VdUnvnKW.mjs";import{r as ct,a as dt}from"./admin-url-DJB8P6Jh.mjs";import{EXIT_CODE as $,isRefusal as lt}from"./EXIT_CODE-DVjUgIaG.mjs";import{join as w,resolve as F,basename as p,dirname as Se,relative as ut,sep as ft}from"node:path";import{createInterface as M}from"node:readline";import ht from"adm-zip";import{i as ve}from"./path-containment-CgxYZggb.mjs";import{Transform as gt}from"node:stream";import{createInflateRaw as mt,crc32 as pt}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{parse as yt}from"csv-parse/sync";import{parse as Ne}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as wt}from"@lunora/runtime";import{S as V,a as bt,I as $t}from"./shared-D-zCOmgY.mjs";import{createHash as St}from"node:crypto";const vt=67324752,O=30,Nt=26,Et=28,ce=0,Tt=8,It=async(e,t)=>{const r=await st(e,"r");try{const n=Buffer.alloc(O),{bytesRead:s}=await r.read(n,0,O,t);if(s<O||n.readUInt32LE(0)!==vt)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+O+n.readUInt16LE(Nt)+n.readUInt16LE(Et)}finally{await r.close()}},de=e=>{let t=0;return new gt({flush(r){if(t===e.header.crc){r();return}r(new Error(`${e.entryName} failed its CRC check — the archive is corrupt or truncated (expected ${String(e.header.crc)}, read ${String(t)})`))},transform(r,n,s){t=pt(r,t),s(void 0,r)}})},At=async(e,t)=>{const{compressedSize:r,encrypted:n,method:s,offset:o}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(s!==ce&&s!==Tt)throw new Error(`${t.entryName} uses unsupported compression method ${String(s)} — re-create the archive with standard deflate`);if(r===0){if(t.header.size>0||t.header.crc!==0)throw new Error(`${t.entryName} declares 0 compressed bytes but ${String(t.header.size)} uncompressed with CRC ${String(t.header.crc)} — the archive is corrupt`);return}const i=await It(e,o),a=E(e,{end:i+r-1,start:i});if(s===ce){const l=de(t);return a.on("error",u=>l.destroy(u)),a.pipe(l)}const c=mt(),d=de(t);return a.on("error",l=>c.destroy(l)),c.on("error",l=>d.destroy(l)),a.pipe(c).pipe(d)},N="_storage",Ee=e=>e.startsWith("_"),Rt=e=>{for(const t of e.getEntries()){const n=t.entryName.replaceAll("\\","/").split("/");if(n.length>=2&&n[n.length-2]==="_storage")return n.slice(0,-1).join("/")}return"_storage"},_t=async e=>{const t=await L(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new ht(e);return{kind:"zip",storagePrefix:Rt(r),zip:r,zipPath:e}}},Ot=async e=>{const t=[];for(const r of await x(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=w(e,r.name,"documents.jsonl");(await L(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},kt=e=>{const t=[];for(const r of e.getEntries()){if(r.isDirectory)continue;const n=r.entryName.replaceAll("\\","/"),s=n.split("/");s.length>=2&&s[s.length-1]==="documents.jsonl"&&t.push({file:n,table:s[s.length-2]})}return t},Lt=async e=>{const t=e.kind==="directory"?await Ot(e.root):kt(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},H=async function*(e,t){if(e.kind==="directory"){for await(const o of M({crlfDelay:Number.POSITIVE_INFINITY,input:E(t.file,{encoding:"utf8"})}))yield o;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await At(e.zipPath,r);if(n===void 0)return;const s=M({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const o of s)yield o}finally{s.close(),n.destroy()}},xt=async(e,t)=>{if(e.kind==="directory"){const n=await ae(w(e.root,"_storage")),s=await ae(F(n,t)).catch(()=>{});if(s===void 0||!ve(n,s))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return v(s)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},j=207,Ct=e=>{const t={conflicts:0,errors:[],failed:[],inserted:{},received:0,replaced:0,warnings:[]};let r=[],n=0;const s=a=>{for(const[c,d]of Object.entries(a.inserted??{}))t.inserted[c]=(t.inserted[c]??0)+d;t.errors.push(...a.errors??[]),t.failed.push(...a.failed??[]),t.conflicts+=a.conflicts??0,t.received+=a.received??0,t.replaced+=a.replaced??0;for(const c of a.warnings??[])t.warnings.includes(c)||t.warnings.push(c)},o=async()=>{if(r.length===0)return;const a=r.join(`
2
+ `);r=[],n=0;const c=await e.fetchImpl(e.requestUrl,{body:a,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!c.ok&&c.status!==j){const l=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`import batch failed (HTTP ${String(c.status)}): ${l}`)}const d=await c.json();s(d),c.status===j&&(d.failed??[]).length===0&&t.failed.push({message:`the endpoint answered ${String(j)} without naming the failed shards`,shardKey:"<unknown>",timedOut:!1})};return{flush:o,push:async a=>{const c=Buffer.byteLength(a)+1;r.length>0&&n+c>e.maxBatchBytes&&await o(),r.push(a),n+=c,r.length>=e.batchSize&&await o()},totals:t}},Te=(e,t,r,n)=>{const s=[],o=[];let i=0;const a=l=>n?.[r]?.includes(l)===!0,c=(l,u,h=!1)=>{if(Array.isArray(l))return l.map(g=>c(g,u,h));if(l!==null&&typeof l=="object"){const g=l;if(typeof g.$storage=="string"){const m=g.$storage,y=t.get(m);return y===void 0?(o.push({column:u,storageId:m,table:r}),l):(i+=1,y)}return Object.fromEntries(Object.entries(g).map(([m,y])=>[m,c(y,u)]))}return typeof l=="string"&&t.has(l)?a(u)?(i+=1,t.get(l)??l):(s.push({column:u,storageId:l,table:r}),l):(h&&typeof l=="string"&&l.length>0&&a(u)&&n!==void 0&&o.push({column:u,storageId:l,table:r}),l)},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,c(u,l,!0)]));return{ambiguous:s,document:d,rewritten:i,unmigrated:o}},le=(e,t,r)=>{for(const n of r){const s=`${n.table}\0${n.column}\0${n.storageId}`;t.has(s)||(t.add(s),e.push(n))}},Ut=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:s,table:o}=e,i=new Set,a=new Set,c=(u,h)=>{let g;try{g=JSON.parse(u)}catch(m){const y=m instanceof Error?m.message:String(m);throw new f("INTERNAL",`invalid JSON on line ${String(h)}: ${y}`,{cause:m})}return JSON.stringify({doc:g,table:o})},d=(u,h)=>{let g;try{g=JSON.parse(u)}catch(y){throw new f("INTERNAL",`line ${String(h)}: import envelope is not valid JSON — ${y instanceof Error?y.message:String(y)}`,{cause:y})}const m=g===null||typeof g!="object"||Array.isArray(g)?void 0:g;if(m===void 0||typeof m.table!="string")throw new f("INTERNAL",`line ${String(h)}: import envelope is missing a string \`table\``);return m},l=u=>{if(u.doc!==null&&typeof u.doc=="object"&&!Array.isArray(u.doc)){let h=u.doc;if(s!==void 0){const g=Te(h,s,u.table,n);h=g.document,r.rewritten+=g.rewritten,le(r.ambiguous,i,g.ambiguous),le(r.unmigrated,a,g.unmigrated)}return JSON.stringify({...u,doc:t===void 0?h:t(h,u.table)})}return JSON.stringify(u)};return(u,h)=>{const g=u.trim();if(g.length===0)return;if(o!==void 0)return c(g,h);const m=d(g,h);return s===void 0&&t===void 0?g:l(m)}},Ie=async(e,t,r,n)=>{const s=await n(e).catch(()=>{});if(s===void 0)throw new f("INTERNAL",`${e} is not a readable directory`);const o=new Map;for(const[d,l]of Object.entries(t?.tables??{}))l.file!==void 0&&o.set(p(l.file),d);const i=s.filter(d=>d.isFile()&&r.matches(d.name)&&!r.authFiles.has(d.name)).map(d=>({file:w(e,d.name),table:o.get(d.name)??r.tableNameOf(d.name)}));if(i.length===0)throw new f("INTERNAL",`${e} ${r.emptyMessage}`);const a=new Set(i.map(d=>p(d.file))),c=[...o].filter(([d])=>!a.has(d));if(c.length>0)throw new f("INTERNAL",`${e}: the mapping names ${String(c.length)} file(s) that are not importable from this directory — ${c.map(([d,l])=>`\`${d}\` (table \`${l}\`)`).join(", ")}. Check the name and that the file is one this source reads.`);return i.toSorted((d,l)=>d.table.localeCompare(l.table))},Ae=async function*(e,t,r,n){for(const s of e){r.has(s.table)||r.set(s.table,0),t.info(`reading ${p(s.file)} → ${s.table}`);for await(const o of n(s))r.set(s.table,(r.get(s.table)??0)+1),yield`${JSON.stringify({doc:o,table:s.table})}
3
+ `}},Re=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],Pt=e=>Re.includes(e),jt=/^\\x([\dA-Fa-f]*)$/,ue=/^[+-]?\d+$/,_e=/[+-]\d{2}$/,Oe=/(?:Z|[+-]\d{2}:\d{2})$/i,ke=/^\+/,Ft=/e/i,Mt=/e/i,Dt=e=>{const[t="0",r="0"]=e.split(Mt),n=Number(r),s=t.startsWith("-"),[o="0",i=""]=(s?t.slice(1):t).replace(ke,"").split("."),a=`${o}${i}`,c=o.length+n;let d;return c<=0?d=`0.${"0".repeat(-c)}${a}`:c>=a.length?d=`${a}${"0".repeat(c-a.length)}`:d=`${a.slice(0,c)}.${a.slice(c)}`,s?`-${d}`:d},zt=/^0+(?=\d)/,fe=e=>{const r=(Ft.test(e.trim())?Dt(e.trim()):e.trim()).replace(ke,""),n=r.startsWith("-"),[s="0",o=""]=(n?r.slice(1):r).split("."),i=s.replace(zt,"");let a=o.length;for(;a>0&&o[a-1]==="0";)a-=1;const c=o.slice(0,a),d=c.length>0?`${i}.${c}`:i;return n&&Number(d)!==0?`-${d}`:d},b=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},he=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),s=_e.test(n)?`${n}:00`:n,o=Oe.test(s)?s:`${s}Z`,i=Date.parse(o);return Number.isNaN(i)&&b(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),i},Bt=(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 s="",o=!1,i=!1,a=!1;const c=()=>{n.push(!i&&s==="NULL"?null:s),s="",i=!1};for(const d of r)a?(s+=d,a=!1):d==="\\"?a=!0:d==='"'?(o=!o,i=!0):d===","&&!o?c():s+=d;return c(),n},Le=(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=jt.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 s=n[1];return s.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(s,"hex").toString("base64")}case"int8-string":return ue.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(ue.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(fe(String(n))!==fe(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 Bt(e,r);case"timestamp-iso":{he(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),s=_e.test(n)?`${n}:00`:n;return Oe.test(s)?s:`${s}Z`}case"timestamp-ms":return he(e,t,r);default:return r}},Jt="auth.",Vt=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),Ht=String.raw`\N`,xe=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===Ht?null:e,Gt=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),qt=async(e,t)=>Ie(e,t,{authFiles:Gt(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(Jt),tableNameOf:r=>p(r,".csv")},async r=>x(r,{withFileTypes:!0})),Wt=(e,t,r)=>{const n=t?.idColumn??"id",s=t?.types??{},o={};let i=!1;for(const[a,c]of Object.entries(e)){if(Vt.has(a.toLowerCase()))throw new f("INTERNAL",`${r}.${a} is credential material — this looks like an auth dump being imported as a table. Name it under \`auth\` in the mapping instead; passwords are never migrated.`);const d=s[a],l=d===void 0?c:Le(a,d,c);if(a===n){if(c===null)throw new f("INTERNAL",`id column \`${n}\` is NULL — every row needs an id to preserve`);o._id=c,i=!0}else{if(a==="_id")throw new f("INTERNAL",`${r}: source column \`_id\` collides with the reserved id field. Rename it in the source, or map it via \`tables.${r}.idColumn\` if it IS the id.`);o[a]=l}}if(!i)throw new f("INTERNAL",`${r}: no \`${n}\` column to preserve as the id (columns present: ${Object.keys(e).join(", ")}). Set \`tables.${r}.idColumn\` in the mapping.`);return o},Kt=async function*(e,t){const r=t?.tables?.[e.table],n=E(e.file).pipe(Ne({cast:xe,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let s=0;const o=n[Symbol.asyncIterator]();for(;;){let i,a;try{if(i=await o.next(),i.done===!0)return;s+=1,a=Wt(i.value,r,e.table)}catch(c){throw new f("INTERNAL",`${p(e.file)} row ${String(s+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},Yt=async function*(e,t,r,n,s){yield*Pe("supabase",s,t,r,n),yield*Ae(e,r,n,o=>Kt(o,t))},Xt=/^\d+$/,Zt=/[+-]\d{2}$/,D=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&Xt.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Zt.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},Ce=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},Qt=e=>{const t=Ce(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]}},er=e=>{const t=Ce(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},tr=(e,t)=>{const{id:r}=e;if(typeof r!="string"||r.length===0)throw new f("INTERNAL","auth row is missing `id` — every user needs an id to preserve");const n=e.raw_user_meta_data,s={_id:r,email:e.email??null,emailVerified:typeof e.email_confirmed_at=="string"&&e.email_confirmed_at.length>0,id:r},o=Qt(n),i=er(n),a=D(e.created_at),c=D(e.updated_at);return o!==void 0&&(s.name=o),i!==void 0&&(s.image=i),a!==void 0&&(s.createdAt=a),c!==void 0&&(s.updatedAt=c),{accounts:t.map(l=>{const u=typeof l.provider=="string"?l.provider:"unknown",h=typeof l.provider_id=="string"?l.provider_id:r,g=`${r}:${u}:${h}`;return{_id:g,accountId:h,id:g,providerId:u,userId:r}}),user:s}},rr=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=D(e.createdAt);return typeof e.displayName=="string"&&(r.name=e.displayName),typeof e.photoUrl=="string"&&(r.image=e.photoUrl),n!==void 0&&(r.createdAt=n),{accounts:(e.providerUserInfo??[]).filter(o=>typeof o.providerId=="string"&&o.providerId!=="password").map(o=>{const i=o.providerId,a=o.rawId??o.federatedId??t,c=`${t}:${i}:${a}`;return{_id:c,accountId:a,id:c,providerId:i,userId:t}}),user:r}},nr=(e,t)=>{const r=new Map,n=[],s=[];for(const{accounts:o,user:i}of e){const a=typeof i.email=="string"?i.email.toLowerCase():void 0;if(a!==void 0&&a.length>0){const c=r.get(a);c===void 0?r.set(a,String(i._id)):n.push(`${a} (ids ${c} and ${String(i._id)})`)}s.push(`${JSON.stringify({doc:i,table:"user"})}
4
+ `),t.set("user",(t.get("user")??0)+1);for(const c of o)s.push(`${JSON.stringify({doc:c,table:"account"})}
5
+ `),t.set("account",(t.get("account")??0)+1)}if(n.length>0)throw new f("INTERNAL",`auth import found ${String(n.length)} duplicate email(s), which would merge distinct users: ${n.slice(0,10).join("; ")}${n.length>10?" …":""}`);return s},G=(e,t)=>w(e,p(t)),Ue=async e=>{const t=await v(e,"utf8");return yt(t,{cast:xe,columns:!0,skipEmptyLines:!0})},sr=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Ue(G(e,t))){const s=n.user_id;typeof s=="string"&&r.set(s,[...r.get(s)??[],n])}return r},or=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Ue(G(e,r)),s=await sr(e,t.auth?.identitiesFile);return n.map(o=>tr(o,s.get(o.id??"")??[]))},ir=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=G(e,r);let s;try{s=JSON.parse(await v(n,"utf8"))}catch(i){throw new f("INTERNAL",`${p(n)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}const o=Array.isArray(s)?s:s.users??[];if(!Array.isArray(o))throw new f("INTERNAL",`${p(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return o.map(i=>rr(i))},Pe=async function*(e,t,r,n,s){if(r?.auth?.file===void 0)return;const o=e==="supabase"?await or(t,r):await ir(t,r);n.info(`auth: ${String(o.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const i of nr(o,s))yield i},ge=/\.(?:nd)?json$/i,je=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},ar=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},cr=(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")},dr=(e,t)=>{const r=typeof e=="string"?Date.parse(e):ar(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},lr=(e,t)=>typeof e=="string"?e:cr(e,t),Fe=(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 dr(e.timestampValue,t);if(e.bytesValue!==void 0)return lr(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 je(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Fe(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return z(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},ur=new Set(["createTime","fields","name","readTime","updateTime"]),fr=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},hr=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>ur.has(r))&&!fr(t)},z=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Fe(n,`${t}.${r}`)])),gr=(e,t,r,n)=>{const s=hr(e),o=z(s?e.fields??{}:e,n),i=e.name??e.__name__,a=typeof i=="string"?je(i):t;if(a===void 0)throw new f("INTERNAL",`${n}: no document id — expected a \`name\`/\`__name__\` resource path, or a document keyed by its id`);const c=r?.types??{};for(const[d,l]of Object.entries(c)){const u=o[d];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${d}: a \`${l}\` reshape needs a scalar, but this field decoded to an object or array`);o[d]=Le(d,l,u===null?null:String(u))}}return{...o,_id:a}},mr=async(e,t)=>Ie(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[p(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>ge.test(r),tableNameOf:r=>r.replace(ge,"")},async r=>x(r,{withFileTypes:!0})),pr=async function*(e){const t=M({crlfDelay:Number.POSITIVE_INFINITY,input:E(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const s=n.trim();if(s.length!==0)try{yield{raw:JSON.parse(s)}}catch(o){throw new f("INTERNAL",`${p(e)} line ${String(r)}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}}}finally{t.close()}},yr=async e=>{const t=await v(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${p(e)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(r!==null&&typeof r=="object"&&Array.isArray(r.documents))return r.documents.map(n=>({raw:n}));if(Array.isArray(r))return r.map(n=>({raw:n}));if(r!==null&&typeof r=="object")return Object.entries(r).map(([n,s])=>({fallbackId:n,raw:s}));throw new f("INTERNAL",`${p(e)}: expected an object, an array, or \`{ documents: [...] }\``)},wr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?pr(e.file):await yr(e.file);let s=0;for await(const o of n)yield gr(o.raw,o.fallbackId,r,`${e.table}[${String(s)}]`),s+=1},br=async function*(e,t,r,n,s){yield*Pe("firebase",s,t,r,n),yield*Ae(e,r,n,o=>wr(o,t))},I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),q=(e,t)=>{if(!I(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},T=(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},Me=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(s=>typeof s!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},$r=(e,t)=>{const r=q(e,t),n=T(r,"file",t),s=T(r,"idColumn",t),o=Me(r,"storageColumns",t),{types:i}=r;if(i!==void 0){if(!I(i))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(i))if(!Pt(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${Re.join(", ")}`)}return{file:n,idColumn:s,storageColumns:o,types:i}},Sr=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])T(e,r,`${t}: auth`)}},vr=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,$r(n,`${t}: tables.${r}`)]))}},Nr=(e,t)=>{const r=q(e,t),n=T(r,"keyPrefix",t),{auth:s,tables:o}=r;return Sr(s,t),{auth:s,keyPrefix:n,tables:vr(o,t)}},De=e=>w("lunora",`import-${e}.json`),Er=async(e,t,r)=>{const n=De(t),s=w(e,n);let o;try{o=await v(s,"utf8")}catch(a){if(a.code==="ENOENT"){r.info(`no ${n} found — every column is copied through untouched (run with --scan to generate one)`);return}throw a}let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${s}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return Nr(i,s)},Tr=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}},Ir=8,Ar=24*1048576,Rr=1e3,_r=/^[\dA-F]{64}$/i,Or=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},kr=/^[\d+/A-Z]{43}=$/i,Lr=e=>_r.test(e)?e.toLowerCase():kr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,xr=(e,t)=>{const r=JSON.parse(e),n=r._id;if(typeof n!="string"||n.length===0||n.includes("/")||n.includes("\\"))throw new f("INTERNAL",`${t}: \`_id\` must be a path-free non-empty string`);if(typeof r.sha256!="string")throw new f("INTERNAL",`${t}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const s=Lr(r.sha256);if(s===void 0)throw new f("INTERNAL",`${t}: \`sha256\` is neither base16 nor base64 SHA-256 (${r.sha256})`);if(typeof r.size!="number"||!Number.isInteger(r.size)||r.size<0)throw new f("INTERNAL",`${t}: \`size\` must be a non-negative integer`);if(r.contentType!==void 0&&(typeof r.contentType!="string"||!Or(r.contentType)))throw new f("INTERNAL",`${t}: \`contentType\` must be a string with no control characters`);return{contentType:typeof r.contentType=="string"?r.contentType:void 0,id:n,sha256:s,size:r.size}},C=async(e,t,r)=>{const n=[];try{let s=0;for await(const o of H(e,t)){const i=o.trim();s+=1,i.length>0&&n.push(xr(i,`_storage/documents.jsonl line ${String(s)}`))}}catch(s){const o=s instanceof Error?s.message:String(s);throw r.error(`failed to read _storage metadata: ${o}`),s}return n},ze=wt,U=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,W=async(e,t)=>await Tr(async r=>{const n=`${e.baseUrl}${V}?prefix=${encodeURIComponent(t)}&limit=${String(Rr)}${r===void 0?"":`&cursor=${encodeURIComponent(r)}`}${U(e)}`,s=await e.fetchImpl(n,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!s.ok){const i=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(s.status)}): ${i}`)}const o=await s.json();return{cursor:o.cursor,records:o.objects,truncated:o.truncated}}),Cr=async(e,t,r,n)=>{const s=`${e.baseUrl}${V}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${U(e)}`,o=await e.fetchImpl(s,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!o.ok){const a=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(o.status)}): ${a}`)}const i=await o.json();if(i.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${i.sha256??"none"}`);return t},Ur=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${V}?key=${encodeURIComponent(t)}${U(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,Pr=async(e,t,r,n,s)=>{const o=`${e.baseUrl}${bt}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${U(e)}`,i=await e.fetchImpl(o,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const m=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(ze)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(i.status)}): ${m}`)}const{url:a}=await i.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const m=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${m}`)}const l=(await W(e,t)).find(m=>m.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const u=l.size!==void 0&&l.size!==n.size,h=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(u||h){const m=await Ur(e,t);throw new f("INTERNAL",`post-upload verification failed: expected sha256=${n.sha256} size=${String(n.size)}, got sha256=${l.sha256??"none"} size=${String(l.size??"none")}${m?" (the object was removed)":` — AND the object could not be removed: delete ${t} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[l.size===void 0?"size":void 0,l.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&s.warn(`blob ${t} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),t},Be=async(e,t,r,n,s)=>{if(r.length!==n.size)throw new f("INTERNAL",`blob ${n.id} is ${String(r.length)} bytes on disk but the export declares ${String(n.size)}`);return r.length<=ze?Cr(e,t,r,n):Pr(e,t,r,n,s)},jr=e=>{const t=[];let r=[],n=0;for(const s of e)r.length>0&&(r.length>=Ir||n+s.size>Ar)&&(t.push(r),r=[],n=0),r.push(s),n+=s.size;return r.length>0&&t.push(r),t},B=(e,t)=>`${e}${t.sha256}`,Fr=async(e,t,r,n)=>{const s=await C(e,t,n);return new Map(s.map(o=>[o.id,B(r,o)]))},Mr=async(e,t,r,n,s)=>{const o=await C(t,r,s),i=new Map,a=await W(e,n),c=new Map(a.map(u=>[u.key,u])),d=[];for(const u of o){const h=B(n,u);c.get(h)?.size===u.size?i.set(u.id,h):d.push(u)}s.info(`migrating ${String(d.length)} storage blobs${i.size>0?` (${String(i.size)} already present)`:""}...`);const l=async u=>{try{const h=await xt(t,u.id);i.set(u.id,await Be(e,B(n,u),h,u,s))}catch(h){const g=h instanceof Error?h.message:String(h);throw s.error(`failed to upload blob ${u.id}: ${g}`),h}};for(const u of jr(d)){const g=(await Promise.allSettled(u.map(m=>l(m)))).find(m=>m.status==="rejected");if(g!==void 0)throw g.reason}return s.success(`migrated ${String(d.length)} storage blobs`),i};async function*Dr(e,t,r){let n=0;for await(const s of H(e,t)){const o=s.trim();if(n+=1,o.length===0)continue;let i;try{i=JSON.parse(o)}catch(a){throw new f("INTERNAL",`${t.table}/documents.jsonl line ${String(n)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}r.set(t.table,(r.get(t.table)??0)+1),yield`${JSON.stringify({doc:i,table:t.table})}
6
+ `}}async function*zr(e,t,r,n,s){for(const o of t){if(Ee(o.table)){o.table===N&&!n&&r.warn(`skipping "${N}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}s.has(o.table)||s.set(o.table,0),yield*Dr(e,o,s)}}const fs=["firebase","supabase"],Br=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 Er(r,t,e.logger),s=Object.values(n?.tables??{}).some(o=>(o.storageColumns??[]).length>0);return e.verify===!0&&e.withStorage!==!0&&s?(e.logger.error("--verify with `storageColumns` declared requires --with-storage — otherwise every storage path stays unmigrated and only row counts would be checked."),{kind:"invalid"}):t==="supabase"?{kind:"supabase",mapping:n,tables:await qt(e.file,n)}:{collections:await mr(e.file,n),kind:"firebase",mapping:n}},Jr=async e=>{if(!await L(e.file).then(()=>!0,()=>!1))return!1;for(const[r,n]of[["--scan",e.scan],["--verify",e.verify],["--with-storage",e.withStorage]])if(n===!0)return e.logger.error(`${r} requires a Convex export directory or .zip snapshot — ${e.file} is not one.`),!0;return!1},Vr=async(e,t,r)=>{const n=t.find(o=>o.table===N);if(n===void 0)return r.logger.error("--verify cannot check file references: this export has no `_storage` table, so it was taken without `--include-file-storage`. Re-export with that flag and pass --with-storage, or drop --verify."),!0;const s=await C(e,n,r.logger);return s.length>0?(r.logger.error(`--verify on an export carrying ${String(s.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),!0):!1},Hr=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return Br(e,e.from,t);const r=await _t(e.file),n=r===void 0?void 0:await Lt(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 Jr(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 Vr(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},k=w("lunora","import-convex.json"),Gr=(e,t)=>{const r=q(e,t),n=T(r,"keyPrefix",t),s=r.storageColumns;if(s!==void 0){if(!I(s))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const o of Object.keys(s))Me(s,o,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:s}},qr=async(e,t)=>{const r=w(e,k);let n;try{n=await v(r,"utf8")}catch(o){if(o.code==="ENOENT"){t.info(`no ${k} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw o}let s;try{s=JSON.parse(n)}catch(o){throw new f("INTERNAL",`${r}: invalid JSON — ${o instanceof Error?o.message:String(o)}`,{cause:o})}return Gr(s,r)},Wr=(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})}},Kr=async(e,t,r)=>{const n=new Map([...r].map(i=>[i,i])),s=[];let o=0;for await(const i of H(e,t)){const a=i.trim();if(o+=1,a.length===0)continue;const{ambiguous:c}=Te(Wr(a,t.table,o),n,t.table);for(const{column:d}of c)s.includes(d)||s.push(d)}return s},Yr=async(e,t,r)=>{const n={};for(const s of t){if(Ee(s.table))continue;const o=await Kr(e,s,r);o.length>0&&(n[s.table]=o)}return n},Xr=async(e,t,r)=>{const n=w(t,k),s=`${JSON.stringify(e,void 0,4)}
7
+ `;await J(w(t,"lunora"),{recursive:!0});try{await $e(n,s,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(o){if(o.code!=="EEXIST")throw o;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(s)}},Zr=async(e,t,r,n)=>{const s=t.find(c=>c.table===N);if(s===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const o=await C(e,s,n),i=new Set(o.map(c=>c.id));n.info(`found ${String(i.size)} storage ids`);const a={keyPrefix:"",storageColumns:await Yr(e,t,i)};return await Xr(a,r,n),a},S=20,Qr=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[s,o]of t){const i=r.inserted[s]??0;i<o&&(n+=1,e.error(`verify: ${s} inserted ${String(i)} of ${String(o)} source rows (${String(o-i)} missing)`))}else{const s=[...t.values()].reduce((i,a)=>i+a,0),o=Object.values(r.inserted).reduce((i,a)=>i+a,0)+r.conflicts;o<s&&(n+=1,e.error(`verify: ${String(o)} of ${String(s)} source rows accounted for across all tables (${String(s-o)} missing; ${String(r.conflicts)} already present)`))}return n>0?e.error(`verify: ${String(n)} row-parity check(s) failed`):e.success("verify: all source rows accounted for"),n},me=(e,t,r)=>{for(const n of t.slice(0,S))e.warn(r(n));t.length>S&&e.warn(`… and ${String(t.length-S)} more`)},Je=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),me(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\``),me(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${k} and re-import`),r&&t.unmigrated.length>0?(e.error(`verify: ${String(t.unmigrated.length)} storage reference(s) resolved to no migrated blob`),!0):!1),en=(e,t,r)=>{for(const n of[...t].slice(0,S))e.warn(`storage path never transferred: ${n} — left as-is`);return t.size>S&&e.warn(`… and ${String(t.size-S)} more untransferred storage paths`),r&&t.size>0},pe=200,tn=/^\\x[\dA-Fa-f]*$/,rn=/^[+-]?\d+$/,nn=/^[+-]?\d+\.\d+$/,sn=/^\{.*\}$/,on=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,an=[["bytea-base64",e=>tn.test(e)],["timestamp-ms",e=>on.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>rn.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>nn.test(e)],[e=>e.every(t=>sn.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],cn=e=>{if(e.length!==0){for(const[t,r]of an)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},dn=(e,t)=>{for(const[r,n]of Object.entries(e)){if(n.length===0)continue;const s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}},ln=async e=>{const t=new Map,r=E(e).pipe(Ne({columns:!0,skipEmptyLines:!0,toLine:pe+1}));let n=0;for await(const o of r)if(dn(o,t),n+=1,n>=pe)break;r.destroy();const s={};for(const[o,i]of t){const a=cn(i);a!==void 0&&(s[o]=a)}return s},Ve=async(e,t,r,n)=>{const s=De(r),o=w(t,s),i=`${JSON.stringify(e,void 0,4)}
8
+ `;await J(Se(o),{recursive:!0});try{await $e(o,i,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${o} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${o} already exists — leaving it untouched. Candidate mapping:`),n.info(i)}},un=async(e,t,r)=>{const n={};for(const o of e){const i=await ln(o.file);r.info(`${p(o.file)} → ${o.table}: ${String(Object.keys(i).length)} column(s) need a reshape`),n[o.table]={file:p(o.file),idColumn:"id",...Object.keys(i).length>0?{types:i}:{}}}const s={keyPrefix:"",tables:n};return await Ve(s,t,"supabase",r),s},fn=async(e,t,r)=>{const n={};for(const o of e)n[o.table]={file:p(o.file),storageColumns:[]};r.info(`found ${String(e.length)} collection(s) — Firestore values are self-describing, so only storage columns need declaring`);const s={keyPrefix:"",tables:n};return await Ve(s,t,"firebase",r),s},K=e=>w("lunora",`.import-storage-${e}.ndjson`),hn=async(e,t,r)=>{const n=new Map;let s;try{s=await v(w(e,K(t)),"utf8")}catch(i){if(i.code==="ENOENT")return n;throw i}let o=0;for(const i of s.split(`
9
+ `)){const a=i.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):o+=1}catch{o+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${o>0?` (${String(o)} unreadable checkpoint line(s) ignored)`:""}`),n},gn=async(e,t,r)=>{const n=w(e,K(t));await J(Se(n),{recursive:!0}),await ot(n,`${JSON.stringify(r)}
10
+ `,"utf8")},He=100,mn=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),pn=async(e,t,r,n,s)=>{const o=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:He,offset:s,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!o.ok){const i=await o.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(o.status)}): ${i}`)}return await o.json()},Ge=async(e,t,r,n="")=>{const s=[];let o=0;for(;;){const i=await pn(e,t,r,n,o);for(const a of i){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?s.push(...await Ge(e,t,r,c)):s.push({contentType:a.metadata?.mimetype,name:c})}if(i.length<He)return s;o+=i.length}},yn=async(e,t,r)=>{const n=await t(`${e.url}/storage/v1/bucket`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!n.ok){const i=await n.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase bucket list failed (HTTP ${String(n.status)}): ${i} — check the project URL and that the key is the service-role key, not the anon key`)}const s=await n.json(),o=[];for(const i of s){const a=await Ge(e,i.name,t);r.info(`supabase bucket ${i.name}: ${String(a.length)} object(s)`);for(const c of a){const d=`${i.name}/${c.name}`;o.push({contentType:c.contentType,bytes:async()=>{const l=await t(`${e.url}/storage/v1/object/${encodeURIComponent(i.name)}/${mn(c.name)}`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!l.ok){const u=await l.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase download failed for ${d} (HTTP ${String(l.status)}): ${u}`)}if(l.arrayBuffer===void 0)throw new f("INTERNAL","the fetch implementation cannot read response bytes, which the storage transfer requires");return Buffer.from(await l.arrayBuffer())},path:d})}}return o},wn=async e=>{const t=F(e),r=[],n=async s=>{const o=await x(s,{withFileTypes:!0}).catch(()=>{});if(o===void 0)throw new f("INTERNAL",`${e} is not a readable directory — download the bucket first with \`gcloud storage cp -r gs://<bucket> <dir>\``);for(const i of o){const a=F(s,i.name);if(!ve(t,a))throw new f("INTERNAL",`${i.name} resolves outside ${e} — refusing to upload it`);i.isDirectory()?await n(a):i.isFile()&&r.push({bytes:async()=>v(a),path:ut(t,a).split(ft).join("/")})}};return await n(t),r},bn=async(e,t,r,n,s)=>{const o=await t.bytes(),i=St("sha256").update(o).digest("hex"),a=`${r.keyPrefix}${i}`;if(n.get(a)?.size!==o.length){const c={contentType:t.contentType,id:t.path,sha256:i,size:o.length};await Be(e,a,o,c,s)}return await gn(r.cwd,r.source,{key:a,path:t.path,size:o.length}),a},$n=(e,t)=>{const r=e>500?100:25;return n=>{if(n===e||n%r===0){const s=e===0?100:Math.round(n/e*100);t.info(`transferred ${String(n)}/${String(e)} object(s) (${String(s)}%)`)}}},ye=async(e,t,r,n)=>{const s=new Map,o=await hn(r.cwd,r.source,n),i=await W(e,r.keyPrefix),a=new Map(i.map(l=>[l.key,l]));o.size>0&&i.length===0&&n.warn(`the checkpoint records ${String(o.size)} transferred object(s) but the target holds none under \`${r.keyPrefix}\` — re-transferring (a different deployment, a wiped bucket, or a changed keyPrefix)`);const c=$n(t.length,n);let d=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const l of t){const u=o.get(l.path);if(u!==void 0&&a.has(u.key)){s.set(l.path,u.key),d+=1,c(d);continue}try{const h=await bn(e,l,r,a,n);s.set(l.path,h)}catch(h){const g=h instanceof Error?h.message:String(h);throw n.error(`failed transferring ${l.path} after ${String(d)} object(s): ${g}`),n.error(`progress is saved — re-run the same command to continue from here (delete ${K(r.source)} to start over)`),h}d+=1,c(d)}return n.success(`transferred ${String(t.length)} object(s) to R2`),s},we=/^\/+/,Sn=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,vn=/[#?]/u,Nn=e=>{const t=new Map(e),r=new Map;for(const[n,s]of e){const o=n.indexOf("/");if(o===-1)continue;const i=n.slice(o+1);i.length===0||e.has(i)||r.set(i,r.has(i)?void 0:s)}for(const[n,s]of r)s!==void 0&&t.set(n,s);return t},En=e=>{const t=Sn.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(vn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},Tn=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(we,""),s=t.get(n);if(s!==void 0)return s;const o=En(e);return o===void 0?void 0:t.get(o)??t.get(o.replace(we,""))},In=500,An=9e5,Rn=async e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)"),{refused:$.USAGE};const t=ct(e.url,e.logger,e.cwd);if(t===void 0)return{refused:$.USAGE};if(it({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`import bulk-writes ${t}, which is not local. Re-run with --yes to confirm.`),{refused:$.USAGE};const{token:r}=at({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:$.AUTH};try{const s=await L(e.file);if(!s.isFile()&&!s.isDirectory())return e.logger.error(`not a file or directory: ${e.file}`),{refused:$.USAGE}}catch(s){const o=s instanceof Error?s.message:String(s);return e.logger.error(`failed to stat ${e.file}: ${o}`),{refused:$.NOT_FOUND}}const n=e.fetchImpl??dt;return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${$t}`,token:r}},qe=(e,t,r)=>({conflicts:e.conflicts,errors:e.errors,...e.failed.length>0?{failed:e.failed}:{},inserted:e.inserted,received:e.received,replaced:e.replaced,...t===void 0?{}:{storage:{ambiguous:r.ambiguous.slice(0,S),ambiguousTotal:r.ambiguous.length,blobs:t.size,rewritten:r.rewritten,unmigrated:r.unmigrated.slice(0,S),unmigratedTotal:r.unmigrated.length}},...e.warnings.length>0?{warnings:e.warnings}:{}}),_n=(e,t,r,n)=>{switch(e.kind){case"convex":return zr(e.snapshot,e.tables,t.logger,r,n);case"firebase":return br(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return Yt(e.tables,e.mapping,t.logger,n,t.file);default:return E(t.file,{encoding:"utf8"})}},On=async(e,t,r)=>{switch(e.kind){case"convex":return Zr(e.snapshot,e.tables,t,r);case"firebase":return fn(e.collections,t,r);case"supabase":return un(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},kn=async(e,t,r,n)=>{const s=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return ye(e,await wn(r.storageDir),{cwd:n,keyPrefix:s,source:t.kind},r.logger);if(t.kind==="firebase"){r.logger.error("--with-storage needs --storage-dir for a Firebase source: download the bucket first (`gcloud storage cp -r gs://<bucket> ./storage`), then point --storage-dir at it.");return}const o=process.env.SUPABASE_URL,i=process.env.SUPABASE_SERVICE_ROLE_KEY;if(o===void 0||i===void 0){r.logger.error("--with-storage needs SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in the environment (the service-role key, not the anon key), or --storage-dir pointing at an already-downloaded bucket.");return}let a=o.length;for(;a>0&&o[a-1]==="/";)a-=1;const c=o.slice(0,a);if(!c.startsWith("https://")){r.logger.error(`SUPABASE_URL must be https:// — refusing to send the service-role key over ${c.split(":")[0]??"an unknown scheme"}.`);return}const d=await yn({serviceKey:i,url:c},e.fetchImpl,r.logger);return ye(e,d,{cwd:n,keyPrefix:s,source:t.kind},r.logger)},Ln=(e,t,r,n,s)=>{const o=n.mapping?.tables?.[t]?.storageColumns??[];if(o.length===0)return e;const i={...e};for(const a of o){const c=i[a];if(typeof c!="string"||c.length===0)continue;const d=Tn(c,r);d===void 0?s.add(`${t}.${a}: ${c}`):i[a]=d}return i},xn=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:Nn(r);return Ut({remapDocument:n===void 0||t===void 0?void 0:(s,o)=>Ln(s,o,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},Cn=async(e,t,r,n)=>{let s="",o=0;const i=async a=>{o+=1;const c=t(a,o);c!==void 0&&await r.push(c)};try{for await(const a of e){s+=typeof a=="string"?a:a.toString("utf8");let c=s.indexOf(`
11
+ `);for(;c!==-1;)await i(s.slice(0,c)),s=s.slice(c+1),c=s.indexOf(`
12
+ `)}s.length>0&&await i(s),await r.flush();return}catch(a){const c=a instanceof Error?a.message:String(a);return r.totals.received===0?(n.error(`import failed before any batch was acknowledged: ${c}`),n.error("re-run the same command once the worker is reachable (existing rows conflict rather than duplicate)")):(n.error(`import failed part-way through: ${c}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)")),a}},Un=async(e,t,r)=>{if(t.withStorage!==!0||e.kind!=="convex")return{};const n=await qr(r,t.logger),s=e.tables.find(o=>o.table===N);if(s===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 Fr(e.snapshot,s,n?.keyPrefix??"",t.logger)}},Pn=async(e,t,r,n)=>{const s=t.tables.find(i=>i.table===N);if(s===void 0)return;const o=await Mr(e,t.snapshot,s,r.mapping?.keyPrefix??"",n);return n.info(`storage map: ${String(o.size)} blobs mapped`),{mapping:r.mapping,storageIdMap:o}},jn=async(e,t,r,n,s)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return Pn(e,t,s,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const o=await kn(e,t,r,n);return o===void 0?void 0:{transferredPaths:o}}catch(o){r.logger.error(`storage transfer failed: ${o instanceof Error?o.message:String(o)}`),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}},Fn=(e,t)=>{for(const o of t.warnings)e.warn(o);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, `:"",s=`imported ${String(t.insertedTotal+t.replaced)} of ${String(t.received)} rows (${n}${String(t.conflicts)} conflicts, ${String(t.errorCount)} errors)`;t.failed?e.error(s):e.success(s)},Mn=async(e,t,r)=>await On(e,t,r.logger)===void 0?{body:void 0,code:$.USAGE,error:"import --scan: the export could not be scanned",inserted:0}:{body:void 0,code:0,inserted:0},Dn="GLOBAL_DRY_RUN_UNSUPPORTED",zn={error:()=>{},info:()=>{},success:()=>{},warn:()=>{}},Bn=e=>({...e,logger:zn}),be=async(e,t,r,n)=>{const s=new Set,o={ambiguous:[],rewritten:0,unmigrated:[]},i=new Map,a=_n(t,e,r.storageIdMap!==void 0,i),c=Ct({batchSize:n.batchSize,fetchImpl:n.fetchImpl,maxBatchBytes:An,requestUrl:n.requestUrl,token:n.token}),d=xn({report:o,source:t,storageColumns:r.mapping?.storageColumns,storageIdMap:r.storageIdMap,table:e.table,transferredPaths:r.transferredPaths,unresolvedPaths:s}),l=await Cn(a,d,c,e.logger);return{batcher:c,remapReport:o,sourceRows:i,streamFailure:l,unresolvedPaths:s}},Y=e=>e instanceof Error?e.message:typeof e=="string"?e:"an unknown failure",We=e=>{const{conflicts:t,inserted:r}=e.batcher.totals;return t>0||Object.values(r).some(n=>n>0)},Jn=(e,t,r,n)=>{const s=qe(t.batcher.totals,n,t.remapReport),o=We(t);if(e.format!=="json"&&e.logger.info(JSON.stringify(s,void 0,2)),t.streamFailure!==void 0){const c=Y(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(o?"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=o?`import: ${e.file} was refused, and rows may already be written: ${r}`:`import: ${e.file} was not written: ${r}`;return{body:s,code:1,data:{file:e.file,inserted:i,summary:s},error:a,inserted:i}},Vn=(e,t)=>{if(e.streamFailure!==void 0)return`the check stopped early: ${Y(e.streamFailure)}`;const{errors:r,failed:n}=e.batcher.totals;if(We(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 s=r.filter(i=>i.code!==Dn);if(s.length>0)return`${String(s.length)} row(s) would be refused`;const o=e.remapReport.unmigrated.length;return t&&o>0?`${String(o)} storage reference(s) resolve to no exported blob`:void 0},Hn=(e,t)=>{e.verify===!0&&t.remapReport.unmigrated.length>0&&Je(e.logger,t.remapReport,!0)},Gn=(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}`)},qn=async(e,t)=>{try{const r=await e.fetchImpl(`${e.requestUrl}?dryRun=true${t?"&onConflict=replace":""}`,{body:`
13
+ `,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!r.ok)return`the worker at ${e.requestUrl} answered HTTP ${String(r.status)} to the check`;const n=await r.json();return n.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`:t&&n.onConflict!=="replace"?`the worker at ${e.requestUrl} predates ?onConflict=replace, so --replace would overwrite nothing; deploy the current runtime and import again`:void 0}catch(r){return`the worker at ${e.requestUrl} did not answer the check: ${Y(r)}`}},Wn=(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}`}},hs=async e=>{const t=e.cwd??process.cwd(),r=await Hr(e,t);if(r.kind==="invalid")return{body:void 0,code:$.USAGE,error:`import: could not read ${e.file}`,inserted:0};if(e.scan===!0)return Mn(r,t,e);const n=await Rn(e);if(lt(n))return{body:void 0,code:n.refused,error:"import: could not resolve the worker URL and admin token",inserted:0};const{baseUrl:s,fetchImpl:o,token:i}=n,a=e.replace===!0,c=Wn(n.requestUrl,a),{write:d}=c,u={batchSize:e.batchSize??In,fetchImpl:o,requestUrl:n.requestUrl,token:i},h=await qn(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 Un(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 m=await be(Bn(e),r,g,{...u,requestUrl:c.check}),y=Vn(m,e.verify===!0);if(y!==void 0)return Hn(e,m),Jn(e,m,y,void 0);const P=await jn({baseUrl:s,fetchImpl:o,token:i},r,e,t,g);if(P===void 0)return{body:void 0,code:1,error:"import: the storage phase failed — no rows were written",inserted:0};const{storageIdMap:X}=P;e.logger.info(r.kind==="convex"?`POST ${d} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${d} -> import ${e.file}`);const{batcher:Z,remapReport:Q,sourceRows:Ke,streamFailure:ee,unresolvedPaths:Ye}=await be(e,r,P,{...u,requestUrl:d}),{conflicts:te,errors:re,failed:ne,inserted:se,received:Xe,replaced:A,warnings:Ze}=Z.totals,Qe=e.verify===!0&&ee===void 0?Qr(e.logger,Ke,{conflicts:te+A,inserted:se}):0,et=X!==void 0&&Je(e.logger,Q,e.verify===!0),tt=en(e.logger,Ye,e.verify===!0),R=Object.values(se).reduce((rt,nt)=>rt+nt,0),_=qe(Z.totals,X,Q);Gn(e.logger,ne);const oe=ee!==void 0||re.length>0||ne.length>0||Qe>0||et||tt;e.format!=="json"&&e.logger.info(JSON.stringify(_,void 0,2)),Fn(e.logger,{conflicts:te,errorCount:re.length,failed:oe,insertedTotal:R,received:Xe,replaced:A,warnings:Ze});const ie={file:e.file,inserted:R,summary:_};return oe?{body:_,code:1,data:ie,error:`import: ${e.file} did not import cleanly`,inserted:R,replaced:A}:{body:_,code:0,data:ie,inserted:R,replaced:A}};export{In as D,fs as I,ze as M,U as b,W as l,hs as r,Be 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,2 @@
1
+ const n=(s,e)=>{for(const t of s)(t.status==="created"||t.status==="updated")&&e.success(`${t.status} ${t.path} — ${t.tool} now skips Lunora's generated files`),t.status==="failed"&&e.warn(`could not configure ${t.tool} to skip Lunora's generated files: ${t.message??"unknown error"}. Add the entries by hand, or re-run once the path is writable.`),t.status==="manual"&&t.snippet!==void 0&&e.warn(`${t.path} needs an entry so ${t.tool} skips Lunora's generated files — add:
2
+ ${t.snippet}`)};export{n as r};
@@ -0,0 +1,2 @@
1
+ import{existsSync as l,readFileSync as u,mkdirSync as v,realpathSync as E,statSync as b,writeFileSync as M,chmodSync as k,renameSync as x,unlinkSync as $}from"node:fs";import{dirname as h}from"@visulima/path";import{parse as w,modify as O,applyEdits as j}from"jsonc-parser";const g=(t,n)=>{let i=t,r;try{i=E(t),r=b(i).mode}catch{}const o=`${i}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{v(h(i),{recursive:!0}),M(o,n,{encoding:"utf8",mode:r??384}),k(o,r??384),x(o,i)}catch(e){try{$(o)}catch{}throw e}},A={formattingOptions:{insertSpaces:!0,tabSize:4}},d=t=>{const n=[],i=w(t,n,{allowTrailingComma:!0});return{errors:n,value:i}},f=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),p=(t,n,i)=>{if(!f(t))return;const r=t[n];return f(r)?r[i]:void 0},F=t=>{if(!l(t.path))return"absent";let n;try{n=u(t.path,"utf8")}catch{return"invalid"}if(n.trim().length===0)return"absent";const{errors:i,value:r}=d(n);return i.length>0||!f(r)?"invalid":p(r,t.key,t.name)===void 0?"absent":"present"},J=t=>F(t)==="present",S=(t,n,i,r,o)=>{try{const e=O(t,[i,r],o,A);e.length>0&&g(n,j(t,e));return}catch(e){return e instanceof Error?e.message:String(e)}},P=t=>{const{entry:n,force:i=!1,key:r,name:o,path:e}=t,c=l(e)?u(e,"utf8"):"";if(c.trim().length===0)return v(h(e),{recursive:!0}),g(e,`${JSON.stringify({[r]:{[o]:n}},void 0,4)}
2
+ `),{action:"created",path:e};const{errors:s,value:a}=d(c);if(s.length>0)return{action:"invalid",error:`parse error at offset ${String(s[0]?.offset??0)}`,path:e};if(!f(a))return{action:"invalid",error:"the file's root is not a JSON object",path:e};const y=a[r];if(y!==void 0&&!f(y))return{action:"invalid",error:`"${r}" is not an object`,path:e};if(p(a,r,o)!==void 0&&!i)return{action:"skipped",path:e};const m=S(c,e,r,o,n);return m===void 0?{action:"updated",path:e}:{action:"invalid",error:m,path:e}},z=t=>{const{key:n,name:i,path:r}=t;if(!l(r))return{action:"absent",path:r};let o;try{o=u(r,"utf8")}catch(a){return{action:"invalid",error:a instanceof Error?a.message:String(a),path:r}}const{errors:e,value:c}=d(o);if(e.length>0)return{action:"invalid",error:`parse error at offset ${String(e[0]?.offset??0)}`,path:r};if(p(c,n,i)===void 0)return{action:"absent",path:r};const s=S(o,r,n,i,void 0);return s===void 0?{action:"removed",path:r}:{action:"invalid",error:s,path:r}};export{J as h,F as i,z as r,P as u,g as w};
@@ -0,0 +1 @@
1
+ import{spawn as i}from"node:child_process";import{platform as s}from"node:os";import{LunoraError as a}from"@lunora/errors";const d=()=>{const o=s();return o==="darwin"?{args:[],command:"open"}:o==="win32"?{args:["/c","start",""],command:"cmd"}:{args:[],command:"xdg-open"}},f=o=>o.replaceAll(/[!"%&()<>^|]/gu,n=>`%${(n.codePointAt(0)??0).toString(16).toUpperCase()}`),w=o=>new Promise((n,r)=>{const{args:e,command:c}=d(),p=s()==="win32"?f(o):o,t=i(c,[...e,p],{detached:!0,stdio:"ignore"});t.once("error",m=>{r(m)}),t.once("spawn",()=>{t.unref(),n()})}),L=async(o,n={})=>{let r;try{r=new URL(o)}catch{throw new a("INTERNAL",`Invalid URL: ${o}`)}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new a("INTERNAL",`Refusing to open non-http(s) URL: ${o}`);await(n.opener??w)(o)};export{L as o};
@@ -0,0 +1,2 @@
1
+ import{isProcessStreamLogger as o,createStderrLogger as e}from"./createLogger-4TujevyB.mjs";const n={description:"Output format: pretty (default) or json",name:"format",type:String},p=(r,t)=>t===void 0?{format:"pretty"}:t==="json"||t==="pretty"?{format:t}:{error:`${r}: unknown --format "${t}" — expected pretty | json`},a=(r,t)=>r==="json"&&o(t)?e():t,i=r=>{process.stdout.write(`${JSON.stringify(r,void 0,2)}
2
+ `)};export{n as O,i as a,a as l,p};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";const d=/[\r\n]/u,w=/^[A-Za-z_]\w*$/u,y=/^[A-Za-z0-9][\w-]*$/u,b=/^[\w.-]+(?:\/[\w.-]+)*$/u,I=(c,s)=>{if(typeof c!="object"||c===null)throw new r("INTERNAL",`registry.json for "${s}" is not an object`);const e=c,{name:n}=e;if(typeof n!="string"||n.length===0)throw new r("INTERNAL",`registry.json for "${s}" is missing a string "name"`);if(!y.test(n))throw new r("INTERNAL",`registry.json for "${s}": name "${n}" must match ${y.source} (letters, digits, "-", "_"; no path separators, "..", or code)`);const g=e.files;if(!Array.isArray(g))throw new TypeError(`registry.json for "${s}" is missing a "files" array`);const A=g.map((t,o)=>{if(typeof t!="object"||t===null)throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}] is not an object`);const i=t,{from:a}=i,{to:f}=i,{merge:p}=i;if(typeof a!="string"||typeof f!="string")throw new TypeError(`registry.json "${s}": files[${String(o)}] needs string "from" and "to"`);if(p!=="create-or-skip"&&p!=="schema-extension")throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}].merge must be "create-or-skip" or "schema-extension"`);for(const[v,l]of[["from",a],["to",f]])if(l.includes("..")||l.startsWith("/"))throw new r("INTERNAL",`registry.json "${s}": files[${String(o)}].${v} "${l}" must be a relative path without ".."`);return{from:a,merge:p,to:f}}),u=t=>typeof t=="object"&&t!==null?t:void 0,h=u(e.deps),m=u(e.devDependencies),$=Array.isArray(e.requires)?e.requires.filter(t=>typeof t=="string"):void 0,E=Array.isArray(e.bindings)?e.bindings.filter(t=>{if(typeof t!="object"||t===null)return!1;const o=t;return Array.isArray(o.path)&&o.path.every(i=>typeof i=="string")}):void 0,j=Array.isArray(e.entrypointReexports)?e.entrypointReexports.filter(t=>typeof t=="object"&&t!==null&&typeof t.module=="string").map(t=>{if(t.module.includes("..")||t.module.startsWith("/")||!b.test(t.module))throw new r("INTERNAL",`registry.json "${s}": entrypointReexports[].module "${t.module}" must be a safe relative module path without path traversal or unsafe characters`);const o={module:t.module};if(typeof t.comment=="string"){if(d.test(t.comment))throw new r("INTERNAL",`registry.json "${s}": entrypointReexports[].comment must not contain a newline`);o.comment=t.comment}return o}):void 0,R=Array.isArray(e.envVars)?e.envVars.filter(t=>typeof t=="object"&&t!==null&&typeof t.name=="string").map(t=>{const o=typeof t.value=="string";if(!w.test(t.name))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].name must match ${w.source} (letters, digits, underscore; no "=" or newline)`);if(o&&d.test(t.value))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].value must not contain a newline`);if(typeof t.description=="string"&&d.test(t.description))throw new r("INTERNAL",`registry.json "${s}": envVars["${t.name}"].description must not contain a newline`);return{...typeof t.description=="string"?{description:t.description}:{},name:t.name,secret:typeof t.secret=="boolean"?t.secret:!o,...o?{value:t.value}:{}}}):void 0;return{bindings:E,deps:h,description:typeof e.description=="string"?e.description:void 0,devDependencies:m,docs:typeof e.docs=="string"?e.docs:void 0,entrypointReexports:j,envVars:R,files:A,name:n,requires:$,title:typeof e.title=="string"?e.title:void 0}};export{I as default};
@@ -0,0 +1 @@
1
+ import{sep as t}from"node:path";const m=(s,i,e=t)=>i===s||i.startsWith(s.endsWith(e)?s:`${s}${e}`);export{m as i};