@lovable.dev/workflows-sdk 0.0.0-dev.11 → 0.0.0-dev.14

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 CHANGED
@@ -273,13 +273,19 @@ every graph carries one `unknown` node and the diagnostic
273
273
  `Install typescript to infer step graphs`.
274
274
  Sequential awaited `ctx.step("name", callback)` calls produce order edges;
275
275
  `await Promise.all([ctx.step(...), ctx.step(...)])` produces parallel branches
276
- that join at the next step. Returned step promises work too. Keep step IDs literal.
276
+ that join at the next step. A `Promise.all()` mapped over a collection with the
277
+ step ID template `step-${item.id}` produces one dynamic parallel node labeled
278
+ `step-{item.id}`. Returned step promises work too. Keep step IDs literal outside
279
+ this mapped form.
277
280
 
278
281
  | Field | Meaning |
279
282
  | --- | --- |
280
283
  | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
281
- | `nodes[].kind` | `step` or `unknown` |
282
- | `nodes[].stepId` | Literal step name, present for known steps |
284
+ | `nodes[].kind` | Durable operation, `parallel`, or `unknown` |
285
+ | `nodes[].stepId` | Literal step name, present for statically named steps |
286
+ | `nodes[].cardinality` | `dynamic` for a runtime-sized parallel fan-out |
287
+ | `nodes[].operation.kind` | Durable operation repeated by a parallel node |
288
+ | `nodes[].operation.stepIdTemplate` | Display template for steps in a dynamic parallel node |
283
289
  | `nodes[].label` | Step name or explanation of unsupported code |
284
290
  | `edges[]` | `{ source, target, kind: "order" }`, referencing node IDs |
285
291
  | `complete` | Whether the handler uses only supported syntax |
@@ -287,24 +293,31 @@ that join at the next step. Returned step promises work too. Keep step IDs liter
287
293
 
288
294
  For example, `read` followed by parallel `transform-a` and `transform-b`, then
289
295
  `save`, produces `read → transform-a → save` and `read → transform-b → save`.
290
- Repeated step names remain separate nodes. Node IDs are deterministic for the
291
- same source, but may change when the handler is edited.
296
+ Node IDs are deterministic for the same source, but may change when the handler
297
+ is edited.
292
298
 
293
299
  Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
294
300
  structure, not run history or data dependencies, and exclude middleware and
295
- initialization. Branches, loops, helper calls, dynamic step IDs, nested steps,
296
- and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
297
- unsupported code are not expanded. The UI should show these unknown nodes and
298
- mark partial graphs. Transforms that rewrite the handler may also produce a
299
- partial graph. A handler with no steps can have an empty graph.
300
-
301
- ## Run endpoint (TanStack Start)
302
-
303
- The same `workflowsPlugin` that writes the manifests also emits one dynamic
304
- route, `src/routes/api/workflows/$workflowId.ts`, serving every registered
301
+ initialization. A mapped `Promise.all` is complete when its callback directly
302
+ returns `ctx.step()` with a template-literal ID derived from a callback parameter.
303
+ Other branches, loops, helper calls, dynamic step IDs, and unawaited steps produce
304
+ `unknown` nodes and `complete: false`; steps inside unsupported code are not
305
+ expanded. The UI should show these unknown nodes and mark partial graphs.
306
+ Transforms that rewrite the handler may also produce a partial graph. A handler
307
+ with no steps can have an empty graph.
308
+
309
+ A step body is one atomic execution unit. Manifest generation rejects statically
310
+ visible durable calls inside it, including `ctx.step`, `ctx.sleep`, `ctx.now`,
311
+ and the other `ctx.*` operations. Move each durable operation into the workflow
312
+ handler and pass its result into the step instead.
313
+
314
+ ## Steps endpoint (TanStack Start)
315
+
316
+ The same `workflowsPlugin` that writes the manifests also emits
317
+ `src/routes/api/workflows/$workflowId/steps.ts`, serving every registered
305
318
  workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
306
- One plugin and one `entry` cover both, so a manifest can never describe a
307
- collection the route does not serve:
319
+ One plugin and one `entry` feed the manifest and route, so they cannot describe
320
+ different workflow collections:
308
321
 
309
322
  ```ts
310
323
  import { tanstackStart } from "@tanstack/react-start/plugin/vite";
@@ -342,18 +355,16 @@ route there for it to be reachable at all:
342
355
  workflowsPlugin({ path: "/api/public/workflows" });
343
356
  ```
344
357
 
345
- That emits `src/routes/api/public/workflows/$workflowId.ts` and serves
346
- `POST /api/public/workflows/{workflow-id}`. The trade is explicit: the prefix
347
- that makes the route reachable also makes it anonymously reachable.
358
+ That emits `src/routes/api/public/workflows/$workflowId/steps.ts` and serves
359
+ `POST /api/public/workflows/{workflow-id}/steps`. The trade is explicit: the
360
+ prefix that makes the route reachable also makes it anonymously reachable.
348
361
 
349
- The emitted file is thin — it imports the collection and mounts
350
- `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk` as the route's
351
- `POST` handler. All runtime logic stays in the package. The file
352
- carries a generated banner, which is the plugin's ownership token: it rewrites
353
- and deletes only files that have it, and deletes its own orphans when `path` or
354
- `workflowIdParam` changes. Delete the banner line to take the route over — the
355
- plugin then leaves that file alone, and the build keeps working. That is also
356
- the supported way to add a check of your own in front of the handler.
362
+ The emitted file imports the collection and mounts its package handler. All
363
+ runtime logic stays in the package. A generated banner is the plugin's
364
+ ownership token: it rewrites and deletes only files that have it, and deletes
365
+ its own orphans when `path` or `workflowIdParam` changes. Delete the banner line
366
+ to take the route over. That is also the supported way to add a check of your
367
+ own in front of the handler.
357
368
 
358
369
  | Option | Default | Meaning |
359
370
  | --- | --- | --- |
@@ -387,14 +398,12 @@ configured still builds; only the specifier is uglier, and its depth tracks
387
398
 
388
399
  ### Calling it
389
400
 
390
- Each workflow gets three routes. The run surface drives a workflow to
391
- completion; the two step surfaces advance it one wave at a time.
401
+ Each workflow gets one route for an external engine to drive one atomic step per
402
+ request.
392
403
 
393
404
  | Route | Does |
394
405
  | --- | --- |
395
- | `POST /api/workflows/{id}` | Runs to completion, streaming SSE |
396
- | `POST /api/workflows/{id}/nextSteps` | Reports what would run next, running nothing |
397
- | `POST /api/workflows/{id}/executeSteps` | Runs the requested steps and returns their results |
406
+ | `POST /api/workflows/{id}/steps` | Advances a singleton frontier or executes one selected step |
398
407
 
399
408
  An unknown workflow ID returns 404 and an unparseable body 400.
400
409
 
@@ -412,14 +421,13 @@ run, from 0) — never by position or `seq`. Two parallel branches can reach the
412
421
  same pair of operations in either order from one pass to the next, so call order
413
422
  is reported but is not the identity.
414
423
 
