@lovable.dev/workflows-sdk 0.0.0-dev.16 → 0.0.0-dev.18

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
@@ -46,9 +46,17 @@ definitions as immutable after registration.
46
46
  See [the authoring example](examples/src/lib/workflows/greet/index.ts) for schemas,
47
47
  typed middleware, and a durable step. The package typecheck includes this example.
48
48
 
49
- Every `ctx.step()` needs a static, user-facing description. Lovable's agent
50
- supplies this text so the workflow UI can explain what the step does before and
51
- during a run:
49
+ Every durable operation needs a static, user-facing description. Lovable's
50
+ agent supplies this text so the workflow UI can explain each operation before
51
+ and during a run. Put it in the operation's options:
52
+
53
+ | Operation | Description field |
54
+ | --- | --- |
55
+ | `ctx.step` | Third argument: `meta.description` |
56
+ | `ctx.sleep`, `ctx.sleepUntil` | Second argument: `meta.description` |
57
+ | `ctx.waitForEvent` | Second argument: `meta.description` |
58
+ | `ctx.now`, `ctx.uuid` | First argument: `meta.description` |
59
+ | `ctx.approve` | First argument: `description` |
52
60
 
53
61
  ```ts
54
62
  await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
@@ -309,19 +317,35 @@ step ID template `step-${item.id}` produces one dynamic parallel node labeled
309
317
  from `meta.group.label`. Returned step promises work too. Keep step IDs literal
310
318
  outside this mapped form.
311
319
 
320
+ An `if` whose body contains durable operations produces a `branch` node. Every
321
+ durable operation inside it includes an outer-to-inner `meta.branches` path;
322
+ each entry has a static `id` and agent-written `description`. Both sides of one
323
+ condition use the same entry. The AST determines nesting and whether an edge is
324
+ the `true` or `false` outcome, so metadata never declares topology. Branch IDs
325
+ identify one `if` statement within the workflow.
326
+
327
+ ```ts
328
+ meta: {
329
+ description: "Publish the approved draft",
330
+ branches: [{ id: "editor-approved", description: "The editor approved the draft" }],
331
+ }
332
+ ```
333
+
312
334
  | Field | Meaning |
313
335
  | --- | --- |
314
336
  | `nodes[].id` | Unique occurrence ID within this graph; use as the UI node key |
315
- | `nodes[].kind` | Durable operation, `parallel`, or `unknown` |
337
+ | `nodes[].kind` | Durable operation, `branch`, `parallel`, or `unknown` |
316
338
  | `nodes[].stepId` | Runtime durable ID for every statically known operation |
317
- | `nodes[].description` | User-facing description for a static step |
339
+ | `nodes[].description` | User-facing description for every known durable operation and branch |
340
+ | `nodes[].branchId` | Stable ID for an inferred `if` node |
341
+ | `nodes[].condition` | Source expression from the corresponding `if` statement |
318
342
  | `nodes[].groupId` | Stable callsite ID for a dynamic parallel node |
319
343
  | `nodes[].cardinality` | `dynamic` for a runtime-sized parallel fan-out |
320
344
  | `nodes[].operation.kind` | Durable operation repeated by a parallel node |
321
345
  | `nodes[].operation.stepIdTemplate` | Display template for steps in a dynamic parallel node |
322
346
  | `nodes[].operation.description` | User-facing description shared by the repeated steps |
323
- | `nodes[].label` | Step ID, group label, or explanation of unsupported code |
324
- | `edges[]` | `{ source, target, kind: "order" }`, referencing node IDs |
347
+ | `nodes[].label` | Step ID, branch description, group label, or explanation of unsupported code |
348
+ | `edges[]` | Order edges or branch edges with an AST-derived boolean `outcome`, referencing node IDs |
325
349
  | `complete` | Whether the handler uses only supported syntax |
326
350
  | `diagnostics` | Reasons the graph is partial |
327
351
 
@@ -338,11 +362,11 @@ Graphs have `source: "inferred"` and `scope: "handler"`. They describe source
338
362
  structure, not run history or data dependencies, and exclude middleware and
339
363
  initialization. A mapped `Promise.all` is complete when its callback directly
340
364
  returns `ctx.step()` with a template-literal ID derived from a callback parameter.
341
- Other branches, loops, helper calls, dynamic step IDs, and unawaited steps produce
342
- `unknown` nodes and `complete: false`; steps inside unsupported code are not
343
- expanded. The UI should show these unknown nodes and mark partial graphs.
344
- Transforms that rewrite the handler may also produce a partial graph. A handler
345
- with no steps can have an empty graph.
365
+ Loops, switch statements, conditional expressions, helper calls, dynamic step IDs,
366
+ and unawaited steps produce `unknown` nodes and `complete: false`; steps inside
367
+ unsupported code are not expanded. The UI should show these unknown nodes and mark
368
+ partial graphs. Transforms that rewrite the handler may also produce a partial
369
+ graph. A handler with no steps can have an empty graph.
346
370
 
347
371
  A step body is one atomic execution unit. Manifest generation rejects statically
348
372
  visible durable calls inside it, including `ctx.step`, `ctx.sleep`, `ctx.now`,
@@ -578,8 +602,10 @@ inside the step and return the key.
578
602
  Each call re-runs the handler from the top. Step bodies run only in their
579
603
  selected request, so side effects belong inside a step.
580
604
 
581
- `next` reports a step's `stepId`, `kind`, and author-supplied `meta`, including
582
- its description and group. It does not report the step input:
605
+ `next` reports an operation's `stepId`, `kind`, and author-supplied `meta`,
606
+ including its description and group. An approval's top-level authoring
607
+ description is copied into runtime metadata for the same response shape. `next`
608
+ does not report a step's input:
583
609
  `ctx.step(id, fn, options)` closes over its arguments rather than declaring
584
610
  them, so the input is not knowable without running `fn`. Deterministic values
585
611
  (`ctx.now`, `ctx.uuid`) are pinned into `memoDelta`, so concurrent calls replay
@@ -593,14 +619,16 @@ a caller needs to resolve them:
593
619
 
594
620
  ```json
