@lovable.dev/workflows-sdk 0.0.0-dev.11 → 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,17 @@ 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 — 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.
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" })`.
441
444
 
442
445
  Manifest generation rejects this before a run exists, when the arguments are
443
446
  literal:
@@ -447,10 +450,10 @@ workflow "greet" calls ctx.now() 2 times with the default id "now";
447
450
  replay cannot tell them apart, so pass an explicit { id } per call site
448
451
  ```
449
452
 
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.
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.
454
457
 
455
458
  **Handler code outside a step runs on every call.** Keep side effects inside
456
459
  `ctx.step`, which is memoized; a bare `fetch` in the handler body repeats each
@@ -476,59 +479,56 @@ app has in the meantime; see `path` above.
476
479
  ### Stepping through a run
477
480
 
478
481
  ```bash
479
- POST /api/workflows/greet/nextSteps
482
+ POST /api/workflows/greet/steps
480
483
  { "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" }] }
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!" }
489
493
  ```
490
494
 
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.
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.
494
498
 
495
499
  ### Driving a run from an orchestrator
496
500
 
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:
501
+ Use the response disposition to choose the next call:
500
502
 
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
- ```
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. |
509
510
 
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.
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.
514
516
 
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.
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.
517
519
 
518
520
  Keep a step's result small: it travels in the memo on every later call, so a
519
521
  large payload is resent for the rest of the run. Write bulk data to storage
520
522
  inside the step and return the key.
521
523
 
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.
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.
526
526
 
527
- `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:
528
528
  `ctx.step(id, fn)` closes over its arguments rather than declaring them, so the
529
529
  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.
530
+ `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay the same
531
+ values after the engine merges the delta.
532
532
 
533
533
  ### Waiting on something outside the app
534
534
 
@@ -541,37 +541,14 @@ a caller needs to resolve them:
541
541
  "config": { "title": "Approve refund", "description": "refund of $40" } }
542
542
  ```
543
543
 
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:
544
+ The endpoint returns `waiting` with that list in `next`. Resume by appending the
545
+ decision to the memo and calling `advance`:
547
546
 
548
547
  ```jsonc
549
548
  { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
550
549
  "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
551
550
  ```
552
551
 
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
552
  `createTanStackWorkflowHandler` is still exported for the engine-backed path
576
553
  (`runWorkflow` plus a `RunStore`, `inMemoryRunStore()` by default). No emitted
577
554
  route uses it: a process-local store loses runs on restart and is invisible to
@@ -584,9 +561,8 @@ caller decides whether to re-issue a failed step. Step retry, timeouts, and
584
561
  `previousVersions` routing are follow-ups.
585
562
 
586
563
  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
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
590
566
  appears in the URL.
591
567
 
592
568
  ## Public entry points
@@ -595,7 +571,7 @@ The package has two, and neither mirrors the source tree:
595
571
 
596
572
  | Import | Provides |
597
573
  | --- | --- |
598
- | `@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 |
599
575
  | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
600
576
 
601
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 };
@@ -184,12 +184,25 @@ function serializeSchema(schema, direction, label) {
184
184
  }
185
185
  async function generateManifests(definition) {
186
186
  const { extractWorkflowGraph } = await import("./graph-CPDci8jW.js");
187
- const { findDuplicateDefaultIds } = await import("./duplicate-ids-CSzTGBYE.js");
187
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-CzUHGRC_.js");
188
+ const { findNestedDurableOperations } = await import("./nested-operations-BnWB9UhQ.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 },
package/dist/index.d.ts CHANGED
@@ -148,33 +148,6 @@ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
148
148
  /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
149
149
  declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
150
150
  //#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
151
  //#region src/runtime/types.d.ts
179
152
  /** Durable operations a replay can answer from the memo. */
180
153
  type StepKind = "step" | "sleep" | "waitForEvent" | "approve" | "now" | "uuid";
@@ -196,20 +169,24 @@ interface MemoEntry {
196
169
  result?: unknown;
197
170
  error?: string;
198
171
  }
199
- /** A durable operation the replay reached but could not answer. */
200
- interface StepIntent {
172
+ interface StepIntentBase {
201
173
  seq: number;
202
174
  stepId: string;
203
175
  occurrence: number;
204
- kind: StepKind;
205
176
  /** Kind-specific detail: sleep `ms`, `waitForEvent` name, approval title. */
206
177
  config?: Record<string, unknown>;
207
178
  }
208
- 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> {
209
186
  seq: number;
210
187
  stepId: string;
211
188
  occurrence: number;
212
- kind: StepKind;
189
+ kind: K;
213
190
  status: "completed" | "failed";
214
191
  result?: unknown;
215
192
  error?: string;
@@ -231,11 +208,57 @@ interface ReplayOutcome {
231
208
  output?: unknown;
232
209
  error?: string;
233
210
  }
234
- /** Identifies one durable operation for `executeSteps`. */
235
- interface StepSelector {
211
+ interface StepReference {
212
+ kind: "step";
236
213
  stepId: string;
237
- /** Defaults to 0; needed only when a run calls the same `stepId` more than once. */
238
- occurrence?: number;
214
+ occurrence: number;
239
215
  }
240
216
  //#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 };
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,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-CKSL3f8L.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-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-DkZJkfZ1.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.11",
3
+ "version": "0.0.0-dev.13",
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 };