415
- Every response returns the memo the next call should send back, along with an
416
- `inputHash`. Send both, plus the **same `input`** — replay re-runs the handler
417
- from the top, and the memo does not carry the input. `inputHash` binds the memo
418
- to the input it came from: resuming with a different one is a 400 rather than a
419
- run whose settled steps and remaining steps saw different records. Key order in
420
- the input does not affect it. Because state travels in the request, a run
421
- survives a restart and can continue on a different instance; there is nothing to
422
- lose and no process affinity.
424
+ Every response returns a `memoDelta` and an `inputHash`. Merge the delta into the
425
+ memo by `(stepId, occurrence)`, then send the full memo, `inputHash`, `runId`, and
426
+ the same `input` on the next call. Replay re-runs the handler from the top, and
427
+ the memo does not carry the input. `inputHash` binds the memo to the input it came
428
+ from: resuming with a different one is a 400. Key order in the input does not
429
+ affect it. Because state travels in the request, a run survives a restart and can
430
+ continue on a different instance.
423
431
 
424
432
  Replay is what makes this work: the handler re-runs from the top on every call,
425
433
  settled operations answer from the memo instead of executing again, and
@@ -430,14 +438,17 @@ replay finds at its id, so a tampered or stale memo fails the call rather than
430
438
  answering the wrong one:
431
439
 
432
440
  ```json
433
- { "status": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
441
+ { "disposition": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
434
442
  ```
435
443
 
436
- **A repeated operation needs an explicit id — and the build says so.** `ctx.now()`, `ctx.uuid()`,
437
- `ctx.sleep(ms)` and friends fall back to a default id, and two calls sharing
438
- one cannot be told apart on replay, so the second is refused. Pass `{ id }` per
439
- call site: `ctx.now({ id: "started" })`. `ctx.step("id", …)` always has an
440
- explicit id, so repeating one in a loop is fine.
444
+ **Every step ID must be unique within a workflow.** Manifest generation rejects
445
+ a repeated literal ID in sequential calls, parallel branches, mutually exclusive
446
+ branches, loops, and callbacks. Dynamic IDs cannot be proven at build time, so
447
+ the runtime refuses the second step that resolves to an ID already reached.
448
+
449
+ `ctx.now()`, `ctx.uuid()`, `ctx.sleep(ms)` and the other durable operations fall
450
+ back to a default ID. Two calls sharing one cannot be told apart on replay, so
451
+ the second is refused. Pass `{ id }` per call site: `ctx.now({ id: "started" })`.
441
452
 
442
453
  Manifest generation rejects this before a run exists, when the arguments are
443
454
  literal:
@@ -447,10 +458,10 @@ workflow "greet" calls ctx.now() 2 times with the default id "now";
447
458
  replay cannot tell them apart, so pass an explicit { id } per call site
448
459
  ```
449
460
 
450
- The same applies to two `ctx.sleep(1000)` calls, two waits on one event name,
451
- or two approvals with one title — the default id is derived from the argument,
452
- so only a repeated argument collides. A dynamic argument cannot be read at
453
- build time and is left to the runtime check.
461
+ The same applies to two `ctx.sleep(1000)` calls, two waits on one event name, or
462
+ two approvals with one title. Their default ID is derived from the argument, so
463
+ only a repeated argument collides. A dynamic argument is left to the runtime
464
+ check.
454
465
 
455
466
  **Handler code outside a step runs on every call.** Keep side effects inside
456
467
  `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
@@ -476,59 +487,56 @@ app has in the meantime; see `path` above.
476
487
  ### Stepping through a run
477
488
 
478
489
  ```bash
479
- POST /api/workflows/greet/nextSteps
490
+ POST /api/workflows/greet/steps
480
491
  { "input": { "name": "yehya" } }
481
- -> { "status": "pending", "memo": [], "steps": [{ "seq": 0, "stepId": "greeting", "kind": "step" }] }
482
-
483
- POST /api/workflows/greet/executeSteps
484
- { "input": { "name": "yehya" }, "memo": [], "steps": [{ "stepId": "greeting" }] }
485
- -> { "status": "pending",
486
- "results": [{ "seq": 0, "stepId": "greeting", "status": "completed", "result": "Hello, yehya!" }],
487
- "memo": [{ "seq": 0, "stepId": "greeting", ... }],
488
- "steps": [{ "seq": 1, "stepId": "shout", "kind": "step" }] }
492
+ -> { "disposition": "advanced",
493
+ "executed": { "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed" },
494
+ "memoDelta": [{ "stepId": "greeting", "occurrence": 0, ... }],
495
+ "next": [{ "seq": 1, "stepId": "shout", "occurrence": 0, "kind": "step" }] }
496
+
497
+ POST /api/workflows/greet/steps
498
+ { "action": "execute", "step": { "stepId": "shout", "occurrence": 0, "kind": "step" },
499
+ "input": { "name": "yehya" }, "memo": [...], "inputHash": "9f2c...", "runId": "run_..." }
500
+ -> { "disposition": "completed", "memoDelta": [...], "next": [], "output": "HELLO, YEHYA!" }
489
501
  ```
490
502
 
491
- Send the returned `memo` back each time; the run ends with
492
- `{"status": "completed", "output": ...}`. Omitting `steps` on `executeSteps`
493
- runs whatever `nextSteps` would report, so the run advances one wave per call.
503
+ Omitting `action` means `"advance"`. When the current frontier contains exactly
504
+ one app-executable step, `advance` executes it and returns the next frontier. A
505
+ sequential workflow therefore needs one HTTP call per step, including the first.
494
506
 
495
507
  ### Driving a run from an orchestrator
496
508
 
497
- **Loop on `executeSteps` alone, with `steps` omitted.** One response carries the
498
- results, the updated `memo`, *and* the operations now pending, so a driver never
499
- needs a separate `nextSteps` call:
509
+ Use the response disposition to choose the next call:
500
510
 
501
- ```jsonc
502
- // POST /api/workflows/greet/executeSteps { "input": {...} }
503
- { "status": "pending",
504
- "results": [{ "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed", "result": "Hello, yehya!" }],
505
- "steps": [{ "stepId": "shout", "occurrence": 0, "kind": "step" }],
506
- "memo": [{ "stepId": "greeting", "occurrence": 0, ... }],
507
- "inputHash": "9f2c…" }
508
- ```
511
+ | Disposition | Engine action |
512
+ | --- | --- |
513
+ | `advanced` | Merge `memoDelta`, then execute the single entry in `next`. |
514
+ | `fork` | Merge `memoDelta`, then execute each app-executable entry in `next` in a separate concurrent request using that same memo. |
515
+ | `waiting` | Settle the external operations in `next`, then call `advance`. |
516
+ | `completed` | Persist `output`; the run is done. |
517
+ | `failed` | Apply the engine's retry or failure policy. |
509
518
 
510
- That is one HTTP call and one replay per wave — the cheapest shape, and the one
511
- to use when a remote orchestrator drives the app. Pairing `nextSteps` with
512
- `executeSteps` doubles both: use it when something needs to *see* what would run
513
- before it runs, such as a UI preview or an approval gate.
519
+ At a fork, every `execute` request receives the same base memo and selects one
520
+ `{ kind: "step", stepId, occurrence }`. Merge all returned deltas, then call
521
+ `advance` once. That replay crosses the join and immediately executes a
522
+ singleton tail when one exists. Do not schedule from one branch's `next`: a
523
+ partial branch response cannot see results still running in its siblings.
514
524
 
