@lunora/cli 1.0.0-alpha.23 → 1.0.0-alpha.230
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.
- package/LICENSE.md +33 -0
- package/README.md +1 -1
- package/__assets__/package-og.svg +1 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +778 -346
- package/dist/index.d.ts +778 -346
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/handler.mjs +1 -150
- package/dist/packem_chunks/handler10.mjs +3 -16
- package/dist/packem_chunks/handler11.mjs +2 -22
- package/dist/packem_chunks/handler12.mjs +1 -192
- package/dist/packem_chunks/handler13.mjs +1 -131
- package/dist/packem_chunks/handler14.mjs +1 -65
- package/dist/packem_chunks/handler15.mjs +1 -58
- package/dist/packem_chunks/handler16.mjs +3 -79
- package/dist/packem_chunks/handler17.mjs +1 -43
- package/dist/packem_chunks/handler18.mjs +1 -105
- package/dist/packem_chunks/handler19.mjs +7 -170
- package/dist/packem_chunks/handler2.mjs +2 -114
- package/dist/packem_chunks/handler20.mjs +1 -89
- package/dist/packem_chunks/handler21.mjs +3 -94
- package/dist/packem_chunks/handler22.mjs +3 -0
- package/dist/packem_chunks/handler23.mjs +1 -0
- package/dist/packem_chunks/handler24.mjs +2 -0
- package/dist/packem_chunks/handler25.mjs +99 -0
- package/dist/packem_chunks/handler26.mjs +10 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler4.mjs +1 -33
- package/dist/packem_chunks/handler5.mjs +1 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +3 -42
- package/dist/packem_chunks/handler8.mjs +1 -174
- package/dist/packem_chunks/handler9.mjs +1 -315
- package/dist/packem_chunks/planDevCommand.mjs +7 -509
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDeployCommand.mjs +7 -594
- package/dist/packem_chunks/runInitCommand.mjs +162 -1392
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-rRB9TbDL.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BMH-ZXl5.mjs +1 -0
- package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
- package/dist/packem_shared/admin-url-BhF5ufg1.mjs +1 -0
- package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
- package/dist/packem_shared/buildRegistryIndex-DVmy8fHE.mjs +1 -0
- package/dist/packem_shared/catalog-Cbzph90w.mjs +1 -0
- package/dist/packem_shared/cli-DIb5Ay4K.mjs +3 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-DwC11Cwe.mjs +1 -0
- package/dist/packem_shared/commands-I18aR_DJ.mjs +15 -0
- package/dist/packem_shared/createLogger-hGafwf-3.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +1 -0
- package/dist/packem_shared/deploy-target-B0Xcb2jV.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-DtC5Cs4Z.mjs +5 -0
- package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
- package/dist/packem_shared/import-Dqd1MOOv.mjs +12 -0
- package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
- package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DfogXx0p.mjs +2 -0
- package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
- package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
- package/dist/packem_shared/resolve-B9ReA3FV.mjs +5 -0
- package/dist/packem_shared/resolve-target-BRvw8Pf7.mjs +1 -0
- package/dist/packem_shared/runAddCommand-BXea8slz.mjs +1 -0
- package/dist/packem_shared/runExportCommand-Dq-SpjAe.mjs +5 -0
- package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-e5fO6GRg.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-B0ixDDxG.mjs +1 -0
- package/dist/packem_shared/tui-prompts-DzYd2fL3.mjs +4 -0
- package/dist/packem_shared/vectorize-metadata-dXpl2_Ar.mjs +1 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CCdt0mUl.mjs +1 -0
- package/package.json +39 -17
- package/skills/README.md +35 -17
- package/skills/lunora/SKILL.md +65 -9
- package/skills/lunora-deploy/SKILL.md +42 -11
- package/skills/lunora-functions/SKILL.md +78 -15
- package/skills/lunora-migration-helper/SKILL.md +74 -21
- package/skills/lunora-performance-audit/SKILL.md +42 -9
- package/skills/lunora-quickstart/SKILL.md +93 -27
- package/skills/lunora-realtime/SKILL.md +58 -30
- package/skills/lunora-setup-auth/SKILL.md +23 -6
- package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
- package/skills/lunora-setup-mail/SKILL.md +34 -28
- package/skills/lunora-setup-scheduler/SKILL.md +18 -14
- package/skills/lunora-setup-storage/SKILL.md +182 -25
- package/dist/packem_shared/COMMANDS-Dwo9q7Bt.mjs +0 -947
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
- package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
- package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
- package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
- package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
- package/dist/packem_shared/commands-hl0mRqqg.mjs +0 -845
- package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
- package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
- package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
- package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
- package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
- package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
- package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
- package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
- package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
- package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-vJdgiR5t.mjs +0 -4
- package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
- package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
- package/dist/packem_shared/storage-B7hHSTZP.mjs +0 -84
- package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
- package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
|
@@ -1,89 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import { runCodegen } from '@lunora/codegen';
|
|
4
|
-
import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
|
|
5
|
-
import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
|
|
6
|
-
import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
|
|
7
|
-
import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
|
|
8
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
9
|
-
import { validateWranglerProject } from '@lunora/config';
|
|
10
|
-
|
|
11
|
-
const runTypecheckStep = async (cwd, spawner) => {
|
|
12
|
-
if (!existsSync(join(cwd, "tsconfig.json"))) {
|
|
13
|
-
return { warning: "no tsconfig.json found — skipping TypeScript type-check" };
|
|
14
|
-
}
|
|
15
|
-
const result = await spawner({ args: ["exec", "tsc", "--noEmit", "-p", "tsconfig.json"], command: "pnpm", cwd });
|
|
16
|
-
return result.code === 0 ? {} : { error: `type errors: tsc --noEmit exited ${String(result.code)}` };
|
|
17
|
-
};
|
|
18
|
-
const reportVerifyResult = (logger, errors, warnings, wranglerPath) => {
|
|
19
|
-
if (errors.length === 0 && warnings.length === 0) {
|
|
20
|
-
logger.success("verify: project is valid");
|
|
21
|
-
return { code: 0, errors: [], warnings: [], wranglerPath };
|
|
22
|
-
}
|
|
23
|
-
if (warnings.length > 0) {
|
|
24
|
-
logger.warn("verify: warnings:");
|
|
25
|
-
for (const warning of warnings) {
|
|
26
|
-
logger.warn(` - ${warning}`);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
if (errors.length > 0) {
|
|
30
|
-
logger.error("verify: errors:");
|
|
31
|
-
for (const error of errors) {
|
|
32
|
-
logger.error(` - ${error}`);
|
|
33
|
-
}
|
|
34
|
-
return { code: 1, errors, warnings, wranglerPath };
|
|
35
|
-
}
|
|
36
|
-
logger.success("verify: project is valid (with warnings)");
|
|
37
|
-
return { code: 0, errors: [], warnings, wranglerPath };
|
|
38
|
-
};
|
|
39
|
-
const runVerifyCommand = async (options) => {
|
|
40
|
-
const cwd = options.cwd ?? process.cwd();
|
|
41
|
-
const logger = loggerForFormat(options.format, options.logger);
|
|
42
|
-
const formatError = validateOutputFormat("verify", options.format);
|
|
43
|
-
if (formatError !== void 0) {
|
|
44
|
-
options.logger.error(formatError);
|
|
45
|
-
return { code: 1, error: formatError, errors: [], warnings: [], wranglerPath: void 0 };
|
|
46
|
-
}
|
|
47
|
-
const validation = validateWranglerProject({ projectRoot: cwd });
|
|
48
|
-
const errors = [...validation.report.errors];
|
|
49
|
-
const warnings = [...validation.report.warnings];
|
|
50
|
-
try {
|
|
51
|
-
const codegen = runCodegen({ apiSpec: options.apiSpec, dryRun: true, projectRoot: cwd });
|
|
52
|
-
const gate = runSchemaDriftGate({ allowDrift: options.allowSchemaDrift === true, codegen, logger, readOnly: true });
|
|
53
|
-
if (gate.blocked) {
|
|
54
|
-
errors.push(gate.reason);
|
|
55
|
-
}
|
|
56
|
-
} catch (error) {
|
|
57
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
58
|
-
errors.push(`codegen failed: ${message}`);
|
|
59
|
-
}
|
|
60
|
-
if (options.typecheck !== false) {
|
|
61
|
-
const typecheck = await runTypecheckStep(cwd, options.spawner ?? defaultSpawner);
|
|
62
|
-
if (typecheck.error !== void 0) {
|
|
63
|
-
errors.push(typecheck.error);
|
|
64
|
-
}
|
|
65
|
-
if (typecheck.warning !== void 0) {
|
|
66
|
-
warnings.push(typecheck.warning);
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
const result = reportVerifyResult(logger, errors, warnings, validation.wranglerPath);
|
|
70
|
-
if (isJsonFormat(options.format)) {
|
|
71
|
-
printJson(result);
|
|
72
|
-
}
|
|
73
|
-
return result;
|
|
74
|
-
};
|
|
75
|
-
const execute = defineHandler(async ({ cwd, logger, options }) => {
|
|
76
|
-
const result = await runVerifyCommand({
|
|
77
|
-
allowSchemaDrift: options.allowSchemaDrift === true,
|
|
78
|
-
apiSpec: parseApiSpec(options.apiSpec),
|
|
79
|
-
cwd,
|
|
80
|
-
format: options.format,
|
|
81
|
-
logger,
|
|
82
|
-
// `--no-typecheck` is declared as a `no-*` option but cerebro exposes it
|
|
83
|
-
// under the negated `typecheck` key (false when passed, true when absent).
|
|
84
|
-
typecheck: options.typecheck === false ? false : void 0
|
|
85
|
-
});
|
|
86
|
-
return { code: result.code };
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
export { execute, runVerifyCommand };
|
|
1
|
+
import{join as l,resolve as m}from"node:path";import{p as u}from"../packem_shared/deploy-target-B0Xcb2jV.mjs";import{d as f}from"../packem_shared/command-DwC11Cwe.mjs";import{v as p,l as g,i as w,p as y}from"../packem_shared/output-format-DfogXx0p.mjs";import{defaultSpawner as v}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 B}from"node:zlib";const D=e=>!e.endsWith(".map")&&e!=="bundle-meta.json"&&e!=="README.md",F=e=>{let t;try{t=S(e,{recursive:!0,withFileTypes:!0})}catch{return}let r=0,i=0,d=0;for(const a of t){if(!a.isFile()||!D(a.name))continue;const o=h(l(a.parentPath,a.name));r+=1,d+=o.byteLength,i+=B(o).byteLength}return r===0?void 0:{files:r,gzipBytes:i,rawBytes:d}},A=".lunora/build",z=async e=>v({...e,stdoutToStderr:!0}),c=e=>`${(e/1024).toFixed(1)} KiB`,$=async e=>{const t=e.outDir??A,r=w(e.format),i=g(e.format,e.logger),d=s=>(r&&y(s),s),a=p("build",e.format);if(a!==void 0)return e.logger.error(a),{code:1,descriptor:void 0,error:a,validation:{problems:[],wranglerPath:void 0}};const o=await b({allowSchemaDrift:e.allowSchemaDrift,apiSpec:e.apiSpec,commandName:"build",cwd:e.cwd,dryRun:!0,emitBindings:e.emitBindings,format:void 0,interactive:r?!1:void 0,logger:i,outDir:t,spawner:e.spawner??(r?z:void 0),strictAdvisories:e.strictAdvisories,target:e.target});if(o.code!==0)return d(o);i.success(`build complete — bundle written to ${t}`);const n=F(m(e.cwd??process.cwd(),t));return n===void 0?i.warn(`could not weigh the bundle — nothing uploadable was found in ${t}`):i.info(`bundle: ${c(n.rawBytes)} raw, ${c(n.gzipBytes)} gzipped across ${String(n.files)} file(s) — Cloudflare's Worker size limit (3 MB Free, 10 MB Paid) applies to the gzipped number`),d({...o,bundle:n})},P=f(async({cwd:e,logger:t,options:r})=>({code:(await $({allowSchemaDrift:r.allowSchemaDrift===!0,apiSpec:u(r.apiSpec),cwd:e,emitBindings:r.emitBindings,format:r.format,logger:t,outDir:r.outDir,strictAdvisories:r.strictAdvisories,target:r.target})).code}));export{P as execute,$ as runBuildCommand};
|
|
@@ -1,94 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
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{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-B9ReA3FV.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 F,{join as l,resolve as N}from"node:path";import{isInteractive as K,promptYesNo as z}from"@lunora/config";import{backupObjectKey as p,isBackupManifestEntry as O,normalizeBackupPrefix as H,BACKUP_KEY_PREFIX as J,backupManifestKey as G,isBackupManifestKey as W,backupObjectKeyOfManifest as A}from"@lunora/runtime";import{r as v,t as Y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as $}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as X}from"../packem_shared/command-DwC11Cwe.mjs";import{r as Q}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{randomUUID as B,createHash as V}from"node:crypto";import{existsSync as T,createReadStream as Z,createWriteStream as ee}from"node:fs";import{mkdir as re,rm as w,rename as U,readFile as D,writeFile as te,realpath as S,mkdtemp as E}from"node:fs/promises";import{LunoraError as h}from"@lunora/errors";import{i as I}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as _}from"node:os";import{Readable as ae}from"node:stream";import{pipeline as oe}from"node:stream/promises";import{b as ne,l as ie,M as x,u as ce,r as se}from"../packem_shared/import-Dqd1MOOv.mjs";import{runExportCommand as de}from"../packem_shared/runExportCommand-Dq-SpjAe.mjs";const y="manifest.json",j=async e=>{const r=V("sha256");let a=0;for await(const t of Z(e)){const o=t;a+=o.byteLength,r.update(o)}return{bytes:a,sha256:r.digest("hex")}},R=async e=>{const r=l(e,y);if(!T(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=>O(t))},ue=async(e,r)=>{const a=l(e,`${y}.${B()}.tmp`);try{await te(a,`${JSON.stringify(r,void 0,2)}
|
|
2
|
+
`,"utf8"),await U(a,l(e,y))}catch(t){throw await w(a,{force:!0}),t}},le=async(e,r)=>{const a=N(e),t=N(a,r.file),o=()=>{throw new h("INTERNAL",`backup: entry ${r.id} points outside ${a} (${r.file}) — refusing to read it`)};if(I(a,t)||o(),!!T(t))return I(await S(a),await S(t))||o(),t},fe=e=>{const r=a=>p("",a);return{commit:async(a,t)=>{await U(t,l(e,a))},label:e,list:async()=>R(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)?t:void 0:await le(e,a))},record:async a=>{const t=await R(e);t.push(a),await ue(e,t)},stage:async a=>{await re(e,{recursive:!0});const t=l(e,`${r(a)}.${B()}.partial`);return{path:t,release:()=>w(t,{force:!0})}}}},ge="/_lunora/admin/storage/object",me="/_lunora/admin/storage",P=8,he=(e,r=F)=>{const a=r.basename(e);return a===""||a==="."||a===".."?"snapshot.ndjson":a},we=e=>{const{context:r,logger:a}=e,t=H(e.prefix??J),o=`bucket ${r.bucket??"(default)"} under ${t}`,i=ne(r),d=c=>`${r.baseUrl}${ge}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const n=await r.fetchImpl(d(c),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!n.ok){const u=await n.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not read ${c} (HTTP ${String(n.status)}): ${u}`)}return n.text()},M=async c=>{try{const n=JSON.parse(await f(c));if(O(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,u)=>{if(u.bytes>x)throw new h("INTERNAL",`backup: the snapshot is ${String(u.bytes)} bytes, above the ${String(x)}-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 ce(r,c,s,{contentType:"application/x-ndjson",id:c,sha256:u.sha256,size:u.bytes},a)},label:o,list:async()=>{const n=(await ie(r,t)).map(s=>s.key).filter(s=>W(s)),u=[];for(let s=0;s<n.length;s+=P){const g=await Promise.all(n.slice(s,s+P).map(async m=>M(m)));u.push(...g.filter(m=>m!==void 0))}return u.toSorted((s,g)=>s.id.localeCompare(g.id))},locate:c=>p(t,c),materialize:async(c,n)=>{const u=c?.file??n,s=await r.fetchImpl(d(u),{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 ${u} (HTTP ${String(s.status)}): ${k}`)}const g=await E(l(_(),"lunora-backup-")),m=l(g,he(u));try{await oe(ae.from(s.body),ee(m))}catch(k){throw await w(g,{force:!0,recursive:!0}),k}return{path:m,release:async()=>w(g,{force:!0,recursive:!0})}},record:async c=>{const n=G(c.file),u=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(!u.ok){const s=await u.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(u.status)}): ${s}`)}},stage:async c=>{const n=await E(l(_(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},be=".lunora-backups",q="/_lunora/admin/backup/retention",ke="/_lunora/admin/backup/prune",pe="/_lunora/admin/pitr",ye="__lunora_admin__:getPitrBookmark",ve="__lunora_admin__:pitrRestore",$e=async(e,r)=>{const a=(e.now??(()=>new Date))().toISOString(),t=await r.stage(a);try{const o=await de({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),d=await j(t.path);await r.commit(i,t.path,d);const f={bytes:d.bytes,createdAt:a,file:i,id:a,rows:o.rows,sha256:d.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${d.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)})`)})}},Te=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`)},Ne=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}},Se=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(d=>d.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 Te(i.path,o,e.logger);if(f!==void 0)return f}return{code:(await se({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(d=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${d instanceof Error?d.message:String(d)})`)})}},Ee=e=>{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}const r=$(e.url,e.logger,e.cwd);if(r===void 0)return;if(e.restore===!0&&Y({prod:e.prod,url:r})&&e.yes!==!0){e.logger.error(`pitr --restore restores data in place at ${r}, which is not local. Re-run with --yes to confirm.`);return}const{token:a}=v({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");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:`${r}${pe}`,token:a}},Ie=(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},_e=async e=>{const r=Ee(e);if(r===void 0)return{code:1};const a=e.restore===!0,t=a?ve:ye,o=Ie(e,a),i=a?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const d=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(d,e.logger),{code:d.ok?0:1}},xe=(e,r)=>{if(e.bucket===void 0){if(e.prefix!==void 0){e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory.");return}return fe(l(r,e.dir??be))}if(e.dir!==void 0){e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one.");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=$(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=v({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 we({context:{baseUrl:a,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:t},logger:e.logger,prefix:e.prefix})},L=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=$(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=v({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}},C=(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(` ${A(a)}`)},Re=async e=>{const r=L(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${q}`,{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}):(C(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})},Pe=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const a of r.deleted)e.logger.info(` ${A(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`)},Oe=async e=>{const r=L(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${q}`,{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(C(e,t),e.yes!==!0){const d=e.confirm??(K()?z:void 0);if(d===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 d(`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}${ke}`,{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 Pe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:t}},Ae=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await _e(e);if(e.subcommand==="retention")return await Re(e);if(e.subcommand==="prune")return await Oe(e);const a=xe(e,r);return a===void 0?{code:1}:e.subcommand==="create"?await $e(e,a):e.subcommand==="list"?await Ne(e,a):await Se(e,a)}catch(a){return e.logger.error(a instanceof Error?a.message:String(a)),{code:1}}},Be=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ze=X(({argument:e,cwd:r,logger:a,options:t})=>{const o=e[0];return Be(o)?Ae({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:Q({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{Ze as execute,Ae 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,2 @@
|
|
|
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 _}from"@lunora/runtime";const S=["trace","debug","log","info","warn","error","fatal"],T=new Set(S),m=/^\d+$/,d=(e,t)=>{if(e===void 0)return;const n=e.trim();if(m.test(n))return Number(n);const r=Date.parse(n);if(Number.isNaN(r))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return r},E=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),C=e=>{const t=e.trim();if(m.test(t))return{ts:Number(t)};let n;try{n=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 n!="object"||n===null||typeof n.ts!="number"||!Number.isFinite(n.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}=n,s=n.seen,a=Array.isArray(s)?s.filter(i=>typeof i=="string"):void 0;return a!==void 0&&a.length>0?{seen:a,ts:r}:{ts:r}},u=(e,t)=>{if(e!==void 0){if(!T.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={},n=d(e.since,"--since");n!==void 0&&(t.sinceTs=n);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 a=u(e.minLevel,"--min-level");if(a!==void 0&&(t.minLevel=a),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},R=e=>{const t=new Date(e.ts).toISOString(),n=e.level.toUpperCase().padEnd(5);return`${t} ${n} ${e.functionPath} ${e.message}`},$=async e=>{const t=e.environment??process.env,n=t.R2_SQL_ACCOUNT_ID,r=t.R2_SQL_TOKEN,s=t.R2_SQL_BUCKET,a=[];if((n===void 0||n.length===0)&&a.push("R2_SQL_ACCOUNT_ID"),(r===void 0||r.length===0)&&a.push("R2_SQL_TOKEN"),(s===void 0||s.length===0)&&a.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&a.push("--table"),a.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${a.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:n,apiToken:r,bucket:s,fetch:e.fetch}),c=await _(l,{namespace:e.namespace,table:e.table}).query(i);for(const o of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(o):R(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 ${E(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},x=new Set(["json","pretty"]),N=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 n=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:n,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),a=h(y(t),s.tool,s.args),i={args:a.args,command:a.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=b(({argument:e,cwd:t,logger:n,options:r})=>r.durable===!0?$({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:n,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:n,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]}));export{k as execute,N as runLogsCommand};
|
|
@@ -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{addArgsFor as Y,detectPackageManager as q,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}},Be=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{Be as execute,we as resolveServerImport,Te as runIntrospectCommand};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import{V as I}from"../packem_shared/cli-DIb5Ay4K.mjs";import{d as R}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as G,renameSync as H,unlinkSync as K}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as q}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as X}from"@visulima/path";import{stringify as Z}from"smol-toml";import{parse as Q,modify as Y,applyEdits as ee}from"jsonc-parser";import{detectPackageManager as re,execArgsFor as te,readLiveDevServerState as b,DEV_STATE_DIR as ne}from"@lunora/config";import{resolveAdminToken as oe}from"@lunora/config/studio-host";import{connectLocalStdio as ae}from"@lunora/mcp";import{resolve as h}from"node:path";import{i as le}from"../packem_shared/path-containment-CgxYZggb.mjs";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),y=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ce=e=>e.transport==="http"?{httpUrl:e.url}:f(e),se=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ie=e=>({args:["-y","mcp-remote",e],command:"npx"}),de=e=>e.transport==="http"?ie(e.url):f(e),ue=e=>e.transport==="http"?{url:e.url}:f(e),fe=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},me=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},pe=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ge=(e,r)=>Z({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),g=[{buildEntry:y,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:y,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:y,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ce,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:de,paths:pe,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:se,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:fe,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:me,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ue,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ge}],x=g.map(e=>e.id),ve=e=>g.find(r=>r.id===e.toLowerCase()),_=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&G(a,n),H(a,t)}catch(o){try{K(a)}catch{}throw o}},he={formattingOptions:{insertSpaces:!0,tabSize:4}},S=e=>{const r=[],t=Q(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),k=(e,r,t)=>{if(!p(e))return;const n=e[r];return p(n)?n[t]:void 0},M=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=S(r);return t.length>0||!p(n)?"invalid":k(n,e.key,e.name)===void 0?"absent":"present"},ye=e=>M(e)==="present",L=(e,r,t,n,a)=>{try{const o=Y(e,[t,n],a,he);o.length>0&&_(r,ee(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},be=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),_(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
|
|
2
|
+
`),{action:"created",path:o};const{errors:c,value:i}=S(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!p(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const m=i[n];if(m!==void 0&&!p(m))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(k(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const $=L(l,o,n,a,r);return $===void 0?{action:"updated",path:o}:{action:"invalid",error:$,path:o}},we=e=>{const{key:r,name:t,path:n}=e;if(!u(n))return{action:"absent",path:n};let a;try{a=v(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=S(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(k(l,r,t)===void 0)return{action:"absent",path:n};const c=L(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},Se=["global","project"],d=(e,r)=>{const t=X(r,e);return t.length>0&&!t.startsWith("..")?t:e},ke=(e,r)=>{const t=e.paths(r);return Se.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},$e=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},Ee=e=>g.filter(r=>Object.values(r.paths(e)).some(t=>u(t))),N=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=ve(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${x.join(", ")}.`);return}a.push(l)}return a},je=e=>e.client.format==="json",Oe="https://lunora.sh/mcp",A="lunora-docs",U="lunora",Ce=e=>u(s(e,"lunora"))&&q(e)!==void 0,xe=e=>{const{args:r,command:t}=te(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},_e=e=>({transport:"http",url:e}),Me=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),D=(e,r,t)=>$e(e,Me(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Le=(e,r,t)=>{const n=D(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=d(a,t.cwd);return t.force!==!0&&ye({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
|
|
3
|
+
${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=be({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=d(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},Ne=(e,r,t)=>{const n=D(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${d(n,t.cwd)}
|
|
4
|
+
|
|
5
|
+
${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Ae=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:A,preferredScope:"global",spec:_e(e.docsUrl??Oe)}),e.docsOnly!==!0&&Ce(e.cwd)&&r.push({allowScopeFallback:!1,name:U,preferredScope:"project",spec:xe(re(e.cwd))}),r},Ue=e=>{const r=e.home??w(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of g){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":d(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${o("project").padEnd(30)} global: ${o("global")}`)}return{code:0,written:[]}},De=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",Pe=(e,r,t)=>{const n=[];for(const a of e)for(const o of r){const l=a.format==="json"?Le(a,o,t):Ne(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Te=e=>{const r=e.home??w(),t=e.platform??process.platform,n=N(e.clients,()=>Ee({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:1,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${x.join(", ")}.`),{code:1,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Ae(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${De(e)}`),{code:1,written:[]};const o=Pe(n,a,{...e,home:r,platform:t});return o.some(l=>l.action==="created"||l.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:o.some(l=>l.action==="invalid")?1:0,written:o}},P=100,T=1e3,E=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Fe=e=>({content:[{text:e,type:"text"}]}),Ie=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?P:Math.min(T,Math.max(1,Math.floor(r)))},j=(e,r)=>{if(r===void 0)return;const t=h(e,ne);return le(t,h(e,r))?h(e,r):void 0},Re=(e,r)=>{const t=v(e,"utf8").split(`
|
|
6
|
+
`);return t.at(-1)===""&&t.pop(),t.slice(-r).join(`
|
|
7
|
+
`)},Je=e=>[{definition:{description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const r=b(e);return E(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:j(e,r.logFile),mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(P)}, max ${String(T)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=b(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=j(e,t.logFile);if(n===void 0||!u(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const a=Ie(r.lines),o=Re(n,a);return Fe(o.length===0?"(the dev server log is empty)":o)}}],We=new Set(["127.0.0.1","::1","localhost"]),F=e=>{try{const{hostname:r}=new URL(e);return We.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},O=e=>{const r=e.url??b(e.cwd)?.url;if(r===void 0||r.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:r};if(!F(r))return{url:r};const t=oe(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},Ve=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},ze=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
|
|
8
|
+
`;const t=!F(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${t})
|
|
9
|
+
`},Ge=async(e,r=ae)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>O(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Je(e.cwd),version:e.version})}catch(o){const l=o instanceof Error?o.message:String(o);return t(`lunora mcp serve: failed to start — ${l}
|
|
10
|
+
`),{code:1,deployment:void 0}}const a=O(e);return t(ze(a)),await Ve(n),{code:0,deployment:a}},He=e=>{const r=[];return e.localOnly!==!0&&r.push(A),e.docsOnly!==!0&&r.push(U),r},Ke=(e,r,t,n)=>{const a=we({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${o}.`):a.action==="invalid"&&n.logger.error(`${e.label}: ${o} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:t}},qe=(e,r,t,n)=>{const a=M({key:e.key,name:r,path:t}),o=d(t,n.cwd);return a==="invalid"?(n.logger.error(`${e.label}: ${o} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):a==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${o}.`),{action:"removed",path:t})},Be=(e,r,t)=>e.flatMap(n=>ke(n,r)).filter(je).filter(n=>t===void 0||n.scope===t),Xe=e=>{const r=e.home??w(),t=e.platform??process.platform,n=N(e.clients,()=>g,e.logger,"uninstall");if(n===void 0)return{code:1,removed:[]};const a=He(e);if(a.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:1,removed:[]};const o=[],l={home:r,platform:t,projectRoot:e.cwd};for(const c of Be(n,l,e.scope))for(const i of a){const m=e.print===!0?qe(c.client,i,c.path,e):Ke(c.client,i,c.path,e);m.action!=="absent"&&o.push({...m,client:c.client.id,server:i})}return o.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:o.some(c=>c.action==="invalid")?1:0,removed:o}},C=e=>e.global===!0?"global":e.project===!0?"project":void 0,Ze=async(e,r)=>{const{code:t}=await Ge({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:I,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},ur=R(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Ze(r,n);if(a==="uninstall"){const l=C(n),{code:c}=Xe({clients:o,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l}});return{code:c}}if(a==="install"){if(n.list===!0)return Ue({cwd:r,logger:t});const l=C(n),{code:c}=Te({clients:o,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:1}});export{ur as execute};
|