@lovable.dev/workflows-sdk 0.0.0-dev.31 → 0.0.0-dev.33

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
@@ -75,7 +75,11 @@ await ctx.step("load-customer", () => loadCustomer(ctx.input.customerId), {
75
75
  });
76
76
  ```
77
77
 
78
- Step IDs must be unique within a workflow. Keep side effects inside step bodies;
78
+ Every durable operation takes an explicit `id` — `ctx.approve({ id, title })`,
79
+ `ctx.waitForEvent(name, { id })`, `ctx.sleep(ms, { id })`, `ctx.now({ id })` —
80
+ and none is derived from a title, name or duration. IDs share one namespace per
81
+ workflow, so the build fails on a missing or repeated one, including two calls
82
+ on mutually exclusive branches. Keep side effects inside step bodies;
79
83
  handler code outside a step may run more than once. A step body is one atomic
80
84
  execution unit and cannot contain another durable operation.
81
85
 
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-CBdqyIz5.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-ZthZ8l6y.js";
2
2
  //#region src/manifests/branch-metadata.ts
3
3
  const optionsArgument = {
4
4
  step: 2,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-CBdqyIz5.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-ZthZ8l6y.js";
2
2
  //#region src/manifests/context-escapes.ts
3
3
  const durableMethods = /* @__PURE__ */ new Set([
4
4
  "step",
@@ -1,5 +1,4 @@
1
- import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-CBdqyIz5.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-ZthZ8l6y.js";
3
2
  //#region src/manifests/duplicate-ids.ts
4
3
  /** Where an explicit `{ id }` would sit for each operation. */
5
4
  const optionsArgument = {
@@ -11,27 +10,22 @@ const optionsArgument = {
11
10
  waitForEvent: 1,
12
11
  step: -1
13
12
  };
14
- /** Operation ids provably reached more than once; dynamic ids are left to runtime. */
13
+ /** Ids provably reached more than once, or why the handler could not be checked. */
15
14
  async function findDuplicateOperationIds(handler) {
16
15
  const api = await loadTypeScript();
17
- if (!api) return [];
16
+ if (!api) return { unchecked: "typescript" };
18
17
  const ts = api;
19
18
  const handlerSource = workflowHandlerSource(handler);
20
- if (!handlerSource) return [];
19
+ if (!handlerSource) return { unchecked: "handler" };
21
20
  const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
22
21
  const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
23
- if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
22
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return { unchecked: "handler" };
24
23
  const parameter = fn.parameters[0]?.name;
25
24
  if (!parameter || !ts.isIdentifier(parameter)) return [];
26
25
  const context = parameter.text;
27
26
  function literalString(node) {
28
27
  return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
29
28
  }
30
- function literalNumber(node) {
31
- if (!node || !ts.isNumericLiteral(node)) return void 0;
32
- const value = Number(node.text);
33
- return Number.isFinite(value) ? value : void 0;
34
- }
35
29
  function property(options, name) {
36
30
  if (!options || !ts.isObjectLiteralExpression(options)) return void 0;
37
31
  for (const entry of options.properties) {
@@ -48,74 +42,20 @@ async function findDuplicateOperationIds(handler) {
48
42
  if (given === void 0) return false;
49
43
  return literalString(given);
50
44
  }
51
- function defaultSource(call, method) {
52
- switch (method) {
53
- case "now":
54
- case "uuid": return { kind: method };
55
- case "sleep": {
56
- const ms = literalNumber(call.arguments[0]);
57
- return ms === void 0 ? void 0 : {
58
- kind: "sleep",
59
- ms
60
- };
61
- }
62
- case "sleepUntil": {
63
- const timestamp = literalNumber(call.arguments[0]);
64
- return timestamp === void 0 ? void 0 : {
65
- kind: "sleepUntil",
66
- timestamp
67
- };
68
- }
69
- case "waitForEvent": {
70
- const name = literalString(call.arguments[0]);
71
- return name === void 0 ? void 0 : {
72
- kind: "waitForEvent",
73
- name
74
- };
75
- }
76
- case "approve": {
77
- const title = literalString(property(call.arguments[0], "title"));
78
- return title === void 0 ? void 0 : {
79
- kind: "approve",
80
- title
81
- };
82
- }
83
- case "step": return;
84
- }
85
- }
86
45
  function repeatedLoopRegion(parent, child) {
87
46
  if (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) return parent.statement === child;
88
47
  if (ts.isForStatement(parent)) return parent.statement === child || parent.condition === child || parent.incrementor === child;
89
48
  return ts.isWhileStatement(parent) || ts.isDoStatement(parent);
90
49
  }
91
- function placement(call) {
92
- const branches = /* @__PURE__ */ new Map();
93
- let repeatable = false;
50
+ /** Whether anything between the call and the handler can run it more than once. */
51
+ function repeatable(call) {
94
52
  let child = call;
95
53
  let parent = call.parent;
96
54
  while (parent && child !== fn) {
97
- if (ts.isIfStatement(parent)) {
98
- if (parent.thenStatement === child) branches.set(String(parent.pos), "then");
99
- else if (parent.elseStatement === child) branches.set(String(parent.pos), "else");
100
- } else if (ts.isConditionalExpression(parent)) {
101
- if (parent.whenTrue === child) branches.set(String(parent.pos), "true");
102
- else if (parent.whenFalse === child) branches.set(String(parent.pos), "false");
103
- } else if (ts.isCaseClause(parent) || ts.isDefaultClause(parent)) branches.set(String(parent.parent.pos), String(parent.parent.clauses.indexOf(parent)));
104
- else if (parent !== fn && (repeatedLoopRegion(parent, child) || ts.isFunctionLike(parent))) repeatable = true;
55
+ if (parent !== fn && (repeatedLoopRegion(parent, child) || ts.isFunctionLike(parent))) return true;
105
56
  child = parent;
106
57
  parent = parent.parent;
107
58
  }
108
- return {
109
- branches,
110
- repeatable
111
- };
112
- }
113
- /** True when a shared conditional puts the two calls on different sides. */
114
- function exclusive(a, b) {
115
- for (const [node, side] of a.branches) {
116
- const other = b.branches.get(node);
117
- if (other !== void 0 && other !== side) return true;
118
- }
119
59
  return false;
120
60
  }
121
61
  const calls = [];
@@ -124,42 +64,34 @@ async function findDuplicateOperationIds(handler) {
124
64
  const method = node.expression.name.text;
125
65
  const index = optionsArgument[method];
126
66
  const given = method === "step" ? literalString(node.arguments[0]) : explicitId(node.arguments[index]);
127
- if (given !== void 0) {
128
- const id = given === false ? void 0 : given;
129
- const derived = id === void 0 ? defaultSource(node, method) : void 0;
130
- const resolved = id ?? (derived && defaultDurableId(derived));
131
- if (resolved) calls.push({
132
- id: resolved,
133
- method,
134
- defaulted: id === void 0,
135
- ...placement(node)
136
- });
137
- }
67
+ if (given !== void 0) calls.push({
68
+ id: given === false ? "" : given,
69
+ method,
70
+ repeatable: repeatable(node)
71
+ });
138
72
  }
139
73
  ts.forEachChild(node, visit);
140
74
  };
141
75
  visit(fn);
142
76
  const found = /* @__PURE__ */ new Map();
143
77
  for (const call of calls) {
144
- if (call.method === "step") {
145
- const reason = call.repeatable ? "loop" : calls.some((other) => other !== call && other.id === call.id) ? "repeated" : void 0;
146
- if (reason) found.set(`step:${call.id}`, {
147
- id: call.id,
78
+ if (call.id === "") {
79
+ found.set(`${call.method}:missing:${found.size}`, {
80
+ id: "",
148
81
  method: call.method,
149
- reason
82
+ reason: "missing"
150
83
  });
151
84
  continue;
152
85
  }
153
- if (!call.defaulted) continue;
154
86
  if (call.repeatable) {
155
- found.set(`${call.method}:${call.id}`, {
87
+ found.set(call.id, {
156
88
  id: call.id,
157
89
  method: call.method,
158
90
  reason: "loop"
159
91
  });
160
92
  continue;
161
93
  }
162
- if (calls.some((other) => other !== call && other.id === call.id && !exclusive(call, other))) found.set(`${call.method}:${call.id}`, {
94
+ if (calls.some((other) => other !== call && other.id === call.id)) found.set(call.id, {
163
95
  id: call.id,
164
96
  method: call.method,
165
97
  reason: "repeated"
@@ -0,0 +1,17 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __defProp = Object.defineProperty;
3
+ var __exportAll = (all, no_symbols) => {
4
+ let target = {};
5
+ for (var name in all) __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true
8
+ });
9
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
10
+ return target;
11
+ };
12
+ //#endregion
13
+ //#region src/core/durable-ids.ts
14
+ var durable_ids_exports = /* @__PURE__ */ __exportAll({ DURABLE_ID_REQUIRED: () => DURABLE_ID_REQUIRED });
15
+ const DURABLE_ID_REQUIRED = "every durable operation needs an explicit, workflow-unique id: ctx.approve({ id, title }), ctx.waitForEvent(name, { id }), ctx.sleep(ms, { id }), ctx.now({ id }), ctx.uuid({ id })";
16
+ //#endregion
17
+ export { durable_ids_exports as n, DURABLE_ID_REQUIRED as t };
@@ -6626,7 +6626,7 @@ function listValueFromJson(listValue, json) {
6626
6626
  }
6627
6627
  //#endregion
6628
6628
  //#region package.json
6629
- var version = "0.0.0-dev.31";
6629
+ var version = "0.0.0-dev.33";
6630
6630
  //#endregion
6631
6631
  //#region src/proto/lovable/appworkflows/v1/workflow_manifest_pb.ts
6632
6632
  /**
@@ -6819,13 +6819,14 @@ function serializeSchema(schema, direction, label) {
6819
6819
  }
6820
6820
  }
6821
6821
  async function generateManifests(definition, options = {}) {
6822
- const { extractWorkflowGraph } = await import("./graph-CBdqyIz5.js");
6823
- const { findBranchMetadataIssues } = await import("./branch-metadata-CkZQpEi7.js");
6824
- const { findWorkflowContextEscapes } = await import("./context-escapes-Di8ThJie.js");
6825
- const { findDuplicateOperationIds } = await import("./duplicate-ids-CRaMUWON.js");
6826
- const { findNestedDurableOperations } = await import("./nested-operations-BBGsI1HN.js");
6827
- const { findOperationDescriptionIssues } = await import("./operation-descriptions-CZAlt0vd.js");
6828
- const { findStepMetadataIssues } = await import("./step-metadata-Xksj4MjW.js");
6822
+ const { extractWorkflowGraph } = await import("./graph-ZthZ8l6y.js");
6823
+ const { findBranchMetadataIssues } = await import("./branch-metadata-6pwT4Ei_.js");
6824
+ const { findWorkflowContextEscapes } = await import("./context-escapes-B66nJs0o.js");
6825
+ const { findDuplicateOperationIds } = await import("./duplicate-ids-CTd1_la_.js");
6826
+ const { DURABLE_ID_REQUIRED } = await import("./durable-ids-Cx341nJQ.js").then((n) => n.n);
6827
+ const { findNestedDurableOperations } = await import("./nested-operations-CuDUxJl4.js");
6828
+ const { findOperationDescriptionIssues } = await import("./operation-descriptions-F6LKn5jJ.js");
6829
+ const { findStepMetadataIssues } = await import("./step-metadata-B3mdzOIH.js");
6829
6830
  const collection = registerWorkflows(definition);
6830
6831
  const manifests = [];
6831
6832
  for (const workflow of collection.workflows.flatMap(workflowVersions)) {
@@ -6838,13 +6839,15 @@ async function generateManifests(definition, options = {}) {
6838
6839
  const parent = nested.parentStepId ? `ctx.step(${JSON.stringify(nested.parentStepId)})` : "ctx.step()";
6839
6840
  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`);