515
- Concurrent steps settle together: `Promise.all([ctx.step("a"), ctx.step("b")])`
516
- is one wave, and a step after the join is the next.
525
+ An `execute` call runs only its selected step. The endpoint returns 409
526
+ `stale_step` if that reference is not executable from the supplied memo.
517
527
 
518
528
  Keep a step's result small: it travels in the memo on every later call, so a
519
529
  large payload is resent for the rest of the run. Write bulk data to storage
520
530
  inside the step and return the key.
521
531
 
522
- **Replay cost.** Each pass re-runs the handler from the top, so code outside
523
- `ctx.step` executes once per wave — for an 8-step workflow, 8 times through a
524
- `executeSteps` loop and 16 through a `nextSteps` + `executeSteps` one. Step
525
- bodies run exactly once each. This is why side effects belong inside a step.
532
+ Each call re-runs the handler from the top. Step bodies run only in their
533
+ selected request, so side effects belong inside a step.
526
534
 
527
- `nextSteps` reports a step's `stepId` and `kind` but **not its input**:
535
+ `next` reports a step's `stepId` and `kind` but not its input:
528
536
  `ctx.step(id, fn)` closes over its arguments rather than declaring them, so the
529
537
  input is not knowable without running `fn`. Deterministic values (`ctx.now`,
530
- `ctx.uuid`) are the exception to the no-side-effects rule — `nextSteps` pins them
531
- and returns them in `memo`, so a later `executeSteps` replays the same values.
538
+ `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay the same
539
+ values after the engine merges the delta.
532
540
 
533
541
  ### Waiting on something outside the app
534
542
 
@@ -541,37 +549,14 @@ a caller needs to resolve them:
541
549
  "config": { "title": "Approve refund", "description": "refund of $40" } }
542
550
  ```
543
551
 
544
- The run surface emits `RUN_PAUSED` with that list and the memo, then ends the
545
- request rather than holding a connection open. Resume by appending the decision
546
- to the memo and calling again:
552
+ The endpoint returns `waiting` with that list in `next`. Resume by appending the
553
+ decision to the memo and calling `advance`:
547
554
 
548
555
  ```jsonc
549
556
  { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
550
557
  "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
551
558
  ```
552
559
 
553
- ### The run surface
554
-
555
- `POST /api/workflows/{workflow-id}` with `{ "input": ... }` starts a run and
556
- `{ "memo": [...] }` continues one. The response is `text/event-stream`, one SSE
557
- message per event, the event name being its `type`:
558
-
559
- ```text
560
- event: RUN_STARTED
561
- data: {"type":"RUN_STARTED","ts":1790528863501,"runId":"run_1790528863501_tzqgjl8i"}
562
-
563
- event: STEP_FINISHED
564
- data: {"type":"STEP_FINISHED","ts":1790528863571,"stepId":"greeting","result":"Hello, yehya!"}
565
-
566
- event: RUN_FINISHED
567
- data: {"type":"RUN_FINISHED","ts":1790528863685,"runId":"...","output":{"message":"Hello, yehya!"}}
568
- ```
569
-
570
- It drives the memo loop internally for the length of one request, so it holds no
571
- state between requests either. `RUN_FINISHED`, `RUN_ERRORED` and `RUN_PAUSED` all carry the
572
- memo, so a caller that only sent an input still holds what already ran and a
573
- retry does not repeat it.
574
-
575
560
  `createTanStackWorkflowHandler` is still exported for the engine-backed path
576
561
  (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
577
562
  route uses it: a process-local store loses runs on restart and is invisible to
@@ -584,9 +569,8 @@ caller decides whether to re-issue a failed step. Step retry, timeouts, and
584
569
  `previousVersions` routing are follow-ups.
585
570
 
586
571
  The path carries no build ID. Version pinning belongs to the signed invocation,
587
- which leaves these paths stable across deployments and safe to publish in a
588
- manifest. Triggers name a workflow rather than an endpoint, so firing one is a
589
- POST to that workflow's run path with the trigger's input; no trigger identifier
572
+ which leaves it stable across deployments and safe to publish in a manifest.
573
+ Triggers name a workflow rather than an endpoint, so no trigger identifier
590
574
  appears in the URL.
591
575
 
592
576
  ## Public entry points
@@ -595,7 +579,7 @@ The package has two, and neither mirrors the source tree:
595
579
 
596
580
  | Import | Provides |
597
581
  | --- | --- |
598
- | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the route handlers (`createRunHandler`, `createNextStepsHandler`, `createExecuteStepsHandler`) |
582
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the `createStepsHandler` route handler |
599
583
  | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
600
584
 
601
585
  The export map is a contract; the directory layout under `src/` is not. They are
@@ -0,0 +1,165 @@
1
+ import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
+ import { loadTypeScript } from "./graph-CZDg07_0.js";
3
+ //#region src/manifests/duplicate-ids.ts
4
+ /** Where an explicit `{ id }` would sit for each operation. */
5
+ const optionsArgument = {
6
+ now: 0,
7
+ uuid: 0,
8
+ approve: 0,
9
+ sleep: 1,
10
+ sleepUntil: 1,
11
+ waitForEvent: 1,
12
+ step: -1
13
+ };
14
+ /** Operation ids provably reached more than once; dynamic ids are left to runtime. */
15
+ async function findDuplicateOperationIds(handler) {
16
+ const api = await loadTypeScript();
17
+ if (!api) return [];
18
+ const ts = api;
19
+ const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
20
+ const declaration = source.statements[0];
21
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
22
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) return [];
23
+ const parameter = fn.parameters[0]?.name;
24
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
25
+ const context = parameter.text;
26
+ function literalString(node) {
27
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
28
+ }
29
+ function literalNumber(node) {
30
+ if (!node || !ts.isNumericLiteral(node)) return void 0;
31
+ const value = Number(node.text);
32
+ return Number.isFinite(value) ? value : void 0;
33
+ }
34
+ function property(options, name) {
35
+ if (!options || !ts.isObjectLiteralExpression(options)) return void 0;
36
+ for (const entry of options.properties) {
37
+ if (!ts.isPropertyAssignment(entry)) continue;
38
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
39
+ }
40
+ }
41
+ /** `undefined` when the options bag is unreadable, so the call is skipped. */
42
+ function explicitId(options) {
43
+ if (options === void 0) return false;
44
+ if (!ts.isObjectLiteralExpression(options)) return void 0;
45
+ if (options.properties.some((entry) => ts.isSpreadAssignment(entry))) return void 0;
46
+ const given = property(options, "id");
47
+ if (given === void 0) return false;
48
+ return literalString(given);
49
+ }
50
+ function defaultSource(call, method) {
51
+ switch (method) {
52
+ case "now":
53
+ case "uuid": return { kind: method };
54
+ case "sleep": {
55
+ const ms = literalNumber(call.arguments[0]);
56
+ return ms === void 0 ? void 0 : {
57
+ kind: "sleep",
58
+ ms
59
+ };
60
+ }
61
+ case "sleepUntil": {
62
+ const timestamp = literalNumber(call.arguments[0]);
63
+ return timestamp === void 0 ? void 0 : {
64
+ kind: "sleepUntil",
65
+ timestamp
66
+ };
67
+ }
68
+ case "waitForEvent": {
69
+ const name = literalString(call.arguments[0]);
70
+ return name === void 0 ? void 0 : {
71
+ kind: "waitForEvent",
72
+ name
73
+ };
74
+ }
75
+ case "approve": {
76
+ const title = literalString(property(call.arguments[0], "title"));
77
+ return title === void 0 ? void 0 : {
78
+ kind: "approve",
79
+ title
80
+ };
81
+ }
82
+ case "step": return;
83
+ }
84
+ }
85
+ function placement(call) {
86
+ const branches = /* @__PURE__ */ new Map();
87
+ let repeatable = false;
88
+ let child = call;
89
+ let parent = call.parent;
90
+ while (parent && child !== fn) {
91
+ if (ts.isIfStatement(parent)) {
92
+ if (parent.thenStatement === child) branches.set(String(parent.pos), "then");
93
+ else if (parent.elseStatement === child) branches.set(String(parent.pos), "else");
94
+ } else if (ts.isConditionalExpression(parent)) {
95
+ if (parent.whenTrue === child) branches.set(String(parent.pos), "true");
96
+ else if (parent.whenFalse === child) branches.set(String(parent.pos), "false");
97
+ } else if (ts.isCaseClause(parent) || ts.isDefaultClause(parent)) branches.set(String(parent.parent.pos), String(parent.parent.clauses.indexOf(parent)));
98
+ else if (parent !== fn && (ts.isForStatement(parent) || ts.isForOfStatement(parent) || ts.isForInStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent) || ts.isFunctionLike(parent))) repeatable = true;
99
+ child = parent;
100
+ parent = parent.parent;
101
+ }
102
+ return {
103
+ branches,
104
+ repeatable
105
+ };
106
+ }
107
+ /** True when a shared conditional puts the two calls on different sides. */
108
+ function exclusive(a, b) {
109
+ for (const [node, side] of a.branches) {
110
+ const other = b.branches.get(node);
111
+ if (other !== void 0 && other !== side) return true;
112
+ }
113
+ return false;
114
+ }
115
+ const calls = [];
116
+ const visit = (node) => {
117
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
118
+ const method = node.expression.name.text;
119
+ const index = optionsArgument[method];
120
+ const given = method === "step" ? literalString(node.arguments[0]) : explicitId(node.arguments[index]);
121
+ if (given !== void 0) {
122
+ const id = given === false ? void 0 : given;
123
+ const derived = id === void 0 ? defaultSource(node, method) : void 0;
124
+ const resolved = id ?? (derived && defaultDurableId(derived));
125
+ if (resolved) calls.push({
126
+ id: resolved,
127
+ method,
128
+ defaulted: id === void 0,
129
+ ...placement(node)
130
+ });
131
+ }
132
+ }
133
+ ts.forEachChild(node, visit);
134
+ };
135
+ visit(fn);
136
+ const found = /* @__PURE__ */ new Map();
137
+ for (const call of calls) {
138
+ if (call.method === "step") {
139
+ const reason = call.repeatable ? "loop" : calls.some((other) => other !== call && other.id === call.id) ? "repeated" : void 0;
140
+ if (reason) found.set(`step:${call.id}`, {
141
+ id: call.id,
142
+ method: call.method,
143
+ reason
144
+ });
145
+ continue;
146
+ }
147
+ if (!call.defaulted) continue;
148
+ if (call.repeatable) {
149
+ found.set(`${call.method}:${call.id}`, {
150
+ id: call.id,
151
+ method: call.method,
152
+ reason: "loop"
153
+ });
154
+ continue;
155
+ }
156
+ if (calls.some((other) => other !== call && other.id === call.id && !exclusive(call, other))) found.set(`${call.method}:${call.id}`, {
157
+ id: call.id,
158
+ method: call.method,
159
+ reason: "repeated"
160
+ });
161
+ }
162
+ return [...found.values()];
163
+ }
164
+ //#endregion
165
+ export { findDuplicateOperationIds };
@@ -183,13 +183,26 @@ function serializeSchema(schema, direction, label) {
183
183
  }
