@lovable.dev/workflows-sdk 0.0.0-dev.2 → 0.0.0-dev.20

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.
@@ -0,0 +1,470 @@
1
+ import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
2
+ //#region src/manifests/handler-source.ts
3
+ const nativeFunctionSource = /\{\s*\[native code\]\s*\}\s*$/;
4
+ function workflowHandlerSource(handler) {
5
+ const source = Function.prototype.toString.call(handler);
6
+ return nativeFunctionSource.test(source) ? void 0 : source;
7
+ }
8
+ //#endregion
9
+ //#region src/manifests/graph.ts
10
+ const durableMethods = {
11
+ step: 0,
12
+ approve: 0,
13
+ waitForEvent: 0,
14
+ sleep: 0,
15
+ sleepUntil: 0,
16
+ now: 0,
17
+ uuid: 0
18
+ };
19
+ let loaded;
20
+ async function loadTypeScript() {
21
+ if (loaded !== void 0) return loaded;
22
+ try {
23
+ const module = await import("typescript");
24
+ const api = module.default ?? module;
25
+ loaded = typeof api?.createSourceFile === "function" ? api : null;
26
+ } catch {
27
+ loaded = null;
28
+ }
29
+ return loaded;
30
+ }
31
+ async function extractWorkflowGraph(handler) {
32
+ const graph = {
33
+ source: "inferred",
34
+ scope: "handler",
35
+ complete: true,
36
+ nodes: [],
37
+ edges: [],
38
+ diagnostics: []
39
+ };
40
+ function addNode(node, parents) {
41
+ const id = `node-${graph.nodes.length}`;
42
+ graph.nodes.push({
43
+ id,
44
+ ...node
45
+ });
46
+ const seen = /* @__PURE__ */ new Set();
47
+ for (const parent of parents) {
48
+ const key = JSON.stringify(parent);
49
+ if (seen.has(key)) continue;
50
+ seen.add(key);
51
+ if (parent.kind === "order") graph.edges.push({
52
+ source: parent.source,
53
+ target: id,
54
+ kind: "order"
55
+ });
56
+ else graph.edges.push({
57
+ source: parent.source,
58
+ target: id,
59
+ kind: "branch",
60
+ outcome: parent.outcome
61
+ });
62
+ }
63
+ return [{
64
+ source: id,
65
+ kind: "order"
66
+ }];
67
+ }
68
+ function degrade(reason) {
69
+ graph.complete = false;
70
+ if (!graph.diagnostics.includes(reason)) graph.diagnostics.push(reason);
71
+ }
72
+ function unknown(reason, parents) {
73
+ degrade(reason);
74
+ return addNode({
75
+ kind: "unknown",
76
+ label: reason
77
+ }, parents);
78
+ }
79
+ const api = await loadTypeScript();
80
+ if (!api) {
81
+ unknown("Install typescript to infer step graphs", []);
82
+ return graph;
83
+ }
84
+ const ts = api;
85
+ const handlerSource = workflowHandlerSource(handler);
86
+ if (!handlerSource) {
87
+ unknown("Handler source is unavailable", []);
88
+ return graph;
89
+ }
90
+ const source = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
91
+ const declaration = source.statements[0];
92
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
93
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) {
94
+ unknown("Handler source is unavailable", []);
95
+ return graph;
96
+ }
97
+ const parameter = fn.parameters[0]?.name;
98
+ if (parameter && !ts.isIdentifier(parameter)) {
99
+ unknown("Destructured workflow context is not supported yet", []);
100
+ return graph;
101
+ }
102
+ const context = parameter?.text;
103
+ function contains(node, predicate, skipFunctions = false) {
104
+ if (skipFunctions && ts.isFunctionLike(node)) return false;
105
+ return predicate(node) || Boolean(ts.forEachChild(node, (child) => contains(child, predicate, skipFunctions) || void 0));
106
+ }
107
+ function durableCall(node) {
108
+ return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in durableMethods;
109
+ }
110
+ function stringLiteral(node) {
111
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
112
+ }
113
+ function numberLiteral(node) {
114
+ if (!node || !ts.isNumericLiteral(node)) return void 0;
115
+ const value = Number(node.text);
116
+ return Number.isFinite(value) ? value : void 0;
117
+ }
118
+ function templateReference(node, parameters) {
119
+ while (ts.isParenthesizedExpression(node)) node = node.expression;
120
+ if (ts.isIdentifier(node)) return parameters.has(node.text) ? node.text : void 0;
121
+ if (ts.isPropertyAccessExpression(node) && !node.questionDotToken) {
122
+ const expression = templateReference(node.expression, parameters);
123
+ return expression === void 0 ? void 0 : `${expression}.${node.name.text}`;
124
+ }
125
+ }
126
+ function stepIdTemplate(node, parameters) {
127
+ if (!node || !ts.isTemplateExpression(node)) return void 0;
128
+ let template = node.head.text;
129
+ for (const span of node.templateSpans) {
130
+ const reference = templateReference(span.expression, parameters);
131
+ if (reference === void 0) return void 0;
132
+ template += `{${reference}}${span.literal.text}`;
133
+ }
134
+ return template;
135
+ }
136
+ function mappedStep(node) {
137
+ while (ts.isParenthesizedExpression(node)) node = node.expression;
138
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression) || node.expression.name.text !== "map" || node.arguments.length !== 1) return;
139
+ const callback = node.arguments[0];
140
+ if (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) return void 0;
141
+ const parameters = new Set(callback.parameters.flatMap((parameter) => ts.isIdentifier(parameter.name) ? [parameter.name.text] : []));
142
+ let body;
143
+ if (ts.isBlock(callback.body)) {
144
+ const statement = callback.body.statements.length === 1 ? callback.body.statements[0] : void 0;
145
+ body = statement && ts.isReturnStatement(statement) ? statement.expression : void 0;
146
+ } else body = callback.body;
147
+ while (body && (ts.isParenthesizedExpression(body) || ts.isAwaitExpression(body))) body = body.expression;
148
+ if (!body || !durableCall(body) || body.expression.name.text !== "step") return;
149
+ const template = stepIdTemplate(body.arguments[0], parameters);
150
+ return template === void 0 ? void 0 : {
151
+ call: body,
152
+ template
153
+ };
154
+ }
155
+ function readableOptions(node) {
156
+ return node && ts.isObjectLiteralExpression(node) && node.properties.every(ts.isPropertyAssignment) ? node : void 0;
157
+ }
158
+ function option(options, name) {
159
+ for (const property of options?.properties ?? []) {
160
+ if (!ts.isPropertyAssignment(property)) continue;
161
+ if ((ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0) === name) return property.initializer;
162
+ }
163
+ }
164
+ function branchMetadata(meta) {
165
+ const branches = option(meta, "branches");
166
+ if (!branches || !ts.isArrayLiteralExpression(branches)) return void 0;
167
+ const path = [];
168
+ for (const element of branches.elements) {
169
+ const entry = readableOptions(element);
170
+ const id = stringLiteral(option(entry, "id"));
171
+ const description = stringLiteral(option(entry, "description"));
172
+ if (id === void 0 || description === void 0) return void 0;
173
+ path.push({
174
+ id,
175
+ description
176
+ });
177
+ }
178
+ return path;
179
+ }
180
+ function operationMeta(call) {
181
+ const method = call.expression.name.text;
182
+ const optionsIndex = method === "step" ? 2 : method === "sleep" || method === "sleepUntil" || method === "waitForEvent" ? 1 : 0;
183
+ return readableOptions(option(readableOptions(call.arguments[optionsIndex]), "meta"));
184
+ }
185
+ function operationBranches(call) {
186
+ return branchMetadata(operationMeta(call));
187
+ }
188
+ function stepMetadata(call) {
189
+ const meta = readableOptions(option(readableOptions(call.arguments[2]), "meta"));
190
+ const description = stringLiteral(option(meta, "description"));
191
+ if (description === void 0) return void 0;
192
+ const groupOptions = readableOptions(option(meta, "group"));
193
+ if (!groupOptions) return { description };
194
+ const id = stringLiteral(option(groupOptions, "id"));
195
+ const label = stringLiteral(option(groupOptions, "label"));
196
+ return id === void 0 || label === void 0 ? { description } : {
197
+ description,
198
+ group: {
199
+ id,
200
+ label
201
+ }
202
+ };
203
+ }
204
+ function operationDescription(options) {
205
+ return stringLiteral(option(readableOptions(option(options, "meta")), "description"));
206
+ }
207
+ function durableStepId(argument, options, fallback) {
208
+ if (argument && !options) return void 0;
209
+ const given = option(options, "id");
210
+ return given ? stringLiteral(given) : fallback;
211
+ }
212
+ function durableNode(call, parents) {
213
+ const method = call.expression.name.text;
214
+ if (method === "step") {
215
+ const stepId = stringLiteral(call.arguments[0]);
216
+ if (stepId === void 0) return unknown("Dynamic step IDs are not supported yet", parents);
217
+ const metadata = stepMetadata(call);
218
+ if (!metadata) return unknown("Step descriptions must be static strings", parents);
219
+ return addNode({
220
+ kind: "step",
221
+ stepId,
222
+ description: metadata.description,
223
+ label: stepId
224
+ }, parents);
225
+ }
226
+ if (method === "approve") {
227
+ const options = readableOptions(call.arguments[0]);
228
+ const title = stringLiteral(option(options, "title"));
229
+ if (title === void 0) return unknown("Dynamic approval titles are not supported yet", parents);
230
+ const stepId = durableStepId(call.arguments[0], options, defaultDurableId({
231
+ kind: "approve",
232
+ title
233
+ }));
234
+ if (stepId === void 0) return unknown("Dynamic approval IDs are not supported yet", parents);
235
+ const description = stringLiteral(option(options, "description"));
236
+ if (description === void 0) return unknown("Approval descriptions must be static strings", parents);
237
+ return addNode({
238
+ kind: "approve",
239
+ stepId,
240
+ description,
241
+ config: {
242
+ title,
243
+ description
244
+ },
245
+ label: title
246
+ }, parents);
247
+ }
248
+ if (method === "waitForEvent") {
249
+ const event = stringLiteral(call.arguments[0]);
250
+ if (event === void 0) return unknown("Dynamic event names are not supported yet", parents);
251
+ const options = readableOptions(call.arguments[1]);
252
+ const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
253
+ kind: "waitForEvent",
254
+ name: event
255
+ }));
256
+ if (stepId === void 0) return unknown("Dynamic waitForEvent IDs are not supported yet", parents);
257
+ const description = operationDescription(options);
258
+ if (description === void 0) return unknown("Wait descriptions must be static strings", parents);
259
+ const given = option(options, "deadline");
260
+ const deadline = numberLiteral(given);
261
+ if (given && deadline === void 0) degrade("Dynamic waitForEvent deadlines are not recorded");
262
+ return addNode({
263
+ kind: "wait-for-event",
264
+ stepId,
265
+ description,
266
+ config: {
267
+ event,
268
+ ...deadline === void 0 ? {} : { deadline }
269
+ },
270
+ label: event
271
+ }, parents);
272
+ }
273
+ if (method === "sleep") {
274
+ const ms = numberLiteral(call.arguments[0]);
275
+ if (ms === void 0) return unknown("Dynamic sleep durations are not supported yet", parents);
276
+ const options = readableOptions(call.arguments[1]);
277
+ const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
278
+ kind: "sleep",
279
+ ms
280
+ }));
281
+ if (stepId === void 0) return unknown("Dynamic sleep IDs are not supported yet", parents);
282
+ const description = operationDescription(options);
283
+ if (description === void 0) return unknown("Sleep descriptions must be static strings", parents);
284
+ return addNode({
285
+ kind: "sleep",
286
+ stepId,
287
+ description,
288
+ config: { ms },
289
+ label: `sleep ${ms}ms`
290
+ }, parents);
291
+ }
292
+ if (method === "sleepUntil") {
293
+ const timestamp = numberLiteral(call.arguments[0]);
294
+ if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
295
+ const options = readableOptions(call.arguments[1]);
296
+ const stepId = durableStepId(call.arguments[1], options, defaultDurableId({
297
+ kind: "sleepUntil",
298
+ timestamp
299
+ }));
300
+ if (stepId === void 0) return unknown("Dynamic sleepUntil IDs are not supported yet", parents);
301
+ const description = operationDescription(options);
302
+ if (description === void 0) return unknown("Sleep descriptions must be static strings", parents);
303
+ return addNode({
304
+ kind: "sleep-until",
305
+ stepId,
306
+ description,
307
+ config: { timestamp },
308
+ label: `sleep until ${timestamp}`
309
+ }, parents);
310
+ }
311
+ const options = readableOptions(call.arguments[0]);
312
+ const stepId = durableStepId(call.arguments[0], options, defaultDurableId({ kind: method }));
313
+ if (stepId === void 0) return unknown(`Dynamic ${method} IDs are not supported yet`, parents);
314
+ const description = operationDescription(options);
315
+ if (description === void 0) return unknown(`${method} descriptions must be static strings`, parents);
316
+ return addNode({
317
+ kind: method,
318
+ stepId,
319
+ description,
320
+ label: stepId
321
+ }, parents);
322
+ }
323
+ function expression(node, parents, awaited = false) {
324
+ if (ts.isParenthesizedExpression(node)) return expression(node.expression, parents, awaited);
325
+ if (ts.isAwaitExpression(node)) return expression(node.expression, parents, true);
326
+ if (durableCall(node)) {
327
+ if (!awaited) return unknown("Unawaited durable calls are not supported yet", parents);
328
+ const tails = durableNode(node, parents);
329
+ if (node.arguments.some((argument) => contains(argument, durableCall))) return unknown("Nested durable calls are not supported yet", tails);
330
+ return tails;
331
+ }
332
+ if (awaited && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Promise" && node.expression.name.text === "all" && node.arguments.length === 1) {
333
+ const argument = node.arguments[0];
334
+ if (ts.isArrayLiteralExpression(argument)) {
335
+ const elements = argument.elements;
336
+ if (elements.some((element) => contains(element, ts.isAwaitExpression, true))) return unknown("Await expressions inside Promise.all are not supported yet", parents);
337
+ return elements.length > 0 ? elements.flatMap((element) => {
338
+ while (ts.isParenthesizedExpression(element)) element = element.expression;
339
+ return ts.isCallExpression(element) ? expression(element, parents, true) : unknown("Dynamic Promise.all entries are not followed", parents);
340
+ }) : parents;
341
+ }
342
+ const mapped = mappedStep(argument);
343
+ if (mapped !== void 0) {
344
+ const metadata = stepMetadata(mapped.call);
345
+ if (!metadata?.group) return unknown("Dynamic parallel steps need static group metadata", parents);
346
+ return addNode({
347
+ kind: "parallel",
348
+ groupId: metadata.group.id,
349
+ cardinality: "dynamic",
350
+ operation: {
351
+ kind: "step",
352
+ stepIdTemplate: mapped.template,
353
+ description: metadata.description
354
+ },
355
+ label: metadata.group.label
356
+ }, parents);
357
+ }
358
+ }
359
+ if (contains(node, (child) => ts.isCallExpression(child) || ts.isAwaitExpression(child) || ts.isNewExpression(child))) return unknown("Helper calls and dynamic expressions are not followed", parents);
360
+ if (ts.isIdentifier(node) && node.text === context) return unknown("Workflow context aliases are not followed", parents);
361
+ return parents;
362
+ }
363
+ function branchInfo(statement, depth) {
364
+ let result;
365
+ const visit = (node) => {
366
+ if (result) return;
367
+ if (durableCall(node)) {
368
+ result = operationBranches(node)?.[depth];
369
+ return;
370
+ }
371
+ ts.forEachChild(node, visit);
372
+ };
373
+ visit(statement.thenStatement);
374
+ if (statement.elseStatement) visit(statement.elseStatement);
375
+ return result;
376
+ }
377
+ function statements(items, parents, branchDepth) {
378
+ let flow = {
379
+ tails: parents,
380
+ fallsThrough: true
381
+ };
382
+ for (const statement of items) {
383
+ if (!flow.fallsThrough) break;
384
+ flow = walkStatement(statement, flow.tails, branchDepth);
385
+ }
386
+ return flow;
387
+ }
388
+ function walkStatement(statement, parents, branchDepth) {
389
+ if (ts.isBlock(statement)) return statements(statement.statements, parents, branchDepth);
390
+ if (ts.isReturnStatement(statement)) {
391
+ if (statement.expression) expression(statement.expression, parents, true);
392
+ return {
393
+ tails: [],
394
+ fallsThrough: false
395
+ };
396
+ }
397
+ if (ts.isThrowStatement(statement)) {
398
+ expression(statement.expression, parents);
399
+ return {
400
+ tails: [],
401
+ fallsThrough: false
402
+ };
403
+ }
404
+ if (ts.isVariableStatement(statement)) {
405
+ if (statement.declarationList.declarations.some((item) => contains(item.name, (child) => ts.isIdentifier(child) && (child.text === "Promise" || child.text === context)))) return {
406
+ tails: unknown("Shadowed context or Promise bindings are not supported yet", parents),
407
+ fallsThrough: false
408
+ };
409
+ let tails = parents;
410
+ for (const item of statement.declarationList.declarations) if (item.initializer) tails = expression(item.initializer, tails);
411
+ return {
412
+ tails,
413
+ fallsThrough: true
414
+ };
415
+ }
416
+ if (ts.isExpressionStatement(statement)) return {
417
+ tails: expression(statement.expression, parents),
418
+ fallsThrough: true
419
+ };
420
+ if (ts.isIfStatement(statement)) {
421
+ const conditionTails = expression(statement.expression, parents);
422
+ const metadata = branchInfo(statement, branchDepth);
423
+ const condition = statement.expression.getText(source);
424
+ const branchTails = metadata ? addNode({
425
+ kind: "branch",
426
+ branchId: metadata.id,
427
+ condition,
428
+ description: metadata.description,
429
+ label: metadata.description
430
+ }, conditionTails) : conditionTails;
431
+ const sourceId = metadata ? branchTails[0]?.source : void 0;
432
+ const thenParents = sourceId ? [{
433
+ source: sourceId,
434
+ kind: "branch",
435
+ outcome: true
436
+ }] : branchTails;
437
+ const elseParents = sourceId ? [{
438
+ source: sourceId,
439
+ kind: "branch",
440
+ outcome: false
441
+ }] : branchTails;
442
+ const thenFlow = walkStatement(statement.thenStatement, thenParents, branchDepth + 1);
443
+ const elseFlow = statement.elseStatement ? walkStatement(statement.elseStatement, elseParents, branchDepth + 1) : {
444
+ tails: elseParents,
445
+ fallsThrough: true
446
+ };
447
+ return {
448
+ tails: [...thenFlow.fallsThrough ? thenFlow.tails : [], ...elseFlow.fallsThrough ? elseFlow.tails : []],
449
+ fallsThrough: thenFlow.fallsThrough || elseFlow.fallsThrough
450
+ };
451
+ }
452
+ if (ts.isEmptyStatement(statement)) return {
453
+ tails: parents,
454
+ fallsThrough: true
455
+ };
456
+ return {
457
+ tails: unknown("Loops and other control flow are not supported yet", parents),
458
+ fallsThrough: true
459
+ };
460
+ }
461
+ const tails = [];
462
+ if (!ts.isBlock(fn.body)) {
463
+ expression(fn.body, tails, true);
464
+ return graph;
465
+ }
466
+ statements(fn.body.statements, tails, 0);
467
+ return graph;
468
+ }
469
+ //#endregion
470
+ export { extractWorkflowGraph, loadTypeScript, workflowHandlerSource as t };