6840
6841
  }
6841
- for (const duplicate of await findDuplicateOperationIds(workflow.handler)) {
6842
- if (duplicate.method === "step") {
6843
- const use = duplicate.reason === "loop" ? "inside a loop or callback" : "more than once";
6844
- 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`);
6845
- }
6846
- const where = duplicate.reason === "loop" ? "inside a loop" : "more than once";
6847
- 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`);
6842
+ const duplicates = await findDuplicateOperationIds(workflow.handler);
6843
+ if (!Array.isArray(duplicates)) {
6844
+ const remedy = duplicates.unchecked === "typescript" ? "install the \"typescript\" peer dependency" : "define the workflow handler as a function in the workflow file";
6845
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" could not be checked for durable operation ids; ${remedy}, because ${DURABLE_ID_REQUIRED}`);
6846
+ }
6847
+ for (const duplicate of duplicates) {
6848
+ if (duplicate.reason === "missing") throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" calls ctx.${duplicate.method}() without an id; ${DURABLE_ID_REQUIRED}`);
6849
+ const where = duplicate.reason === "loop" ? "inside a loop or callback" : "more than once";
6850
+ throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" uses id ${JSON.stringify(duplicate.id)} ${where}; every durable operation id must be unique within a workflow`);
6848
6851
  }
6849
6852
  const metadataIssue = (await findStepMetadataIssues(workflow.handler))[0];
6850
6853
  if (metadataIssue?.kind === "description") {
@@ -1,5 +1,4 @@
1
- import { _ as WorkflowManifestUnknownNodeV1Schema, a as WorkflowManifestGraphEdgeV1Schema, b as create, c as WorkflowManifestLoopNodeV1Schema, d as WorkflowManifestParallelNodeV1Schema, f as WorkflowManifestRepeatedStepV1Schema, g as WorkflowManifestStepNodeV1Schema, h as WorkflowManifestStepExecutionPolicyV1Schema, i as WorkflowManifestBranchNodeV1Schema, l as WorkflowManifestNowNodeV1Schema, m as WorkflowManifestSleepUntilNodeV1Schema, n as WorkflowManifestApproveNodeV1Schema, o as WorkflowManifestGraphNodeV1Schema, p as WorkflowManifestSleepNodeV1Schema, r as WorkflowManifestBranchEdgeV1Schema, s as WorkflowManifestGraphV1Schema, u as WorkflowManifestOrderEdgeV1Schema, v as WorkflowManifestUuidNodeV1Schema, y as WorkflowManifestWaitForEventNodeV1Schema } from "./generate-Dk1_3N-g.js";
2
- import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
1
+ import { _ as WorkflowManifestUnknownNodeV1Schema, a as WorkflowManifestGraphEdgeV1Schema, b as create, c as WorkflowManifestLoopNodeV1Schema, d as WorkflowManifestParallelNodeV1Schema, f as WorkflowManifestRepeatedStepV1Schema, g as WorkflowManifestStepNodeV1Schema, h as WorkflowManifestStepExecutionPolicyV1Schema, i as WorkflowManifestBranchNodeV1Schema, l as WorkflowManifestNowNodeV1Schema, m as WorkflowManifestSleepUntilNodeV1Schema, n as WorkflowManifestApproveNodeV1Schema, o as WorkflowManifestGraphNodeV1Schema, p as WorkflowManifestSleepNodeV1Schema, r as WorkflowManifestBranchEdgeV1Schema, s as WorkflowManifestGraphV1Schema, u as WorkflowManifestOrderEdgeV1Schema, v as WorkflowManifestUuidNodeV1Schema, y as WorkflowManifestWaitForEventNodeV1Schema } from "./generate-CDOP4pMi.js";
3
2
  //#region src/manifests/handler-source.ts
4
3
  const nativeFunctionSource = /\{\s*\[native code\]\s*\}\s*$/;
5
4
  function workflowHandlerSource(handler) {
@@ -277,10 +276,11 @@ async function extractWorkflowGraph(workflow) {
277
276
  function operationDescription(options) {
278
277
  return stringLiteral(option(readableOptions(option(options, "meta")), "description"));
279
278
  }
280
- function durableStepId(argument, options, fallback) {
279
+ /** Undefined when the call names no static id, which the graph cannot invent. */
280
+ function durableStepId(argument, options) {
281
281
  if (argument && !options) return void 0;
282
282
  const given = option(options, "id");
283
- return given ? stringLiteral(given) : fallback;
283
+ return given ? stringLiteral(given) : void 0;
284
284
  }
285
285
  function durableNode(call, parents) {
286
286
  const method = call.expression.name.text;
@@ -303,11 +303,8 @@ async function extractWorkflowGraph(workflow) {
303
303
  const options = readableOptions(call.arguments[0]);
304
304
  const title = stringLiteral(option(options, "title"));
305
305
  if (title === void 0) return unknown("Dynamic approval titles are not supported yet", parents);
306
- const stepId = durableStepId(call.arguments[0], options, defaultDurableId({
307
- kind: "approve",
308
- title
309
- }));
310
- if (stepId === void 0) return unknown("Dynamic approval IDs are not supported yet", parents);
306
+ const stepId = durableStepId(call.arguments[0], options);
307
+ if (stepId === void 0) return unknown("ctx.approve needs a static { id }", parents);
311
308
  const description = stringLiteral(option(options, "description"));
312
309
  if (description === void 0) return unknown("Approval descriptions must be static strings", parents);
313
310
  return addNode(title, {
@@ -323,10 +320,7 @@ async function extractWorkflowGraph(workflow) {
323
320
  const event = stringLiteral(call.arguments[0]);
324
321
  if (event === void 0) return unknown("Dynamic event names are not supported yet", parents);
325
322
  const options = readableOptions(call.arguments[1]);
326
- const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
327
- kind: "waitForEvent",
328
- name: event
329
- }));
323
+ const stepId = durableStepId(call.arguments[1], options);
330
324
  if (stepId === void 0) return unknown("Dynamic waitForEvent IDs are not supported yet", parents);
331
325
  const description = operationDescription(options);
332
326
  if (description === void 0) return unknown("Wait descriptions must be static strings", parents);
@@ -347,10 +341,7 @@ async function extractWorkflowGraph(workflow) {
347
341
  const ms = numberLiteral(call.arguments[0]);
348
342
  if (ms === void 0) return unknown("Dynamic sleep durations are not supported yet", parents);
349
343
  const options = readableOptions(call.arguments[1]);
350
- const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
351
- kind: "sleep",
352
- ms
353
- }));
344
+ const stepId = durableStepId(call.arguments[1], options);
354
345
  if (stepId === void 0) return unknown("Dynamic sleep IDs are not supported yet", parents);
355
346
  const description = operationDescription(options);
356
347
  if (description === void 0) return unknown("Sleep descriptions must be static strings", parents);
@@ -367,10 +358,7 @@ async function extractWorkflowGraph(workflow) {
367
358
  const timestamp = numberLiteral(call.arguments[0]);
368
359
  if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
369
360
  const options = readableOptions(call.arguments[1]);
370
- const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
371
- kind: "sleepUntil",
372
- timestamp
373
- }));
361
+ const stepId = durableStepId(call.arguments[1], options);
374
362
  if (stepId === void 0) return unknown("Dynamic sleepUntil IDs are not supported yet", parents);
375
363
  const description = operationDescription(options);
376
364
  if (description === void 0) return unknown("Sleep descriptions must be static strings", parents);
@@ -384,7 +372,7 @@ async function extractWorkflowGraph(workflow) {
384
372
  }, parents);
385
373
  }
386
374
  const options = readableOptions(call.arguments[0]);
387
- const stepId = durableStepId(call.arguments[0], options, defaultDurableId({ kind: method }));
375
+ const stepId = durableStepId(call.arguments[0], options);
388
376
  if (stepId === void 0) return unknown(`Dynamic ${method} IDs are not supported yet`, parents);
389
377
  const description = operationDescription(options);
390
378
  if (description === void 0) return unknown(`${method} descriptions must be static strings`, parents);
package/dist/index.d.ts CHANGED
@@ -734,8 +734,6 @@ interface MemoEntry {
734
734
  * branches can order differently on a later pass, so it is not the key. */
735
735
  seq: number;
736
736
  stepId: string;
737
- /** Which call of this `stepId` in the run, from 0. */
738
- occurrence: number;
739
737
  /** Key of the step whose body recorded this, if any; a memoized parent hides it. */
740
738
  parent?: string;
741
739
  kind: StepKind;
@@ -747,7 +745,6 @@ interface MemoEntry {
747
745
  interface StepIntentBase {
748
746
  seq: number;
749
747
  stepId: string;
750
- occurrence: number;
751
748
  /** Kind-specific detail: sleep `ms`, `waitForEvent` name, approval title. */
752
749
  config?: Record<string, unknown>;
753
750
  meta?: WorkflowMetadata;
@@ -761,7 +758,6 @@ type StepIntent = StepIntentBase & ({
761
758
  interface StepResult<K extends StepKind = StepKind> {
762
759
  seq: number;
763
760
  stepId: string;
764
- occurrence: number;
765
761
  kind: K;
766
762
  meta?: WorkflowMetadata;
767
763
  status: "completed" | "failed";
@@ -788,7 +784,6 @@ interface ReplayOutcome {
788
784
  interface StepReference {
789
785
  kind: "step";
790
786
  stepId: string;
791
- occurrence: number;
792
787
  }
793
788
  //#endregion
794
789
  //#region src/stacks/tanstack/project-auth.d.ts
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { C as registerWorkflows, D as hourly, E as daily, O as weekly, S as createWorkflow, T as defineSchedule, t as generateManifests, w as workflowVersions, x as createMiddleware } from "./generate-Dk1_3N-g.js";
2
- import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
1
+ import { t as DURABLE_ID_REQUIRED } from "./durable-ids-Cx341nJQ.js";
2
+ import { C as registerWorkflows, D as hourly, E as daily, O as weekly, S as createWorkflow, T as defineSchedule, t as generateManifests, w as workflowVersions, x as createMiddleware } from "./generate-CDOP4pMi.js";
3
3
  import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
4
4
  //#region src/stacks/tanstack/sse.ts
5
5
  const HEADERS = {
@@ -127,9 +127,6 @@ async function hashInput(input) {
127
127
  //#region src/runtime/replay.ts
128
128
  /** How long a pass waits for handler work that is not a durable operation. */
129
129
  const DEFAULT_SETTLE_MS = 5e3;
130
- function memoKey(stepId, occurrence) {
131
- return `${stepId}#${occurrence}`;
132
- }
133
130
  const EXECUTABLE = /* @__PURE__ */ new Set([
134
131
  "step",
135
132
  "now",
@@ -169,13 +166,13 @@ async function throughMiddleware(middlewares, ctx, handler) {
169
166
  }
170
167
  async function replay(options) {
171
168
  const { workflow, input, runId } = options;
172
- const byKey = new Map(options.memo.map((entry) => [memoKey(entry.stepId, entry.occurrence ?? 0), entry]));
169
+ const byKey = new Map(options.memo.map((entry) => [entry.stepId, entry]));
173
170
  const allow = options.shouldExecute ?? (() => true);
174
171
  const never = new Promise(() => {});
175
172
  const pending = [];
176
173
  const settled = /* @__PURE__ */ new Map();
177
174
  const pass = { stepsSettled: 0 };
178
- const occurrences = /* @__PURE__ */ new Map();
175
+ const reached = /* @__PURE__ */ new Set();
179
176
  const consumed = /* @__PURE__ */ new Set();
180
177
  let lastProgress = Date.now();
181
178
  let currentParent;
@@ -185,13 +182,12 @@ async function replay(options) {
185
182
  let seq = 0;
186
183
  let nonDeterminism;
187
184
  function record(entry) {
188
- settled.set(memoKey(entry.stepId, entry.occurrence), entry);
185
+ settled.set(entry.stepId, entry);
189
186
  lastProgress = Date.now();
190
187
  if (entry.kind === "step") pass.stepsSettled += 1;
191
188
  const result = {
192
189
  seq: entry.seq,
193
190
  stepId: entry.stepId,
194
- occurrence: entry.occurrence,
195
191
  kind: entry.kind,
196
192
  ...entry.meta ? { meta: entry.meta } : {},
197
193
  status: entry.status,
@@ -201,24 +197,22 @@ async function replay(options) {
201
197
  results.push(result);
202
198
  options.onStepSettle?.(result);
203
199
  }
204
- function durable(kind, stepId, run, config, defaulted = false, meta) {
205
- const index = seq++;
206
- const occurrence = occurrences.get(stepId) ?? 0;
207
- occurrences.set(stepId, occurrence + 1);
208
- if (kind === "step" && occurrence > 0) {
209
- nonDeterminism = `ctx.step() was reached more than once with id "${stepId}"; every step id must be unique within a workflow`;
200
+ function durable(kind, stepId, run, config, meta) {
201
+ if (!stepId) {
202
+ nonDeterminism = `ctx.${kind}() was called without an id; ${DURABLE_ID_REQUIRED}`;
210
203
  return never;
211
204
  }
212
- if (defaulted && occurrence > 0) {
213
- nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
205
+ const index = seq++;
206
+ if (reached.has(stepId)) {
207
+ nonDeterminism = `id "${stepId}" was reached more than once; every durable operation id must be unique within a workflow`;
214
208
  return never;
215
209
  }
216
- const key = memoKey(stepId, occurrence);
217
- consumed.add(key);
218
- const answered = byKey.get(key) ?? settled.get(key);
210
+ reached.add(stepId);
211
+ consumed.add(stepId);
212
+ const answered = byKey.get(stepId) ?? settled.get(stepId);
219
213
  if (answered) {
220
214
  if (answered.kind !== kind) {
221
- nonDeterminism = `memo has ${answered.kind} "${stepId}" (#${occurrence}), replay produced ${kind}`;
215
+ nonDeterminism = `memo has ${answered.kind} "${stepId}", replay produced ${kind}`;
222
216
  return never;
223
217
  }
224
218
  const recordedGroupId = groupId(answered.meta);
@@ -233,7 +227,6 @@ async function replay(options) {
233
227
  const intent = {
234
228
  seq: index,
235
229
  stepId,
236
- occurrence,
237
230
  kind,
238
231
  ...config ? { config } : {},
239
232
  ...meta ? { meta } : {}
@@ -244,7 +237,7 @@ async function replay(options) {
244
237
  }
245
238
  options.onStepStart?.(intent);
246
239
  const enclosing = currentParent;
247
- currentParent = key;
240
+ currentParent = stepId;
248
241
  let body;
249
242
  try {
250
243
  body = run();
@@ -255,7 +248,6 @@ async function replay(options) {
255
248
  record({
256
249
  seq: index,
257
250
  stepId,
258
- occurrence,
259
251
  kind,
260
252
  status: "completed",
261
253
  result,
@@ -267,7 +259,6 @@ async function replay(options) {
267
259
  record({
268
260
  seq: index,
269
261
  stepId,
270
- occurrence,
271
262
  kind,
272
263
  status: "failed",
273
264
  error: describe(error),
@@ -293,31 +284,19 @@ async function replay(options) {
293
284
  attempt: 1,
294
285
  runtime,
295
286
  signal: controller.signal
296
- }), void 0, false, stepOptions?.meta),
297
- sleep: (ms, opts) => durable("sleep", opts?.id ?? defaultDurableId({
298
- kind: "sleep",
299
- ms
300
- }), void 0, { ms }, opts?.id === void 0, opts?.meta),
301
- sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? defaultDurableId({
302
- kind: "sleepUntil",
303
- timestamp
304
- }), void 0, { timestamp }, opts?.id === void 0, opts?.meta),
305
- waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? defaultDurableId({
306
- kind: "waitForEvent",
307
- name
308
- }), void 0, { name }, opts?.id === void 0, opts?.meta),
309
- approve: (opts) => durable("approve", opts.id ?? defaultDurableId({
310
- kind: "approve",
311
- title: opts.title
312
- }), void 0, {
287
+ }), void 0, stepOptions?.meta),
288
+ sleep: (ms, opts) => durable("sleep", opts?.id, void 0, { ms }, opts?.meta),
289
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id, void 0, { timestamp }, opts?.meta),
290
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id, void 0, { name }, opts?.meta),
291
+ approve: (opts) => durable("approve", opts.id, void 0, {
313
292
  title: opts.title,
314
293
  ...opts.description === void 0 ? {} : { description: opts.description }
315
- }, opts.id === void 0, {
294
+ }, {
316
295
  ...opts.meta,
317
296
  ...opts.description === void 0 ? {} : { description: opts.description }
318
297
  }),
319
- now: (opts) => durable("now", opts?.id ?? defaultDurableId({ kind: "now" }), async () => Date.now(), void 0, opts?.id === void 0, opts?.meta),
320
- uuid: (opts) => durable("uuid", opts?.id ?? defaultDurableId({ kind: "uuid" }), async () => crypto.randomUUID(), void 0, opts?.id === void 0, opts?.meta),
298
+ now: (opts) => durable("now", opts?.id, async () => Date.now(), void 0, opts?.meta),
299
+ uuid: (opts) => durable("uuid", opts?.id, async () => crypto.randomUUID(), void 0, opts?.meta),
321
300
  emit: (name, value) => {
322
301
  emitted.push({
323
302
  name,
@@ -484,7 +463,7 @@ function resolveWorkflowId(ctx, param) {
484
463
  }
485
464
  function isMemoEntry(value) {
486
465
  const entry = value;
487
- return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.seq) && Number.isInteger(entry.occurrence) && entry.occurrence >= 0 && (entry.status === "completed" || entry.status === "failed");
466
+ return typeof entry === "object" && entry !== null && Number.isInteger(entry.seq) && entry.seq >= 0 && typeof entry.stepId === "string" && Number.isInteger(entry.seq) && (entry.status === "completed" || entry.status === "failed");
488
467
  }
489
468
  function parseBody(value) {
490
469
  if (value === null || typeof value !== "object") return "body must be a JSON object";
@@ -492,10 +471,10 @@ function parseBody(value) {
492
471
  if (body.workflowVersion !== void 0 && typeof body.workflowVersion !== "string") return "workflowVersion must be a string";
493
472
  if (body.memo !== void 0) {
494
473
  if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
495
- 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";
474
+ if (new Set(body.memo.map((entry) => entry.stepId)).size !== body.memo.length) return "memo entries must be unique per stepId";
496
475
  }
497
476
  if (body.action !== void 0 && body.action !== "advance" && body.action !== "execute") return "action must be \"advance\" or \"execute\"";
498
- if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\", stepId, occurrence } reference when action is \"execute\"";
477
+ if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\", stepId } reference when action is \"execute\"";
499
478
  if (body.action !== "execute" && body.step !== void 0) return "step is only valid when action is \"execute\"";
500
479
  if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
501
480
  return body;
@@ -505,12 +484,9 @@ async function readBody(request) {
505
484
  if (!text.trim()) return {};
506
485
  return JSON.parse(text);
507
486
  }
508
- function operationKey(operation) {
509
- return memoKey(operation.stepId, operation.occurrence);
510
- }
511
487
  function isStepReference(value) {
512
488
  const step = value;
513
- return typeof step === "object" && step !== null && step.kind === "step" && typeof step.stepId === "string" && Number.isInteger(step.occurrence) && step.occurrence >= 0;
489
+ return typeof step === "object" && step !== null && step.kind === "step" && typeof step.stepId === "string";
514
490
  }
515
491
  function disposition(outcome) {
516
492
  if (outcome.status === "completed") return "completed";
@@ -519,8 +495,8 @@ function disposition(outcome) {
519
495
  return outcome.steps.length > 1 ? "fork" : "advanced";
520
496
  }
521
497
  function memoDelta(before, after) {
522
- const existing = new Set(before.map((entry) => memoKey(entry.stepId, entry.occurrence)));
523
- return after.filter((entry) => !existing.has(memoKey(entry.stepId, entry.occurrence)));
498
+ const existing = new Set(before.map((entry) => entry.stepId));
499
+ return after.filter((entry) => !existing.has(entry.stepId));
524
500
  }
525
501
  function respond(runId, inputHash, workflowVersion, before, outcome, executed) {
526
502
  const { steps, emitted, output, error } = outcome;
@@ -666,12 +642,12 @@ function createStepsHandler(collection, options = {}) {
666
642
  input,
667
643
  memo: before,
668
644
  runId,
669
- shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(selected)
645
+ shouldExecute: (intent) => intent.kind !== "step" || intent.stepId === selected.stepId
670
646
  }));
671
- const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(selected));
647
+ const executed = outcome.results.find((result) => result.kind === "step" && result.stepId === selected.stepId);
672
648
  if (executed === void 0 && outcome.status !== "failed") return json(409, {
673
649
  error: "stale_step",
674
- message: `step "${selected.stepId}" (#${selected.occurrence}) is not executable from this memo`
650
+ message: `step "${selected.stepId}" is not executable from this memo`
675
651
  });
676
652
  return respond(runId, inputHash, workflow.version, before, outcome, executed);
677
653
  }
@@ -689,12 +665,12 @@ function createStepsHandler(collection, options = {}) {
689
665
  input,
690
666
  memo: described.memo,
691
667
  runId,
692
- shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(only)
668
+ shouldExecute: (intent) => intent.kind !== "step" || intent.stepId === only.stepId
693
669
  }));
694
- const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(only));
670
+ const executed = outcome.results.find((result) => result.kind === "step" && result.stepId === only.stepId);
695
671
  if (executed === void 0 && outcome.status !== "failed") return json(409, {
696
672
  error: "stale_step",
697
- message: `step "${only.stepId}" (#${only.occurrence}) is not executable from this memo`
673
+ message: `step "${only.stepId}" is not executable from this memo`
698
674
  });
699
675
  return respond(runId, inputHash, workflow.version, before, outcome, executed);
700
676
  };
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-CBdqyIz5.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-ZthZ8l6y.js";
2
2
  //#region src/manifests/nested-operations.ts
3
3
  const durableMethods = [
4
4
  "step",
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-CBdqyIz5.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-ZthZ8l6y.js";
2
2
  //#region src/manifests/operation-descriptions.ts
3
3
  const optionsArgument = {
4
4
  approve: 0,
@@ -1,4 +1,4 @@
1
- import { loadTypeScript, t as workflowHandlerSource } from "./graph-CBdqyIz5.js";
1
+ import { loadTypeScript, t as workflowHandlerSource } from "./graph-ZthZ8l6y.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-Dk1_3N-g.js";
1
+ import { t as generateManifests } from "./generate-CDOP4pMi.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.31",
3
+ "version": "0.0.0-dev.33",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",
@@ -1,17 +0,0 @@
1
- //#region src/core/durable-ids.ts
2
- /**
3
- * Shared by the runtime and the build-time check, so the ids a build rejects
4
- * are exactly the ones replay would collide.
5
- */
6
- function defaultDurableId(source) {
7
- switch (source.kind) {
8
- case "now": return "now";
9
- case "uuid": return "uuid";
10
- case "sleep": return `sleep:${source.ms}`;
11
- case "sleepUntil": return `sleepUntil:${source.timestamp}`;
12
- case "waitForEvent": return `event:${source.name}`;
13
- case "approve": return `approve:${source.title}`;
14
- }
15
- }
16
- //#endregion
17
- export { defaultDurableId as t };