@lovable.dev/workflows-sdk 0.0.0-dev.10 → 0.0.0-dev.13

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
@@ -287,24 +287,29 @@ that join at the next step. Returned step promises work too. Keep step IDs liter
287
287
 
288
288
  For example, `read` followed by parallel `transform-a` and `transform-b`, then
289
289
  `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.
290
+ Node IDs are deterministic for the same source, but may change when the handler
291
+ is edited.
292
292
 
293
293
  Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
294
294
  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.
295
+ initialization. Branches, loops, helper calls, dynamic step IDs, and unawaited
296
+ steps produce `unknown` nodes and `complete: false`; steps inside unsupported
297
+ code are not expanded. The UI should show these unknown nodes and mark partial
298
+ graphs. Transforms that rewrite the handler may also produce a partial graph.
299
+ A handler with no steps can have an empty graph.
300
300
 
301
- ## Run endpoint (TanStack Start)
301
+ A step body is one atomic execution unit. Manifest generation rejects statically
302
+ visible durable calls inside it, including `ctx.step`, `ctx.sleep`, `ctx.now`,
303
+ and the other `ctx.*` operations. Move each durable operation into the workflow
304
+ handler and pass its result into the step instead.
302
305
 
303
- The same `workflowsPlugin` that writes the manifests also emits one dynamic
304
- route, `src/routes/api/workflows/$workflowId.ts`, serving every registered
306
+ ## Steps endpoint (TanStack Start)
307
+
308
+ The same `workflowsPlugin` that writes the manifests also emits
309
+ `src/routes/api/workflows/$workflowId/steps.ts`, serving every registered
305
310
  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:
311
+ One plugin and one `entry` feed the manifest and route, so they cannot describe
312
+ different workflow collections:
308
313
 
309
314
  ```ts
310
315
  import { tanstackStart } from "@tanstack/react-start/plugin/vite";
@@ -342,18 +347,16 @@ route there for it to be reachable at all:
342
347
  workflowsPlugin({ path: "/api/public/workflows" });
343
348
  ```
344
349
 
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.
350
+ That emits `src/routes/api/public/workflows/$workflowId/steps.ts` and serves
351
+ `POST /api/public/workflows/{workflow-id}/steps`. The trade is explicit: the
352
+ prefix that makes the route reachable also makes it anonymously reachable.
348
353
 
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.
354
+ The emitted file imports the collection and mounts its package handler. All
355
+ runtime logic stays in the package. A generated banner is the plugin's
356
+ ownership token: it rewrites and deletes only files that have it, and deletes
357
+ its own orphans when `path` or `workflowIdParam` changes. Delete the banner line
358
+ to take the route over. That is also the supported way to add a check of your
359
+ own in front of the handler.
357
360
 
358
361
  | Option | Default | Meaning |
359
362
  | --- | --- | --- |
@@ -387,14 +390,12 @@ configured still builds; only the specifier is uglier, and its depth tracks
387
390
 
388
391
  ### Calling it
389
392
 
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.
393
+ Each workflow gets one route for an external engine to drive one atomic step per
394
+ request.
392
395
 
393
396
  | Route | Does |
394
397
  | --- | --- |
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 |
398
+ | `POST /api/workflows/{id}/steps` | Advances a singleton frontier or executes one selected step |
398
399
 
399
400
  An unknown workflow ID returns 404 and an unparseable body 400.
400
401
 
@@ -412,14 +413,13 @@ run, from 0) — never by position or `seq`. Two parallel branches can reach the
412
413
  same pair of operations in either order from one pass to the next, so call order
413
414
  is reported but is not the identity.
414
415
 
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.
416
+ Every response returns a `memoDelta` and an `inputHash`. Merge the delta into the
417
+ memo by `(stepId, occurrence)`, then send the full memo, `inputHash`, `runId`, and
418
+ the same `input` on the next call. Replay re-runs the handler from the top, and
419
+ the memo does not carry the input. `inputHash` binds the memo to the input it came
420
+ from: resuming with a different one is a 400. Key order in the input does not
421
+ affect it. Because state travels in the request, a run survives a restart and can
422
+ continue on a different instance.
423
423
 
424
424
  Replay is what makes this work: the handler re-runs from the top on every call,
425
425
  settled operations answer from the memo instead of executing again, and
@@ -430,14 +430,30 @@ replay finds at its id, so a tampered or stale memo fails the call rather than
430
430
  answering the wrong one:
431
431
 
432
432
  ```json
