@lunora/cli 1.0.0-alpha.21 → 1.0.0-alpha.211

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 (110) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/bin.mjs +2 -10
  5. package/dist/index.d.mts +745 -341
  6. package/dist/index.d.ts +745 -341
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -150
  9. package/dist/packem_chunks/handler10.mjs +4 -22
  10. package/dist/packem_chunks/handler11.mjs +2 -192
  11. package/dist/packem_chunks/handler12.mjs +1 -131
  12. package/dist/packem_chunks/handler13.mjs +1 -65
  13. package/dist/packem_chunks/handler14.mjs +1 -58
  14. package/dist/packem_chunks/handler15.mjs +1 -79
  15. package/dist/packem_chunks/handler16.mjs +3 -43
  16. package/dist/packem_chunks/handler17.mjs +1 -105
  17. package/dist/packem_chunks/handler18.mjs +1 -170
  18. package/dist/packem_chunks/handler19.mjs +7 -89
  19. package/dist/packem_chunks/handler2.mjs +2 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -94
  21. package/dist/packem_chunks/handler21.mjs +2 -311
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +3 -0
  24. package/dist/packem_chunks/handler24.mjs +1 -0
  25. package/dist/packem_chunks/handler25.mjs +99 -0
  26. package/dist/packem_chunks/handler26.mjs +10 -0
  27. package/dist/packem_chunks/handler3.mjs +1 -204
  28. package/dist/packem_chunks/handler4.mjs +1 -33
  29. package/dist/packem_chunks/handler5.mjs +1 -49
  30. package/dist/packem_chunks/handler6.mjs +1 -91
  31. package/dist/packem_chunks/handler7.mjs +3 -42
  32. package/dist/packem_chunks/handler8.mjs +1 -174
  33. package/dist/packem_chunks/handler9.mjs +1 -16
  34. package/dist/packem_chunks/planDevCommand.mjs +7 -500
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +1 -504
  37. package/dist/packem_chunks/runInitCommand.mjs +118 -1383
  38. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-BXbrW8dd.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Cf8ZymM1.mjs +1 -0
  43. package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +1 -0
  44. package/dist/packem_shared/admin-url-Cil3Or6N.mjs +1 -0
  45. package/dist/packem_shared/advisory-gate-Cl8IEFIj.mjs +1 -0
  46. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  47. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  48. package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  49. package/dist/packem_shared/cli-C37AI4tr.mjs +3 -0
  50. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  51. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  52. package/dist/packem_shared/commands-BNKj7r1R.mjs +19 -0
  53. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  54. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  55. package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
  56. package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +5 -0
  57. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  58. package/dist/packem_shared/import-CdHdZRjj.mjs +12 -0
  59. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  60. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  61. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  62. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  63. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  64. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  65. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  66. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  67. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  68. package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
  69. package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +1 -0
  70. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  71. package/dist/packem_shared/schema-drift-gate-DARCKocg.mjs +1 -0
  72. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  73. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  74. package/dist/packem_shared/storage-wIUel5Az.mjs +1 -0
  75. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  76. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
  77. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  78. package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
  79. package/package.json +39 -17
  80. package/skills/README.md +35 -17
  81. package/skills/lunora/SKILL.md +65 -9
  82. package/skills/lunora-functions/SKILL.md +38 -3
  83. package/skills/lunora-migration-helper/SKILL.md +70 -17
  84. package/skills/lunora-performance-audit/SKILL.md +36 -6
  85. package/skills/lunora-quickstart/SKILL.md +90 -24
  86. package/skills/lunora-realtime/SKILL.md +58 -30
  87. package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
  88. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  89. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  90. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  91. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  92. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  93. package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
  94. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  95. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  96. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  97. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  98. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  99. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  100. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  101. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  102. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  103. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  104. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  105. package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
  106. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  107. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  108. package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
  109. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  110. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,114 +1,2 @@
