withruntime 0.34.0 → 0.37.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.
Files changed (47) hide show
  1. package/BLAXEL.md +207 -204
  2. package/COMPATIBILITY.md +367 -337
  3. package/DAYTONA.md +180 -173
  4. package/E2B.md +246 -230
  5. package/README.md +182 -142
  6. package/README.src.md +182 -142
  7. package/VERCEL.md +173 -168
  8. package/agent-platforms-inventory.json +387 -0
  9. package/dist/agents-cli.d.ts +7 -1
  10. package/dist/agents-cli.js +219 -2
  11. package/dist/ci-cli.d.ts +7 -1
  12. package/dist/ci-cli.js +25 -1
  13. package/dist/cli-words.js +1 -0
  14. package/dist/cli.d.ts +1 -1
  15. package/dist/cli.js +25 -3
  16. package/dist/errors.d.ts +1 -1
  17. package/dist/errors.js +4 -1
  18. package/dist/functions/index.d.ts +10 -0
  19. package/dist/functions/index.js +11 -0
  20. package/dist/index.d.ts +3 -3
  21. package/dist/inngest/index.d.ts +96 -0
  22. package/dist/inngest/index.js +183 -0
  23. package/dist/jobs-code/cron.d.ts +12 -0
  24. package/dist/jobs-code/cron.js +93 -0
  25. package/dist/jobs-code/registry.d.ts +31 -0
  26. package/dist/jobs-code/registry.js +30 -0
  27. package/dist/jobs-code/runner.d.ts +1 -0
  28. package/dist/jobs-code/runner.js +74 -0
  29. package/dist/jobs-deploy.d.ts +22 -0
  30. package/dist/jobs-deploy.js +247 -0
  31. package/dist/jobs-import.d.ts +15 -0
  32. package/dist/jobs-import.js +231 -0
  33. package/dist/products/agents.d.ts +161 -1
  34. package/dist/products/agents.js +40 -0
  35. package/dist/products/ci.d.ts +19 -1
  36. package/dist/products/functions.d.ts +2 -0
  37. package/dist/products/functions.js +5 -0
  38. package/dist/products/index.d.ts +2 -0
  39. package/dist/products/index.js +3 -0
  40. package/dist/products/jobs.d.ts +77 -0
  41. package/dist/products/jobs.js +5 -0
  42. package/dist/transport.d.ts +5 -1
  43. package/dist/transport.js +7 -1
  44. package/dist/trigger/index.d.ts +202 -0
  45. package/dist/trigger/index.js +244 -0
  46. package/dist/types.d.ts +15 -3
  47. package/package.json +19 -3