184
184
  }
185
185
  async function generateManifests(definition) {
186
- const { extractWorkflowGraph } = await import("./graph-CPDci8jW.js");
187
- const { findDuplicateDefaultIds } = await import("./duplicate-ids-CSzTGBYE.js");
186
+ const { extractWorkflowGraph } = await import("./graph-CZDg07_0.js");
187
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-DFD8TO2y.js");
188
+ const { findNestedDurableOperations } = await import("./nested-operations-OEvIJ3AZ.js");
188
189
  const collection = registerWorkflows(definition);
189
190
  const manifests = [];
190
191
  for (const workflow of collection.workflows) {
191
192
  if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
192
- for (const duplicate of await findDuplicateDefaultIds(workflow.handler)) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" calls ctx.${duplicate.method}() ${duplicate.count} times with the default id "${duplicate.id}"; replay cannot tell them apart, so pass an explicit { id } per call site`);
193
+ const nested = (await findNestedDurableOperations(workflow.handler))[0];
194
+ if (nested) {
195
+ const parent = nested.parentStepId ? `ctx.step(${JSON.stringify(nested.parentStepId)})` : "ctx.step()";
196
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" calls ctx.${nested.method}() inside ${parent}; step bodies are atomic and cannot contain durable operations`);
197
+ }
198
+ for (const duplicate of await findDuplicateOperationIds(workflow.handler)) {
199
+ if (duplicate.method === "step") {
200
+ const use = duplicate.reason === "loop" ? "inside a loop or callback" : "more than once";
201
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" uses step id ${JSON.stringify(duplicate.id)} ${use}; every step id must be unique within a workflow`);
202
+ }
203
+ const where = duplicate.reason === "loop" ? "inside a loop" : "more than once";
204
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" calls ctx.${duplicate.method}() ${where} with the default id "${duplicate.id}"; replay cannot tell the occurrences apart, so pass an explicit { id } per call site`);
205
+ }
193
206
  const metadata = {
194
207
  id: workflow.id,
195
208
  ...workflow.description === void 0 ? {} : { description: workflow.description },
@@ -85,6 +85,39 @@ async function extractWorkflowGraph(handler) {
85
85
  const value = Number(node.text);
86
86
  return Number.isFinite(value) ? value : void 0;
87
87
  }
88
+ function templateReference(node, parameters) {
89
+ while (ts.isParenthesizedExpression(node)) node = node.expression;
90
+ if (ts.isIdentifier(node)) return parameters.has(node.text) ? node.text : void 0;
91
+ if (ts.isPropertyAccessExpression(node) && !node.questionDotToken) {
92
+ const expression = templateReference(node.expression, parameters);
93
+ return expression === void 0 ? void 0 : `${expression}.${node.name.text}`;
94
+ }
95
+ }
96
+ function stepIdTemplate(node, parameters) {
97
+ if (!node || !ts.isTemplateExpression(node)) return void 0;
98
+ let template = node.head.text;
99
+ for (const span of node.templateSpans) {
100
+ const reference = templateReference(span.expression, parameters);
101
+ if (reference === void 0) return void 0;
102
+ template += `{${reference}}${span.literal.text}`;
103
+ }
104
+ return template;
105
+ }
106
+ function mappedStepTemplate(node) {
107
+ while (ts.isParenthesizedExpression(node)) node = node.expression;
108
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "map" || node.arguments.length !== 1) return;
109
+ const callback = node.arguments[0];
110
+ if (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) return void 0;
111
+ const parameters = new Set(callback.parameters.flatMap((parameter) => ts.isIdentifier(parameter.name) ? [parameter.name.text] : []));
112
+ let body;
113
+ if (ts.isBlock(callback.body)) {
114
+ const statement = callback.body.statements.length === 1 ? callback.body.statements[0] : void 0;
115
+ body = statement && ts.isReturnStatement(statement) ? statement.expression : void 0;
116
+ } else body = callback.body;
117
+ while (body && (ts.isParenthesizedExpression(body) || ts.isAwaitExpression(body))) body = body.expression;
118
+ if (!body || !durableCall(body) || body.expression.name.text !== "step") return;
119
+ return stepIdTemplate(body.arguments[0], parameters);
120
+ }
88
121
  function readableOptions(node) {
89
122
  return node && ts.isObjectLiteralExpression(node) && node.properties.every(ts.isPropertyAssignment) ? node : void 0;
90
123
  }
@@ -164,13 +197,26 @@ async function extractWorkflowGraph(handler) {
164
197
  if (node.arguments.some((argument) => contains(argument, durableCall))) return unknown("Nested durable calls are not supported yet", tails);
165
198
  return tails;
166
199
  }
167
- if (awaited && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Promise" && node.expression.name.text === "all" && node.arguments.length === 1 && ts.isArrayLiteralExpression(node.arguments[0])) {
168
- const elements = node.arguments[0].elements;
169
- if (elements.some((element) => contains(element, ts.isAwaitExpression, true))) return unknown("Await expressions inside Promise.all are not supported yet", parents);
170
- return elements.length > 0 ? elements.flatMap((element) => {
171
- while (ts.isParenthesizedExpression(element)) element = element.expression;
172
- return ts.isCallExpression(element) ? expression(element, parents, true) : unknown("Dynamic Promise.all entries are not followed", parents);
173
- }) : parents;
200
+ if (awaited && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Promise" && node.expression.name.text === "all" && node.arguments.length === 1) {
201
+ const argument = node.arguments[0];
202
+ if (ts.isArrayLiteralExpression(argument)) {
203
+ const elements = argument.elements;
204
+ if (elements.some((element) => contains(element, ts.isAwaitExpression, true))) return unknown("Await expressions inside Promise.all are not supported yet", parents);
205
+ return elements.length > 0 ? elements.flatMap((element) => {
206
+ while (ts.isParenthesizedExpression(element)) element = element.expression;
207
+ return ts.isCallExpression(element) ? expression(element, parents, true) : unknown("Dynamic Promise.all entries are not followed", parents);
208
+ }) : parents;
209
+ }
210
+ const template = mappedStepTemplate(argument);
211
+ if (template !== void 0) return addNode({
212
+ kind: "parallel",
213
+ cardinality: "dynamic",
214
+ operation: {
215
+ kind: "step",
216
+ stepIdTemplate: template
217
+ },
218
+ label: template
219
+ }, parents);
174
220
  }
175
221
  if (contains(node, (child) => ts.isCallExpression(child) || ts.isAwaitExpression(child) || ts.isNewExpression(child))) return unknown("Helper calls and dynamic expressions are not followed", parents);
176
222
  if (ts.isIdentifier(node) && node.text === context) return unknown("Workflow context aliases are not followed", parents);
package/dist/index.d.ts CHANGED
@@ -55,6 +55,13 @@ declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflow
55
55
  type WorkflowGraphNodeDetails = {
56
56
  kind: "step";
57
57
  stepId: string;
58
+ } | {
59
+ kind: "parallel";
60
+ cardinality: "dynamic";
61
+ operation: {
62
+ kind: "step";
63
+ stepIdTemplate: string;
64
+ };
58
65
  } | {
59
66
  kind: "approve";
60
67
  config: {
@@ -148,33 +155,6 @@ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
148
155
  /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
149
156
  declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
150
157
  //#endregion
151
- //#region src/stacks/tanstack/steps.d.ts
152
- interface StepsHandlerOptions {
153
- /** Route parameter carrying the workflow ID. @default "workflowId" */
154
- workflowIdParam?: string;
155
- }
156
- interface RouteCtx {
157
- request: Request;
158
- params?: Record<string, string | undefined>;
159
- }
160
- type StepsHandler = (ctx: RouteCtx) => Promise<Response>;
161
- /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
162
- * `memo` so a later executeSteps replays the same values. */
163
- declare function createNextStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
164
- /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
165
- * report, advancing the run one wave per call. */
166
- declare function createExecuteStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
167
- //#endregion
168
- //#region src/stacks/tanstack/run.d.ts
169
- declare function createRunHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
170
- //#endregion
171
- //#region src/stacks/tanstack/sse.d.ts
172
- /**
173
- * Encode a workflow event stream as `text/event-stream`. Each event keeps its
174
- * engine `type` as the SSE event name and its whole JSON as the data line.
175
- */
176
- declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
177
- //#endregion
178
158
  //#region src/runtime/types.d.ts
179
159
  /** Durable operations a replay can answer from the memo. */
180
160
  type StepKind = "step" | "sleep" | "waitForEvent" | "approve" | "now" | "uuid";
@@ -196,20 +176,24 @@ interface MemoEntry {
196
176
  result?: unknown;
197
177
  error?: string;
198
178
  }
199
- /** A durable operation the replay reached but could not answer. */
200
- interface StepIntent {
179
+ interface StepIntentBase {
201
180
  seq: number;
202
181
  stepId: string;
203
182
  occurrence: number;
204
- kind: StepKind;
205
183
  /** Kind-specific detail: sleep `ms`, `waitForEvent` name, approval title. */
206
184
  config?: Record<string, unknown>;
207
185
  }
208
- interface StepResult {
186
+ /** A durable operation the replay reached but could not answer. */
187
+ type StepIntent = StepIntentBase & ({
188
+ kind: "step";
189
+ } | {
190
+ kind: Exclude<StepKind, "step">;
191
+ });
192
+ interface StepResult<K extends StepKind = StepKind> {
209
193
  seq: number;
210
194
  stepId: string;
211
195
  occurrence: number;
212
- kind: StepKind;
196
+ kind: K;
213
197
  status: "completed" | "failed";
214
198
  result?: unknown;
215
199
  error?: string;
@@ -231,11 +215,57 @@ interface ReplayOutcome {
231
215
  output?: unknown;
232
216
  error?: string;
233
217
  }
234
- /** Identifies one durable operation for `executeSteps`. */
235
- interface StepSelector {
218
+ interface StepReference {
219
+ kind: "step";
236
220
  stepId: string;
237
- /** Defaults to 0; needed only when a run calls the same `stepId` more than once. */
238
- occurrence?: number;
221
+ occurrence: number;
222
+ }
223
+ //#endregion
224
+ //#region src/stacks/tanstack/steps.d.ts
225
+ interface StepsHandlerOptions {
226
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
227
+ workflowIdParam?: string;
239
228
  }
229
+ interface RouteCtx {
230
+ request: Request;
231
+ params?: Record<string, string | undefined>;
232
+ }
233
+ type StepsHandler = (ctx: RouteCtx) => Promise<Response>;
234
+ interface StepsRequestBase {
235
+ input?: unknown;
236
+ memo?: MemoEntry[];
237
+ runId?: string;
238
+ inputHash?: string;
239
+ }
240
+ type StepsRequest = StepsRequestBase & ({
241
+ action?: "advance";
242
+ step?: never;
243
+ } | {
244
+ action: "execute";
245
+ step: StepReference;
246
+ });
247
+ type StepsDisposition = "advanced" | "fork" | "waiting" | "completed" | "failed";
248
+ interface StepsResponse {
249
+ runId: string;
250
+ inputHash: string;
251
+ disposition: StepsDisposition;
252
+ memoDelta: MemoEntry[];
253
+ next: StepIntent[];
254
+ executed?: StepResult<"step">;
255
+ emitted?: {
256
+ name: string;
257
+ value: Record<string, unknown>;
258
+ }[];
259
+ output?: unknown;
260
+ error?: string;
261
+ }
262
+ declare function createStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
263
+ //#endregion
264
+ //#region src/stacks/tanstack/sse.d.ts
265
+ /**
266
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
267
+ * engine `type` as the SSE event name and its whole JSON as the data line.
268
+ */
269
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
240
270
  //#endregion
241
- export { type AnyWorkflowDefinition, type Cadence, type Ctx, type MemoEntry, type OverlapPolicy, type ReplayOutcome, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepIntent, type StepKind, type StepOptions, type StepResult, type StepSelector, type StepsHandler, type StepsHandlerOptions, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type Weekday, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
271
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type MemoEntry, type OverlapPolicy, type ReplayOutcome, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepIntent, type StepKind, type StepOptions, type StepReference, type StepResult, type StepsDisposition, type StepsHandler, type StepsHandlerOptions, type StepsRequest, type StepsResponse, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type Weekday, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as defineSchedule, c as weekly, i as registerWorkflows, n as createMiddleware, o as daily, r as createWorkflow, s as hourly, t as generateManifests } from "./generate-DkZJkfZ1.js";
1
+ import { a as defineSchedule, c as weekly, i as registerWorkflows, n as createMiddleware, o as daily, r as createWorkflow, s as hourly, t as generateManifests } from "./generate-CUlH7Z2x.js";
2
2
  import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
3
3
  import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
4
4
  //#region src/stacks/tanstack/sse.ts
@@ -189,6 +189,10 @@ async function replay(options) {
189
189
  const index = seq++;
190
190
  const occurrence = occurrences.get(stepId) ?? 0;
191
191
  occurrences.set(stepId, occurrence + 1);
192
+ if (kind === "step" && occurrence > 0) {
193
+ nonDeterminism = `ctx.step() was reached more than once with id "${stepId}"; every step id must be unique within a workflow`;
194
+ return never;
195
+ }
192
196
  if (defaulted && occurrence > 0) {
193
197
  nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
194
198
  return never;
@@ -320,14 +324,18 @@ async function replay(options) {
320
324
  }
321
325
  while (inflight.length > 0) await Promise.all(inflight.splice(0));
322
326
  const memo = [...byKey.values(), ...settled.values()];
323
- const hidden = (key, seen) => {
324
- const parent = byKey.get(key)?.parent;
325
- if (parent === void 0 || seen.has(parent)) return false;
326
- if (consumed.has(parent)) return true;
327
- seen.add(parent);
328
- return hidden(parent, seen);
327
+ const hidden = (start) => {
328
+ const seen = /* @__PURE__ */ new Set([start]);
329
+ let key = start;
330
+ for (;;) {
331
+ const parent = byKey.get(key)?.parent;
332
+ if (parent === void 0 || seen.has(parent)) return false;
333
+ if (consumed.has(parent)) return true;
334
+ seen.add(parent);
335
+ key = parent;
336
+ }
329
337
  };
330
- const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key, /* @__PURE__ */ new Set([key])));
338
+ const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key));
331
339
  pending.sort((a, b) => a.seq - b.seq);
332
340
  results.sort((a, b) => a.seq - b.seq);
333
341
  const base = {
@@ -396,7 +404,9 @@ function parseBody(value) {
396
404
  if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
397
405
  if (new Set(body.memo.map((entry) => memoKey(entry.stepId, entry.occurrence))).size !== body.memo.length) return "memo entries must be unique per stepId and occurrence";
398
406
  }
399
- if (body.steps !== void 0 && (!Array.isArray(body.steps) || !body.steps.every(isSelector))) return "steps must be an array of { stepId, occurrence? } selectors";
407
+ if (body.action !== void 0 && body.action !== "advance" && body.action !== "execute") return "action must be \"advance\" or \"execute\"";
408
+ if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\", stepId, occurrence } reference when action is \"execute\"";
409
+ if (body.action !== "execute" && body.step !== void 0) return "step is only valid when action is \"execute\"";
400
410
  if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
401
411
  return body;
402
412
  }
@@ -405,22 +415,32 @@ async function readBody(request) {
405
415
  if (!text.trim()) return {};
406
416
  return JSON.parse(text);
407
417
  }
408
- function selectorKey(selector) {
409
- return memoKey(selector.stepId, selector.occurrence ?? 0);
418
+ function operationKey(operation) {
419
+ return memoKey(operation.stepId, operation.occurrence);
420
+ }
421
+ function isStepReference(value) {
422
+ const step = value;
423
+ return typeof step === "object" && step !== null && step.kind === "step" && typeof step.stepId === "string" && Number.isInteger(step.occurrence) && step.occurrence >= 0;
410
424
  }
411
- function isSelector(value) {
412
- const selector = value;
413
- return typeof selector === "object" && selector !== null && typeof selector.stepId === "string" && (selector.occurrence === void 0 || Number.isInteger(selector.occurrence) && selector.occurrence >= 0);
425
+ function disposition(outcome) {
426
+ if (outcome.status === "completed") return "completed";
427
+ if (outcome.status === "failed") return "failed";
428
+ if (!outcome.steps.some((step) => step.kind === "step")) return "waiting";
429
+ return outcome.steps.length > 1 ? "fork" : "advanced";
414
430
  }
415
- function respond(runId, inputHash, outcome) {
416
- const { status, memo, steps, results, emitted, output, error } = outcome;
431
+ function memoDelta(before, after) {
432
+ const existing = new Set(before.map((entry) => memoKey(entry.stepId, entry.occurrence)));
433
+ return after.filter((entry) => !existing.has(memoKey(entry.stepId, entry.occurrence)));
434
+ }
435
+ function respond(runId, inputHash, before, outcome, executed) {
436
+ const { steps, emitted, output, error } = outcome;
417
437
  return json(200, {
418
438
  runId,
419
439
  inputHash,
420
- status,
421
- memo,
422
- steps,
423
- results,
440
+ disposition: disposition(outcome),
441
+ memoDelta: memoDelta(before, outcome.memo),
442
+ next: steps,
443
+ ...executed === void 0 ? {} : { executed },
424
444
  ...emitted.length > 0 ? { emitted } : {},
425
445
  ...output === void 0 ? {} : { output },
426
446
  ...error === void 0 ? {} : { error }
@@ -465,199 +485,53 @@ async function resolve(ctx, param, byId) {
465
485
  inputHash
466
486
  };
467
487
  }
468
- /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
469
- * `memo` so a later executeSteps replays the same values. */
470
- function createNextStepsHandler(collection, options = {}) {
471
- const { param, byId } = prepare(collection, options);
472
- return async (ctx) => {
473
- const resolved = await resolve(ctx, param, byId);
474
- if (resolved instanceof Response) return resolved;
475
- const { workflow, body, runId, inputHash } = resolved;
476
- return respond(runId, inputHash, await replay({
477
- workflow,
478
- input: body.input ?? null,
479
- memo: body.memo ?? [],
480
- runId,
481
- shouldExecute: (intent) => intent.kind !== "step"
482
- }));
483
- };
484
- }
485
- /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
486
- * report, advancing the run one wave per call. */
487
- function createExecuteStepsHandler(collection, options = {}) {
488
+ function createStepsHandler(collection, options = {}) {
488
489
  const { param, byId } = prepare(collection, options);
489
490
  return async (ctx) => {
490
491
  const resolved = await resolve(ctx, param, byId);
491
492
  if (resolved instanceof Response) return resolved;
492
493
  const { workflow, body, runId, inputHash } = resolved;
493
494
  const input = body.input ?? null;
494
- const memo = body.memo ?? [];
495
- const wanted = body.steps && new Set(body.steps.map(selectorKey));
496
- return respond(runId, inputHash, await replay({
495
+ const before = body.memo ?? [];
496
+ if (body.action === "execute") {
497
+ const selected = body.step;
498
+ const outcome = await replay({
499
+ workflow,
500
+ input,
501
+ memo: before,
502
+ runId,
503
+ shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(selected)
504
+ });
505
+ const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(selected));
506
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
507
+ error: "stale_step",
508
+ message: `step "${selected.stepId}" (#${selected.occurrence}) is not executable from this memo`
509
+ });
510
+ return respond(runId, inputHash, before, outcome, executed);
511
+ }
512
+ const described = await replay({
497
513
  workflow,
498
514
  input,
499
- memo,
515
+ memo: before,
500
516
  runId,
501
- shouldExecute: (intent, pass) => intent.kind !== "step" || (wanted ? wanted.has(selectorKey(intent)) : pass.stepsSettled === 0)
502
- }));
503
- };
504
- }
505
- //#endregion
506
- //#region src/stacks/tanstack/run.ts
507
- function event(type, fields) {
508
- return {
509
- type,
510
- ts: Date.now(),
511
- ...fields
512
- };
513
- }
514
- async function* drive(workflow, input, runId, initialMemo, inputHash) {
515
- let memo = [...initialMemo];
516
- yield event("RUN_STARTED", {
517
- runId,
518
- inputHash
519
- });
520
- for (;;) {
521
- const queue = [];
522
- let wake;
523
- const emit = (next) => {
524
- queue.push(next);
525
- wake?.();
526
- wake = void 0;
527
- };
528
- let settledPass;
529
- let passError;
530
- let finished = false;
531
- const running = replay({
517
+ shouldExecute: (intent) => intent.kind !== "step"
518
+ });
519
+ const only = described.steps.length === 1 ? described.steps[0] : void 0;
520
+ if (described.status !== "pending" || only?.kind !== "step") return respond(runId, inputHash, before, described);
521
+ const outcome = await replay({
532
522
  workflow,
533
523
  input,
534
- memo,
524
+ memo: described.memo,
535
525
  runId,
536
- shouldExecute: (intent, state) => intent.kind !== "step" || state.stepsSettled === 0,
537
- onStepStart: (intent) => {
538
- if (intent.kind === "step") emit(event("STEP_STARTED", { stepId: intent.stepId }));
539
- },
540
- onStepSettle: (result) => {
541
- if (result.kind !== "step") return;
542
- emit(result.status === "completed" ? event("STEP_FINISHED", {
543
- stepId: result.stepId,
544
- result: result.result
545
- }) : event("STEP_FAILED", {
546
- stepId: result.stepId,
547
- error: result.error
548
- }));
549
- }
550
- }).then((value) => {
551
- settledPass = value;
552
- finished = true;
553
- wake?.();
554
- wake = void 0;
555
- }, (error) => {
556
- passError = error;
557
- finished = true;
558
- wake?.();
559
- wake = void 0;
526
+ shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(only)
560
527
  });
561
- for (;;) {
562
- if (queue.length > 0) {
563
- yield queue.shift();
564
- continue;
565
- }
566
- if (finished) break;
567
- await new Promise((resolve) => {
568
- wake = resolve;
569
- });
570
- }
571
- await running;
572
- if (!settledPass) {
573
- yield event("RUN_ERRORED", {
574
- runId,
575
- inputHash,
576
- error: `replay threw: ${passError instanceof Error ? passError.message : String(passError)}`,
577
- memo
578
- });
579
- return;
580
- }
581
- const pass = settledPass;
582
- memo = pass.memo;
583
- if (pass.status === "completed") {
584
- yield event("RUN_FINISHED", {
585
- runId,
586
- inputHash,
587
- output: pass.output,
588
- memo
589
- });
590
- return;
591
- }
592
- if (pass.status === "failed") {
593
- yield event("RUN_ERRORED", {
594
- runId,
595
- inputHash,
596
- error: pass.error,
597
- memo
598
- });
599
- return;
600
- }
601
- if (pass.steps.every((intent) => intent.kind !== "step")) {
602
- yield event("RUN_PAUSED", {
603
- runId,
604
- inputHash,
605
- waitingOn: pass.steps,
606
- memo
607
- });
608
- return;
609
- }
610
- if (pass.results.length === 0) {
611
- yield event("RUN_ERRORED", {
612
- runId,
613
- inputHash,
614
- error: "run made no progress",
615
- memo
616
- });
617
- return;
618
- }
619
- }
620
- }
621
- function createRunHandler(collection, options = {}) {
622
- const param = options.workflowIdParam ?? "workflowId";
623
- const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
624
- return async (ctx) => {
625
- const workflowId = ctx.params?.[param] ?? new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
626
- const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
627
- if (!workflow) return new Response(JSON.stringify({
628
- error: "unknown_workflow",
629
- workflowId: workflowId ?? ""
630
- }), {
631
- status: 404,
632
- headers: { "content-type": "application/json; charset=utf-8" }
528
+ const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(only));
529
+ if (executed === void 0 && outcome.status !== "failed") return json(409, {
530
+ error: "stale_step",
531
+ message: `step "${only.stepId}" (#${only.occurrence}) is not executable from this memo`
633
532
  });
634
- let body = {};
635
- try {
636
- const text = await ctx.request.text();
637
- if (text.trim()) body = JSON.parse(text);
638
- } catch (error) {
639
- return new Response(JSON.stringify({
640
- error: "invalid_request",
641
- message: String(error)
642
- }), {
643
- status: 400,
644
- headers: { "content-type": "application/json; charset=utf-8" }
645
- });
646
- }
647
- const inputHash = await hashInput(body.input ?? null);
648
- if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) {
649
- const message = body.inputHash === void 0 ? "inputHash must be sent with a memo; echo the value from the previous response" : "input does not match the run this memo came from";
650
- return new Response(JSON.stringify({
651
- error: "invalid_request",
652
- message
653
- }), {
654
- status: 400,
655
- headers: { "content-type": "application/json; charset=utf-8" }
656
- });
657
- }
658
- const runId = body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
659
- return toServerSentEventsResponse(drive(workflow, body.input ?? null, runId, body.memo ?? [], inputHash));
533
+ return respond(runId, inputHash, before, outcome, executed);
660
534
  };
661
535
  }
662
536
  //#endregion
663
- export { createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
537
+ export { createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
@@ -0,0 +1,53 @@
1
+ import { loadTypeScript } from "./graph-CZDg07_0.js";
2
+ //#region src/manifests/nested-operations.ts
3
+ const durableMethods = [
4
+ "step",
5
+ "approve",
6
+ "waitForEvent",
7
+ "sleep",
8
+ "sleepUntil",
9
+ "now",
10
+ "uuid"
11
+ ];
12
+ async function findNestedDurableOperations(handler) {
13
+ const api = await loadTypeScript();
14
+ if (!api) return [];
15
+ const ts = api;
16
+ const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
17
+ const declaration = source.statements[0];
18
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
19
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) return [];
20
+ const parameter = fn.parameters[0]?.name;
21
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
22
+ const context = parameter.text;
23
+ function methodOf(node) {
24
+ if (!ts.isCallExpression(node)) return void 0;
25
+ const expression = node.expression;
26
+ let name;
27
+ if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context) name = expression.name.text;
28
+ else if (ts.isElementAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context && expression.argumentExpression && (ts.isStringLiteral(expression.argumentExpression) || ts.isNoSubstitutionTemplateLiteral(expression.argumentExpression))) name = expression.argumentExpression.text;
29
+ return durableMethods.find((method) => method === name);
30
+ }
31
+ function stepIdOf(node) {
32
+ const argument = node.arguments[0];
33
+ return argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : void 0;
34
+ }
35
+ const nested = [];
36
+ const visit = (node, parentStepId) => {
37
+ const method = methodOf(node);
38
+ if (method && parentStepId !== void 0) nested.push({
39
+ method,
40
+ parentStepId
41
+ });
42
+ if (method === "step" && ts.isCallExpression(node)) {
43
+ visit(node.expression, parentStepId);
44
+ node.arguments.forEach((argument, index) => visit(argument, index === 1 ? stepIdOf(node) ?? "" : parentStepId));
45
+ return;
46
+ }
47
+ ts.forEachChild(node, (child) => visit(child, parentStepId));
48
+ };
49
+ visit(fn);
50
+ return nested;
51
+ }
52
+ //#endregion
53
+ export { findNestedDurableOperations };
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as generateManifests } from "./generate-DkZJkfZ1.js";
1
+ import { t as generateManifests } from "./generate-CUlH7Z2x.js";
2
2
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { createServer } from "vite";
4
4
  import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
@@ -159,20 +159,10 @@ function relativeImportSpecifier(routeFile, target) {
159
159
  function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
160
160
  return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
161
161
  }
162
- const SURFACES = [
163
- {
164
- segment: "",
165
- factory: "createRunHandler"
166
- },
167
- {
168
- segment: "nextSteps",
169
- factory: "createNextStepsHandler"
170
- },
171
- {
172
- segment: "executeSteps",
173
- factory: "createExecuteStepsHandler"
174
- }
175
- ];
162
+ const SURFACES = [{
163
+ segment: "steps",
164
+ factory: "createStepsHandler"
165
+ }];
176
166
  function buildRouteSource(routeFile, routeLiteral, param, specifier, root, factory) {
177
167
  return `${GENERATED_BANNER}
178
168
  // route: ${routeLiteral}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.11",
3
+ "version": "0.0.0-dev.14",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",
@@ -1,115 +0,0 @@
1
- import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
- import { loadTypeScript } from "./graph-CPDci8jW.js";
3
- //#region src/manifests/duplicate-ids.ts
4
- /** Where an explicit `{ id }` would sit for each operation. */
5
- const optionsArgument = {
6
- now: 0,
7
- uuid: 0,
8
- approve: 0,
9
- sleep: 1,
10
- sleepUntil: 1,
11
- waitForEvent: 1
12
- };
13
- /**
14
- * Durable calls sharing one defaulted id, which replay cannot tell apart. The
15
- * pass sees literal arguments only; anything dynamic is left to the runtime.
16
- */
17
- async function findDuplicateDefaultIds(handler) {
18
- const api = await loadTypeScript();
19
- if (!api) return [];
20
- const ts = api;
21
- const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
22
- const declaration = source.statements[0];
23
- const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
24
- if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) return [];
25
- const parameter = fn.parameters[0]?.name;
26
- if (!parameter || !ts.isIdentifier(parameter)) return [];
27
- const context = parameter.text;
28
- function literalString(node) {
29
- return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
30
- }
31
- function literalNumber(node) {
32
- if (!node || !ts.isNumericLiteral(node)) return void 0;
33
- const value = Number(node.text);
34
- return Number.isFinite(value) ? value : void 0;
35
- }
36
- function hasExplicitId(options) {
37
- if (!options || !ts.isObjectLiteralExpression(options)) return options !== void 0;
38
- return options.properties.some((property) => {
39
- if (ts.isPropertyAssignment(property) || ts.isShorthandPropertyAssignment(property)) {
40
- const name = property.name;
41
- return (ts.isIdentifier(name) || ts.isStringLiteral(name)) && name.text === "id";
42
- }
43
- return ts.isSpreadAssignment(property);
44
- });
45
- }
46
- function sourceOf(call, method) {
47
- switch (method) {
48
- case "now":
49
- case "uuid": return { kind: method };
50
- case "sleep": {
51
- const ms = literalNumber(call.arguments[0]);
52
- return ms === void 0 ? void 0 : {
53
- kind: "sleep",
54
- ms
55
- };
56
- }
57
- case "sleepUntil": {
58
- const timestamp = literalNumber(call.arguments[0]);
59
- return timestamp === void 0 ? void 0 : {
60
- kind: "sleepUntil",
61
- timestamp
62
- };
63
- }
64
- case "waitForEvent": {
65
- const name = literalString(call.arguments[0]);
66
- return name === void 0 ? void 0 : {
67
- kind: "waitForEvent",
68
- name
69
- };
70
- }
71
- case "approve": {
72
- const options = call.arguments[0];
73
- const title = options && ts.isObjectLiteralExpression(options) ? titleOf(options) : void 0;
74
- return title === void 0 ? void 0 : {
75
- kind: "approve",
76
- title
77
- };
78
- }
79
- }
80
- }
81
- function titleOf(options) {
82
- for (const property of options.properties) {
83
- if (!ts.isPropertyAssignment(property)) continue;
84
- const name = property.name;
85
- if ((ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : void 0) === "title") return literalString(property.initializer);
86
- }
87
- }
88
- const counts = /* @__PURE__ */ new Map();
89
- const visit = (node) => {
90
- if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
91
- const method = node.expression.name.text;
92
- if (!hasExplicitId(node.arguments[optionsArgument[method]])) {
93
- const derived = sourceOf(node, method);
94
- if (derived) {
95
- const id = defaultDurableId(derived);
96
- const seen = counts.get(id);
97
- if (seen) seen.count += 1;
98
- else counts.set(id, {
99
- method,
100
- count: 1
101
- });
102
- }
103
- }
104
- }
105
- ts.forEachChild(node, visit);
106
- };
107
- visit(fn);
108
- return [...counts].filter(([, seen]) => seen.count > 1).map(([id, seen]) => ({
109
- id,
110
- method: seen.method,
111
- count: seen.count
112
- }));
113
- }
114
- //#endregion
115
- export { findDuplicateDefaultIds };