@lunora/cli 1.0.0-alpha.2 → 1.0.0-alpha.200

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 (109) 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 +797 -358
  6. package/dist/index.d.ts +797 -358
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/handler.mjs +1 -76
  9. package/dist/packem_chunks/handler10.mjs +2 -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 -41
  16. package/dist/packem_chunks/handler17.mjs +1 -105
  17. package/dist/packem_chunks/handler18.mjs +1 -172
  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 +2 -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 -543
  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 +1141 -565
  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-su5nmqYP.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Nf7GsE6v.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/buildRegistryIndex-Zi3bBqpc.mjs +1 -0
  48. package/dist/packem_shared/cli-RB-BoDnW.mjs +3 -0
  49. package/dist/packem_shared/codegen-error-C04fGQjf.mjs +3 -0
  50. package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
  51. package/dist/packem_shared/commands-BOgN2nF7.mjs +19 -0
  52. package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
  53. package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
  54. package/dist/packem_shared/deploy-target-D9GPy_tq.mjs +1 -0
  55. package/dist/packem_shared/detect-package-manager-DSaAqRof.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/health-probe-QEPfFdgJ.mjs +1 -0
  59. package/dist/packem_shared/import-CrVGrOt3.mjs +12 -0
  60. package/dist/packem_shared/insertSchemaExtension-DY4pA8wE.mjs +8 -0
  61. package/dist/packem_shared/lint-ignore-report-CDbcbtv7.mjs +2 -0
  62. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  63. package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
  64. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  65. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  66. package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +4 -0
  67. package/dist/packem_shared/post-codegen-hook-DRdEoTsQ.mjs +1 -0
  68. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  69. package/dist/packem_shared/resolve-DZAGzg67.mjs +1 -0
  70. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  71. package/dist/packem_shared/runAddCommand-BXz-PXbb.mjs +1 -0
  72. package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +5 -0
  73. package/dist/packem_shared/schema-drift-gate-AscQpYH5.mjs +1 -0
  74. package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +1 -0
  75. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  76. package/dist/packem_shared/tui-prompts-Dd0pDuNr.mjs +4 -0
  77. package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +1 -0
  78. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  79. package/dist/packem_shared/wrangler-secrets-CE7jcf8E.mjs +1 -0
  80. package/package.json +43 -19
  81. package/skills/README.md +35 -17
  82. package/skills/lunora/SKILL.md +65 -9
  83. package/skills/lunora-functions/SKILL.md +38 -3
  84. package/skills/lunora-migration-helper/SKILL.md +70 -17
  85. package/skills/lunora-performance-audit/SKILL.md +36 -6
  86. package/skills/lunora-quickstart/SKILL.md +90 -24
  87. package/skills/lunora-realtime/SKILL.md +58 -30
  88. package/skills/lunora-setup-storage/SKILL.md +7 -3
  89. package/dist/packem_shared/COMMANDS-1V_KEx35.mjs +0 -905
  90. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  91. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  92. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  93. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  94. package/dist/packem_shared/command-BDXcJCCJ.mjs +0 -14
  95. package/dist/packem_shared/createLogger-CHPNjFw2.mjs +0 -73
  96. package/dist/packem_shared/defaultSpawner-DxI3mebw.mjs +0 -43
  97. package/dist/packem_shared/diffSnapshots-RR2ZE8Ya.mjs +0 -161
  98. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  99. package/dist/packem_shared/features-ocSSpZtS.mjs +0 -24
  100. package/dist/packem_shared/insertSchemaExtension-BuzF6-t2.mjs +0 -59
  101. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  102. package/dist/packem_shared/output-format-7gyGR3h8.mjs +0 -17
  103. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  104. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  105. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  106. package/dist/packem_shared/runAddCommand-BZGkRnBs.mjs +0 -693
  107. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  108. package/dist/packem_shared/schemaIrToSnapshot-aBTo7TM5.mjs +0 -43
  109. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,94 +1,2 @@
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-BDXcJCCJ.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{readdirSync as u,readFileSync as m,mkdirSync as f,writeFileSync as g}from"node:fs";import{join as p,resolve as l,isAbsolute as w,dirname as y}from"node:path";import{findWranglerFile as b,readWranglerJsonc as h,buildBindingManifest as v}from"@lunora/config/cloudflare";import{p as S}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as B}from"../packem_shared/command-DwC11Cwe.mjs";import{v as F,l as $,i as D,p as k}from"../packem_shared/output-format-DfogXx0p.mjs";import{defaultSpawner as z}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{runDeployCommand as M}from"./runDeployCommand.mjs";import{gzipSync as A}from"node:zlib";const T=e=>!e.endsWith(".map")&&e!=="bundle-meta.json"&&e!=="README.md",W=e=>{let n;try{n=u(e,{recursive:!0,withFileTypes:!0})}catch{return}let r=0,i=0,s=0;for(const t of n){if(!t.isFile()||!T(t.name))continue;const o=m(p(t.parentPath,t.name));r+=1,s+=o.byteLength,i+=A(o).byteLength}return r===0?void 0:{files:r,gzipBytes:i,rawBytes:s}},E=".lunora/build",J=async e=>z({...e,stdoutToStderr:!0}),c=e=>`${(e/1024).toFixed(1)} KiB`,O=(e,n,r)=>{const i=b(e),s=i===void 0?void 0:h(i).parsed;if(s===void 0)return{error:`--emit-bindings found no readable wrangler config in ${e}. The manifest is derived from it, and an empty one would tell a deployer this Worker needs nothing.`};const t=v(s),o=w(n)?n:l(e,n);return f(y(o),{recursive:!0}),g(o,`${JSON.stringify(t,void 0,2)}
2
+ `,"utf8"),r.success(`binding manifest written to ${o} (${t.bindings.length.toString()} bindings, ${t.crons.length.toString()} crons)`),t.unknown.length>0&&r.warn(`binding manifest does not model these wrangler sections: ${t.unknown.join(", ")}. Anything they bind must be provisioned by hand — please report them so the manifest can cover them.`),{}},P=async e=>{const n=e.outDir??E,r=D(e.format),i=$(e.format,e.logger),s=a=>(r&&k(a),a),t=F("build",e.format);if(t!==void 0)return e.logger.error(t),{code:1,descriptor:void 0,error:t,validation:{problems:[],wranglerPath:void 0}};const o=await M({apiSpec:e.apiSpec,cwd:e.cwd,dryRun:!0,format:void 0,interactive:r?!1:void 0,logger:i,outDir:n,spawner:e.spawner??(r?J:void 0),target:e.target});if(o.code!==0)return s(o);i.success(`build complete — bundle written to ${n}`);const d=W(l(e.cwd??process.cwd(),n));if(d===void 0?i.warn(`could not weigh the bundle — nothing uploadable was found in ${n}`):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:a}=O(e.cwd??process.cwd(),e.emitBindings,i);if(a!==void 0)return i.error(a),s({...o,bundle:d,code:1})}return s({...o,bundle:d})},N=B(async({cwd:e,logger:n,options:r})=>({code:(await P({apiSpec:S(r.apiSpec),cwd:e,emitBindings:r.emitBindings,format:r.format,logger:n,outDir:r.outDir,target:r.target})).code}));export{N as execute,P 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-BDXcJCCJ.mjs';
5
- import { defaultSpawner } from '../packem_shared/defaultSpawner-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}from"@lunora/config";import{d as h}from"../packem_shared/command-DwC11Cwe.mjs";import{e as y,d as b}from"../packem_shared/detect-package-manager-DSaAqRof.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,s=a.seen,n=Array.isArray(s)?s.filter(i=>typeof i=="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 s=u(e.level,"--level");s!==void 0&&(t.level=s);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 i=Number(e.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=i}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}`},p=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,r=t.R2_SQL_TOKEN,s=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"),(s===void 0||s.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 i;try{i=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:s,fetch:e.fetch}),c=await S(l,{namespace:e.namespace,table:e.table}).query(i);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}},x=new Set(["json","pretty"]),E=async e=>{const t=e.cwd??process.cwd();if(e.format!==void 0&&!x.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 s=r.toolchain.tail({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),n=y(b(t),s.tool,s.args),i={args:n.args,command:n.command,cwd:t};return e.logger.info(`tailing logs via ${i.command} ${i.args.join(" ")}`),{code:(await(e.spawner??w)(i)).code,descriptor:i}},k=h(({argument:e,cwd:t,logger:a,options:r})=>r.durable===!0?p({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}):E({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{k as execute,E 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{a as X}from"../packem_shared/resolve-target-C_ZloTvd.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-CrVGrOt3.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};
@@ -0,0 +1,99 @@
1
+ import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as I,mkdir as k}from"node:fs/promises";import{join as b}from"@visulima/path";import{d as B}from"../packem_shared/command-DwC11Cwe.mjs";import{createRequire as U}from"node:module";import{LunoraError as N}from"@lunora/errors";import{b as Y,d as q}from"../packem_shared/detect-package-manager-DSaAqRof.mjs";import{parseSchema as F,applyAdditiveEdit as P}from"@lunora/config";const H=/^\//,K=(e,t)=>{try{const{args:n,command:r}=Y(q(e),[t],{dev:!0});return`${r} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${t}`}},L=(e,t,n)=>{const r=U(b(n,"noop.cjs"));try{r.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${t}\` driver to read this database, and it isn't installed.
2
+
3
+ Install it in your project:
4
+
5
+ ${K(n,t)}`)}return r(e)},j=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},G=e=>{try{const t=new URL(e).pathname.replace(H,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},J=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=L("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,d)=>(await u.query(l,[...d])).rows,schema:n??"public"}}const a=L("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??G(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),Q={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},W={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,t)=>{const r=(t==="postgres"?Q:W)[e.dataType],s=e.references===void 0?r:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,X=/[^\dA-Z]+(.)?/gi,z=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(V,t=>ee[t]??t),S=e=>M.test(e)?e:f(e),ne=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),te=e=>{const t=e.replaceAll(Z,"_");return t===""?"table":t},re=e=>{const n=e.replaceAll(X,(r,s)=>s?.toUpperCase()??"").replace(z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(t=>!h.has(t.name)),ae=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!h.has(n))},D=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),se=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){r.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
6
+ ${s.join(`
7
+ `)}
8
+ })
9
+ ${a.join(`
10
+ `)},`},oe=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>se(a,e.dialect,r,n)).join(`
11
+ `);return`/**
12
+ * Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
13
+ *
14
+ * This file is a STARTING POINT, not a build artifact — it is written once and is
15
+ * yours to edit. Review it before shipping: column types are mapped
16
+ * conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
17
+ * its rows live in the external database. Re-running \`lunora introspect\` will not
18
+ * overwrite it unless you pass \`--force\`.
19
+ */
20
+ import { defineSchema, defineTable, v } from "${t.serverImport}";
21
+
22
+ export default defineSchema({
23
+ ${s}
24
+ });
25
+ `},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(e.name)}`;return`/**
26
+ * Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
27
+ * starting point you own and edit.
28
+ *
29
+ * Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
30
+ * this data should be public, and gate them with your auth/RLS middleware first —
31
+ * \`introspect\` cannot know who is allowed to read this table.
32
+ */
33
+ import { defineListArgs, v } from "${n.serverImport}";
34
+
35
+ import type { Doc } from "./_generated/dataModel";
36
+ import { c } from "./_generated/server";
37
+
38
+ const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
39
+ // Only index-backed columns are published as filterable, so a caller cannot
40
+ // reach a column you did not choose to expose. Note that \`contains\` and the
41
+ // negative operators still scan — narrow this list, and review it, before
42
+ // adding \`.expose({ rest: true })\`.
43
+ filter: {
44
+ ${c.join(`
45
+ `)}
46
+ },
47
+ orderBy: [${m}],
48
+ });
49
+
50
+ export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
51
+
52
+ export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
53
+ `},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=te(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return r},ue=(e,t,n)=>{const r=[],s=new Set(t?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
54
+ SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
55
+ FROM information_schema.columns c
56
+ JOIN information_schema.tables t
57
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
58
+ WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
59
+ ORDER BY c.table_name, c.ordinal_position`,fe=`
60
+ SELECT tc.table_name, kcu.column_name
61
+ FROM information_schema.table_constraints tc
62
+ JOIN information_schema.key_column_usage kcu
63
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
64
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
65
+ ORDER BY tc.table_name, kcu.ordinal_position`,ve=`
66
+ SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
67
+ FROM information_schema.table_constraints tc
68
+ JOIN information_schema.key_column_usage kcu
69
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
70
+ JOIN information_schema.constraint_column_usage ccu
71
+ ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
72
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,he=`
73
+ SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
74
+ FROM pg_class t
75
+ JOIN pg_index ix ON t.oid = ix.indrelid
76
+ JOIN pg_class i ON i.oid = ix.indexrelid
77
+ JOIN pg_namespace n ON n.oid = t.relnamespace
78
+ CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
79
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
80
+ WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
81
+ ORDER BY t.relname, i.relname, k.ord`,be=`
82
+ SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
83
+ FROM information_schema.COLUMNS c
84
+ JOIN information_schema.TABLES t
85
+ ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
86
+ WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
87
+ ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,Ee=`
88
+ SELECT TABLE_NAME, COLUMN_NAME
89
+ FROM information_schema.KEY_COLUMN_USAGE
90
+ WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
91
+ ORDER BY TABLE_NAME, ORDINAL_POSITION`,_e=`
92
+ SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
93
+ FROM information_schema.KEY_COLUMN_USAGE
94
+ WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,ye=`
95
+ SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
96
+ FROM information_schema.STATISTICS
97
+ WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
98
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
99
+ `).length)} lines)`),!1):(await k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Ue=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Ue as execute,we as resolveServerImport,Te as runIntrospectCommand};