433
- { "status": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
433
+ { "disposition": "failed", "error": "non-deterministic replay: memo has approve \"thing\" (#0), replay produced step" }
434
434
  ```
435
435
 
436
- **A repeated operation needs an explicit id.** `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.
436
+ **Every step ID must be unique within a workflow.** Manifest generation rejects
437
+ a repeated literal ID in sequential calls, parallel branches, mutually exclusive
438
+ branches, loops, and callbacks. Dynamic IDs cannot be proven at build time, so
439
+ the runtime refuses the second step that resolves to an ID already reached.
440
+
441
+ `ctx.now()`, `ctx.uuid()`, `ctx.sleep(ms)` and the other durable operations fall
442
+ back to a default ID. Two calls sharing one cannot be told apart on replay, so
443
+ the second is refused. Pass `{ id }` per call site: `ctx.now({ id: "started" })`.
444
+
445
+ Manifest generation rejects this before a run exists, when the arguments are
446
+ literal:
447
+
448
+ ```text
449
+ workflow "greet" calls ctx.now() 2 times with the default id "now";
450
+ replay cannot tell them apart, so pass an explicit { id } per call site
451
+ ```
452
+
453
+ The same applies to two `ctx.sleep(1000)` calls, two waits on one event name, or
454
+ two approvals with one title. Their default ID is derived from the argument, so
455
+ only a repeated argument collides. A dynamic argument is left to the runtime
456
+ check.
441
457
 
442
458
  **Handler code outside a step runs on every call.** Keep side effects inside
443
459
  `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
@@ -463,59 +479,56 @@ app has in the meantime; see `path` above.
463
479
  ### Stepping through a run
464
480
 
465
481
  ```bash
466
- POST /api/workflows/greet/nextSteps
482
+ POST /api/workflows/greet/steps
467
483
  { "input": { "name": "yehya" } }
468
- -> { "status": "pending", "memo": [], "steps": [{ "seq": 0, "stepId": "greeting", "kind": "step" }] }
469
-
470
- POST /api/workflows/greet/executeSteps
471
- { "input": { "name": "yehya" }, "memo": [], "steps": [{ "stepId": "greeting" }] }
472
- -> { "status": "pending",
473
- "results": [{ "seq": 0, "stepId": "greeting", "status": "completed", "result": "Hello, yehya!" }],
474
- "memo": [{ "seq": 0, "stepId": "greeting", ... }],
475
- "steps": [{ "seq": 1, "stepId": "shout", "kind": "step" }] }
484
+ -> { "disposition": "advanced",
485
+ "executed": { "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed" },
486
+ "memoDelta": [{ "stepId": "greeting", "occurrence": 0, ... }],
487
+ "next": [{ "seq": 1, "stepId": "shout", "occurrence": 0, "kind": "step" }] }
488
+
489
+ POST /api/workflows/greet/steps
490
+ { "action": "execute", "step": { "stepId": "shout", "occurrence": 0, "kind": "step" },
491
+ "input": { "name": "yehya" }, "memo": [...], "inputHash": "9f2c...", "runId": "run_..." }
492
+ -> { "disposition": "completed", "memoDelta": [...], "next": [], "output": "HELLO, YEHYA!" }
476
493
  ```
477
494
 
478
- Send the returned `memo` back each time; the run ends with
479
- `{"status": "completed", "output": ...}`. Omitting `steps` on `executeSteps`
480
- runs whatever `nextSteps` would report, so the run advances one wave per call.
495
+ Omitting `action` means `"advance"`. When the current frontier contains exactly
496
+ one app-executable step, `advance` executes it and returns the next frontier. A
497
+ sequential workflow therefore needs one HTTP call per step, including the first.
481
498
 
482
499
  ### Driving a run from an orchestrator
483
500
 
484
- **Loop on `executeSteps` alone, with `steps` omitted.** One response carries the
485
- results, the updated `memo`, *and* the operations now pending, so a driver never
486
- needs a separate `nextSteps` call:
501
+ Use the response disposition to choose the next call:
487
502
 
488
- ```jsonc
489
- // POST /api/workflows/greet/executeSteps { "input": {...} }
490
- { "status": "pending",
491
- "results": [{ "stepId": "greeting", "occurrence": 0, "kind": "step", "status": "completed", "result": "Hello, yehya!" }],
492
- "steps": [{ "stepId": "shout", "occurrence": 0, "kind": "step" }],
493
- "memo": [{ "stepId": "greeting", "occurrence": 0, ... }],
494
- "inputHash": "9f2c…" }
495
- ```
503
+ | Disposition | Engine action |
504
+ | --- | --- |
505
+ | `advanced` | Merge `memoDelta`, then execute the single entry in `next`. |
506
+ | `fork` | Merge `memoDelta`, then execute each app-executable entry in `next` in a separate concurrent request using that same memo. |
507
+ | `waiting` | Settle the external operations in `next`, then call `advance`. |
508
+ | `completed` | Persist `output`; the run is done. |
509
+ | `failed` | Apply the engine's retry or failure policy. |
496
510
 
497
- That is one HTTP call and one replay per wave — the cheapest shape, and the one
498
- to use when a remote orchestrator drives the app. Pairing `nextSteps` with
499
- `executeSteps` doubles both: use it when something needs to *see* what would run
500
- before it runs, such as a UI preview or an approval gate.
511
+ At a fork, every `execute` request receives the same base memo and selects one
512
+ `{ kind: "step", stepId, occurrence }`. Merge all returned deltas, then call
513
+ `advance` once. That replay crosses the join and immediately executes a
514
+ singleton tail when one exists. Do not schedule from one branch's `next`: a
515
+ partial branch response cannot see results still running in its siblings.
501
516
 
502
- Concurrent steps settle together: `Promise.all([ctx.step("a"), ctx.step("b")])`
503
- is one wave, and a step after the join is the next.
517
+ An `execute` call runs only its selected step. The endpoint returns 409
518
+ `stale_step` if that reference is not executable from the supplied memo.
504
519
 
505
520
  Keep a step's result small: it travels in the memo on every later call, so a
506
521
  large payload is resent for the rest of the run. Write bulk data to storage
507
522
  inside the step and return the key.
508
523
 
509
- **Replay cost.** Each pass re-runs the handler from the top, so code outside
510
- `ctx.step` executes once per wave — for an 8-step workflow, 8 times through a
511
- `executeSteps` loop and 16 through a `nextSteps` + `executeSteps` one. Step
512
- bodies run exactly once each. This is why side effects belong inside a step.
524
+ Each call re-runs the handler from the top. Step bodies run only in their
525
+ selected request, so side effects belong inside a step.
513
526
 
514
- `nextSteps` reports a step's `stepId` and `kind` but **not its input**:
527
+ `next` reports a step's `stepId` and `kind` but not its input:
515
528
  `ctx.step(id, fn)` closes over its arguments rather than declaring them, so the
516
529
  input is not knowable without running `fn`. Deterministic values (`ctx.now`,
517
- `ctx.uuid`) are the exception to the no-side-effects rule — `nextSteps` pins them
518
- and returns them in `memo`, so a later `executeSteps` replays the same values.
530
+ `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay the same
531
+ values after the engine merges the delta.
519
532
 
520
533
  ### Waiting on something outside the app
521
534
 
@@ -528,37 +541,14 @@ a caller needs to resolve them:
528
541
  "config": { "title": "Approve refund", "description": "refund of $40" } }