595
621
  { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
596
- "config": { "title": "Approve refund", "description": "refund of $40" } }
622
+ "meta": { "description": "Ask a reviewer to approve the refund" },
623
+ "config": { "title": "Approve refund", "description": "Ask a reviewer to approve the refund" } }
597
624
  ```
598
625
 
599
626
  The endpoint returns `waiting` with that list in `next`. Resume by appending the
600
- decision to the memo and calling `advance`:
627
+ decision to the memo, preserving its `meta`, and calling `advance`:
601
628
 
602
629
  ```jsonc
603
630
  { "seq": 1, "stepId": "approve:Approve refund", "kind": "approve",
631
+ "meta": { "description": "Ask a reviewer to approve the refund" },
604
632
  "status": "completed", "result": { "approved": true, "approvalId": "apr_1" } }
605
633
  ```
606
634
 
@@ -0,0 +1,110 @@
1
+ import { loadTypeScript } from "./graph-V2yqSs3X.js";
2
+ //#region src/manifests/branch-metadata.ts
3
+ const optionsArgument = {
4
+ step: 2,
5
+ approve: 0,
6
+ sleep: 1,
7
+ sleepUntil: 1,
8
+ waitForEvent: 1,
9
+ now: 0,
10
+ uuid: 0
11
+ };
12
+ async function findBranchMetadataIssues(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 property(node, name) {
24
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
25
+ for (const entry of node.properties) {
26
+ if (!ts.isPropertyAssignment(entry)) continue;
27
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
28
+ }
29
+ }
30
+ function literalString(node) {
31
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
32
+ }
33
+ function durableCall(node) {
34
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || !ts.isIdentifier(node.expression.expression) || node.expression.expression.text !== context || !(node.expression.name.text in optionsArgument)) return;
35
+ return {
36
+ call: node,
37
+ method: node.expression.name.text
38
+ };
39
+ }
40
+ function branchPath(call, method) {
41
+ const options = call.arguments[optionsArgument[method]];
42
+ const branches = property(property(options, "meta"), "branches");
43
+ if (!branches || !ts.isArrayLiteralExpression(branches)) return void 0;
44
+ const path = [];
45
+ for (const element of branches.elements) {
46
+ if (!ts.isObjectLiteralExpression(element)) return void 0;
47
+ const id = literalString(property(element, "id"));
48
+ const description = literalString(property(element, "description"));
49
+ if (id === void 0 || description === void 0) return void 0;
50
+ path.push({
51
+ id,
52
+ description
53
+ });
54
+ }
55
+ return path;
56
+ }
57
+ const issues = [];
58
+ const metadataByBranch = /* @__PURE__ */ new Map();
59
+ const branchById = /* @__PURE__ */ new Map();
60
+ function visit(node, branches) {
61
+ if (issues.length > 0) return;
62
+ if (ts.isIfStatement(node)) {
63
+ visit(node.expression, branches);
64
+ visit(node.thenStatement, [...branches, node]);
65
+ if (node.elseStatement) visit(node.elseStatement, [...branches, node]);
66
+ return;
67
+ }
68
+ const durable = durableCall(node);
69
+ if (durable) {
70
+ const path = branchPath(durable.call, durable.method);
71
+ const stepId = durable.method === "step" ? literalString(durable.call.arguments[0]) : void 0;
72
+ if (branches.length === 0 && path !== void 0 || branches.length > 0 && (path === void 0 || path.length !== branches.length)) {
73
+ issues.push({
74
+ kind: "path",
75
+ method: durable.method,
76
+ ...stepId === void 0 ? {} : { stepId }
77
+ });
78
+ return;
79
+ }
80
+ for (let index = 0; index < branches.length; index++) {
81
+ const branch = branches[index];
82
+ const entry = path?.[index];
83
+ if (!branch || !entry) continue;
84
+ const existing = metadataByBranch.get(branch);
85
+ if (existing && (existing.id !== entry.id || existing.description !== entry.description)) {
86
+ issues.push({
87
+ kind: "inconsistent",
88
+ branchId: existing.id
89
+ });
90
+ return;
91
+ }
92
+ const existingNode = branchById.get(entry.id);
93
+ if (existingNode && existingNode !== branch) {
94
+ issues.push({
95
+ kind: "duplicate-id",
96
+ branchId: entry.id
97
+ });
98
+ return;
99
+ }
100
+ metadataByBranch.set(branch, entry);
101
+ branchById.set(entry.id, branch);
102
+ }
103
+ }
104
+ ts.forEachChild(node, (child) => visit(child, branches));
105
+ }
106
+ visit(fn, []);
107
+ return issues;
108
+ }
109
+ //#endregion
110
+ export { findBranchMetadataIssues };
@@ -1,5 +1,5 @@
1
1
  import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
- import { loadTypeScript } from "./graph-BEfFBC6v.js";
2
+ import { loadTypeScript } from "./graph-V2yqSs3X.js";
3
3
  //#region src/manifests/duplicate-ids.ts
4
4
  /** Where an explicit `{ id }` would sit for each operation. */
5
5
  const optionsArgument = {
@@ -183,10 +183,12 @@ function serializeSchema(schema, direction, label) {
183
183
  }
184
184
  }
185
185
  async function generateManifests(definition) {
186
- const { extractWorkflowGraph } = await import("./graph-BEfFBC6v.js");
187
- const { findDuplicateOperationIds } = await import("./duplicate-ids-CosMS6qZ.js");
188
- const { findNestedDurableOperations } = await import("./nested-operations-hWj5wt1m.js");
189
- const { findStepMetadataIssues } = await import("./step-metadata-Cly35okS.js");
186
+ const { extractWorkflowGraph } = await import("./graph-V2yqSs3X.js");
187
+ const { findBranchMetadataIssues } = await import("./branch-metadata-DeUhEFah.js");
188
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-BSJNfUhh.js");
189
+ const { findNestedDurableOperations } = await import("./nested-operations-DsecXS12.js");
190
+ const { findOperationDescriptionIssues } = await import("./operation-descriptions-C_f87Bmr.js");
191
+ const { findStepMetadataIssues } = await import("./step-metadata-D4OpY6r1.js");
190
192
  const collection = registerWorkflows(definition);
191
193
  const manifests = [];
192
194
  for (const workflow of collection.workflows) {
@@ -214,6 +216,19 @@ async function generateManifests(definition) {
214
216
  throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" ${step} is declared in a loop or callback and must include a static { meta: { group: { id: "...", label: "..." } } }`);
