@lovable.dev/workflows-sdk 0.0.0-dev.6 → 0.0.0-dev.60
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 +338 -357
- package/dist/branch-metadata-C8JF4mRD.js +113 -0
- package/dist/cli/generate-manifests.d.ts +1 -0
- package/dist/cli/generate-manifests.js +30 -0
- package/dist/context-escapes-CaWQZiKA.js +80 -0
- package/dist/duplicate-ids-piCSoy97.js +105 -0
- package/dist/durable-ids-B8WBvR9R.js +2 -0
- package/dist/durable-ids-CdlFkNKw.js +4 -0
- package/dist/generate-DGdzUQcG.js +1251 -0
- package/dist/graph-C_Y_mGVf.js +2 -0
- package/dist/graph-DSYE4aER.js +791 -0
- package/dist/index.d.ts +1291 -75
- package/dist/index.js +1284 -2
- package/dist/llm-validation-DdDO6csU.js +61 -0
- package/dist/nested-operations-CEA4t4q_.js +60 -0
- package/dist/operation-descriptions-BtUOwQoK.js +47 -0
- package/dist/plugin-CXlzS4_y.js +379 -0
- package/dist/step-metadata-DvieDJGl.js +105 -0
- package/dist/vite.d.ts +2 -4
- package/dist/vite.js +1 -244
- package/dist/wait-deadlines-DULtPtuu.js +63 -0
- package/dist/wait-deadlines-DpK-Fgnd.js +4 -0
- package/dist/workflow_manifest_pb-DnavtUll.js +5736 -0
- package/package.json +9 -7
- package/dist/generate-DyUHbtre.js +0 -233
- package/dist/graph-BgdiEUHq.js +0 -201
- package/dist/stacks/tanstack/index.d.ts +0 -31
- package/dist/stacks/tanstack/index.js +0 -99
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lovable.dev/workflows-sdk",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.60",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"tag": "dev",
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"description": "Author workflows for Lovable apps.",
|
|
10
10
|
"type": "module",
|
|
11
|
+
"sideEffects": false,
|
|
11
12
|
"repository": {
|
|
12
13
|
"type": "git",
|
|
13
14
|
"url": "git+https://github.com/lovablelabs/lovable.git",
|
|
@@ -22,20 +23,21 @@
|
|
|
22
23
|
"./vite": {
|
|
23
24
|
"types": "./dist/vite.d.ts",
|
|
24
25
|
"import": "./dist/vite.js"
|
|
25
|
-
},
|
|
26
|
-
"./stacks/tanstack": {
|
|
27
|
-
"types": "./dist/stacks/tanstack/index.d.ts",
|
|
28
|
-
"import": "./dist/stacks/tanstack/index.js"
|
|
29
26
|
}
|
|
30
27
|
},
|
|
28
|
+
"bin": {
|
|
29
|
+
"lovable-workflows-generate-manifests": "./dist/cli/generate-manifests.js"
|
|
30
|
+
},
|
|
31
31
|
"files": [
|
|
32
32
|
"dist"
|
|
33
33
|
],
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@standard-schema/spec": "^1.1.0",
|
|
36
|
-
"@tanstack/workflow-core": "0.0.4"
|
|
36
|
+
"@tanstack/workflow-core": "0.0.4",
|
|
37
|
+
"@lovable.dev/ai-gateway": "0.1.13"
|
|
37
38
|
},
|
|
38
39
|
"devDependencies": {
|
|
40
|
+
"@bufbuild/protobuf": "^2.10.1",
|
|
39
41
|
"@types/node": "22.13.13",
|
|
40
42
|
"vite": "^7.3.1",
|
|
41
43
|
"zod": "^4.1.13",
|
|
@@ -55,7 +57,7 @@
|
|
|
55
57
|
}
|
|
56
58
|
},
|
|
57
59
|
"scripts": {
|
|
58
|
-
"build": "tsdown",
|
|
60
|
+
"build": "pnpm --filter @lovable.dev/workflows-sdk^... build && tsdown",
|
|
59
61
|
"test": "node --test tests/*.test.mjs",
|
|
60
62
|
"typecheck": "tsc -p tsconfig.typecheck.json",
|
|
61
63
|
"check:package": "tmp=$(mktemp -d) && pnpm pack --out \"$tmp/pkg.tgz\" && tar -xzf \"$tmp/pkg.tgz\" -C \"$tmp\" && publint \"$tmp/package\" --strict && attw \"$tmp/pkg.tgz\" && node scripts/check-deps.mjs \"$tmp/package/package.json\""
|
|
@@ -1,233 +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/cadence.ts
|
|
8
|
-
const WEEKDAYS = [
|
|
9
|
-
"mon",
|
|
10
|
-
"tue",
|
|
11
|
-
"wed",
|
|
12
|
-
"thu",
|
|
13
|
-
"fri",
|
|
14
|
-
"sat",
|
|
15
|
-
"sun"
|
|
16
|
-
];
|
|
17
|
-
const WEEKDAY_NAMES = {
|
|
18
|
-
mon: "mon",
|
|
19
|
-
monday: "mon",
|
|
20
|
-
tue: "tue",
|
|
21
|
-
tuesday: "tue",
|
|
22
|
-
wed: "wed",
|
|
23
|
-
wednesday: "wed",
|
|
24
|
-
thu: "thu",
|
|
25
|
-
thursday: "thu",
|
|
26
|
-
fri: "fri",
|
|
27
|
-
friday: "fri",
|
|
28
|
-
sat: "sat",
|
|
29
|
-
saturday: "sat",
|
|
30
|
-
sun: "sun",
|
|
31
|
-
sunday: "sun"
|
|
32
|
-
};
|
|
33
|
-
function fail$1(message) {
|
|
34
|
-
throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
|
|
35
|
-
}
|
|
36
|
-
function parseWeekday(value, label) {
|
|
37
|
-
const day = typeof value === "string" ? WEEKDAY_NAMES[value.toLowerCase()] : void 0;
|
|
38
|
-
if (day === void 0) fail$1(`${label} names an unknown day "${String(value)}"; use ${WEEKDAYS.join(", ")}`);
|
|
39
|
-
return day;
|
|
40
|
-
}
|
|
41
|
-
function parseDays(value, label) {
|
|
42
|
-
if (!Array.isArray(value) || value.length === 0) fail$1(`${label} must be a non-empty array of days`);
|
|
43
|
-
const days = [...new Set(value.map((entry) => parseWeekday(entry, label)))].sort((a, b) => WEEKDAYS.indexOf(a) - WEEKDAYS.indexOf(b));
|
|
44
|
-
return days.length === WEEKDAYS.length ? null : days;
|
|
45
|
-
}
|
|
46
|
-
function parseHoursOfDay(value, label) {
|
|
47
|
-
const entries = Array.isArray(value) ? value : [value];
|
|
48
|
-
if (entries.length === 0) fail$1(`${label} must name at least one hour`);
|
|
49
|
-
for (const entry of entries) if (!Number.isInteger(entry) || entry < 0 || entry > 23) fail$1(`${label}: ${JSON.stringify(entry)} must be a whole hour from 0 to 23; the platform picks the minute`);
|
|
50
|
-
return [...new Set(entries)].sort((a, b) => a - b);
|
|
51
|
-
}
|
|
52
|
-
function hourly(options) {
|
|
53
|
-
if (options !== void 0) fail$1(`hourly() takes no options; the platform decides where in the hour a schedule runs`);
|
|
54
|
-
return { kind: "hourly" };
|
|
55
|
-
}
|
|
56
|
-
function daily(options = {}) {
|
|
57
|
-
return {
|
|
58
|
-
kind: "daily",
|
|
59
|
-
at: options.at === void 0 ? null : parseHoursOfDay(options.at, "daily({ at })"),
|
|
60
|
-
days: options.days === void 0 ? null : parseDays(options.days, "daily({ days })")
|
|
61
|
-
};
|
|
62
|
-
}
|
|
63
|
-
function weekly(options) {
|
|
64
|
-
if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: 7 }`);
|
|
65
|
-
return {
|
|
66
|
-
kind: "daily",
|
|
67
|
-
at: options.at === void 0 ? null : parseHoursOfDay(options.at, "weekly({ at })"),
|
|
68
|
-
days: [parseWeekday(options.on, "weekly({ on })")]
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
function isHourSet(value) {
|
|
72
|
-
if (value === null) return true;
|
|
73
|
-
if (!Array.isArray(value) || value.length === 0) return false;
|
|
74
|
-
return value.every((hour, index) => Number.isInteger(hour) && hour >= 0 && hour <= 23 && (index === 0 || hour > value[index - 1]));
|
|
75
|
-
}
|
|
76
|
-
function isDaySet(value) {
|
|
77
|
-
if (value === null) return true;
|
|
78
|
-
if (!Array.isArray(value) || value.length === 0 || value.length >= WEEKDAYS.length) return false;
|
|
79
|
-
const indexes = value.map((day) => WEEKDAYS.indexOf(day));
|
|
80
|
-
return indexes.every((index, position) => index >= 0 && (position === 0 || index > indexes[position - 1]));
|
|
81
|
-
}
|
|
82
|
-
function isCadence(value) {
|
|
83
|
-
if (typeof value !== "object" || value === null) return false;
|
|
84
|
-
const cadence = value;
|
|
85
|
-
if (cadence.kind === "hourly") return Object.keys(cadence).length === 1;
|
|
86
|
-
if (cadence.kind === "daily") return isHourSet(cadence.at) && isDaySet(cadence.days);
|
|
87
|
-
return false;
|
|
88
|
-
}
|
|
89
|
-
//#endregion
|
|
90
|
-
//#region src/core/schedule.ts
|
|
91
|
-
const OVERLAP_POLICIES = [
|
|
92
|
-
"skip",
|
|
93
|
-
"allow",
|
|
94
|
-
"buffer-one"
|
|
95
|
-
];
|
|
96
|
-
function fail(message) {
|
|
97
|
-
throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
|
|
98
|
-
}
|
|
99
|
-
const CANONICAL_ZONES = new Set(typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []);
|
|
100
|
-
function resolveTimeZone(schedule) {
|
|
101
|
-
const timeZone = schedule.timeZone;
|
|
102
|
-
if (typeof timeZone !== "string" || timeZone === "") fail(`schedule "${schedule.id}" needs a timeZone, such as "Europe/Stockholm" or "UTC"`);
|
|
103
|
-
if (timeZone !== "UTC" && CANONICAL_ZONES.size > 0 && !CANONICAL_ZONES.has(timeZone)) fail(`schedule "${schedule.id}" timeZone "${timeZone}" must be "UTC" or a canonical IANA name such as "Europe/Stockholm"; fixed offsets and aliases such as "EST", "GMT", "Etc/GMT+5", and "US/Pacific" are not accepted`);
|
|
104
|
-
new Intl.DateTimeFormat("en", { timeZone });
|
|
105
|
-
return timeZone;
|
|
106
|
-
}
|
|
107
|
-
function defineSchedule(schedule) {
|
|
108
|
-
assertIdentifier("schedule", schedule.id);
|
|
109
|
-
if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from hourly(), daily(), or weekly()`);
|
|
110
|
-
const cadence = schedule.cadence;
|
|
111
|
-
const timeZone = resolveTimeZone(schedule);
|
|
112
|
-
const overlapPolicy = schedule.overlapPolicy ?? "skip";
|
|
113
|
-
if (!OVERLAP_POLICIES.includes(overlapPolicy)) fail(`schedule "${schedule.id}" overlapPolicy must be one of ${OVERLAP_POLICIES.join(", ")}`);
|
|
114
|
-
const enabled = schedule.enabled ?? true;
|
|
115
|
-
if (typeof enabled !== "boolean") fail(`schedule "${schedule.id}" enabled must be a boolean`);
|
|
116
|
-
return {
|
|
117
|
-
...schedule,
|
|
118
|
-
type: "schedule",
|
|
119
|
-
cadence,
|
|
120
|
-
timeZone,
|
|
121
|
-
overlapPolicy,
|
|
122
|
-
enabled
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
//#endregion
|
|
126
|
-
//#region src/core/workflow.ts
|
|
127
|
-
function registerWorkflows(definition) {
|
|
128
|
-
for (const key of Object.keys(definition)) {
|
|
129
|
-
if (key === "workflows" || key === "triggers") continue;
|
|
130
|
-
throw new Error(key === "schedules" ? `@lovable.dev/workflows-sdk: registerWorkflows() no longer takes "schedules"; rename the key to "triggers"` : `@lovable.dev/workflows-sdk: registerWorkflows() does not take "${key}"`);
|
|
131
|
-
}
|
|
132
|
-
const { workflows, triggers = [] } = definition;
|
|
133
|
-
const ids = /* @__PURE__ */ new Set();
|
|
134
|
-
for (const workflow of workflows) {
|
|
135
|
-
if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
|
|
136
|
-
assertIdentifier("workflow", workflow.id);
|
|
137
|
-
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");
|
|
138
|
-
if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
|
|
139
|
-
ids.add(workflow.id);
|
|
140
|
-
}
|
|
141
|
-
const scheduleIds = /* @__PURE__ */ new Set();
|
|
142
|
-
const registeredTriggers = triggers.map((trigger) => {
|
|
143
|
-
const definition = defineSchedule(trigger);
|
|
144
|
-
if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
|
|
145
|
-
if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
|
|
146
|
-
scheduleIds.add(definition.id);
|
|
147
|
-
return definition;
|
|
148
|
-
});
|
|
149
|
-
return {
|
|
150
|
-
workflows: [...workflows],
|
|
151
|
-
triggers: registeredTriggers
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
//#endregion
|
|
155
|
-
//#region src/manifests/json.ts
|
|
156
|
-
function toJson(value, jsonPath, ancestors = /* @__PURE__ */ new Set()) {
|
|
157
|
-
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
158
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
159
|
-
if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain finite, acyclic JSON values`);
|
|
160
|
-
ancestors.add(value);
|
|
161
|
-
try {
|
|
162
|
-
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must not contain symbol keys`);
|
|
163
|
-
if (Array.isArray(value)) {
|
|
164
|
-
if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must be a dense JSON array without extra properties`);
|
|
165
|
-
return Array.from(value, (item, index) => toJson(item, `${jsonPath}[${index}]`, ancestors));
|
|
166
|
-
}
|
|
167
|
-
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain plain JSON objects`);
|
|
168
|
-
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${jsonPath}.${key}`, ancestors)]));
|
|
169
|
-
} finally {
|
|
170
|
-
ancestors.delete(value);
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
//#endregion
|
|
174
|
-
//#region src/manifests/generate.ts
|
|
175
|
-
function serializeSchema(schema, direction, label) {
|
|
176
|
-
if (!schema) return void 0;
|
|
177
|
-
const standard = schema["~standard"];
|
|
178
|
-
if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
|
|
179
|
-
try {
|
|
180
|
-
return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
|
|
181
|
-
} catch (cause) {
|
|
182
|
-
throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
async function generateManifests(definition) {
|
|
186
|
-
const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
|
|
187
|
-
const collection = registerWorkflows(definition);
|
|
188
|
-
const manifests = [];
|
|
189
|
-
for (const workflow of collection.workflows) {
|
|
190
|
-
if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
|
|
191
|
-
const metadata = {
|
|
192
|
-
id: workflow.id,
|
|
193
|
-
...workflow.description === void 0 ? {} : { description: workflow.description },
|
|
194
|
-
...workflow.version === void 0 ? {} : { version: workflow.version },
|
|
195
|
-
...workflow.inputSchema ? { inputSchema: serializeSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
|
|
196
|
-
...workflow.outputSchema ? { outputSchema: serializeSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
|
|
197
|
-
...workflow.stateSchema ? { stateSchema: serializeSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
|
|
198
|
-
};
|
|
199
|
-
const triggers = [];
|
|
200
|
-
for (const schedule of collection.triggers.filter((trigger) => trigger.workflow === workflow)) {
|
|
201
|
-
const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
|
|
202
|
-
const schema = schedule.workflow.inputSchema;
|
|
203
|
-
if (schema) {
|
|
204
|
-
const result = await schema["~standard"].validate(input);
|
|
205
|
-
if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
|
|
206
|
-
}
|
|
207
|
-
triggers.push({
|
|
208
|
-
type: schedule.type,
|
|
209
|
-
id: schedule.id,
|
|
210
|
-
cadence: schedule.cadence,
|
|
211
|
-
timeZone: schedule.timeZone,
|
|
212
|
-
enabled: schedule.enabled,
|
|
213
|
-
overlapPolicy: schedule.overlapPolicy,
|
|
214
|
-
input
|
|
215
|
-
});
|
|
216
|
-
}
|
|
217
|
-
triggers.sort((a, b) => {
|
|
218
|
-
const key = (entry) => `${entry.type}\u0000${entry.id}`;
|
|
219
|
-
return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0;
|
|
220
|
-
});
|
|
221
|
-
const manifest = {
|
|
222
|
-
version: 1,
|
|
223
|
-
workflow: metadata,
|
|
224
|
-
triggers,
|
|
225
|
-
graph: await extractWorkflowGraph(workflow.handler)
|
|
226
|
-
};
|
|
227
|
-
toJson(manifest, "manifest");
|
|
228
|
-
manifests.push(manifest);
|
|
229
|
-
}
|
|
230
|
-
return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
|
|
231
|
-
}
|
|
232
|
-
//#endregion
|
|
233
|
-
export { defineSchedule as a, weekly as c, registerWorkflows as i, createMiddleware as n, daily as o, createWorkflow as r, hourly as s, generateManifests as t };
|
package/dist/graph-BgdiEUHq.js
DELETED
|
@@ -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 };
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { AnyWorkflowDefinition, RunStore, WorkflowEvent } from "@tanstack/workflow-core";
|
|
2
|
-
//#region src/stacks/tanstack/handlers.d.ts
|
|
3
|
-
/** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
|
|
4
|
-
interface WorkflowCollection {
|
|
5
|
-
readonly workflows: readonly AnyWorkflowDefinition[];
|
|
6
|
-
}
|
|
7
|
-
interface TanStackWorkflowHandlerOptions {
|
|
8
|
-
/** @default a process-local `inMemoryRunStore()`, lost on restart */
|
|
9
|
-
runStore?: RunStore;
|
|
10
|
-
/**
|
|
11
|
-
* Route parameter carrying the workflow ID.
|
|
12
|
-
* @default "workflowId"
|
|
13
|
-
*/
|
|
14
|
-
workflowIdParam?: string;
|
|
15
|
-
}
|
|
16
|
-
interface TanStackRouteCtx {
|
|
17
|
-
request: Request;
|
|
18
|
-
params?: Record<string, string | undefined>;
|
|
19
|
-
}
|
|
20
|
-
type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
|
|
21
|
-
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
22
|
-
declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
|
|
23
|
-
//#endregion
|
|
24
|
-
//#region src/stacks/tanstack/sse.d.ts
|
|
25
|
-
/**
|
|
26
|
-
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
27
|
-
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
28
|
-
*/
|
|
29
|
-
declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
|
|
30
|
-
//#endregion
|
|
31
|
-
export { type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type WorkflowCollection, createTanStackWorkflowHandler, toServerSentEventsResponse };
|
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
|
|
2
|
-
//#region src/stacks/tanstack/sse.ts
|
|
3
|
-
const HEADERS = {
|
|
4
|
-
"content-type": "text/event-stream; charset=utf-8",
|
|
5
|
-
"cache-control": "no-cache, no-transform",
|
|
6
|
-
connection: "keep-alive",
|
|
7
|
-
"x-accel-buffering": "no"
|
|
8
|
-
};
|
|
9
|
-
function describe(error) {
|
|
10
|
-
return error instanceof Error ? error.message : String(error);
|
|
11
|
-
}
|
|
12
|
-
function frame(name, data) {
|
|
13
|
-
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
17
|
-
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
18
|
-
*/
|
|
19
|
-
function toServerSentEventsResponse(events) {
|
|
20
|
-
const encoder = new TextEncoder();
|
|
21
|
-
const body = new ReadableStream({ async start(controller) {
|
|
22
|
-
let connected = true;
|
|
23
|
-
const write = (text) => {
|
|
24
|
-
if (!connected) return;
|
|
25
|
-
try {
|
|
26
|
-
controller.enqueue(encoder.encode(text));
|
|
27
|
-
} catch {
|
|
28
|
-
connected = false;
|
|
29
|
-
}
|
|
30
|
-
};
|
|
31
|
-
const send = (name, data) => {
|
|
32
|
-
try {
|
|
33
|
-
write(frame(name, data));
|
|
34
|
-
} catch (error) {
|
|
35
|
-
write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe(error)}` }));
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
try {
|
|
39
|
-
for await (const event of events) send(event.type, event);
|
|
40
|
-
} catch (error) {
|
|
41
|
-
send("STREAM_ERRORED", { message: describe(error) });
|
|
42
|
-
} finally {
|
|
43
|
-
try {
|
|
44
|
-
controller.close();
|
|
45
|
-
} catch {
|
|
46
|
-
connected = false;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
} });
|
|
50
|
-
return new Response(body, { headers: HEADERS });
|
|
51
|
-
}
|
|
52
|
-
//#endregion
|
|
53
|
-
//#region src/stacks/tanstack/handlers.ts
|
|
54
|
-
function json(status, body) {
|
|
55
|
-
return new Response(JSON.stringify(body), {
|
|
56
|
-
status,
|
|
57
|
-
headers: { "content-type": "application/json; charset=utf-8" }
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
function resolveWorkflowId(ctx, param) {
|
|
61
|
-
const fromParams = ctx.params?.[param];
|
|
62
|
-
if (fromParams) return fromParams;
|
|
63
|
-
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
|
|
64
|
-
}
|
|
65
|
-
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
66
|
-
function createTanStackWorkflowHandler(collection, options = {}) {
|
|
67
|
-
const runStore = options.runStore ?? inMemoryRunStore();
|
|
68
|
-
const param = options.workflowIdParam ?? "workflowId";
|
|
69
|
-
const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
|
|
70
|
-
return async (ctx) => {
|
|
71
|
-
const workflowId = resolveWorkflowId(ctx, param);
|
|
72
|
-
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
73
|
-
if (!workflow) return json(404, {
|
|
74
|
-
error: "unknown_workflow",
|
|
75
|
-
workflowId: workflowId ?? ""
|
|
76
|
-
});
|
|
77
|
-
let params;
|
|
78
|
-
try {
|
|
79
|
-
params = await parseWorkflowRequest(ctx.request);
|
|
80
|
-
} catch (error) {
|
|
81
|
-
if (error instanceof WorkflowRequestParseError) return json(400, {
|
|
82
|
-
error: "invalid_request",
|
|
83
|
-
message: error.message
|
|
84
|
-
});
|
|
85
|
-
throw error;
|
|
86
|
-
}
|
|
87
|
-
if (params.abort) return json(501, {
|
|
88
|
-
error: "abort_unsupported",
|
|
89
|
-
message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
|
|
90
|
-
});
|
|
91
|
-
return toServerSentEventsResponse(runWorkflow({
|
|
92
|
-
workflow,
|
|
93
|
-
runStore,
|
|
94
|
-
...params
|
|
95
|
-
}));
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
//#endregion
|
|
99
|
-
export { createTanStackWorkflowHandler, toServerSentEventsResponse };
|