@@ -0,0 +1,247 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { basename, join, relative, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { me } from "./cli-name.js";
5
+ import { jobNameOf } from "./jobs-code/registry.js";
6
+ import { MACHINES } from "./trigger/index.js";
7
+ import { JOB_DEFAULTS, JOB_LIMITS } from "./products/jobs.js";
8
+ export const JOB_DEPLOY_HELP = `runtime jobs deploy [<dir>] [--name <project>] [--dry-run]
9
+
10
+ Run Trigger.dev tasks and Inngest functions as Runtime jobs. First change the
11
+ import: \`@trigger.dev/sdk\` (or /v3) to \`withruntime/trigger\`, or \`inngest\`
12
+ (and its serve adapters, such as inngest/next) to \`withruntime/inngest\`.
13
+
14
+ Each schedules.task, or Inngest function with a cron trigger, becomes a job on
15
+ that schedule. Each task, or function with an event trigger, becomes a paused
16
+ job that tasks.trigger(id, payload) or inngest.send(event) runs once per call.
17
+ A task's machine, maxDuration and retry.maxAttempts (an Inngest function's
18
+ retries and timeouts.finish) size its job.
19
+
20
+ --name the jobs' prefix: <name>-<task id>. Default: trigger.config's project,
21
+ the Inngest app's id, or package.json's name
22
+ --dry-run list the tasks the files declare; create nothing (it still builds the image)
23
+ `;
24
+ const SKIP = new Set([
25
+ "node_modules",
26
+ ".git",
27
+ "dist",
28
+ "build",
29
+ ".next",
30
+ ".turbo",
31
+ ".trigger",
32
+ "coverage",
33
+ ]);
34
+ const CODE = /\.(m?[jt]sx?|cts|cjs)$/;
35
+ /** The project's files that import a drop-in, and those that still import
36
+ * the platform's own SDK. */
37
+ export async function scanProject(dir) {
38
+ const ours = [];
39
+ const theirs = [];
40
+ const walk = async (at, depth) => {
41
+ if (depth > 8)
42
+ return;
43
+ for (const entry of await readdir(at, { withFileTypes: true })) {
44
+ if (entry.isDirectory()) {
45
+ if (!SKIP.has(entry.name) && !entry.name.startsWith("."))
46
+ await walk(join(at, entry.name), depth + 1);
47
+ continue;
48
+ }
49
+ if (!CODE.test(entry.name) || entry.name.endsWith(".d.ts"))
50
+ continue;
51
+ const path = join(at, entry.name);
52
+ const text = await readFile(path, "utf8");
53
+ const rel = relative(dir, path);
54
+ if (/["']withruntime\/(trigger|inngest)["']/.test(text))
55
+ ours.push(rel);
56
+ else if (/["'](@trigger\.dev\/sdk(\/v3)?|inngest)["']/.test(text))
57
+ theirs.push(rel);
58
+ }
59
+ };
60
+ await walk(dir, 0);
61
+ return { ours: ours.sort(), theirs: theirs.sort() };
62
+ }
63
+ /** The Dockerfile a project's code jobs run from: Node 22 and Bun, the
64
+ * project's dependencies by its own lockfile, and the runner. */
65
+ /** When an on-demand task's template job is due: 1 January 9999, UTC, never
66
+ * reached (the API takes a time up to the year 275760). */
67
+ export const TEMPLATE_AT = Date.UTC(9999, 0, 1);
68
+ export function codeDockerfile(runner) {
69
+ const b64 = Buffer.from(runner).toString("base64");
70
+ const chunks = b64.match(/.{1,4000}/g) ?? [];
71
+ return [
72
+ "FROM node:22-bookworm-slim",
73
+ "RUN npm install -g bun@1.2.23 && apt-get update && apt-get install -y --no-install-recommends ca-certificates git && rm -rf /var/lib/apt/lists/*",
74
+ "WORKDIR /workspace/app",
75
+ "COPY . .",
76
+ "RUN if [ -f bun.lock ] || [ -f bun.lockb ]; then bun install --frozen-lockfile; " +
77
+ "elif [ -f pnpm-lock.yaml ]; then npx -y pnpm@9 install --frozen-lockfile; " +
78
+ "elif [ -f yarn.lock ]; then npx -y yarn@1 install --frozen-lockfile; " +
79
+ "elif [ -f package-lock.json ]; then npm ci; " +
80
+ "elif [ -f package.json ]; then npm install; fi",
81
+ "RUN mkdir -p .runtime",
82
+ ...chunks.map((c) => `RUN printf %s '${c}' >> .runtime/runner.b64`),
83
+ "RUN base64 -d .runtime/runner.b64 > .runtime/jobs-runner.ts && rm .runtime/runner.b64",
84
+ "",
85
+ ].join("\n");
86
+ }
87
+ const DOCKERIGNORE = "node_modules\n.git\n.env\n.env.*\ndist\n.next\n.turbo\n.trigger\ncoverage\n";
88
+ async function projectName(dir, files) {
89
+ for (const name of ["trigger.config.ts", "trigger.config.js", "trigger.config.mjs"]) {
90
+ const text = await readFile(join(dir, name), "utf8").catch(() => "");
91
+ const found = /project\s*:\s*["'`]([^"'`]+)["'`]/.exec(text);
92
+ if (found)
93
+ return found[1];
94
+ }
95
+ for (const file of files) {
96
+ const text = await readFile(join(dir, file), "utf8").catch(() => "");
97
+ const found = /new\s+Inngest\(\s*\{[^}]*\bid\s*:\s*["'`]([^"'`]+)["'`]/.exec(text);
98
+ if (found)
99
+ return found[1];
100
+ }
101
+ const pkg = await readFile(join(dir, "package.json"), "utf8").catch(() => "{}");
102
+ const name = JSON.parse(pkg).name?.replace(/^@[^/]+\//, "");
103
+ return name || basename(resolve(dir));
104
+ }
105
+ export async function jobsDeployCommand(argv, out, runtime, kit) {
106
+ if (argv[0] === "help" || argv[0] === "--help") {
107
+ out.write(out.json ? JSON.stringify({ usage: JOB_DEPLOY_HELP }) : JOB_DEPLOY_HELP);
108
+ return 0;
109
+ }
110
+ const args = kit.parse(argv, ["dry-run"], ["name", "region"]);
111
+ const dir = resolve(args.positional[0] ?? ".");
112
+ const say = (text) => !out.json && out.write(text);
113
+ const { ours, theirs } = await scanProject(dir);
114
+ if (!ours.length)
115
+ throw kit.usage(theirs.length
116
+ ? `${theirs.join(", ")} still import Trigger.dev's or Inngest's SDK. Change \`@trigger.dev/sdk\` to \`withruntime/trigger\`, or \`inngest\` to \`withruntime/inngest\`, then deploy again.`
117
+ : `No file under ${dir} imports withruntime/trigger or withruntime/inngest.`);
118
+ if (theirs.length)
119
+ say(`Not deployed, still importing Trigger.dev's or Inngest's SDK: ${theirs.join(", ")}`);
120
+ const project = kit.flag(args, "name") ?? (await projectName(dir, ours));
121
+ const client = await runtime();
122
+ const region = kit.flag(args, "region");
123
+ say(`Building ${project}'s image from ${dir}...`);
124
+ const runner = await readFile(fileURLToPath(new URL("./jobs-code/runner.js", import.meta.url)), "utf8").catch(() => readFile(fileURLToPath(new URL("./jobs-code/runner.ts", import.meta.url)), "utf8"));
125
+ const image = await client.images.build({
126
+ name: `jobs-${project}`.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 63),
127
+ dockerfile: codeDockerfile(runner),
128
+ contextDir: dir,
129
+ dockerignore: DOCKERIGNORE,
130
+ ...(region ? { region } : {}),
131
+ });
132
+ say(`Reading the tasks in ${ours.length} file${ours.length === 1 ? "" : "s"}...`);
133
+ const sandbox = await client.sandboxes.create({
134
+ image: image.id,
135
+ ...(region ? { region } : {}),
136
+ });
137
+ let found;
138
+ let defaults = null;
139
+ try {
140
+ const listed = await sandbox.exec(["bun", ".runtime/jobs-runner.ts", "discover", ...ours], {
141
+ cwd: "/workspace/app",
142
+ env: { RUNTIME_JOBS_PROJECT: project },
143
+ timeoutMs: 120_000,
144
+ });
145
+ const line = listed.stdout.split("\n").find((l) => l.startsWith("JOBS-DISCOVERED "));
146
+ if (!line)
147
+ throw new Error(`Reading the tasks failed:\n${listed.stderr.slice(-2000) || listed.stdout.slice(-2000)}`);
148
+ for (const failed of listed.stderr.split("\n").filter((l) => l.startsWith("JOBS-FILE-FAILED ")))
149
+ say(` could not load ${failed.slice("JOBS-FILE-FAILED ".length)}`);
150
+ const listedTasks = JSON.parse(line.slice("JOBS-DISCOVERED ".length));
151
+ found = listedTasks.tasks;
152
+ defaults = listedTasks.triggerConfig;
153
+ }
154
+ finally {
155
+ await sandbox.delete().catch(() => undefined);
156
+ }
157
+ if (!found.length)
158
+ throw new Error(`The files declare no task: ${ours.join(", ")}.`);
159
+ const existing = new Map();
160
+ for await (const job of await client.jobs.list({ limit: 100 }))
161
+ if (job.state === "active" || job.state === "paused")
162
+ existing.set(job.name, job);
163
+ const results = [];
164
+ for (const task of found) {
165
+ const name = jobNameOf(project, task.id);
166
+ if (has(args, "dry-run")) {
167
+ results.push({ id: task.id, job: name, action: "planned" });
168
+ continue;
169
+ }
170
+ // trigger.config's defaults stand for what a Trigger.dev task leaves out.
171
+ const fallback = task.kind === "trigger" ? defaults : null;
172
+ const machine = fallback?.machine ? MACHINES[fallback.machine] : undefined;
173
+ const compute = task.compute ?? machine;
174
+ const timeoutSeconds = Math.min(JOB_LIMITS.maxDurationSeconds, task.maxDuration ?? fallback?.maxDuration ?? JOB_DEFAULTS.timeoutSeconds);
175
+ const attempts = task.retry?.maxAttempts ?? fallback?.maxAttempts ?? 1;
176
+ const definition = {
177
+ image: image.id,
178
+ command: ["bun", ".runtime/jobs-runner.ts", "run", task.file, task.kind, task.id],
179
+ compute: {
180
+ vcpu: compute?.vcpu ?? 1,
181
+ memoryMiB: compute?.memoryMiB ?? 1024,
182
+ diskMiB: Math.max(JOB_DEFAULTS.diskMiB, Math.ceil(((image.sizeMiB ?? 0) + 1024) / 1024) * 1024),
183
+ durationSeconds: Math.min(JOB_LIMITS.maxDurationSeconds, timeoutSeconds + JOB_DEFAULTS.startSeconds),
184
+ ...(region ? { region } : {}),
185
+ },
186
+ timeoutSeconds,
187
+ retry: { maxAttempts: Math.min(5, attempts), backoffSeconds: 10 },
188
+ };
189
+ // A task run on demand is a template: tasks.trigger and inngest.send
190
+ // copy it into a one-off run per payload. Its own schedule is once, at
191
+ // TEMPLATE_AT, so it never runs by itself even before it is paused or
192
+ // if the pause fails; it is paused too, so the console shows it waiting.
193
+ const schedule = task.schedule
194
+ ? { cron: task.schedule.cron, timezone: task.schedule.timezone }
195
+ : { at: TEMPLATE_AT };
196
+ try {
197
+ const same = existing.get(name);
198
+ let jobId;
199
+ if (same) {
200
+ await client.jobs.update(same.id, { ...definition, command: definition.command });
201
+ await client.jobs.reschedule(same.id, schedule);
202
+ jobId = same.id;
203
+ }
204
+ else {
205
+ jobId = (await client.jobs.create({ name, schedule, ...definition })).id;
206
+ }
207
+ // A failed pause fails this task's line, and the deploy exits 1.
208
+ if (!task.schedule) {
209
+ if (same?.state !== "paused")
210
+ await client.jobs.pause(jobId);
211
+ }
212
+ else if (same?.state === "paused")
213
+ await client.jobs.resume(jobId);
214
+ results.push({ id: task.id, job: name, jobId, action: same ? "updated" : "created" });
215
+ }
216
+ catch (error) {
217
+ results.push({
218
+ id: task.id,
219
+ job: name,
220
+ error: error instanceof Error ? error.message : String(error),
221
+ });
222
+ }
223
+ }
224
+ if (out.json)
225
+ out.write(JSON.stringify({ project, image: image.id, tasks: found, results }));
226
+ else
227
+ out.write([
228
+ "",
229
+ ...found.map((task, i) => {
230
+ const r = results[i];
231
+ const when = task.schedule
232
+ ? `${task.schedule.cron} ${task.schedule.timezone}`
233
+ : task.events?.length
234
+ ? `on ${task.events.join(", ")}`
235
+ : "on demand";
236
+ return r.error
237
+ ? `✗ ${task.kind} ${task.id}: ${r.error}`
238
+ : `✓ ${task.kind} ${task.id} → job ${r.job} ${r.jobId ?? ""} (${when}) ${r.action}`;
239
+ }),
240
+ "",
241
+ `Run one now: ${me} jobs trigger <job id> && ${me} jobs logs <job id> -f`,
242
+ ].join("\n"));
243
+ return results.every((r) => !r.error) ? 0 : 1;
244
+ function has(a, name) {
245
+ return kit.has(a, name);
246
+ }
247
+ }
@@ -0,0 +1,15 @@
1
+ import type { CliKit } from "./cli.js";
2
+ import type { Runtime } from "./client.js";
3
+ import type { Image } from "./products/images.js";
4
+ type Out = {
5
+ json: boolean;
6
+ write: (text: string) => void;
7
+ error: (text: string) => void;
8
+ };
9
+ export declare const JOB_IMPORT_HELP = "runtime jobs import <file>... [--from cloud-run|aws-batch] [--parameter NAME=VALUE]...\n [--cron \"<five fields>\" [--timezone <zone>] | --at <time|now>] [--region us-east]\n [--dry-run]\n\n Move jobs from Google Cloud Run or AWS Batch. Each job runs the same container\n image, command, environment, size, timeout and retries, on the same schedule.\n\n Cloud Run: the job's YAML (gcloud run jobs describe <job> --format export), and the\n Cloud Scheduler job that runs it (gcloud scheduler jobs describe <job> --format yaml)\n AWS Batch: the job definition (register-job-definition's JSON, describe-job-definitions'\n output, or a CloudFormation template), and the EventBridge Scheduler schedule\n or EventBridge rule that submits it\n\n --parameter a CloudFormation template's value, such as AWS::Region=us-east-1\n --cron, --at the schedule for a job no schedule in the files runs\n --dry-run print the plan and each image's Dockerfile; build and create nothing\n\n A secret the job read from Secret Manager, Secrets Manager or SSM is bound from the\n jobs secret of the same name: store it first with\n printf %s \"$VALUE\" | runtime secrets set NAME --jobs\n Pulling from a private registry (Artifact Registry, ECR) needs its credential once:\n runtime images registry set <host> ...\n";
10
+ /** A wall-clock time in an IANA zone, as Unix milliseconds. */
11
+ export declare function zonedTime(local: string, timeZone: string): number;
12
+ /** The command a job of a built image runs: its start command. */
13
+ export declare function startArgv(image: Pick<Image, "start">): string[] | undefined;
14
+ export declare function jobsImportCommand(argv: string[], out: Out, runtime: () => Promise<Runtime>, kit: CliKit): Promise<number>;
15
+ export {};
@@ -0,0 +1,231 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename } from "node:path";
3
+ import { me } from "./cli-name.js";
4
+ import { JOB_DEFAULTS, JOB_LIMITS, } from "./products/jobs.js";
5
+ export const JOB_IMPORT_HELP = `runtime jobs import <file>... [--from cloud-run|aws-batch] [--parameter NAME=VALUE]...
6
+ [--cron "<five fields>" [--timezone <zone>] | --at <time|now>] [--region us-east]
7
+ [--dry-run]
8
+
9
+ Move jobs from Google Cloud Run or AWS Batch. Each job runs the same container
10
+ image, command, environment, size, timeout and retries, on the same schedule.
11
+
12
+ Cloud Run: the job's YAML (gcloud run jobs describe <job> --format export), and the
13
+ Cloud Scheduler job that runs it (gcloud scheduler jobs describe <job> --format yaml)
14
+ AWS Batch: the job definition (register-job-definition's JSON, describe-job-definitions'
15
+ output, or a CloudFormation template), and the EventBridge Scheduler schedule
16
+ or EventBridge rule that submits it
17
+
18
+ --parameter a CloudFormation template's value, such as AWS::Region=us-east-1
19
+ --cron, --at the schedule for a job no schedule in the files runs
20
+ --dry-run print the plan and each image's Dockerfile; build and create nothing
21
+
22
+ A secret the job read from Secret Manager, Secrets Manager or SSM is bound from the
23
+ jobs secret of the same name: store it first with
24
+ printf %s "$VALUE" | runtime secrets set NAME --jobs
25
+ Pulling from a private registry (Artifact Registry, ECR) needs its credential once:
26
+ runtime images registry set <host> ...
27
+ `;
28
+ /** A wall-clock time in an IANA zone, as Unix milliseconds. */
29
+ export function zonedTime(local, timeZone) {
30
+ const found = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/.exec(local.trim());
31
+ if (!found)
32
+ throw new Error(`${local} is not a time such as 2026-11-01T03:00:00`);
33
+ const [y, mo, d, h, mi, s] = found.slice(1).map((n) => Number(n ?? 0));
34
+ const guess = Date.UTC(y, mo - 1, d, h, mi, s ?? 0);
35
+ // The zone's offset at the guess, then again at the corrected instant.
36
+ const offset = (at) => {
37
+ const parts = new Intl.DateTimeFormat("en-US", {
38
+ timeZone,
39
+ hourCycle: "h23",
40
+ year: "numeric",
41
+ month: "2-digit",
42
+ day: "2-digit",
43
+ hour: "2-digit",
44
+ minute: "2-digit",
45
+ second: "2-digit",
46
+ }).formatToParts(new Date(at));
47
+ const n = (type) => Number(parts.find((p) => p.type === type)?.value);
48
+ return Date.UTC(n("year"), n("month") - 1, n("day"), n("hour"), n("minute"), n("second")) - at;
49
+ };
50
+ const first = guess - offset(guess);
51
+ return guess - offset(first);
52
+ }
53
+ /** The command a job of a built image runs: its start command. */
54
+ export function startArgv(image) {
55
+ if (image.start?.argv?.length)
56
+ return image.start.argv;
57
+ if (image.start?.command)
58
+ return ["sh", "-c", image.start.command];
59
+ return undefined;
60
+ }
61
+ function planLines(plan) {
62
+ const lines = [
63
+ `Read ${plan.read.join(", ")} as ${plan.from === "cloud-run" ? "Cloud Run" : "AWS Batch"}.`,
64
+ ];
65
+ for (const job of plan.jobs) {
66
+ const when = !job.schedule
67
+ ? "no schedule"
68
+ : job.schedule.kind === "cron"
69
+ ? `${job.schedule.expression} ${job.schedule.timezone}`
70
+ : `once at ${job.schedule.at} ${job.schedule.timezone}`;
71
+ lines.push("", `${job.blocked ? "✗" : "✓"} ${job.name} ${job.sourceImage}`, ` ${job.compute.vcpu} vCPU, ${job.compute.memoryMib} MiB, timeout ${job.timeoutSeconds} s, ${job.retry.maxAttempts} attempt${job.retry.maxAttempts === 1 ? "" : "s"}, ${when}`);
72
+ if (job.command)
73
+ lines.push(` runs ${job.command.join(" ")}`);
74
+ if (job.secrets.length)
75
+ lines.push(` secrets: ${job.secrets.map((s) => `${s.name} (from ${s.from})`).join(", ")}`);
76
+ if (job.blocked)
77
+ lines.push(` not moved: ${job.blocked}`);
78
+ }
79
+ const marks = { unmapped: "left out", changed: "changed", info: "note" };
80
+ if (plan.notes.length)
81
+ lines.push("");
82
+ for (const note of plan.notes)
83
+ lines.push(` ${marks[note.level]}: ${note.job ? `${note.job}: ` : ""}${note.message} (${note.file} ${note.key})`);
84
+ return lines;
85
+ }
86
+ export async function jobsImportCommand(argv, out, runtime, kit) {
87
+ if (argv[0] === "help" || argv[0] === "--help") {
88
+ out.write(out.json ? JSON.stringify({ usage: JOB_IMPORT_HELP }) : JOB_IMPORT_HELP);
89
+ return 0;
90
+ }
91
+ const args = kit.parse(argv, ["dry-run"], ["from", "parameter", "cron", "timezone", "at", "region"]);
92
+ if (!args.positional.length)
93
+ throw kit.usage(`Name the files: ${me} jobs import job.yaml scheduler.yaml`);
94
+ const from = kit.flag(args, "from");
95
+ if (from !== undefined && from !== "cloud-run" && from !== "aws-batch")
96
+ throw kit.usage(`--from is cloud-run or aws-batch, not ${from}.`);
97
+ const cron = kit.flag(args, "cron");
98
+ const at = kit.flag(args, "at");
99
+ if (cron !== undefined && at !== undefined)
100
+ throw kit.usage("Give --cron or --at, not both.");
101
+ const files = await Promise.all(args.positional.map(async (path) => ({
102
+ path: basename(path),
103
+ text: await readFile(path, "utf8"),
104
+ })));
105
+ const parameters = kit.pairs(args, "parameter");
106
+ const client = await runtime();
107
+ const plan = await client.jobs.importPlan({
108
+ files,
109
+ ...(from ? { from } : {}),
110
+ ...(Object.keys(parameters).length ? { parameters } : {}),
111
+ });
112
+ if (!out.json)
113
+ out.write(planLines(plan).join("\n"));
114
+ if (has(args, "dry-run")) {
115
+ if (out.json)
116
+ out.write(JSON.stringify(plan));
117
+ // The build file each job's image would be built from, whole, so what
118
+ // runs is read before anything is built.
119
+ else
120
+ for (const job of plan.jobs)
121
+ if (job.dockerfile)
122
+ out.write(`\n${job.name}: its image's Dockerfile\n${job.dockerfile}`);
123
+ return plan.importable ? 0 : 1;
124
+ }
125
+ const secrets = plan.jobs.some((j) => j.secrets.length) ? await client.secrets.all() : [];
126
+ const existing = [];
127
+ for await (const job of await client.jobs.list({ limit: 100 }))
128
+ if (job.state === "active" || job.state === "paused")
129
+ existing.push(job);
130
+ const results = [];
131
+ for (const job of plan.jobs) {
132
+ if (job.blocked) {
133
+ results.push({ name: job.name, refused: job.blocked });
134
+ continue;
135
+ }
136
+ try {
137
+ results.push({
138
+ name: job.name,
139
+ ...(await move(client, job, { secrets, existing, cron, at, args, kit, out })),
140
+ });
141
+ }
142
+ catch (error) {
143
+ results.push({
144
+ name: job.name,
145
+ refused: error instanceof Error ? error.message : String(error),
146
+ });
147
+ }
148
+ }
149
+ if (out.json)
150
+ out.write(JSON.stringify({ plan, results }));
151
+ else
152
+ out.write([
153
+ "",
154
+ ...results.map((r) => r.refused
155
+ ? `✗ ${r.name}: ${r.refused}`
156
+ : `✓ ${r.name} ${r.action} ${r.id} (image ${r.image})`),
157
+ ...(results.some((r) => r.id)
158
+ ? [``, `Run one now: ${me} jobs trigger <id> && ${me} jobs logs <id> -f`]
159
+ : []),
160
+ ].join("\n"));
161
+ return results.every((r) => r.id) ? 0 : 1;
162
+ function has(a, name) {
163
+ return kit.has(a, name);
164
+ }
165
+ }
166
+ async function move(client, job, context) {
167
+ const { kit, args } = context;
168
+ const bindings = job.secrets.map((needed) => {
169
+ const found = context.secrets.find((s) => s.name === needed.name)?.jobs;
170
+ if (!found)
171
+ throw new Error(`${needed.name} came from ${needed.from}; store it for jobs first: printf %s "$VALUE" | ${me} secrets set ${needed.name} --jobs`);
172
+ return { name: needed.name, secretId: found.id };
173
+ });
174
+ const schedule = context.cron
175
+ ? {
176
+ cron: context.cron,
177
+ ...(kit.flag(args, "timezone") ? { timezone: kit.flag(args, "timezone") } : {}),
178
+ }
179
+ : context.at
180
+ ? { at: context.at === "now" ? Date.now() : Date.parse(context.at) }
181
+ : job.schedule?.kind === "cron"
182
+ ? { cron: job.schedule.expression, timezone: job.schedule.timezone }
183
+ : job.schedule?.kind === "once"
184
+ ? { at: zonedTime(job.schedule.at, job.schedule.timezone) }
185
+ : undefined;
186
+ if (!schedule)
187
+ throw new Error(`no schedule in the files runs it: give one with --cron "<five fields>" or --at now`);
188
+ if (!context.out.json)
189
+ context.out.write(`Building ${job.name}'s image from ${job.sourceImage}...`);
190
+ const image = await client.images.build({
191
+ name: `job-${job.name}`.slice(0, 63),
192
+ dockerfile: job.dockerfile,
193
+ ...(kit.flag(args, "region") ? { region: kit.flag(args, "region") } : {}),
194
+ });
195
+ const argv = startArgv(image);
196
+ if (!argv)
197
+ throw new Error(`${job.sourceImage} names no command (no ENTRYPOINT or CMD) and the file gives none`);
198
+ const imageMiB = image.sizeMiB ?? 0;
199
+ const diskMiB = Math.max(job.compute.diskMib ?? 4096, Math.ceil((imageMiB + 1024) / 1024) * 1024);
200
+ const compute = {
201
+ vcpu: job.compute.vcpu,
202
+ memoryMiB: job.compute.memoryMib + (job.compute.memoryMib % 2),
203
+ diskMiB,
204
+ durationSeconds: Math.min(JOB_LIMITS.maxDurationSeconds, job.timeoutSeconds + JOB_DEFAULTS.startSeconds),
205
+ ...(kit.flag(args, "region") ? { region: kit.flag(args, "region") } : {}),
206
+ };
207
+ const same = context.existing.find((j) => j.name === job.name);
208
+ if (same) {
209
+ await client.jobs.update(same.id, {
210
+ image: image.id,
211
+ command: argv,
212
+ compute,
213
+ timeoutSeconds: job.timeoutSeconds,
214
+ retry: job.retry,
215
+ secrets: bindings,
216
+ });
217
+ await client.jobs.reschedule(same.id, schedule);
218
+ return { id: same.id, image: `${image.name}@${image.version}`, action: "updated" };
219
+ }
220
+ const made = await client.jobs.create({
221
+ name: job.name,
222
+ schedule,
223
+ image: image.id,
224
+ command: argv,
225
+ compute,
226
+ timeoutSeconds: job.timeoutSeconds,
227
+ retry: job.retry,
228
+ ...(bindings.length ? { secrets: bindings } : {}),
229
+ });
230
+ return { id: made.id, image: `${image.name}@${image.version}`, action: "created" };
231
+ }