215
217
  }
216
218
  if (metadataIssue?.kind === "duplicate-group") throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" uses group id ${JSON.stringify(metadataIssue.groupId)} at more than one repeated step callsite; every group id must identify one callsite`);
219
+ const operationDescriptionIssue = (await findOperationDescriptionIssues(workflow.handler))[0];
220
+ if (operationDescriptionIssue) {
221
+ const { method } = operationDescriptionIssue;
222
+ const description = method === "approve" ? "{ description: \"...\" }" : "{ meta: { description: \"...\" } }";
223
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" ctx.${method}() must include a static ${description}`);
224
+ }
225
+ const branchMetadataIssue = (await findBranchMetadataIssues(workflow.handler))[0];
226
+ if (branchMetadataIssue?.kind === "path") {
227
+ const operation = branchMetadataIssue.method === "step" && branchMetadataIssue.stepId ? `ctx.step(${JSON.stringify(branchMetadataIssue.stepId)})` : `ctx.${branchMetadataIssue.method}()`;
228
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" ${operation} must include a static meta.branches path matching its enclosing if/else branches; each entry needs { id, description }`);
229
+ }
230
+ if (branchMetadataIssue?.kind === "inconsistent") throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" uses inconsistent metadata for branch ${JSON.stringify(branchMetadataIssue.branchId)}; every operation under one if statement must use the same branch id and description`);
231
+ if (branchMetadataIssue?.kind === "duplicate-id") throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" uses branch id ${JSON.stringify(branchMetadataIssue.branchId)} for more than one if statement; every branch id must identify one condition`);
217
232
  const metadata = {
218
233
  id: workflow.id,
219
234
  ...workflow.description === void 0 ? {} : { description: workflow.description },
@@ -5,7 +5,9 @@ const durableMethods = {
5
5
  approve: 0,
6
6
  waitForEvent: 0,
7
7
  sleep: 0,
8
- sleepUntil: 0
8
+ sleepUntil: 0,
9
+ now: 0,
10
+ uuid: 0
9
11
  };
10
12
  let loaded;
11
13
  async function loadTypeScript() {
@@ -34,12 +36,27 @@ async function extractWorkflowGraph(handler) {
34
36
  id,
35
37
  ...node
36
38
  });
37
- for (const parent of new Set(parents)) graph.edges.push({
38
- source: parent,
39
- target: id,
39
+ const seen = /* @__PURE__ */ new Set();
40
+ for (const parent of parents) {
41
+ const key = JSON.stringify(parent);
42
+ if (seen.has(key)) continue;
43
+ seen.add(key);
44
+ if (parent.kind === "order") graph.edges.push({
45
+ source: parent.source,
46
+ target: id,
47
+ kind: "order"
48
+ });
49
+ else graph.edges.push({
50
+ source: parent.source,
51
+ target: id,
52
+ kind: "branch",
53
+ outcome: parent.outcome
54
+ });
55
+ }
56
+ return [{
57
+ source: id,
40
58
  kind: "order"
41
- });
42
- return [id];
59
+ }];
43
60
  }
