@lovable.dev/workflows-sdk 0.0.0-dev.7 → 0.0.0-dev.8

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 CHANGED
@@ -347,8 +347,8 @@ That emits `src/routes/api/public/workflows/$workflowId.ts` and serves
347
347
  that makes the route reachable also makes it anonymously reachable.
348
348
 
349
349
  The emitted file is thin — it imports the collection and mounts
350
- `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
351
- as the route's `POST` handler. All runtime logic stays in the package. The file
350
+ `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk` as the route's
351
+ `POST` handler. All runtime logic stays in the package. The file
352
352
  carries a generated banner, which is the plugin's ownership token: it rewrites
353
353
  and deletes only files that have it, and deletes its own orphans when `path` or
354
354
  `workflowIdParam` changes. Delete the banner line to take the route over — the
@@ -362,6 +362,29 @@ the supported way to add a check of your own in front of the handler.
362
362
  | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
363
363
  | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
364
364
 
365
+ ### How the emitted file imports the collection
366
+
367
+ The plugin prefers an alias, so the specifier does not change when `path` moves:
368
+
369
+ ```ts
370
+ import workflows from "@/lib/workflows/index";
371
+ ```
372
+
373
+ It does not assume `@`. It reads the app's Vite `resolve.alias` and its
374
+ tsconfig `compilerOptions.paths`, and picks an alias whose target directory
375
+ contains the collection entry — preferring one both sources declare, then the
376
+ deepest match.
377
+
378
+ An alias is only emitted when the *bundler* can resolve it: a Vite
379
+ `resolve.alias` entry, or a tsconfig `paths` entry when a plugin such as
380
+ `vite-tsconfig-paths` is active. A tsconfig `paths` entry alone instructs the
381
+ typechecker and not the bundler, so emitting it would fail the build.
382
+
383
+ When no alias qualifies, the plugin falls back to a relative specifier
384
+ (`../../../lib/workflows/index`), which always resolves. An app with no alias
385
+ configured still builds; only the specifier is uglier, and its depth tracks
386
+ `path`.
387
+
365
388
  ### Calling it
366
389
 
367
390
  `POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
@@ -397,6 +420,22 @@ manifest. Triggers name a workflow rather than an endpoint, so firing one is a
397
420
  POST to that workflow's path with the trigger's input; no trigger identifier
398
421
  appears in the URL.
399
422
 
423
+ ## Public entry points
424
+
425
+ The package has two, and neither mirrors the source tree:
426
+
427
+ | Import | Provides |
428
+ | --- | --- |
429
+ | `@lovable.dev/workflows-sdk` | Authoring (`createWorkflow`, `registerWorkflows`, cadences, `defineSchedule`), `generateManifests`, and `createTanStackWorkflowHandler` |
430
+ | `@lovable.dev/workflows-sdk/vite` | `workflowsPlugin`, the build-time Vite plugin |
431
+
432
+ The export map is a contract; the directory layout under `src/` is not. They are
433
+ deliberately decoupled, so the package can be reorganised without a breaking
434
+ change for apps that already have an emitted route.
435
+
436
+ The package sets `"sideEffects": false` and the handler is a plain re-export, so
437
+ a client bundle importing only authoring APIs drops the execution engine.
438
+
400
439
  ## Next PRs
401
440
 
402
441
  Connect the manifest and app code to Lovable deployment and runtime execution.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, StepContext, StepOptions, WorkflowDefinition, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
1
+ import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, RunStore, StepContext, StepOptions, WorkflowDefinition, WorkflowEvent, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
2
  //#region src/core/cadence.d.ts
3
3
  type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
