@alineo-labs/workflow 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.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ # @alineo-labs/workflow
2
+
3
+ Lazy pipeline builder for [alineo](https://alineo.tech) — retry, conditional branching, fan-out, and parallel sandboxes, all flushed in one `await`.
4
+
5
+ ```bash
6
+ bun add @alineo-labs/workflow
7
+ ```
8
+
9
+ **[Full documentation →](https://docs.alineo.tech/docs/workflow)**
10
+
11
+ ---
12
+
13
+ ## How it works
14
+
15
+ `workflow(client).sandbox(opts, fn)` returns a builder. The `fn` callback receives a `SandboxBuilder` — all methods on it queue operations synchronously. Nothing runs until you `await .pipe()` or `.result()`.
16
+
17
+ ```ts
18
+ import { workflow } from "@alineo-labs/workflow";
19
+
20
+ await workflow(client)
21
+ .sandbox({ image: "node:20-slim", resources: { cpu: "1", memory: "512Mi" } }, (sb) => {
22
+ sb.exec("npm ci");
23
+ sb.exec("npm run build");
24
+ sb.exec("npm test");
25
+ })
26
+ .pipe(process.stdout);
27
+ ```
28
+
29
+ ---
30
+
31
+ ## Retry
32
+
33
+ ```ts
34
+ sb.retry(
35
+ 3,
36
+ (r) => {
37
+ r.exec("flaky-network-call");
38
+ },
39
+ { delayMs: 500, backoff: "exponential" },
40
+ );
41
+ ```
42
+
43
+ ## Conditional branching
44
+
45
+ The predicate receives `{ stdout, exitCode, vars }` from the previous step.
46
+
47
+ ```ts
48
+ sb.exec("test -f /app/build.sh", { strict: false });
49
+ sb.when(
50
+ (ctx) => ctx.exitCode === 0,
51
+ (s) => s.exec("bash /app/build.sh"),
52
+ (s) => s.exec("echo 'no build script'"),
53
+ );
54
+ ```
55
+
56
+ ## Fan-out
57
+
58
+ ```ts
59
+ sb.forEach(
60
+ ["a.ts", "b.ts", "c.ts"],
61
+ (s, file) => {
62
+ s.exec(`tsc --noEmit ${file}`);
63
+ },
64
+ { concurrency: 4 },
65
+ );
66
+ ```
67
+
68
+ ## Capture a value
69
+
70
+ `sb.readFile(path, as)` stores file contents in `vars[as]` on the result object.
71
+
72
+ ```ts
73
+ const { vars } = await workflow(client)
74
+ .sandbox({ image: "node:20-slim", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
75
+ sb.exec(`node -e "require('fs').writeFileSync('/out.txt', process.version)"`);
76
+ sb.readFile("/out.txt", "nodeVersion");
77
+ })
78
+ .result();
79
+
80
+ console.log(vars.nodeVersion); // "v20.x.x"
81
+ ```
82
+
83
+ ## Parallel sandboxes
84
+
85
+ Run the same builder across multiple configs simultaneously:
86
+
87
+ ```ts
88
+ await workflow(client)
89
+ .parallel(
90
+ [
91
+ { image: "node:18-slim", resources: { cpu: "500m", memory: "256Mi" } },
92
+ { image: "node:20-slim", resources: { cpu: "500m", memory: "256Mi" } },
93
+ { image: "node:22-slim", resources: { cpu: "500m", memory: "256Mi" } },
94
+ ],
95
+ (sb) => {
96
+ sb.exec("node --version");
97
+ sb.exec("npm ci && npm test");
98
+ },
99
+ )
100
+ .pipe(process.stdout);
101
+ ```
102
+
103
+ ## Sequential pipeline
104
+
105
+ Pass work across sandboxes in order, each starting fresh:
106
+
107
+ ```ts
108
+ await workflow(client)
109
+ .sequence([
110
+ {
111
+ image: "node:20-slim",
112
+ resources: { cpu: "1", memory: "512Mi" },
113
+ run: (sb) => {
114
+ sb.exec("npm ci");
115
+ sb.exec("npm run build");
116
+ },
117
+ },
118
+ {
119
+ image: "alpine:3",
120
+ resources: { cpu: "500m", memory: "256Mi" },
121
+ run: (sb) => {
122
+ sb.exec("ls /app/dist");
123
+ },
124
+ },
125
+ ])
126
+ .pipe(process.stdout);
127
+ ```
128
+
129
+ ---
130
+
131
+ ## License
132
+
133
+ Apache 2.0
@@ -0,0 +1,231 @@
1
+ import { Alineo, ExecCodeOptions, ExecOptions, SandboxOptions } from "alineo";
2
+
3
+ //#region src/sandbox-builder.d.ts
4
+ /** An operation queued on a SandboxBuilder and executed later. */
5
+ type SandboxOp = {
6
+ kind: "exec";
7
+ cmd: string;
8
+ opts: ExecOptions;
9
+ } | {
10
+ kind: "execCode";
11
+ code: string;
12
+ opts: ExecCodeOptions;
13
+ } | {
14
+ kind: "writeFile";
15
+ path: string;
16
+ content: string;
17
+ } | {
18
+ kind: "readFile";
19
+ path: string;
20
+ as: string;
21
+ } | {
22
+ kind: "deleteFile";
23
+ path: string;
24
+ } | {
25
+ kind: "moveFile";
26
+ from: string;
27
+ to: string;
28
+ } | {
29
+ kind: "checkpoint";
30
+ name?: string;
31
+ } | {
32
+ kind: "retry";
33
+ maxAttempts: number;
34
+ fn: (sb: SandboxBuilder) => void;
35
+ opts: RetryOptions;
36
+ } | {
37
+ kind: "when";
38
+ pred: WhenPredicate;
39
+ then: (sb: SandboxBuilder) => void;
40
+ else?: (sb: SandboxBuilder) => void;
41
+ } | {
42
+ kind: "forEach";
43
+ items: unknown[];
44
+ fn: (sb: SandboxBuilder, item: unknown, index: number) => void;
45
+ opts: ForEachOptions;
46
+ };
47
+ interface RetryOptions {
48
+ backoff?: "fixed" | "exponential";
49
+ delayMs?: number;
50
+ }
51
+ type WhenPredicate = (ctx: {
52
+ stdout: string;
53
+ exitCode: number;
54
+ vars: Record<string, unknown>;
55
+ }) => boolean;
56
+ interface ForEachOptions {
57
+ concurrency?: number;
58
+ }
59
+ /**
60
+ * Synchronous lazy builder for sandbox operations.
61
+ *
62
+ * All methods queue an operation and return `this` — no awaits, no async.
63
+ * The queue is flushed when `WorkflowBuilder.pipe()` or `.result()` is called.
64
+ * This gives a single `await` at the end regardless of workflow complexity.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * await workflow(client)
69
+ * .sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
70
+ * sb.exec("npm ci")
71
+ * sb.checkpoint()
72
+ * sb.retry(3, (sb) => sb.exec("npm test"), { backoff: "exponential" })
73
+ * })
74
+ * .pipe(process.stdout);
75
+ * ```
76
+ */
77
+ declare class SandboxBuilder {
78
+ readonly _ops: SandboxOp[];
79
+ /** Queue a shell command. */
80
+ exec(cmd: string, opts?: ExecOptions): this;
81
+ /** Queue a code execution (Python/JS/TS via execd code interpreter). */
82
+ execCode(code: string, opts?: ExecCodeOptions): this;
83
+ /** Queue a file write into the sandbox. */
84
+ writeFile(path: string, content: string): this;
85
+ /** Queue a file read from the sandbox, stored in `vars[as]`. */
86
+ readFile(path: string, as: string): this;
87
+ /** Queue a file deletion inside the sandbox. */
88
+ deleteFile(path: string): this;
89
+ /** Queue a file move/rename inside the sandbox. */
90
+ moveFile(from: string, to: string): this;
91
+ /** Queue a checkpoint (snapshot). */
92
+ checkpoint(name?: string): this;
93
+ /**
94
+ * Retry an inner builder callback up to `maxAttempts` times on failure.
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * sb.retry(3, (sb) => sb.exec("npm test"), { backoff: "exponential" })
99
+ * ```
100
+ */
101
+ retry(maxAttempts: number, fn: (sb: SandboxBuilder) => void, opts?: RetryOptions): this;
102
+ /**
103
+ * Conditionally execute one of two builder callbacks based on a predicate.
104
+ *
105
+ * The predicate receives the current `FlushContext`: `stdout` accumulated
106
+ * across every exec run so far in this sandbox, `exitCode` from the most
107
+ * recent exec, and `vars` captured so far.
108
+ *
109
+ * @example
110
+ * ```ts
111
+ * sb.when(
112
+ * (ctx) => ctx.exitCode === 0,
113
+ * (sb) => sb.exec("echo success"),
114
+ * (sb) => sb.exec("echo failure"),
115
+ * )
116
+ * ```
117
+ */
118
+ when(pred: WhenPredicate, then: (sb: SandboxBuilder) => void, otherwise?: (sb: SandboxBuilder) => void): this;
119
+ /**
120
+ * Execute a builder callback for each item in `items`, optionally in parallel.
121
+ *
122
+ * @example
123
+ * ```ts
124
+ * sb.forEach(["a", "b", "c"], (sb, item) => sb.exec(`echo ${item}`))
125
+ * ```
126
+ */
127
+ forEach(items: unknown[], fn: (sb: SandboxBuilder, item: unknown, index: number) => void, opts?: ForEachOptions): this;
128
+ }
129
+ //#endregion
130
+ //#region src/workflow-builder.d.ts
131
+ interface WorkflowResult {
132
+ /** Concatenated stdout from all sandboxes in the workflow. */
133
+ stdout: string;
134
+ /** Named values captured by `sb.readFile(path, as)`. */
135
+ vars: Record<string, unknown>;
136
+ }
137
+ /** A single step in a `.sequence()` call. */
138
+ interface SequenceStep {
139
+ image: SandboxOptions["image"];
140
+ resources: SandboxOptions["resources"];
141
+ env?: SandboxOptions["env"];
142
+ timeout?: SandboxOptions["timeout"];
143
+ name?: string;
144
+ run: (sb: SandboxBuilder, prevResult?: WorkflowResult) => void;
145
+ }
146
+ /**
147
+ * Lazy workflow builder. Collects stages and executes them all when `.pipe()` or
148
+ * `.result()` is awaited. Sandboxes are created via the `Alineo` client internally
149
+ * — the user never manages sandbox lifecycle when using this layer.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * import { workflow } from "@alineo-labs/workflow";
154
+ *
155
+ * await workflow(client)
156
+ * .sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
157
+ * sb.exec("npm ci")
158
+ * sb.checkpoint()
159
+ * sb.retry(3, (sb) => sb.exec("npm test"), { backoff: "exponential" })
160
+ * })
161
+ * .pipe(process.stdout);
162
+ * ```
163
+ */
164
+ declare class WorkflowBuilder {
165
+ private readonly _client;
166
+ private readonly _stages;
167
+ constructor(client: Alineo);
168
+ /**
169
+ * Add a sandbox stage. The `fn` callback receives a `SandboxBuilder` to
170
+ * queue operations synchronously. Sandboxes across multiple `.sandbox()` calls
171
+ * run sequentially, top-to-bottom.
172
+ */
173
+ sandbox(opts: SandboxOptions, fn: (sb: SandboxBuilder) => void): this;
174
+ /**
175
+ * Run the same operation across multiple sandbox configurations in parallel.
176
+ * All sandboxes receive the same `fn` callback.
177
+ *
178
+ * @example
179
+ * ```ts
180
+ * await workflow(client)
181
+ * .parallel(
182
+ * [{ image: "node:20" }, { image: "node:22" }, { image: "node:24" }],
183
+ * (sb) => sb.exec("npm test"),
184
+ * )
185
+ * .pipe(process.stdout);
186
+ * ```
187
+ */
188
+ parallel(configs: SandboxOptions[], fn: (sb: SandboxBuilder) => void): this;
189
+ /**
190
+ * Run sandboxes in sequence, passing the previous stage's result to the next.
191
+ *
192
+ * @example
193
+ * ```ts
194
+ * await workflow(client)
195
+ * .sequence([
196
+ * { image: "node:22", run: (sb) => sb.exec("npm run build") },
197
+ * { image: "ubuntu:22.04", run: (sb, prev) => sb.exec("./deploy.sh") },
198
+ * ])
199
+ * .pipe(process.stdout);
200
+ * ```
201
+ */
202
+ sequence(steps: SequenceStep[]): this;
203
+ /** Execute the workflow and pipe stdout to a writable. */
204
+ pipe(writable: {
205
+ write(chunk: string): unknown;
206
+ }): Promise<void>;
207
+ /** Execute the workflow and return the full result. */
208
+ result(): Promise<WorkflowResult>;
209
+ private _execute;
210
+ private _runSandbox;
211
+ private _runParallel;
212
+ private _runSequence;
213
+ }
214
+ /**
215
+ * Create a workflow builder attached to a `Alineo` client.
216
+ *
217
+ * @example
218
+ * ```ts
219
+ * import { workflow } from "@alineo-labs/workflow";
220
+ *
221
+ * await workflow(client)
222
+ * .sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
223
+ * sb.exec("npm ci")
224
+ * sb.exec("npm test")
225
+ * })
226
+ * .pipe(process.stdout);
227
+ * ```
228
+ */
229
+ declare function workflow(client: Alineo): WorkflowBuilder;
230
+ //#endregion
231
+ export { type ForEachOptions, type RetryOptions, SandboxBuilder, type SandboxOp, type SequenceStep, type WhenPredicate, WorkflowBuilder, type WorkflowResult, workflow };
package/dist/index.mjs ADDED
@@ -0,0 +1,425 @@
1
+ //#region src/sandbox-builder.ts
2
+ /**
3
+ * Synchronous lazy builder for sandbox operations.
4
+ *
5
+ * All methods queue an operation and return `this` — no awaits, no async.
6
+ * The queue is flushed when `WorkflowBuilder.pipe()` or `.result()` is called.
7
+ * This gives a single `await` at the end regardless of workflow complexity.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * await workflow(client)
12
+ * .sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
13
+ * sb.exec("npm ci")
14
+ * sb.checkpoint()
15
+ * sb.retry(3, (sb) => sb.exec("npm test"), { backoff: "exponential" })
16
+ * })
17
+ * .pipe(process.stdout);
18
+ * ```
19
+ */
20
+ var SandboxBuilder = class {
21
+ _ops = [];
22
+ /** Queue a shell command. */
23
+ exec(cmd, opts = {}) {
24
+ this._ops.push({
25
+ kind: "exec",
26
+ cmd,
27
+ opts
28
+ });
29
+ return this;
30
+ }
31
+ /** Queue a code execution (Python/JS/TS via execd code interpreter). */
32
+ execCode(code, opts = {}) {
33
+ this._ops.push({
34
+ kind: "execCode",
35
+ code,
36
+ opts
37
+ });
38
+ return this;
39
+ }
40
+ /** Queue a file write into the sandbox. */
41
+ writeFile(path, content) {
42
+ this._ops.push({
43
+ kind: "writeFile",
44
+ path,
45
+ content
46
+ });
47
+ return this;
48
+ }
49
+ /** Queue a file read from the sandbox, stored in `vars[as]`. */
50
+ readFile(path, as) {
51
+ this._ops.push({
52
+ kind: "readFile",
53
+ path,
54
+ as
55
+ });
56
+ return this;
57
+ }
58
+ /** Queue a file deletion inside the sandbox. */
59
+ deleteFile(path) {
60
+ this._ops.push({
61
+ kind: "deleteFile",
62
+ path
63
+ });
64
+ return this;
65
+ }
66
+ /** Queue a file move/rename inside the sandbox. */
67
+ moveFile(from, to) {
68
+ this._ops.push({
69
+ kind: "moveFile",
70
+ from,
71
+ to
72
+ });
73
+ return this;
74
+ }
75
+ /** Queue a checkpoint (snapshot). */
76
+ checkpoint(name) {
77
+ this._ops.push({
78
+ kind: "checkpoint",
79
+ name
80
+ });
81
+ return this;
82
+ }
83
+ /**
84
+ * Retry an inner builder callback up to `maxAttempts` times on failure.
85
+ *
86
+ * @example
87
+ * ```ts
88
+ * sb.retry(3, (sb) => sb.exec("npm test"), { backoff: "exponential" })
89
+ * ```
90
+ */
91
+ retry(maxAttempts, fn, opts = {}) {
92
+ this._ops.push({
93
+ kind: "retry",
94
+ maxAttempts,
95
+ fn,
96
+ opts
97
+ });
98
+ return this;
99
+ }
100
+ /**
101
+ * Conditionally execute one of two builder callbacks based on a predicate.
102
+ *
103
+ * The predicate receives the current `FlushContext`: `stdout` accumulated
104
+ * across every exec run so far in this sandbox, `exitCode` from the most
105
+ * recent exec, and `vars` captured so far.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * sb.when(
110
+ * (ctx) => ctx.exitCode === 0,
111
+ * (sb) => sb.exec("echo success"),
112
+ * (sb) => sb.exec("echo failure"),
113
+ * )
114
+ * ```
115
+ */
116
+ when(pred, then, otherwise) {
117
+ this._ops.push({
118
+ kind: "when",
119
+ pred,
120
+ then,
121
+ else: otherwise
122
+ });
123
+ return this;
124
+ }
125
+ /**
126
+ * Execute a builder callback for each item in `items`, optionally in parallel.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * sb.forEach(["a", "b", "c"], (sb, item) => sb.exec(`echo ${item}`))
131
+ * ```
132
+ */
133
+ forEach(items, fn, opts = {}) {
134
+ this._ops.push({
135
+ kind: "forEach",
136
+ items,
137
+ fn,
138
+ opts
139
+ });
140
+ return this;
141
+ }
142
+ };
143
+ /** Flush a SandboxBuilder's op queue against a live Sandbox. */
144
+ async function flushOps(sandbox, ops, ctx) {
145
+ for (const op of ops) switch (op.kind) {
146
+ case "exec": {
147
+ const handle = sandbox.exec(op.cmd, op.opts);
148
+ if (ctx.sink) {
149
+ for await (const chunk of handle.stdout()) {
150
+ ctx.stdout += chunk;
151
+ ctx.sink.write(chunk);
152
+ }
153
+ ctx.exitCode = (await handle.result()).exitCode;
154
+ } else {
155
+ const result = await handle;
156
+ ctx.stdout += result.stdout;
157
+ ctx.exitCode = result.exitCode;
158
+ }
159
+ break;
160
+ }
161
+ case "execCode": {
162
+ const handle = sandbox.execCode(op.code, op.opts);
163
+ if (ctx.sink) {
164
+ for await (const chunk of handle.stdout()) {
165
+ ctx.stdout += chunk;
166
+ ctx.sink.write(chunk);
167
+ }
168
+ ctx.exitCode = (await handle.result()).exitCode;
169
+ } else {
170
+ const result = await handle;
171
+ ctx.stdout += result.stdout;
172
+ ctx.exitCode = result.exitCode;
173
+ }
174
+ break;
175
+ }
176
+ case "writeFile":
177
+ await sandbox.writeFile(op.path, op.content);
178
+ break;
179
+ case "readFile": {
180
+ const content = await sandbox.readFile(op.path);
181
+ ctx.vars[op.as] = content;
182
+ break;
183
+ }
184
+ case "deleteFile":
185
+ await sandbox.deleteFile(op.path);
186
+ break;
187
+ case "moveFile":
188
+ await sandbox.moveFile(op.from, op.to);
189
+ break;
190
+ case "checkpoint":
191
+ await sandbox.checkpoint(op.name);
192
+ break;
193
+ case "retry":
194
+ await flushRetry(sandbox, op.fn, op.maxAttempts, op.opts, ctx);
195
+ break;
196
+ case "when": {
197
+ const branch = op.pred(ctx) ? op.then : op["else"];
198
+ if (branch) {
199
+ const inner = new SandboxBuilder();
200
+ branch(inner);
201
+ await flushOps(sandbox, inner._ops, ctx);
202
+ }
203
+ break;
204
+ }
205
+ case "forEach":
206
+ await flushForEach(sandbox, op.items, op.fn, op.opts, ctx);
207
+ break;
208
+ }
209
+ }
210
+ async function flushRetry(sandbox, fn, maxAttempts, opts, ctx) {
211
+ let lastErr;
212
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
213
+ if (attempt > 0) {
214
+ const base = opts.delayMs ?? 1e3;
215
+ const delay = opts.backoff === "exponential" ? base * 2 ** (attempt - 1) : base;
216
+ await new Promise((r) => setTimeout(r, delay));
217
+ }
218
+ try {
219
+ const inner = new SandboxBuilder();
220
+ fn(inner);
221
+ await flushOps(sandbox, inner._ops, ctx);
222
+ return;
223
+ } catch (err) {
224
+ lastErr = err;
225
+ }
226
+ }
227
+ throw lastErr;
228
+ }
229
+ async function flushForEach(sandbox, items, fn, opts, ctx) {
230
+ const concurrency = opts.concurrency ?? 1;
231
+ if (concurrency <= 1) for (let i = 0; i < items.length; i++) {
232
+ const inner = new SandboxBuilder();
233
+ fn(inner, items[i], i);
234
+ await flushOps(sandbox, inner._ops, ctx);
235
+ }
236
+ else {
237
+ let idx = 0;
238
+ async function worker() {
239
+ while (idx < items.length) {
240
+ const i = idx++;
241
+ const inner = new SandboxBuilder();
242
+ fn(inner, items[i], i);
243
+ await flushOps(sandbox, inner._ops, { ...ctx });
244
+ }
245
+ }
246
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, worker);
247
+ await Promise.all(workers);
248
+ }
249
+ }
250
+ //#endregion
251
+ //#region src/workflow-builder.ts
252
+ /**
253
+ * Lazy workflow builder. Collects stages and executes them all when `.pipe()` or
254
+ * `.result()` is awaited. Sandboxes are created via the `Alineo` client internally
255
+ * — the user never manages sandbox lifecycle when using this layer.
256
+ *
257
+ * @example
258
+ * ```ts
259
+ * import { workflow } from "@alineo-labs/workflow";
260
+ *
261
+ * await workflow(client)
262
+ * .sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
263
+ * sb.exec("npm ci")
264
+ * sb.checkpoint()
265
+ * sb.retry(3, (sb) => sb.exec("npm test"), { backoff: "exponential" })
266
+ * })
267
+ * .pipe(process.stdout);
268
+ * ```
269
+ */
270
+ var WorkflowBuilder = class {
271
+ _client;
272
+ _stages = [];
273
+ constructor(client) {
274
+ this._client = client;
275
+ }
276
+ /**
277
+ * Add a sandbox stage. The `fn` callback receives a `SandboxBuilder` to
278
+ * queue operations synchronously. Sandboxes across multiple `.sandbox()` calls
279
+ * run sequentially, top-to-bottom.
280
+ */
281
+ sandbox(opts, fn) {
282
+ this._stages.push({
283
+ type: "sandbox",
284
+ opts,
285
+ fn
286
+ });
287
+ return this;
288
+ }
289
+ /**
290
+ * Run the same operation across multiple sandbox configurations in parallel.
291
+ * All sandboxes receive the same `fn` callback.
292
+ *
293
+ * @example
294
+ * ```ts
295
+ * await workflow(client)
296
+ * .parallel(
297
+ * [{ image: "node:20" }, { image: "node:22" }, { image: "node:24" }],
298
+ * (sb) => sb.exec("npm test"),
299
+ * )
300
+ * .pipe(process.stdout);
301
+ * ```
302
+ */
303
+ parallel(configs, fn) {
304
+ this._stages.push({
305
+ type: "parallel",
306
+ configs,
307
+ fn
308
+ });
309
+ return this;
310
+ }
311
+ /**
312
+ * Run sandboxes in sequence, passing the previous stage's result to the next.
313
+ *
314
+ * @example
315
+ * ```ts
316
+ * await workflow(client)
317
+ * .sequence([
318
+ * { image: "node:22", run: (sb) => sb.exec("npm run build") },
319
+ * { image: "ubuntu:22.04", run: (sb, prev) => sb.exec("./deploy.sh") },
320
+ * ])
321
+ * .pipe(process.stdout);
322
+ * ```
323
+ */
324
+ sequence(steps) {
325
+ this._stages.push({
326
+ type: "sequence",
327
+ steps
328
+ });
329
+ return this;
330
+ }
331
+ /** Execute the workflow and pipe stdout to a writable. */
332
+ async pipe(writable) {
333
+ await this._execute(writable);
334
+ }
335
+ /** Execute the workflow and return the full result. */
336
+ async result() {
337
+ return this._execute(void 0);
338
+ }
339
+ async _execute(sink) {
340
+ const combined = {
341
+ stdout: "",
342
+ vars: {}
343
+ };
344
+ for (const stage of this._stages) if (stage.type === "sandbox") {
345
+ const result = await this._runSandbox(stage.opts, stage.fn, sink);
346
+ combined.stdout += result.stdout;
347
+ Object.assign(combined.vars, result.vars);
348
+ } else if (stage.type === "parallel") {
349
+ const results = await this._runParallel(stage.configs, stage.fn, sink);
350
+ for (const r of results) {
351
+ combined.stdout += r.stdout;
352
+ Object.assign(combined.vars, r.vars);
353
+ }
354
+ } else if (stage.type === "sequence") {
355
+ const result = await this._runSequence(stage.steps, sink);
356
+ combined.stdout += result.stdout;
357
+ Object.assign(combined.vars, result.vars);
358
+ }
359
+ return combined;
360
+ }
361
+ async _runSandbox(opts, fn, sink) {
362
+ const sb = new SandboxBuilder();
363
+ fn(sb);
364
+ const sandbox = await this._client.sandbox(opts);
365
+ try {
366
+ const ctx = {
367
+ stdout: "",
368
+ exitCode: 0,
369
+ vars: {},
370
+ sink
371
+ };
372
+ await flushOps(sandbox, sb._ops, ctx);
373
+ return {
374
+ stdout: ctx.stdout,
375
+ vars: ctx.vars
376
+ };
377
+ } finally {
378
+ await sandbox.close();
379
+ }
380
+ }
381
+ async _runParallel(configs, fn, sink) {
382
+ return Promise.all(configs.map((opts) => this._runSandbox(opts, fn, sink)));
383
+ }
384
+ async _runSequence(steps, sink) {
385
+ const combined = {
386
+ stdout: "",
387
+ vars: {}
388
+ };
389
+ let prev;
390
+ for (const step of steps) {
391
+ const opts = {
392
+ image: step.image,
393
+ resources: step.resources,
394
+ env: step.env,
395
+ timeout: step.timeout,
396
+ name: step.name
397
+ };
398
+ const result = await this._runSandbox(opts, (sb) => step.run(sb, prev), sink);
399
+ combined.stdout += result.stdout;
400
+ Object.assign(combined.vars, result.vars);
401
+ prev = result;
402
+ }
403
+ return combined;
404
+ }
405
+ };
406
+ /**
407
+ * Create a workflow builder attached to a `Alineo` client.
408
+ *
409
+ * @example
410
+ * ```ts
411
+ * import { workflow } from "@alineo-labs/workflow";
412
+ *
413
+ * await workflow(client)
414
+ * .sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } }, (sb) => {
415
+ * sb.exec("npm ci")
416
+ * sb.exec("npm test")
417
+ * })
418
+ * .pipe(process.stdout);
419
+ * ```
420
+ */
421
+ function workflow(client) {
422
+ return new WorkflowBuilder(client);
423
+ }
424
+ //#endregion
425
+ export { SandboxBuilder, WorkflowBuilder, workflow };
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@alineo-labs/workflow",
3
+ "version": "0.1.0",
4
+ "license": "Apache-2.0",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/DrejT/alineo.git",
8
+ "directory": "packages/workflow"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "type": "module",
14
+ "main": "./dist/index.mjs",
15
+ "types": "./dist/index.d.mts",
16
+ "exports": {
17
+ ".": {
18
+ "import": "./dist/index.mjs",
19
+ "types": "./dist/index.d.mts"
20
+ }
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "provenance": true
25
+ },
26
+ "scripts": {
27
+ "build": "tsdown",
28
+ "test": "vitest run",
29
+ "test:watch": "vitest"
30
+ },
31
+ "dependencies": {
32
+ "alineo": "0.1.0"
33
+ },
34
+ "devDependencies": {
35
+ "bun-types": "1.3.14",
36
+ "tsdown": "0.22.3",
37
+ "typescript": "6.0.3",
38
+ "vitest": "4.1.9"
39
+ }
40
+ }