44
61
  function degrade(reason) {
45
62
  graph.complete = false;
@@ -132,6 +149,30 @@ async function extractWorkflowGraph(handler) {
132
149
  if ((ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0) === name) return property.initializer;
133
150
  }
134
151
  }
152
+ function branchMetadata(meta) {
153
+ const branches = option(meta, "branches");
154
+ if (!branches || !ts.isArrayLiteralExpression(branches)) return void 0;
155
+ const path = [];
156
+ for (const element of branches.elements) {
157
+ const entry = readableOptions(element);
158
+ const id = stringLiteral(option(entry, "id"));
159
+ const description = stringLiteral(option(entry, "description"));
160
+ if (id === void 0 || description === void 0) return void 0;
161
+ path.push({
162
+ id,
163
+ description
164
+ });
165
+ }
166
+ return path;
167
+ }
168
+ function operationMeta(call) {
169
+ const method = call.expression.name.text;
170
+ const optionsIndex = method === "step" ? 2 : method === "sleep" || method === "sleepUntil" || method === "waitForEvent" ? 1 : 0;
171
+ return readableOptions(option(readableOptions(call.arguments[optionsIndex]), "meta"));
172
+ }
173
+ function operationBranches(call) {
174
+ return branchMetadata(operationMeta(call));
175
+ }
135
176
  function stepMetadata(call) {
136
177
  const meta = readableOptions(option(readableOptions(call.arguments[2]), "meta"));
137
178
  const description = stringLiteral(option(meta, "description"));
@@ -140,7 +181,7 @@ async function extractWorkflowGraph(handler) {
140
181
  if (!groupOptions) return { description };
141
182
  const id = stringLiteral(option(groupOptions, "id"));
142
183
  const label = stringLiteral(option(groupOptions, "label"));
143
- return id === void 0 || label === void 0 ? void 0 : {
184
+ return id === void 0 || label === void 0 ? { description } : {
144
185
  description,
145
186
  group: {
146
187
  id,
@@ -148,6 +189,9 @@ async function extractWorkflowGraph(handler) {
148
189
  }
149
190
  };
150
191
  }
192
+ function operationDescription(options) {
193
+ return stringLiteral(option(readableOptions(option(options, "meta")), "description"));
194
+ }
151
195
  function durableStepId(argument, options, fallback) {
152
196
  if (argument && !options) return void 0;
153
197
  const given = option(options, "id");
@@ -176,15 +220,15 @@ async function extractWorkflowGraph(handler) {
176
220
  title
177
221
  }));
178
222
  if (stepId === void 0) return unknown("Dynamic approval IDs are not supported yet", parents);
179
- const given = option(options, "description");
180
- const description = stringLiteral(given);
181
- if (given && description === void 0) degrade("Dynamic approval descriptions are not recorded");
223
+ const description = stringLiteral(option(options, "description"));
224
+ if (description === void 0) return unknown("Approval descriptions must be static strings", parents);
182
225
  return addNode({
183
226
  kind: "approve",
184
227
  stepId,
228
+ description,
185
229
  config: {
186
230
  title,
187
- ...description === void 0 ? {} : { description }
231
+ description
188
232
  },
189
233
  label: title
190
234
  }, parents);
@@ -198,12 +242,15 @@ async function extractWorkflowGraph(handler) {
198
242
  name: event
199
243
  }));
