@lunora/cli 1.0.0-alpha.42 → 1.0.0-alpha.420
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 +3 -1
- package/dist/bin.mjs +2 -10
- package/dist/index.d.mts +1069 -374
- package/dist/index.d.ts +1069 -374
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/dispatch.mjs +1 -0
- package/dist/packem_chunks/handler.mjs +23 -158
- package/dist/packem_chunks/handler10.mjs +1 -16
- package/dist/packem_chunks/handler11.mjs +1 -22
- package/dist/packem_chunks/handler12.mjs +1 -192
- package/dist/packem_chunks/handler13.mjs +1 -131
- package/dist/packem_chunks/handler14.mjs +3 -65
- package/dist/packem_chunks/handler15.mjs +1 -58
- package/dist/packem_chunks/handler16.mjs +1 -80
- package/dist/packem_chunks/handler17.mjs +1 -43
- package/dist/packem_chunks/handler18.mjs +7 -105
- package/dist/packem_chunks/handler19.mjs +2 -170
- package/dist/packem_chunks/handler2.mjs +1 -114
- package/dist/packem_chunks/handler20.mjs +1 -94
- 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 +2 -0
- package/dist/packem_chunks/handler27.mjs +9 -0
- package/dist/packem_chunks/handler28.mjs +1 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler4.mjs +1 -33
- package/dist/packem_chunks/handler5.mjs +3 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +1 -42
- package/dist/packem_chunks/handler8.mjs +1 -174
- package/dist/packem_chunks/handler9.mjs +2 -315
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDevCommand.mjs +2 -0
- package/dist/packem_chunks/runInitCommand.mjs +165 -1432
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/COMMANDS-BCSDC-pv.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
- package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
- package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
- package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
- package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
- package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
- package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
- package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
- package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
- package/dist/packem_shared/cli-BbgDNGew.mjs +2 -0
- package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
- package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-CB4JM-Jl.mjs +1 -0
- package/dist/packem_shared/commands-DvSfLvyt.mjs +13 -0
- package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
- package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
- package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
- package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
- package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
- package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
- package/dist/packem_shared/index-oHZBGBwB.mjs +1 -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/mcp-config-file-CcDTeXIq.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DWe_tkTR.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/plan-DFY3CqHD.mjs +5 -0
- package/dist/packem_shared/planDevCommand-BDoJUgQ4.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
- package/dist/packem_shared/render-lunora-error-B6893vbU.mjs +2 -0
- package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
- package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
- package/dist/packem_shared/runAddCommand-BChdJQ5L.mjs +1 -0
- package/dist/packem_shared/runDeployCommand-D40F3PLQ.mjs +1 -0
- package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
- package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
- package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
- package/dist/packem_shared/secret-key-8DPOH98z.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-DNzYhXR-.mjs +1 -0
- package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
- package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-CTQPpalP.mjs +1 -0
- package/package.json +39 -19
- package/skills/README.md +36 -17
- package/skills/lunora/SKILL.md +158 -65
- package/skills/lunora-cloudflare-audit/SKILL.md +163 -0
- package/skills/lunora-create-package/SKILL.md +97 -84
- package/skills/lunora-deploy/SKILL.md +175 -105
- package/skills/lunora-functions/SKILL.md +363 -56
- package/skills/lunora-migration-helper/SKILL.md +162 -137
- package/skills/lunora-performance-audit/SKILL.md +137 -95
- package/skills/lunora-quickstart/SKILL.md +136 -136
- package/skills/lunora-realtime/SKILL.md +217 -97
- package/skills/lunora-setup-auth/SKILL.md +162 -102
- package/skills/lunora-setup-hyperdrive/SKILL.md +130 -109
- package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
- package/skills/lunora-setup-mail/SKILL.md +85 -113
- package/skills/lunora-setup-scheduler/SKILL.md +132 -96
- package/skills/lunora-setup-storage/SKILL.md +189 -95
- package/dist/packem_chunks/planDevCommand.mjs +0 -541
- package/dist/packem_chunks/runDeployCommand.mjs +0 -594
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
- package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
- 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/codegen-error-DJG-ghs_.mjs +0 -31
- package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
- package/dist/packem_shared/commands-B-gR09Z_.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/prompt-cancelled-APzX1Im-.mjs +0 -9
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-bnY6-HKb.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-BIsph-Vk.mjs +0 -84
- package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
- package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
|
@@ -1,315 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
import { DEV_VARS_FILE, DEV_VARS_KEY_PATTERN, generateSecretValue, DEV_VARS_EXAMPLE_FILE, parseDevVariableEntries, isPlaceholderValue, packageNamesFromBindings, inferLunoraBindings, requiredSecrets, isMintableSecretKey } from '@lunora/config';
|
|
4
|
-
import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
|
|
5
|
-
import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
|
|
6
|
-
import { l as listRemoteSecrets } from '../packem_shared/wrangler-secrets-P2_ZUR-k.mjs';
|
|
7
|
-
|
|
8
|
-
const NEWLINE_PRESENT = /[\r\n]/u;
|
|
9
|
-
const UNREPRESENTABLE_PRESENT = /["\\]/u;
|
|
10
|
-
const parseDevVariables = (content) => {
|
|
11
|
-
const map = /* @__PURE__ */ new Map();
|
|
12
|
-
for (const entry of parseDevVariableEntries(content)) {
|
|
13
|
-
map.set(entry.key, entry);
|
|
14
|
-
}
|
|
15
|
-
return map;
|
|
16
|
-
};
|
|
17
|
-
const serializeDevVariables = (map) => {
|
|
18
|
-
const lines = [];
|
|
19
|
-
for (const entry of map.values()) {
|
|
20
|
-
lines.push(`${entry.key}="${entry.value}"`);
|
|
21
|
-
}
|
|
22
|
-
return `${lines.join("\n")}
|
|
23
|
-
`;
|
|
24
|
-
};
|
|
25
|
-
const redact = (value) => {
|
|
26
|
-
if (value.length <= 4) {
|
|
27
|
-
return "****";
|
|
28
|
-
}
|
|
29
|
-
return `${value.slice(0, 4)}${"*".repeat(Math.min(8, value.length - 4))}`;
|
|
30
|
-
};
|
|
31
|
-
const loadDevVariables = (devVariablesPath) => {
|
|
32
|
-
if (!existsSync(devVariablesPath)) {
|
|
33
|
-
return /* @__PURE__ */ new Map();
|
|
34
|
-
}
|
|
35
|
-
return parseDevVariables(readFileSync(devVariablesPath, "utf8"));
|
|
36
|
-
};
|
|
37
|
-
const runEnvList = (context) => {
|
|
38
|
-
const map = loadDevVariables(context.devVariablesPath);
|
|
39
|
-
if (map.size === 0) {
|
|
40
|
-
context.logger.info(`${DEV_VARS_FILE}: (empty)`);
|
|
41
|
-
return { code: 0, descriptors: [] };
|
|
42
|
-
}
|
|
43
|
-
for (const entry of map.values()) {
|
|
44
|
-
context.logger.info(`${entry.key}=${redact(entry.value)}`);
|
|
45
|
-
}
|
|
46
|
-
return { code: 0, descriptors: [] };
|
|
47
|
-
};
|
|
48
|
-
const runEnvGet = (context) => {
|
|
49
|
-
const { devVariablesPath, logger, options } = context;
|
|
50
|
-
if (!options.key) {
|
|
51
|
-
logger.error("env get requires a key. Usage: lunora env get <KEY>");
|
|
52
|
-
return { code: 1, descriptors: [] };
|
|
53
|
-
}
|
|
54
|
-
const entry = loadDevVariables(devVariablesPath).get(options.key);
|
|
55
|
-
if (!entry) {
|
|
56
|
-
logger.error(`env: ${options.key} is not set in ${DEV_VARS_FILE}`);
|
|
57
|
-
return { code: 1, descriptors: [] };
|
|
58
|
-
}
|
|
59
|
-
process.stdout.write(`${entry.value}
|
|
60
|
-
`);
|
|
61
|
-
return { code: 0, descriptors: [] };
|
|
62
|
-
};
|
|
63
|
-
const runEnvSet = (context) => {
|
|
64
|
-
const { devVariablesPath, logger, options } = context;
|
|
65
|
-
if (!options.key) {
|
|
66
|
-
logger.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>");
|
|
67
|
-
return { code: 1, descriptors: [] };
|
|
68
|
-
}
|
|
69
|
-
if (!DEV_VARS_KEY_PATTERN.test(options.key)) {
|
|
70
|
-
logger.error(`env: invalid key "${options.key}" — must match [A-Za-z_][A-Za-z0-9_]*`);
|
|
71
|
-
return { code: 1, descriptors: [] };
|
|
72
|
-
}
|
|
73
|
-
if (options.value === void 0) {
|
|
74
|
-
logger.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>");
|
|
75
|
-
return { code: 1, descriptors: [] };
|
|
76
|
-
}
|
|
77
|
-
if (NEWLINE_PRESENT.test(options.value)) {
|
|
78
|
-
logger.error(`env: value for "${options.key}" contains a newline, which .dev.vars cannot represent`);
|
|
79
|
-
return { code: 1, descriptors: [] };
|
|
80
|
-
}
|
|
81
|
-
if (UNREPRESENTABLE_PRESENT.test(options.value)) {
|
|
82
|
-
logger.error(`env: value for "${options.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`);
|
|
83
|
-
return { code: 1, descriptors: [] };
|
|
84
|
-
}
|
|
85
|
-
const map = loadDevVariables(devVariablesPath);
|
|
86
|
-
map.set(options.key, { key: options.key, value: options.value });
|
|
87
|
-
writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
|
|
88
|
-
logger.success(`env: set ${options.key} (${redact(options.value)}) in ${DEV_VARS_FILE}`);
|
|
89
|
-
return { code: 0, descriptors: [] };
|
|
90
|
-
};
|
|
91
|
-
const runEnvUnset = (context) => {
|
|
92
|
-
const { devVariablesPath, logger, options } = context;
|
|
93
|
-
if (!options.key) {
|
|
94
|
-
logger.error("env unset requires a key. Usage: lunora env unset <KEY>");
|
|
95
|
-
return { code: 1, descriptors: [] };
|
|
96
|
-
}
|
|
97
|
-
const map = loadDevVariables(devVariablesPath);
|
|
98
|
-
if (!map.delete(options.key)) {
|
|
99
|
-
logger.warn(`env: ${options.key} was not set in ${DEV_VARS_FILE}`);
|
|
100
|
-
return { code: 0, descriptors: [] };
|
|
101
|
-
}
|
|
102
|
-
writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
|
|
103
|
-
logger.success(`env: unset ${options.key} in ${DEV_VARS_FILE}`);
|
|
104
|
-
return { code: 0, descriptors: [] };
|
|
105
|
-
};
|
|
106
|
-
const runEnvPush = async (context) => {
|
|
107
|
-
const { devVariablesPath, logger, options } = context;
|
|
108
|
-
if (!options.yes) {
|
|
109
|
-
logger.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm.");
|
|
110
|
-
return { code: 1, descriptors: [] };
|
|
111
|
-
}
|
|
112
|
-
const map = loadDevVariables(devVariablesPath);
|
|
113
|
-
if (map.size === 0) {
|
|
114
|
-
logger.warn(`${DEV_VARS_FILE}: nothing to push (empty)`);
|
|
115
|
-
return { code: 0, descriptors: [] };
|
|
116
|
-
}
|
|
117
|
-
const spawner = options.spawner ?? defaultSpawner;
|
|
118
|
-
const descriptors = [];
|
|
119
|
-
for (const entry of map.values()) {
|
|
120
|
-
const args = ["exec", "wrangler", "secret", "put", entry.key];
|
|
121
|
-
if (options.prod) {
|
|
122
|
-
args.push("--env", "production");
|
|
123
|
-
}
|
|
124
|
-
if (options.temporary) {
|
|
125
|
-
args.push("--temporary");
|
|
126
|
-
}
|
|
127
|
-
const descriptor = {
|
|
128
|
-
args,
|
|
129
|
-
command: "pnpm",
|
|
130
|
-
cwd: options.cwd ?? process.cwd(),
|
|
131
|
-
// `wrangler secret put <name>` reads the value from stdin. We
|
|
132
|
-
// pipe it through the spawner's `input` channel so the secret
|
|
133
|
-
// never lands on the command line, in env, or in shell history.
|
|
134
|
-
input: entry.value
|
|
135
|
-
};
|
|
136
|
-
descriptors.push(descriptor);
|
|
137
|
-
logger.info(`pushing ${entry.key} -> wrangler secret${options.prod ? " (production)" : ""}`);
|
|
138
|
-
const result = await spawner(descriptor);
|
|
139
|
-
if (result.code !== 0) {
|
|
140
|
-
logger.error(`env push: failed at ${entry.key} (exit ${String(result.code)})`);
|
|
141
|
-
return { code: result.code, descriptors };
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
logger.success(`env: pushed ${String(map.size)} secret(s)`);
|
|
145
|
-
return { code: 0, descriptors };
|
|
146
|
-
};
|
|
147
|
-
const fetchRemoteSecretNames = (context) => {
|
|
148
|
-
const lister = context.options.secretLister ?? listRemoteSecrets;
|
|
149
|
-
return lister({
|
|
150
|
-
cwd: context.cwd,
|
|
151
|
-
env: context.options.prod ? "production" : void 0,
|
|
152
|
-
temporary: context.options.temporary
|
|
153
|
-
});
|
|
154
|
-
};
|
|
155
|
-
const runEnvDiff = async (context) => {
|
|
156
|
-
const { devVariablesPath, logger } = context;
|
|
157
|
-
const remote = await fetchRemoteSecretNames(context);
|
|
158
|
-
if (!remote.ok) {
|
|
159
|
-
logger.error(`env diff: ${remote.error ?? "failed to list remote secrets"}`);
|
|
160
|
-
return { code: 1, descriptors: [] };
|
|
161
|
-
}
|
|
162
|
-
const localKeys = new Set(loadDevVariables(devVariablesPath).keys());
|
|
163
|
-
const remoteKeys = new Set(remote.names);
|
|
164
|
-
const localOnly = [...localKeys].filter((key) => !remoteKeys.has(key)).toSorted((a, b) => a.localeCompare(b));
|
|
165
|
-
const remoteOnly = remote.names.filter((name) => !localKeys.has(name));
|
|
166
|
-
const both = [...localKeys].filter((key) => remoteKeys.has(key)).toSorted((a, b) => a.localeCompare(b));
|
|
167
|
-
for (const key of localOnly) {
|
|
168
|
-
logger.info(`local only (run \`lunora env push\`): ${key}`);
|
|
169
|
-
}
|
|
170
|
-
for (const key of remoteOnly) {
|
|
171
|
-
logger.info(`remote only (in Cloudflare, not ${DEV_VARS_FILE}): ${key}`);
|
|
172
|
-
}
|
|
173
|
-
logger.info(`in both: ${String(both.length)} secret(s)`);
|
|
174
|
-
if (localOnly.length === 0 && remoteOnly.length === 0) {
|
|
175
|
-
logger.success("env diff: local and remote secret names match");
|
|
176
|
-
}
|
|
177
|
-
return { code: 0, descriptors: [] };
|
|
178
|
-
};
|
|
179
|
-
const runEnvDoctor = (context) => {
|
|
180
|
-
const { cwd, devVariablesPath, logger } = context;
|
|
181
|
-
const examplePath = join(cwd, DEV_VARS_EXAMPLE_FILE);
|
|
182
|
-
if (!existsSync(examplePath)) {
|
|
183
|
-
logger.info(`env doctor: no ${DEV_VARS_EXAMPLE_FILE} to check against — nothing to validate.`);
|
|
184
|
-
return { code: 0, descriptors: [] };
|
|
185
|
-
}
|
|
186
|
-
const exampleKeys = parseDevVariableEntries(readFileSync(examplePath, "utf8")).map((entry) => entry.key);
|
|
187
|
-
const current = loadDevVariables(devVariablesPath);
|
|
188
|
-
if (!existsSync(devVariablesPath)) {
|
|
189
|
-
logger.error(`env doctor: ${DEV_VARS_FILE} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`);
|
|
190
|
-
logger.info(`expected (from ${DEV_VARS_EXAMPLE_FILE}): ${exampleKeys.join(", ")}`);
|
|
191
|
-
return { code: 1, descriptors: [] };
|
|
192
|
-
}
|
|
193
|
-
const missing = exampleKeys.filter((key) => !current.has(key));
|
|
194
|
-
const placeholders = [...current.values()].filter((entry) => isPlaceholderValue(entry.value)).map((entry) => entry.key);
|
|
195
|
-
const exampleKeySet = new Set(exampleKeys);
|
|
196
|
-
const extra = [...current.keys()].filter((key) => !exampleKeySet.has(key));
|
|
197
|
-
for (const key of missing) {
|
|
198
|
-
logger.error(`missing: ${key} is in ${DEV_VARS_EXAMPLE_FILE} but not ${DEV_VARS_FILE}`);
|
|
199
|
-
}
|
|
200
|
-
for (const key of placeholders) {
|
|
201
|
-
logger.error(`unset: ${key} still has a placeholder value`);
|
|
202
|
-
}
|
|
203
|
-
for (const key of extra) {
|
|
204
|
-
logger.info(`extra: ${key} is set locally but not listed in ${DEV_VARS_EXAMPLE_FILE}`);
|
|
205
|
-
}
|
|
206
|
-
if (missing.length === 0 && placeholders.length === 0) {
|
|
207
|
-
logger.success(`env doctor: ${DEV_VARS_FILE} looks good (${String(current.size)} var(s)).`);
|
|
208
|
-
return { code: 0, descriptors: [] };
|
|
209
|
-
}
|
|
210
|
-
return { code: 1, descriptors: [] };
|
|
211
|
-
};
|
|
212
|
-
const resolveMintableKeys = async (context) => {
|
|
213
|
-
let packages = [];
|
|
214
|
-
try {
|
|
215
|
-
packages = packageNamesFromBindings(await inferLunoraBindings({ projectRoot: context.cwd }));
|
|
216
|
-
} catch {
|
|
217
|
-
}
|
|
218
|
-
const fromPackages = requiredSecrets(packages).map((entry) => entry.key).filter((key) => isMintableSecretKey(key));
|
|
219
|
-
const fromLocal = [...loadDevVariables(context.devVariablesPath).keys()].filter((key) => isMintableSecretKey(key));
|
|
220
|
-
return [.../* @__PURE__ */ new Set([...fromPackages, ...fromLocal])];
|
|
221
|
-
};
|
|
222
|
-
const runEnvGenerate = async (context) => {
|
|
223
|
-
const { devVariablesPath, logger, options } = context;
|
|
224
|
-
let keys;
|
|
225
|
-
if (options.key === void 0) {
|
|
226
|
-
keys = await resolveMintableKeys(context);
|
|
227
|
-
if (keys.length === 0) {
|
|
228
|
-
logger.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>");
|
|
229
|
-
return { code: 0, descriptors: [] };
|
|
230
|
-
}
|
|
231
|
-
} else {
|
|
232
|
-
if (!DEV_VARS_KEY_PATTERN.test(options.key)) {
|
|
233
|
-
logger.error(`env: invalid key "${options.key}" — must match [A-Za-z_][A-Za-z0-9_]*`);
|
|
234
|
-
return { code: 1, descriptors: [] };
|
|
235
|
-
}
|
|
236
|
-
keys = [options.key];
|
|
237
|
-
}
|
|
238
|
-
const generated = keys.map((key) => {
|
|
239
|
-
return { key, value: generateSecretValue() };
|
|
240
|
-
});
|
|
241
|
-
if (options.set === true) {
|
|
242
|
-
const map = loadDevVariables(devVariablesPath);
|
|
243
|
-
for (const entry of generated) {
|
|
244
|
-
map.set(entry.key, entry);
|
|
245
|
-
}
|
|
246
|
-
writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
|
|
247
|
-
logger.success(`env: generated ${String(generated.length)} secret(s) into ${DEV_VARS_FILE}: ${generated.map((entry) => entry.key).join(", ")}`);
|
|
248
|
-
return { code: 0, descriptors: [] };
|
|
249
|
-
}
|
|
250
|
-
for (const entry of generated) {
|
|
251
|
-
process.stdout.write(`${entry.key}=${entry.value}
|
|
252
|
-
`);
|
|
253
|
-
}
|
|
254
|
-
return { code: 0, 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 "generate": {
|
|
272
|
-
return runEnvGenerate(context);
|
|
273
|
-
}
|
|
274
|
-
case "get": {
|
|
275
|
-
return runEnvGet(context);
|
|
276
|
-
}
|
|
277
|
-
case "list": {
|
|
278
|
-
return runEnvList(context);
|
|
279
|
-
}
|
|
280
|
-
case "push": {
|
|
281
|
-
return runEnvPush(context);
|
|
282
|
-
}
|
|
283
|
-
case "set": {
|
|
284
|
-
return runEnvSet(context);
|
|
285
|
-
}
|
|
286
|
-
case "unset": {
|
|
287
|
-
return runEnvUnset(context);
|
|
288
|
-
}
|
|
289
|
-
default: {
|
|
290
|
-
options.logger.error(`env: unknown subcommand "${options.subcommand}"`);
|
|
291
|
-
return { code: 1, descriptors: [] };
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
};
|
|
295
|
-
const isEnvSubcommand = (value) => value === "list" || value === "get" || value === "set" || value === "unset" || value === "push" || value === "diff" || value === "doctor" || value === "generate";
|
|
296
|
-
const execute = defineHandler(({ argument, cwd, logger, options }) => {
|
|
297
|
-
const sub = argument[0];
|
|
298
|
-
if (!isEnvSubcommand(sub)) {
|
|
299
|
-
logger.error(`env: unknown subcommand "${sub ?? ""}" — expected list | get | set | unset | push | diff | doctor | generate`);
|
|
300
|
-
return { code: 1 };
|
|
301
|
-
}
|
|
302
|
-
return runEnvCommand({
|
|
303
|
-
cwd,
|
|
304
|
-
key: argument[1],
|
|
305
|
-
logger,
|
|
306
|
-
prod: options.prod === true,
|
|
307
|
-
set: options.set === true,
|
|
308
|
-
subcommand: sub,
|
|
309
|
-
temporary: options.temporary === true,
|
|
310
|
-
value: argument[2],
|
|
311
|
-
yes: options.yes === true
|
|
312
|
-
});
|
|
313
|
-
});
|
|
314
|
-
|
|
315
|
-
export { execute, runEnvCommand };
|
|
1
|
+
import{r as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as M,a as y}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as x}from"../packem_shared/command-CB4JM-Jl.mjs";import{EXIT_CODE as u,exitCodeForStatus as T}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as I}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const O="__lunora_admin__:getFunctionStats",_=10,f=(r,o)=>({calls:r.calls,conflicts:r.conflicts??0,errors:r.errors,lastErrorMessage:r.lastErrorMessage,maxDurationMs:r.maxDurationMs,meanDurationMs:r.calls===0?0:r.totalDurationMs/r.calls,path:r.path,rate:o}),k=(r,o)=>{const t=r.filter(e=>(e.conflicts??0)>0).map(e=>f(e,e.calls===0?0:(e.conflicts??0)/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.conflicts-e.conflicts).slice(0,o),n=r.filter(e=>e.errors>0).map(e=>f(e,e.calls===0?0:e.errors/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.errors-e.errors).slice(0,o),a=r.map(e=>f(e,0)).toSorted((e,s)=>s.maxDurationMs-e.maxDurationMs).slice(0,o);return{errorHotspots:n,latencyOutliers:a,totalFunctions:r.length,writeContention:t}},p=r=>`${(r*100).toFixed(1)}%`,$=r=>r<1e3?`${Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,m=(r,o,t,n)=>[r,...o.length===0?[` ${t}`]:o.map(a=>` ${n(a)}`)],E=r=>{const o=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${r.totalFunctions.toString()} function${r.totalFunctions===1?"":"s"}`,"",...m("Write-conflict hot-spots (OCC contention — candidates for sharding):",r.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...m("Error hot-spots:",r.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${o(t)}`),"",...m("Latency outliers (slowest single call):",r.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${$(t.maxDurationMs)}, mean ${$(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
|
|
2
|
+
`)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),F=r=>r===void 0||!Number.isFinite(r)||r<=0?_:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",u.USAGE);const t=M(r.url,o,r.cwd);if(t===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const a=`${t}/_lunora/rpc`,e=y,s={args:{},functionPath:O};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let d;try{d=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=d.result??d,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=k(h,F(r.limit));return r.format!=="json"&&o.info(E(g)),{code:0,report:g}},L=x(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:I({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{k as buildInsightsReport,L as execute,E as formatInsightsReport,A as runInsightsCommand};
|
|
@@ -1,52 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const CRON_TRIGGER_LIMIT = 3;
|
|
7
|
-
const runCodegenCommand = (options) => {
|
|
8
|
-
const projectRoot = options.cwd ?? process.cwd();
|
|
9
|
-
const json = isJsonFormat(options.format);
|
|
10
|
-
const logger = loggerForFormat(options.format, options.logger);
|
|
11
|
-
const formatError = validateOutputFormat("codegen", options.format);
|
|
12
|
-
if (formatError !== void 0) {
|
|
13
|
-
options.logger.error(formatError);
|
|
14
|
-
return { advisories: [], cronTriggers: [], error: formatError, outputDirectory: "" };
|
|
15
|
-
}
|
|
16
|
-
const result = runCodegen({ apiSpec: options.apiSpec, projectRoot });
|
|
17
|
-
const commandResult = {
|
|
18
|
-
advisories: result.advisories.map((advisory) => {
|
|
19
|
-
return {
|
|
20
|
-
detail: advisory.detail,
|
|
21
|
-
level: advisory.level,
|
|
22
|
-
name: advisory.name,
|
|
23
|
-
remediation: advisory.remediation
|
|
24
|
-
};
|
|
25
|
-
}),
|
|
26
|
-
cronTriggers: result.cronTriggers,
|
|
27
|
-
outputDirectory: result.outputDirectory
|
|
28
|
-
};
|
|
29
|
-
logger.success(`codegen wrote dataModel.ts, api.ts, server.ts to ${result.outputDirectory}`);
|
|
30
|
-
if (result.advisories.length > 0) {
|
|
31
|
-
const count = result.advisories.length;
|
|
32
|
-
const lines = result.advisories.map((advisory) => ` [${advisory.level}] ${advisory.name} — ${advisory.detail}
|
|
33
|
-
↳ ${advisory.remediation}`);
|
|
34
|
-
logger.warn(`${count.toString()} schema ${count === 1 ? "advisory" : "advisories"}:
|
|
35
|
-
${lines.join("\n")}`);
|
|
36
|
-
}
|
|
37
|
-
if (result.cronTriggers.length > CRON_TRIGGER_LIMIT) {
|
|
38
|
-
logger.warn(
|
|
39
|
-
`${result.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${CRON_TRIGGER_LIMIT.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`
|
|
40
|
-
);
|
|
41
|
-
}
|
|
42
|
-
if (json) {
|
|
43
|
-
printJson(commandResult);
|
|
44
|
-
}
|
|
45
|
-
return commandResult;
|
|
46
|
-
};
|
|
47
|
-
const execute = defineHandler(({ cwd, logger, options }) => {
|
|
48
|
-
const result = runCodegenCommand({ apiSpec: parseApiSpec(options.apiSpec), cwd, format: options.format, logger });
|
|
49
|
-
return { code: result.error === void 0 ? 0 : 1 };
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
export { execute, runCodegenCommand };
|
|
1
|
+
import{runCodegen as h}from"@lunora/codegen";import{resolveLazyFunctions as m,applyLintIgnores as w,detectLintTools as y,inferLunoraBindings as $,resolveSchemaDirectory as A}from"@lunora/config";import{warnCloudflareCliConfigOnce as T,wranglerCodegenInputs as C,collectExportGaps as D}from"@lunora/config/cloudflare";import{r as S,a as x,e as k}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as E}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as b}from"../packem_shared/command-CB4JM-Jl.mjs";import{r as I}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as O}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";const u=3,R=r=>{const s=r.cwd??process.cwd(),{logger:i}=r,e=S(r),o=I(s,r.target);if(o.target===void 0)return r.logger.error(o.error??"unknown deploy target"),{advisories:[],code:L.USAGE,cronTriggers:[],error:o.error??"unknown deploy target",failedAdvisories:0,outputDirectory:""};const{target:a}=o,t=h({apiSpec:r.apiSpec,lazyFunctions:m(r.lazyFunctions),projectRoot:s,target:a,...C(s)}),d={advisories:t.advisories.map(n=>({detail:n.detail,level:n.level,name:n.name,remediation:n.remediation})),cronTriggers:t.cronTriggers,failedAdvisories:0,outputDirectory:t.outputDirectory};if(i.success(`codegen wrote ${t.writtenFiles.join(", ")} to ${t.outputDirectory}`),t.advisories.length>0){const n=t.advisories.length,v=t.advisories.map(c=>` [${c.level}] ${c.name} — ${c.detail}
|
|
2
|
+
↳ ${c.remediation}`);i.warn(`${n.toString()} schema ${n===1?"advisory":"advisories"}:
|
|
3
|
+
${v.join(`
|
|
4
|
+
`)}`)}const g=x(t.platformDiagnostics,i);g.errors.length>0&&(d.error=g.errors.join("; "));const{errorAdvisories:l,names:p,shouldBlock:f}=k(d.advisories,e);return f&&i.error(`${l.length.toString()} ERROR-level ${l.length===1?"advisory":"advisories"} (${p.join(", ")}). Codegen wrote its output; this exit code is the gate. Pass --no-strict-advisories to downgrade it to a warning.`),t.cronTriggers.length>u&&i.warn(`${t.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${u.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`),{...d,failedAdvisories:e?l.length:0}},F=async(r,s)=>{let i;try{i=D(await $({projectRoot:r,schemaDir:A(r)}))}catch(e){s.warn(`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}. Run \`lunora doctor\` to check explicitly.`);return}for(const e of i)s.warn(`${e.kind} "${e.exportName}" is declared but ${e.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/${e.module}"\` so wrangler can provision its binding. Until then it deploys with nothing to run.`)},G=(r,s)=>{try{O(w(r,y(r)),s)}catch{}},W=b(async({cwd:r,format:s,logger:i,options:e})=>{const o=R({apiSpec:E(e.apiSpec),cwd:r,format:s,lazyFunctions:m(e.lazyFunctions),logger:i,strictAdvisories:e.strictAdvisories,target:e.target});if(o.outputDirectory!==""){const a=i;G(r,a),await F(r,a),T(r,t=>{a.warn(t)})}return{code:o.code??(o.error===void 0&&o.failedAdvisories===0?0:1),data:{advisories:o.advisories,cronTriggers:o.cronTriggers,failedAdvisories:o.failedAdvisories,outputDirectory:o.outputDirectory},error:o.error}});export{W as execute,R as runCodegenCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readServiceBindings as G,runCodegen as M}from"@lunora/codegen";import{runPostCodegenHook as X,resolveLazyFunctions as E,detectAgentRules as W,updateDevServerState as H,readDevServerState as Y,DEV_DAEMON_ENV as x,detectAiAgent as J,readProjectRemotePreference as K,readLiveDevServerState as V,createDiscoveryCache as Q,DEV_HANDOFF_ENV as _,clearDevServerState as Z,claimDevServerState as q,DEV_LOG_FILE_ENV as ee,inferLunoraBindings as re,resolveSchemaDirectory as te,secretSourcesFromBindings as ne,ensureDevVarsExample as oe,ensureDevVariables as ae,isInteractive as ie,DEV_VARS_FILE as T,DEV_VARS_EXAMPLE_FILE as se,fillDevSecrets as ce,DEV_BINDINGS_FILE as de,DEV_STATE_FILE as B,claimAgentRulesHint as le,AGENT_RULES_HINT as ue}from"@lunora/config";import{wranglerCodegenInputs as U,resolveRemoteEnabled as fe,startLocalHyperdrive as ve,describeWithheld as ge}from"@lunora/config/cloudflare";import{p as me}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{w as we}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as he,watch as A}from"node:fs";import{join as ye,dirname as Se}from"node:path";import{a as pe}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as Ee}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as be}from"../packem_shared/command-CB4JM-Jl.mjs";import{a as De}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as k}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{forceJsonLogging as _e}from"../packem_shared/createLogger-4TujevyB.mjs";import{createServer as ke,request as Re}from"node:http";import{connect as Te}from"node:net";import{pipeline as Ae}from"node:stream";import{loadStudioAssets as P,studioAssetsStamp as C,renderStudioHtml as Pe,resolveAdminToken as Ce,requestPathname as O,transportRejectionReason as $,SCHEMA_EDIT_ENDPOINT as Oe,POLICY_SCAFFOLD_ENDPOINT as $e,SEED_ENDPOINT as Le,sendStudioDocument as Fe,serveJsonHandler as Ne,isStandaloneModulePath as Ie,readStandaloneAsset as je,assetContentType as Me,handleSchemaEditRequest as We,handlePolicyScaffoldRequest as He,handleSeedRequest as xe,applyStudioAssetCache as Ve}from"@lunora/config/studio-host";import{c as Be}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as Ue}from"node:timers/promises";import{r as ze,d as Ge,P as Xe,a as Ye,b as R,c as Je,s as Ke,n as z,e as Qe,f as Ze,g as qe,h as er,i as L,w as rr,j as tr,k as nr,t as or,l as ar,m as ir,o as sr}from"../packem_shared/plan-DFY3CqHD.mjs";import{b as cr}from"./handler.mjs";const dr=100,lr=/(?:\.[cm]?[jt]sx?|(?:^|[/\\])tsconfig(?:\..+)?\.json)$/u,ur=300,F=/[/\\]/u,fr=(e,r,n)=>{const{apiSpec:t,lazyFunctions:o,logger:i,projectRoot:l,target:d}=e;try{const a=M({apiSpec:t,lazyFunctions:E(o),lunoraDirectory:r,projectRoot:l,target:d,...U(l)});i.success(`codegen: wrote ${r}/_generated (${n})`),Ee(a.platformDiagnostics,i)}catch(a){return i.error(pe(a,n)),!1}return!0},vr=e=>{const r=e.lunoraDirectory??"lunora",n=ye(e.projectRoot,r),t=e.debounceMs??dr;let o=!1,i=!1,l=!1,d,a=0,f=Promise.resolve(),S;const y=new Promise(v=>{S=v}),w=v=>{o||(d=v,!i&&(i=!0,f=(async()=>{try{for(;d!==void 0;){const g=d;if(d=void 0,!!fr(e,r,g)){l=!0;try{(await X({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(a=Date.now())}finally{l=!1}}}}catch(g){e.logger.error(`codegen watch: ${g instanceof Error?g.message:String(g)}`)}finally{i=!1,S()}})()))};w("startup");const c=v=>(e.logger.warn(`codegen watch unavailable (${v}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,d=void 0,f),ready:y,watchAvailable:!1});let s,u;if(!he(n))return c(`no such directory: ${n}`);const m=v=>{if(l||Date.now()-a<ur){s&&(clearTimeout(s),s=void 0);return}s&&clearTimeout(s),s=setTimeout(()=>{w(`change: ${v??"?"}`)},t)},h=[];try{u=A(n,{recursive:!0},(v,g)=>{typeof g=="string"&&g.split(F).includes("_generated")||m(g)});for(const v of G(e.projectRoot).services)if(v.rpcEntrypoint!==void 0){const g=A(Se(v.wranglerPath),{recursive:!0},(D,b)=>{typeof b=="string"&&lr.test(b)&&!b.split(F).includes("node_modules")&&m(b)});g.on("error",D=>{e.logger.warn(`codegen watch: stopped watching service "${v.name}" (${D.message})`),g.close()}),h.push(g)}}catch(v){u?.close();for(const g of h)g.close();return c(v instanceof Error?v.message:String(v))}const p=u;return{close:()=>{o=!0,d=void 0,s&&clearTimeout(s),p.close();for(const v of h)v.close();return f},ready:y,watchAvailable:!0}},N="/_lunora",I=3e4,j=(e,r,n)=>{const t=Re({headers:{...e.headers,host:n.host},hostname:n.hostname,method:e.method,path:e.url,port:n.port},o=>{r.writeHead(o.statusCode??502,o.headers),Ae(o,r,()=>{})});t.setTimeout(I,()=>{t.destroy(new Error(`no response within ${String(I)}ms`))}),t.on("error",o=>{if(r.headersSent){r.destroy();return}r.statusCode=o.message.startsWith("no response within")?504:502,r.end(`lunora dev: worker unreachable (${o.message})`)}),r.on("close",()=>{r.writableFinished||t.destroy()}),e.pipe(t)},gr=5e3,mr=(e,r,n,t)=>{const o=Te({host:t.hostname,port:Number(t.port)},()=>{o.setTimeout(0);const i=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[l,d]of Object.entries(e.headers))if(l!=="host")for(const a of Array.isArray(d)?d:[d])a!==void 0&&i.push(`${l}: ${a}`);i.push(`host: ${t.host}`,"",""),o.write(i.join(`\r
|
|
2
|
+
`)),n.length>0&&o.write(n),o.pipe(r),r.pipe(o)});o.setTimeout(gr,()=>o.destroy()),o.on("error",()=>r.destroy()),r.on("error",()=>o.destroy())},wr=async e=>{const r=e.host??"127.0.0.1",n=r==="127.0.0.1"||r==="localhost"||r==="::1",t=new URL(e.workerOrigin);let o=P(e.logger,import.meta.url),i=C(import.meta.url);const l=Pe({adminToken:n?Ce(e.cwd):void 0,basePath:"/",dataEditable:n,rulesInstalled:W(e.cwd).installed,runAsIdentity:n,schemaEditable:n,scriptSrc:"/studio.js",styleHref:"/styles.css"}),d=(c,s,u,m,h)=>{Ve(c,s,h,i)||(s.statusCode=200,s.setHeader("Content-Type",m),s.end(u))},a=(c,s,u)=>{c.statusCode=s,c.setHeader("Content-Type","text/plain"),c.end(u)},f=(c,s,u,m)=>{if(n){Ne(c,s,u,e.cwd,{apiSpec:e.apiSpec,lazyFunctions:E(e.lazyFunctions)});return}a(s,403,m)},S=(c,s,u)=>{const m=c==="/styles.css",h=Ie(c);if(!m&&!h)return!1;const p=C(import.meta.url);if(p!==i&&(o=P(e.logger,import.meta.url),i=p),o===void 0)return a(u,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(m)return d(s,u,o.styles,"text/css; charset=utf-8","styles.css"),!0;const v=c.slice(c.lastIndexOf("/")+1),g=je(v,import.meta.url);return g===void 0?(a(u,404,"Not found"),!0):(d(s,u,g,Me(v),v),!0)},y=Buffer.from(l),w=ke((c,s)=>{const u=O(c.url??"/");if(n){const h=$(c,e.logger);if(h!==void 0){a(s,403,h);return}}if(u.startsWith(N)){if(!n){a(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}j(c,s,t);return}if(u===Oe){f(c,s,We,"Lunora schema editing is only available on loopback hosts in dev.");return}if(u===$e){f(c,s,He,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(u===Le){f(c,s,xe,"Lunora data seeding is only available on loopback hosts in dev.");return}if(S(u,c,s))return;const m=c.headers["sec-fetch-mode"];if(n&&typeof m=="string"&&m!=="navigate"){j(c,s,t);return}Fe(s,y)});return w.on("upgrade",(c,s,u)=>{if(!n||$(c,e.logger)!==void 0){s.destroy();return}O(c.url??"").startsWith(N)?mr(c,s,u,t):s.destroy()}),await new Promise((c,s)=>{w.once("error",u=>{u.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:u})):s(u)}),w.listen(e.port,r,()=>{c()})}),{close:()=>new Promise(c=>{w.close(()=>{c()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},hr=async e=>{const{cwd:r,logger:n,origin:t,signal:o}=e,i=e.probe??Ge,l=ze(e.readyTimeoutMs),d=Date.now()+l,a=()=>o.aborted;for(;!a()&&Date.now()<d;){let f=!1;try{f=await i(t,o)}catch{}if(a()||Date.now()>=d)break;if(f)return H(r,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),Y(r)?.readyAt!==void 0;try{await Ue(Xe,void 0,{signal:o})}catch{}}return a()||n.warn(`server did not answer on ${t} within ${String(Math.round(l/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},yr=(e,r,n,t)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),n!==void 0&&e.info(` ➜ Studio: ${n}`),r.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),t!==void 0&&e.info(` ➜ Supervisor: ${t} (needs) · ${B} (status)`),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):r.remote.reason!==void 0&&e.warn(` ➜ Remote: requested but inactive (${r.remote.reason}) — running fully local`));for(const o of r.remote.withheld)e.warn(` ➜ ${ge(o)}`);e.info("")},Sr=(e,r)=>{W(r).installed||!le()||(e.info(` ⓘ ${ue}`),e.info(""))},pr=async(e,r,n)=>{try{const o=await re({cache:n,projectRoot:r,schemaDir:te(r)}),i=ne(o),l=(e.ensureExample??oe)(r,i);if(l.length>0){const d=i.map(a=>a.includes(":")?`${a.replace(":"," (")})`:a);e.logger.info(`Updated .dev.vars.example with secrets for: ${d.join(", ")} (${l.join(", ")})`)}}catch{}(await(e.ensureEnv??ae)({confirm:Be(),cwd:r,info:o=>{e.logger.info(o)}})).status==="declined"&&!ie()&&e.logger.info(`hint: ${T} was not scaffolded (non-interactive run). Copy ${se} → ${T} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??ce)({cwd:r,info:o=>{e.logger.info(o)}})}catch{}},Er=(e,r,n,t,o)=>{if(e.flavor!=="wrangler")return;t!==void 0&&H(r,{studioUrl:t});let i;try{i=sr(r,n)}catch{}return yr(n,e,t,o),i},br=(e,r)=>{const n=Number(process.env[_]),t=q(r,{background:process.env[x]==="1",logFile:process.env[ee],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(n)&&n>0?{supersedePid:n}:void 0);return t.ok?void 0:t.existing},Dr=e=>{const{cwd:r,destination:n,logger:t,plan:o}=e,i=n!==void 0,l=n??de,d=we({destination:l,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:B},logger:i?t:{...t,success:()=>{},warn:()=>{}},projectRoot:r});return d.error!==void 0?i?d:(t.debug?.(`skipped the default binding manifest: ${d.error}`),{}):{written:l}},_r=async(e,r,n,t)=>{if(r.studioEnabled)try{return await(e.startStudio??wr)({apiSpec:e.apiSpec,lazyFunctions:E(e.lazyFunctions),cwd:n,logger:{warnOnce:o=>{t.warn(o)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(o){t.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},kr=e=>{const r=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(t=>t!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},Rr=(e,r,n,t,o)=>{if(!(e.sidecar===void 0||!ar(r)))try{M({apiSpec:r.apiSpec,lazyFunctions:E(r.lazyFunctions),lunoraDirectory:"lunora",projectRoot:n,target:o,...U(n)})}catch(i){t.warn(`codegen (pre-sidecar) failed: ${i instanceof Error?i.message:String(i)} — the framework dev server will retry`)}},Tr=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,Ar=async(e,r,n,t,o)=>{try{return e.celldSession===!0?await ir({logger:o,port:e.workerPort,projectRoot:t,start:r.startCelldSession}):n(e.wrangler,o)}catch(i){o.error(`could not start the worker: ${i instanceof Error?i.message:String(i)}`);return}},Pr=async(e,r,n)=>{const t=await(e.startHyperdrive??ve)({onWarning:o=>{n.warn(o)},projectRoot:r});return t!==void 0&&t.bindings.length>0&&n.info(`Hyperdrive ${t.bindings.join(", ")}: embedded Postgres (PGlite), data in .wrangler/state/lunora-pglite. Set CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_<BINDING> to use your own.`),t},Cr=async e=>{const{logger:r}=e,n=Q(),t=e.cwd??process.cwd(),o=e.flavor??Qe(t),i=De(t,e.target);if(i.target===void 0)throw new Error(i.error??"unknown deploy target");const{target:l}=i,d=Ze(l,o,r);d==="wrangler"&&await cr(t,r,void 0,l,void 0,n);const a=await qe({...e,flavor:d,target:l}),f={remoteCleanup:a.remote.cleanup,serviceConfigCleanup:a.serviceConfigCleanup};try{const S=Number(process.env[_]),y=V(t);if(y!==void 0&&y.pid!==process.pid&&y.pid!==S)return R(r,y),{code:0,plan:a};const w=br(a,t);if(w!==void 0)return R(r,w),{code:0,plan:a};(a.flavor==="vite"||a.flavor==="framework-worker")&&(a.wrangler.env={...a.wrangler.env,[_]:String(process.pid)}),a.workerEnabled&&l==="cloudflare"&&(f.hyperdrive=await Pr(e,t,r)),await pr(e,t,n),r.info(Tr(a)),er(r,t),a.ipv4LoopbackForced&&r.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),a.runsCodegenWatch&&(f.codegen=(e.startCodegen??vr)({apiSpec:e.apiSpec,lazyFunctions:E(e.lazyFunctions),jsonLogs:e.jsonLogs,logger:r,projectRoot:t,target:l})),f.studio=await _r(e,a,t,r);const c=Dr({cwd:t,destination:e.emitBindings,logger:r,plan:a});if(c.error!==void 0)return r.error(c.error),{code:k.USAGE,plan:a};await f.codegen?.ready;const s=f.studio?.url;a.frameworkHint!==void 0&&r.warn(a.frameworkHint);const u=()=>{a.flavor==="wrangler"&&(f.readyProbe=new AbortController,hr({cwd:t,logger:r,origin:a.workerOrigin,probe:e.probeReady,signal:f.readyProbe.signal}))};if(!a.workerEnabled)return u(),r.info(kr(a)),f.tunnel=L({cwd:t,logger:r,plan:a,tunnel:e.tunnel}),{code:await(e.waitForInterrupt??rr)(r),plan:a};Rr(a,e,t,r,l);const m=e.startWorker??tr,h=await Ar(a,e,m,t,r);if(h===void 0)return{code:k.FAILURE,plan:a};const p=a.sidecar===void 0?void 0:m(a.sidecar,r);return u(),f.containerLogs=Er(a,t,r,s,c.written),f.tunnel=L({cwd:t,logger:r,plan:a,tunnel:e.tunnel}),Sr(r,t),{code:await nr(h,p,r),plan:a}}finally{f.readyProbe?.abort(),Z(t,process.pid),await or(f)}},Or=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),$r=e=>{if(e.local===!0&&e.remote===!0)return"`--local` and `--remote` are mutually exclusive — pass at most one.";const{entries:r,invalid:n}=z(e.allowMail);if(n.length>0)return`\`--allow-mail\` takes email addresses or '*@domain' — not ${n.map(t=>`"${t}"`).join(", ")}.`;if(r.length>0&&e.tunnel!==!0)return"`--allow-mail` only applies to a tunnel — add `--tunnel`."},Lr=e=>e.tunnel===!0?{allowMail:z(e.allowMail).entries}:void 0,rt=be(async({argument:e,cwd:r,logger:n,options:t})=>{const o=t.json===!0,i=Ye({cwd:r,json:o,lines:t.lines,logger:n,subcommand:e[0]});if(i!==void 0)return i;const l=process.env[x]==="1",d=l?void 0:J(),a=o||d!==void 0;a&&_e(),d!==void 0&&t.background!==!0&&n.info(`AI agent detected (${d.name} via ${d.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const f=$r(t);if(f!==void 0)return n.error(`dev: ${f}`),{code:k.USAGE};const S=Lr(t),y=t.local===!0?!1:fe({configPreference:K(r),envValue:process.env.LUNORA_REMOTE,flag:t.remote});if(!l&&(t.background===!0||d!==void 0)){const w=V(r);return w!==void 0?(R(n,w),{code:0}):(S?.allowMail.length===0&&Je(n),Ke({cwd:r,jsonLogs:a,logger:n,options:t,remote:y}))}return Cr({apiSpec:me(t.apiSpec),cwd:r,emitBindings:t.emitBindings,inspectorPort:t.inspectorPort,lazyFunctions:E(t.lazyFunctions),jsonLogs:a,local:t.local,logger:n,port:t.port,remote:y,target:t.target,tunnel:S,workerPort:t.workerPort,...Or(t)})});export{$r as devFlagConflict,rt as execute,Or as negatableDevFlags,Cr as runDevCommand};
|