@lovable.dev/workflows-sdk 0.0.0-dev.3 → 0.0.0-dev.30

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.
@@ -1,115 +0,0 @@
1
- import { createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
- //#region src/core/identifier.ts
3
- function assertIdentifier(kind, id) {
4
- if (typeof id !== "string" || id.trim() === "" || id !== id.trim()) throw new Error(`@lovable.dev/workflows-sdk: ${kind} IDs must be non-empty and have no surrounding whitespace`);
5
- }
6
- //#endregion
7
- //#region src/core/schedule.ts
8
- function defineSchedule(schedule) {
9
- assertIdentifier("schedule", schedule.id);
10
- if (typeof schedule.cron !== "string" || schedule.cron.trim().split(/\s+/).length !== 5) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" requires a five-field cron expression`);
11
- const timeZone = schedule.timeZone ?? "UTC";
12
- new Intl.DateTimeFormat("en", { timeZone });
13
- return {
14
- ...schedule,
15
- timeZone
16
- };
17
- }
18
- //#endregion
19
- //#region src/core/workflow.ts
20
- function registerWorkflows({ workflows, schedules = [] }) {
21
- const ids = /* @__PURE__ */ new Set();
22
- for (const workflow of workflows) {
23
- if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
24
- assertIdentifier("workflow", workflow.id);
25
- if (!/^[a-z0-9][a-z0-9_-]{0,127}$/.test(workflow.id)) throw new Error("@lovable.dev/workflows-sdk: workflow names must be 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
26
- if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
27
- ids.add(workflow.id);
28
- }
29
- const scheduleIds = /* @__PURE__ */ new Set();
30
- const registeredSchedules = schedules.map((schedule) => {
31
- const definition = defineSchedule(schedule);
32
- if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
33
- if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
34
- scheduleIds.add(definition.id);
35
- return definition;
36
- });
37
- return {
38
- workflows: [...workflows],
39
- schedules: registeredSchedules
40
- };
41
- }
42
- //#endregion
43
- //#region src/manifests/json.ts
44
- function toJson(value, jsonPath, ancestors = /* @__PURE__ */ new Set()) {
45
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
46
- if (typeof value === "number" && Number.isFinite(value)) return value;
47
- if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain finite, acyclic JSON values`);
48
- ancestors.add(value);
49
- try {
50
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must not contain symbol keys`);
51
- if (Array.isArray(value)) {
52
- if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must be a dense JSON array without extra properties`);
53
- return Array.from(value, (item, index) => toJson(item, `${jsonPath}[${index}]`, ancestors));
54
- }
55
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain plain JSON objects`);
56
- return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${jsonPath}.${key}`, ancestors)]));
57
- } finally {
58
- ancestors.delete(value);
59
- }
60
- }
61
- //#endregion
62
- //#region src/manifests/generate.ts
63
- function serializeSchema(schema, direction, label) {
64
- if (!schema) return void 0;
65
- const standard = schema["~standard"];
66
- if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
67
- try {
68
- return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
69
- } catch (cause) {
70
- throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
71
- }
72
- }
73
- async function generateManifests(definition) {
74
- const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
75
- const collection = registerWorkflows(definition);
76
- const manifests = [];
77
- for (const workflow of collection.workflows) {
78
- if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
79
- const metadata = {
80
- id: workflow.id,
81
- ...workflow.description === void 0 ? {} : { description: workflow.description },
82
- ...workflow.version === void 0 ? {} : { version: workflow.version },
83
- ...workflow.inputSchema ? { inputSchema: serializeSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
84
- ...workflow.outputSchema ? { outputSchema: serializeSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
85
- ...workflow.stateSchema ? { stateSchema: serializeSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
86
- };
87
- const schedules = [];
88
- for (const schedule of collection.schedules.filter((schedule) => schedule.workflow === workflow)) {
89
- const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
90
- const schema = schedule.workflow.inputSchema;
91
- if (schema) {
92
- const result = await schema["~standard"].validate(input);
93
- if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
94
- }
95
- schedules.push({
96
- id: schedule.id,
97
- cron: schedule.cron,
98
- timeZone: schedule.timeZone ?? "UTC",
99
- input
100
- });
101
- }
102
- schedules.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
103
- const manifest = {
104
- version: 1,
105
- workflow: metadata,
106
- schedules,
107
- graph: await extractWorkflowGraph(workflow.handler)
108
- };
109
- toJson(manifest, "manifest");
110
- manifests.push(manifest);
111
- }
112
- return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
113
- }
114
- //#endregion
115
- export { defineSchedule as a, registerWorkflows as i, createMiddleware as n, createWorkflow as r, generateManifests as t };
@@ -1,201 +0,0 @@
1
- //#region src/manifests/graph.ts
2
- const durableMethods = {
3
- step: 0,
4
- approve: 0,
5
- waitForEvent: 0,
6
- sleep: 0,
7
- sleepUntil: 0
8
- };
9
- let loaded;
10
- async function loadTypeScript() {
11
- if (loaded !== void 0) return loaded;
12
- try {
13
- const module = await import("typescript");
14
- const api = module.default ?? module;
15
- loaded = typeof api?.createSourceFile === "function" ? api : null;
16
- } catch {
17
- loaded = null;
18
- }
19
- return loaded;
20
- }
21
- async function extractWorkflowGraph(handler) {
22
- const graph = {
23
- source: "inferred",
24
- scope: "handler",
25
- complete: true,
26
- nodes: [],
27
- edges: [],
28
- diagnostics: []
29
- };
30
- function addNode(node, parents) {
31
- const id = `node-${graph.nodes.length}`;
32
- graph.nodes.push({
33
- id,
34
- ...node
35
- });
36
- for (const parent of new Set(parents)) graph.edges.push({
37
- source: parent,
38
- target: id,
39
- kind: "order"
40
- });
41
- return [id];
42
- }
43
- function degrade(reason) {
44
- graph.complete = false;
45
- if (!graph.diagnostics.includes(reason)) graph.diagnostics.push(reason);
46
- }
47
- function unknown(reason, parents) {
48
- degrade(reason);
49
- return addNode({
50
- kind: "unknown",
51
- label: reason
52
- }, parents);
53
- }
54
- const api = await loadTypeScript();
55
- if (!api) {
56
- unknown("Install typescript to infer step graphs", []);
57
- return graph;
58
- }
59
- const ts = api;
60
- const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
61
- const declaration = source.statements[0];
62
- const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
63
- if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) {
64
- unknown("Handler source is unavailable", []);
65
- return graph;
66
- }
67
- const parameter = fn.parameters[0]?.name;
68
- if (parameter && !ts.isIdentifier(parameter)) {
69
- unknown("Destructured workflow context is not supported yet", []);
70
- return graph;
71
- }
72
- const context = parameter?.text;
73
- function contains(node, predicate, skipFunctions = false) {
74
- if (skipFunctions && ts.isFunctionLike(node)) return false;
75
- return predicate(node) || Boolean(ts.forEachChild(node, (child) => contains(child, predicate, skipFunctions) || void 0));
76
- }
77
- function durableCall(node) {
78
- return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in durableMethods;
79
- }
80
- function stringLiteral(node) {
81
- return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
82
- }
83
- function numberLiteral(node) {
84
- if (!node || !ts.isNumericLiteral(node)) return void 0;
85
- const value = Number(node.text);
86
- return Number.isFinite(value) ? value : void 0;
87
- }
88
- function readableOptions(node) {
89
- return node && ts.isObjectLiteralExpression(node) && node.properties.every(ts.isPropertyAssignment) ? node : void 0;
90
- }
91
- function option(options, name) {
92
- for (const property of options?.properties ?? []) {
93
- if (!ts.isPropertyAssignment(property)) continue;
94
- if ((ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0) === name) return property.initializer;
95
- }
96
- }
97
- function durableNode(call, parents) {
98
- const method = call.expression.name.text;
99
- if (method === "step") {
100
- const stepId = stringLiteral(call.arguments[0]);
101
- if (stepId === void 0) return unknown("Dynamic step IDs are not supported yet", parents);
102
- return addNode({
103
- kind: "step",
104
- stepId,
105
- label: stepId
106
- }, parents);
107
- }
108
- if (method === "approve") {
109
- const options = readableOptions(call.arguments[0]);
110
- const title = stringLiteral(option(options, "title"));
111
- if (title === void 0) return unknown("Dynamic approval titles are not supported yet", parents);
112
- const given = option(options, "description");
113
- const description = stringLiteral(given);
114
- if (given && description === void 0) degrade("Dynamic approval descriptions are not recorded");
115
- return addNode({
116
- kind: "approve",
117
- config: {
118
- title,
119
- ...description === void 0 ? {} : { description }
120
- },
121
- label: title
122
- }, parents);
123
- }
124
- if (method === "waitForEvent") {
125
- const event = stringLiteral(call.arguments[0]);
126
- if (event === void 0) return unknown("Dynamic event names are not supported yet", parents);
127
- const options = readableOptions(call.arguments[1]);
128
- if (call.arguments[1] && !options) degrade("Dynamic waitForEvent options are not recorded");
129
- const given = option(options, "deadline");
130
- const deadline = numberLiteral(given);
131
- if (given && deadline === void 0) degrade("Dynamic waitForEvent deadlines are not recorded");
132
- return addNode({
133
- kind: "wait-for-event",
134
- config: {
135
- event,
136
- ...deadline === void 0 ? {} : { deadline }
137
- },
138
- label: event
139
- }, parents);
140
- }
141
- if (method === "sleep") {
142
- const ms = numberLiteral(call.arguments[0]);
143
- if (ms === void 0) return unknown("Dynamic sleep durations are not supported yet", parents);
144
- return addNode({
145
- kind: "sleep",
146
- config: { ms },
147
- label: `sleep ${ms}ms`
148
- }, parents);
149
- }
150
- const timestamp = numberLiteral(call.arguments[0]);
151
- if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
152
- return addNode({
153
- kind: "sleep-until",
154
- config: { timestamp },
155
- label: `sleep until ${timestamp}`
156
- }, parents);
157
- }
158
- function expression(node, parents, awaited = false) {
159
- if (ts.isParenthesizedExpression(node)) return expression(node.expression, parents, awaited);
160
- if (ts.isAwaitExpression(node)) return expression(node.expression, parents, true);
161
- if (durableCall(node)) {
162
- if (!awaited) return unknown("Unawaited durable calls are not supported yet", parents);
163
- const tails = durableNode(node, parents);
164
- if (node.arguments.some((argument) => contains(argument, durableCall))) return unknown("Nested durable calls are not supported yet", tails);
165
- return tails;
166
- }
167
- 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 && ts.isArrayLiteralExpression(node.arguments[0])) {
168
- const elements = node.arguments[0].elements;
169
- if (elements.some((element) => contains(element, ts.isAwaitExpression, true))) return unknown("Await expressions inside Promise.all are not supported yet", parents);
170
- return elements.length > 0 ? elements.flatMap((element) => {
171
- while (ts.isParenthesizedExpression(element)) element = element.expression;
172
- return ts.isCallExpression(element) ? expression(element, parents, true) : unknown("Dynamic Promise.all entries are not followed", parents);
173
- }) : parents;
174
- }
175
- if (contains(node, (child) => ts.isCallExpression(child) || ts.isAwaitExpression(child) || ts.isNewExpression(child))) return unknown("Helper calls and dynamic expressions are not followed", parents);
176
- if (ts.isIdentifier(node) && node.text === context) return unknown("Workflow context aliases are not followed", parents);
177
- return parents;
178
- }
179
- let tails = [];
180
- if (!ts.isBlock(fn.body)) {
181
- expression(fn.body, tails, true);
182
- return graph;
183
- }
184
- for (const statement of fn.body.statements) {
185
- if (ts.isReturnStatement(statement)) {
186
- if (statement.expression) expression(statement.expression, tails, true);
187
- break;
188
- }
189
- if (ts.isVariableStatement(statement)) {
190
- if (statement.declarationList.declarations.some((item) => contains(item.name, (child) => ts.isIdentifier(child) && (child.text === "Promise" || child.text === context)))) {
191
- tails = unknown("Shadowed context or Promise bindings are not supported yet", tails);
192
- break;
193
- }
194
- for (const item of statement.declarationList.declarations) if (item.initializer) tails = expression(item.initializer, tails);
195
- } else if (ts.isExpressionStatement(statement)) tails = expression(statement.expression, tails);
196
- else tails = unknown("Branches, loops, and other control flow are not supported yet", tails);
197
- }
198
- return graph;
199
- }
200
- //#endregion
201
- export { extractWorkflowGraph };