200
244
  if (stepId === void 0) return unknown("Dynamic waitForEvent IDs are not supported yet", parents);
245
+ const description = operationDescription(options);
246
+ if (description === void 0) return unknown("Wait descriptions must be static strings", parents);
201
247
  const given = option(options, "deadline");
202
248
  const deadline = numberLiteral(given);
203
249
  if (given && deadline === void 0) degrade("Dynamic waitForEvent deadlines are not recorded");
204
250
  return addNode({
205
251
  kind: "wait-for-event",
206
252
  stepId,
253
+ description,
207
254
  config: {
208
255
  event,
209
256
  ...deadline === void 0 ? {} : { deadline }
@@ -220,26 +267,45 @@ async function extractWorkflowGraph(handler) {
220
267
  ms
221
268
  }));
222
269
  if (stepId === void 0) return unknown("Dynamic sleep IDs are not supported yet", parents);
270
+ const description = operationDescription(options);
271
+ if (description === void 0) return unknown("Sleep descriptions must be static strings", parents);
223
272
  return addNode({
224
273
  kind: "sleep",
225
274
  stepId,
275
+ description,
226
276
  config: { ms },
227
277
  label: `sleep ${ms}ms`
228
278
  }, parents);
229
279
  }
230
- const timestamp = numberLiteral(call.arguments[0]);
231
- if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
232
- const options = readableOptions(call.arguments[1]);
233
- const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
234
- kind: "sleepUntil",
235
- timestamp
236
- }));
237
- if (stepId === void 0) return unknown("Dynamic sleepUntil IDs are not supported yet", parents);
280
+ if (method === "sleepUntil") {
281
+ const timestamp = numberLiteral(call.arguments[0]);
282
+ if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
283
+ const options = readableOptions(call.arguments[1]);
284
+ const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
285
+ kind: "sleepUntil",
286
+ timestamp
287
+ }));
288
+ if (stepId === void 0) return unknown("Dynamic sleepUntil IDs are not supported yet", parents);
289
+ const description = operationDescription(options);
290
+ if (description === void 0) return unknown("Sleep descriptions must be static strings", parents);
291
+ return addNode({
292
+ kind: "sleep-until",
293
+ stepId,
294
+ description,
295
+ config: { timestamp },
296
+ label: `sleep until ${timestamp}`
297
+ }, parents);
298
+ }
299
+ const options = readableOptions(call.arguments[0]);
300
+ const stepId = durableStepId(call.arguments[0], options, defaultDurableId({ kind: method }));
301
+ if (stepId === void 0) return unknown(`Dynamic ${method} IDs are not supported yet`, parents);
302
+ const description = operationDescription(options);
303
+ if (description === void 0) return unknown(`${method} descriptions must be static strings`, parents);
238
304
  return addNode({
239
- kind: "sleep-until",
305
+ kind: method,
240
306
  stepId,
241
- config: { timestamp },
242
- label: `sleep until ${timestamp}`
307
+ description,
308
+ label: stepId
243
309
  }, parents);
244
310
  }
