effect-ci 0.0.0-stage → 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,1978 @@
1
+ import {
2
+ ApprovalError,
3
+ CommandCheckpointError,
4
+ CommandError,
5
+ CommandExecutionError,
6
+ RollbackError,
7
+ SecretError,
8
+ VitePlusAvailable,
9
+ WorkflowPlanError,
10
+ Workspace,
11
+ formatPlan,
12
+ fromPackageJson,
13
+ isAction,
14
+ parallel,
15
+ runPromise,
16
+ workflow
17
+ } from "./chunk-X4HGOXPL.js";
18
+ import {
19
+ decodeCommandDiagnostics
20
+ } from "./chunk-WGBTI7DS.js";
21
+ import "./chunk-MZ5FQEN6.js";
22
+ import "./chunk-U3DVQKHN.js";
23
+ import "./chunk-WOG7K3QJ.js";
24
+
25
+ // ../cli/src/workload-auth.ts
26
+ var hasWorkloadIdentity = () => !!process.env.EFFECT_CI_OIDC_TOKEN || !!(process.env.ACTIONS_ID_TOKEN_REQUEST_URL && process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN);
27
+ var workloadToken = async (service) => {
28
+ const origin = new URL(service).origin;
29
+ if (process.env.EFFECT_CI_OIDC_TOKEN) return process.env.EFFECT_CI_OIDC_TOKEN;
30
+ if (!process.env.ACTIONS_ID_TOKEN_REQUEST_URL || !process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) {
31
+ throw new Error("Run in the hosted Effect CI runner or GitHub Actions with permissions: id-token: write");
32
+ }
33
+ const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL);
34
+ url.searchParams.set("audience", origin);
35
+ const response = await fetch(url, {
36
+ headers: { authorization: `Bearer ${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` },
37
+ redirect: "error",
38
+ signal: AbortSignal.timeout(15e3)
39
+ });
40
+ if (!response.ok) throw new Error("GitHub OIDC identity request failed");
41
+ const { value } = await response.json();
42
+ if (typeof value !== "string" || !value || /[\r\n]/.test(value)) throw new Error("Invalid workload identity");
43
+ return value;
44
+ };
45
+ var workloadHeaders = async (service) => new Headers({
46
+ "content-type": "application/json",
47
+ authorization: `Bearer ${await workloadToken(service)}`
48
+ });
49
+
50
+ // ../cli/src/oidc.ts
51
+ import { spawn, execFileSync as execFileSync2 } from "node:child_process";
52
+ import { appendFileSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
53
+ import { dirname, join as join2 } from "node:path";
54
+ import { parseArgs } from "node:util";
55
+
56
+ // ../cli/src/remote-protocol.ts
57
+ var remoteOrigin = (origin) => {
58
+ const url = new URL(origin);
59
+ const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
60
+ if (url.username || url.password || url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
61
+ throw new Error("Remote service must use HTTPS (HTTP is allowed only for local development)");
62
+ }
63
+ return url.href.replace(/\/$/, "");
64
+ };
65
+ var remoteEventUrl = (origin, eventsUrl) => {
66
+ const base = new URL(origin);
67
+ const events = new URL(eventsUrl, base);
68
+ if (events.origin !== base.origin || events.username || events.password) {
69
+ throw new Error("Remote event stream must use the configured service origin");
70
+ }
71
+ return events.href;
72
+ };
73
+ async function* remoteRecords(body) {
74
+ const reader = body.getReader();
75
+ const decoder = new TextDecoder();
76
+ let buffer = "";
77
+ try {
78
+ while (true) {
79
+ const chunk = await reader.read();
80
+ buffer += decoder.decode(chunk.value, { stream: !chunk.done });
81
+ const lines = buffer.split("\n");
82
+ buffer = lines.pop() ?? "";
83
+ for (const line of lines) if (line.trim()) yield JSON.parse(line);
84
+ if (chunk.done) {
85
+ if (buffer.trim()) yield JSON.parse(buffer);
86
+ break;
87
+ }
88
+ }
89
+ } finally {
90
+ await reader.cancel().catch(() => {
91
+ });
92
+ reader.releaseLock();
93
+ }
94
+ }
95
+
96
+ // ../cli/src/remote-auth.ts
97
+ import { execFileSync } from "node:child_process";
98
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
99
+ import { homedir } from "node:os";
100
+ import { join } from "node:path";
101
+ var remoteProfilePath = () => process.env.EFFECT_CI_REMOTE_PROFILE || join(homedir(), ".config", "effect-ci", "remotes.json");
102
+ var readRemoteProfile = (repository, path = remoteProfilePath()) => {
103
+ if (!existsSync(path)) return void 0;
104
+ const file = lstatSync(path);
105
+ if (!file.isFile() || file.isSymbolicLink() || file.size > 65536 || process.platform !== "win32" && ((file.mode & 63) !== 0 || file.uid !== process.getuid?.())) {
106
+ throw new Error("Effect CI remote profile must be a private, user-owned file (mode 600)");
107
+ }
108
+ const value = JSON.parse(readFileSync(path, "utf8"));
109
+ if (value.version !== 1 || !Array.isArray(value.remotes) || value.remotes.length > 32) {
110
+ throw new Error("Invalid Effect CI remote profile");
111
+ }
112
+ const normalize = (repo) => repo.replace(/\.git$/, "");
113
+ const matches = value.remotes.filter((entry2) => typeof entry2.repository === "string" && normalize(entry2.repository) === normalize(repository));
114
+ if (matches.length > 1) throw new Error("Ambiguous Effect CI remote profile");
115
+ const entry = matches[0];
116
+ if (!entry) return void 0;
117
+ if (typeof entry.url !== "string" || typeof entry.token !== "string" || !entry.token || entry.token.length > 8192 || /[\r\n]/.test(entry.token)) {
118
+ throw new Error("Invalid Effect CI remote profile");
119
+ }
120
+ return { url: remoteOrigin(entry.url), token: entry.token };
121
+ };
122
+ var jwt = /^[\w-]+\.[\w-]+\.[\w-]+$/;
123
+ var accessEnvironment = () => {
124
+ const allowed = ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"];
125
+ return Object.fromEntries(allowed.filter((key) => process.env[key] !== void 0).map((key) => [key, process.env[key]]));
126
+ };
127
+ var readAccessToken = (origin, exec = (file, args) => execFileSync(file, args, {
128
+ encoding: "utf8",
129
+ timeout: 15e3,
130
+ maxBuffer: 65536,
131
+ stdio: ["ignore", "pipe", "pipe"],
132
+ env: accessEnvironment()
133
+ })) => {
134
+ const attempts = [
135
+ ["cf", ["access", "token", origin, "--quiet"]],
136
+ ["cloudflared", ["access", "token", "--app", origin]]
137
+ ];
138
+ let failure;
139
+ for (const [file, args] of attempts) {
140
+ try {
141
+ const token = exec(file, args).split(/\r?\n/).map((line) => line.trim()).find((line) => jwt.test(line));
142
+ if (token) return token;
143
+ } catch (error) {
144
+ failure = error;
145
+ }
146
+ }
147
+ throw failure ?? new Error("No Access token");
148
+ };
149
+ var cachedAccessToken = (url, read = readAccessToken) => {
150
+ const origin = new URL(remoteOrigin(url));
151
+ if (origin.protocol !== "https:") return void 0;
152
+ try {
153
+ const token = read(origin.origin).trim();
154
+ return token.length <= 32768 && jwt.test(token) ? token : void 0;
155
+ } catch {
156
+ return void 0;
157
+ }
158
+ };
159
+
160
+ // ../cli/src/oidc.ts
161
+ var repositoryName = (remote) => {
162
+ const match = remote.match(/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/);
163
+ if (!match) throw new Error("OIDC setup requires a GitHub remote.origin.url");
164
+ return match[1];
165
+ };
166
+ var runOidc = async (args, cwd, headers, host) => {
167
+ const separator = args.indexOf("--");
168
+ const command = separator < 0 ? [] : args.slice(separator + 1);
169
+ const { values: values2 } = parseArgs({ args: separator < 0 ? args : args.slice(0, separator), options: {
170
+ service: { type: "string" },
171
+ worker: { type: "string" },
172
+ scopes: { type: "string", default: "workers:edit" },
173
+ help: { type: "boolean", short: "h" }
174
+ } });
175
+ if (values2.help) {
176
+ console.log(`effect-ci oidc [--service https://your-ci-host] Enable this repository through Access
177
+ effect-ci oidc -- <deploy command> Deploy using temporary credentials`);
178
+ return;
179
+ }
180
+ const root = execFileSync2("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8" }).trim();
181
+ const path = join2(root, ".cloudflare", "ci", "oidc.json");
182
+ const saved = existsSync2(path) ? JSON.parse(readFileSync2(path, "utf8")) : void 0;
183
+ const configured = values2.service ?? (process.env.EFFECT_CI_REMOTE_URL || host) ?? saved?.issuer;
184
+ if (!configured) throw new Error(`Set EFFECT_CI_REMOTE_URL or use effect-ci oidc --service https://your-ci-host`);
185
+ const issuer = remoteOrigin(configured);
186
+ if (new URL(issuer).pathname !== "/") throw new Error("OIDC service must be an HTTPS origin without a path");
187
+ if (separator < 0) {
188
+ const repository = repositoryName(execFileSync2("git", ["config", "--get", "remote.origin.url"], { cwd: root, encoding: "utf8" }).trim());
189
+ const workload = hasWorkloadIdentity();
190
+ if (!workload && process.env.GITHUB_ACTIONS === "true") throw new Error("GitHub Actions OIDC requires permissions: id-token: write");
191
+ if (!workload && !headers.has("cf-access-token") && !headers.has("cf-access-client-id")) {
192
+ try {
193
+ headers.set("cf-access-token", readAccessToken(issuer));
194
+ } catch {
195
+ throw new Error(`Sign into Cloudflare Access with effect-ci login ${issuer}, or set CF_ACCESS_TOKEN / CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET`);
196
+ }
197
+ }
198
+ const response2 = await fetch(`${issuer}${workload ? "/api" : ""}/oidc/repositories`, {
199
+ method: "POST",
200
+ headers: workload ? await workloadHeaders(issuer) : headers,
201
+ redirect: "manual",
202
+ signal: AbortSignal.timeout(3e4),
203
+ body: JSON.stringify({ repository })
204
+ });
205
+ if (!response2.ok) throw new Error(`Could not enable OIDC (${response2.status}). Check Access, the GitHub App installation, and the hosted issuer configuration.`);
206
+ const result = await response2.json();
207
+ if (result.enabled !== true || result.issuer !== issuer || result.repository.toLowerCase() !== repository.toLowerCase()) throw new Error("Invalid OIDC setup response");
208
+ if (workload) {
209
+ if (process.env.GITHUB_ACTIONS === "true" && process.env.GITHUB_ENV) appendFileSync(process.env.GITHUB_ENV, `EFFECT_CI_REMOTE_URL=${issuer}
210
+ `);
211
+ console.log(`OIDC enabled for ${result.repository}. The checkout was not modified.`);
212
+ return;
213
+ }
214
+ mkdirSync(dirname(path), { recursive: true });
215
+ writeFileSync(path, JSON.stringify({ issuer, repository: result.repository }, null, 2) + "\n");
216
+ console.log(`OIDC enabled for ${result.repository}. Commit .cloudflare/ci/oidc.json, then use effect-ci oidc -- <deploy command>.`);
217
+ return;
218
+ }
219
+ if (!command.length) throw new Error("Provide a deploy command after --");
220
+ if (new URL(issuer).protocol !== "https:") throw new Error("Workload credential exchange requires HTTPS");
221
+ const identity = await workloadToken(issuer);
222
+ const response = await fetch(`${issuer}/token`, {
223
+ method: "POST",
224
+ redirect: "error",
225
+ signal: AbortSignal.timeout(3e4),
226
+ headers: { authorization: `Bearer ${identity}`, "content-type": "application/json" },
227
+ body: JSON.stringify({ worker: values2.worker ?? "*", scopes: values2.scopes.split(/\s+/).filter(Boolean) })
228
+ });
229
+ if (!response.ok) throw new Error(`OIDC exchange rejected (${response.status}); enable this repository with effect-ci oidc first`);
230
+ const credential = await response.json();
231
+ if (!credential.token || /[\r\n]/.test(credential.token) || !credential.receipt || /[\r\n]/.test(credential.receipt) || !/^[a-f0-9]{32}$/.test(credential.accountId)) {
232
+ throw new Error("Invalid credential service response");
233
+ }
234
+ if (process.env.GITHUB_ACTIONS === "true") {
235
+ for (const secret of [credential.token, credential.receipt]) console.log(`::add-mask::${secret.replaceAll("%", "%25")}`);
236
+ }
237
+ try {
238
+ const env = { ...process.env, CLOUDFLARE_API_TOKEN: credential.token, CLOUDFLARE_ACCOUNT_ID: credential.accountId };
239
+ delete env.EFFECT_CI_OIDC_TOKEN;
240
+ process.exitCode = await new Promise((resolve3, reject) => {
241
+ const child = spawn(command[0], command.slice(1), { cwd, env, stdio: "inherit" });
242
+ child.on("error", reject);
243
+ child.on("exit", (code) => resolve3(code ?? 1));
244
+ });
245
+ } finally {
246
+ const revoked = await fetch(`${issuer}/revoke`, { method: "POST", headers: { authorization: `Bearer ${credential.receipt}` }, redirect: "error", signal: AbortSignal.timeout(15e3) });
247
+ if (!revoked.ok) throw new Error("Token revocation failed; the token will expire after 15 minutes");
248
+ }
249
+ };
250
+
251
+ // ../cli/src/push.ts
252
+ import { execFileSync as execFileSync3, spawnSync } from "node:child_process";
253
+ var artifactsRemote = /^https:\/\/[a-f0-9]{32}\.artifacts\.cloudflare\.net\/git\/([a-z0-9][a-z0-9_-]{0,62})\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99}?)\.git$/;
254
+ var hasGitRemote = (root, name) => {
255
+ try {
256
+ execFileSync3("git", ["remote", "get-url", name], { cwd: root, stdio: "ignore" });
257
+ return true;
258
+ } catch {
259
+ return false;
260
+ }
261
+ };
262
+ var artifactsTarget = (root, name) => {
263
+ let remote;
264
+ try {
265
+ remote = execFileSync3("git", ["remote", "get-url", name], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
266
+ } catch {
267
+ return void 0;
268
+ }
269
+ const match = artifactsRemote.exec(remote);
270
+ return match ? { remote, namespace: match[1], repo: match[2] } : void 0;
271
+ };
272
+ var artifactsRunId = (repo, revision) => `artifacts-${repo.replace(/[^A-Za-z0-9_-]/g, "-").slice(0, 48)}-${revision}`;
273
+ var artifactsPushToken = (target) => {
274
+ if (process.env.EFFECT_CI_ARTIFACTS_TOKEN) return process.env.EFFECT_CI_ARTIFACTS_TOKEN;
275
+ const output = execFileSync3("cf", [
276
+ "artifacts",
277
+ "namespaces",
278
+ "tokens",
279
+ "create",
280
+ target.namespace,
281
+ "--repo",
282
+ target.repo,
283
+ "--scope",
284
+ "write",
285
+ "--ttl",
286
+ "600"
287
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"] });
288
+ const token = JSON.parse(output).plaintext;
289
+ if (typeof token !== "string" || !token) throw new Error("cf did not return an Artifacts token");
290
+ return token;
291
+ };
292
+ var cf = (...args) => JSON.parse(execFileSync3("cf", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }));
293
+ var setupArtifactsRemote = (root, name, repo, host, branch, log) => {
294
+ let remote;
295
+ try {
296
+ remote = cf("artifacts", "namespaces", "repos", "get", repo, "--namespace", host.namespace).remote;
297
+ } catch {
298
+ remote = cf("artifacts", "namespaces", "repos", "create", host.namespace, "--name", repo, "--default-branch", branch).remote;
299
+ log(`Created Artifacts repository ${host.namespace}/${repo}`);
300
+ }
301
+ const queue = cf("queues", "list").find((entry) => entry.queue_name === host.queue);
302
+ if (!queue) throw new Error(`Queue ${host.queue} not found; deploy the host first`);
303
+ const subscription = `${host.queue}-${repo}`.slice(0, 64);
304
+ const listed = cf("queues", "subscriptions", "list");
305
+ const existing = (Array.isArray(listed) ? listed : listed.result ?? []).some((entry) => entry.name === subscription);
306
+ if (!existing) {
307
+ cf("queues", "subscriptions", "create", "--body", JSON.stringify({
308
+ name: subscription,
309
+ enabled: true,
310
+ events: ["pushed"],
311
+ source: { type: "artifacts.repo", namespace: host.namespace, repo_name: repo },
312
+ destination: { type: "queues.queue", queue_id: queue.queue_id }
313
+ }));
314
+ log(`Subscribed ${host.namespace}/${repo} pushes to ${host.queue}`);
315
+ }
316
+ execFileSync3("git", ["remote", "add", name, remote], { cwd: root });
317
+ log(`Added Git remote ${name} \u2192 ${remote}`);
318
+ const match = artifactsRemote.exec(remote);
319
+ if (!match) throw new Error("Artifacts returned an unexpected remote URL");
320
+ return { remote, namespace: match[1], repo: match[2] };
321
+ };
322
+ var pushToArtifacts = (root, target, refspecs, token, quiet = false) => spawnSync("git", ["push", ...quiet ? ["--quiet"] : [], target.remote, ...[refspecs].flat()], {
323
+ cwd: root,
324
+ stdio: ["ignore", quiet ? "ignore" : "inherit", quiet ? "ignore" : "inherit"],
325
+ env: {
326
+ ...process.env,
327
+ GIT_CONFIG_COUNT: "1",
328
+ GIT_CONFIG_KEY_0: "http.extraHeader",
329
+ GIT_CONFIG_VALUE_0: `Authorization: Bearer ${token}`,
330
+ GIT_TERMINAL_PROMPT: "0"
331
+ }
332
+ }).status ?? 1;
333
+
334
+ // ../cli/src/vite-plus.ts
335
+ import { execFileSync as execFileSync4 } from "node:child_process";
336
+ var vitePlusTasks = (root) => {
337
+ const output = execFileSync4(process.execPath, ["--input-type=module", "-e", `
338
+ const { loadConfigFromFile } = await import("vite-plus")
339
+ const loaded = await loadConfigFromFile({ command: "build", mode: "production" }, undefined, process.cwd(), "silent")
340
+ const config = loaded?.config ?? {}
341
+ if (config.tasks) throw new Error("Vite+ tasks belong under run.tasks in vite.config.ts, not top-level tasks")
342
+ const { readFileSync } = await import("node:fs")
343
+ const packageName = JSON.parse(readFileSync("package.json", "utf8")).name
344
+ const tasks = config.run?.tasks ?? {}
345
+ for (const [name, task] of Object.entries(tasks)) {
346
+ if (task && typeof task === "object" && "dependencies" in task)
347
+ throw new Error("Vite+ task " + name + " uses dependencies; use dependsOn instead")
348
+ }
349
+ const dependencies = Object.fromEntries(Object.entries(tasks).map(([name, task]) => [name,
350
+ (task?.dependsOn ?? []).filter(dependency => typeof dependency === "string" &&
351
+ (!dependency.includes("#") || dependency.startsWith(packageName + "#")))
352
+ .map(dependency => dependency.includes("#") ? dependency.slice(packageName.length + 1) : dependency)
353
+ ]))
354
+ console.log("\\nEFFECT_CI_VITE_TASKS=" + JSON.stringify({ names: Object.keys(tasks), dependencies }))
355
+ `], {
356
+ cwd: root,
357
+ encoding: "utf8",
358
+ // Vite+'s metadata flag skips lazy plugin factories only in this child.
359
+ env: { ...process.env, VP_RESOLVING_CONFIG_METADATA: "1" },
360
+ timeout: 3e4,
361
+ maxBuffer: 1048576
362
+ });
363
+ const result = output.split("\n").reverse().find((line) => line.startsWith("EFFECT_CI_VITE_TASKS="));
364
+ if (!result) throw new Error("Vite+ did not return task metadata");
365
+ return JSON.parse(result.slice("EFFECT_CI_VITE_TASKS=".length));
366
+ };
367
+ var vitePlusAvailable = (cwd) => {
368
+ try {
369
+ execFileSync4("sh", ["-c", 'PATH="$PATH:$PWD/node_modules/.bin"; command -v vp'], { cwd, stdio: "ignore" });
370
+ return true;
371
+ } catch {
372
+ return false;
373
+ }
374
+ };
375
+
376
+ // ../cli/src/index.ts
377
+ import { existsSync as existsSync6, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, realpathSync, writeFileSync as writeFileSync3 } from "node:fs";
378
+ import { execFileSync as execFileSync5 } from "node:child_process";
379
+ import { basename, dirname as dirname4, join as join6, relative, resolve as resolve2 } from "node:path";
380
+ import { pathToFileURL } from "node:url";
381
+ import { parseArgs as parseArgs2, parseEnv as parseEnv3 } from "node:util";
382
+
383
+ // ../cli/src/project-env.ts
384
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
385
+ import { dirname as dirname2, join as join3, resolve } from "node:path";
386
+ import { parseEnv } from "node:util";
387
+ function projectEnvironment(cwd) {
388
+ const directories = [];
389
+ for (let directory = resolve(cwd); ; directory = dirname2(directory)) {
390
+ directories.unshift(directory);
391
+ if (existsSync3(join3(directory, ".git")) || dirname2(directory) === directory) break;
392
+ }
393
+ const settings = {};
394
+ for (const directory of directories) {
395
+ for (const name of [".env", ".env.local"]) {
396
+ const path = join3(directory, name);
397
+ if (existsSync3(path)) Object.assign(settings, parseEnv(readFileSync3(path, "utf8")));
398
+ }
399
+ }
400
+ if (settings.EFFECT_CI_PUBLIC_URL) settings.EFFECT_CI_REMOTE_URL ??= settings.EFFECT_CI_PUBLIC_URL;
401
+ if (settings.EFFECT_CI_API_TOKEN) settings.EFFECT_CI_REMOTE_TOKEN ??= settings.EFFECT_CI_API_TOKEN;
402
+ return settings;
403
+ }
404
+
405
+ // ../cli/src/index.ts
406
+ import { determineAgent } from "@vercel/detect-agent";
407
+ import * as Effect2 from "effect/Effect";
408
+ import * as Logger from "effect/Logger";
409
+ import { CurrentLogAnnotations, MinimumLogLevel } from "effect/References";
410
+ import * as Schema from "effect/Schema";
411
+
412
+ // ../cloudflare-dynamic-worker/src/project-service.ts
413
+ import * as Context from "effect/Context";
414
+ var ProjectChecks = class extends Context.Service()("@effect-ci-testbed/ProjectChecks") {
415
+ };
416
+
417
+ // ../cloudflare-dynamic-worker/src/local.ts
418
+ import { fileURLToPath } from "node:url";
419
+ import * as Effect from "effect/Effect";
420
+
421
+ // ../cloudflare-dynamic-worker/src/project-protocol.ts
422
+ var projectPolicy = Object.freeze({
423
+ compatibilityDate: "2026-10-07",
424
+ cpuMs: 50,
425
+ subRequests: 0,
426
+ maxModules: 16,
427
+ maxSourceBytes: 64 * 1024,
428
+ maxChecks: 16,
429
+ maxResponseBytes: 4096,
430
+ timeoutMs: 5e3
431
+ });
432
+ var encoder = new TextEncoder();
433
+ var validModule = (path) => /^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*\.js$/.test(path);
434
+ function validateProject(request) {
435
+ const entries2 = Object.entries(request.modules);
436
+ if (!validModule(request.mainModule) || entries2.length === 0 || entries2.length > projectPolicy.maxModules || !Object.hasOwn(request.modules, request.mainModule)) throw new Error("Invalid project module manifest");
437
+ let size = 0;
438
+ const modules = /* @__PURE__ */ Object.create(null);
439
+ for (const [path, source] of entries2) {
440
+ if (!validModule(path) || typeof source !== "string") throw new Error("Invalid project module manifest");
441
+ size += encoder.encode(source).byteLength;
442
+ if (size > projectPolicy.maxSourceBytes) throw new Error("Project source exceeds limit");
443
+ modules[path] = source;
444
+ }
445
+ if (request.checks.length === 0 || request.checks.length > projectPolicy.maxChecks) throw new Error("Invalid project assertions");
446
+ const names = /* @__PURE__ */ new Set();
447
+ const checks = request.checks.map((check) => {
448
+ if (!/^[a-zA-Z0-9 -]{1,64}$/.test(check.name) || names.has(check.name) || !/^\/[a-zA-Z0-9/_-]*$/.test(check.path) || !Number.isInteger(check.status) || check.status < 200 || check.status > 599 || typeof check.body !== "string" || encoder.encode(check.body).byteLength > projectPolicy.maxResponseBytes) throw new Error("Invalid project assertions");
449
+ names.add(check.name);
450
+ return { ...check };
451
+ });
452
+ return { mainModule: request.mainModule, modules, checks };
453
+ }
454
+
455
+ // ../cloudflare-dynamic-worker/src/local.ts
456
+ var LocalIsolateUnavailable = class extends Error {
457
+ code = "CI_LOCAL_ISOLATE_UNAVAILABLE";
458
+ constructor() {
459
+ super("Local project checks require workerd with WorkerLoader and loopback access. Install the locked workspace dependencies and allow local loopback; project modules will never fall back to Node execution.");
460
+ }
461
+ };
462
+ var startBridge = async () => {
463
+ let runtime;
464
+ try {
465
+ const esbuild = import("esbuild");
466
+ const { Miniflare, Log, LogLevel } = await import("miniflare");
467
+ const { build } = await esbuild;
468
+ const bundle = await build({
469
+ entryPoints: [fileURLToPath(new URL("./local-bridge.js", import.meta.url))],
470
+ bundle: true,
471
+ write: false,
472
+ format: "esm",
473
+ platform: "neutral",
474
+ conditions: ["workerd", "import"],
475
+ external: ["node:*", "cloudflare:workers", "cloudflare:workflows"],
476
+ logLevel: "silent"
477
+ });
478
+ const contents = bundle.outputFiles[0]?.text;
479
+ if (!contents) throw new Error("Missing trusted bridge bundle");
480
+ const engine = new Miniflare({
481
+ log: new Log(LogLevel.NONE),
482
+ // Runtime console events bypass Miniflare's Log level. Never promote
483
+ // untrusted module logs into CLI JSON, host diagnostics or agent instructions.
484
+ handleStructuredLogs: () => {
485
+ },
486
+ workers: [{ config: {
487
+ name: "effect-ci-local-project",
488
+ compatibilityDate: "2026-10-07",
489
+ compatibilityFlags: ["nodejs_compat"],
490
+ env: { LOADER: { type: "worker-loader" } },
491
+ manifest: { mainModule: "bridge.js", modules: { "bridge.js": { type: "esm", contents } } }
492
+ } }]
493
+ });
494
+ runtime = engine;
495
+ const health = await engine.dispatchFetch("https://local-project.invalid/ready");
496
+ if (health.status !== 200 || await health.text() !== "ready") throw new Error("Unsupported WorkerLoader capability");
497
+ return { request: (body) => engine.dispatchFetch("https://local-project.invalid/check", { method: "POST", body }), dispose: () => engine.dispose() };
498
+ } catch {
499
+ await runtime?.dispose().catch(() => {
500
+ });
501
+ throw new LocalIsolateUnavailable();
502
+ }
503
+ };
504
+ function makeLocalProjectChecks(options = {}) {
505
+ let started, disposal, closed = false;
506
+ const dispose = () => {
507
+ closed = true;
508
+ return disposal ??= started ? started.then((bridge) => bridge.dispose(), () => {
509
+ }) : Promise.resolve();
510
+ };
511
+ const service = { run: (input) => Effect.tryPromise({ try: async () => {
512
+ if (closed) throw new Error("Local isolate scope is closed");
513
+ const request = validateProject(input);
514
+ started ??= (options.start ?? startBridge)().catch(() => {
515
+ throw new LocalIsolateUnavailable();
516
+ });
517
+ const bridge = await started;
518
+ const passed = [];
519
+ for (const check of request.checks) {
520
+ let timer, timedOut = false;
521
+ try {
522
+ const result = await Promise.race([
523
+ (async () => {
524
+ const response = await bridge.request(JSON.stringify({ ...request, checks: [check] })), text = await response.text();
525
+ if (text.length > 4096) throw new Error("Invalid local isolate response");
526
+ const value = JSON.parse(text);
527
+ if (!value || typeof value !== "object") throw new Error("Invalid local isolate response");
528
+ const result2 = value;
529
+ if (response.status !== 200) throw new Error(result2.error === `Project check failed: ${check.name}` ? result2.error : "Isolated project assertions failed");
530
+ if (result2.runtime !== "dynamic-worker" || result2.containers !== 0 || JSON.stringify(result2.passed) !== JSON.stringify([check.name])) throw new Error("Invalid local isolate proof");
531
+ return check.name;
532
+ })(),
533
+ new Promise((_, reject) => {
534
+ timer = setTimeout(() => {
535
+ timedOut = true;
536
+ reject(new Error(`Local project check timed out: ${check.name}; workerd scope terminated`));
537
+ }, projectPolicy.timeoutMs + 1e3);
538
+ })
539
+ ]);
540
+ passed.push(result);
541
+ } catch (error) {
542
+ if (timedOut) await dispose();
543
+ throw error;
544
+ } finally {
545
+ if (timer !== void 0) clearTimeout(timer);
546
+ }
547
+ }
548
+ return { runtime: "dynamic-worker", containers: 0, passed };
549
+ }, catch: (error) => error }) };
550
+ return { service, dispose };
551
+ }
552
+
553
+ // ../cli/src/login.ts
554
+ import { spawnSync as spawnSync2 } from "node:child_process";
555
+ import { chmodSync, existsSync as existsSync4, lstatSync as lstatSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "node:fs";
556
+ import { homedir as homedir2 } from "node:os";
557
+ import { dirname as dirname3, join as join4 } from "node:path";
558
+ var userConfigPath = () => process.env.EFFECT_CI_CONFIG || join4(homedir2(), ".config", "effect-ci", "config.json");
559
+ var readUserConfig = (path = userConfigPath()) => {
560
+ if (!existsSync4(path)) return {};
561
+ const file = lstatSync2(path);
562
+ if (!file.isFile() || file.isSymbolicLink() || file.size > 8192) throw new Error(`Invalid Effect CI config: ${path}`);
563
+ const value = JSON.parse(readFileSync4(path, "utf8"));
564
+ if (value.version !== 1) throw new Error(`Invalid Effect CI config: ${path}`);
565
+ return typeof value.remoteUrl === "string" ? { remoteUrl: remoteOrigin(value.remoteUrl) } : {};
566
+ };
567
+ var writeUserConfig = (config, path = userConfigPath()) => {
568
+ mkdirSync2(dirname3(path), { recursive: true, mode: 448 });
569
+ writeFileSync2(path, JSON.stringify({ version: 1, remoteUrl: remoteOrigin(config.remoteUrl) }, null, 2) + "\n", { mode: 384 });
570
+ chmodSync(path, 384);
571
+ };
572
+ var interactive = (file, args) => spawnSync2(file, args, { stdio: "inherit" });
573
+ var accessLogin = (origin, run = interactive) => {
574
+ const cf2 = run("cf", ["access", "login", origin]);
575
+ if (!cf2.error) {
576
+ if (cf2.status === 0) return "cf";
577
+ throw new Error(`cf access login ${origin} failed`);
578
+ }
579
+ const cloudflared = run("cloudflared", ["access", "login", origin]);
580
+ if (!cloudflared.error && cloudflared.status === 0) return "cloudflared";
581
+ throw new Error(cloudflared.error ? "Install the Cloudflare CLI (npm i -g cf) or cloudflared to sign in to Cloudflare Access" : `cloudflared access login ${origin} failed`);
582
+ };
583
+ var runLogin = async (args, deps = {}) => {
584
+ const log = deps.log ?? console.log;
585
+ if (args.includes("--help") || args.includes("-h")) {
586
+ log(`effect-ci login [url] Sign in to an Effect CI host protected by Cloudflare Access
587
+
588
+ The URL defaults to EFFECT_CI_REMOTE_URL (shell, .env, .env.local) or the last login.
589
+ Uses \`cf access login\` (falls back to cloudflared). Agents can skip the browser by
590
+ setting CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET (an Access service token).`);
591
+ return;
592
+ }
593
+ const positional = args.filter((arg) => !arg.startsWith("-"));
594
+ if (positional.length > 1) throw new Error("Use effect-ci login [url]");
595
+ const configured = positional[0] ?? process.env.EFFECT_CI_REMOTE_URL ?? readUserConfig(deps.configPath).remoteUrl;
596
+ if (!configured) throw new Error("Use effect-ci login https://your-effect-ci-host");
597
+ const url = remoteOrigin(configured);
598
+ const origin = new URL(url).origin;
599
+ const service = Boolean(process.env.CF_ACCESS_CLIENT_ID && process.env.CF_ACCESS_CLIENT_SECRET);
600
+ const headers = new Headers();
601
+ if (service) {
602
+ headers.set("cf-access-client-id", process.env.CF_ACCESS_CLIENT_ID);
603
+ headers.set("cf-access-client-secret", process.env.CF_ACCESS_CLIENT_SECRET);
604
+ log(`Using the Access service token from CF_ACCESS_CLIENT_ID for ${origin}`);
605
+ } else if (new URL(url).protocol === "https:") {
606
+ const tool = (deps.login ?? accessLogin)(origin);
607
+ const token = (deps.token ?? cachedAccessToken)(url);
608
+ if (!token) throw new Error(`Signed in with ${tool}, but no Access token was found for ${origin}`);
609
+ headers.set("cf-access-token", token);
610
+ }
611
+ const response = await (deps.fetch ?? fetch)(new URL("capabilities", url + "/"), {
612
+ headers,
613
+ redirect: "manual",
614
+ signal: AbortSignal.timeout(15e3)
615
+ }).catch((error) => {
616
+ throw new Error(`Could not reach ${origin} (${error instanceof Error ? error.message : String(error)})`);
617
+ });
618
+ writeUserConfig({ remoteUrl: url }, deps.configPath);
619
+ log(`Saved ${url} to ${deps.configPath ?? userConfigPath()}`);
620
+ if (response.ok) {
621
+ log(`Signed in to ${origin}. Next: effect-ci push`);
622
+ return;
623
+ }
624
+ throw new Error(response.status >= 300 && response.status < 400 ? `${origin} redirected to a login page; the Access session or service token was not accepted` : `${origin} answered ${response.status}; check its Access policy${service ? " allows this service token" : ""}`);
625
+ };
626
+
627
+ // ../cli/src/remote-config.ts
628
+ import { existsSync as existsSync5, lstatSync as lstatSync3, readFileSync as readFileSync5 } from "node:fs";
629
+ import { join as join5 } from "node:path";
630
+ import { parseEnv as parseEnv2 } from "node:util";
631
+ var readProjectRemote = (root) => {
632
+ const read = (name) => {
633
+ const path = join5(root, name);
634
+ if (!existsSync5(path)) return {};
635
+ const stat = lstatSync3(path);
636
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536)
637
+ throw new Error("Invalid remote configuration file");
638
+ const values2 = parseEnv2(readFileSync5(path, "utf8"));
639
+ return values2;
640
+ };
641
+ const shared = read(".env"), local = read(".env.local");
642
+ const oidc = readProjectOidc(root);
643
+ const url = local.EFFECT_CI_REMOTE_URL || shared.EFFECT_CI_REMOTE_URL || (typeof oidc?.issuer === "string" ? oidc.issuer : void 0);
644
+ return { ...url ? { url: remoteOrigin(url) } : {} };
645
+ };
646
+ var resolveRemote = (environment, profile, project, user) => {
647
+ const configured = environment.EFFECT_CI_REMOTE_URL || profile?.url || project?.url || user?.remoteUrl;
648
+ const url = configured ? remoteOrigin(configured) : void 0;
649
+ const token = environment.EFFECT_CI_REMOTE_TOKEN || (url && profile && remoteOrigin(profile.url) === url ? profile.token : void 0);
650
+ return { url, token };
651
+ };
652
+ var readProjectOidc = (root) => {
653
+ const path = join5(root, ".cloudflare/ci/oidc.json");
654
+ if (!existsSync5(path)) return void 0;
655
+ const file = lstatSync3(path);
656
+ if (!file.isFile() || file.isSymbolicLink() || file.size > 8192) throw new Error("Invalid OIDC configuration file");
657
+ return JSON.parse(readFileSync5(path, "utf8"));
658
+ };
659
+
660
+ // ../cli/src/remote-diagnostics.ts
661
+ var remoteErrorMessage = (message) => {
662
+ const d = decodeCommandDiagnostics(message);
663
+ if (!d) return message;
664
+ const output = [
665
+ d.output.stdout ? `stdout:
666
+ ${d.output.stdout.trimEnd()}` : "",
667
+ d.output.stderr ? `stderr:
668
+ ${d.output.stderr.trimEnd()}` : ""
669
+ ].filter(Boolean).join("\n");
670
+ return `Command failed (${d.exitCode}): ${d.command}${output ? `
671
+ ${output}` : ""}${d.output.truncated ? "\n[diagnostics truncated]" : ""}`;
672
+ };
673
+ var remoteCommandDiagnostics = (events) => {
674
+ const seen = /* @__PURE__ */ new Set();
675
+ const out = [];
676
+ for (const e of events) {
677
+ const d = decodeCommandDiagnostics(e.error?.message);
678
+ if (!d) continue;
679
+ const { version: _, ...details } = d;
680
+ const key = JSON.stringify(details);
681
+ if (!seen.has(key)) {
682
+ seen.add(key);
683
+ out.push(details);
684
+ }
685
+ if (out.length === 16) break;
686
+ }
687
+ return out;
688
+ };
689
+
690
+ // ../cli/src/source-comparison.ts
691
+ var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
692
+ var sha = (value) => typeof value === "string" && /^[a-f0-9]{40}$/.test(value) && !/^0+$/.test(value);
693
+ function githubSourceComparison(type, payload, revision) {
694
+ const event = record(payload);
695
+ if (type === "push" && sha(event.before) && sha(event.after) && (!revision || revision === event.after))
696
+ return { base: event.before, head: event.after };
697
+ if (type === "merge_group") {
698
+ const group = record(event.merge_group);
699
+ if (sha(group.base_sha) && sha(group.head_sha) && (!revision || revision === group.head_sha))
700
+ return { base: group.base_sha, head: group.head_sha };
701
+ }
702
+ if (type === "pull_request") {
703
+ const pr = record(event.pull_request), base = record(pr.base).sha, head = record(pr.head).sha;
704
+ if (!sha(base) || !sha(head)) return;
705
+ if (!revision || revision === head) return { base, head, mergeBase: true };
706
+ if (sha(pr.merge_commit_sha) && revision === pr.merge_commit_sha)
707
+ return { base, head: revision };
708
+ }
709
+ }
710
+
711
+ // ../cli/src/plan.ts
712
+ import * as Graph from "effect/Graph";
713
+ var toPlanGraph = (plan) => Graph.directed((graph) => {
714
+ const indices = /* @__PURE__ */ new Map();
715
+ for (const node of plan.nodes) {
716
+ if (indices.has(node.id)) throw new WorkflowPlanError(`Duplicate workflow node: ${node.id}`);
717
+ indices.set(node.id, Graph.addNode(graph, node));
718
+ }
719
+ const connect = (source, target, kind) => {
720
+ const sourceIndex = indices.get(source);
721
+ const targetIndex = indices.get(target);
722
+ if (sourceIndex === void 0 || targetIndex === void 0) {
723
+ throw new WorkflowPlanError(`Unknown workflow node: ${sourceIndex === void 0 ? source : target}`);
724
+ }
725
+ Graph.addEdge(graph, sourceIndex, targetIndex, kind);
726
+ };
727
+ for (const node of plan.nodes) {
728
+ for (const dependency of node.dependencies) connect(dependency, node.id, "dependency");
729
+ for (const predecessor of node.after) connect(predecessor, node.id, "after");
730
+ if (node.rollbackFor) connect(node.rollbackFor, node.id, "rollback");
731
+ }
732
+ });
733
+ var planNodeLabel = (node) => {
734
+ const qualifiers = [
735
+ node.optional ? "optional" : void 0,
736
+ node.condition ? "conditional" : void 0
737
+ ].filter((value) => value !== void 0);
738
+ return qualifiers.length > 0 ? `${node.id} (${qualifiers.join(", ")})` : node.id;
739
+ };
740
+ var formatPlanDot = (plan) => Graph.toGraphViz(toPlanGraph(plan), {
741
+ graphName: plan.workflowId,
742
+ nodeLabel: planNodeLabel,
743
+ edgeLabel: (kind) => kind
744
+ });
745
+ var formatPlanMermaid = (plan) => {
746
+ const graph = toPlanGraph(plan);
747
+ const ids = /* @__PURE__ */ new Map();
748
+ const used = /* @__PURE__ */ new Set();
749
+ const lines = ["flowchart LR"];
750
+ for (const [index, node] of Graph.entries(Graph.nodes(graph))) {
751
+ let id = `step_${node.id.replaceAll(/[^a-zA-Z0-9_]/g, "_")}`;
752
+ while (used.has(id)) id += `_${index}`;
753
+ used.add(id);
754
+ ids.set(index, id);
755
+ lines.push(` ${id}[${JSON.stringify(planNodeLabel(node))}]`);
756
+ }
757
+ for (const edge of Graph.values(Graph.edges(graph))) {
758
+ const arrow = edge.data === "dependency" ? "-->" : edge.data === "after" ? "-.->" : "-. rollback .->";
759
+ lines.push(` ${ids.get(edge.source)} ${arrow} ${ids.get(edge.target)}`);
760
+ }
761
+ return lines.join("\n");
762
+ };
763
+
764
+ // ../cli/src/index.ts
765
+ var ExitCode = {
766
+ success: 0,
767
+ workflowFailure: 1,
768
+ usage: 2,
769
+ providerUnavailable: 3,
770
+ approval: 4
771
+ };
772
+ var CliFailure = class extends Error {
773
+ code;
774
+ exitCode;
775
+ details;
776
+ constructor(code, exitCode, message, details) {
777
+ super(message);
778
+ this.code = code;
779
+ this.exitCode = exitCode;
780
+ this.details = details;
781
+ }
782
+ };
783
+ var actionTargets = (actions) => Object.fromEntries(
784
+ Object.entries(actions ?? {}).filter(
785
+ (entry) => isAction(entry[1])
786
+ )
787
+ );
788
+ var agentEnvironment = await determineAgent().catch(() => ({ isAgent: false }));
789
+ var detectedFormat = () => {
790
+ try {
791
+ return agentEnvironment.isAgent ? "json" : "text";
792
+ } catch {
793
+ return "text";
794
+ }
795
+ };
796
+ var remoteHeaders = (url, token) => {
797
+ const headers = new Headers({ "content-type": "application/json" });
798
+ if (process.env.EFFECT_CI_REMOTE_TOKEN || token) {
799
+ headers.set("authorization", `Bearer ${process.env.EFFECT_CI_REMOTE_TOKEN || token}`);
800
+ }
801
+ if (process.env.CF_ACCESS_TOKEN) {
802
+ headers.set("cf-access-token", process.env.CF_ACCESS_TOKEN);
803
+ } else if (process.env.CF_ACCESS_CLIENT_ID && process.env.CF_ACCESS_CLIENT_SECRET) {
804
+ headers.set("cf-access-client-id", process.env.CF_ACCESS_CLIENT_ID);
805
+ headers.set("cf-access-client-secret", process.env.CF_ACCESS_CLIENT_SECRET);
806
+ } else {
807
+ const access = cachedAccessToken(url);
808
+ if (access) headers.set("cf-access-token", access);
809
+ }
810
+ return headers;
811
+ };
812
+ var git = (root, ...args) => execFileSync5("git", args, { cwd: root, encoding: "utf8" }).trim();
813
+ var gitOptional = (root, ...args) => {
814
+ try {
815
+ return git(root, ...args);
816
+ } catch {
817
+ return void 0;
818
+ }
819
+ };
820
+ var cloneUrl = (value) => {
821
+ const githubSsh = value.match(/^git@github\.com:(.+)$/);
822
+ return githubSsh ? `https://github.com/${githubSsh[1]}` : value;
823
+ };
824
+ var describeEvent = (event) => {
825
+ const errorMessage = remoteErrorMessage(event.error?.message);
826
+ switch (event.type) {
827
+ case "step_completed": {
828
+ let value = event.output;
829
+ if (typeof value === "string") {
830
+ try {
831
+ value = JSON.parse(value);
832
+ } catch {
833
+ }
834
+ }
835
+ const output = value && typeof value === "object" ? value : void 0;
836
+ let stdout = typeof output?.stdout === "string" ? output.stdout.trimEnd() : "";
837
+ if (stdout) {
838
+ try {
839
+ const result = JSON.parse(stdout);
840
+ if (result?.schemaVersion === 1 && result.ok === true && result.plan)
841
+ stdout = formatPlan(result.plan);
842
+ } catch {
843
+ }
844
+ }
845
+ const stderr = typeof output?.stderr === "string" ? output.stderr.trimEnd() : "";
846
+ const logs = [stdout, stderr].filter(Boolean).join("\n");
847
+ return logs;
848
+ }
849
+ case "workflow_completed":
850
+ return "\u2713 Workflow completed";
851
+ case "workflow_errored":
852
+ return `\u2717 Workflow failed${errorMessage ? `: ${errorMessage}` : ""}`;
853
+ case "workflow_terminated":
854
+ return "\u2717 Workflow terminated";
855
+ default:
856
+ return "";
857
+ }
858
+ };
859
+ var streamRemoteEvents = async (response, format, events, cursor) => {
860
+ if (!response.ok || !response.body) {
861
+ throw new CliFailure(
862
+ "CI_REMOTE_FAILED",
863
+ ExitCode.providerUnavailable,
864
+ `Could not follow the remote run (${response.status}): ${await response.text()}`
865
+ );
866
+ }
867
+ for await (const record2 of remoteRecords(response.body)) {
868
+ const event = record2;
869
+ if (typeof event.eventId === "number" && Number.isSafeInteger(event.eventId) && event.eventId >= 0) {
870
+ if (cursor.value !== void 0 && event.eventId <= cursor.value) continue;
871
+ cursor.value = event.eventId;
872
+ }
873
+ events.push(event);
874
+ if (format === "text") {
875
+ const text = describeEvent(event);
876
+ if (text) console.log(text);
877
+ }
878
+ if (["workflow_completed", "workflow_errored", "workflow_terminated"].includes(event.type)) break;
879
+ }
880
+ return events;
881
+ };
882
+ var remoteConnection = (root) => {
883
+ const configuredRepository = gitOptional(root, "config", "--get", "remote.origin.url");
884
+ const profile = configuredRepository ? readRemoteProfile(cloneUrl(configuredRepository)) : void 0;
885
+ const configured = resolveRemote(process.env, profile, readProjectRemote(root), readUserConfig());
886
+ const remoteUrl = configured.url;
887
+ if (!remoteUrl) {
888
+ throw new CliFailure(
889
+ "CI_REMOTE_UNAVAILABLE",
890
+ ExitCode.providerUnavailable,
891
+ "No remote endpoint configured. Run effect-ci login https://your-effect-ci-host, set EFFECT_CI_REMOTE_URL in .env.local (or your shell), configure a private remote profile, or export a custom remote runner."
892
+ );
893
+ }
894
+ if (hasWorkloadIdentity()) {
895
+ const service = new URL(remoteUrl);
896
+ if (!["/", "/api"].includes(service.pathname)) throw new CliFailure(
897
+ "CI_REMOTE_AUTH_REQUIRED",
898
+ ExitCode.providerUnavailable,
899
+ "Workload authentication requires the hosted service origin, without a demo route prefix"
900
+ );
901
+ return {
902
+ remoteUrl: service.origin + "/api",
903
+ headers: new Headers(),
904
+ accessOnly: false,
905
+ workload: true,
906
+ requestHeaders: () => workloadHeaders(service.origin)
907
+ };
908
+ }
909
+ if (process.env.GITHUB_ACTIONS === "true" && !configured.token && !hasWorkloadIdentity())
910
+ throw new CliFailure("CI_REMOTE_AUTH_REQUIRED", ExitCode.providerUnavailable, "GitHub Actions remote authentication requires permissions: id-token: write");
911
+ const headers = remoteHeaders(remoteUrl, configured.token);
912
+ const accessOnly = !configured.token && (headers.has("cf-access-token") || headers.has("cf-access-client-id"));
913
+ if (accessOnly) headers.delete("authorization");
914
+ if (!configured.token && !accessOnly) {
915
+ throw new CliFailure(
916
+ "CI_REMOTE_AUTH_REQUIRED",
917
+ ExitCode.providerUnavailable,
918
+ `Remote endpoint found, but authentication is missing. For an enrolled Access identity, run effect-ci login ${new URL(remoteUrl).origin}, then effect-ci doctor --remote. Other hosts require your private Effect CI API profile. Keep credentials out of project env files; never use a deployment token.`
919
+ );
920
+ }
921
+ return { remoteUrl, headers, accessOnly, workload: false, requestHeaders: async () => headers };
922
+ };
923
+ var remoteCapabilities = async ({ remoteUrl, accessOnly, workload, requestHeaders }) => {
924
+ let available;
925
+ try {
926
+ const response = await fetch(`${remoteUrl}/capabilities`, { headers: await requestHeaders(), redirect: "manual", signal: AbortSignal.timeout(15e3) });
927
+ let accessLogin2 = false;
928
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
929
+ try {
930
+ const location = new URL(response.headers.get("location") ?? "", remoteUrl);
931
+ accessLogin2 = location.protocol === "https:" && (/(^|\.)cloudflareaccess\.com$/.test(location.hostname) || location.origin === new URL(remoteUrl).origin && location.pathname.startsWith("/cdn-cgi/access/"));
932
+ } catch {
933
+ }
934
+ }
935
+ if (response.status === 401 || response.status === 403 || accessLogin2) {
936
+ await response.body?.cancel().catch(() => {
937
+ });
938
+ throw new CliFailure(
939
+ "CI_REMOTE_AUTH_REQUIRED",
940
+ ExitCode.providerUnavailable,
941
+ workload ? `Workload authentication was rejected. Grant id-token: write and enable this repository with effect-ci oidc. No run was dispatched.` : `Remote authentication needs refreshing. Run effect-ci login ${new URL(remoteUrl).origin}, then effect-ci doctor --remote. Other hosts may require their private API profile. No run was dispatched.`
942
+ );
943
+ }
944
+ if (response.ok) available = await response.json();
945
+ } catch (error) {
946
+ if (error instanceof CliFailure) throw error;
947
+ }
948
+ const descriptor = available;
949
+ const targets = descriptor?.targets;
950
+ if (descriptor?.protocol !== "effect-ci-remote-v1" || !Array.isArray(targets) || targets.length > 16 || targets.some((name) => typeof name !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,63}$/.test(name)) || new Set(targets).size !== targets.length || descriptor.targetDiscovery !== void 0 && descriptor.targetDiscovery !== "project")
951
+ throw new CliFailure(
952
+ "CI_REMOTE_TARGET_UNAVAILABLE",
953
+ ExitCode.providerUnavailable,
954
+ "The remote host did not return compatible capabilities. No run was dispatched; check the endpoint and Access login, or update the host."
955
+ );
956
+ if (accessOnly && (!Array.isArray(descriptor.authentication) || !descriptor.authentication.includes("cloudflare-access-identity")))
957
+ throw new CliFailure(
958
+ "CI_REMOTE_AUTH_REQUIRED",
959
+ ExitCode.providerUnavailable,
960
+ "This host has not enrolled Access-only remote authentication. Configure its private API profile; no run was dispatched."
961
+ );
962
+ if (workload && (!Array.isArray(descriptor.authentication) || !descriptor.authentication.includes("github-oidc")))
963
+ throw new CliFailure("CI_REMOTE_AUTH_REQUIRED", ExitCode.providerUnavailable, "This host has not enabled workload identity authentication");
964
+ return {
965
+ targets,
966
+ ...descriptor.projectSelection === true ? { projectSelection: true } : {},
967
+ ...descriptor.rerun === true ? { rerun: true } : {},
968
+ ...descriptor.targetDiscovery === "project" ? { targetDiscovery: "project" } : {}
969
+ };
970
+ };
971
+ var builtInRemote = async (invocation, root, workflowPath) => {
972
+ const connection = remoteConnection(root);
973
+ const { remoteUrl } = connection;
974
+ if (invocation.command !== "run") {
975
+ throw new CliFailure(
976
+ "CI_REMOTE_COMMAND_UNAVAILABLE",
977
+ ExitCode.providerUnavailable,
978
+ "The built-in hosted runner supports `run --remote`; plan locally before dispatching"
979
+ );
980
+ }
981
+ const repository = cloneUrl(git(root, "config", "--get", "remote.origin.url"));
982
+ if (git(root, "status", "--porcelain", "--untracked-files=normal")) {
983
+ throw new CliFailure(
984
+ "CI_REMOTE_DIRTY_WORKTREE",
985
+ ExitCode.usage,
986
+ "Remote execution checks the pushed commit, not local edits. Run locally or commit and push the changes first."
987
+ );
988
+ }
989
+ const revision = git(root, "rev-parse", "HEAD");
990
+ const repositoryRoot = git(root, "rev-parse", "--show-toplevel");
991
+ const selectedRoot = relative(realpathSync(repositoryRoot), realpathSync(root)).split("\\").join("/") || ".";
992
+ const selectedWorkflow2 = relative(root, workflowPath).split("\\").join("/");
993
+ const workflow2 = selectedWorkflow2 === ".cloudflare/ci/workflow.ts" ? void 0 : selectedWorkflow2 === ".cloudflare/ci/ci.ts" && !existsSync6(workflowPath) ? "." : selectedWorkflow2;
994
+ const needsSelection = selectedRoot !== "." || Boolean(workflow2);
995
+ const capabilities = await remoteCapabilities(connection).catch((error) => {
996
+ if (!needsSelection && error instanceof CliFailure && error.code === "CI_REMOTE_TARGET_UNAVAILABLE") return void 0;
997
+ throw error;
998
+ });
999
+ const project = capabilities?.projectSelection ? { root: selectedRoot, ...workflow2 ? { workflow: workflow2 } : {} } : void 0;
1000
+ if (needsSelection && !project && (selectedRoot !== "." || capabilities?.targetDiscovery === "project")) {
1001
+ throw new CliFailure(
1002
+ "CI_REMOTE_TARGET_UNAVAILABLE",
1003
+ ExitCode.providerUnavailable,
1004
+ "This host cannot select a project directory or workflow. No run was dispatched; update the host or run locally."
1005
+ );
1006
+ }
1007
+ const ref = gitOptional(root, "symbolic-ref", "--quiet", "HEAD");
1008
+ const targets = invocation.targets?.length ? invocation.targets : invocation.target ? [invocation.target] : void 0;
1009
+ if (!targets && !capabilities && (connection.accessOnly || connection.workload)) await remoteCapabilities(connection);
1010
+ if (targets) {
1011
+ if (targets.length > 16 || targets.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9:._-]{0,63}$/.test(name)))
1012
+ throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "Select at most 16 bounded remote goal names");
1013
+ const enrolled = capabilities ?? await remoteCapabilities(connection);
1014
+ if (invocation.rerunFrom && !enrolled.rerun)
1015
+ throw new CliFailure(
1016
+ "CI_REMOTE_TARGET_UNAVAILABLE",
1017
+ ExitCode.providerUnavailable,
1018
+ "This host has not enrolled explicit compute reruns. No run was dispatched."
1019
+ );
1020
+ if (enrolled.targetDiscovery !== "project" && targets.some((target) => !enrolled.targets.includes(target))) {
1021
+ throw new CliFailure(
1022
+ "CI_REMOTE_TARGET_UNAVAILABLE",
1023
+ ExitCode.providerUnavailable,
1024
+ "This host has not enrolled every requested goal. No run was dispatched; update/select a compatible host or run these goals locally."
1025
+ );
1026
+ }
1027
+ }
1028
+ const response = await fetch(`${remoteUrl}/runs`, {
1029
+ method: "POST",
1030
+ redirect: "error",
1031
+ headers: await connection.requestHeaders(),
1032
+ body: JSON.stringify({
1033
+ repository,
1034
+ revision,
1035
+ ...ref ? { ref } : {},
1036
+ ...targets ? { targets } : {},
1037
+ ...project ? { project } : {},
1038
+ ...invocation.rerunFrom ? { rerunFrom: invocation.rerunFrom } : {},
1039
+ ...invocation.verbose ? { verbose: invocation.verbose } : {},
1040
+ ...invocation.force ? { force: true } : {}
1041
+ })
1042
+ });
1043
+ if (!response.ok) {
1044
+ throw new CliFailure(
1045
+ "CI_REMOTE_FAILED",
1046
+ ExitCode.providerUnavailable,
1047
+ `Could not start the remote run (${response.status}): ${await response.text()}`
1048
+ );
1049
+ }
1050
+ const run = await response.json();
1051
+ if (invocation.format === "text") console.log(`Remote Workflow ${run.instanceId}`);
1052
+ return followRemoteRun(connection, invocation.format, run);
1053
+ };
1054
+ var followRemoteRun = async (connection, format, run) => {
1055
+ const { remoteUrl } = connection;
1056
+ const events = [];
1057
+ const cursor = {};
1058
+ let interruptions = 0;
1059
+ let completedByStatus = false;
1060
+ while (true) {
1061
+ const eventUrl = new URL(remoteEventUrl(remoteUrl, run.eventsUrl));
1062
+ if (cursor.value !== void 0) eventUrl.searchParams.set("cursor", String(cursor.value));
1063
+ const before = events.length;
1064
+ try {
1065
+ await streamRemoteEvents(await fetch(eventUrl, {
1066
+ headers: await connection.requestHeaders(),
1067
+ redirect: "error",
1068
+ signal: AbortSignal.timeout(3e4)
1069
+ }), format, events, cursor);
1070
+ if (["workflow_completed", "workflow_errored", "workflow_terminated"].includes(events.at(-1)?.type ?? "")) break;
1071
+ } catch (error) {
1072
+ if (error instanceof CliFailure) throw error;
1073
+ if (error instanceof SyntaxError) {
1074
+ throw new CliFailure(
1075
+ "CI_REMOTE_FAILED",
1076
+ ExitCode.providerUnavailable,
1077
+ "The remote service returned an invalid event record",
1078
+ { instanceId: run.instanceId }
1079
+ );
1080
+ }
1081
+ }
1082
+ const status = await fetch(remoteEventUrl(remoteUrl, run.statusUrl), {
1083
+ headers: await connection.requestHeaders(),
1084
+ redirect: "error",
1085
+ signal: AbortSignal.timeout(15e3)
1086
+ }).then(async (response) => response.ok ? await response.json() : void 0).catch(() => void 0);
1087
+ if (status) {
1088
+ if (status.status === "errored" || status.status === "terminated") {
1089
+ throw new CliFailure(
1090
+ "CI_WORKFLOW_FAILED",
1091
+ ExitCode.workflowFailure,
1092
+ remoteErrorMessage(status.error?.message) ?? `Remote Workflow ${status.status}`,
1093
+ { instanceId: run.instanceId, events, diagnostics: remoteCommandDiagnostics(events) }
1094
+ );
1095
+ }
1096
+ if (status.status === "complete") {
1097
+ completedByStatus = true;
1098
+ if (format === "text") console.log("\u2713 Workflow completed");
1099
+ break;
1100
+ }
1101
+ if (["queued", "running", "waiting", "paused"].includes(status.status ?? "")) interruptions = 0;
1102
+ }
1103
+ if (events.length > before) interruptions = 0;
1104
+ if (++interruptions > 5) {
1105
+ throw new CliFailure(
1106
+ "CI_REMOTE_STREAM_ENDED",
1107
+ ExitCode.providerUnavailable,
1108
+ "Could not resume remote logs. The Workflow may still be running; inspect its details before dispatching again.",
1109
+ { instanceId: run.instanceId, events }
1110
+ );
1111
+ }
1112
+ if (format === "text") console.log("Remote logs disconnected; reconnecting to the same Workflow\u2026");
1113
+ await new Promise((resolve3) => setTimeout(resolve3, Math.min(1e3 * interruptions, 5e3)));
1114
+ }
1115
+ const terminal = events.at(-1);
1116
+ if (terminal?.type === "workflow_errored" || terminal?.type === "workflow_terminated") {
1117
+ throw new CliFailure(
1118
+ "CI_WORKFLOW_FAILED",
1119
+ ExitCode.workflowFailure,
1120
+ describeEvent(terminal),
1121
+ { instanceId: run.instanceId, events, diagnostics: remoteCommandDiagnostics(events) }
1122
+ );
1123
+ }
1124
+ if (terminal?.type !== "workflow_completed" && !completedByStatus) {
1125
+ throw new CliFailure(
1126
+ "CI_REMOTE_STREAM_ENDED",
1127
+ ExitCode.providerUnavailable,
1128
+ "The remote event stream ended before the Workflow reported a terminal result",
1129
+ { instanceId: run.instanceId, events }
1130
+ );
1131
+ }
1132
+ if (run.resultAvailable === true) {
1133
+ const statusUrl = remoteEventUrl(remoteUrl, run.statusUrl);
1134
+ try {
1135
+ const response = await fetch(statusUrl, { headers: await connection.requestHeaders(), redirect: "error", signal: AbortSignal.timeout(15e3) });
1136
+ if (!response.ok) throw Error("Status unavailable");
1137
+ const status = await response.json();
1138
+ if (status.status !== "complete" || !status.output) throw Error("Result unavailable");
1139
+ return { ...run, events, output: status.output };
1140
+ } catch {
1141
+ throw new CliFailure(
1142
+ "CI_REMOTE_RESULT_UNAVAILABLE",
1143
+ ExitCode.providerUnavailable,
1144
+ "Remote execution completed, but its evidence could not be retrieved. Inspect the same Workflow status; do not dispatch again.",
1145
+ { instanceId: run.instanceId, events }
1146
+ );
1147
+ }
1148
+ }
1149
+ return { ...run, events };
1150
+ };
1151
+ var runPush = async (input, cwd, detected) => {
1152
+ const requested = input.find((arg) => arg.startsWith("--format="))?.slice("--format=".length);
1153
+ if (requested !== void 0 && requested !== "text" && requested !== "json")
1154
+ throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "effect-ci push supports --format=text or --format=json");
1155
+ const format = requested ?? detected;
1156
+ const args = input.filter((arg) => !arg.startsWith("--format="));
1157
+ const to = args[0] === "--to" ? args[1] : void 0;
1158
+ if (args.length > (to ? 2 : 0)) throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "Use effect-ci push [--to <git remote>]");
1159
+ const root = gitOptional(cwd, "rev-parse", "--show-toplevel");
1160
+ if (!root) throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "effect-ci push runs inside a Git repository");
1161
+ const name = to ?? "cloudflare";
1162
+ const remote = remoteConnection(cwd);
1163
+ const connection = { ...remote, remoteUrl: remote.remoteUrl.replace(/\/+$/, "") + "/" };
1164
+ const branch = gitOptional(root, "symbolic-ref", "--quiet", "--short", "HEAD");
1165
+ if (!branch) throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "Check out a branch before pushing");
1166
+ const log = (line) => {
1167
+ if (format === "text") console.log(line);
1168
+ };
1169
+ let target = artifactsTarget(root, name);
1170
+ if (!target) {
1171
+ if (hasGitRemote(root, name)) throw new CliFailure(
1172
+ "CI_REMOTE_UNAVAILABLE",
1173
+ ExitCode.providerUnavailable,
1174
+ `Git remote "${name}" is not a Cloudflare Artifacts repository`
1175
+ );
1176
+ const response = await fetch(new URL("capabilities", connection.remoteUrl), {
1177
+ headers: await connection.requestHeaders(),
1178
+ redirect: "error",
1179
+ signal: AbortSignal.timeout(15e3)
1180
+ }).catch(() => void 0);
1181
+ const host = response?.ok ? (await response.json()).artifacts : void 0;
1182
+ if (typeof host?.namespace !== "string" || typeof host.queue !== "string")
1183
+ throw new CliFailure("CI_REMOTE_UNAVAILABLE", ExitCode.providerUnavailable, "This host does not accept Artifacts pushes. Update the host, or add an Artifacts remote yourself.");
1184
+ const repo = basename(root).toLowerCase().replace(/[^a-z0-9_.-]+/g, "-").replace(/^[^a-z0-9]+/, "").slice(0, 100) || "project";
1185
+ try {
1186
+ target = setupArtifactsRemote(root, name, repo, { namespace: host.namespace, queue: host.queue }, branch, log);
1187
+ } catch (error) {
1188
+ throw new CliFailure(
1189
+ "CI_REMOTE_AUTH_REQUIRED",
1190
+ ExitCode.providerUnavailable,
1191
+ `Could not set up the Artifacts repository (${error instanceof Error ? error.message : String(error)}). Run cf auth login and try again.`
1192
+ );
1193
+ }
1194
+ }
1195
+ const revision = git(root, "rev-parse", "HEAD");
1196
+ let token;
1197
+ try {
1198
+ token = artifactsPushToken(target);
1199
+ } catch (error) {
1200
+ throw new CliFailure(
1201
+ "CI_REMOTE_AUTH_REQUIRED",
1202
+ ExitCode.providerUnavailable,
1203
+ `Could not create an Artifacts push token (${error instanceof Error ? error.message : String(error)}). Run cf auth login, or set EFFECT_CI_ARTIFACTS_TOKEN.`
1204
+ );
1205
+ }
1206
+ if (pushToArtifacts(root, target, `HEAD:refs/heads/${branch}`, token) !== 0)
1207
+ throw new CliFailure("CI_REMOTE_FAILED", ExitCode.providerUnavailable, "git push to Artifacts failed; no run was started");
1208
+ const instanceId = artifactsRunId(target.repo, revision);
1209
+ const run = { instanceId, eventsUrl: `runs/${instanceId}/events`, statusUrl: `runs/${instanceId}`, resultAvailable: true };
1210
+ if (format === "text") console.log(`Waiting for the run of ${revision.slice(0, 7)} on ${connection.remoteUrl}\u2026`);
1211
+ for (let attempt = 0; attempt < 5; attempt++) {
1212
+ const response = await fetch(new URL("artifacts/runs", connection.remoteUrl), {
1213
+ method: "POST",
1214
+ headers: await connection.requestHeaders(),
1215
+ body: JSON.stringify({ repo: target.repo, ref: `refs/heads/${branch}`, revision }),
1216
+ redirect: "error",
1217
+ signal: AbortSignal.timeout(15e3)
1218
+ }).catch(() => void 0);
1219
+ const detail = response && !response.ok ? (await response.text().catch(() => "")).trim() : "";
1220
+ if (response?.ok) await response.body?.cancel().catch(() => {
1221
+ });
1222
+ if (response?.status === 401 || response?.status === 403)
1223
+ throw new CliFailure("CI_REMOTE_AUTH_REQUIRED", ExitCode.providerUnavailable, "The host rejected this login; the push succeeded, but its run cannot be started or followed");
1224
+ if (response?.status === 400)
1225
+ throw new CliFailure("CI_REMOTE_FAILED", ExitCode.providerUnavailable, `The push succeeded, but the host could not start its run: ${detail}`, { instanceId });
1226
+ if (response?.ok || response?.status === 404 || attempt === 4) break;
1227
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3 * (attempt + 1)));
1228
+ }
1229
+ const deadline = Date.now() + 6e4;
1230
+ while (true) {
1231
+ const response = await fetch(remoteEventUrl(connection.remoteUrl, run.statusUrl), {
1232
+ headers: await connection.requestHeaders(),
1233
+ redirect: "error",
1234
+ signal: AbortSignal.timeout(15e3)
1235
+ }).catch(() => void 0);
1236
+ if (response?.status === 401 || response?.status === 403)
1237
+ throw new CliFailure("CI_REMOTE_AUTH_REQUIRED", ExitCode.providerUnavailable, "The host rejected this login; the push succeeded, but its run cannot be followed");
1238
+ if (response?.ok) break;
1239
+ await response?.body?.cancel().catch(() => {
1240
+ });
1241
+ if (Date.now() > deadline)
1242
+ throw new CliFailure(
1243
+ "CI_REMOTE_FAILED",
1244
+ ExitCode.providerUnavailable,
1245
+ `The push succeeded, but no run started for ${revision} within 60 seconds. Check the Artifacts event subscription for ${target.namespace}/${target.repo}.`,
1246
+ { instanceId }
1247
+ );
1248
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
1249
+ }
1250
+ if (format === "text") console.log(`Remote Workflow ${instanceId}`);
1251
+ const result = await followRemoteRun(connection, format, run);
1252
+ if (format === "json") console.log(JSON.stringify({ schemaVersion: 1, ok: true, command: "push", revision, result }));
1253
+ };
1254
+ var stepLogger = (sink) => Logger.layer([Logger.make((options) => {
1255
+ const step = options.fiber.getRef(CurrentLogAnnotations)["ci.step"];
1256
+ const messages = Array.isArray(options.message) ? options.message : [options.message];
1257
+ sink({
1258
+ ...step === void 0 ? {} : { step: String(step) },
1259
+ level: options.logLevel,
1260
+ message: messages.map((message) => typeof message === "string" ? message : JSON.stringify(message)).join(" ")
1261
+ });
1262
+ })]);
1263
+ var printStepLog = (log) => {
1264
+ process.stderr.write(`${log.step === void 0 ? "" : `[${log.step}] `}${log.message}
1265
+ `);
1266
+ };
1267
+ var parseInvocation = (args, onFormat, root) => {
1268
+ let parsed;
1269
+ try {
1270
+ parsed = parseArgs2({
1271
+ args: [...args],
1272
+ allowPositionals: true,
1273
+ options: {
1274
+ format: { short: "f", type: "string" },
1275
+ agent: { type: "boolean" },
1276
+ help: { short: "h", type: "boolean" },
1277
+ local: { type: "boolean" },
1278
+ remote: { type: "boolean" },
1279
+ "rerun-from": { type: "string" },
1280
+ verbose: { short: "v", type: "boolean", multiple: true },
1281
+ force: { type: "boolean" }
1282
+ },
1283
+ strict: true
1284
+ });
1285
+ } catch (error) {
1286
+ throw new CliFailure(
1287
+ "CI_USAGE_ERROR",
1288
+ ExitCode.usage,
1289
+ error instanceof Error ? error.message : String(error)
1290
+ );
1291
+ }
1292
+ const format = parsed.values.format ?? (parsed.values.agent ? "json" : detectedFormat());
1293
+ if (format !== "json" && format !== "mermaid" && format !== "dot" && format !== "text") {
1294
+ throw new CliFailure(
1295
+ "CI_USAGE_ERROR",
1296
+ ExitCode.usage,
1297
+ `Unknown output format: ${format}. Expected text, json, mermaid, or dot.`
1298
+ );
1299
+ }
1300
+ onFormat?.(format);
1301
+ if (parsed.values.local && parsed.values.remote) {
1302
+ throw new CliFailure(
1303
+ "CI_USAGE_ERROR",
1304
+ ExitCode.usage,
1305
+ "--local and --remote are mutually exclusive"
1306
+ );
1307
+ }
1308
+ const [first] = parsed.positionals;
1309
+ const command = first === "list" || first === "plan" || first === "run" || first === "doctor" ? first : "run";
1310
+ const requested = command === "run" && first && first !== "run" ? parsed.positionals : parsed.positionals.slice(1);
1311
+ if (requested.length > 32) throw new CliFailure(
1312
+ "CI_USAGE_ERROR",
1313
+ ExitCode.usage,
1314
+ "Select at most 32 action targets"
1315
+ );
1316
+ const targets = [...new Set(requested)];
1317
+ const target = targets.length === 1 ? targets[0] : void 0;
1318
+ const rerunFrom = parsed.values["rerun-from"];
1319
+ if (rerunFrom !== void 0 && (command !== "run" || !parsed.values.remote || targets.length === 0 || !Schema.is(Schema.String.check(Schema.isUUID(void 0)))(rerunFrom)))
1320
+ throw new CliFailure(
1321
+ "CI_USAGE_ERROR",
1322
+ ExitCode.usage,
1323
+ `Use effect-ci run <compute goals...> --remote --rerun-from <run UUID>`
1324
+ );
1325
+ if (parsed.values.force && (command !== "run" || rerunFrom !== void 0))
1326
+ throw new CliFailure(
1327
+ "CI_USAGE_ERROR",
1328
+ ExitCode.usage,
1329
+ "--force only applies to effect-ci run, and cannot be combined with --rerun-from"
1330
+ );
1331
+ if (command === "doctor" && (!parsed.values.remote || targets.length || format === "mermaid" || format === "dot"))
1332
+ throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, `Use effect-ci doctor --remote [--format=text|json]; it checks access without running work`);
1333
+ if (command === "list" && targets.length) {
1334
+ throw new CliFailure(
1335
+ "CI_USAGE_ERROR",
1336
+ ExitCode.usage,
1337
+ "list does not accept a target"
1338
+ );
1339
+ }
1340
+ const enrollment = command === "run" && !parsed.values.help && !parsed.values.local && !parsed.values.remote && root ? readProjectOidc(root) : void 0;
1341
+ const location = parsed.values.remote || typeof enrollment?.issuer === "string" && typeof enrollment.repository === "string" ? "remote" : "local";
1342
+ return {
1343
+ command,
1344
+ format,
1345
+ help: parsed.values.help === true,
1346
+ location,
1347
+ targets,
1348
+ verbose: parsed.values.verbose?.length ?? 0,
1349
+ force: parsed.values.force === true,
1350
+ ...rerunFrom ? { rerunFrom } : {},
1351
+ ...target ? { target } : {}
1352
+ };
1353
+ };
1354
+ var help = (workflowId) => `Effect CI: ${workflowId}
1355
+
1356
+ Usage:
1357
+ effect-ci login [url] Sign in to your Effect CI host (Cloudflare Access) and remember it
1358
+ effect-ci push [--to <git remote>] Push HEAD to Cloudflare Artifacts and follow its CI run
1359
+ effect-ci oidc [--service https://your-ci-host]
1360
+ effect-ci oidc -- <deploy command>
1361
+ effect-ci Show this help and project targets
1362
+ effect-ci run [targets...] [--local|--remote] [--force] [--format=text|json]
1363
+ effect-ci run <compute goals...> --remote --rerun-from <run UUID>
1364
+ effect-ci plan [targets...] [--local|--remote] [--format=text|json|mermaid|dot]
1365
+ effect-ci list [--format=text|json]
1366
+ effect-ci doctor --remote [--format=text|json]
1367
+ effect-ci run path/to/workflow.ts [target]
1368
+ effect-ci --workflow path/to/workflow.ts [run|plan|list] [target]
1369
+ effect-ci --workflow path/to/package [run|plan|list] [target]
1370
+ effect-ci run --remote --env-file path/to/.env.production
1371
+
1372
+ Commands:
1373
+ oidc Enable repository deployment, or run a command with temporary credentials
1374
+ run Execute the default workflow, or fan out to the selected exported actions
1375
+ plan Resolve the graph without executing commands
1376
+ list List runnable commands for this project
1377
+
1378
+ Examples:
1379
+ effect-ci run Execute the whole default workflow
1380
+ effect-ci run test build Run both goals with their shared dependencies
1381
+ effect-ci run build -v Also log step details (stderr, or "logs" in JSON); -vv adds debug
1382
+ effect-ci run deploy --force Skip cache reuse, including Vite+ task caches
1383
+ effect-ci plan Inspect the whole workflow without executing
1384
+ effect-ci plan --format=mermaid Print its Mermaid graph
1385
+ effect-ci plan --format=dot Print its Graphviz DOT graph
1386
+ effect-ci list Discover exact commands to run
1387
+ AI_AGENT=demo effect-ci list Preview automatic agent-friendly JSON
1388
+
1389
+ Without an explicit path, effect-ci discovers .cloudflare/ci/workflow.ts or an empty
1390
+ ci.ts marker from the current directory or one of its parents. Help never initializes
1391
+ a project. Auto-discovered scripts and Vite+ tasks require an explicit action name.
1392
+ A named local run can initialize the CI marker.
1393
+ Run defaults to remote after OIDC enrollment; --local runs working-tree edits.
1394
+ List and plan stay local. Remote failures never fall back to local execution.
1395
+ Output defaults to JSON for a directly detected coding agent and text otherwise.
1396
+ Detection uses @vercel/detect-agent, including AI_AGENT and tool-specific signals.
1397
+ No agent flag is needed. An explicit --format always wins.`;
1398
+ var workflowNames = [
1399
+ "workflow.ts",
1400
+ "workflow.mts",
1401
+ "workflow.js",
1402
+ "workflow.mjs",
1403
+ "ci.ts",
1404
+ "ci.mts",
1405
+ "ci.js",
1406
+ "ci.mjs"
1407
+ ];
1408
+ var findWorkflow = (cwd) => {
1409
+ let directory = resolve2(cwd);
1410
+ while (true) {
1411
+ for (const name of workflowNames) {
1412
+ const candidate = join6(directory, ".cloudflare", "ci", name);
1413
+ if (existsSync6(candidate)) return candidate;
1414
+ }
1415
+ const parent = dirname4(directory);
1416
+ if (parent === directory) return void 0;
1417
+ directory = parent;
1418
+ }
1419
+ };
1420
+ var looksLikeWorkflowPath = (value) => value.includes("/") || value.includes("\\") || /\.(?:[cm]?[jt]s)$/.test(value);
1421
+ var extractWorkflow = (args, cwd) => {
1422
+ const remaining = [...args];
1423
+ let explicit;
1424
+ for (let index = 0; index < remaining.length; index += 1) {
1425
+ const argument = remaining[index];
1426
+ if (argument === "--workflow") {
1427
+ explicit = remaining[index + 1];
1428
+ if (!explicit) {
1429
+ throw new CliFailure(
1430
+ "CI_USAGE_ERROR",
1431
+ ExitCode.usage,
1432
+ "--workflow requires a path"
1433
+ );
1434
+ }
1435
+ remaining.splice(index, 2);
1436
+ break;
1437
+ }
1438
+ if (argument?.startsWith("--workflow=")) {
1439
+ explicit = argument.slice("--workflow=".length);
1440
+ remaining.splice(index, 1);
1441
+ break;
1442
+ }
1443
+ }
1444
+ if (!explicit) {
1445
+ const positional = remaining.findIndex(
1446
+ (argument, index) => argument !== void 0 && !argument.startsWith("-") && !(index === 0 && ["list", "plan", "run"].includes(argument)) && looksLikeWorkflowPath(argument)
1447
+ );
1448
+ if (positional >= 0) {
1449
+ explicit = remaining[positional];
1450
+ remaining.splice(positional, 1);
1451
+ }
1452
+ }
1453
+ const path = explicit ? resolve2(cwd, explicit) : findWorkflow(cwd);
1454
+ if (!path || !existsSync6(path)) {
1455
+ throw new CliFailure(
1456
+ "CI_WORKFLOW_NOT_FOUND",
1457
+ ExitCode.usage,
1458
+ explicit ? `Workflow not found: ${resolve2(cwd, explicit)}` : `No .cloudflare/ci/workflow.ts found from ${resolve2(cwd)}`
1459
+ );
1460
+ }
1461
+ return { args: remaining, path };
1462
+ };
1463
+ var loadProgram = async (args = process.argv.slice(2), cwd = process.cwd()) => {
1464
+ const selected = extractWorkflow(args, cwd);
1465
+ if (lstatSync4(selected.path).isDirectory()) {
1466
+ return {
1467
+ args: selected.args,
1468
+ path: join6(selected.path, ".cloudflare/ci/ci.ts"),
1469
+ program: inferJavaScriptProgram(selected.path)
1470
+ };
1471
+ }
1472
+ if (basename(selected.path).startsWith("ci.") && readFileSync6(selected.path, "utf8").trim() === "") {
1473
+ return {
1474
+ args: selected.args,
1475
+ path: selected.path,
1476
+ program: inferJavaScriptProgram(projectRoot(selected.path))
1477
+ };
1478
+ }
1479
+ const module = await import(pathToFileURL(selected.path).href);
1480
+ if (!module.default && basename(selected.path).startsWith("ci.")) {
1481
+ return {
1482
+ args: selected.args,
1483
+ path: selected.path,
1484
+ program: inferJavaScriptProgram(projectRoot(selected.path))
1485
+ };
1486
+ }
1487
+ if (!module.default) {
1488
+ throw new CliFailure(
1489
+ "CI_WORKFLOW_INVALID",
1490
+ ExitCode.usage,
1491
+ `${selected.path} must default-export a CI workflow`
1492
+ );
1493
+ }
1494
+ return {
1495
+ args: selected.args,
1496
+ path: selected.path,
1497
+ program: {
1498
+ actions: module,
1499
+ ...module.local ? { local: module.local } : {},
1500
+ ...module.remote ? { remote: module.remote } : {},
1501
+ workflow: module.default
1502
+ }
1503
+ };
1504
+ };
1505
+ var inferJavaScriptProgram = (root) => {
1506
+ const manifestPath = join6(root, "package.json");
1507
+ if (!existsSync6(manifestPath)) {
1508
+ throw new CliFailure(
1509
+ "CI_ZERO_CONFIG_UNSUPPORTED",
1510
+ ExitCode.usage,
1511
+ `Zero-config CI requires a package.json at ${manifestPath}`
1512
+ );
1513
+ }
1514
+ const manifest = JSON.parse(readFileSync6(manifestPath, "utf8"));
1515
+ let tasks = { names: [], dependencies: {} };
1516
+ if (manifest.dependencies?.["vite-plus"] || manifest.devDependencies?.["vite-plus"]) {
1517
+ try {
1518
+ tasks = vitePlusTasks(root);
1519
+ } catch (error) {
1520
+ throw new CliFailure(
1521
+ "CI_VITE_PLUS_CONFIG_INVALID",
1522
+ ExitCode.usage,
1523
+ `Cannot discover Vite+ tasks. Install project dependencies and check vite.config.ts. ${error instanceof Error ? error.message : String(error)}`
1524
+ );
1525
+ }
1526
+ }
1527
+ const names = [...Object.keys(manifest.scripts ?? {}), ...tasks.names];
1528
+ if (names.length === 0) {
1529
+ throw new CliFailure(
1530
+ "CI_ZERO_CONFIG_NO_TASKS",
1531
+ ExitCode.usage,
1532
+ "Zero-config CI found no package.json scripts or Vite+ run.tasks"
1533
+ );
1534
+ }
1535
+ return fromPackageJson(manifest, {
1536
+ tasks: tasks.names,
1537
+ taskDependencies: tasks.dependencies
1538
+ });
1539
+ };
1540
+ var initializeJavaScriptProject = (args, cwd) => {
1541
+ if (findWorkflow(cwd) || args.some(
1542
+ (arg) => arg === "--workflow" || arg.startsWith("--workflow=") || looksLikeWorkflowPath(arg)
1543
+ )) return void 0;
1544
+ const invocation = parseInvocation(args, void 0, cwd);
1545
+ if (invocation.help || invocation.command !== "run" || invocation.location !== "local") return void 0;
1546
+ requireAction(invocation.targets);
1547
+ const program = inferJavaScriptProgram(resolve2(cwd));
1548
+ selectedWorkflow(program, invocation.targets);
1549
+ for (const directory of [join6(cwd, ".cloudflare"), join6(cwd, ".cloudflare", "ci")]) {
1550
+ if (existsSync6(directory)) {
1551
+ const entry = lstatSync4(directory);
1552
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
1553
+ throw new CliFailure(
1554
+ "CI_INITIALIZATION_UNSAFE",
1555
+ ExitCode.usage,
1556
+ "Zero-config initialization requires ordinary project-owned directories"
1557
+ );
1558
+ }
1559
+ } else {
1560
+ mkdirSync3(directory);
1561
+ }
1562
+ }
1563
+ const marker = join6(cwd, ".cloudflare", "ci", "ci.ts");
1564
+ writeFileSync3(marker, "", { flag: "wx" });
1565
+ return marker;
1566
+ };
1567
+ var printJson = (value) => {
1568
+ process.stdout.write(`${JSON.stringify(value, null, 2)}
1569
+ `);
1570
+ };
1571
+ var projectRoot = (workflowPath) => basename(dirname4(workflowPath)) === "ci" && basename(dirname4(dirname4(workflowPath))) === ".cloudflare" ? resolve2(dirname4(workflowPath), "../..") : dirname4(workflowPath);
1572
+ var defaultLocalOptions = (workflowPath) => {
1573
+ const event = process.env.EFFECT_CI_EVENT ?? process.env.GITHUB_EVENT_NAME;
1574
+ const revision = process.env.EFFECT_CI_REVISION ?? process.env.GITHUB_SHA;
1575
+ const repository = process.env.GITHUB_REPOSITORY;
1576
+ const decision = process.env.EFFECT_CI_APPROVAL;
1577
+ let payload;
1578
+ try {
1579
+ const path = process.env.GITHUB_EVENT_PATH;
1580
+ if (path && lstatSync4(path).isFile() && lstatSync4(path).size <= 4194304)
1581
+ payload = JSON.parse(readFileSync6(path, "utf8"));
1582
+ } catch {
1583
+ }
1584
+ const comparison = process.env.EFFECT_CI_BASE_REVISION ? { base: process.env.EFFECT_CI_BASE_REVISION, ...revision ? { head: revision } : {} } : githubSourceComparison(event ?? "workflow_dispatch", payload, revision);
1585
+ const approval = decision === "approved" || decision === "rejected" ? { request: () => Effect2.succeed({ decision }) } : void 0;
1586
+ return {
1587
+ ...approval ? { approval } : {},
1588
+ env: process.env.NODE_ENV ?? (process.env.CI ? "test" : "development"),
1589
+ event: {
1590
+ type: event ?? "workflow_dispatch",
1591
+ ...comparison ? { comparison } : {},
1592
+ ...process.env.GITHUB_REF ? { ref: process.env.GITHUB_REF } : {},
1593
+ ...revision ? { revision } : {},
1594
+ ...repository && revision ? {
1595
+ source: {
1596
+ kind: "git",
1597
+ repository: `https://github.com/${repository}.git`,
1598
+ revision
1599
+ }
1600
+ } : {}
1601
+ },
1602
+ source: {
1603
+ checkout: () => Effect2.succeed(Workspace.local(projectRoot(workflowPath))),
1604
+ reference: { kind: "local", path: projectRoot(workflowPath) }
1605
+ }
1606
+ };
1607
+ };
1608
+ var classifyFailure = (error) => {
1609
+ if (error instanceof CliFailure) return error;
1610
+ if (error instanceof LocalIsolateUnavailable) return new CliFailure(error.code, ExitCode.providerUnavailable, error.message);
1611
+ if (error instanceof ApprovalError) {
1612
+ return new CliFailure(
1613
+ error.decision === "rejected" ? "CI_APPROVAL_REJECTED" : "CI_APPROVAL_UNAVAILABLE",
1614
+ ExitCode.approval,
1615
+ error.message,
1616
+ { decision: error.decision, stepId: error.stepId }
1617
+ );
1618
+ }
1619
+ if (error instanceof CommandCheckpointError || error instanceof CommandExecutionError) {
1620
+ return new CliFailure("CI_COMMAND_OUTCOME_UNKNOWN", ExitCode.workflowFailure, error.message, {
1621
+ command: error.command,
1622
+ cwd: error.cwd,
1623
+ stepId: error.stepId,
1624
+ stage: error.stage,
1625
+ processExitCode: null,
1626
+ effects: error.effects,
1627
+ ...error instanceof CommandCheckpointError && error.checkpoint ? { checkpoint: error.checkpoint } : {}
1628
+ });
1629
+ }
1630
+ if (error instanceof CommandError) {
1631
+ return new CliFailure(
1632
+ "CI_COMMAND_FAILED",
1633
+ ExitCode.workflowFailure,
1634
+ error.message,
1635
+ {
1636
+ command: error.command,
1637
+ cwd: error.cwd,
1638
+ exitCode: error.exitCode,
1639
+ stepId: error.stepId,
1640
+ ...error.output ? { output: error.output } : error.details ? { output: { text: error.details } } : {}
1641
+ }
1642
+ );
1643
+ }
1644
+ if (error instanceof SecretError) {
1645
+ return new CliFailure(
1646
+ "CI_SECRET_MISSING",
1647
+ ExitCode.workflowFailure,
1648
+ error.message,
1649
+ { name: error.secret }
1650
+ );
1651
+ }
1652
+ if (error instanceof RollbackError) {
1653
+ return new CliFailure(
1654
+ "CI_ROLLBACK_FAILED",
1655
+ ExitCode.workflowFailure,
1656
+ error.message,
1657
+ { stepId: error.stepId }
1658
+ );
1659
+ }
1660
+ return new CliFailure(
1661
+ "CI_WORKFLOW_FAILED",
1662
+ ExitCode.workflowFailure,
1663
+ error instanceof Error ? error.message : String(error)
1664
+ );
1665
+ };
1666
+ var requireAction = (targets) => {
1667
+ if (!targets.length) throw new CliFailure(
1668
+ "CI_ACTION_REQUIRED",
1669
+ ExitCode.usage,
1670
+ "Choose an action: effect-ci run <action>. Use effect-ci list to see available actions."
1671
+ );
1672
+ };
1673
+ var selectedWorkflow = (program, targets) => {
1674
+ if (!targets.length) return program.workflow;
1675
+ const available = actionTargets(program.actions);
1676
+ const actions = targets.map((target) => {
1677
+ const action = available[target];
1678
+ if (!action) throw new CliFailure(
1679
+ "CI_UNKNOWN_TARGET",
1680
+ ExitCode.usage,
1681
+ `Unknown action target: ${target}${Object.keys(available).length === 0 ? ". No exported actions were found; export CI actions from your workflow to select them by name." : ""}`,
1682
+ { available: Object.keys(available).sort() }
1683
+ );
1684
+ return action;
1685
+ });
1686
+ return workflow(
1687
+ `${program.workflow.id}/${targets.join("+")}`,
1688
+ actions.length === 1 ? actions[0] : () => parallel(actions.map((action) => action()))
1689
+ );
1690
+ };
1691
+ var list = (program, format) => {
1692
+ const targets = Object.keys(actionTargets(program.actions)).sort();
1693
+ if (format === "json") {
1694
+ printJson({
1695
+ schemaVersion: 1,
1696
+ ok: true,
1697
+ command: "list",
1698
+ workflow: program.workflow.id,
1699
+ targets,
1700
+ commands: [...program.requiresTarget ? [] : ["effect-ci run"], ...targets.map((target) => `effect-ci run ${target}`)]
1701
+ });
1702
+ return;
1703
+ }
1704
+ console.log(`Workflow: ${program.workflow.id}`);
1705
+ console.log("Run commands:");
1706
+ if (!program.requiresTarget) console.log(` effect-ci run (whole workflow)`);
1707
+ for (const target of targets) console.log(` effect-ci run ${target}`);
1708
+ };
1709
+ var main = async (program, args = process.argv.slice(2), workflowPath = resolve2(process.cwd(), ".cloudflare/ci/workflow.ts")) => {
1710
+ let format = detectedFormat();
1711
+ const logs = [];
1712
+ try {
1713
+ const invocation = parseInvocation(args, (value) => {
1714
+ format = value;
1715
+ }, projectRoot(workflowPath));
1716
+ format = invocation.format;
1717
+ if (invocation.help) {
1718
+ console.log(help(program.workflow.id));
1719
+ console.log("");
1720
+ list(program, "text");
1721
+ return ExitCode.success;
1722
+ }
1723
+ if (invocation.command === "list") {
1724
+ if (format === "mermaid" || format === "dot") {
1725
+ throw new CliFailure(
1726
+ "CI_USAGE_ERROR",
1727
+ ExitCode.usage,
1728
+ "Graph output is available for plan, not list"
1729
+ );
1730
+ }
1731
+ list(program, format);
1732
+ return ExitCode.success;
1733
+ }
1734
+ if (invocation.command === "doctor") {
1735
+ const capabilities = await remoteCapabilities(remoteConnection(projectRoot(workflowPath)));
1736
+ const result2 = {
1737
+ schemaVersion: 1,
1738
+ ok: true,
1739
+ command: "doctor",
1740
+ location: "remote",
1741
+ targets: capabilities.targets,
1742
+ ...capabilities.rerun ? { rerun: true } : {},
1743
+ ...capabilities.targetDiscovery ? { targetDiscovery: capabilities.targetDiscovery } : {},
1744
+ dispatched: false
1745
+ };
1746
+ if (format === "json") printJson(result2);
1747
+ else console.log(capabilities.targetDiscovery === "project" ? "Remote access ready. Selected goals are discovered inside the project workspace. No workflow started." : `Remote access ready. Enrolled goals: ${capabilities.targets.join(", ") || "default workflow only"}. No workflow started.`);
1748
+ return ExitCode.success;
1749
+ }
1750
+ if (invocation.command === "run" && program.requiresTarget) requireAction(invocation.targets);
1751
+ const workflow2 = invocation.location === "remote" && !program.remote ? program.workflow : selectedWorkflow(program, invocation.targets);
1752
+ const request = {
1753
+ command: invocation.command,
1754
+ format,
1755
+ location: invocation.location,
1756
+ ...invocation.target ? { target: invocation.target } : {},
1757
+ ...invocation.targets.length > 1 ? { targets: invocation.targets } : {},
1758
+ ...invocation.rerunFrom ? { rerunFrom: invocation.rerunFrom } : {},
1759
+ ...invocation.verbose ? { verbose: Math.min(invocation.verbose, 2) } : {},
1760
+ ...invocation.force ? { force: true } : {},
1761
+ workflow: workflow2
1762
+ };
1763
+ if (invocation.location === "remote") {
1764
+ if (invocation.rerunFrom && program.remote)
1765
+ throw new CliFailure(
1766
+ "CI_REMOTE_TARGET_UNAVAILABLE",
1767
+ ExitCode.providerUnavailable,
1768
+ "Explicit compute reruns require negotiated hosted support; a custom remote handler cannot ignore this option."
1769
+ );
1770
+ const result2 = program.remote ? await program.remote(request) : await builtInRemote(request, projectRoot(workflowPath), workflowPath);
1771
+ if (format === "json") {
1772
+ printJson({
1773
+ schemaVersion: 1,
1774
+ ok: true,
1775
+ command: invocation.command,
1776
+ location: invocation.location,
1777
+ ...invocation.target ? { target: invocation.target } : {},
1778
+ ...invocation.targets.length > 1 ? { targets: invocation.targets } : {},
1779
+ workflow: workflow2.id,
1780
+ result: result2
1781
+ });
1782
+ }
1783
+ return ExitCode.success;
1784
+ }
1785
+ const defaults = defaultLocalOptions(workflowPath);
1786
+ const overrides = typeof program.local === "function" ? program.local({ root: projectRoot(workflowPath), workflowPath }) : program.local ?? {};
1787
+ const configured = { ...defaults, ...overrides };
1788
+ const isolate = makeLocalProjectChecks();
1789
+ const localWorkflow = { ...workflow2, effect: workflow2.effect.pipe(
1790
+ Effect2.provideService(ProjectChecks, isolate.service),
1791
+ // Vite+ caches every script; runner workspaces and machines without `vp` use the package manager.
1792
+ Effect2.provideService(VitePlusAvailable, (workspace) => workspace.kind === "local" && vitePlusAvailable(workspace.cwd)),
1793
+ Effect2.provideService(MinimumLogLevel, invocation.verbose >= 2 ? "Debug" : invocation.verbose === 1 ? "Info" : "Warn"),
1794
+ Effect2.provide(stepLogger((log) => format === "json" ? logs.push(log) : printStepLog(log)))
1795
+ ) };
1796
+ const result = await (async () => {
1797
+ try {
1798
+ return await runPromise(localWorkflow, {
1799
+ ...configured,
1800
+ mode: invocation.command === "plan" ? "plan" : "execute",
1801
+ ...invocation.force ? { force: true } : {},
1802
+ ...format === "json" || format === "mermaid" || format === "dot" ? { output: "silent" } : configured.output ? { output: configured.output } : {}
1803
+ });
1804
+ } finally {
1805
+ try {
1806
+ await isolate.dispose();
1807
+ } finally {
1808
+ await configured.dispose?.();
1809
+ }
1810
+ }
1811
+ })();
1812
+ if (format === "json") {
1813
+ printJson({
1814
+ schemaVersion: 1,
1815
+ ok: true,
1816
+ command: invocation.command,
1817
+ location: invocation.location,
1818
+ ...invocation.target ? { target: invocation.target } : {},
1819
+ ...invocation.targets.length > 1 ? { targets: invocation.targets } : {},
1820
+ workflow: workflow2.id,
1821
+ plan: result.plan,
1822
+ ...logs.length ? { logs } : {}
1823
+ });
1824
+ } else if (format === "mermaid") {
1825
+ console.log(formatPlanMermaid(result.plan));
1826
+ } else if (format === "dot") {
1827
+ console.log(formatPlanDot(result.plan));
1828
+ }
1829
+ return ExitCode.success;
1830
+ } catch (error) {
1831
+ const failure = classifyFailure(error);
1832
+ if (format === "json") {
1833
+ printJson({
1834
+ schemaVersion: 1,
1835
+ ok: false,
1836
+ error: {
1837
+ code: failure.code,
1838
+ message: failure.message,
1839
+ ...failure.details === void 0 ? {} : { details: failure.details }
1840
+ },
1841
+ ...logs.length ? { logs } : {}
1842
+ });
1843
+ } else {
1844
+ console.error(`Error [${failure.code}]: ${failure.message}`);
1845
+ }
1846
+ return failure.exitCode;
1847
+ }
1848
+ };
1849
+ var runCli = async (args = process.argv.slice(2), cwd = process.cwd()) => {
1850
+ if (args.length === 0) args = ["--help"];
1851
+ let format = detectedFormat();
1852
+ try {
1853
+ for (const [key, value] of Object.entries(projectEnvironment(cwd))) {
1854
+ if (process.env[key] === void 0) process.env[key] = value;
1855
+ }
1856
+ const remaining = [];
1857
+ for (let index = 0; index < args.length; index++) {
1858
+ const argument = args[index];
1859
+ if (argument !== "--env-file" && !argument.startsWith("--env-file=")) {
1860
+ remaining.push(argument);
1861
+ continue;
1862
+ }
1863
+ const path = argument === "--env-file" ? args[++index] : argument.slice("--env-file=".length);
1864
+ if (!path || path.startsWith("--")) {
1865
+ throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "--env-file requires a path");
1866
+ }
1867
+ let settings;
1868
+ try {
1869
+ settings = parseEnv3(readFileSync6(resolve2(cwd, path), "utf8"));
1870
+ } catch {
1871
+ throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, `Cannot read environment file: ${path}`);
1872
+ }
1873
+ Object.assign(process.env, settings);
1874
+ if (settings.EFFECT_CI_REMOTE_URL ?? settings.EFFECT_CI_PUBLIC_URL) {
1875
+ process.env.EFFECT_CI_REMOTE_URL = settings.EFFECT_CI_REMOTE_URL ?? settings.EFFECT_CI_PUBLIC_URL;
1876
+ }
1877
+ if (settings.EFFECT_CI_REMOTE_TOKEN ?? settings.EFFECT_CI_API_TOKEN) {
1878
+ process.env.EFFECT_CI_REMOTE_TOKEN = settings.EFFECT_CI_REMOTE_TOKEN ?? settings.EFFECT_CI_API_TOKEN;
1879
+ }
1880
+ if (settings.CF_ACCESS_CLIENT_ID && settings.CF_ACCESS_CLIENT_SECRET && !settings.CF_ACCESS_TOKEN) {
1881
+ process.env.CF_ACCESS_TOKEN = "";
1882
+ }
1883
+ }
1884
+ args = remaining.length ? remaining : ["--help"];
1885
+ if (args[0] === "push") {
1886
+ const requested = args.find((arg) => arg.startsWith("--format="))?.slice("--format=".length);
1887
+ if (requested === "text" || requested === "json") format = requested;
1888
+ await runPush(args.slice(1), cwd, format === "json" ? "json" : "text");
1889
+ return;
1890
+ }
1891
+ if (args[0] === "login") {
1892
+ await runLogin(args.slice(1));
1893
+ return;
1894
+ }
1895
+ if (args[0] === "oidc") {
1896
+ const host = process.env.EFFECT_CI_REMOTE_URL || readUserConfig().remoteUrl;
1897
+ await runOidc(args.slice(1), cwd, host ? remoteHeaders(host) : new Headers({ "content-type": "application/json" }), host);
1898
+ return;
1899
+ }
1900
+ const explicit = args.some((arg) => arg === "--workflow" || arg.startsWith("--workflow=") || looksLikeWorkflowPath(arg));
1901
+ if (!explicit) {
1902
+ const invocation = parseInvocation(args, (value) => {
1903
+ format = value;
1904
+ }, cwd);
1905
+ if (invocation.command === "doctor") {
1906
+ process.exitCode = await main(
1907
+ { workflow: workflow("hosted", function* () {
1908
+ }) },
1909
+ args,
1910
+ resolve2(cwd, ".cloudflare/ci/workflow.ts")
1911
+ );
1912
+ return;
1913
+ }
1914
+ } else if (args[0] === "doctor") {
1915
+ throw new CliFailure("CI_USAGE_ERROR", ExitCode.usage, "doctor checks the current project's remote configuration; do not pass a workflow path");
1916
+ }
1917
+ if (!explicit) {
1918
+ const invocation = parseInvocation(args, (value) => {
1919
+ format = value;
1920
+ }, cwd);
1921
+ if (!invocation.help && invocation.command === "run" && !invocation.targets.length) {
1922
+ const path = findWorkflow(cwd);
1923
+ if (!path || basename(path).startsWith("ci.") && readFileSync6(path, "utf8").trim() === "") {
1924
+ requireAction(invocation.targets);
1925
+ }
1926
+ }
1927
+ if (invocation.location === "remote" && invocation.command === "run") {
1928
+ process.exitCode = await main(
1929
+ { workflow: workflow("hosted", function* () {
1930
+ }) },
1931
+ args,
1932
+ resolve2(cwd, ".cloudflare/ci/workflow.ts")
1933
+ );
1934
+ return;
1935
+ }
1936
+ }
1937
+ if (!explicit && !findWorkflow(cwd)) {
1938
+ const invocation = parseInvocation(args, (value) => {
1939
+ format = value;
1940
+ }, cwd);
1941
+ if (invocation.location === "local" && (invocation.help || invocation.command !== "run")) {
1942
+ let program;
1943
+ try {
1944
+ program = inferJavaScriptProgram(resolve2(cwd));
1945
+ } catch (error) {
1946
+ if (invocation.help && error instanceof CliFailure && ["CI_ZERO_CONFIG_UNSUPPORTED", "CI_ZERO_CONFIG_NO_TASKS"].includes(error.code)) {
1947
+ console.log(help("no workflow selected"));
1948
+ process.exitCode = ExitCode.success;
1949
+ return;
1950
+ }
1951
+ throw error;
1952
+ }
1953
+ process.exitCode = await main(program, args, resolve2(cwd, ".cloudflare/ci/ci.ts"));
1954
+ return;
1955
+ }
1956
+ }
1957
+ initializeJavaScriptProject(args, cwd);
1958
+ const loaded = await loadProgram(args, cwd);
1959
+ process.exitCode = await main(loaded.program, loaded.args, loaded.path);
1960
+ } catch (error) {
1961
+ const failure = classifyFailure(error);
1962
+ if (format === "json") {
1963
+ printJson({ schemaVersion: 1, ok: false, error: {
1964
+ code: failure.code,
1965
+ message: failure.message,
1966
+ ...failure.details === void 0 ? {} : { details: failure.details }
1967
+ } });
1968
+ } else console.error(`Error [${failure.code}]: ${failure.message}`);
1969
+ process.exitCode = failure.exitCode;
1970
+ }
1971
+ };
1972
+ export {
1973
+ ExitCode,
1974
+ initializeJavaScriptProject,
1975
+ loadProgram,
1976
+ main,
1977
+ runCli
1978
+ };