@lovable.dev/workflows-sdk 0.0.0-dev → 0.0.0-dev.10

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/dist/index.js CHANGED
@@ -1,3 +1,650 @@
1
- import { n as registerWorkflows, r as defineSchedule, t as generateManifests } from "./manifest-jkqqGByV.js";
2
- import { createMiddleware, createWorkflow } from "@tanstack/workflow-core";
3
- export { createMiddleware, createWorkflow, defineSchedule, generateManifests, registerWorkflows };
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-DyUHbtre.js";
2
+ import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
3
+ //#region src/stacks/tanstack/sse.ts
4
+ const HEADERS = {
5
+ "content-type": "text/event-stream; charset=utf-8",
6
+ "cache-control": "no-cache, no-transform",
7
+ connection: "keep-alive",
8
+ "x-accel-buffering": "no"
9
+ };
10
+ function describe$1(error) {
11
+ return error instanceof Error ? error.message : String(error);
12
+ }
13
+ function frame(name, data) {
14
+ return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
15
+ }
16
+ /**
17
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
18
+ * engine `type` as the SSE event name and its whole JSON as the data line.
19
+ */
20
+ function toServerSentEventsResponse(events) {
21
+ const encoder = new TextEncoder();
22
+ const body = new ReadableStream({ async start(controller) {
23
+ let connected = true;
24
+ const write = (text) => {
25
+ if (!connected) return;
26
+ try {
27
+ controller.enqueue(encoder.encode(text));
28
+ } catch {
29
+ connected = false;
30
+ }
31
+ };
32
+ const send = (name, data) => {
33
+ try {
34
+ write(frame(name, data));
35
+ } catch (error) {
36
+ write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe$1(error)}` }));
37
+ }
38
+ };
39
+ try {
40
+ for await (const event of events) send(event.type, event);
41
+ } catch (error) {
42
+ send("STREAM_ERRORED", { message: describe$1(error) });
43
+ } finally {
44
+ try {
45
+ controller.close();
46
+ } catch {
47
+ connected = false;
48
+ }
49
+ }
50
+ } });
51
+ return new Response(body, { headers: HEADERS });
52
+ }
53
+ //#endregion
54
+ //#region src/stacks/tanstack/handlers.ts
55
+ function json$1(status, body) {
56
+ return new Response(JSON.stringify(body), {
57
+ status,
58
+ headers: { "content-type": "application/json; charset=utf-8" }
59
+ });
60
+ }
61
+ function resolveWorkflowId$1(ctx, param) {
62
+ const fromParams = ctx.params?.[param];
63
+ if (fromParams) return fromParams;
64
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
65
+ }
66
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
67
+ function createTanStackWorkflowHandler(collection, options = {}) {
68
+ const runStore = options.runStore ?? inMemoryRunStore();
69
+ const param = options.workflowIdParam ?? "workflowId";
70
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
71
+ return async (ctx) => {
72
+ const workflowId = resolveWorkflowId$1(ctx, param);
73
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
74
+ if (!workflow) return json$1(404, {
75
+ error: "unknown_workflow",
76
+ workflowId: workflowId ?? ""
77
+ });
78
+ let params;
79
+ try {
80
+ params = await parseWorkflowRequest(ctx.request);
81
+ } catch (error) {
82
+ if (error instanceof WorkflowRequestParseError) return json$1(400, {
83
+ error: "invalid_request",
84
+ message: error.message
85
+ });
86
+ throw error;
87
+ }
88
+ if (params.abort) return json$1(501, {
89
+ error: "abort_unsupported",
90
+ message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
91
+ });
92
+ return toServerSentEventsResponse(runWorkflow({
93
+ workflow,
94
+ runStore,
95
+ ...params
96
+ }));
97
+ };
98
+ }
99
+ //#endregion
100
+ //#region src/runtime/input-hash.ts
101
+ /** Key order must not change the hash, so objects are serialized sorted. */
102
+ function canonical(value) {
103
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
104
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
105
+ 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(",")}}`;
106
+ }
107
+ /**
108
+ * Identifies the input a run started with. A resume carries it back so replay
109
+ * cannot be pointed at a different record than the one its memo came from.
110
+ */
111
+ async function hashInput(input) {
112
+ const bytes = new TextEncoder().encode(canonical(input));
113
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
114
+ return [...new Uint8Array(digest)].slice(0, 16).map((byte) => byte.toString(16).padStart(2, "0")).join("");
115
+ }
116
+ //#endregion
117
+ //#region src/runtime/replay.ts
118
+ /** How long a pass waits for handler work that is not a durable operation. */
119
+ const DEFAULT_SETTLE_MS = 5e3;
120
+ function memoKey(stepId, occurrence) {
121
+ return `${stepId}#${occurrence}`;
122
+ }
123
+ const EXECUTABLE = /* @__PURE__ */ new Set([
124
+ "step",
125
+ "now",
126
+ "uuid"
127
+ ]);
128
+ function describe(error) {
129
+ return error instanceof Error ? `${error.name}: ${error.message}` : String(error);
130
+ }
131
+ function runtimeContext() {
132
+ return {
133
+ timeRemaining: () => Number.POSITIVE_INFINITY,
134
+ shouldYield: () => false,
135
+ yield: async () => {}
136
+ };
137
+ }
138
+ /** Thread the handler through `.middleware([...])`, merging each extension into ctx. */
139
+ async function throughMiddleware(middlewares, ctx, handler) {
140
+ let index = 0;
141
+ const dispatch = async () => {
142
+ const middleware = middlewares[index++];
143
+ if (!middleware) return handler(ctx);
144
+ return middleware.server({
145
+ ctx,
146
+ next: async ({ context }) => {
147
+ Object.assign(ctx, context);
148
+ return dispatch();
149
+ }
150
+ });
151
+ };
152
+ return dispatch();
153
+ }
154
+ async function replay(options) {
155
+ const { workflow, input, runId } = options;
156
+ const byKey = new Map(options.memo.map((entry) => [memoKey(entry.stepId, entry.occurrence ?? 0), entry]));
157
+ const allow = options.shouldExecute ?? (() => true);
158
+ const never = new Promise(() => {});
159
+ const pending = [];
160
+ const settled = /* @__PURE__ */ new Map();
161
+ const pass = { stepsSettled: 0 };
162
+ const occurrences = /* @__PURE__ */ new Map();
163
+ const consumed = /* @__PURE__ */ new Set();
164
+ let lastProgress = Date.now();
165
+ let currentParent;
166
+ const results = [];
167
+ const emitted = [];
168
+ const inflight = [];
169
+ let seq = 0;
170
+ let nonDeterminism;
171
+ function record(entry) {
172
+ settled.set(memoKey(entry.stepId, entry.occurrence), entry);
173
+ lastProgress = Date.now();
174
+ if (entry.kind === "step") pass.stepsSettled += 1;
175
+ const result = {
176
+ seq: entry.seq,
177
+ stepId: entry.stepId,
178
+ occurrence: entry.occurrence,
179
+ kind: entry.kind,
180
+ status: entry.status,
181
+ result: entry.result,
182
+ error: entry.error
183
+ };
184
+ results.push(result);
185
+ options.onStepSettle?.(result);
186
+ }
187
+ function durable(kind, stepId, run, config, defaulted = false) {
188
+ const index = seq++;
189
+ const occurrence = occurrences.get(stepId) ?? 0;
190
+ occurrences.set(stepId, occurrence + 1);
191
+ if (defaulted && occurrence > 0) {
192
+ nonDeterminism = `ctx.${kind}() was reached more than once with the default id "${stepId}"; pass an explicit { id } per call site`;
193
+ return never;
194
+ }
195
+ const key = memoKey(stepId, occurrence);
196
+ consumed.add(key);
197
+ const answered = byKey.get(key) ?? settled.get(key);
198
+ if (answered) {
199
+ if (answered.kind !== kind) {
200
+ nonDeterminism = `memo has ${answered.kind} "${stepId}" (#${occurrence}), replay produced ${kind}`;
201
+ return never;
202
+ }
203
+ if (answered.status === "completed") return Promise.resolve(answered.result);
204
+ return Promise.reject(new Error(answered.error ?? `step "${stepId}" failed`));
205
+ }
206
+ const parent = currentParent;
207
+ const intent = {
208
+ seq: index,
209
+ stepId,
210
+ occurrence,
211
+ kind,
212
+ ...config ? { config } : {}
213
+ };
214
+ if (!run || !EXECUTABLE.has(kind) || !allow(intent, pass)) {
215
+ pending.push(intent);
216
+ return never;
217
+ }
218
+ options.onStepStart?.(intent);
219
+ const enclosing = currentParent;
220
+ currentParent = key;
221
+ let body;
222
+ try {
223
+ body = run();
224
+ } finally {
225
+ currentParent = enclosing;
226
+ }
227
+ const running = body.then((result) => {
228
+ record({
229
+ seq: index,
230
+ stepId,
231
+ occurrence,
232
+ kind,
233
+ status: "completed",
234
+ result,
235
+ ...parent ? { parent } : {}
236
+ });
237
+ return result;
238
+ }, (error) => {
239
+ record({
240
+ seq: index,
241
+ stepId,
242
+ occurrence,
243
+ kind,
244
+ status: "failed",
245
+ error: describe(error),
246
+ ...parent ? { parent } : {}
247
+ });
248
+ throw error;
249
+ });
250
+ inflight.push(running.then(noop, noop));
251
+ return running;
252
+ }
253
+ const state = { ...workflow.initialize?.({ input }) };
254
+ const runtime = runtimeContext();
255
+ const controller = new AbortController();
256
+ const ctx = {
257
+ runId,
258
+ input,
259
+ state,
260
+ signal: controller.signal,
261
+ runtime,
262
+ step: (id, fn, _options) => durable("step", id, async () => fn({
263
+ id,
264
+ attempt: 1,
265
+ runtime,
266
+ signal: controller.signal
267
+ })),
268
+ sleep: (ms, opts) => durable("sleep", opts?.id ?? `sleep:${ms}`, void 0, { ms }, opts?.id === void 0),
269
+ sleepUntil: (timestamp, opts) => durable("sleep", opts?.id ?? `sleepUntil:${timestamp}`, void 0, { timestamp }, opts?.id === void 0),
270
+ waitForEvent: (name, opts) => durable("waitForEvent", opts?.id ?? `event:${name}`, void 0, { name }, opts?.id === void 0),
271
+ approve: (opts) => durable("approve", opts.id ?? `approve:${opts.title}`, void 0, {
272
+ title: opts.title,
273
+ ...opts.description === void 0 ? {} : { description: opts.description }
274
+ }, opts.id === void 0),
275
+ now: (opts) => durable("now", opts?.id ?? "now", async () => Date.now(), void 0, opts?.id === void 0),
276
+ uuid: (opts) => durable("uuid", opts?.id ?? "uuid", async () => crypto.randomUUID(), void 0, opts?.id === void 0),
277
+ emit: (name, value) => {
278
+ emitted.push({
279
+ name,
280
+ value
281
+ });
282
+ }
283
+ };
284
+ let outcome;
285
+ throughMiddleware(workflow.middlewares ?? [], ctx, workflow.handler).then((output) => {
286
+ outcome = {
287
+ status: "completed",
288
+ output: output ?? null
289
+ };
290
+ }, (error) => {
291
+ outcome = {
292
+ status: "failed",
293
+ error: describe(error)
294
+ };
295
+ });
296
+ const settleMs = options.settleMs ?? DEFAULT_SETTLE_MS;
297
+ for (;;) {
298
+ for (let tick = 0; tick < 20; tick++) await new Promise((resolve) => setTimeout(resolve, 0));
299
+ if (outcome || nonDeterminism) break;
300
+ if (inflight.length > 0) {
301
+ await Promise.all(inflight.splice(0));
302
+ lastProgress = Date.now();
303
+ continue;
304
+ }
305
+ if (pending.length > 0 || Date.now() - lastProgress >= settleMs) break;
306
+ await new Promise((resolve) => setTimeout(resolve, 5));
307
+ }
308
+ while (inflight.length > 0) await Promise.all(inflight.splice(0));
309
+ const memo = [...byKey.values(), ...settled.values()];
310
+ const hidden = (key, seen) => {
311
+ const parent = byKey.get(key)?.parent;
312
+ if (parent === void 0 || seen.has(parent)) return false;
313
+ if (consumed.has(parent)) return true;
314
+ seen.add(parent);
315
+ return hidden(parent, seen);
316
+ };
317
+ const orphan = [...byKey.keys()].find((key) => !consumed.has(key) && !hidden(key, /* @__PURE__ */ new Set([key])));
318
+ pending.sort((a, b) => a.seq - b.seq);
319
+ results.sort((a, b) => a.seq - b.seq);
320
+ const base = {
321
+ memo,
322
+ results,
323
+ emitted
324
+ };
325
+ if (nonDeterminism) return {
326
+ ...base,
327
+ status: "failed",
328
+ steps: [],
329
+ error: `non-deterministic replay: ${nonDeterminism}`
330
+ };
331
+ if (orphan !== void 0) return {
332
+ ...base,
333
+ status: "failed",
334
+ steps: [],
335
+ error: `stale memo: no operation matched "${orphan}"`
336
+ };
337
+ if (outcome?.status === "completed") return {
338
+ ...base,
339
+ status: "completed",
340
+ steps: [],
341
+ output: outcome.output
342
+ };
343
+ if (outcome?.status === "failed") return {
344
+ ...base,
345
+ status: "failed",
346
+ steps: [],
347
+ error: outcome.error
348
+ };
349
+ if (pending.length > 0) return {
350
+ ...base,
351
+ status: "pending",
352
+ steps: pending
353
+ };
354
+ return {
355
+ ...base,
356
+ status: "failed",
357
+ steps: [],
358
+ error: `workflow stalled: no durable operation and nothing settled for ${settleMs}ms`
359
+ };
360
+ }
361
+ function noop() {}
362
+ //#endregion
363
+ //#region src/stacks/tanstack/steps.ts
364
+ function json(status, body) {
365
+ return new Response(JSON.stringify(body), {
366
+ status,
367
+ headers: { "content-type": "application/json; charset=utf-8" }
368
+ });
369
+ }
370
+ function resolveWorkflowId(ctx, param) {
371
+ const fromParams = ctx.params?.[param];
372
+ if (fromParams) return fromParams;
373
+ return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-2);
374
+ }
375
+ function isMemoEntry(value) {
376
+ const entry = value;
377
+ 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");
378
+ }
379
+ function parseBody(value) {
380
+ if (value === null || typeof value !== "object") return "body must be a JSON object";
381
+ const body = value;
382
+ if (body.memo !== void 0) {
383
+ if (!Array.isArray(body.memo) || !body.memo.every(isMemoEntry)) return "memo must be an array of settled step entries";
384
+ 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";
385
+ }
386
+ if (body.steps !== void 0 && (!Array.isArray(body.steps) || !body.steps.every(isSelector))) return "steps must be an array of { stepId, occurrence? } selectors";
387
+ if (body.memo !== void 0 && body.memo.length > 0 && !("input" in value)) return "input must be sent with every call, including a resume";
388
+ return body;
389
+ }
390
+ async function readBody(request) {
391
+ const text = await request.text();
392
+ if (!text.trim()) return {};
393
+ return JSON.parse(text);
394
+ }
395
+ function selectorKey(selector) {
396
+ return memoKey(selector.stepId, selector.occurrence ?? 0);
397
+ }
398
+ function isSelector(value) {
399
+ const selector = value;
400
+ return typeof selector === "object" && selector !== null && typeof selector.stepId === "string" && (selector.occurrence === void 0 || Number.isInteger(selector.occurrence) && selector.occurrence >= 0);
401
+ }
402
+ function respond(runId, inputHash, outcome) {
403
+ const { status, memo, steps, results, emitted, output, error } = outcome;
404
+ return json(200, {
405
+ runId,
406
+ inputHash,
407
+ status,
408
+ memo,
409
+ steps,
410
+ results,
411
+ ...emitted.length > 0 ? { emitted } : {},
412
+ ...output === void 0 ? {} : { output },
413
+ ...error === void 0 ? {} : { error }
414
+ });
415
+ }
416
+ function prepare(collection, options) {
417
+ return {
418
+ param: options.workflowIdParam ?? "workflowId",
419
+ byId: new Map(collection.workflows.map((workflow) => [workflow.id, workflow]))
420
+ };
421
+ }
422
+ async function resolve(ctx, param, byId) {
423
+ const workflowId = resolveWorkflowId(ctx, param);
424
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
425
+ if (!workflow) return json(404, {
426
+ error: "unknown_workflow",
427
+ workflowId: workflowId ?? ""
428
+ });
429
+ let raw;
430
+ try {
431
+ raw = await readBody(ctx.request);
432
+ } catch (error) {
433
+ return json(400, {
434
+ error: "invalid_request",
435
+ message: `body is not valid JSON: ${String(error)}`
436
+ });
437
+ }
438
+ const body = parseBody(raw);
439
+ if (typeof body === "string") return json(400, {
440
+ error: "invalid_request",
441
+ message: body
442
+ });
443
+ const inputHash = await hashInput(body.input ?? null);
444
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) return json(400, {
445
+ error: "invalid_request",
446
+ 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"
447
+ });
448
+ return {
449
+ workflow,
450
+ body,
451
+ runId: body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
452
+ inputHash
453
+ };
454
+ }
455
+ /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
456
+ * `memo` so a later executeSteps replays the same values. */
457
+ function createNextStepsHandler(collection, options = {}) {
458
+ const { param, byId } = prepare(collection, options);
459
+ return async (ctx) => {
460
+ const resolved = await resolve(ctx, param, byId);
461
+ if (resolved instanceof Response) return resolved;
462
+ const { workflow, body, runId, inputHash } = resolved;
463
+ return respond(runId, inputHash, await replay({
464
+ workflow,
465
+ input: body.input ?? null,
466
+ memo: body.memo ?? [],
467
+ runId,
468
+ shouldExecute: (intent) => intent.kind !== "step"
469
+ }));
470
+ };
471
+ }
472
+ /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
473
+ * report, advancing the run one wave per call. */
474
+ function createExecuteStepsHandler(collection, options = {}) {
475
+ const { param, byId } = prepare(collection, options);
476
+ return async (ctx) => {
477
+ const resolved = await resolve(ctx, param, byId);
478
+ if (resolved instanceof Response) return resolved;
479
+ const { workflow, body, runId, inputHash } = resolved;
480
+ const input = body.input ?? null;
481
+ const memo = body.memo ?? [];
482
+ const wanted = body.steps && new Set(body.steps.map(selectorKey));
483
+ return respond(runId, inputHash, await replay({
484
+ workflow,
485
+ input,
486
+ memo,
487
+ runId,
488
+ shouldExecute: (intent, pass) => intent.kind !== "step" || (wanted ? wanted.has(selectorKey(intent)) : pass.stepsSettled === 0)
489
+ }));
490
+ };
491
+ }
492
+ //#endregion
493
+ //#region src/stacks/tanstack/run.ts
494
+ function event(type, fields) {
495
+ return {
496
+ type,
497
+ ts: Date.now(),
498
+ ...fields
499
+ };
500
+ }
501
+ async function* drive(workflow, input, runId, initialMemo, inputHash) {
502
+ let memo = [...initialMemo];
503
+ yield event("RUN_STARTED", {
504
+ runId,
505
+ inputHash
506
+ });
507
+ for (;;) {
508
+ const queue = [];
509
+ let wake;
510
+ const emit = (next) => {
511
+ queue.push(next);
512
+ wake?.();
513
+ wake = void 0;
514
+ };
515
+ let settledPass;
516
+ let passError;
517
+ let finished = false;
518
+ const running = replay({
519
+ workflow,
520
+ input,
521
+ memo,
522
+ runId,
523
+ shouldExecute: (intent, state) => intent.kind !== "step" || state.stepsSettled === 0,
524
+ onStepStart: (intent) => {
525
+ if (intent.kind === "step") emit(event("STEP_STARTED", { stepId: intent.stepId }));
526
+ },
527
+ onStepSettle: (result) => {
528
+ if (result.kind !== "step") return;
529
+ emit(result.status === "completed" ? event("STEP_FINISHED", {
530
+ stepId: result.stepId,
531
+ result: result.result
532
+ }) : event("STEP_FAILED", {
533
+ stepId: result.stepId,
534
+ error: result.error
535
+ }));
536
+ }
537
+ }).then((value) => {
538
+ settledPass = value;
539
+ finished = true;
540
+ wake?.();
541
+ wake = void 0;
542
+ }, (error) => {
543
+ passError = error;
544
+ finished = true;
545
+ wake?.();
546
+ wake = void 0;
547
+ });
548
+ for (;;) {
549
+ if (queue.length > 0) {
550
+ yield queue.shift();
551
+ continue;
552
+ }
553
+ if (finished) break;
554
+ await new Promise((resolve) => {
555
+ wake = resolve;
556
+ });
557
+ }
558
+ await running;
559
+ if (!settledPass) {
560
+ yield event("RUN_ERRORED", {
561
+ runId,
562
+ inputHash,
563
+ error: `replay threw: ${passError instanceof Error ? passError.message : String(passError)}`,
564
+ memo
565
+ });
566
+ return;
567
+ }
568
+ const pass = settledPass;
569
+ memo = pass.memo;
570
+ if (pass.status === "completed") {
571
+ yield event("RUN_FINISHED", {
572
+ runId,
573
+ inputHash,
574
+ output: pass.output,
575
+ memo
576
+ });
577
+ return;
578
+ }
579
+ if (pass.status === "failed") {
580
+ yield event("RUN_ERRORED", {
581
+ runId,
582
+ inputHash,
583
+ error: pass.error,
584
+ memo
585
+ });
586
+ return;
587
+ }
588
+ if (pass.steps.every((intent) => intent.kind !== "step")) {
589
+ yield event("RUN_PAUSED", {
590
+ runId,
591
+ inputHash,
592
+ waitingOn: pass.steps,
593
+ memo
594
+ });
595
+ return;
596
+ }
597
+ if (pass.results.length === 0) {
598
+ yield event("RUN_ERRORED", {
599
+ runId,
600
+ inputHash,
601
+ error: "run made no progress",
602
+ memo
603
+ });
604
+ return;
605
+ }
606
+ }
607
+ }
608
+ function createRunHandler(collection, options = {}) {
609
+ const param = options.workflowIdParam ?? "workflowId";
610
+ const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
611
+ return async (ctx) => {
612
+ const workflowId = ctx.params?.[param] ?? new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
613
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
614
+ if (!workflow) return new Response(JSON.stringify({
615
+ error: "unknown_workflow",
616
+ workflowId: workflowId ?? ""
617
+ }), {
618
+ status: 404,
619
+ headers: { "content-type": "application/json; charset=utf-8" }
620
+ });
621
+ let body = {};
622
+ try {
623
+ const text = await ctx.request.text();
624
+ if (text.trim()) body = JSON.parse(text);
625
+ } catch (error) {
626
+ return new Response(JSON.stringify({
627
+ error: "invalid_request",
628
+ message: String(error)
629
+ }), {
630
+ status: 400,
631
+ headers: { "content-type": "application/json; charset=utf-8" }
632
+ });
633
+ }
634
+ const inputHash = await hashInput(body.input ?? null);
635
+ if (body.memo !== void 0 && body.memo.length > 0 && body.inputHash !== inputHash) {
636
+ const 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";
637
+ return new Response(JSON.stringify({
638
+ error: "invalid_request",
639
+ message
640
+ }), {
641
+ status: 400,
642
+ headers: { "content-type": "application/json; charset=utf-8" }
643
+ });
644
+ }
645
+ const runId = body.runId ?? `run_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
646
+ return toServerSentEventsResponse(drive(workflow, body.input ?? null, runId, body.memo ?? [], inputHash));
647
+ };
648
+ }
649
+ //#endregion
650
+ export { createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
package/dist/vite.d.ts CHANGED
@@ -1,7 +1,20 @@
1
1
  import { Plugin } from "vite";
2
- //#region src/vite.d.ts
3
- declare function workflowsManifest({ entry }: {
4
- entry: string;
5
- }): Plugin;
2
+ //#region src/vite/plugin.d.ts
3
+ interface WorkflowsPluginOptions {
4
+ /** Collection entry, relative to the project root. @default "src/lib/workflows/index.ts" */
5
+ entry?: string;
6
+ /** Where TanStack route files live; the plugin emits under this directory.
7
+ * @default "src/routes" */
8
+ routesDir?: string;
9
+ /** URL prefix; the workflow ID is appended as a dynamic segment. @default "/api/workflows" */
10
+ path?: string;
11
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
12
+ workflowIdParam?: string;
13
+ }
14
+ /**
15
+ * Build the collection's manifests and emit the route serving them; one `entry`
16
+ * feeds both, so the two can never describe different sets.
17
+ */
18
+ declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
6
19
  //#endregion
7
- export { workflowsManifest };
20
+ export { type WorkflowsPluginOptions, workflowsPlugin };