245
311
  function expression(node, parents, awaited = false) {
@@ -282,25 +348,110 @@ async function extractWorkflowGraph(handler) {
282
348
  if (ts.isIdentifier(node) && node.text === context) return unknown("Workflow context aliases are not followed", parents);
283
349
  return parents;
284
350
  }
285
- let tails = [];
286
- if (!ts.isBlock(fn.body)) {
287
- expression(fn.body, tails, true);
288
- return graph;
351
+ function branchInfo(statement, depth) {
352
+ let result;
353
+ const visit = (node) => {
354
+ if (result) return;
355
+ if (durableCall(node)) {
356
+ result = operationBranches(node)?.[depth];
357
+ return;
358
+ }
359
+ ts.forEachChild(node, visit);
360
+ };
361
+ visit(statement.thenStatement);
362
+ if (statement.elseStatement) visit(statement.elseStatement);
363
+ return result;
289
364
  }
290
- for (const statement of fn.body.statements) {
365
+ function statements(items, parents, branchDepth) {
366
+ let flow = {
367
+ tails: parents,
368
+ fallsThrough: true
369
+ };
370
+ for (const statement of items) {
371
+ if (!flow.fallsThrough) break;
372
+ flow = walkStatement(statement, flow.tails, branchDepth);
373
+ }
374
+ return flow;
375
+ }
376
+ function walkStatement(statement, parents, branchDepth) {
377
+ if (ts.isBlock(statement)) return statements(statement.statements, parents, branchDepth);
291
378
  if (ts.isReturnStatement(statement)) {
292
- if (statement.expression) expression(statement.expression, tails, true);
293
- break;
379
+ if (statement.expression) expression(statement.expression, parents, true);
380
+ return {
381
+ tails: [],
382
+ fallsThrough: false
383
+ };
384
+ }
385
+ if (ts.isThrowStatement(statement)) {
386
+ expression(statement.expression, parents);
387
+ return {
388
+ tails: [],
389
+ fallsThrough: false
390
+ };
294
391
  }
295
392
  if (ts.isVariableStatement(statement)) {
296
- if (statement.declarationList.declarations.some((item) => contains(item.name, (child) => ts.isIdentifier(child) && (child.text === "Promise" || child.text === context)))) {
297
- tails = unknown("Shadowed context or Promise bindings are not supported yet", tails);
298
- break;
299
- }
393
+ if (statement.declarationList.declarations.some((item) => contains(item.name, (child) => ts.isIdentifier(child) && (child.text === "Promise" || child.text === context)))) return {
394
+ tails: unknown("Shadowed context or Promise bindings are not supported yet", parents),
395
+ fallsThrough: false
396
+ };
397
+ let tails = parents;
300
398
  for (const item of statement.declarationList.declarations) if (item.initializer) tails = expression(item.initializer, tails);
301
- } else if (ts.isExpressionStatement(statement)) tails = expression(statement.expression, tails);
302
- else tails = unknown("Branches, loops, and other control flow are not supported yet", tails);
399
+ return {
400
+ tails,
401
+ fallsThrough: true
402
+ };
403
+ }
404
+ if (ts.isExpressionStatement(statement)) return {
405
+ tails: expression(statement.expression, parents),
406
+ fallsThrough: true
407
+ };
408
+ if (ts.isIfStatement(statement)) {
409
+ const conditionTails = expression(statement.expression, parents);
410
+ const metadata = branchInfo(statement, branchDepth);
411
+ const condition = statement.expression.getText(source);
412
+ const branchTails = metadata ? addNode({
413
+ kind: "branch",
414
+ branchId: metadata.id,
415
+ condition,
416
+ description: metadata.description,
417
+ label: metadata.description
418
+ }, conditionTails) : conditionTails;
419
+ const sourceId = metadata ? branchTails[0]?.source : void 0;
420
+ const thenParents = sourceId ? [{
421
+ source: sourceId,
422
+ kind: "branch",
423
+ outcome: true
424
+ }] : branchTails;
425
+ const elseParents = sourceId ? [{
426
+ source: sourceId,
427
+ kind: "branch",
428
+ outcome: false
429
+ }] : branchTails;
430
+ const thenFlow = walkStatement(statement.thenStatement, thenParents, branchDepth + 1);
431
+ const elseFlow = statement.elseStatement ? walkStatement(statement.elseStatement, elseParents, branchDepth + 1) : {
432
+ tails: elseParents,
433
+ fallsThrough: true
434
+ };
435
+ return {
436
+ tails: [...thenFlow.fallsThrough ? thenFlow.tails : [], ...elseFlow.fallsThrough ? elseFlow.tails : []],
437
+ fallsThrough: thenFlow.fallsThrough || elseFlow.fallsThrough
438
+ };
439
+ }
440
+ if (ts.isEmptyStatement(statement)) return {
441
+ tails: parents,
442
+ fallsThrough: true
443
+ };
444
+ return {
445
+ tails: unknown("Loops and other control flow are not supported yet", parents),
446
+ fallsThrough: true
447
+ };
448
+ }
449
+ const tails = [];
450
+ if (!ts.isBlock(fn.body)) {
451
+ expression(fn.body, tails, true);
452
+ return graph;
303
453
  }
454
+ statements(fn.body.statements, tails, 0);
304
455
  return graph;
305
456
  }
306
457
  //#endregion
package/dist/index.d.ts CHANGED
@@ -56,8 +56,15 @@ interface WorkflowStepGroup {
56
56
  id: string;
57
57
  label: string;
58
58
  }
59
- type WorkflowStepMetadata = Record<string, unknown> & {
59
+ interface WorkflowBranchMetadata {
60
+ id: string;
61
+ description: string;
62
+ }
63
+ type WorkflowOperationMetadata = Record<string, unknown> & {
60
64
  description: string;
65
+ branches?: WorkflowBranchMetadata[];
66
+ };
67
+ type WorkflowStepMetadata = WorkflowOperationMetadata & {
61
68
  group?: WorkflowStepGroup;
62
69
  };
63
70
  //#endregion
@@ -78,13 +85,15 @@ type WorkflowGraphNodeDetails = {
78
85
  } | {
79
86
  kind: "approve";
80
87
  stepId: string;
88
+ description: string;
81
89
  config: {
82
90
  title: string;
83
- description?: string;
91
+ description: string;
84
92
  };
85
93
  } | {
86
94
  kind: "wait-for-event";
87
95
  stepId: string;
96
+ description: string;
88
97
  config: {
89
98
  event: string;
90
99
  deadline?: number;
@@ -92,15 +101,30 @@ type WorkflowGraphNodeDetails = {
92
101
  } | {
93
102
  kind: "sleep";
94
103
  stepId: string;
104
+ description: string;
95
105
  config: {
96
106
  ms: number;
97
107
  };
98
108
  } | {
99
109
  kind: "sleep-until";
100
110
  stepId: string;
111
+ description: string;
101
112
  config: {
102
113
  timestamp: number;
103
114
  };
115
+ } | {
116
+ kind: "now";
117
+ stepId: string;
118
+ description: string;
119
+ } | {
120
+ kind: "uuid";
121
+ stepId: string;
122
+ description: string;
123
+ } | {
124
+ kind: "branch";
125
+ branchId: string;
126
+ condition: string;
127
+ description: string;
104
128
  } | {
105
129
  kind: "unknown";
106
130
  };
@@ -108,16 +132,22 @@ type WorkflowGraphNode = {
108
132
  id: string;
109
133
  label: string;
110
134
  } & WorkflowGraphNodeDetails;
135
+ type WorkflowGraphEdge = {
136
+ source: string;
137
+ target: string;
138
+ kind: "order";
139
+ } | {
140
+ source: string;
141
+ target: string;
142
+ kind: "branch";
143
+ outcome: boolean;
144
+ };
111
145
  interface WorkflowGraph {
112
146
  source: "inferred";
113
147
  scope: "handler";
114
148
  complete: boolean;
115
149
  nodes: WorkflowGraphNode[];
116
- edges: {
117
- source: string;
118
- target: string;
119
- kind: "order";
120
- }[];
150
+ edges: WorkflowGraphEdge[];
121
151
  diagnostics: string[];
122
152
  }
123
153
  //#endregion
@@ -288,4 +318,4 @@ declare function createStepsHandler(collection: WorkflowCollection, options?: St
288
318
  */
289
319
  declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
290
320
  //#endregion
291
- 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 WorkflowStepGroup, type WorkflowStepMetadata, type WorkflowsDefinition, createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
321
+ 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 WorkflowBranchMetadata, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphEdge, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOperationMetadata, type WorkflowOutput, type WorkflowState, type WorkflowStepGroup, type WorkflowStepMetadata, 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-DTzFAh96.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-B4itoNSW.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
@@ -288,24 +288,27 @@ async function replay(options) {
288
288
  sleep: (ms, opts) => durable("sleep", opts?.id ?? defaultDurableId({
289
289
  kind: "sleep",
290
290
  ms
291
- }), void 0, { ms }, opts?.id === void 0),
291
+ }), void 0, { ms }, opts?.id === void 0, opts?.meta),
292
292
  sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? defaultDurableId({
293
293
  kind: "sleepUntil",
294
294
  timestamp
295
- }), void 0, { timestamp }, opts?.id === void 0),
295
+ }), void 0, { timestamp }, opts?.id === void 0, opts?.meta),
296
296
  waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? defaultDurableId({
297
297
  kind: "waitForEvent",
298
298
  name
299
- }), void 0, { name }, opts?.id === void 0),
299
+ }), void 0, { name }, opts?.id === void 0, opts?.meta),
300
300
  approve: (opts) => durable("approve", opts.id ?? defaultDurableId({
301
301
  kind: "approve",
302
302
  title: opts.title
303
303
  }), void 0, {
304
304
  title: opts.title,
305
305
  ...opts.description === void 0 ? {} : { description: opts.description }
306
- }, opts.id === void 0),
307
- now: (opts) => durable("now", opts?.id ?? defaultDurableId({ kind: "now" }), async () => Date.now(), void 0, opts?.id === void 0),
308
- uuid: (opts) => durable("uuid", opts?.id ?? defaultDurableId({ kind: "uuid" }), async () => crypto.randomUUID(), void 0, opts?.id === void 0),
306
+ }, opts.id === void 0, {
307
+ ...opts.meta,
308
+ ...opts.description === void 0 ? {} : { description: opts.description }
309
+ }),
310
+ now: (opts) => durable("now", opts?.id ?? defaultDurableId({ kind: "now" }), async () => Date.now(), void 0, opts?.id === void 0, opts?.meta),
311
+ uuid: (opts) => durable("uuid", opts?.id ?? defaultDurableId({ kind: "uuid" }), async () => crypto.randomUUID(), void 0, opts?.id === void 0, opts?.meta),
309
312
  emit: (name, value) => {
310
313
  emitted.push({
311
314
  name,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript } from "./graph-BEfFBC6v.js";
1
+ import { loadTypeScript } from "./graph-V2yqSs3X.js";
2
2
  //#region src/manifests/nested-operations.ts
3
3
  const durableMethods = [
4
4
  "step",
@@ -0,0 +1,45 @@
1
+ import { loadTypeScript } from "./graph-V2yqSs3X.js";
2
+ //#region src/manifests/operation-descriptions.ts
3
+ const optionsArgument = {
4
+ approve: 0,
5
+ sleep: 1,
6
+ sleepUntil: 1,
7
+ waitForEvent: 1,
8
+ now: 0,
9
+ uuid: 0
10
+ };
11
+ async function findOperationDescriptionIssues(handler) {
12
+ const api = await loadTypeScript();
13
+ if (!api) return [];
14
+ const ts = api;
15
+ const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
16
+ const declaration = source.statements[0];
17
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
18
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) return [];
19
+ const parameter = fn.parameters[0]?.name;
20
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
21
+ const context = parameter.text;
22
+ function literalString(node) {
23
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
24
+ }
25
+ function property(node, name) {
26
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
27
+ for (const entry of node.properties) {
28
+ if (!ts.isPropertyAssignment(entry)) continue;
29
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
30
+ }
31
+ }
32
+ const issues = [];
33
+ const visit = (node) => {
34
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
35
+ const method = node.expression.name.text;
36
+ const options = node.arguments[optionsArgument[method]];
37
+ if ((method === "approve" ? literalString(property(options, "description")) : literalString(property(property(options, "meta"), "description"))) === void 0) issues.push({ method });
38
+ }
39
+ ts.forEachChild(node, visit);
40
+ };
41
+ visit(fn);
42
+ return issues;
43
+ }
44
+ //#endregion
45
+ export { findOperationDescriptionIssues };
@@ -1,4 +1,4 @@
1
- import { loadTypeScript } from "./graph-BEfFBC6v.js";
1
+ import { loadTypeScript } from "./graph-V2yqSs3X.js";
2
2
  //#region src/manifests/step-metadata.ts
3
3
  async function findStepMetadataIssues(handler) {
4
4
  const api = await loadTypeScript();
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as generateManifests } from "./generate-DTzFAh96.js";
1
+ import { t as generateManifests } from "./generate-B4itoNSW.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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.16",
3
+ "version": "0.0.0-dev.18",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",