@lovable.dev/workflows-sdk 0.0.0-dev.2 → 0.0.0-dev.21
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 +580 -40
- package/dist/branch-metadata-D3f-8DT-.js +111 -0
- package/dist/context-escapes-DPKbDPIx.js +78 -0
- package/dist/duplicate-ids-C4Ug3kFs.js +166 -0
- package/dist/durable-ids-LsygHSZC.js +17 -0
- package/dist/generate-CrIdSenf.js +279 -0
- package/dist/graph-BDLuv4B_.js +538 -0
- package/dist/index.d.ts +280 -26
- package/dist/index.js +555 -3
- package/dist/nested-operations-IG6_OTsi.js +54 -0
- package/dist/operation-descriptions-DWsquPYE.js +46 -0
- package/dist/step-metadata-CPpfxR2q.js +64 -0
- package/dist/vite.d.ts +18 -5
- package/dist/vite.js +293 -9
- package/package.json +3 -2
- package/dist/graph-extract-CGLWzaln.js +0 -119
- package/dist/manifest-DIeHMgS8.js +0 -114
package/dist/index.js
CHANGED
|
@@ -1,3 +1,555 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { a as defineSchedule, c as weekly, i as registerWorkflows, n as createMiddleware, o as daily, r as createWorkflow, s as hourly, t as generateManifests } from "./generate-CrIdSenf.js";
|
|
2
|
+
import { t as defaultDurableId } from "./durable-ids-LsygHSZC.js";
|
|
3
|
+
import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
|
|
4
|
+
//#region src/stacks/tanstack/sse.ts
|
|
5
|
+
const HEADERS = {
|
|
6
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
7
|
+
"cache-control": "no-cache, no-transform",
|
|
8
|
+
connection: "keep-alive",
|
|
9
|
+
"x-accel-buffering": "no"
|
|
10
|
+
};
|
|
11
|
+
function describe$1(error) {
|
|
12
|
+
return error instanceof Error ? error.message : String(error);
|
|
13
|
+
}
|
|
14
|
+
function frame(name, data) {
|
|
15
|
+
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
19
|
+
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
20
|
+
*/
|
|
21
|
+
function toServerSentEventsResponse(events) {
|
|
22
|
+
const encoder = new TextEncoder();
|
|
23
|
+
const body = new ReadableStream({ async start(controller) {
|
|
24
|
+
let connected = true;
|
|
25
|
+
const write = (text) => {
|
|
26
|
+
if (!connected) return;
|
|
27
|
+
try {
|
|
28
|
+
controller.enqueue(encoder.encode(text));
|
|
29
|
+
} catch {
|
|
30
|
+
connected = false;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
const send = (name, data) => {
|
|
34
|
+
try {
|
|
35
|
+
write(frame(name, data));
|
|
36
|
+
} catch (error) {
|
|
37
|
+
write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
try {
|
|
41
|
+
for await (const event of events) send(event.type, event);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
send("STREAM_ERRORED", { message: describe$1(error) });
|
|
44
|
+
} finally {
|
|
45
|
+
try {
|
|
46
|
+
controller.close();
|
|
47
|
+
} catch {
|
|
48
|
+
connected = false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
} });
|
|
52
|
+
return new Response(body, { headers: HEADERS });
|
|
53
|
+
}
|
|
54
|
+
//#endregion
|
|
55
|
+
//#region src/stacks/tanstack/handlers.ts
|
|
56
|
+
function json$1(status, body) {
|
|
57
|
+
return new Response(JSON.stringify(body), {
|
|
58
|
+
status,
|
|
59
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
function resolveWorkflowId$1(ctx, param) {
|
|
63
|
+
const fromParams = ctx.params?.[param];
|
|
64
|
+
if (fromParams) return fromParams;
|
|
65
|
+
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
|
|
66
|
+
}
|
|
67
|
+
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
68
|
+
function createTanStackWorkflowHandler(collection, options = {}) {
|
|
69
|
+
const runStore = options.runStore ?? inMemoryRunStore();
|
|
70
|
+
const param = options.workflowIdParam ?? "workflowId";
|
|
71
|
+
const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
|
|
72
|
+
return async (ctx) => {
|
|
73
|
+
const workflowId = resolveWorkflowId$1(ctx, param);
|
|
74
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
75
|
+
if (!workflow) return json$1(404, {
|
|
76
|
+
error: "unknown_workflow",
|
|
77
|
+
workflowId: workflowId ?? ""
|
|
78
|
+
});
|
|
79
|
+
let params;
|
|
80
|
+
try {
|
|
81
|
+
params = await parseWorkflowRequest(ctx.request);
|
|
82
|
+
} catch (error) {
|
|
83
|
+
if (error instanceof WorkflowRequestParseError) return json$1(400, {
|
|
84
|
+
error: "invalid_request",
|
|
85
|
+
message: error.message
|
|
86
|
+
});
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
if (params.abort) return json$1(501, {
|
|
90
|
+
error: "abort_unsupported",
|
|
91
|
+
message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
|
|
92
|
+
});
|
|
93
|
+
return toServerSentEventsResponse(runWorkflow({
|
|
94
|
+
workflow,
|
|
95
|
+
runStore,
|
|
96
|
+
...params
|
|
97
|
+
}));
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region src/runtime/input-hash.ts
|
|
102
|
+
/** Key order must not change the hash, so objects are serialized sorted. */
|
|
103
|
+
function canonical(value) {
|
|
104
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
105
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
106
|
+
return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Identifies the input a run started with. A resume carries it back so replay
|
|
110
|
+
* cannot be pointed at a different record than the one its memo came from.
|
|
111
|
+
*/
|
|
112
|
+
async function hashInput(input) {
|
|
113
|
+
const bytes = new TextEncoder().encode(canonical(input));
|
|
114
|
+
const digest = await crypto.subtle.digest("SHA-256", bytes);
|
|
115
|
+
return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
//#region src/runtime/replay.ts
|
|
119
|
+
/** How long a pass waits for handler work that is not a durable operation. */
|
|
120
|
+
const DEFAULT_SETTLE_MS = 5e3;
|
|
121
|
+
function memoKey(stepId, occurrence) {
|
|
122
|
+
return `${stepId}#${occurrence}`;
|
|
123
|
+
}
|
|
124
|
+
const EXECUTABLE = /* @__PURE__ */ new Set([
|
|
125
|
+
"step",
|
|
126
|
+
"now",
|
|
127
|
+
"uuid"
|
|
128
|
+
]);
|
|
129
|
+
function describe(error) {
|
|
130
|
+
return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
|
|
131
|
+
}
|
|
132
|
+
function groupId(meta) {
|
|
133
|
+
const group = meta?.group;
|
|
134
|
+
if (group === null || typeof group !== "object") return void 0;
|
|
135
|
+
const id = group.id;
|
|
136
|
+
return typeof id === "string" ? id : void 0;
|
|
137
|
+
}
|
|
138
|
+
function runtimeContext() {
|
|
139
|
+
return {
|
|
140
|
+
timeRemaining: () => Number.POSITIVE_INFINITY,
|
|
141
|
+
shouldYield: () => false,
|
|
142
|
+
yield: async () => {}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
/** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
|
|
146
|
+
async function throughMiddleware(middlewares, ctx, handler) {
|
|
147
|
+
let index = 0;
|
|
148
|
+
const dispatch = async () => {
|
|
149
|
+
const middleware = middlewares[index++];
|
|
150
|
+
if (!middleware) return handler(ctx);
|
|
151
|
+
return middleware.server({
|
|
152
|
+
ctx,
|
|
153
|
+
next: async ({ context }) => {
|
|
154
|
+
Object.assign(ctx, context);
|
|
155
|
+
return dispatch();
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
};
|
|
159
|
+
return dispatch();
|
|
160
|
+
}
|
|
161
|
+
async function replay(options) {
|
|
162
|
+
const { workflow, input, runId } = options;
|
|
163
|
+
const byKey = new Map(options.memo.map((entry) => [memoKey(entry.stepId, entry.occurrence ?? 0), entry]));
|
|
164
|
+
const allow = options.shouldExecute ?? (() => true);
|
|
165
|
+
const never = new Promise(() => {});
|
|
166
|
+
const pending = [];
|
|
167
|
+
const settled = /* @__PURE__ */ new Map();
|
|
168
|
+
const pass = { stepsSettled: 0 };
|
|
169
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
170
|
+
const consumed = /* @__PURE__ */ new Set();
|
|
171
|
+
let lastProgress = Date.now();
|
|
172
|
+
let currentParent;
|
|
173
|
+
const results = [];
|
|
174
|
+
const emitted = [];
|
|
175
|
+
const inflight = [];
|
|
176
|
+
let seq = 0;
|
|
177
|
+
let nonDeterminism;
|
|
178
|
+
function record(entry) {
|
|
179
|
+
settled.set(memoKey(entry.stepId, entry.occurrence), entry);
|
|
180
|
+
lastProgress = Date.now();
|
|
181
|
+
if (entry.kind === "step") pass.stepsSettled += 1;
|
|
182
|
+
const result = {
|
|
183
|
+
seq: entry.seq,
|
|
184
|
+
stepId: entry.stepId,
|
|
185
|
+
occurrence: entry.occurrence,
|
|
186
|
+
kind: entry.kind,
|
|
187
|
+
...entry.meta ? { meta: entry.meta } : {},
|
|
188
|
+
status: entry.status,
|
|
189
|
+
result: entry.result,
|
|
190
|
+
error: entry.error
|
|
191
|
+
};
|
|
192
|
+
results.push(result);
|
|
193
|
+
options.onStepSettle?.(result);
|
|
194
|
+
}
|
|
195
|
+
function durable(kind, stepId, run, config, defaulted = false, meta) {
|
|
196
|
+
const index = seq++;
|
|
197
|
+
const occurrence = occurrences.get(stepId) ?? 0;
|
|
198
|
+
occurrences.set(stepId, occurrence + 1);
|
|
199
|
+
if (kind === "step" && occurrence > 0) {
|
|
200
|
+
nonDeterminism = `ctx.step() was reached more than once with id "${stepId}"; every step id must be unique within a workflow`;
|
|
201
|
+
return never;
|
|
202
|
+
}
|
|
203
|
+
if (defaulted && occurrence > 0) {
|
|
204
|
+
nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
|
|
205
|
+
return never;
|
|
206
|
+
}
|
|
207
|
+
const key = memoKey(stepId, occurrence);
|
|
208
|
+
consumed.add(key);
|
|
209
|
+
const answered = byKey.get(key) ?? settled.get(key);
|
|
210
|
+
if (answered) {
|
|
211
|
+
if (answered.kind !== kind) {
|
|
212
|
+
nonDeterminism = `memo has ${answered.kind} "${stepId}" (#${occurrence}), replay produced ${kind}`;
|
|
213
|
+
return never;
|
|
214
|
+
}
|
|
215
|
+
const recordedGroupId = groupId(answered.meta);
|
|
216
|
+
if (recordedGroupId !== void 0 && recordedGroupId !== groupId(meta)) {
|
|
217
|
+
nonDeterminism = `memo has group "${recordedGroupId}" for step "${stepId}", replay produced a different group`;
|
|
218
|
+
return never;
|
|
219
|
+
}
|
|
220
|
+
if (answered.status === "completed") return Promise.resolve(answered.result);
|
|
221
|
+
return Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`));
|
|
222
|
+
}
|
|
223
|
+
const parent = currentParent;
|
|
224
|
+
const intent = {
|
|
225
|
+
seq: index,
|
|
226
|
+
stepId,
|
|
227
|
+
occurrence,
|
|
228
|
+
kind,
|
|
229
|
+
...config ? { config } : {},
|
|
230
|
+
...meta ? { meta } : {}
|
|
231
|
+
};
|
|
232
|
+
if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
|
|
233
|
+
pending.push(intent);
|
|
234
|
+
return never;
|
|
235
|
+
}
|
|
236
|
+
options.onStepStart?.(intent);
|
|
237
|
+
const enclosing = currentParent;
|
|
238
|
+
currentParent = key;
|
|
239
|
+
let body;
|
|
240
|
+
try {
|
|
241
|
+
body = run();
|
|
242
|
+
} finally {
|
|
243
|
+
currentParent = enclosing;
|
|
244
|
+
}
|
|
245
|
+
const running = body.then((result) => {
|
|
246
|
+
record({
|
|
247
|
+
seq: index,
|
|
248
|
+
stepId,
|
|
249
|
+
occurrence,
|
|
250
|
+
kind,
|
|
251
|
+
status: "completed",
|
|
252
|
+
result,
|
|
253
|
+
...parent ? { parent } : {},
|
|
254
|
+
...meta ? { meta } : {}
|
|
255
|
+
});
|
|
256
|
+
return result;
|
|
257
|
+
}, (error) => {
|
|
258
|
+
record({
|
|
259
|
+
seq: index,
|
|
260
|
+
stepId,
|
|
261
|
+
occurrence,
|
|
262
|
+
kind,
|
|
263
|
+
status: "failed",
|
|
264
|
+
error: describe(error),
|
|
265
|
+
...parent ? { parent } : {},
|
|
266
|
+
...meta ? { meta } : {}
|
|
267
|
+
});
|
|
268
|
+
throw error;
|
|
269
|
+
});
|
|
270
|
+
inflight.push(running.then(noop, noop));
|
|
271
|
+
return running;
|
|
272
|
+
}
|
|
273
|
+
const state = { ...workflow.initialize?.({ input }) };
|
|
274
|
+
const runtime = runtimeContext();
|
|
275
|
+
const controller = new AbortController();
|
|
276
|
+
const ctx = {
|
|
277
|
+
runId,
|
|
278
|
+
input,
|
|
279
|
+
state,
|
|
280
|
+
signal: controller.signal,
|
|
281
|
+
runtime,
|
|
282
|
+
step: (id, fn, stepOptions) => durable("step", id, async () => fn({
|
|
283
|
+
id,
|
|
284
|
+
attempt: 1,
|
|
285
|
+
runtime,
|
|
286
|
+
signal: controller.signal
|
|
287
|
+
}), void 0, false, stepOptions?.meta),
|
|
288
|
+
sleep: (ms, opts) => durable("sleep", opts?.id ?? defaultDurableId({
|
|
289
|
+
kind: "sleep",
|
|
290
|
+
ms
|
|
291
|
+
}), void 0, { ms }, opts?.id === void 0, opts?.meta),
|
|
292
|
+
sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? defaultDurableId({
|
|
293
|
+
kind: "sleepUntil",
|
|
294
|
+
timestamp
|
|
295
|
+
}), void 0, { timestamp }, opts?.id === void 0, opts?.meta),
|
|
296
|
+
waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? defaultDurableId({
|
|
297
|
+
kind: "waitForEvent",
|
|
298
|
+
name
|
|
299
|
+
}), void 0, { name }, opts?.id === void 0, opts?.meta),
|
|
300
|
+
approve: (opts) => durable("approve", opts.id ?? defaultDurableId({
|
|
301
|
+
kind: "approve",
|
|
302
|
+
title: opts.title
|
|
303
|
+
}), void 0, {
|
|
304
|
+
title: opts.title,
|
|
305
|
+
...opts.description === void 0 ? {} : { description: opts.description }
|
|
306
|
+
}, opts.id === void 0, {
|
|
307
|
+
...opts.meta,
|
|
308
|
+
...opts.description === void 0 ? {} : { description: opts.description }
|
|
309
|
+
}),
|
|
310
|
+
now: (opts) => durable("now", opts?.id ?? defaultDurableId({ kind: "now" }), async () => Date.now(), void 0, opts?.id === void 0, opts?.meta),
|
|
311
|
+
uuid: (opts) => durable("uuid", opts?.id ?? defaultDurableId({ kind: "uuid" }), async () => crypto.randomUUID(), void 0, opts?.id === void 0, opts?.meta),
|
|
312
|
+
emit: (name, value) => {
|
|
313
|
+
emitted.push({
|
|
314
|
+
name,
|
|
315
|
+
value
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
let outcome;
|
|
320
|
+
throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
|
|
321
|
+
outcome = {
|
|
322
|
+
status: "completed",
|
|
323
|
+
output: output ?? null
|
|
324
|
+
};
|
|
325
|
+
}, (error) => {
|
|
326
|
+
outcome = {
|
|
327
|
+
status: "failed",
|
|
328
|
+
error: describe(error)
|
|
329
|
+
};
|
|
330
|
+
});
|
|
331
|
+
const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
|
|
332
|
+
for (;;) {
|
|
333
|
+
for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
|
|
334
|
+
if (outcome || nonDeterminism) break;
|
|
335
|
+
if (inflight.length > 0) {
|
|
336
|
+
await Promise.all(inflight.splice(0));
|
|
337
|
+
lastProgress = Date.now();
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
|
|
341
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
342
|
+
}
|
|
343
|
+
while (inflight.length > 0) await Promise.all(inflight.splice(0));
|
|
344
|
+
const memo = [...byKey.values(), ...settled.values()];
|
|
345
|
+
const hidden = (start) => {
|
|
346
|
+
const seen = /* @__PURE__ */ new Set([start]);
|
|
347
|
+
let key = start;
|
|
348
|
+
for (;;) {
|
|
349
|
+
const parent = byKey.get(key)?.parent;
|
|
350
|
+
if (parent === void 0 || seen.has(parent)) return false;
|
|
351
|
+
if (consumed.has(parent)) return true;
|
|
352
|
+
seen.add(parent);
|
|
353
|
+
key = parent;
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key));
|
|
357
|
+
pending.sort((a, b) => a.seq - b.seq);
|
|
358
|
+
results.sort((a, b) => a.seq - b.seq);
|
|
359
|
+
const base = {
|
|
360
|
+
memo,
|
|
361
|
+
results,
|
|
362
|
+
emitted
|
|
363
|
+
};
|
|
364
|
+
if (nonDeterminism) return {
|
|
365
|
+
...base,
|
|
366
|
+
status: "failed",
|
|
367
|
+
steps: [],
|
|
368
|
+
error: `non-deterministic replay: ${nonDeterminism}`
|
|
369
|
+
};
|
|
370
|
+
if (orphan !== void 0) return {
|
|
371
|
+
...base,
|
|
372
|
+
status: "failed",
|
|
373
|
+
steps: [],
|
|
374
|
+
error: `stale memo: no operation matched "${orphan}"`
|
|
375
|
+
};
|
|
376
|
+
if (outcome?.status === "completed") return {
|
|
377
|
+
...base,
|
|
378
|
+
status: "completed",
|
|
379
|
+
steps: [],
|
|
380
|
+
output: outcome.output
|
|
381
|
+
};
|
|
382
|
+
if (outcome?.status === "failed") return {
|
|
383
|
+
...base,
|
|
384
|
+
status: "failed",
|
|
385
|
+
steps: [],
|
|
386
|
+
error: outcome.error
|
|
387
|
+
};
|
|
388
|
+
if (pending.length > 0) return {
|
|
389
|
+
...base,
|
|
390
|
+
status: "pending",
|
|
391
|
+
steps: pending
|
|
392
|
+
};
|
|
393
|
+
return {
|
|
394
|
+
...base,
|
|
395
|
+
status: "failed",
|
|
396
|
+
steps: [],
|
|
397
|
+
error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function noop() {}
|
|
401
|
+
//#endregion
|
|
402
|
+
//#region src/stacks/tanstack/steps.ts
|
|
403
|
+
function json(status, body) {
|
|
404
|
+
return new Response(JSON.stringify(body), {
|
|
405
|
+
status,
|
|
406
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
function resolveWorkflowId(ctx, param) {
|
|
410
|
+
const fromParams = ctx.params?.[param];
|
|
411
|
+
if (fromParams) return fromParams;
|
|
412
|
+
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
|
|
413
|
+
}
|
|
414
|
+
function isMemoEntry(value) {
|
|
415
|
+
const entry = value;
|
|
416
|
+
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");
|
|
417
|
+
}
|
|
418
|
+
function parseBody(value) {
|
|
419
|
+
if (value === null || typeof value !== "object") return "body must be a JSON object";
|
|
420
|
+
const body = value;
|
|
421
|
+
if (body.memo !== void 0) {
|
|
422
|
+
if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
|
|
423
|
+
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";
|
|
424
|
+
}
|
|
425
|
+
if (body.action !== void 0 && body.action !== "advance" && body.action !== "execute") return "action must be \"advance\" or \"execute\"";
|
|
426
|
+
if (body.action === "execute" && !isStepReference(body.step)) return "step must be a { kind: \"step\", stepId, occurrence } reference when action is \"execute\"";
|
|
427
|
+
if (body.action !== "execute" && body.step !== void 0) return "step is only valid when action is \"execute\"";
|
|
428
|
+
if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
|
|
429
|
+
return body;
|
|
430
|
+
}
|
|
431
|
+
async function readBody(request) {
|
|
432
|
+
const text = await request.text();
|
|
433
|
+
if (!text.trim()) return {};
|
|
434
|
+
return JSON.parse(text);
|
|
435
|
+
}
|
|
436
|
+
function operationKey(operation) {
|
|
437
|
+
return memoKey(operation.stepId, operation.occurrence);
|
|
438
|
+
}
|
|
439
|
+
function isStepReference(value) {
|
|
440
|
+
const step = value;
|
|
441
|
+
return typeof step === "object" && step !== null && step.kind === "step" && typeof step.stepId === "string" && Number.isInteger(step.occurrence) && step.occurrence >= 0;
|
|
442
|
+
}
|
|
443
|
+
function disposition(outcome) {
|
|
444
|
+
if (outcome.status === "completed") return "completed";
|
|
445
|
+
if (outcome.status === "failed") return "failed";
|
|
446
|
+
if (!outcome.steps.some((step) => step.kind === "step")) return "waiting";
|
|
447
|
+
return outcome.steps.length > 1 ? "fork" : "advanced";
|
|
448
|
+
}
|
|
449
|
+
function memoDelta(before, after) {
|
|
450
|
+
const existing = new Set(before.map((entry) => memoKey(entry.stepId, entry.occurrence)));
|
|
451
|
+
return after.filter((entry) => !existing.has(memoKey(entry.stepId, entry.occurrence)));
|
|
452
|
+
}
|
|
453
|
+
function respond(runId, inputHash, before, outcome, executed) {
|
|
454
|
+
const { steps, emitted, output, error } = outcome;
|
|
455
|
+
return json(200, {
|
|
456
|
+
runId,
|
|
457
|
+
inputHash,
|
|
458
|
+
disposition: disposition(outcome),
|
|
459
|
+
memoDelta: memoDelta(before, outcome.memo),
|
|
460
|
+
next: steps,
|
|
461
|
+
...executed === void 0 ? {} : { executed },
|
|
462
|
+
...emitted.length > 0 ? { emitted } : {},
|
|
463
|
+
...output === void 0 ? {} : { output },
|
|
464
|
+
...error === void 0 ? {} : { error }
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
function prepare(collection, options) {
|
|
468
|
+
return {
|
|
469
|
+
param: options.workflowIdParam ?? "workflowId",
|
|
470
|
+
byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow]))
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
async function resolve(ctx, param, byId) {
|
|
474
|
+
const workflowId = resolveWorkflowId(ctx, param);
|
|
475
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
476
|
+
if (!workflow) return json(404, {
|
|
477
|
+
error: "unknown_workflow",
|
|
478
|
+
workflowId: workflowId ?? ""
|
|
479
|
+
});
|
|
480
|
+
let raw;
|
|
481
|
+
try {
|
|
482
|
+
raw = await readBody(ctx.request);
|
|
483
|
+
} catch (error) {
|
|
484
|
+
return json(400, {
|
|
485
|
+
error: "invalid_request",
|
|
486
|
+
message: `body is not valid JSON: ${String(error)}`
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
const body = parseBody(raw);
|
|
490
|
+
if (typeof body === "string") return json(400, {
|
|
491
|
+
error: "invalid_request",
|
|
492
|
+
message: body
|
|
493
|
+
});
|
|
494
|
+
const inputHash = await hashInput(body.input ?? null);
|
|
495
|
+
if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
|
|
496
|
+
error: "invalid_request",
|
|
497
|
+
message: body.inputHash === void 0 ? "inputHash must be sent with a memo; echo the value from the previous response" : "input does not match the run this memo came from"
|
|
498
|
+
});
|
|
499
|
+
return {
|
|
500
|
+
workflow,
|
|
501
|
+
body,
|
|
502
|
+
runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
|
|
503
|
+
inputHash
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
function createStepsHandler(collection, options = {}) {
|
|
507
|
+
const { param, byId } = prepare(collection, options);
|
|
508
|
+
return async (ctx) => {
|
|
509
|
+
const resolved = await resolve(ctx, param, byId);
|
|
510
|
+
if (resolved instanceof Response) return resolved;
|
|
511
|
+
const { workflow, body, runId, inputHash } = resolved;
|
|
512
|
+
const input = body.input ?? null;
|
|
513
|
+
const before = body.memo ?? [];
|
|
514
|
+
if (body.action === "execute") {
|
|
515
|
+
const selected = body.step;
|
|
516
|
+
const outcome = await replay({
|
|
517
|
+
workflow,
|
|
518
|
+
input,
|
|
519
|
+
memo: before,
|
|
520
|
+
runId,
|
|
521
|
+
shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(selected)
|
|
522
|
+
});
|
|
523
|
+
const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(selected));
|
|
524
|
+
if (executed === void 0 && outcome.status !== "failed") return json(409, {
|
|
525
|
+
error: "stale_step",
|
|
526
|
+
message: `step "${selected.stepId}" (#${selected.occurrence}) is not executable from this memo`
|
|
527
|
+
});
|
|
528
|
+
return respond(runId, inputHash, before, outcome, executed);
|
|
529
|
+
}
|
|
530
|
+
const described = await replay({
|
|
531
|
+
workflow,
|
|
532
|
+
input,
|
|
533
|
+
memo: before,
|
|
534
|
+
runId,
|
|
535
|
+
shouldExecute: (intent) => intent.kind !== "step"
|
|
536
|
+
});
|
|
537
|
+
const only = described.steps.length === 1 ? described.steps[0] : void 0;
|
|
538
|
+
if (described.status !== "pending" || only?.kind !== "step") return respond(runId, inputHash, before, described);
|
|
539
|
+
const outcome = await replay({
|
|
540
|
+
workflow,
|
|
541
|
+
input,
|
|
542
|
+
memo: described.memo,
|
|
543
|
+
runId,
|
|
544
|
+
shouldExecute: (intent) => intent.kind !== "step" || operationKey(intent) === operationKey(only)
|
|
545
|
+
});
|
|
546
|
+
const executed = outcome.results.find((result) => result.kind === "step" && operationKey(result) === operationKey(only));
|
|
547
|
+
if (executed === void 0 && outcome.status !== "failed") return json(409, {
|
|
548
|
+
error: "stale_step",
|
|
549
|
+
message: `step "${only.stepId}" (#${only.occurrence}) is not executable from this memo`
|
|
550
|
+
});
|
|
551
|
+
return respond(runId, inputHash, before, outcome, executed);
|
|
552
|
+
};
|
|
553
|
+
}
|
|
554
|
+
//#endregion
|
|
555
|
+
export { createMiddleware, createStepsHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { loadTypeScript, t as workflowHandlerSource } from "./graph-BDLuv4B_.js";
|
|
2
|
+
//#region src/manifests/nested-operations.ts
|
|
3
|
+
const durableMethods = [
|
|
4
|
+
"step",
|
|
5
|
+
"approve",
|
|
6
|
+
"waitForEvent",
|
|
7
|
+
"sleep",
|
|
8
|
+
"sleepUntil",
|
|
9
|
+
"now",
|
|
10
|
+
"uuid"
|
|
11
|
+
];
|
|
12
|
+
async function findNestedDurableOperations(handler) {
|
|
13
|
+
const api = await loadTypeScript();
|
|
14
|
+
if (!api) return [];
|
|
15
|
+
const ts = api;
|
|
16
|
+
const handlerSource = workflowHandlerSource(handler);
|
|
17
|
+
if (!handlerSource) return [];
|
|
18
|
+
const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
|
|
19
|
+
const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
|
|
20
|
+
if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
|
|
21
|
+
const parameter = fn.parameters[0]?.name;
|
|
22
|
+
if (!parameter || !ts.isIdentifier(parameter)) return [];
|
|
23
|
+
const context = parameter.text;
|
|
24
|
+
function methodOf(node) {
|
|
25
|
+
if (!ts.isCallExpression(node)) return void 0;
|
|
26
|
+
const expression = node.expression;
|
|
27
|
+
let name;
|
|
28
|
+
if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context) name = expression.name.text;
|
|
29
|
+
else if (ts.isElementAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context && expression.argumentExpression && (ts.isStringLiteral(expression.argumentExpression) || ts.isNoSubstitutionTemplateLiteral(expression.argumentExpression))) name = expression.argumentExpression.text;
|
|
30
|
+
return durableMethods.find((method) => method === name);
|
|
31
|
+
}
|
|
32
|
+
function stepIdOf(node) {
|
|
33
|
+
const argument = node.arguments[0];
|
|
34
|
+
return argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : void 0;
|
|
35
|
+
}
|
|
36
|
+
const nested = [];
|
|
37
|
+
const visit = (node, parentStepId) => {
|
|
38
|
+
const method = methodOf(node);
|
|
39
|
+
if (method && parentStepId !== void 0) nested.push({
|
|
40
|
+
method,
|
|
41
|
+
parentStepId
|
|
42
|
+
});
|
|
43
|
+
if (method === "step" && ts.isCallExpression(node)) {
|
|
44
|
+
visit(node.expression, parentStepId);
|
|
45
|
+
node.arguments.forEach((argument, index) => visit(argument, index === 1 ? stepIdOf(node) ?? "" : parentStepId));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
ts.forEachChild(node, (child) => visit(child, parentStepId));
|
|
49
|
+
};
|
|
50
|
+
visit(fn);
|
|
51
|
+
return nested;
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
export { findNestedDurableOperations };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { loadTypeScript, t as workflowHandlerSource } from "./graph-BDLuv4B_.js";
|
|
2
|
+
//#region src/manifests/operation-descriptions.ts
|
|
3
|
+
const optionsArgument = {
|
|
4
|
+
approve: 0,
|
|
5
|
+
sleep: 1,
|
|
6
|
+
sleepUntil: 1,
|
|
7
|
+
waitForEvent: 1,
|
|
8
|
+
now: 0,
|
|
9
|
+
uuid: 0
|
|
10
|
+
};
|
|
11
|
+
async function findOperationDescriptionIssues(handler) {
|
|
12
|
+
const api = await loadTypeScript();
|
|
13
|
+
if (!api) return [];
|
|
14
|
+
const ts = api;
|
|
15
|
+
const handlerSource = workflowHandlerSource(handler);
|
|
16
|
+
if (!handlerSource) return [];
|
|
17
|
+
const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
|
|
18
|
+
const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
|
|
19
|
+
if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
|
|
20
|
+
const parameter = fn.parameters[0]?.name;
|
|
21
|
+
if (!parameter || !ts.isIdentifier(parameter)) return [];
|
|
22
|
+
const context = parameter.text;
|
|
23
|
+
function literalString(node) {
|
|
24
|
+
return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
|
|
25
|
+
}
|
|
26
|
+
function property(node, name) {
|
|
27
|
+
if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
|
|
28
|
+
for (const entry of node.properties) {
|
|
29
|
+
if (!ts.isPropertyAssignment(entry)) continue;
|
|
30
|
+
if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const issues = [];
|
|
34
|
+
const visit = (node) => {
|
|
35
|
+
if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
|
|
36
|
+
const method = node.expression.name.text;
|
|
37
|
+
const options = node.arguments[optionsArgument[method]];
|
|
38
|
+
if ((method === "approve" ? literalString(property(options, "description")) : literalString(property(property(options, "meta"), "description"))) === void 0) issues.push({ method });
|
|
39
|
+
}
|
|
40
|
+
ts.forEachChild(node, visit);
|
|
41
|
+
};
|
|
42
|
+
visit(fn);
|
|
43
|
+
return issues;
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { findOperationDescriptionIssues };
|