4
  type Cadence = {
@@ -125,4 +125,33 @@ interface WorkflowManifest {
125
125
  }
126
126
  declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
127
127
  //#endregion
128
- export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TriggerDefinition, type Weekday, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
128
+ //#region src/stacks/tanstack/handlers.d.ts
129
+ /** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
130
+ interface WorkflowCollection {
131
+ readonly workflows: readonly AnyWorkflowDefinition$1[];
132
+ }
133
+ interface TanStackWorkflowHandlerOptions {
134
+ /** @default a process-local `inMemoryRunStore()`, lost on restart */
135
+ runStore?: RunStore;
136
+ /**
137
+ * Route parameter carrying the workflow ID.
138
+ * @default "workflowId"
139
+ */
140
+ workflowIdParam?: string;
141
+ }
142
+ interface TanStackRouteCtx {
143
+ request: Request;
144
+ params?: Record<string, string | undefined>;
145
+ }
146
+ type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
147
+ /** Build a TanStack Start `POST` handler serving every workflow in the collection. */
148
+ declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
149
+ //#endregion
150
+ //#region src/stacks/tanstack/sse.d.ts
151
+ /**
152
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
153
+ * engine `type` as the SSE event name and its whole JSON as the data line.
154
+ */
155
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
156
+ //#endregion
157
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type TriggerDefinition, type Weekday, type WorkflowCollection, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
package/dist/index.js CHANGED
@@ -1,2 +1,100 @@
1
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
- export { createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
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(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(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(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(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(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(ctx, param);
73
+ const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
74
+ if (!workflow) return json(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(400, {
83
+ error: "invalid_request",
84
+ message: error.message
85
+ });
86
+ throw error;
87
+ }
88
+ if (params.abort) return json(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
+ export { createMiddleware, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };
package/dist/vite.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as generateManifests } from "./generate-DyUHbtre.js";
2
- import { dirname, join, relative, resolve, sep } from "node:path";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { createServer } from "vite";
4
4
  import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
5
5
  import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
@@ -31,6 +31,101 @@ async function writeManifests(root, manifests) {
31
31
  }
32
32
  }
33
33
  //#endregion
34
+ //#region src/vite/alias.ts
35
+ function normalize(path) {
36
+ return path.split(sep).join("/");
37
+ }
38
+ function parseTsconfig(text) {
39
+ const withoutComments = text.replace(/"(?:\\.|[^"\\])*"|(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g, (match, comment) => comment ? "" : match);
40
+ return JSON.parse(withoutComments.replace(/,(\s*[}\]])/g, "$1"));
41
+ }
42
+ function isRecord(value) {
43
+ return typeof value === "object" && value !== null;
44
+ }
45
+ /** Wildcard `paths` entries (`"@/*": ["./src/*"]`), the only shape an emitted import can use. */
46
+ function tsconfigAliases(root, tsconfigPath = "tsconfig.json") {
47
+ let parsed;
48
+ try {
49
+ parsed = parseTsconfig(readFileSync(resolve(root, tsconfigPath), "utf8"));
50
+ } catch {
51
+ return [];
52
+ }
53
+ if (!isRecord(parsed)) return [];
54
+ const options = parsed.compilerOptions;
55
+ if (!isRecord(options)) return [];
56
+ const paths = options.paths;
57
+ if (!isRecord(paths)) return [];
58
+ const baseUrl = typeof options.baseUrl === "string" ? resolve(root, options.baseUrl) : root;
59
+ const entries = [];
60
+ for (const [pattern, targets] of Object.entries(paths)) {
61
+ if (!pattern.endsWith("/*") || !Array.isArray(targets)) continue;
62
+ const target = targets[0];
63
+ if (typeof target !== "string" || !target.endsWith("/*")) continue;
64
+ entries.push({
65
+ prefix: pattern.slice(0, -2),
66
+ dir: resolve(baseUrl, target.slice(0, -2)),
67
+ sources: {
68
+ vite: false,
69
+ tsconfig: true
70
+ }
71
+ });
72
+ }
73
+ return entries;
74
+ }
75
+ /** String-`find` entries of a resolved Vite `resolve.alias`; a regex alias cannot be re-emitted. */
76
+ function viteAliases(alias) {
77
+ if (!alias) return [];
78
+ const entries = [];
79
+ for (const { find, replacement } of alias) {
80
+ if (typeof find !== "string" || !find || !isAbsolute(replacement)) continue;
81
+ entries.push({
82
+ prefix: find.replace(/\/$/, ""),
83
+ dir: replacement.replace(/\/$/, ""),
84
+ sources: {
85
+ vite: true,
86
+ tsconfig: false
87
+ }
88
+ });
89
+ }
90
+ return entries;
91
+ }
92
+ function merge(entries) {
93
+ const byKey = /* @__PURE__ */ new Map();
94
+ for (const entry of entries) {
95
+ const key = `${entry.prefix}::${normalize(entry.dir)}`;
96
+ const existing = byKey.get(key);
97
+ if (existing) {
98
+ existing.sources.vite ||= entry.sources.vite;
99
+ existing.sources.tsconfig ||= entry.sources.tsconfig;
100
+ } else byKey.set(key, {
101
+ ...entry,
102
+ sources: { ...entry.sources }
103
+ });
104
+ }
105
+ return [...byKey.values()];
106
+ }
107
+ function contains(dir, file) {
108
+ return normalize(file).startsWith(`${normalize(dir)}/`);
109
+ }
110
+ function score(entry) {
111
+ if (entry.sources.vite && entry.sources.tsconfig) return 2;
112
+ return entry.sources.vite ? 1 : 0;
113
+ }
114
+ function isResolvable(entry, tsconfigPathsPlugin) {
115
+ return entry.sources.vite || tsconfigPathsPlugin;
116
+ }
117
+ /**
118
+ * The aliased specifier for `target`, or `undefined` when no alias resolves it.
119
+ * Prefers an alias both sources agree on, then the deepest directory.
120
+ */
121
+ function aliasedSpecifier(target, entries, tsconfigPathsPlugin = false) {
122
+ const matches = merge(entries).filter((entry) => contains(entry.dir, target) && isResolvable(entry, tsconfigPathsPlugin));
123
+ if (matches.length === 0) return void 0;
124
+ matches.sort((a, b) => score(b) - score(a) || normalize(b.dir).length - normalize(a.dir).length);
125
+ const best = matches[0];
126
+ return `${best.prefix}/${normalize(relative(best.dir, target)).replace(/\.tsx?$/, "")}`;
127
+ }
128
+ //#endregion
34
129
  //#region src/vite/route-emitter.ts
35
130
  const GENERATED_BANNER = "// AUTO-GENERATED by @lovable.dev/workflows-sdk — do not edit. Regenerated by the Vite plugin.\n// To take ownership, delete this banner line; the plugin then leaves the file alone.";
36
131
  function isFileMissing(error) {
@@ -61,7 +156,10 @@ function relativeImportSpecifier(routeFile, target) {
61
156
  const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
62
157
  return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
63
158
  }
64
- function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
159
+ function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
160
+ return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
161
+ }
162
+ function buildRouteSource(routeFile, routeLiteral, param, specifier, root) {
65
163
  return `${GENERATED_BANNER}
66
164
  // route: ${routeLiteral}
67
165
  // emitted to: ${normalizePath(relative(root, routeFile))}
@@ -70,9 +168,9 @@ function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
70
168
 
71
169
  import { createFileRoute } from "@tanstack/react-router";
72
170
 
73
- import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk/stacks/tanstack";
171
+ import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk";
74
172
 
75
- import workflows from "${relativeImportSpecifier(routeFile, entry)}";
173
+ import workflows from "${specifier}";
76
174
 
77
175
  export const Route = createFileRoute("${routeLiteral}")({
78
176
  server: {
@@ -136,10 +234,14 @@ function createRouteEmitter(options) {
136
234
  let entry = resolve(root, options.entry);
137
235
  let routesDir = resolve(root, options.routesDir);
138
236
  let routeFile = resolve(routesDir, routeFileName);
237
+ let aliases = [];
238
+ let tsconfigPathsPlugin = false;
139
239
  return {
140
240
  entryPath: () => entry,
141
- setRoot(next) {
241
+ setRoot(next, context) {
142
242
  root = next;
243
+ aliases = [...viteAliases(context?.alias), ...tsconfigAliases(next)];
244
+ tsconfigPathsPlugin = context?.tsconfigPathsPlugin === true;
143
245
  entry = resolve(root, options.entry);
144
246
  assertContains(root, entry, `entry "${options.entry}"`);
145
247
  routesDir = resolve(root, options.routesDir);
@@ -158,7 +260,8 @@ function createRouteEmitter(options) {
158
260
  const expected = /* @__PURE__ */ new Set();
159
261
  if (entryExists) {
160
262
  expected.add(routeFile);
161
- writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, entry, root));
263
+ const specifier = collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin);
264
+ writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, specifier, root));
162
265
  }
163
266
  for (const file of findAdoptedFiles(routesDir)) {
164
267
  if (expected.has(file)) continue;
@@ -173,6 +276,7 @@ function createRouteEmitter(options) {
173
276
  }
174
277
  //#endregion
175
278
  //#region src/vite/plugin.ts
279
+ const TSCONFIG_PATHS_PLUGINS = /* @__PURE__ */ new Set(["vite-tsconfig-paths", "vite-plugin-tsconfig-paths"]);
176
280
  /**
177
281
  * Build the collection's manifests and emit the route serving them; one `entry`
178
282
  * feeds both, so the two can never describe different sets.
@@ -190,7 +294,10 @@ function workflowsPlugin(options = {}) {
190
294
  name: "@lovable.dev/workflows-sdk",
191
295
  configResolved(resolved) {
192
296
  config = resolved;
193
- emitter.setRoot(config.root);
297
+ emitter.setRoot(config.root, {
298
+ alias: config.resolve.alias,
299
+ tsconfigPathsPlugin: config.plugins.some((plugin) => TSCONFIG_PATHS_PLUGINS.has(plugin.name))
300
+ });
194
301
  emitter.regenerate();
195
302
  },
196
303
  configureServer(server) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.7",
3
+ "version": "0.0.0-dev.8",
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,10 +23,6 @@
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
  },
31
28
  "files": [
@@ -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 };