1
- import { mkdtempSync, rmSync, existsSync, readdirSync, statSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { join, relative } from 'node:path';
4
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
5
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
6
-
7
- const walk = (root) => {
8
- const entries = [];
9
- const recurse = (directory) => {
10
- for (const name of readdirSync(directory)) {
11
- const full = join(directory, name);
12
- const info = statSync(full);
13
- if (info.isDirectory()) {
14
- recurse(full);
15
- } else if (info.isFile()) {
16
- entries.push({ path: relative(root, full), sizeBytes: info.size });
17
- }
18
- }
19
- };
20
- recurse(root);
21
- return entries;
22
- };
23
- const formatBytes = (bytes) => {
24
- if (bytes < 1024) {
25
- return `${String(bytes)} B`;
26
- }
27
- if (bytes < 1024 * 1024) {
28
- return `${(bytes / 1024).toFixed(1)} KiB`;
29
- }
30
- return `${(bytes / (1024 * 1024)).toFixed(2)} MiB`;
31
- };
32
- const buildReport = (outdir) => {
33
- const all = walk(outdir);
34
- const sorted = all.toSorted((a, b) => b.sizeBytes - a.sizeBytes);
35
- const totalBytes = all.reduce((sum, entry) => sum + entry.sizeBytes, 0);
36
- const generatedFiles = all.filter((entry) => entry.path.includes("_generated"));
37
- return {
38
- generatedFiles,
39
- outdir,
40
- topModules: sorted.slice(0, 10),
41
- totalBytes,
42
- totalFiles: all.length
43
- };
44
- };
45
- const renderText = (report, logger) => {
46
- logger.info(`outdir: ${report.outdir}`);
47
- logger.info(`total: ${String(report.totalFiles)} files, ${formatBytes(report.totalBytes)}`);
48
- if (report.topModules.length > 0) {
49
- logger.info("");
50
- logger.info("top modules by size:");
51
- for (const entry of report.topModules) {
52
- logger.info(` ${formatBytes(entry.sizeBytes).padStart(10, " ")} ${entry.path}`);
53
- }
54
- }
55
- if (report.generatedFiles.length > 0) {
56
- logger.info("");
57
- logger.info(`_generated/ files: ${String(report.generatedFiles.length)}`);
58
- for (const entry of report.generatedFiles) {
59
- logger.info(` ${formatBytes(entry.sizeBytes).padStart(10, " ")} ${entry.path}`);
60
- }
61
- }
62
- };
63
- const runAnalyzeCommand = async (options) => {
64
- const cwd = options.cwd ?? process.cwd();
65
- const { logger } = options;
66
- let outdir;
67
- let descriptor;
68
- let temporary = false;
69
- if (options.inspectOnly) {
70
- outdir = options.inspectOnly;
71
- } else {
72
- outdir = mkdtempSync(join(tmpdir(), "lunora-analyze-"));
73
- temporary = true;
74
- descriptor = {
75
- args: ["exec", "wrangler", "deploy", "--dry-run", "--outdir", outdir],
76
- command: "pnpm",
77
- cwd
78
- };
79
- logger.info(`analyze: building via ${descriptor.command} ${descriptor.args.join(" ")}`);
80
- const spawner = options.spawner ?? defaultSpawner;
81
- const spawned = await spawner(descriptor);
82
- if (spawned.code !== 0) {
83
- logger.error(`analyze: wrangler dry-run failed (exit ${String(spawned.code)})`);
84
- rmSync(outdir, { force: true, recursive: true });
85
- return { code: spawned.code, descriptor, report: void 0 };
86
- }
87
- }
88
- try {
89
- if (!existsSync(outdir)) {
90
- logger.error(`analyze: outdir not found at ${outdir}`);
91
- return { code: 1, descriptor, report: void 0 };
92
- }
93
- const report = buildReport(outdir);
94
- if (options.json) {
95
- process.stdout.write(`${JSON.stringify(report, void 0, 2)}
96
- `);
97
- } else {
98
- renderText(report, logger);
99
- }
100
- return { code: 0, descriptor, report };
101
- } finally {
102
- if (temporary && existsSync(outdir)) {
103
- try {
104
- rmSync(outdir, { force: true, recursive: true });
105
- } catch {
106
- }
107
- }
108
- }
109
- };
110
- const execute = defineHandler(
111
- ({ cwd, logger, options }) => runAnalyzeCommand({ cwd, json: options.json === true, logger })
112
- );
113
-
114
- export { execute, runAnalyzeCommand };
1
+ import{mkdtempSync as u,rmSync as d,existsSync as l,readdirSync as y,statSync as m}from"node:fs";import{tmpdir as p}from"node:os";import{join as f,relative as $}from"node:path";import{d as S}from"../packem_shared/command-DwC11Cwe.mjs";import{defaultSpawner as g}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{execArgsFor as w,detectPackageManager as z}from"@lunora/config";const B=e=>{const t=[],r=n=>{for(const s of y(n)){const i=f(n,s),o=m(i);o.isDirectory()?r(i):o.isFile()&&t.push({path:$(e,i),sizeBytes:o.size})}};return r(e),t},c=e=>e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(2)} MiB`,F=e=>{const t=B(e),r=t.toSorted((i,o)=>o.sizeBytes-i.sizeBytes),n=t.reduce((i,o)=>i+o.sizeBytes,0);return{generatedFiles:t.filter(i=>i.path.includes("_generated")),outdir:e,topModules:r.slice(0,10),totalBytes:n,totalFiles:t.length}},h=(e,t)=>{if(t.info(`outdir: ${e.outdir}`),t.info(`total: ${String(e.totalFiles)} files, ${c(e.totalBytes)}`),e.topModules.length>0){t.info(""),t.info("top modules by size:");for(const r of e.topModules)t.info(` ${c(r.sizeBytes).padStart(10," ")} ${r.path}`)}if(e.generatedFiles.length>0){t.info(""),t.info(`_generated/ files: ${String(e.generatedFiles.length)}`);for(const r of e.generatedFiles)t.info(` ${c(r.sizeBytes).padStart(10," ")} ${r.path}`)}},x=async e=>{const t=e.cwd??process.cwd(),{logger:r}=e;let n,s,i=!1;if(e.inspectOnly)n=e.inspectOnly;else{n=u(f(p(),"lunora-analyze-")),i=!0;const o=w(z(t),"wrangler",["deploy","--dry-run","--outdir",n]);s={args:o.args,command:o.command,cwd:t},r.info(`analyze: building via ${s.command} ${s.args.join(" ")}`);const a=await(e.spawner??g)(s);if(a.code!==0)return r.error(`analyze: wrangler dry-run failed (exit ${String(a.code)})`),d(n,{force:!0,recursive:!0}),{code:a.code,descriptor:s,report:void 0}}try{if(!l(n))return r.error(`analyze: outdir not found at ${n}`),{code:1,descriptor:s,report:void 0};const o=F(n);return e.json?process.stdout.write(`${JSON.stringify(o,void 0,2)}
2
+ `):h(o,r),{code:0,descriptor:s,report:o}}finally{if(i&&l(n))try{d(n,{force:!0,recursive:!0})}catch{}}},C=S(({cwd:e,logger:t,options:r})=>x({cwd:e,json:r.json===!0,logger:t}));export{C as execute,x as runAnalyzeCommand};
@@ -1,94 +1 @@
1
- import { readFileSync, existsSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { parse } from 'jsonc-parser';
4
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
5
- import { o as openUrl } from '../packem_shared/open-url-Dfq6fAyT.mjs';
6
-
7
- const DEFAULT_DEV_PORT = 8787;
8
- const STUDIO_PATH = "/_lunora/studio";
9
- const findWranglerFile = (projectRoot) => {
10
- for (const candidate of ["wrangler.jsonc", "wrangler.json"]) {
11
- const fullPath = join(projectRoot, candidate);
12
- if (existsSync(fullPath)) {
13
- return fullPath;
14
- }
15
- }
16
- return void 0;
17
- };
18
- const readWrangler = (projectRoot) => {
19
- const file = findWranglerFile(projectRoot);
20
- if (!file) {
21
- return void 0;
22
- }
23
- try {
24
- const parsed = parse(readFileSync(file, "utf8"));
25
- return parsed !== null && typeof parsed === "object" ? parsed : void 0;
26
- } catch {
27
- return void 0;
28
- }
29
- };
30
- const resolveDevPort = (wrangler) => {
31
- if (!wrangler) {
32
- return DEFAULT_DEV_PORT;
33
- }
34
- const { dev } = wrangler;
35
- if (dev !== null && typeof dev === "object") {
36
- const { port } = dev;
37
- if (typeof port === "number" && Number.isFinite(port)) {
38
- return port;
39
- }
40
- }
41
- return DEFAULT_DEV_PORT;
42
- };
43
- const resolveRemoteUrl = (wrangler) => {
44
- if (!wrangler) {
45
- return void 0;
46
- }
47
- const { routes } = wrangler;
48
- if (Array.isArray(routes) && routes.length > 0) {
49
- const first = routes[0];
50
- if (typeof first === "string") {
51
- return `https://${first.split("/")[0] ?? first}${STUDIO_PATH}`;
52
- }
53
- if (first !== null && typeof first === "object") {
54
- const { pattern } = first;
55
- if (typeof pattern === "string" && pattern.length > 0) {
56
- return `https://${pattern.split("/")[0] ?? pattern}${STUDIO_PATH}`;
57
- }
58
- }
59
- }
60
- const { name } = wrangler;
61
- if (typeof name === "string" && name.length > 0) {
62
- return `https://${name}.workers.dev${STUDIO_PATH}`;
63
- }
64
- return void 0;
65
- };
66
- const runViewCommand = async (options) => {
67
- const cwd = options.cwd ?? process.cwd();
68
- const wrangler = readWrangler(cwd);
69
- const { logger } = options;
70
- let url;
71
- if (options.remote) {
72
- url = resolveRemoteUrl(wrangler);
73
- if (!url) {
74
- logger.error("view --remote: could not determine the remote URL from wrangler config (set `routes` or `name`).");
75
- return { code: 1, url: void 0 };
76
- }
77
- } else {
78
- url = `http://localhost:${String(resolveDevPort(wrangler))}${STUDIO_PATH}`;
79
- }
80
- logger.info(`opening ${url}`);
81
- try {
82
- await openUrl(url, { opener: options.opener });
83
- } catch (error) {
84
- const message = error instanceof Error ? error.message : String(error);
85
- logger.error(`view: failed to open URL: ${message}`);
86
- return { code: 1, url };
87
- }
88
- return { code: 0, url };
89
- };
90
- const execute = defineHandler(
91
- ({ cwd, logger, options }) => runViewCommand({ cwd, logger, remote: options.remote === true })
92
- );
93
-
94
- export { execute, runViewCommand };
1
+ import{join as l,resolve as u}from"node:path";import{p as m}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{w as f}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as p}from"../packem_shared/command-DwC11Cwe.mjs";import{v as g,l as w,i as y,p as v}from"../packem_shared/output-format-DfogXx0p.mjs";import{defaultSpawner as b}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{runDeployCommand as B}from"./runDeployCommand.mjs";import{readdirSync as S,readFileSync as h}from"node:fs";import{gzipSync as F}from"node:zlib";const D=e=>!e.endsWith(".map")&&e!=="bundle-meta.json"&&e!=="README.md",z=e=>{let t;try{t=S(e,{recursive:!0,withFileTypes:!0})}catch{return}let r=0,i=0,a=0;for(const o of t){if(!o.isFile()||!D(o.name))continue;const n=h(l(o.parentPath,o.name));r+=1,a+=n.byteLength,i+=F(n).byteLength}return r===0?void 0:{files:r,gzipBytes:i,rawBytes:a}},M=".lunora/build",$=async e=>b({...e,stdoutToStderr:!0}),c=e=>`${(e/1024).toFixed(1)} KiB`,E=(e,t,r)=>f({destination:t,logger:r,projectRoot:e}),T=async e=>{const t=e.outDir??M,r=y(e.format),i=w(e.format,e.logger),a=s=>(r&&v(s),s),o=g("build",e.format);if(o!==void 0)return e.logger.error(o),{code:1,descriptor:void 0,error:o,validation:{problems:[],wranglerPath:void 0}};const n=await B({apiSpec:e.apiSpec,cwd:e.cwd,dryRun:!0,format:void 0,interactive:r?!1:void 0,logger:i,outDir:t,spawner:e.spawner??(r?$:void 0),target:e.target});if(n.code!==0)return a(n);i.success(`build complete — bundle written to ${t}`);const d=z(u(e.cwd??process.cwd(),t));if(d===void 0?i.warn(`could not weigh the bundle — nothing uploadable was found in ${t}`):i.info(`bundle: ${c(d.rawBytes)} raw, ${c(d.gzipBytes)} gzipped across ${String(d.files)} file(s) — Cloudflare's Worker size limit (3 MB Free, 10 MB Paid) applies to the gzipped number`),e.emitBindings!==void 0){const{error:s}=E(e.cwd??process.cwd(),e.emitBindings,i);if(s!==void 0)return i.error(s),a({...n,bundle:d,code:1})}return a({...n,bundle:d})},k=p(async({cwd:e,logger:t,options:r})=>({code:(await T({apiSpec:m(r.apiSpec),cwd:e,emitBindings:r.emitBindings,format:r.format,logger:t,outDir:r.outDir,target:r.target})).code}));export{k as execute,T as runBuildCommand};
@@ -1,311 +1,2 @@
1
- import { writeFileSync, existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { DEV_VARS_FILE, DEV_VARS_KEY_PATTERN, DEV_VARS_EXAMPLE_FILE, parseDevVariableEntries, isPlaceholderValue } from '@lunora/config';
4
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
5
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
6
- import { execFile } from 'node:child_process';
7
-
8
- const execCode = (error) => {
9
- if (!error) {
10
- return 0;
11
- }
12
- return typeof error.code === "number" ? error.code : 1;
13
- };
14
- const defaultRunner = (command, args, cwd) => new Promise((resolve) => {
15
- execFile(command, [...args], { cwd }, (error, stdout, stderr) => {
16
- resolve({ code: execCode(error), stderr, stdout });
17
- });
18
- });
19
- const parseSecretNames = (stdout) => {
20
- let parsed;
21
- try {
22
- parsed = JSON.parse(stdout);
23
- } catch {
24
- return void 0;
25
- }
26
- if (!Array.isArray(parsed)) {
27
- return void 0;
28
- }
29
- const names = parsed.map((entry) => entry !== null && typeof entry === "object" ? entry.name : void 0).filter((name) => typeof name === "string" && name.length > 0);
30
- return [...names].toSorted((a, b) => a.localeCompare(b));
31
- };
32
- const listRemoteSecrets = async (inputs) => {
33
- const args = ["exec", "wrangler", "secret", "list", "--format", "json"];
34
- if (inputs.env !== void 0) {
35
- args.push("--env", inputs.env);
36
- }
37
- if (inputs.temporary) {
38
- args.push("--temporary");
39
- }
40
- const runner = inputs.runner ?? defaultRunner;
41
- const result = await runner("pnpm", args, inputs.cwd);
42
- if (result.code !== 0) {
43
- return { error: result.stderr.trim() || `wrangler secret list exited ${String(result.code)}`, names: [], ok: false };
44
- }
45
- const names = parseSecretNames(result.stdout);
46
- if (names === void 0) {
47
- return { error: "could not parse `wrangler secret list --format json` output", names: [], ok: false };
48
- }
49
- return { names, ok: true };
50
- };
51
-
52
- const NEWLINE_PRESENT = /[\r\n]/u;
53
- const UNREPRESENTABLE_PRESENT = /["\\]/u;
54
- const parseDevVariables = (content) => {
55
- const map = /* @__PURE__ */ new Map();
56
- for (const entry of parseDevVariableEntries(content)) {
57
- map.set(entry.key, entry);
58
- }
59
- return map;
60
- };
61
- const serializeDevVariables = (map) => {
62
- const lines = [];
63
- for (const entry of map.values()) {
64
- lines.push(`${entry.key}="${entry.value}"`);
65
- }
66
- return `${lines.join("\n")}
67
- `;
68
- };
69
- const redact = (value) => {
70
- if (value.length <= 4) {
71
- return "****";
72
- }
73
- return `${value.slice(0, 4)}${"*".repeat(Math.min(8, value.length - 4))}`;
74
- };
75
- const loadDevVariables = (devVariablesPath) => {
76
- if (!existsSync(devVariablesPath)) {
77
- return /* @__PURE__ */ new Map();
78
- }
79
- return parseDevVariables(readFileSync(devVariablesPath, "utf8"));
80
- };
81
- const runEnvList = (context) => {
82
- const map = loadDevVariables(context.devVariablesPath);
83
- if (map.size === 0) {
84
- context.logger.info(`${DEV_VARS_FILE}: (empty)`);
85
- return { code: 0, descriptors: [] };
86
- }
87
- for (const entry of map.values()) {
88
- context.logger.info(`${entry.key}=${redact(entry.value)}`);
89
- }
90
- return { code: 0, descriptors: [] };
91
- };
92
- const runEnvGet = (context) => {
93
- const { devVariablesPath, logger, options } = context;
94
- if (!options.key) {
95
- logger.error("env get requires a key. Usage: lunora env get <KEY>");
96
- return { code: 1, descriptors: [] };
97
- }
98
- const entry = loadDevVariables(devVariablesPath).get(options.key);
99
- if (!entry) {
100
- logger.error(`env: ${options.key} is not set in ${DEV_VARS_FILE}`);
101
- return { code: 1, descriptors: [] };
102
- }
103
- process.stdout.write(`${entry.value}
104
- `);
105
- return { code: 0, descriptors: [] };
106
- };
107
- const runEnvSet = (context) => {
108
- const { devVariablesPath, logger, options } = context;
109
- if (!options.key) {
110
- logger.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>");
111
- return { code: 1, descriptors: [] };
112
- }
113
- if (!DEV_VARS_KEY_PATTERN.test(options.key)) {
114
- logger.error(`env: invalid key "${options.key}" — must match [A-Za-z_][A-Za-z0-9_]*`);
115
- return { code: 1, descriptors: [] };
116
- }
117
- if (options.value === void 0) {
118
- logger.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>");
119
- return { code: 1, descriptors: [] };
120
- }
121
- if (NEWLINE_PRESENT.test(options.value)) {
122
- logger.error(`env: value for "${options.key}" contains a newline, which .dev.vars cannot represent`);
123
- return { code: 1, descriptors: [] };
124
- }
125
- if (UNREPRESENTABLE_PRESENT.test(options.value)) {
126
- logger.error(`env: value for "${options.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`);
127
- return { code: 1, descriptors: [] };
128
- }
129
- const map = loadDevVariables(devVariablesPath);
130
- map.set(options.key, { key: options.key, value: options.value });
131
- writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
132
- logger.success(`env: set ${options.key} (${redact(options.value)}) in ${DEV_VARS_FILE}`);
133
- return { code: 0, descriptors: [] };
134
- };
135
- const runEnvUnset = (context) => {
136
- const { devVariablesPath, logger, options } = context;
137
- if (!options.key) {
138
- logger.error("env unset requires a key. Usage: lunora env unset <KEY>");
139
- return { code: 1, descriptors: [] };
140
- }
141
- const map = loadDevVariables(devVariablesPath);
142
- if (!map.delete(options.key)) {
143
- logger.warn(`env: ${options.key} was not set in ${DEV_VARS_FILE}`);
144
- return { code: 0, descriptors: [] };
145
- }
146
- writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
147
- logger.success(`env: unset ${options.key} in ${DEV_VARS_FILE}`);
148
- return { code: 0, descriptors: [] };
149
- };
150
- const runEnvPush = async (context) => {
151
- const { devVariablesPath, logger, options } = context;
152
- if (!options.yes) {
153
- logger.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm.");
154
- return { code: 1, descriptors: [] };
155
- }
156
- const map = loadDevVariables(devVariablesPath);
157
- if (map.size === 0) {
158
- logger.warn(`${DEV_VARS_FILE}: nothing to push (empty)`);
159
- return { code: 0, descriptors: [] };
160
- }
161
- const spawner = options.spawner ?? defaultSpawner;
162
- const descriptors = [];
163
- for (const entry of map.values()) {
164
- const args = ["exec", "wrangler", "secret", "put", entry.key];
165
- if (options.prod) {
166
- args.push("--env", "production");
167
- }
168
- if (options.temporary) {
169
- args.push("--temporary");
170
- }
171
- const descriptor = {
172
- args,
173
- command: "pnpm",
174
- cwd: options.cwd ?? process.cwd(),
175
- // `wrangler secret put <name>` reads the value from stdin. We
176
- // pipe it through the spawner's `input` channel so the secret
177
- // never lands on the command line, in env, or in shell history.
178
- input: entry.value
179
- };
180
- descriptors.push(descriptor);
181
- logger.info(`pushing ${entry.key} -> wrangler secret${options.prod ? " (production)" : ""}`);
182
- const result = await spawner(descriptor);
183
- if (result.code !== 0) {
184
- logger.error(`env push: failed at ${entry.key} (exit ${String(result.code)})`);
185
- return { code: result.code, descriptors };
186
- }
187
- }
188
- logger.success(`env: pushed ${String(map.size)} secret(s)`);
189
- return { code: 0, descriptors };
190
- };
191
- const fetchRemoteSecretNames = (context) => {
192
- const lister = context.options.secretLister ?? listRemoteSecrets;
193
- return lister({
194
- cwd: context.cwd,
195
- env: context.options.prod ? "production" : void 0,
196
- temporary: context.options.temporary
197
- });
198
- };
199
- const runEnvDiff = async (context) => {
200
- const { devVariablesPath, logger } = context;
201
- const remote = await fetchRemoteSecretNames(context);
202
- if (!remote.ok) {
203
- logger.error(`env diff: ${remote.error ?? "failed to list remote secrets"}`);
204
- return { code: 1, descriptors: [] };
205
- }
206
- const localKeys = new Set(loadDevVariables(devVariablesPath).keys());
207
- const remoteKeys = new Set(remote.names);
208
- const localOnly = [...localKeys].filter((key) => !remoteKeys.has(key)).toSorted((a, b) => a.localeCompare(b));
209
- const remoteOnly = remote.names.filter((name) => !localKeys.has(name));
210
- const both = [...localKeys].filter((key) => remoteKeys.has(key)).toSorted((a, b) => a.localeCompare(b));
211
- for (const key of localOnly) {
212
- logger.info(`local only (run \`lunora env push\`): ${key}`);
213
- }
214
- for (const key of remoteOnly) {
215
- logger.info(`remote only (in Cloudflare, not ${DEV_VARS_FILE}): ${key}`);
216
- }
217
- logger.info(`in both: ${String(both.length)} secret(s)`);
218
- if (localOnly.length === 0 && remoteOnly.length === 0) {
219
- logger.success("env diff: local and remote secret names match");
220
- }
221
- return { code: 0, descriptors: [] };
222
- };
223
- const runEnvDoctor = (context) => {
224
- const { cwd, devVariablesPath, logger } = context;
225
- const examplePath = join(cwd, DEV_VARS_EXAMPLE_FILE);
226
- if (!existsSync(examplePath)) {
227
- logger.info(`env doctor: no ${DEV_VARS_EXAMPLE_FILE} to check against — nothing to validate.`);
228
- return { code: 0, descriptors: [] };
229
- }
230
- const exampleKeys = parseDevVariableEntries(readFileSync(examplePath, "utf8")).map((entry) => entry.key);
231
- const current = loadDevVariables(devVariablesPath);
232
- if (!existsSync(devVariablesPath)) {
233
- logger.error(`env doctor: ${DEV_VARS_FILE} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`);
234
- logger.info(`expected (from ${DEV_VARS_EXAMPLE_FILE}): ${exampleKeys.join(", ")}`);
235
- return { code: 1, descriptors: [] };
236
- }
237
- const missing = exampleKeys.filter((key) => !current.has(key));
238
- const placeholders = [...current.values()].filter((entry) => isPlaceholderValue(entry.value)).map((entry) => entry.key);
239
- const exampleKeySet = new Set(exampleKeys);
240
- const extra = [...current.keys()].filter((key) => !exampleKeySet.has(key));
241
- for (const key of missing) {
242
- logger.error(`missing: ${key} is in ${DEV_VARS_EXAMPLE_FILE} but not ${DEV_VARS_FILE}`);
243
- }
244
- for (const key of placeholders) {
245
- logger.error(`unset: ${key} still has a placeholder value`);
246
- }
247
- for (const key of extra) {
248
- logger.info(`extra: ${key} is set locally but not listed in ${DEV_VARS_EXAMPLE_FILE}`);
249
- }
250
- if (missing.length === 0 && placeholders.length === 0) {
251
- logger.success(`env doctor: ${DEV_VARS_FILE} looks good (${String(current.size)} var(s)).`);
252
- return { code: 0, descriptors: [] };
253
- }
254
- return { code: 1, descriptors: [] };
255
- };
256
- const runEnvCommand = async (options) => {
257
- const cwd = options.cwd ?? process.cwd();
258
- const context = {
259
- cwd,
260
- devVariablesPath: join(cwd, DEV_VARS_FILE),
261
- logger: options.logger,
262
- options
263
- };
264
- switch (options.subcommand) {
265
- case "diff": {
266
- return runEnvDiff(context);
267
- }
268
- case "doctor": {
269
- return runEnvDoctor(context);
270
- }
271
- case "get": {
272
- return runEnvGet(context);
273
- }
274
- case "list": {
275
- return runEnvList(context);
276
- }
277
- case "push": {
278
- return runEnvPush(context);
279
- }
280
- case "set": {
281
- return runEnvSet(context);
282
- }
283
- case "unset": {
284
- return runEnvUnset(context);
285
- }
286
- default: {
287
- options.logger.error(`env: unknown subcommand "${options.subcommand}"`);
288
- return { code: 1, descriptors: [] };
289
- }
290
- }
291
- };
292
- const isEnvSubcommand = (value) => value === "list" || value === "get" || value === "set" || value === "unset" || value === "push" || value === "diff" || value === "doctor";
293
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
294
- const sub = argument[0];
295
- if (!isEnvSubcommand(sub)) {
296
- logger.error(`env: unknown subcommand "${sub ?? ""}" — expected list | get | set | unset | push | diff | doctor`);
297
- return { code: 1 };
298
- }
299
- return runEnvCommand({
300
- cwd,
301
- key: argument[1],
302
- logger,
303
- prod: options.prod === true,
304
- subcommand: sub,
305
- temporary: options.temporary === true,
306
- value: argument[2],
307
- yes: options.yes === true
308
- });
309
- });
310
-
311
- export { execute, runEnvCommand };
1
+ import{readLinkedProject as g,resolveDeployDriver as v,execArgsFor as h,detectPackageManager as y}from"@lunora/config";import{d as b}from"../packem_shared/command-DwC11Cwe.mjs";import{defaultSpawner as w}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{createR2Sql as L}from"@lunora/bindings/r2sql";import{createPipelineLogReader as S}from"@lunora/runtime";const _=new Set(["debug","error","fatal","info","log","trace","warn"]),m=/^\d+$/,d=(e,t)=>{if(e===void 0)return;const a=e.trim();if(m.test(a))return Number(a);const r=Date.parse(a);if(Number.isNaN(r))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return r},T=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),C=e=>{const t=e.trim();if(m.test(t))return{ts:Number(t)};let a;try{a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:r}=a,i=a.seen,n=Array.isArray(i)?i.filter(s=>typeof s=="string"):void 0;return n!==void 0&&n.length>0?{seen:n,ts:r}:{ts:r}},u=(e,t)=>{if(e!==void 0){if(!_.has(e))throw new TypeError(`logs: invalid ${t} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},I=e=>{const t={},a=d(e.since,"--since");a!==void 0&&(t.sinceTs=a);const r=d(e.until,"--until");r!==void 0&&(t.untilTs=r);const i=u(e.level,"--level");i!==void 0&&(t.level=i);const n=u(e.minLevel,"--min-level");if(n!==void 0&&(t.minLevel=n),e.functionPrefix!==void 0&&(t.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(t.traceId=e.traceId),e.shardKey!==void 0&&(t.shardKey=e.shardKey),e.userId!==void 0&&(t.userId=e.userId),e.limit!==void 0){const s=Number(e.limit);if(!Number.isFinite(s))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=s}return e.cursor!==void 0&&(t.cursor=C(e.cursor)),t},$=e=>{const t=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${t} ${a} ${e.functionPath} ${e.message}`},x=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,r=t.R2_SQL_TOKEN,i=t.R2_SQL_BUCKET,n=[];if((a===void 0||a.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(r===void 0||r.length===0)&&n.push("R2_SQL_TOKEN"),(i===void 0||i.length===0)&&n.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&n.push("--table"),n.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:1,error:"not configured"};let s;try{s=I(e)}catch(o){return e.logger.error(o instanceof Error?o.message:String(o)),{code:1,error:"invalid option"}}const l=L({accountId:a,apiToken:r,bucket:i,fetch:e.fetch}),c=await S(l,{namespace:e.namespace,table:e.table}).query(s);for(const o of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(o):$(o)}
2
+ `);return c.rows.length===0?e.logger.info("logs --durable: no matching log records"):c.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${T(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},E=new Set(["json","pretty"]),N=async e=>{const t=e.cwd??process.cwd();if(e.format!==void 0&&!E.has(e.format))return e.logger.error(`logs: unknown --format "${e.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const a=e.env??g(t)?.env,r=v(e.target);if(r.toolchain===void 0)return e.logger.error(`logs: deploy target "${r.id}" has no command-line toolchain`),{code:1,descriptor:void 0,error:"no toolchain"};const i=r.toolchain.tail({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),n=h(y(t),i.tool,i.args),s={args:n.args,command:n.command,cwd:t};return e.logger.info(`tailing logs via ${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??w)(s)).code,descriptor:s}},Q=b(({argument:e,cwd:t,logger:a,options:r})=>r.durable===!0?x({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:a,minLevel:r.minLevel,namespace:r.namespace,ndjson:r.ndjson===!0,shardKey:r.shardKey,since:r.since,table:r.table,traceId:r.traceId,until:r.until,userId:r.userId}):N({cwd:t,env:r.env,format:r.format,logger:a,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]}));export{Q as execute,N as runLogsCommand};
@@ -0,0 +1,3 @@
1
+ import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-DwC11Cwe.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-DZAGzg67.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
2
+ `)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
3
+ `,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
@@ -0,0 +1,3 @@
1
+ import K,{join as l,resolve as T}from"node:path";import{isInteractive as F,promptYesNo as z}from"@lunora/config";import{backupObjectKey as p,isBackupManifestEntry as x,normalizeBackupPrefix as H,BACKUP_KEY_PREFIX as J,backupManifestKey as G,isBackupManifestKey as Y,backupObjectKeyOfManifest as O}from"@lunora/runtime";import{r as A}from"../packem_shared/admin-token-rxXZbVMZ.mjs";import{r as v}from"../packem_shared/admin-url-Cil3Or6N.mjs";import{d as W}from"../packem_shared/command-DwC11Cwe.mjs";import{r as X}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{randomUUID as U,createHash as Q}from"node:crypto";import{existsSync as $,createReadStream as V,createWriteStream as Z}from"node:fs";import{mkdir as ee,rm as w,rename as B,readFile as D,writeFile as re,realpath as N,mkdtemp as S}from"node:fs/promises";import{LunoraError as h}from"@lunora/errors";import{i as E}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as I}from"node:os";import{Readable as te}from"node:stream";import{pipeline as ae}from"node:stream/promises";import{b as oe,l as ne,M as _,u as ie,r as ce}from"../packem_shared/import-CdHdZRjj.mjs";import{runExportCommand as se}from"../packem_shared/runExportCommand-DmXKEWSq.mjs";const y="manifest.json",j=async e=>{const r=Q("sha256");let a=0;for await(const t of V(e)){const o=t;a+=o.byteLength,r.update(o)}return{bytes:a,sha256:r.digest("hex")}},P=async e=>{const r=l(e,y);if(!$(r))return[];let a;try{a=JSON.parse(await D(r,"utf8"))}catch(t){const o=t instanceof Error?t.message:String(t);throw new h("INTERNAL",`backup: ${r} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:t})}if(!Array.isArray(a))throw new TypeError(`backup: ${r} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return a.filter(t=>x(t))},ue=async(e,r)=>{const a=l(e,`${y}.${U()}.tmp`);try{await re(a,`${JSON.stringify(r,void 0,2)}
2
+ `,"utf8"),await B(a,l(e,y))}catch(t){throw await w(a,{force:!0}),t}},de=async(e,r)=>{const a=T(e),t=T(a,r.file),o=()=>{throw new h("INTERNAL",`backup: entry ${r.id} points outside ${a} (${r.file}) — refusing to read it`)};if(E(a,t)||o(),!!$(t))return E(await N(a),await N(t))||o(),t},le=e=>{const r=a=>p("",a);return{commit:async(a,t)=>{await B(t,l(e,a))},label:e,list:async()=>P(e),locate:r,materialize:async(a,t)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(a===void 0?$(t)?t:void 0:await de(e,a))},record:async a=>{const t=await P(e);t.push(a),await ue(e,t)},stage:async a=>{await ee(e,{recursive:!0});const t=l(e,`${r(a)}.${U()}.partial`);return{path:t,release:()=>w(t,{force:!0})}}}},fe="/_lunora/admin/storage/object",me="/_lunora/admin/storage",R=8,ge=(e,r=K)=>{const a=r.basename(e);return a===""||a==="."||a===".."?"snapshot.ndjson":a},he=e=>{const{context:r,logger:a}=e,t=H(e.prefix??J),o=`bucket ${r.bucket??"(default)"} under ${t}`,i=oe(r),u=c=>`${r.baseUrl}${fe}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const n=await r.fetchImpl(u(c),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!n.ok){const d=await n.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not read ${c} (HTTP ${String(n.status)}): ${d}`)}return n.text()},C=async c=>{try{const n=JSON.parse(await f(c));if(x(n))return n;a.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(n){a.warn(`backup: ignoring ${c} — ${n instanceof Error?n.message:String(n)}`)}};return{commit:async(c,n,d)=>{if(d.bytes>_)throw new h("INTERNAL",`backup: the snapshot is ${String(d.bytes)} bytes, above the ${String(_)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const s=await D(n);await ie(r,c,s,{contentType:"application/x-ndjson",id:c,sha256:d.sha256,size:d.bytes},a)},label:o,list:async()=>{const n=(await ne(r,t)).map(s=>s.key).filter(s=>Y(s)),d=[];for(let s=0;s<n.length;s+=R){const m=await Promise.all(n.slice(s,s+R).map(async g=>C(g)));d.push(...m.filter(g=>g!==void 0))}return d.toSorted((s,m)=>s.id.localeCompare(m.id))},locate:c=>p(t,c),materialize:async(c,n)=>{const d=c?.file??n,s=await r.fetchImpl(u(d),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(s.status===404)return;if(!s.ok||s.body===null){const k=await s.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not download ${d} (HTTP ${String(s.status)}): ${k}`)}const m=await S(l(I(),"lunora-backup-")),g=l(m,ge(d));try{await ae(te.from(s.body),Z(g))}catch(k){throw await w(m,{force:!0,recursive:!0}),k}return{path:g,release:async()=>w(m,{force:!0,recursive:!0})}},record:async c=>{const n=G(c.file),d=await r.fetchImpl(`${r.baseUrl}${me}?key=${encodeURIComponent(n)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
3
+ `,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"PUT"});if(!d.ok){const s=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(d.status)}): ${s}`)}},stage:async c=>{const n=await S(l(I(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},we=".lunora-backups",L="/_lunora/admin/backup/retention",be="/_lunora/admin/backup/prune",ke="/_lunora/admin/pitr",pe="__lunora_admin__:getPitrBookmark",ye="__lunora_admin__:pitrRestore",ve=async(e,r)=>{const a=(e.now??(()=>new Date))().toISOString(),t=await r.stage(a);try{const o=await se({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:t.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=r.locate(a),u=await j(t.path);await r.commit(i,t.path,u);const f={bytes:u.bytes,createdAt:a,file:i,id:a,rows:o.rows,sha256:u.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${u.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await t.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},$e=async(e,r,a)=>{if(r?.sha256===void 0)return a.error(r===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${r.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:1};const t=await j(e);if(t.sha256!==r.sha256)return a.error(`--verify: ${r.file} does not match its recorded checksum (expected ${r.sha256}, got ${t.sha256}) — nothing was imported`),{code:1};a.success(`verified ${r.file} against its recorded sha256`)},Te=async(e,r)=>{const a=await r.list();if(a.length===0)return e.logger.info(`no backups found in ${r.label}`),{code:0};for(const t of a)e.logger.info(`${t.id} ${t.rows.toString()} rows ${t.bytes.toString()} bytes ${t.file}`);return{code:0}},Ne=async(e,r)=>{const{target:a}=e;if(a===void 0||a.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const o=(await r.list()).find(u=>u.id===a),i=await r.materialize(o,a);if(i===void 0)return e.logger.error(`backup not found: ${a}`),{code:1};try{if(e.verify===!0){const f=await $e(i.path,o,e.logger);if(f!==void 0)return f}return{code:(await ce({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes})).code}}finally{await i.release().catch(u=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${u instanceof Error?u.message:String(u)})`)})}},Se=e=>{const r=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!r){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0){e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(e.restore===!0&&e.prod===!0&&e.yes!==!0){e.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const t=e.adminFetch??globalThis.fetch;if(typeof t!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:t,requestUrl:`${a}${ke}`,token:r}},Ee=(e,r)=>{const a={};return e.at!==void 0&&(a.time=e.at),r&&e.bookmark!==void 0&&(a.bookmark=e.bookmark),r&&e.restart===!0&&(a.restart=!0),a},Ie=async e=>{const r=Se(e);if(r===void 0)return{code:1};const a=e.restore===!0,t=a?ye:pe,o=Ee(e,a),i=a?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const u=await r.fetchImpl(r.requestUrl,{body:JSON.stringify({args:o,functionPath:t,shardKey:e.shard}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});return await b(u,e.logger),{code:u.ok?0:1}},_e=(e,r)=>{if(e.bucket===void 0)return le(l(r,e.dir??we));if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=A({cwd:r,token:e.token,url:a});if(!t){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return he({context:{baseUrl:a,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:t},logger:e.logger,prefix:e.prefix})},q=e=>{const r=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(r.length>0){e.logger.error(`${r.join(" / ")} ${r.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`);return}if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const a=v(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=A({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!t){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:a,fetchImpl:o,token:t}},M=(e,r)=>{e.logger.info(`backup retention would keep the newest ${r.keep.toString()} of ${r.eligible.toString()} under ${r.prefix} and delete ${r.wouldDelete.length.toString()}`);for(const a of r.wouldDelete)e.logger.info(` ${O(a)}`)},Pe=async e=>{const r=q(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();return t.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:t}):t.keep<=0?(e.logger.info(`retention is off for cron "${t.cron}" (\`backupRetain\` unset) — every snapshot under ${t.prefix} is kept`),{code:0,preview:t}):(M(e,t),t.eligible===0&&e.logger.info(`no snapshot under ${t.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:t})},Re=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const a of r.deleted)e.logger.info(` ${O(a)}`);r.failed.length>0&&e.logger.warn(`${r.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),r.ignored>0&&e.logger.info(`${r.ignored.toString()} were already gone by the time the delete ran`),r.remaining>0&&e.logger.info(`${r.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},xe=async e=>{const r=q(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();if(t.keep<=0||t.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:1,preview:t};if(t.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${t.eligible.toString()} snapshot(s) under ${t.prefix} and retention keeps the newest ${t.keep.toString()}`),{code:0,preview:t};if(M(e,t),e.yes!==!0){const u=e.confirm??(F()?z:void 0);if(u===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:1,preview:t};if(!await u(`delete ${t.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:t}}const o=await r.fetchImpl(`${r.baseUrl}${be}`,{body:JSON.stringify({confirm:t.wouldDelete}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await b(o,e.logger),{code:1,preview:t};const i=await o.json();return Re(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:t}},Oe=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await Ie(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await xe(e);const a=_e(e,r);return a===void 0?{code:1}:e.subcommand==="create"?await ve(e,a):e.subcommand==="list"?await Te(e,a):await Ne(e,a)}catch(a){return e.logger.error(a instanceof Error?a.message:String(a)),{code:1}}},Ae=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ve=W(({argument:e,cwd:r,logger:a,options:t})=>{const o=e[0];return Ae(o)?Oe({at:t.at,bookmark:t.bookmark,bucket:t.bucket,cwd:r,dir:t.dir,logger:a,prefix:t.prefix,prod:t.prod===!0,restart:t.restart===!0,restore:t.restore===!0,shard:t.shard,subcommand:o,tables:t.tables,target:e[1],token:t.token,url:X({cwd:r,prod:t.prod===!0,url:t.url}),verify:t.verify===!0,yes:t.yes===!0}):(a.error(`backup: unknown subcommand "${o??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Ve as execute,Oe as runBackupCommand};
@@ -0,0 +1 @@
1
+ import{readdirSync as w,lstatSync as R,existsSync as T}from"node:fs";import{join as v,basename as $}from"node:path";import{pathToFileURL as O}from"node:url";import{d as _}from"../packem_shared/command-DwC11Cwe.mjs";import{v as N,i as g,p as E,l as x}from"../packem_shared/output-format-DfogXx0p.mjs";const c=".eval.ts",b=new Set([".git","_generated","dist","node_modules"]),p=(e,s=[])=>{let r;try{r=w(e)}catch{return s}for(const t of r){const o=v(e,t);let n;try{n=R(o)}catch{continue}if(n.isDirectory()){if(b.has(t))continue;p(o,s)}else n.isFile()&&t.endsWith(c)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},L=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",S=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,I="evals",A='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',D=/unknown file extension ".ts"/i,y=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:D.test(e.message):!1,m=e=>$(e,c),M=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),F=e=>({code:e.code,error:e.error,evals:e.evals.map(s=>M(s))}),i=(e,s,r)=>{e.error(r);const t={code:1,error:r,evals:[]};return g(s)&&E(F(t)),t},U=(e,s,r)=>{if(!T(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=p(e);return t.length===0&&r.info(`eval: no ${c} files found under "${s}"`),t},C=async e=>{const r=(await import(O(e).href)).default;if(!L(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},J=async(e,s)=>{let r;try{r=await C(e)}catch(n){if(y(n))throw n;return{error:n instanceof Error?n.message:String(n),name:m(e),passed:!1,path:e}}const t=r.name??m(e);if(r.threshold!==void 0&&!S(r.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(r.threshold)}`,name:t,passed:!1,path:e};const o=r.threshold??s;try{const n=await r.run(),l=o===void 0||n.average>=o;return{name:t,passed:l,path:e,result:n,threshold:o}}catch(n){return{error:n instanceof Error?n.message:String(n),name:t,passed:!1,path:e,threshold:o}}},W=async(e,s)=>{const r=[];for(const t of e)r.push(await J(t,s));return r},H=e=>{if(e.error!==void 0)return`ERROR: ${e.error}`;const s=e.passed?"pass":"FAIL",r=e.result?.items.length??0;return`${s} (${String(r)} cases)`},V=e=>{if(e.length===0)return[];const s=Math.max(4,...e.map(t=>t.name.length)),r=[`${"NAME".padEnd(s)} SCORE THRESHOLD STATUS`];for(const t of e){const o=t.result===void 0?"—":t.result.average.toFixed(3),n=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${o.padEnd(6)} ${n.padEnd(9)} ${H(t)}`)}return r},X=async e=>{const s=e.cwd??process.cwd(),r=x(e.format,e.logger),t=N("eval",e.format);if(t!==void 0)return e.logger.error(t),{code:1,error:t,evals:[]};if(e.threshold!==void 0&&!S(e.threshold))return i(r,e.format,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`);const o=e.dir??I,n=v(s,o),l=U(n,o,r);let d;try{d=await W(l,e.threshold)}catch(a){if(!y(a))throw a;return i(r,e.format,A)}if(e.threshold!==void 0&&d.length===0){const a=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${o}" — nothing was gated`;return i(r,e.format,a)}for(const a of V(d))r.info(a);const h=d.filter(a=>!a.passed),f=h.length>0?1:0;f===0?r.success(`eval: ${String(d.length)} eval(s) passed`):r.error(`eval: ${String(h.length)}/${String(d.length)} eval(s) failed`);const u={code:f,evals:d};return g(e.format)&&E(F(u)),u},z=_(async({cwd:e,logger:s,options:r})=>({code:(await X({cwd:e,dir:r.dir,format:r.format,logger:s,threshold:r.threshold})).code}));export{z as execute,X as runEvalCommand};