529
542
  ```
530
543
 
531
- The run surface emits `RUN_PAUSED` with that list and the memo, then ends the
532
- request rather than holding a connection open. Resume by appending the decision
533
- to the memo and calling again:
544
+ The endpoint returns `waiting` with that list in `next`. Resume by appending the
545
+ decision to the memo and calling `advance`:
534
546
 
535
547
  ```jsonc
536
548
  { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
537
549
  "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
538
550
  ```
539
551
 
540
- ### The run surface
541
-
542
- `POST /api/workflows/{workflow-id}` with `{ "input": ... }` starts a run and
543
- `{ "memo": [...] }` continues one. The response is `text/event-stream`, one SSE
544
- message per event, the event name being its `type`:
545
-
546
- ```text
547
- event: RUN_STARTED
548
- data: {"type":"RUN_STARTED","ts":1790528863501,"runId":"run_1790528863501_tzqgjl8i"}
549
-
550
- event: STEP_FINISHED
551
- data: {"type":"STEP_FINISHED","ts":1790528863571,"stepId":"greeting","result":"Hello, yehya!"}
552
-
553
- event: RUN_FINISHED
554
- data: {"type":"RUN_FINISHED","ts":1790528863685,"runId":"...","output":{"message":"Hello, yehya!"}}
555
- ```
556
-
557
- It drives the memo loop internally for the length of one request, so it holds no
558
- state between requests either. `RUN_FINISHED`, `RUN_ERRORED` and `RUN_PAUSED` all carry the
559
- memo, so a caller that only sent an input still holds what already ran and a
560
- retry does not repeat it.
561
-
562
552
  `createTanStackWorkflowHandler` is still exported for the engine-backed path
563
553
  (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
564
554
  route uses it: a process-local store loses runs on restart and is invisible to
@@ -571,9 +561,8 @@ caller decides whether to re-issue a failed step. Step retry, timeouts, and
571
561
  `previousVersions` routing are follow-ups.
572
562
 
573
563
  The path carries no build ID. Version pinning belongs to the signed invocation,
574
- which leaves these paths stable across deployments and safe to publish in a
575
- manifest. Triggers name a workflow rather than an endpoint, so firing one is a
576
- POST to that workflow's run path with the trigger's input; no trigger identifier
564
+ which leaves it stable across deployments and safe to publish in a manifest.
565
+ Triggers name a workflow rather than an endpoint, so no trigger identifier
577
566
  appears in the URL.
578
567
 
579
568
  ## Public entry points
@@ -582,7 +571,7 @@ The package has two, and neither mirrors the source tree:
582
571
 
583
572
  | Import | Provides |
584
573
  | --- | --- |
585
- | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the route handlers (`createRunHandler`, `createNextStepsHandler`, `createExecuteStepsHandler`) |
574
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and the `createStepsHandler` route handler |
586
575
  | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
587
576
 
588
577
  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-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
+ 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 };
@@ -0,0 +1,17 @@
1
+ //#region src/core/durable-ids.ts
2
+ /**
3
+ * Shared by the runtime and the build-time check, so the ids a build rejects
4
+ * are exactly the ones replay would collide.
5
+ */
6
+ function defaultDurableId(source) {
7
+ switch (source.kind) {
8
+ case "now": return "now";
9
+ case "uuid": return "uuid";
10
+ case "sleep": return `sleep:${source.ms}`;
11
+ case "sleepUntil": return `sleepUntil:${source.timestamp}`;
12
+ case "waitForEvent": return `event:${source.name}`;
13
+ case "approve": return `approve:${source.title}`;
14
+ }
15
+ }
16
+ //#endregion
17
+ export { defaultDurableId as t };
@@ -183,11 +183,26 @@ function serializeSchema(schema, direction, label) {
183
183
  }
184
184
  }
185
185
  async function generateManifests(definition) {
186
- const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
186
+ const { extractWorkflowGraph } = await import("./graph-CPDci8jW.js");
187
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-CzUHGRC_.js");
188
+ const { findNestedDurableOperations } = await import("./nested-operations-BnWB9UhQ.js");
187
189
  const collection = registerWorkflows(definition);
188
190
  const manifests = [];
189
191
  for (const workflow of collection.workflows) {
190
192
  if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
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
+ }
191
206
  const metadata = {
192
207
  id: workflow.id,
193
208
  ...workflow.description === void 0 ? {} : { description: workflow.description },
@@ -198,4 +198,4 @@ async function extractWorkflowGraph(handler) {
198
198
  return graph;
199
199
  }
200
200
  //#endregion
201
- export { extractWorkflowGraph };
201
+ export { extractWorkflowGraph, loadTypeScript };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, RunStore, StepContext, StepOptions, WorkflowDefinition, WorkflowEvent, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
+ import "typescript";
2
3
  //#region src/core/cadence.d.ts
3
4
  type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
5
  type Cadence = {
@@ -147,33 +148,6 @@ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
147
148
  /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
148
149
  declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
149
150
  //#endregion
150
- //#region src/stacks/tanstack/steps.d.ts
151
- interface StepsHandlerOptions {
152
- /** Route parameter carrying the workflow ID. @default "workflowId" */
153
- workflowIdParam?: string;
154
- }
155
- interface RouteCtx {
156
- request: Request;
157
- params?: Record<string, string | undefined>;
158
- }
159
- type StepsHandler = (ctx: RouteCtx) => Promise<Response>;
160
- /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
161
- * `memo` so a later executeSteps replays the same values. */
162
- declare function createNextStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
163
- /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
164
- * report, advancing the run one wave per call. */
165
- declare function createExecuteStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
166
- //#endregion
167
- //#region src/stacks/tanstack/run.d.ts
168
- declare function createRunHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
169
- //#endregion
170
- //#region src/stacks/tanstack/sse.d.ts
171
- /**
172
- * Encode a workflow event stream as `text/event-stream`. Each event keeps its
173
- * engine `type` as the SSE event name and its whole JSON as the data line.
174
- */
175
- declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
176
- //#endregion
177
151
  //#region src/runtime/types.d.ts
178
152
  /** Durable operations a replay can answer from the memo. */
179
153
  type StepKind = "step" | "sleep" | "waitForEvent" | "approve" | "now" | "uuid";
@@ -195,20 +169,24 @@ interface MemoEntry {
195
169
  result?: unknown;
196
170
  error?: string;
197
171
  }
198
- /** A durable operation the replay reached but could not answer. */
199
- interface StepIntent {
172
+ interface StepIntentBase {
200
173
  seq: number;
201
174
  stepId: string;
202
175
  occurrence: number;
203
- kind: StepKind;
204
176
  /** Kind-specific detail: sleep `ms`, `waitForEvent` name, approval title. */
205
177
  config?: Record<string, unknown>;
206
178
  }
207
- interface StepResult {
179
+ /** A durable operation the replay reached but could not answer. */
180
+ type StepIntent = StepIntentBase & ({
181
+ kind: "step";
182
+ } | {
183
+ kind: Exclude<StepKind, "step">;
184
+ });
185
+ interface StepResult<K extends StepKind = StepKind> {
208
186
  seq: number;
209
187
  stepId: string;
210
188
  occurrence: number;
211
- kind: StepKind;
189
+ kind: K;
212
190
  status: "completed" | "failed";
213
191
  result?: unknown;
214
192
  error?: string;
@@ -230,11 +208,57 @@ interface ReplayOutcome {
230
208
  output?: unknown;
231
209
  error?: string;
232
210
  }
233
- /** Identifies one durable operation for `executeSteps`. */
234
- interface StepSelector {
211
+ interface StepReference {
212
+ kind: "step";
235
213
  stepId: string;
236
- /** Defaults to 0; needed only when a run calls the same `stepId` more than once. */
237
- occurrence?: number;
214
+ occurrence: number;
238
215
  }
239
216
  //#endregion
240
- 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 };
217
+ //#region src/stacks/tanstack/steps.d.ts
218
+ interface StepsHandlerOptions {
219
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
220
+ workflowIdParam?: string;
221
+ }
222
+ interface RouteCtx {
223
+ request: Request;
224
+ params?: Record<string, string | undefined>;
225
+ }
226
+ type StepsHandler = (ctx: RouteCtx) => Promise<Response>;
227
+ interface StepsRequestBase {
228
+ input?: unknown;
229
+ memo?: MemoEntry[];
230
+ runId?: string;
231
+ inputHash?: string;
232
+ }
233
+ type StepsRequest = StepsRequestBase & ({
234
+ action?: "advance";
235
+ step?: never;
236
+ } | {
237
+ action: "execute";
238
+ step: StepReference;
239
+ });
240
+ type StepsDisposition = "advanced" | "fork" | "waiting" | "completed" | "failed";
241
+ interface StepsResponse {
242
+ runId: string;
243
+ inputHash: string;
244
+ disposition: StepsDisposition;
245
+ memoDelta: MemoEntry[];
246
+ next: StepIntent[];
247
+ executed?: StepResult<"step">;
248
+ emitted?: {
249
+ name: string;
250
+ value: Record<string, unknown>;
251
+ }[];
252
+ output?: unknown;
253
+ error?: string;
254
+ }
255
+ declare function createStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
256
+ //#endregion
257
+ //#region src/stacks/tanstack/sse.d.ts
258
+ /**
259
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
260
+ * engine `type` as the SSE event name and its whole JSON as the data line.
261
+ */
262
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
263
+ //#endregion
264
+ 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,5 @@
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-DyUHbtre.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-CKSL3f8L.js";
2
+ import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
3
  import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
3
4
  //#region src/stacks/tanstack/sse.ts
4
5
  const HEADERS = {
@@ -188,6 +189,10 @@ async function replay(options) {
188
189
  const index = seq++;
189
190
  const occurrence = occurrences.get(stepId) ?? 0;
190
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
+ }
191
196
  if (defaulted && occurrence > 0) {
192
197
  nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
193
198
  return never;
@@ -265,15 +270,27 @@ async function replay(options) {
265
270
  runtime,
266
271
  signal: controller.signal
267
272
  })),
268
- sleep: (ms, opts) => durable("sleep", opts?.id ?? `sleep:${ms}`, void 0, { ms }, opts?.id === void 0),
269
- sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? `sleepUntil:${timestamp}`, void 0, { timestamp }, opts?.id === void 0),
270
- waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? `event:${name}`, void 0, { name }, opts?.id === void 0),
271
- approve: (opts) => durable("approve", opts.id ?? `approve:${opts.title}`, void 0, {
273
+ sleep: (ms, opts) => durable("sleep", opts?.id ?? defaultDurableId({
274
+ kind: "sleep",
275
+ ms
276
+ }), void 0, { ms }, opts?.id === void 0),
277
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? defaultDurableId({
278
+ kind: "sleepUntil",
279
+ timestamp
280
+ }), void 0, { timestamp }, opts?.id === void 0),
281
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? defaultDurableId({
282
+ kind: "waitForEvent",
283
+ name
284
+ }), void 0, { name }, opts?.id === void 0),
285
+ approve: (opts) => durable("approve", opts.id ?? defaultDurableId({
286
+ kind: "approve",
287
+ title: opts.title
288
+ }), void 0, {
272
289
  title: opts.title,
273
290
  ...opts.description === void 0 ? {} : { description: opts.description }
274
291
  }, opts.id === void 0),
275
- now: (opts) => durable("now", opts?.id ?? "now", async () => Date.now(), void 0, opts?.id === void 0),
276
- uuid: (opts) => durable("uuid", opts?.id ?? "uuid", async () => crypto.randomUUID(), void 0, opts?.id === void 0),
292
+ now: (opts) => durable("now", opts?.id ?? defaultDurableId({ kind: "now" }), async () => Date.now(), void 0, opts?.id === void 0),
293
+ uuid: (opts) => durable("uuid", opts?.id ?? defaultDurableId({ kind: "uuid" }), async () => crypto.randomUUID(), void 0, opts?.id === void 0),
277
294
  emit: (name, value) => {
278
295
  emitted.push({
279
296
  name,
@@ -307,14 +324,18 @@ async function replay(options) {
307
324
  }
308
325
  while (inflight.length > 0) await Promise.all(inflight.splice(0));
309
326
  const memo = [...byKey.values(), ...settled.values()];
310
- const hidden = (key, seen) => {
311
- const parent = byKey.get(key)?.parent;
312
- if (parent === void 0 || seen.has(parent)) return false;
313
- if (consumed.has(parent)) return true;
314
- seen.add(parent);
315
- 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
+ }
316
337
  };
317
- 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));
318
339
  pending.sort((a, b) => a.seq - b.seq);
319
340
  results.sort((a, b) => a.seq - b.seq);
320
341
  const base = {
@@ -383,7 +404,9 @@ function parseBody(value) {
383
404
  if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
384
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";
385
406
  }
386
- 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\"";
387
410
  if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
388
411
  return body;
389
412
  }
@@ -392,22 +415,32 @@ async function readBody(request) {
392
415
  if (!text.trim()) return {};
393
416
  return JSON.parse(text);
394
417
  }
395
- function selectorKey(selector) {
396
- 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;
397
424
  }
398
- function isSelector(value) {
399
- const selector = value;
400
- 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";
401
430
  }
402
- function respond(runId, inputHash, outcome) {
403
- 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;
404
437
  return json(200, {
405
438
  runId,
406
439
  inputHash,
407
- status,
408
- memo,
409
- steps,
410
- results,
440
+ disposition: disposition(outcome),
441
+ memoDelta: memoDelta(before, outcome.memo),
442
+ next: steps,
443
+ ...executed === void 0 ? {} : { executed },
411
444
  ...emitted.length > 0 ? { emitted } : {},
412
445
  ...output === void 0 ? {} : { output },
413
446
  ...error === void 0 ? {} : { error }
@@ -452,199 +485,53 @@ async function resolve(ctx, param, byId) {
452
485
  inputHash
453
486
  };
454
487
  }
455
- /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
456
- * `memo` so a later executeSteps replays the same values. */
457
- function createNextStepsHandler(collection, options = {}) {
458
- const { param, byId } = prepare(collection, options);
459
- return async (ctx) => {
460
- const resolved = await resolve(ctx, param, byId);
461
- if (resolved instanceof Response) return resolved;
462
- const { workflow, body, runId, inputHash } = resolved;
463
- return respond(runId, inputHash, await replay({
464
- workflow,
465
- input: body.input ?? null,
466
- memo: body.memo ?? [],
467
- runId,
468
- shouldExecute: (intent) => intent.kind !== "step"
469
- }));
470
- };
471
- }
472
- /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
473
- * report, advancing the run one wave per call. */
474
- function createExecuteStepsHandler(collection, options = {}) {
488
+ function createStepsHandler(collection, options = {}) {
475
489
  const { param, byId } = prepare(collection, options);
476
490
  return async (ctx) => {
477
491
  const resolved = await resolve(ctx, param, byId);
478
492
  if (resolved instanceof Response) return resolved;
479
493
  const { workflow, body, runId, inputHash } = resolved;
480
494
  const input = body.input ?? null;
481
- const memo = body.memo ?? [];
482
- const wanted = body.steps && new Set(body.steps.map(selectorKey));
483
- 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({
484
513
  workflow,
485
514
  input,
486
- memo,
515
+ memo: before,
487
516
  runId,
488
- shouldExecute: (intent, pass) => intent.kind !== "step" || (wanted ? wanted.has(selectorKey(intent)) : pass.stepsSettled === 0)
489
- }));
490
- };
491
- }
492
- //#endregion
493
- //#region src/stacks/tanstack/run.ts
494
- function event(type, fields) {
495
- return {
496
- type,
497
- ts: Date.now(),
498
- ...fields
499
- };
500
- }
501
- async function* drive(workflow, input, runId, initialMemo, inputHash) {
502
- let memo = [...initialMemo];
503
- yield event("RUN_STARTED", {
504
- runId,
505
- inputHash
506
- });
507
- for (;;) {
508
- const queue = [];
509
- let wake;
510
- const emit = (next) => {
511
- queue.push(next);
512
- wake?.();
513
- wake = void 0;
514
- };
515
- let settledPass;
516
- let passError;
517
- let finished = false;
518
- 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({
519
522
  workflow,
520
523
  input,
521
- memo,
524
+ memo: described.memo,
522
525
  runId,
523
- shouldExecute: (intent, state) => intent.kind !== "step" || state.stepsSettled === 0,
524
- onStepStart: (intent) => {
525
- if (intent.kind === "step") emit(event("STEP_STARTED", { stepId: intent.stepId }));
526
- },
527
- onStepSettle: (result) => {
528
- if (result.kind !== "step") return;
529
- emit(result.status === "completed" ? event("STEP_FINISHED", {
530
- stepId: result.stepId,
531
- result: result.result
532
- }) : event("STEP_FAILED", {
533
- stepId: result.stepId,
534
- error: result.error
535
- }));
536
- }
537
- }).then((value) => {
538
- settledPass = value;
539
- finished = true;
540
- wake?.();
541
- wake = void 0;
542
- }, (error) => {
543
- passError = error;
544
- finished = true;
545
- wake?.();
546
- wake = void 0;
526
+ shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(only)
547
527
  });
548
- for (;;) {
549
- if (queue.length > 0) {
550
- yield queue.shift();
551
- continue;
552
- }
553
- if (finished) break;
554
- await new Promise((resolve) => {
555
- wake = resolve;
556
- });
557
- }
558
- await running;
559
- if (!settledPass) {
560
- yield event("RUN_ERRORED", {
561
- runId,
562
- inputHash,
563
- error: `replay threw: ${passError instanceof Error ? passError.message : String(passError)}`,
564
- memo
565
- });
566
- return;
567
- }
568
- const pass = settledPass;
569
- memo = pass.memo;
570
- if (pass.status === "completed") {
571
- yield event("RUN_FINISHED", {
572
- runId,
573
- inputHash,
574
- output: pass.output,
575
- memo
576
- });
577
- return;
578
- }
579
- if (pass.status === "failed") {
580
- yield event("RUN_ERRORED", {
581
- runId,
582
- inputHash,
583
- error: pass.error,
584
- memo
585
- });
586
- return;
587
- }
588
- if (pass.steps.every((intent) => intent.kind !== "step")) {
589
- yield event("RUN_PAUSED", {
590
- runId,
591
- inputHash,
592
- waitingOn: pass.steps,
593
- memo
594
- });
595
- return;
596
- }
597
- if (pass.results.length === 0) {
598
- yield event("RUN_ERRORED", {
599
- runId,
600
- inputHash,
601
- error: "run made no progress",
602
- memo
603
- });
604
- return;
605
- }
606
- }
607
- }
608
- function createRunHandler(collection, options = {}) {
609
- const param = options.workflowIdParam ?? "workflowId";
610
- const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
611
- return async (ctx) => {
612
- const workflowId = ctx.params?.[param] ?? new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
613
- const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
614
- if (!workflow) return new Response(JSON.stringify({
615
- error: "unknown_workflow",
616
- workflowId: workflowId ?? ""
617
- }), {
618
- status: 404,
619
- 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`
620
532
  });
621
- let body = {};
622
- try {
623
- const text = await ctx.request.text();
624
- if (text.trim()) body = JSON.parse(text);
625
- } catch (error) {
626
- return new Response(JSON.stringify({
627
- error: "invalid_request",
628
- message: String(error)
629
- }), {
630
- status: 400,
631
- headers: { "content-type": "application/json; charset=utf-8" }
632
- });
633
- }
634
- const inputHash = await hashInput(body.input ?? null);
635
- if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) {
636
- 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";
637
- return new Response(JSON.stringify({
638
- error: "invalid_request",
639
- message
640
- }), {
641
- status: 400,
642
- headers: { "content-type": "application/json; charset=utf-8" }
643
- });
644
- }
645
- const runId = body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
646
- return toServerSentEventsResponse(drive(workflow, body.input ?? null, runId, body.memo ?? [], inputHash));
533
+ return respond(runId, inputHash, before, outcome, executed);
647
534
  };
648
535
  }
649
536
  //#endregion
650
- 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-CPDci8jW.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-DyUHbtre.js";
1
+ import { t as generateManifests } from "./generate-CKSL3f8L.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.10",
3
+ "version": "0.0.0-dev.13",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",