@moinulmoin/eden 0.1.0

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.
@@ -0,0 +1,2007 @@
1
+ import { createRequire, } from "node:module";
2
+ import { createHash, randomUUID, } from "node:crypto";
3
+ import { join, dirname, relative, } from "node:path";
4
+ import { lstat, mkdir, readFile, readdir, realpath, rename, rm, symlink, writeFile, } from "node:fs/promises";
5
+ import { homedir, } from "node:os";
6
+ import { createServer, } from "node:net";
7
+ import { execFile, spawn, } from "node:child_process";
8
+ import { fileURLToPath, } from "node:url";
9
+ import { promisify, } from "node:util";
10
+ import { EveCliError, } from "./eve.js";
11
+ import { buildEveProjectSnapshot, createDockerEveProjectBuilder, revalidateEveProjectCandidateInputs, EvePackagingError, } from "./eve-packaging.js";
12
+ import { buildEveRuntimeImage, revalidateEveRuntimeCandidate, validateEveHostRequirements, } from "./eve-runtime-image.js";
13
+ import { EveRuntimeConfigError, prepareEveRuntimeInjection, redactEveRuntimeOutput, } from "./eve-runtime-config.js";
14
+ const execFileAsync = promisify(execFile);
15
+ const require = createRequire(import.meta.url);
16
+ const wranglerEntrypoint = require.resolve("wrangler");
17
+ export const DEFAULT_EVE_HOST_REQUIREMENTS = Object.freeze({
18
+ architecture: "linux/amd64",
19
+ world: "supported",
20
+ sandbox: "supported",
21
+ privileged: false,
22
+ devices: "none",
23
+ kernel: "supported",
24
+ network: "supported",
25
+ durableLocalFilesystem: false,
26
+ });
27
+ const wranglerCwd = dirname(wranglerEntrypoint);
28
+ export const DEFAULT_EVE_NODE_IMAGE = Object.freeze({
29
+ reference: "node:24.17.0-bookworm-slim",
30
+ digest: "sha256:862263c612aa437e3037674b85419622a9d93bff80aa1eee5398dfe686375532",
31
+ });
32
+ function safeText(value) {
33
+ return redactEveRuntimeOutput(value)
34
+ .replace(/(?:^|[\s"'=])(?:Bearer|Token)\s+\S+/giu, "$1[redacted]")
35
+ .slice(0, 2_000);
36
+ }
37
+ function check(id, status, message, remediation) {
38
+ return {
39
+ id,
40
+ status,
41
+ message: safeText(message),
42
+ ...(remediation === undefined ? {} : { remediation: safeText(remediation) }),
43
+ };
44
+ }
45
+ function mapPackagingCheck(value) {
46
+ const id = (() => {
47
+ if (value.id.startsWith("VAL-"))
48
+ return value.id;
49
+ switch (value.id) {
50
+ case "ROOT_INVALID":
51
+ return "VAL-CLI-004";
52
+ case "UNSUPPORTED_TOOLCHAIN":
53
+ case "DEPENDENCY_AMBIGUITY":
54
+ return "VAL-BUILD-001";
55
+ case "SOURCE_RACE":
56
+ return "VAL-CROSS-004";
57
+ case "EVE_BUILD_FAILED":
58
+ case "UNSUPPORTED_EVE_OUTPUT":
59
+ return "VAL-BUILD-004";
60
+ case "SECRET_EXCLUSION_FAILED":
61
+ return "VAL-SEC-003";
62
+ case "DOCKER_PLATFORM_BLOCKED":
63
+ return "VAL-BUILD-005";
64
+ default:
65
+ return `EVE-${value.id}`;
66
+ }
67
+ })();
68
+ return check(id, value.status === "pass" ? "passed" : "failed", value.reason, value.remediation ?? undefined);
69
+ }
70
+ function blockedAfterFailure(id, message) {
71
+ return check(id, "blocked", message, "Resolve the earlier failed or blocked check, then retry the exact Eve target.");
72
+ }
73
+ function allChecksClear(checks) {
74
+ return checks.every((value) => value.status === "passed" || value.status === "skipped");
75
+ }
76
+ function runtimeConfigExclusion(config) {
77
+ if (config === undefined)
78
+ return undefined;
79
+ return {
80
+ envFilePath: config.inputPath,
81
+ inputIdentity: config.seam.inputIdentity,
82
+ readInputIdentity: () => config.readInputIdentity(),
83
+ variableNames: config.seam.variableNames,
84
+ redactionRegistered: true,
85
+ };
86
+ }
87
+ function candidateMetadata(candidate, imageDigest) {
88
+ return {
89
+ generationId: candidate.generationId,
90
+ sourceDigest: candidate.sourceDigest,
91
+ outputDigest: candidate.generatedOutput.outputDigest,
92
+ ...(imageDigest === undefined ? {} : { imageDigest }),
93
+ };
94
+ }
95
+ function safeWranglerEnvironment() {
96
+ return {
97
+ PATH: process.env.PATH,
98
+ HOME: process.env.HOME,
99
+ TMPDIR: process.env.TMPDIR,
100
+ LANG: process.env.LANG,
101
+ LC_ALL: process.env.LC_ALL,
102
+ CLOUDFLARE_API_TOKEN: process.env.CLOUDFLARE_API_TOKEN,
103
+ NODE_OPTIONS: undefined,
104
+ };
105
+ }
106
+ function safeDockerEnvironment() {
107
+ return {
108
+ PATH: process.env.PATH,
109
+ HOME: process.env.HOME,
110
+ TMPDIR: process.env.TMPDIR,
111
+ LANG: process.env.LANG,
112
+ LC_ALL: process.env.LC_ALL,
113
+ DOCKER_HOST: process.env.DOCKER_HOST,
114
+ DOCKER_CONTEXT: process.env.DOCKER_CONTEXT,
115
+ };
116
+ }
117
+ async function readWranglerJson(args) {
118
+ try {
119
+ const result = await execFileAsync(process.execPath, [wranglerEntrypoint, ...args], {
120
+ env: safeWranglerEnvironment(),
121
+ cwd: wranglerCwd,
122
+ maxBuffer: 2 * 1024 * 1024,
123
+ timeout: 30_000,
124
+ });
125
+ const parsed = JSON.parse(result.stdout.trim());
126
+ return { value: parsed, failed: false };
127
+ }
128
+ catch (error) {
129
+ const stderr = typeof error === "object" &&
130
+ error !== null &&
131
+ typeof error.stderr === "string"
132
+ ? error.stderr
133
+ : undefined;
134
+ return {
135
+ failed: true,
136
+ ...(stderr === undefined ? {} : { stderr: safeText(stderr) }),
137
+ };
138
+ }
139
+ }
140
+ function jsonCollection(value) {
141
+ if (Array.isArray(value))
142
+ return value;
143
+ if (typeof value === "object" &&
144
+ value !== null &&
145
+ Array.isArray(value.result)) {
146
+ return value.result;
147
+ }
148
+ return undefined;
149
+ }
150
+ function exactContainerEntries(value, name) {
151
+ const collection = jsonCollection(value);
152
+ if (collection === undefined)
153
+ return undefined;
154
+ const entries = [];
155
+ for (const entry of collection) {
156
+ if (typeof entry !== "object" ||
157
+ entry === null ||
158
+ typeof entry.id !== "string" ||
159
+ typeof entry.name !== "string") {
160
+ return undefined;
161
+ }
162
+ const id = entry.id;
163
+ const entryName = entry.name;
164
+ if (entryName === name)
165
+ entries.push({ id, name: entryName });
166
+ }
167
+ if (entries.length === 0 && collection.length >= 100) {
168
+ return undefined;
169
+ }
170
+ return entries;
171
+ }
172
+ function exactDeploymentEntries(value) {
173
+ const collection = jsonCollection(value);
174
+ if (collection === undefined)
175
+ return undefined;
176
+ if (collection.some((entry) => typeof entry !== "object" || entry === null)) {
177
+ return undefined;
178
+ }
179
+ return collection;
180
+ }
181
+ function authenticatedWranglerAccount(value) {
182
+ return typeof value === "object" &&
183
+ value !== null &&
184
+ value.loggedIn === true &&
185
+ Array.isArray(value.accounts);
186
+ }
187
+ function authenticatedAccountId(value) {
188
+ if (!authenticatedWranglerAccount(value))
189
+ return undefined;
190
+ const accounts = value.accounts;
191
+ if (accounts.length !== 1)
192
+ return undefined;
193
+ const account = accounts[0];
194
+ if (typeof account !== "object" ||
195
+ account === null ||
196
+ typeof account.id !== "string") {
197
+ return undefined;
198
+ }
199
+ return account.id;
200
+ }
201
+ async function readWranglerOAuthToken() {
202
+ const root = process.env.WRANGLER_HOME ??
203
+ (process.platform === "darwin"
204
+ ? join(homedir(), "Library", "Preferences", ".wrangler")
205
+ : join(homedir(), ".config", ".wrangler"));
206
+ const raw = await readFile(join(root, "config", "default.toml"), "utf8")
207
+ .catch(() => undefined);
208
+ if (raw === undefined)
209
+ return undefined;
210
+ const match = /^oauth_token\s*=\s*["']([^"'\r\n]+)["']/m.exec(raw);
211
+ return match === null ? undefined : match[1];
212
+ }
213
+ async function readWorkersDevSubdomain(accountId) {
214
+ const envToken = process.env.CLOUDFLARE_API_TOKEN;
215
+ const token = envToken !== undefined && envToken.length > 0
216
+ ? envToken
217
+ : await readWranglerOAuthToken();
218
+ if (accountId === undefined || token === undefined || token.length === 0) {
219
+ return undefined;
220
+ }
221
+ try {
222
+ const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/subdomain`, {
223
+ headers: {
224
+ Authorization: `Bearer ${token}`,
225
+ Accept: "application/json",
226
+ },
227
+ signal: AbortSignal.timeout(30_000),
228
+ });
229
+ if (!response.ok)
230
+ return undefined;
231
+ const body = await response.json();
232
+ const result = typeof body === "object" && body !== null
233
+ ? body.result
234
+ : undefined;
235
+ const subdomain = typeof result === "object" && result !== null
236
+ ? result.subdomain
237
+ : undefined;
238
+ return typeof subdomain === "string" &&
239
+ /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u.test(subdomain)
240
+ ? subdomain
241
+ : undefined;
242
+ }
243
+ catch {
244
+ return undefined;
245
+ }
246
+ }
247
+ async function defaultCloudflareRead(request) {
248
+ const account = await readWranglerJson(["whoami", "--json"]);
249
+ const containers = await readWranglerJson([
250
+ "containers",
251
+ "list",
252
+ "--json",
253
+ "--per-page",
254
+ "100",
255
+ ]);
256
+ const containerCollection = jsonCollection(containers.value);
257
+ const deployments = await readWranglerJson([
258
+ "deployments",
259
+ "list",
260
+ "--name",
261
+ request.name,
262
+ "--json",
263
+ ]);
264
+ const accountId = authenticatedAccountId(account.value);
265
+ const accountAccess = account.failed || accountId === undefined
266
+ ? "unavailable"
267
+ : "available";
268
+ const containerEntries = exactContainerEntries(containers.value, request.name);
269
+ const containerAccess = containers.failed || containerEntries === undefined
270
+ ? "unavailable"
271
+ : "available";
272
+ const deploymentEntries = deployments.failed &&
273
+ /(?:does not exist|not found)/iu.test(deployments.stderr ?? "")
274
+ ? []
275
+ : exactDeploymentEntries(deployments.value);
276
+ const workersDevSubdomain = await readWorkersDevSubdomain(accountId);
277
+ if (accountAccess === "unavailable" ||
278
+ containerAccess === "unavailable" ||
279
+ deploymentEntries === undefined) {
280
+ return {
281
+ accountAccess,
282
+ containerAccess,
283
+ ...(accountId === undefined
284
+ ? {}
285
+ : { accountId }),
286
+ ...(workersDevSubdomain === undefined
287
+ ? {}
288
+ : { workersDevSubdomain }),
289
+ target: {
290
+ state: "ambiguous",
291
+ message: "The authenticated Cloudflare read-only checks did not return a complete exact-target result.",
292
+ remediation: "Retry with authenticated account, Container, and exact Worker deployment reads; preflight never guesses or mutates a target.",
293
+ },
294
+ };
295
+ }
296
+ if (deploymentEntries.length === 0 &&
297
+ containerCollection?.length === 0) {
298
+ return {
299
+ accountAccess,
300
+ containerAccess,
301
+ ...(accountId === undefined
302
+ ? {}
303
+ : { accountId }),
304
+ ...(workersDevSubdomain === undefined
305
+ ? {}
306
+ : { workersDevSubdomain }),
307
+ target: { state: "absent" },
308
+ };
309
+ }
310
+ return {
311
+ accountAccess,
312
+ containerAccess,
313
+ ...(accountId === undefined
314
+ ? {}
315
+ : { accountId }),
316
+ ...(workersDevSubdomain === undefined
317
+ ? {}
318
+ : { workersDevSubdomain }),
319
+ target: {
320
+ state: "ambiguous",
321
+ message: "The exact target could not be proven absent or owned from the read-only Cloudflare inventory.",
322
+ remediation: "Resolve the exact Worker and Container ownership state before deployment; no target was claimed or changed.",
323
+ },
324
+ };
325
+ }
326
+ async function readEveCloudflareTarget(request, options) {
327
+ return options.cloudflareRead === undefined
328
+ ? defaultCloudflareRead(request)
329
+ : options.cloudflareRead(request);
330
+ }
331
+ async function resolvedCloudflareOrigin(result, workerName) {
332
+ if (result.accountId === undefined ||
333
+ result.workersDevSubdomain === undefined) {
334
+ return undefined;
335
+ }
336
+ try {
337
+ const { resolveStableWorkersDevOrigin } = await import("@moinulmoin/eden-runtime-cloudflare");
338
+ const origin = resolveStableWorkersDevOrigin({
339
+ workerName,
340
+ workersDevSubdomain: result.workersDevSubdomain,
341
+ });
342
+ return result.stableWorkersDevOrigin === undefined ||
343
+ result.stableWorkersDevOrigin === origin
344
+ ? origin
345
+ : undefined;
346
+ }
347
+ catch {
348
+ return undefined;
349
+ }
350
+ }
351
+ async function findAvailableEveHealthPort() {
352
+ for (let port = 4310; port <= 4399; port += 1) {
353
+ const available = await new Promise((resolveResult) => {
354
+ const server = createServer();
355
+ const finish = (value) => {
356
+ server.removeAllListeners();
357
+ server.close(() => resolveResult(value));
358
+ };
359
+ server.once("error", () => finish(false));
360
+ server.listen({ host: "127.0.0.1", port }, () => finish(true));
361
+ });
362
+ if (available)
363
+ return port;
364
+ }
365
+ throw new EveCliError({
366
+ code: "EVE_HEALTH_PORT_UNAVAILABLE",
367
+ message: "No task-owned Eve health port was available in the allowed 4310-4399 range.",
368
+ });
369
+ }
370
+ async function defaultRuntimeRunner(request) {
371
+ let result;
372
+ try {
373
+ const imageRequest = {
374
+ candidate: request.candidate,
375
+ nodeImage: request.nodeImage,
376
+ healthPort: request.healthPort,
377
+ hostRequirements: request.hostRequirements,
378
+ ...(request.publicOrigin === undefined
379
+ ? {}
380
+ : { publicOrigin: request.publicOrigin }),
381
+ ...(request.runtimeInjection === undefined
382
+ ? {}
383
+ : { runtimeInjection: request.runtimeInjection }),
384
+ retainImage: request.retainImage ?? false,
385
+ };
386
+ result = await buildEveRuntimeImage(imageRequest);
387
+ }
388
+ catch {
389
+ return {
390
+ ok: false,
391
+ checks: [
392
+ check("VAL-BUILD-005", "failed", "The Linux/amd64 Eve runtime image runner failed before returning a verified result.", "Retry with the pinned Docker/OrbStack runtime and inspect only the owned candidate identities."),
393
+ ],
394
+ cleanup: {
395
+ bootContainerId: null,
396
+ bootContainerRemoved: false,
397
+ imageIdentity: "indeterminate",
398
+ imageRetained: false,
399
+ verified: false,
400
+ },
401
+ };
402
+ }
403
+ return {
404
+ ok: result.deployable,
405
+ checks: result.checks.map((value) => check(value.id, value.status === "pass" ? "passed" : "failed", value.reason, value.remediation ?? undefined)),
406
+ ...(result.image?.imageDigest === undefined
407
+ ? {}
408
+ : { imageDigest: result.image.imageDigest }),
409
+ ...(result.image?.imageReference === undefined
410
+ ? {}
411
+ : { imageReference: result.image.imageReference }),
412
+ cleanup: result.cleanup,
413
+ };
414
+ }
415
+ function cloudflareChecks(result) {
416
+ const accessMessage = result.accountAccess === "available" &&
417
+ result.containerAccess === "available"
418
+ ? "Authenticated account and Container access were verified through the read-only adapter."
419
+ : "Authenticated Cloudflare account and Container access could not be verified without a mutating operation.";
420
+ const accessRemediation = result.accountAccess === "available" &&
421
+ result.containerAccess === "available"
422
+ ? undefined
423
+ : "Use an authenticated read-only adapter with account and Container access; preflight never uploads, publishes, or changes remote state.";
424
+ const target = result.target;
425
+ const targetPasses = target.state === "absent" ||
426
+ (target.state === "owned" && target.matchesCandidate === true);
427
+ const targetMessage = targetPasses
428
+ ? target.state === "absent"
429
+ ? "The exact target read is absent and is eligible without claiming ownership."
430
+ : "The exact target is already owned by this candidate identity; no ownership claim was attempted."
431
+ : target.message ??
432
+ "The exact target read is unowned, mismatched, cross-environment, or ambiguous.";
433
+ const targetRemediation = targetPasses
434
+ ? undefined
435
+ : target.remediation ??
436
+ "Inspect only the exact target and resolve ownership or identity ambiguity before deploy; do not broaden the target.";
437
+ return [
438
+ check("VAL-CLI-007-CLOUDFLARE-ACCESS", accessMessage === undefined ? "blocked" : (result.accountAccess === "available" &&
439
+ result.containerAccess === "available"
440
+ ? "passed"
441
+ : "blocked"), accessMessage, accessRemediation),
442
+ check("VAL-CLI-007-TARGET-CONFLICT", targetPasses ? "passed" : "failed", targetMessage, targetRemediation),
443
+ ];
444
+ }
445
+ function stableDeploymentKey(projectId, accountId, environment, name) {
446
+ const digest = createHash("sha256")
447
+ .update(`${projectId}\n${accountId}\n${environment}\n${name}`, "utf8")
448
+ .digest("hex");
449
+ return `${environment}-${name}-${digest.slice(0, 24)}`;
450
+ }
451
+ function boundedResourceName(name, suffix) {
452
+ const value = `${name}-${suffix}`;
453
+ return value.length <= 63 ? value : value.slice(0, 63).replace(/-+$/u, "");
454
+ }
455
+ function imageDigestFromReference(value) {
456
+ const match = /@sha256:([0-9a-f]{64})$/u.exec(value);
457
+ return match === null ? undefined : `sha256:${match[1]}`;
458
+ }
459
+ function transportIdentityMatches(expected, observed) {
460
+ if (observed === undefined)
461
+ return false;
462
+ const required = [
463
+ "deploymentId",
464
+ "generationId",
465
+ "stableWorkersDevOrigin",
466
+ "workerName",
467
+ "stableContainerInstanceName",
468
+ ];
469
+ if (!required.every((key) => observed[key] === expected[key])) {
470
+ return false;
471
+ }
472
+ return expected.runtimeRevisionHandle === undefined
473
+ ? observed.runtimeRevisionHandle === undefined
474
+ : observed.runtimeRevisionHandle === expected.runtimeRevisionHandle;
475
+ }
476
+ function identityMatches(expected, observed) {
477
+ if (observed === undefined)
478
+ return false;
479
+ const required = [
480
+ "projectId",
481
+ "sourceDigest",
482
+ "generationId",
483
+ "deploymentId",
484
+ "environment",
485
+ "name",
486
+ "accountId",
487
+ "workersDevSubdomain",
488
+ "stableWorkersDevOrigin",
489
+ "workerName",
490
+ "containerApplicationName",
491
+ "stableContainerInstanceName",
492
+ "containerImage",
493
+ ];
494
+ if (!required.every((key) => observed[key] === expected[key]))
495
+ return false;
496
+ if (observed.runtimeVariableNames === undefined ||
497
+ observed.runtimeVariableNames.length !== expected.runtimeVariableNames.length ||
498
+ observed.runtimeVariableNames.some((name, index) => name !== expected.runtimeVariableNames[index])) {
499
+ return false;
500
+ }
501
+ return expected.runtimeRevisionHandle === undefined
502
+ ? observed.runtimeRevisionHandle === undefined
503
+ : observed.runtimeRevisionHandle === expected.runtimeRevisionHandle;
504
+ }
505
+ function safeIdentity(identity) {
506
+ return {
507
+ projectId: identity.projectId,
508
+ sourceDigest: identity.sourceDigest,
509
+ generationId: identity.generationId,
510
+ deploymentId: identity.deploymentId,
511
+ environment: identity.environment,
512
+ name: identity.name,
513
+ accountId: identity.accountId,
514
+ workersDevSubdomain: identity.workersDevSubdomain,
515
+ stableWorkersDevOrigin: identity.stableWorkersDevOrigin,
516
+ workerName: identity.workerName,
517
+ containerApplicationName: identity.containerApplicationName,
518
+ stableContainerInstanceName: identity.stableContainerInstanceName,
519
+ containerImage: identity.containerImage,
520
+ runtimeVariableNames: identity.runtimeVariableNames,
521
+ ...(identity.runtimeRevisionHandle === undefined
522
+ ? {}
523
+ : { runtimeRevisionHandle: identity.runtimeRevisionHandle }),
524
+ };
525
+ }
526
+ async function writeEveDeploymentArtifacts(candidate, hostConfig, workerSource) {
527
+ const workerRoot = join(candidate.generationRoot, "worker");
528
+ const workerSourcePath = join(workerRoot, "worker.ts");
529
+ const wranglerConfigPath = join(workerRoot, "wrangler.jsonc");
530
+ await mkdir(workerRoot, { recursive: true });
531
+ await writeFile(workerSourcePath, workerSource, {
532
+ encoding: "utf8",
533
+ mode: 0o600,
534
+ flag: "wx",
535
+ });
536
+ const runtimePackageRoot = dirname(dirname(fileURLToPath(import.meta.resolve("@moinulmoin/eden-runtime-cloudflare"))));
537
+ const bundleSource = join(runtimePackageRoot, "dist", "eden-eve-host-worker.mjs");
538
+ const bundleContents = await readFile(bundleSource).catch(() => undefined);
539
+ if (bundleContents === undefined) {
540
+ throw deploymentFailure("EVE_HOST_BUNDLE_UNAVAILABLE", "The vendored Eve host worker bundle is missing from the installed runtime package.");
541
+ }
542
+ await writeFile(join(workerRoot, "eden-eve-host-worker.mjs"), bundleContents, { mode: 0o644, flag: "wx" });
543
+ const config = {
544
+ $schema: "https://developers.cloudflare.com/workers/wrangler/config-schema.json",
545
+ ...hostConfig.worker,
546
+ main: "worker.ts",
547
+ };
548
+ await writeFile(wranglerConfigPath, `${JSON.stringify(config, null, 2)}\n`, {
549
+ encoding: "utf8",
550
+ mode: 0o600,
551
+ flag: "wx",
552
+ });
553
+ return { workerSourcePath, wranglerConfigPath };
554
+ }
555
+ function runWranglerWithInput(args, cwd, input) {
556
+ return new Promise((resolveResult) => {
557
+ const child = spawn(process.execPath, [wranglerEntrypoint, ...args], {
558
+ cwd,
559
+ env: safeWranglerEnvironment(),
560
+ stdio: ["pipe", "pipe", "pipe"],
561
+ });
562
+ let stdout = "";
563
+ let stderr = "";
564
+ let settled = false;
565
+ const finish = (result) => {
566
+ if (settled)
567
+ return;
568
+ settled = true;
569
+ resolveResult({
570
+ exitCode: result.exitCode,
571
+ stdout: safeText(result.stdout),
572
+ stderr: safeText(result.stderr),
573
+ });
574
+ };
575
+ const timeout = setTimeout(() => {
576
+ child.kill("SIGTERM");
577
+ finish({
578
+ exitCode: 1,
579
+ stdout,
580
+ stderr: "The bounded Wrangler operation timed out.",
581
+ });
582
+ }, 120_000);
583
+ child.stdout.on("data", (chunk) => {
584
+ stdout += chunk.toString();
585
+ });
586
+ child.stderr.on("data", (chunk) => {
587
+ stderr += chunk.toString();
588
+ });
589
+ child.once("error", () => {
590
+ clearTimeout(timeout);
591
+ finish({ exitCode: 1, stdout, stderr: "Wrangler could not be started." });
592
+ });
593
+ child.once("close", (code) => {
594
+ clearTimeout(timeout);
595
+ finish({ exitCode: code ?? 1, stdout, stderr });
596
+ });
597
+ if (input === undefined)
598
+ child.stdin.end();
599
+ else
600
+ child.stdin.end(input);
601
+ });
602
+ }
603
+ function defaultProtectedStore(workerName) {
604
+ return {
605
+ async put(request) {
606
+ for (const name of request.variableNames) {
607
+ const result = await runWranglerWithInput([
608
+ "secret",
609
+ "put",
610
+ name,
611
+ "--name",
612
+ workerName,
613
+ ], process.cwd(), request.values[name] === undefined ? "" : `${request.values[name]}\n`);
614
+ if (result.exitCode !== 0) {
615
+ throw new EveRuntimeConfigError({
616
+ code: "EVE_RUNTIME_PROTECTED_UPLOAD_FAILED",
617
+ message: "The protected Cloudflare runtime upload failed.",
618
+ });
619
+ }
620
+ }
621
+ return {
622
+ revision: request.revision,
623
+ handle: `eve-runtime-handle-${randomUUID()}`,
624
+ };
625
+ },
626
+ };
627
+ }
628
+ async function defaultImagePublicationRunner(request) {
629
+ try {
630
+ await execFileAsync("docker", ["tag", request.localImageReference, request.localImageTag], {
631
+ env: safeDockerEnvironment(),
632
+ cwd: request.generationRoot,
633
+ maxBuffer: 512 * 1024,
634
+ });
635
+ const pushed = await runWranglerWithInput(["containers", "push", request.localImageTag], request.generationRoot);
636
+ if (pushed.exitCode !== 0) {
637
+ return {
638
+ status: "indeterminate",
639
+ reason: "The exact Cloudflare Container image push did not complete.",
640
+ evidenceRetained: true,
641
+ };
642
+ }
643
+ const inspected = await execFileAsync("docker", [
644
+ "image",
645
+ "inspect",
646
+ request.localImageTag,
647
+ "--format",
648
+ "{{json .RepoDigests}}",
649
+ ], {
650
+ env: safeDockerEnvironment(),
651
+ cwd: request.generationRoot,
652
+ maxBuffer: 512 * 1024,
653
+ });
654
+ const repoDigests = JSON.parse(inspected.stdout.trim());
655
+ const exact = Array.isArray(repoDigests)
656
+ ? repoDigests.find((value) => typeof value === "string" &&
657
+ value.startsWith(`${request.targetImageReference.split("@")[0]}@`))
658
+ : undefined;
659
+ if (exact === undefined ||
660
+ !/^registry\.cloudflare\.com\/[a-f0-9]{32}\/[A-Za-z0-9._/-]+@sha256:[0-9a-f]{64}$/u
661
+ .test(exact)) {
662
+ return {
663
+ status: "indeterminate",
664
+ reason: "The pushed Cloudflare image digest could not be proven exactly.",
665
+ evidenceRetained: true,
666
+ };
667
+ }
668
+ const digest = imageDigestFromReference(exact);
669
+ if (digest === undefined) {
670
+ return {
671
+ status: "indeterminate",
672
+ reason: "The pushed Cloudflare image returned no immutable digest.",
673
+ evidenceRetained: true,
674
+ };
675
+ }
676
+ return {
677
+ status: "published",
678
+ imageReference: exact,
679
+ imageDigest: digest,
680
+ };
681
+ }
682
+ catch {
683
+ return {
684
+ status: "indeterminate",
685
+ reason: "The exact Cloudflare Container image publication failed ambiguously.",
686
+ evidenceRetained: true,
687
+ };
688
+ }
689
+ }
690
+ function defaultPublicationRunner() {
691
+ return async (request) => {
692
+ const result = await runWranglerWithInput([
693
+ "deploy",
694
+ "--config",
695
+ request.wranglerConfigPath,
696
+ "--name",
697
+ request.identity.workerName,
698
+ "--env",
699
+ request.identity.environment,
700
+ "--strict",
701
+ "--containers-rollout",
702
+ "immediate",
703
+ ], dirname(request.wranglerConfigPath));
704
+ if (result.exitCode !== 0) {
705
+ return {
706
+ status: "indeterminate",
707
+ reason: "The exact Cloudflare publication did not return a terminal success result.",
708
+ ownershipEvidenceRetained: true,
709
+ };
710
+ }
711
+ const containers = await readWranglerJson([
712
+ "containers",
713
+ "list",
714
+ "--json",
715
+ "--per-page",
716
+ "100",
717
+ ]);
718
+ const containerEntries = exactContainerEntries(containers.value, request.hostConfig.container.applicationName);
719
+ const deployments = await readWranglerJson([
720
+ "deployments",
721
+ "list",
722
+ "--name",
723
+ request.identity.workerName,
724
+ "--json",
725
+ ]);
726
+ const deploymentEntries = exactDeploymentEntries(deployments.value);
727
+ if (containers.failed ||
728
+ containerEntries === undefined ||
729
+ containerEntries.length !== 1 ||
730
+ deployments.failed ||
731
+ deploymentEntries === undefined ||
732
+ deploymentEntries.length === 0) {
733
+ return {
734
+ status: "indeterminate",
735
+ reason: "The exact Worker deployment and named Container could not be re-read after publication.",
736
+ ownershipEvidenceRetained: true,
737
+ };
738
+ }
739
+ return {
740
+ status: "published",
741
+ identity: request.identity,
742
+ createdByAttempt: true,
743
+ ownershipProven: true,
744
+ };
745
+ };
746
+ }
747
+ function responseIdentity(response, body) {
748
+ const record = typeof body === "object" && body !== null
749
+ ? body
750
+ : {};
751
+ const identity = {};
752
+ const read = (name, header) => {
753
+ const bodyValue = record[name];
754
+ const headerValue = response.headers.get(header);
755
+ if (typeof bodyValue === "string") {
756
+ identity[name] = bodyValue;
757
+ }
758
+ else if (headerValue !== null) {
759
+ identity[name] = headerValue;
760
+ }
761
+ };
762
+ read("projectId", "x-eden-eve-project-id");
763
+ read("sourceDigest", "x-eden-eve-source-digest");
764
+ read("generationId", "x-eden-eve-generation-id");
765
+ read("deploymentId", "x-eden-eve-deployment-id");
766
+ read("environment", "x-eden-eve-environment");
767
+ read("name", "x-eden-eve-name");
768
+ read("accountId", "x-eden-eve-account-id");
769
+ read("workersDevSubdomain", "x-eden-eve-workers-dev-subdomain");
770
+ read("stableWorkersDevOrigin", "x-eden-eve-public-origin");
771
+ read("workerName", "x-eden-eve-worker-name");
772
+ read("containerApplicationName", "x-eden-eve-container-application");
773
+ read("stableContainerInstanceName", "x-eden-eve-container-instance");
774
+ read("containerImage", "x-eden-eve-container-image");
775
+ return identity;
776
+ }
777
+ function defaultHealthRunner() {
778
+ return async (request) => {
779
+ const attempts = 12;
780
+ const perAttemptTimeoutMs = 20_000;
781
+ const retryDelayMs = 5_000;
782
+ let sawResponse = false;
783
+ let lastReason = "The public Eve health request did not complete.";
784
+ const wait = async () => {
785
+ // Executor form: the CLI lib target predates Promise.withResolvers.
786
+ await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
787
+ };
788
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
789
+ let response;
790
+ try {
791
+ response = await fetch(`${request.origin}/eve/v1/health`, {
792
+ method: "GET",
793
+ signal: AbortSignal.timeout(perAttemptTimeoutMs),
794
+ });
795
+ sawResponse = true;
796
+ }
797
+ catch {
798
+ lastReason =
799
+ "The public Eve health request did not complete before the bounded deadline (cold Container boot may still be starting).";
800
+ await wait();
801
+ continue;
802
+ }
803
+ let body;
804
+ try {
805
+ body = await response.json();
806
+ }
807
+ catch {
808
+ body = undefined;
809
+ }
810
+ const ready = response.ok &&
811
+ typeof body === "object" &&
812
+ body !== null &&
813
+ (body.status === "ready" ||
814
+ body.state === "ready" ||
815
+ body.ready === true);
816
+ if (ready) {
817
+ return {
818
+ status: "ready",
819
+ identity: responseIdentity(response, body),
820
+ };
821
+ }
822
+ lastReason =
823
+ "The public Eve health route did not report ready before the bounded deadline.";
824
+ await wait();
825
+ }
826
+ return {
827
+ status: sawResponse ? "failed" : "indeterminate",
828
+ reason: lastReason,
829
+ };
830
+ };
831
+ }
832
+ async function acquireEveTargetLock(projectRoot, environment, name) {
833
+ const lockRoot = join(projectRoot, ".eden", "eve-deploy", "locks");
834
+ await mkdir(lockRoot, { recursive: true });
835
+ const lockPath = join(lockRoot, `${environment}-${name}.lock`);
836
+ const serialized = `${JSON.stringify({
837
+ kind: "eden.eve.deploy.lock",
838
+ version: 1,
839
+ pid: process.pid,
840
+ startedAt: new Date().toISOString(),
841
+ environment,
842
+ name,
843
+ })}\n`;
844
+ try {
845
+ await writeFile(lockPath, serialized, {
846
+ encoding: "utf8",
847
+ mode: 0o600,
848
+ flag: "wx",
849
+ });
850
+ }
851
+ catch (error) {
852
+ const code = error;
853
+ if (code.code === "EEXIST") {
854
+ throw new EveCliError({
855
+ code: "EVE_DEPLOY_BUSY",
856
+ message: "Another Eve deployment owns the exact target; retry after it finishes.",
857
+ source: "deployment-lock",
858
+ });
859
+ }
860
+ throw error;
861
+ }
862
+ return { path: lockPath, serialized };
863
+ }
864
+ async function releaseEveTargetLock(lock) {
865
+ const observed = await readFile(lock.path, "utf8").catch(() => undefined);
866
+ if (observed === undefined)
867
+ return false;
868
+ if (observed !== lock.serialized)
869
+ return false;
870
+ await rm(lock.path, { force: true });
871
+ return (await lstat(lock.path).catch(() => undefined)) === undefined;
872
+ }
873
+ async function promoteEveTargetPointer(deploymentRoot, targetKey, generationRoot) {
874
+ const targetRoot = join(deploymentRoot, "targets", targetKey);
875
+ const artifactBoundary = await realpath(dirname(deploymentRoot)).catch(() => undefined);
876
+ const generationCanonical = await realpath(generationRoot).catch(() => undefined);
877
+ if (artifactBoundary === undefined ||
878
+ generationCanonical === undefined ||
879
+ (generationCanonical !== artifactBoundary &&
880
+ !generationCanonical.startsWith(`${artifactBoundary}/`))) {
881
+ throw new EveCliError({
882
+ code: "EVE_DEPLOY_PROMOTION_FAILED",
883
+ message: "The immutable Eve generation escaped the Eden artifact boundary.",
884
+ source: "generation",
885
+ });
886
+ }
887
+ const generationDetails = await lstat(generationRoot).catch(() => undefined);
888
+ if (generationDetails === undefined ||
889
+ !generationDetails.isDirectory() ||
890
+ generationDetails.isSymbolicLink()) {
891
+ throw new EveCliError({
892
+ code: "EVE_DEPLOY_PROMOTION_FAILED",
893
+ message: "The immutable Eve generation was unavailable for promotion.",
894
+ source: relative(deploymentRoot, generationRoot),
895
+ });
896
+ }
897
+ await mkdir(targetRoot, { recursive: true });
898
+ const targetRootCanonical = await realpath(targetRoot).catch(() => undefined);
899
+ if (targetRootCanonical === undefined || targetRootCanonical !== targetRoot) {
900
+ throw new EveCliError({
901
+ code: "EVE_DEPLOY_PROMOTION_FAILED",
902
+ message: "The Eve target pointer directory could not be verified safely.",
903
+ source: targetKey,
904
+ });
905
+ }
906
+ const currentPath = join(targetRoot, "CURRENT");
907
+ const stagePath = join(targetRoot, `.CURRENT-${process.pid}-${randomUUID()}`);
908
+ await symlink(relative(targetRoot, generationRoot), stagePath);
909
+ try {
910
+ await rename(stagePath, currentPath);
911
+ }
912
+ finally {
913
+ await rm(stagePath, { force: true }).catch(() => undefined);
914
+ }
915
+ const resolved = await realpath(currentPath).catch(() => undefined);
916
+ if (resolved !== generationCanonical) {
917
+ throw new EveCliError({
918
+ code: "EVE_DEPLOY_PROMOTION_FAILED",
919
+ message: "The Eve target pointer did not resolve to the promoted generation.",
920
+ source: targetKey,
921
+ });
922
+ }
923
+ return currentPath;
924
+ }
925
+ async function writeEveDeploymentRecord(candidate, identity, hostConfig, status, extra = {}) {
926
+ await writeFile(join(candidate.generationRoot, "deployment.json"), `${JSON.stringify({
927
+ version: 1,
928
+ status,
929
+ identity: safeIdentity(identity),
930
+ worker: hostConfig.worker,
931
+ container: hostConfig.container,
932
+ ...extra,
933
+ }, null, 2)}\n`, {
934
+ encoding: "utf8",
935
+ mode: 0o600,
936
+ flag: "wx",
937
+ });
938
+ }
939
+ async function writeEveIndeterminateEvidence(candidate, evidence, extra = {}) {
940
+ await writeFile(join(candidate.generationRoot, "deployment-attempt.json"), `${JSON.stringify({
941
+ version: 1,
942
+ status: "indeterminate",
943
+ generationId: candidate.generationId,
944
+ sourceDigest: candidate.sourceDigest,
945
+ outputDigest: candidate.generatedOutput.outputDigest,
946
+ evidence: safeText(evidence),
947
+ ...extra,
948
+ }, null, 2)}\n`, {
949
+ encoding: "utf8",
950
+ mode: 0o600,
951
+ flag: "wx",
952
+ });
953
+ }
954
+ function deploymentMetadata(identity, targetKey, status) {
955
+ return {
956
+ status,
957
+ targetKey,
958
+ deploymentId: identity.deploymentId,
959
+ workerName: identity.workerName,
960
+ containerApplicationName: identity.containerApplicationName,
961
+ stableContainerInstanceName: identity.stableContainerInstanceName,
962
+ stableWorkersDevOrigin: identity.stableWorkersDevOrigin,
963
+ imageReference: identity.containerImage,
964
+ runtimeVariableNames: identity.runtimeVariableNames,
965
+ evidenceRetained: true,
966
+ };
967
+ }
968
+ function deploymentFailure(code, message) {
969
+ return new EveCliError({
970
+ code,
971
+ message: safeText(message),
972
+ source: "eve deploy",
973
+ });
974
+ }
975
+ async function runEveDeployment(request, options, collected) {
976
+ const candidate = collected.candidate;
977
+ const cloudflare = collected.cloudflare;
978
+ const runtimeEvidence = collected.runtimeEvidence;
979
+ if (candidate === undefined ||
980
+ cloudflare === undefined ||
981
+ runtimeEvidence === undefined ||
982
+ collected.projectId === undefined) {
983
+ throw deploymentFailure("EVE_DEPLOY_CHECKS_FAILED", "The inline Eve deploy checks did not return a complete immutable candidate.");
984
+ }
985
+ const accountId = cloudflare.accountId ??
986
+ cloudflare.target.identity?.accountId;
987
+ const workersDevSubdomain = cloudflare.workersDevSubdomain ??
988
+ cloudflare.target.identity?.workersDevSubdomain;
989
+ if (accountId === undefined || workersDevSubdomain === undefined) {
990
+ throw deploymentFailure("EVE_ORIGIN_UNAVAILABLE", "The authenticated Cloudflare account and workers.dev subdomain were not returned by the read-only resolver.");
991
+ }
992
+ let stableWorkersDevOrigin;
993
+ try {
994
+ const { resolveStableWorkersDevOrigin } = await import("@moinulmoin/eden-runtime-cloudflare");
995
+ stableWorkersDevOrigin = resolveStableWorkersDevOrigin({
996
+ workerName: request.name,
997
+ workersDevSubdomain,
998
+ });
999
+ }
1000
+ catch (error) {
1001
+ throw deploymentFailure("EVE_ORIGIN_UNAVAILABLE", error instanceof Error
1002
+ ? error.message
1003
+ : "The exact workers.dev origin could not be resolved.");
1004
+ }
1005
+ if (cloudflare.stableWorkersDevOrigin !== undefined &&
1006
+ cloudflare.stableWorkersDevOrigin !== stableWorkersDevOrigin) {
1007
+ throw deploymentFailure("EVE_ORIGIN_UNAVAILABLE", "The authenticated stable workers.dev origin did not match the exact Worker target.");
1008
+ }
1009
+ const imageDigest = runtimeEvidence.imageDigest;
1010
+ if (imageDigest === undefined || !/^sha256:[0-9a-f]{64}$/u.test(imageDigest)) {
1011
+ throw deploymentFailure("EVE_IMAGE_IDENTITY_UNAVAILABLE", "The deploy candidate did not provide an immutable runtime image digest.");
1012
+ }
1013
+ const targetKey = stableDeploymentKey(collected.projectId, accountId, request.environment, request.name);
1014
+ let imageReference = options.containerImageReference;
1015
+ if (imageReference !== undefined) {
1016
+ if (imageDigestFromReference(imageReference) !== imageDigest) {
1017
+ throw deploymentFailure("EVE_IMAGE_IDENTITY_MISMATCH", "The exact Container image reference did not match the verified local image digest.");
1018
+ }
1019
+ }
1020
+ else {
1021
+ const localImageReference = runtimeEvidence.imageReference;
1022
+ if (localImageReference === undefined || localImageReference.length === 0) {
1023
+ throw deploymentFailure("EVE_IMAGE_IDENTITY_UNAVAILABLE", "The deploy candidate did not return an exact local image handle for publication.");
1024
+ }
1025
+ const imageRepository = `eden-eve-${targetKey}-${candidate.generationId}`;
1026
+ const imageTag = `${imageRepository}:candidate`;
1027
+ const targetImageReference = `registry.cloudflare.com/${accountId}/${imageRepository}@${imageDigest}`;
1028
+ const imagePublication = await (options.publishImage ??
1029
+ defaultImagePublicationRunner)({
1030
+ accountId,
1031
+ targetImageReference,
1032
+ localImageReference,
1033
+ localImageTag: imageTag,
1034
+ generationRoot: candidate.generationRoot,
1035
+ });
1036
+ if (imagePublication.status === "indeterminate") {
1037
+ await writeEveIndeterminateEvidence(candidate, imagePublication.reason, {
1038
+ accountId,
1039
+ targetKey,
1040
+ imageRepository,
1041
+ imageDigest,
1042
+ });
1043
+ throw deploymentFailure("DEPLOY_INDETERMINATE", imagePublication.reason);
1044
+ }
1045
+ const publishedRepo = imagePublication.imageReference.split("@")[0];
1046
+ const expectedRepo = targetImageReference.split("@")[0];
1047
+ if (publishedRepo !== expectedRepo ||
1048
+ imageDigestFromReference(imagePublication.imageReference) !==
1049
+ imagePublication.imageDigest) {
1050
+ await writeEveIndeterminateEvidence(candidate, "The published image did not match the exact target repository and digest identity.", {
1051
+ accountId,
1052
+ targetKey,
1053
+ imageRepository,
1054
+ imageDigest,
1055
+ });
1056
+ throw deploymentFailure("DEPLOY_INDETERMINATE", "The published image did not match the exact target repository and digest identity.");
1057
+ }
1058
+ imageReference = imagePublication.imageReference;
1059
+ }
1060
+ if (imageReference === undefined) {
1061
+ throw deploymentFailure("EVE_IMAGE_IDENTITY_UNAVAILABLE", "The deploy candidate did not resolve an immutable registry image reference.");
1062
+ }
1063
+ let runtimeInjection;
1064
+ if (collected.runtimeConfig !== undefined) {
1065
+ try {
1066
+ runtimeInjection = await prepareEveRuntimeInjection(collected.runtimeConfig, {
1067
+ mode: "deploy",
1068
+ targetId: targetKey,
1069
+ protectedStore: options.protectedStore ??
1070
+ defaultProtectedStore(request.name),
1071
+ });
1072
+ }
1073
+ catch (error) {
1074
+ const reason = error instanceof Error
1075
+ ? error.message
1076
+ : "protected runtime injection failed before Worker publication";
1077
+ await writeEveIndeterminateEvidence(candidate, reason, {
1078
+ accountId,
1079
+ targetKey,
1080
+ imageReference,
1081
+ imageDigest,
1082
+ });
1083
+ throw deploymentFailure("DEPLOY_INDETERMINATE", reason);
1084
+ }
1085
+ }
1086
+ const deploymentId = `eve-deploy-${randomUUID()}`;
1087
+ const containerApplicationName = boundedResourceName(request.name, "container");
1088
+ const stableContainerInstanceName = boundedResourceName(request.name, "instance");
1089
+ const runtimeVariableNames = candidate.runtimeVariableNames;
1090
+ const identity = {
1091
+ projectId: collected.projectId,
1092
+ sourceDigest: candidate.sourceDigest,
1093
+ generationId: candidate.generationId,
1094
+ deploymentId,
1095
+ environment: request.environment,
1096
+ name: request.name,
1097
+ accountId,
1098
+ workersDevSubdomain,
1099
+ stableWorkersDevOrigin,
1100
+ workerName: request.name,
1101
+ containerApplicationName,
1102
+ stableContainerInstanceName,
1103
+ containerImage: imageReference,
1104
+ runtimeVariableNames,
1105
+ ...(runtimeInjection?.protectedHandle === undefined
1106
+ ? {}
1107
+ : { runtimeRevisionHandle: runtimeInjection.protectedHandle }),
1108
+ };
1109
+ let hostConfig;
1110
+ try {
1111
+ const { createEveHostConfig, } = await import("@moinulmoin/eden-runtime-cloudflare");
1112
+ hostConfig = createEveHostConfig({
1113
+ accountId,
1114
+ workerName: identity.workerName,
1115
+ containerApplicationName: identity.containerApplicationName,
1116
+ containerClassName: "EveHostContainer",
1117
+ containerBindingName: "EVE_CONTAINER",
1118
+ stableContainerInstanceName: identity.stableContainerInstanceName,
1119
+ deploymentId: identity.deploymentId,
1120
+ generationId: identity.generationId,
1121
+ stableWorkersDevOrigin: identity.stableWorkersDevOrigin,
1122
+ containerImage: identity.containerImage,
1123
+ runtimeVariableNames: identity.runtimeVariableNames,
1124
+ ...(identity.runtimeRevisionHandle === undefined
1125
+ ? {}
1126
+ : { runtimeRevisionHandle: identity.runtimeRevisionHandle }),
1127
+ });
1128
+ }
1129
+ catch (error) {
1130
+ throw deploymentFailure("EVE_HOST_CONFIG_INVALID", error instanceof Error
1131
+ ? error.message
1132
+ : "The exact Eve Worker/Container host configuration was invalid.");
1133
+ }
1134
+ const { generateEveHostWorkerSource } = await import("@moinulmoin/eden-runtime-cloudflare");
1135
+ const workerSource = generateEveHostWorkerSource({ config: hostConfig });
1136
+ const paths = await writeEveDeploymentArtifacts(candidate, hostConfig, workerSource);
1137
+ const publicationRequest = {
1138
+ identity,
1139
+ hostConfig,
1140
+ workerSource,
1141
+ ...paths,
1142
+ ...(runtimeInjection === undefined ? {} : { runtimeInjection }),
1143
+ };
1144
+ let publication;
1145
+ try {
1146
+ publication = await (options.publish ?? defaultPublicationRunner())(publicationRequest);
1147
+ }
1148
+ catch {
1149
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "publication-threw-before-terminal-result" });
1150
+ const deployment = deploymentMetadata(identity, targetKey, "indeterminate");
1151
+ return {
1152
+ ...collected.result,
1153
+ ok: false,
1154
+ deployment,
1155
+ };
1156
+ }
1157
+ if (publication.status === "indeterminate") {
1158
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: safeText(publication.reason) });
1159
+ return {
1160
+ ...collected.result,
1161
+ ok: false,
1162
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1163
+ };
1164
+ }
1165
+ if (publication.status === "failed" ||
1166
+ !identityMatches(identity, publication.identity)) {
1167
+ if (publication.status === "failed" &&
1168
+ publication.createdByAttempt === true &&
1169
+ publication.ownershipProven !== true) {
1170
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "publication-created-resource-ownership-unproven" });
1171
+ return {
1172
+ ...collected.result,
1173
+ ok: false,
1174
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1175
+ };
1176
+ }
1177
+ if (publication.status === "failed" &&
1178
+ publication.createdByAttempt === true &&
1179
+ publication.ownershipProven === true &&
1180
+ options.compensate === undefined) {
1181
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "exact-compensation-runner-unavailable" });
1182
+ return {
1183
+ ...collected.result,
1184
+ ok: false,
1185
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1186
+ };
1187
+ }
1188
+ if (publication.status === "failed" &&
1189
+ publication.createdByAttempt === true &&
1190
+ publication.ownershipProven === true &&
1191
+ options.compensate !== undefined) {
1192
+ try {
1193
+ await options.compensate({
1194
+ identity,
1195
+ publication,
1196
+ });
1197
+ }
1198
+ catch {
1199
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "exact-compensation-not-proven" });
1200
+ return {
1201
+ ...collected.result,
1202
+ ok: false,
1203
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1204
+ };
1205
+ }
1206
+ }
1207
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "failed", {
1208
+ evidence: publication.status === "failed"
1209
+ ? safeText(publication.reason)
1210
+ : "publication identity did not match the immutable candidate",
1211
+ });
1212
+ return {
1213
+ ...collected.result,
1214
+ ok: false,
1215
+ deployment: deploymentMetadata(identity, targetKey, "failed"),
1216
+ };
1217
+ }
1218
+ let health;
1219
+ try {
1220
+ health = await (options.health ?? defaultHealthRunner())({
1221
+ identity,
1222
+ origin: stableWorkersDevOrigin,
1223
+ });
1224
+ }
1225
+ catch {
1226
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "health-threw-before-terminal-result" });
1227
+ return {
1228
+ ...collected.result,
1229
+ ok: false,
1230
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1231
+ };
1232
+ }
1233
+ if (health.status === "indeterminate") {
1234
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: safeText(health.reason) });
1235
+ return {
1236
+ ...collected.result,
1237
+ ok: false,
1238
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1239
+ };
1240
+ }
1241
+ const observedHealthIdentity = health.status === "ready"
1242
+ ? {
1243
+ ...publication.identity,
1244
+ ...health.identity,
1245
+ }
1246
+ : undefined;
1247
+ if (health.status === "failed" ||
1248
+ !transportIdentityMatches(identity, observedHealthIdentity)) {
1249
+ if (publication.createdByAttempt === true &&
1250
+ publication.ownershipProven !== true) {
1251
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "health-failure-ownership-unproven" });
1252
+ return {
1253
+ ...collected.result,
1254
+ ok: false,
1255
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1256
+ };
1257
+ }
1258
+ if (publication.createdByAttempt === true &&
1259
+ publication.ownershipProven === true &&
1260
+ options.compensate === undefined) {
1261
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "exact-compensation-runner-unavailable-after-health" });
1262
+ return {
1263
+ ...collected.result,
1264
+ ok: false,
1265
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1266
+ };
1267
+ }
1268
+ if (publication.createdByAttempt === true &&
1269
+ publication.ownershipProven === true &&
1270
+ options.compensate !== undefined) {
1271
+ try {
1272
+ await options.compensate({ identity, publication });
1273
+ }
1274
+ catch {
1275
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "exact-compensation-not-proven-after-health" });
1276
+ return {
1277
+ ...collected.result,
1278
+ ok: false,
1279
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1280
+ };
1281
+ }
1282
+ }
1283
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "failed", {
1284
+ evidence: health.status === "failed"
1285
+ ? safeText(health.reason)
1286
+ : "health identity did not match the immutable candidate",
1287
+ });
1288
+ return {
1289
+ ...collected.result,
1290
+ ok: false,
1291
+ deployment: deploymentMetadata(identity, targetKey, "failed"),
1292
+ };
1293
+ }
1294
+ try {
1295
+ await revalidateEveRuntimeCandidate(candidate);
1296
+ await revalidateEveProjectCandidateInputs(candidate, runtimeConfigExclusion(collected.runtimeConfig));
1297
+ }
1298
+ catch (error) {
1299
+ if (publication.createdByAttempt === true &&
1300
+ publication.ownershipProven === true &&
1301
+ options.compensate !== undefined) {
1302
+ try {
1303
+ await options.compensate({ identity, publication });
1304
+ }
1305
+ catch {
1306
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", { evidence: "post-health-input-race-compensation-unproven" });
1307
+ return {
1308
+ ...collected.result,
1309
+ ok: false,
1310
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1311
+ };
1312
+ }
1313
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "failed", {
1314
+ evidence: error instanceof Error
1315
+ ? safeText(error.message)
1316
+ : "candidate inputs changed after health",
1317
+ });
1318
+ return {
1319
+ ...collected.result,
1320
+ ok: false,
1321
+ deployment: deploymentMetadata(identity, targetKey, "failed"),
1322
+ };
1323
+ }
1324
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "indeterminate", {
1325
+ evidence: error instanceof Error
1326
+ ? safeText(error.message)
1327
+ : "candidate inputs changed after health without exact compensation",
1328
+ });
1329
+ return {
1330
+ ...collected.result,
1331
+ ok: false,
1332
+ deployment: deploymentMetadata(identity, targetKey, "indeterminate"),
1333
+ };
1334
+ }
1335
+ await writeEveDeploymentRecord(candidate, identity, hostConfig, "deployed", {
1336
+ evidence: {
1337
+ publication: "published",
1338
+ health: "ready",
1339
+ identity: "exact",
1340
+ },
1341
+ });
1342
+ await promoteEveTargetPointer(join(request.projectRoot, ".eden", "eve-deploy"), targetKey, candidate.generationRoot);
1343
+ await options.afterPromotion?.();
1344
+ return {
1345
+ ...collected.result,
1346
+ ok: true,
1347
+ deployment: deploymentMetadata(identity, targetKey, "deployed"),
1348
+ };
1349
+ }
1350
+ async function collectEvePreflight(request, options) {
1351
+ let runtimeConfig;
1352
+ const checks = [];
1353
+ try {
1354
+ if (request.envFile === undefined) {
1355
+ checks.push(check("VAL-SEC-001", "skipped", "No explicit --env-file was supplied; no implicit project environment source was read."), check("VAL-SEC-002", "skipped", "No explicit runtime names were supplied; reserved host-name validation was not needed."));
1356
+ }
1357
+ else if (options.runtimeConfigLoader === undefined) {
1358
+ checks.push(check("VAL-SEC-001", "blocked", "The explicit environment path was received, but no deployment-safety runtime-config loader was configured.", "Pass the opaque --env-file path to the deployment-safety runtime-config seam; the control plane never parses its contents."));
1359
+ }
1360
+ else {
1361
+ runtimeConfig = await options.runtimeConfigLoader(request.envFile, request.cwd);
1362
+ checks.push(check("VAL-SEC-001", "passed", "The explicit environment file passed the deployment-safety opaque UTF-8 KEY=VALUE grammar."), check("VAL-SEC-002", "passed", "The explicit environment file contains no reserved Eve host-variable collision."));
1363
+ }
1364
+ }
1365
+ catch (error) {
1366
+ checks.push(check("VAL-SEC-001", "failed", error instanceof EveRuntimeConfigError
1367
+ ? error.message
1368
+ : "The explicit environment file could not be validated safely.", "Fix the explicit environment file through the documented opaque grammar, then retry."), blockedAfterFailure("VAL-SEC-002", "Reserved-name validation was blocked because explicit environment validation failed."), blockedAfterFailure("VAL-CLI-004", "Project and Eve build checks were blocked by explicit environment validation."), blockedAfterFailure("VAL-BUILD-005", "Image, Eve-start, and health checks were blocked by explicit environment validation."), blockedAfterFailure("VAL-CLI-007-CLOUDFLARE-ACCESS", "Cloudflare access checks were blocked before any remote read."), blockedAfterFailure("VAL-CLI-007-TARGET-CONFLICT", "Exact target conflict checks were blocked before any remote read."));
1369
+ return {
1370
+ result: {
1371
+ command: request.command === "deploy" ? "eve deploy" : "eve preflight",
1372
+ ok: false,
1373
+ environment: request.environment,
1374
+ name: request.name,
1375
+ checks,
1376
+ candidate: null,
1377
+ },
1378
+ runtimeConfig,
1379
+ };
1380
+ }
1381
+ const nodeImage = options.nodeImage ?? DEFAULT_EVE_NODE_IMAGE;
1382
+ const artifactRoot = options.artifactRoot ??
1383
+ join(request.projectRoot, ".eden", "eve-deploy", "generations", `preflight-${randomUUID()}`);
1384
+ let packaging;
1385
+ const builder = options.builder ??
1386
+ createDockerEveProjectBuilder({ nodeImage });
1387
+ try {
1388
+ const baseSnapshotOptions = {
1389
+ projectRoot: request.projectRoot,
1390
+ artifactRoot,
1391
+ builder,
1392
+ nodeImage,
1393
+ };
1394
+ const runtimeExclusion = runtimeConfigExclusion(runtimeConfig);
1395
+ packaging = runtimeExclusion === undefined
1396
+ ? await buildEveProjectSnapshot(baseSnapshotOptions)
1397
+ : await buildEveProjectSnapshot({
1398
+ ...baseSnapshotOptions,
1399
+ runtimeConfig: runtimeExclusion,
1400
+ });
1401
+ }
1402
+ catch {
1403
+ packaging = {
1404
+ schemaVersion: 1,
1405
+ worker: "eve-packaging-worker",
1406
+ operation: "local-package",
1407
+ status: "blocked",
1408
+ returnCode: "ROOT_INVALID",
1409
+ deployable: false,
1410
+ project: null,
1411
+ candidate: null,
1412
+ snapshot: null,
1413
+ toolchain: null,
1414
+ image: null,
1415
+ runtime: null,
1416
+ secrets: {
1417
+ runtimeVariableNames: [],
1418
+ valuesRecorded: false,
1419
+ excludedFromSnapshot: true,
1420
+ excludedFromBuildEnvironment: true,
1421
+ excludedFromDockerContext: true,
1422
+ excludedFromImage: true,
1423
+ excludedFromHistory: true,
1424
+ excludedFromManifestsAndLogs: true,
1425
+ redactionRegisteredBeforeChildren: false,
1426
+ },
1427
+ checks: [],
1428
+ candidateImageId: null,
1429
+ candidateImageRetainedLocally: false,
1430
+ writtenPaths: [],
1431
+ error: null,
1432
+ };
1433
+ }
1434
+ checks.push(...packaging.checks.map(mapPackagingCheck));
1435
+ const discardPackagingImage = async () => {
1436
+ if (packaging.candidateImageId === null ||
1437
+ builder.discard === undefined) {
1438
+ return;
1439
+ }
1440
+ const result = {
1441
+ imageId: packaging.candidateImageId,
1442
+ ...(packaging.image?.imageReference === null ||
1443
+ packaging.image?.imageReference === undefined
1444
+ ? {}
1445
+ : { imageReference: packaging.image.imageReference }),
1446
+ ...(packaging.image?.imageDigest === null ||
1447
+ packaging.image?.imageDigest === undefined
1448
+ ? {}
1449
+ : { imageDigest: packaging.image.imageDigest }),
1450
+ imagePlatform: "linux/amd64",
1451
+ };
1452
+ try {
1453
+ await builder.discard(result);
1454
+ }
1455
+ catch {
1456
+ checks.push(check("VAL-CROSS-004", "failed", "The intermediate local Eve image could not be removed with exact identity proof.", "Inspect only the recorded candidate image identity; do not run broad Docker cleanup."));
1457
+ }
1458
+ };
1459
+ if (!packaging.deployable || packaging.candidate === null) {
1460
+ checks.push(blockedAfterFailure("VAL-BUILD-005", "Linux/amd64 image, official Eve-start boot, and real health checks were blocked because no immutable candidate was produced."), blockedAfterFailure("VAL-CLI-007-CLOUDFLARE-ACCESS", "Cloudflare access checks were blocked before any remote read."), blockedAfterFailure("VAL-CLI-007-TARGET-CONFLICT", "Exact target conflict checks were blocked before any remote read."));
1461
+ return {
1462
+ result: {
1463
+ command: request.command === "deploy" ? "eve deploy" : "eve preflight",
1464
+ ok: false,
1465
+ environment: request.environment,
1466
+ name: request.name,
1467
+ checks,
1468
+ candidate: null,
1469
+ },
1470
+ runtimeConfig,
1471
+ };
1472
+ }
1473
+ const candidate = packaging.candidate;
1474
+ let cloudflare;
1475
+ let publicOrigin;
1476
+ if (request.command === "deploy") {
1477
+ try {
1478
+ cloudflare = await readEveCloudflareTarget({
1479
+ projectId: packaging.project?.projectId ?? "unknown-project",
1480
+ sourceDigest: candidate.sourceDigest,
1481
+ environment: request.environment,
1482
+ name: request.name,
1483
+ }, options);
1484
+ }
1485
+ catch {
1486
+ await discardPackagingImage();
1487
+ checks.push(check("VAL-CLI-007-CLOUDFLARE-ACCESS", "failed", "The exact read-only Cloudflare adapter failed without a safe result.", "Retry with an authenticated read-only account, Container, and exact-target adapter; no remote mutation was attempted."), blockedAfterFailure("VAL-CLI-007-TARGET-CONFLICT", "The exact target conflict read was blocked because the read-only Cloudflare adapter failed."));
1488
+ return {
1489
+ result: {
1490
+ command: "eve deploy",
1491
+ ok: false,
1492
+ environment: request.environment,
1493
+ name: request.name,
1494
+ checks,
1495
+ candidate: candidateMetadata(candidate, undefined),
1496
+ },
1497
+ runtimeConfig,
1498
+ };
1499
+ }
1500
+ checks.push(...cloudflareChecks(cloudflare));
1501
+ publicOrigin = await resolvedCloudflareOrigin(cloudflare, request.name);
1502
+ if (publicOrigin === undefined) {
1503
+ checks.push(check("VAL-HOST-006", "failed", "The authenticated Cloudflare read did not prove the exact workers.dev origin before Eve initialization.", "Return one authenticated account ID, one workers.dev subdomain, and the exact Worker-origin binding."));
1504
+ }
1505
+ if (!allChecksClear(checks)) {
1506
+ await discardPackagingImage();
1507
+ return {
1508
+ result: {
1509
+ command: "eve deploy",
1510
+ ok: false,
1511
+ environment: request.environment,
1512
+ name: request.name,
1513
+ checks,
1514
+ candidate: candidateMetadata(candidate, undefined),
1515
+ },
1516
+ runtimeConfig,
1517
+ };
1518
+ }
1519
+ }
1520
+ let hostRequirements;
1521
+ let hostRequirementsValid = false;
1522
+ try {
1523
+ if (options.hostRequirements !== undefined) {
1524
+ hostRequirements = typeof options.hostRequirements === "function"
1525
+ ? await options.hostRequirements(candidate)
1526
+ : options.hostRequirements;
1527
+ }
1528
+ }
1529
+ catch {
1530
+ checks.push(check("VAL-BUILD-007", "failed", "The Eve host-capability adapter failed without a verified result.", "Return an explicit provider-neutral Linux/amd64, World, sandbox, process, network, and disposable-storage result."));
1531
+ }
1532
+ if (hostRequirements === undefined) {
1533
+ checks.push(check("VAL-BUILD-007", "blocked", "Eve host capabilities were not proven for this preflight invocation.", "Provide an explicit host-capability result; unknown World, sandbox, architecture, device, kernel, network, or durable-storage requirements fail closed."));
1534
+ }
1535
+ else {
1536
+ try {
1537
+ validateEveHostRequirements(hostRequirements);
1538
+ hostRequirementsValid = true;
1539
+ }
1540
+ catch (error) {
1541
+ checks.push(check("VAL-BUILD-007", "failed", error instanceof Error
1542
+ ? error.message
1543
+ : "The Eve host-capability result was not supported by the hosting contract.", "Use only the documented Linux/amd64, disposable-process, outbound-network, sandbox, World, and non-durable-storage capabilities."));
1544
+ hostRequirements = undefined;
1545
+ }
1546
+ }
1547
+ let runtimeEvidence;
1548
+ let runtimeInjection;
1549
+ if (hostRequirements !== undefined && hostRequirementsValid) {
1550
+ try {
1551
+ if (runtimeConfig !== undefined && request.command === "preflight") {
1552
+ runtimeInjection = await prepareEveRuntimeInjection(runtimeConfig, {
1553
+ mode: "preflight",
1554
+ });
1555
+ }
1556
+ const runtimeRunner = options.runtimeRunner ?? defaultRuntimeRunner;
1557
+ runtimeEvidence = await runtimeRunner({
1558
+ candidate,
1559
+ nodeImage,
1560
+ healthPort: options.healthPort ?? await findAvailableEveHealthPort(),
1561
+ hostRequirements,
1562
+ ...(publicOrigin === undefined ? {} : { publicOrigin }),
1563
+ retainImage: request.command === "deploy",
1564
+ ...(runtimeInjection === undefined ? {} : { runtimeInjection }),
1565
+ });
1566
+ checks.push(...runtimeEvidence.checks);
1567
+ const requiredRuntimeChecks = [
1568
+ "VAL-BUILD-005",
1569
+ "VAL-BUILD-006",
1570
+ "VAL-BUILD-007",
1571
+ ];
1572
+ const runtimeProofComplete = requiredRuntimeChecks.every((id) => runtimeEvidence?.checks.some((value) => value.id === id && value.status === "passed"));
1573
+ const runtimeImageIdentityValid = /^sha256:[0-9a-f]{64}$/u.test(runtimeEvidence.imageDigest ?? "");
1574
+ if (!runtimeProofComplete) {
1575
+ checks.push(check("VAL-BUILD-005", "failed", "The runtime seam did not return complete proof of Linux/amd64 image construction, official Eve-start boot, and real health.", "Return passed VAL-BUILD-005, VAL-BUILD-006, and VAL-BUILD-007 checks from the disposable runtime runner."));
1576
+ }
1577
+ if (!runtimeImageIdentityValid) {
1578
+ checks.push(check("VAL-BUILD-005", "failed", "The runtime seam did not return an exact immutable Linux/amd64 image digest.", "Return the verified sha256 image identity from the disposable runtime runner."));
1579
+ }
1580
+ if (!runtimeEvidence.ok && runtimeProofComplete) {
1581
+ checks.push(check("VAL-BUILD-005", "failed", "The local Eve runtime runner did not prove a deployable Linux/amd64 candidate.", "Inspect the project-local Eve start supervisor, sandbox prewarm, Workflow World startup, and real health route."));
1582
+ }
1583
+ if (!runtimeEvidence.cleanup.bootContainerRemoved ||
1584
+ (request.command === "preflight" &&
1585
+ runtimeEvidence.cleanup.imageRetained) ||
1586
+ runtimeEvidence.cleanup.imageIdentity !== "exact" ||
1587
+ !runtimeEvidence.cleanup.verified) {
1588
+ checks.push(check("VAL-CROSS-004", "failed", "The disposable Eve runtime did not return verified exact cleanup evidence.", "Remove and verify only the task-owned runtime image and boot container before retrying; never use broad Docker cleanup."));
1589
+ }
1590
+ await revalidateEveRuntimeCandidate(candidate);
1591
+ await revalidateEveProjectCandidateInputs(candidate, runtimeConfigExclusion(runtimeConfig));
1592
+ }
1593
+ catch (error) {
1594
+ checks.push(check(error instanceof EveRuntimeConfigError
1595
+ ? "VAL-SEC-003"
1596
+ : error instanceof EvePackagingError && error.code === "SOURCE_RACE"
1597
+ ? "VAL-CROSS-004"
1598
+ : "VAL-BUILD-005", "failed", error instanceof Error
1599
+ ? error.message
1600
+ : "The local Linux/amd64 Eve runtime candidate failed without a safe diagnostic.", "Inspect the owned candidate and retry after fixing the project-local Eve start, sandbox, World, and health path."));
1601
+ }
1602
+ }
1603
+ else {
1604
+ checks.push(blockedAfterFailure("VAL-BUILD-005", "Image, Eve-start, and real health checks were blocked because host capability was not proven."));
1605
+ }
1606
+ const candidateResult = candidateMetadata(candidate, runtimeEvidence?.imageDigest);
1607
+ if (!allChecksClear(checks)) {
1608
+ await discardPackagingImage();
1609
+ checks.push(blockedAfterFailure("VAL-CLI-007-CLOUDFLARE-ACCESS", "Cloudflare access checks were blocked because local Eve candidate checks did not complete successfully."), blockedAfterFailure("VAL-CLI-007-TARGET-CONFLICT", "Exact target conflict checks were blocked because local Eve candidate checks did not complete successfully."));
1610
+ return {
1611
+ result: {
1612
+ command: request.command === "deploy" ? "eve deploy" : "eve preflight",
1613
+ ok: false,
1614
+ environment: request.environment,
1615
+ name: request.name,
1616
+ checks,
1617
+ candidate: candidateResult,
1618
+ },
1619
+ runtimeConfig,
1620
+ };
1621
+ }
1622
+ if (cloudflare === undefined) {
1623
+ try {
1624
+ cloudflare = await readEveCloudflareTarget({
1625
+ projectId: packaging.project?.projectId ?? "unknown-project",
1626
+ sourceDigest: candidate.sourceDigest,
1627
+ environment: request.environment,
1628
+ name: request.name,
1629
+ }, options);
1630
+ }
1631
+ catch {
1632
+ await discardPackagingImage();
1633
+ checks.push(check("VAL-CLI-007-CLOUDFLARE-ACCESS", "failed", "The exact read-only Cloudflare adapter failed without a safe result.", "Retry with an authenticated read-only account, Container, and exact-target adapter; no remote mutation was attempted."), blockedAfterFailure("VAL-CLI-007-TARGET-CONFLICT", "The exact target conflict read was blocked because the read-only Cloudflare adapter failed."));
1634
+ return {
1635
+ result: {
1636
+ command: "eve preflight",
1637
+ ok: false,
1638
+ environment: request.environment,
1639
+ name: request.name,
1640
+ checks,
1641
+ candidate: candidateResult,
1642
+ },
1643
+ runtimeConfig,
1644
+ };
1645
+ }
1646
+ checks.push(...cloudflareChecks(cloudflare));
1647
+ }
1648
+ await discardPackagingImage();
1649
+ return {
1650
+ result: {
1651
+ command: request.command === "deploy" ? "eve deploy" : "eve preflight",
1652
+ ok: allChecksClear(checks),
1653
+ environment: request.environment,
1654
+ name: request.name,
1655
+ checks,
1656
+ candidate: candidateResult,
1657
+ },
1658
+ runtimeConfig,
1659
+ candidate,
1660
+ ...(packaging.project?.projectId === undefined
1661
+ ? {}
1662
+ : { projectId: packaging.project.projectId }),
1663
+ ...(runtimeEvidence === undefined ? {} : { runtimeEvidence }),
1664
+ cloudflare,
1665
+ };
1666
+ }
1667
+ export async function runEveControlPlane(request, options = {}) {
1668
+ const lock = request.command === "deploy"
1669
+ ? await acquireEveTargetLock(request.projectRoot, request.environment, request.name)
1670
+ : undefined;
1671
+ let collected;
1672
+ let primaryError;
1673
+ let failed = false;
1674
+ let lockReleased = true;
1675
+ try {
1676
+ collected = await collectEvePreflight(request, options);
1677
+ if (!collected.result.ok) {
1678
+ (options.stdout ?? (() => undefined))(redactEveRuntimeOutput(JSON.stringify(collected.result)));
1679
+ throw new EveCliError({
1680
+ code: request.command === "deploy"
1681
+ ? "EVE_DEPLOY_CHECKS_FAILED"
1682
+ : "EVE_PREFLIGHT_FAILED",
1683
+ message: request.command === "deploy"
1684
+ ? "The inline Eve deploy checks failed; no remote mutation was attempted."
1685
+ : "The Eve preflight checks failed; no remote mutation or active-state promotion was attempted.",
1686
+ });
1687
+ }
1688
+ if (request.command === "preflight") {
1689
+ (options.stdout ?? (() => undefined))(redactEveRuntimeOutput(JSON.stringify(collected.result)));
1690
+ }
1691
+ else {
1692
+ const deploymentResult = await runEveDeployment(request, options, collected);
1693
+ (options.stdout ?? (() => undefined))(redactEveRuntimeOutput(JSON.stringify(deploymentResult)));
1694
+ if (!deploymentResult.ok) {
1695
+ const status = deploymentResult.deployment?.status;
1696
+ throw new EveCliError({
1697
+ code: status === "indeterminate"
1698
+ ? "DEPLOY_INDETERMINATE"
1699
+ : "EVE_DEPLOYMENT_FAILED",
1700
+ message: status === "indeterminate"
1701
+ ? "The Eve deployment outcome is indeterminate; inspect the retained exact ownership evidence before retrying."
1702
+ : "The Eve deployment failed before exact target promotion.",
1703
+ });
1704
+ }
1705
+ }
1706
+ }
1707
+ catch (error) {
1708
+ failed = true;
1709
+ primaryError = error;
1710
+ }
1711
+ finally {
1712
+ collected?.runtimeConfig?.dispose();
1713
+ lockReleased = lock === undefined || await releaseEveTargetLock(lock);
1714
+ }
1715
+ if (!lockReleased) {
1716
+ throw new EveCliError({
1717
+ code: "EVE_DEPLOY_LOCK_RELEASE_UNPROVEN",
1718
+ message: "The Eve deployment lock could not be released with exact ownership proof; local residue was retained.",
1719
+ source: "deployment-lock",
1720
+ });
1721
+ }
1722
+ if (failed) {
1723
+ throw primaryError;
1724
+ }
1725
+ }
1726
+ async function readEveDestroyRecord(projectRoot, environment, name) {
1727
+ const targetsRoot = join(projectRoot, ".eden", "eve-deploy", "targets", `${environment}-${name}`);
1728
+ const current = await lstat(join(targetsRoot, "CURRENT")).catch(() => undefined);
1729
+ if (current === undefined || !current.isSymbolicLink()) {
1730
+ return readEveDestroyRecordFromGenerations(projectRoot, environment, name);
1731
+ }
1732
+ const generationRoot = await realpath(join(targetsRoot, "CURRENT")).catch(() => undefined);
1733
+ if (generationRoot === undefined) {
1734
+ return readEveDestroyRecordFromGenerations(projectRoot, environment, name);
1735
+ }
1736
+ const parsed = await parseEveDestroyRecord(join(generationRoot, "deployment.json"), environment, name);
1737
+ return parsed === undefined
1738
+ ? undefined
1739
+ : { ...parsed, generationRoot };
1740
+ }
1741
+ async function readEveDestroyRecordFromGenerations(projectRoot, environment, name) {
1742
+ const generationsRoot = join(projectRoot, ".eden", "eve-deploy", "generations");
1743
+ const entries = await readdir(generationsRoot).catch(() => []);
1744
+ const withRecords = [];
1745
+ for (const entry of entries) {
1746
+ const generationRoot = join(generationsRoot, entry);
1747
+ const details = await lstat(generationRoot).catch(() => undefined);
1748
+ if (details === undefined || !details.isDirectory())
1749
+ continue;
1750
+ const recordDetails = await lstat(join(generationRoot, "deployment.json")).catch(() => undefined);
1751
+ if (recordDetails !== undefined && recordDetails.isFile()) {
1752
+ withRecords.push({
1753
+ generationRoot,
1754
+ modifiedAt: recordDetails.mtimeMs,
1755
+ });
1756
+ }
1757
+ }
1758
+ withRecords.sort((left, right) => right.modifiedAt - left.modifiedAt);
1759
+ for (const { generationRoot } of withRecords) {
1760
+ const parsed = await parseEveDestroyRecord(join(generationRoot, "deployment.json"), environment, name);
1761
+ if (parsed !== undefined) {
1762
+ return { ...parsed, generationRoot };
1763
+ }
1764
+ }
1765
+ return undefined;
1766
+ }
1767
+ async function parseEveDestroyRecord(recordPath, environment, name) {
1768
+ let raw;
1769
+ try {
1770
+ raw = await readFile(recordPath, "utf8");
1771
+ }
1772
+ catch {
1773
+ return undefined;
1774
+ }
1775
+ let parsed;
1776
+ try {
1777
+ parsed = JSON.parse(raw);
1778
+ }
1779
+ catch {
1780
+ return undefined;
1781
+ }
1782
+ if (typeof parsed !== "object" || parsed === null)
1783
+ return undefined;
1784
+ const record = parsed;
1785
+ if (record.status !== undefined && typeof record.status !== "string") {
1786
+ return undefined;
1787
+ }
1788
+ const identity = record.identity ?? {};
1789
+ const required = [
1790
+ "workerName",
1791
+ "containerApplicationName",
1792
+ "stableContainerInstanceName",
1793
+ "accountId",
1794
+ "environment",
1795
+ "name",
1796
+ ];
1797
+ for (const key of required) {
1798
+ if (typeof identity[key] !== "string" || identity[key].length === 0) {
1799
+ return undefined;
1800
+ }
1801
+ }
1802
+ if (identity.environment !== environment || identity.name !== name) {
1803
+ return undefined;
1804
+ }
1805
+ return {
1806
+ recordPath,
1807
+ identity: identity,
1808
+ };
1809
+ }
1810
+ async function defaultDestroyTargetRead(request) {
1811
+ const account = await readWranglerJson(["whoami", "--json"]);
1812
+ const deployments = await readWranglerJson([
1813
+ "deployments",
1814
+ "list",
1815
+ "--name",
1816
+ request.workerName,
1817
+ "--json",
1818
+ ]);
1819
+ const containers = await readWranglerJson([
1820
+ "containers",
1821
+ "list",
1822
+ "--json",
1823
+ "--per-page",
1824
+ "100",
1825
+ ]);
1826
+ const accountId = authenticatedAccountId(account.value);
1827
+ const workerExists = !deployments.failed &&
1828
+ (exactDeploymentEntries(deployments.value)?.length ?? 0) > 0;
1829
+ const entries = exactContainerEntries(containers.value, request.containerApplicationName);
1830
+ const firstContainer = entries === undefined ? undefined : entries[0];
1831
+ return {
1832
+ workerExists,
1833
+ ...(firstContainer === undefined
1834
+ ? {}
1835
+ : { containerApplicationId: firstContainer.id }),
1836
+ ...(accountId === undefined ? {} : { accountId }),
1837
+ };
1838
+ }
1839
+ async function defaultWorkerDelete(request) {
1840
+ const result = await runWranglerWithInput(["delete", "--name", request.name, "--force"], process.cwd(), "y\n");
1841
+ if (result.exitCode === 0)
1842
+ return "deleted";
1843
+ if (/(?:does not exist|not found|10007)/iu.test(result.stderr)) {
1844
+ return "absent";
1845
+ }
1846
+ return "indeterminate";
1847
+ }
1848
+ async function defaultContainerDelete(request) {
1849
+ const result = await runWranglerWithInput(["containers", "delete", request.applicationId], process.cwd());
1850
+ if (result.exitCode === 0)
1851
+ return "deleted";
1852
+ if (/(?:does not exist|not found|not supported|10007)/iu.test(result.stderr)) {
1853
+ return "absent";
1854
+ }
1855
+ return "indeterminate";
1856
+ }
1857
+ async function verifyEveAbsence(request, options) {
1858
+ const reader = options.destroyCloudflareRead ?? defaultDestroyTargetRead;
1859
+ const observed = await reader({
1860
+ workerName: request.workerName,
1861
+ containerApplicationName: request.containerApplicationName,
1862
+ });
1863
+ return !observed.workerExists &&
1864
+ observed.containerApplicationId === undefined;
1865
+ }
1866
+ export async function runEveDestroy(request, options = {}) {
1867
+ const checks = [];
1868
+ const emit = (outcome) => {
1869
+ (options.stdout ?? (() => undefined))(redactEveRuntimeOutput(JSON.stringify(outcome)));
1870
+ };
1871
+ const fail = (code, message) => {
1872
+ throw new EveCliError({ code, message, source: "eve destroy" });
1873
+ };
1874
+ let lockReleased = false;
1875
+ try {
1876
+ const lock = await acquireEveTargetLock(request.projectRoot, request.environment, request.name);
1877
+ try {
1878
+ await runEveDestroyLocked(request, options, checks, emit, fail);
1879
+ }
1880
+ finally {
1881
+ lockReleased = await releaseEveTargetLock(lock);
1882
+ }
1883
+ }
1884
+ catch (error) {
1885
+ if (error instanceof EveCliError)
1886
+ throw error;
1887
+ if (error instanceof EveRuntimeConfigError)
1888
+ throw error;
1889
+ throw new EveCliError({
1890
+ code: "EVE_DESTROY_FAILED",
1891
+ message: "The eve destroy operation failed.",
1892
+ source: "eve destroy",
1893
+ });
1894
+ }
1895
+ if (!lockReleased) {
1896
+ fail("EVE_DEPLOY_LOCK_RELEASE_UNPROVEN", "The Eve destroy lock could not be released with exact ownership proof; local residue was retained.");
1897
+ }
1898
+ }
1899
+ async function runEveDestroyLocked(request, options, checks, emit, fail) {
1900
+ const found = await readEveDestroyRecord(request.projectRoot, request.environment, request.name);
1901
+ if (found === undefined) {
1902
+ fail("EVE_DESTROY_RECORD_UNPROVEN", "No immutable deployed record matched the exact target; destroy refuses to guess or broaden cleanup.");
1903
+ }
1904
+ const record = found;
1905
+ const expectedWorker = record.identity.workerName;
1906
+ const expectedContainer = record.identity.containerApplicationName;
1907
+ if (expectedWorker !== request.name ||
1908
+ typeof record.identity.accountId !== "string") {
1909
+ fail("EVE_DESTROY_RECORD_MISMATCH", "The immutable deployment record does not match the selected target.");
1910
+ }
1911
+ checks.push(check("VAL-LIFE-006-RECORD", "passed", "The immutable deployment record matched the exact target selectors."));
1912
+ const reader = options.destroyCloudflareRead ?? defaultDestroyTargetRead;
1913
+ const before = await reader({
1914
+ workerName: expectedWorker,
1915
+ containerApplicationName: expectedContainer,
1916
+ });
1917
+ if (before.accountId !== record.identity.accountId) {
1918
+ fail("EVE_DESTROY_OWNERSHIP_UNPROVEN", "The authenticated account does not own the recorded deployment account.");
1919
+ }
1920
+ if (!before.workerExists && before.containerApplicationId === undefined) {
1921
+ emit({
1922
+ ok: true,
1923
+ status: "absent",
1924
+ environment: request.environment,
1925
+ name: request.name,
1926
+ checks: [
1927
+ ...checks,
1928
+ check("VAL-LIFE-006", "passed", "The exact target is already absent; destroy is idempotent without touching siblings."),
1929
+ ],
1930
+ });
1931
+ return;
1932
+ }
1933
+ const deleteWorker = options.deleteWorker ?? defaultWorkerDelete;
1934
+ if (before.workerExists) {
1935
+ const workerResult = await deleteWorker({ name: expectedWorker });
1936
+ if (workerResult === "indeterminate") {
1937
+ emit({
1938
+ ok: false,
1939
+ status: "indeterminate",
1940
+ environment: request.environment,
1941
+ name: request.name,
1942
+ checks: [
1943
+ ...checks,
1944
+ check("VAL-LIFE-006", "failed", "The exact Worker deletion did not complete with a terminal result; no broad cleanup was attempted.", "Inspect the retained deployment record and Cloudflare inventory, then retry the exact target."),
1945
+ ],
1946
+ });
1947
+ fail("EVE_DESTROY_INDETERMINATE", "The Worker deletion outcome was indeterminate.");
1948
+ }
1949
+ checks.push(check("VAL-LIFE-006-WORKER", "passed", workerResult === "deleted"
1950
+ ? "The exact owned Worker was deleted."
1951
+ : "The exact Worker was already absent."));
1952
+ }
1953
+ const deleteContainer = options.deleteContainer ?? defaultContainerDelete;
1954
+ if (before.containerApplicationId !== undefined) {
1955
+ const containerResult = await deleteContainer({
1956
+ applicationId: before.containerApplicationId,
1957
+ });
1958
+ if (containerResult === "indeterminate") {
1959
+ emit({
1960
+ ok: false,
1961
+ status: "indeterminate",
1962
+ environment: request.environment,
1963
+ name: request.name,
1964
+ checks: [
1965
+ ...checks,
1966
+ check("VAL-LIFE-006", "failed", "The exact Container application deletion did not complete with a terminal result; no broad cleanup was attempted.", "Inspect the retained deployment record and Cloudflare inventory, then retry the exact target."),
1967
+ ],
1968
+ });
1969
+ fail("EVE_DESTROY_INDETERMINATE", "The Container deletion outcome was indeterminate.");
1970
+ }
1971
+ checks.push(check("VAL-LIFE-006-CONTAINER", "passed", containerResult === "deleted"
1972
+ ? "The exact owned Container application was deleted."
1973
+ : "The exact Container application was already absent."));
1974
+ }
1975
+ const absent = await verifyEveAbsence({
1976
+ workerName: expectedWorker,
1977
+ containerApplicationName: expectedContainer,
1978
+ }, options);
1979
+ if (!absent) {
1980
+ emit({
1981
+ ok: false,
1982
+ status: "failed",
1983
+ environment: request.environment,
1984
+ name: request.name,
1985
+ checks: [
1986
+ ...checks,
1987
+ check("VAL-LIFE-006", "failed", "Bounded absence verification failed; CURRENT remains unchanged and no broad delete was attempted.", "Inspect the exact target inventory, then retry destroy after the provider state settles."),
1988
+ ],
1989
+ });
1990
+ fail("EVE_DESTROY_ABSENCE_UNPROVEN", "The exact target could not be proven absent after deletion.");
1991
+ }
1992
+ checks.push(check("VAL-LIFE-006", "passed", "Exact absence was verified; clearing this target's CURRENT pointer only."));
1993
+ const currentPath = join(request.projectRoot, ".eden", "eve-deploy", "targets", `${request.environment}-${request.name}`, "CURRENT");
1994
+ await rm(currentPath, { force: true });
1995
+ const gone = await lstat(currentPath).catch(() => undefined);
1996
+ if (gone !== undefined) {
1997
+ fail("EVE_DESTROY_POINTER_UNCLEARED", "The target CURRENT pointer could not be cleared after verified absence.");
1998
+ }
1999
+ emit({
2000
+ ok: true,
2001
+ status: "destroyed",
2002
+ environment: request.environment,
2003
+ name: request.name,
2004
+ checks,
2005
+ });
2006
+ }
2007
+ //# sourceMappingURL=eve-control-plane.js.map