@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.
@@ -0,0 +1,61 @@
1
+ //#region src/core/llm-validation.ts
2
+ function fail(message) {
3
+ throw new Error(`@lovable.dev/workflows-sdk: ctx.llm() ${message}`);
4
+ }
5
+ function object(value) {
6
+ return value !== null && typeof value === "object" && !Array.isArray(value);
7
+ }
8
+ function uint32(value) {
9
+ return typeof value === "number" && Number.isInteger(value) && value > 0 && value <= 4294967295;
10
+ }
11
+ function assertLlmModel(model) {
12
+ if (typeof model !== "string" || !/^[^/\s]+\/[^\s]+$/.test(model)) fail("requires a provider-prefixed model ID, such as openai/gpt-5");
13
+ }
14
+ function assertLlmRequest(request) {
15
+ if (!object(request)) fail("requires a request object");
16
+ if (Object.keys(request).some((key) => ![
17
+ "model",
18
+ "prompt",
19
+ "messages",
20
+ "system",
21
+ "maxTokens"
22
+ ].includes(key))) fail("request contains unsupported fields");
23
+ assertLlmModel(request.model);
24
+ if (request.prompt !== void 0 === (request.messages !== void 0)) fail("requires exactly one of prompt or messages");
25
+ if (request.prompt !== void 0 && typeof request.prompt !== "string") fail("prompt must be a string");
26
+ if (request.messages !== void 0) {
27
+ if (!Array.isArray(request.messages) || request.messages.length === 0) fail("messages must be a nonempty array");
28
+ for (const message of request.messages) if (!object(message) || message.role !== "user" && message.role !== "assistant" || typeof message.content !== "string" || Object.keys(message).some((key) => key !== "role" && key !== "content")) fail("messages must contain only user/assistant roles and string content");
29
+ }
30
+ if (request.system !== void 0 && typeof request.system !== "string") fail("system must be a string");
31
+ if (request.maxTokens !== void 0 && !uint32(request.maxTokens)) fail("maxTokens must be an integer between 1 and 4294967295");
32
+ }
33
+ function assertLlmOptions(options) {
34
+ if (!object(options)) fail("requires an options object");
35
+ if (Object.keys(options).some((key) => ![
36
+ "id",
37
+ "meta",
38
+ "timeout",
39
+ "retry"
40
+ ].includes(key))) fail("options contain unsupported fields");
41
+ if (typeof options.id !== "string" || options.id.trim() === "") fail("requires a nonempty id");
42
+ if (!object(options.meta) || typeof options.meta.description !== "string" || options.meta.description.trim() === "") fail("requires a nonempty meta.description");
43
+ const group = options.meta.group;
44
+ if (group !== void 0 && (!object(group) || typeof group.id !== "string" || group.id.trim() === "" || typeof group.label !== "string" || group.label.trim() === "")) fail("meta.group must contain a nonempty id and label");
45
+ if (options.timeout !== void 0 && (typeof options.timeout !== "number" || !Number.isFinite(options.timeout) || options.timeout <= 0)) fail("timeout must be finite and positive");
46
+ const retry = options.retry;
47
+ if (retry === void 0) return;
48
+ if (!object(retry)) fail("retry must be an object with serializable settings");
49
+ if (Object.keys(retry).some((key) => ![
50
+ "maxAttempts",
51
+ "backoff",
52
+ "baseMs",
53
+ "shouldRetry"
54
+ ].includes(key))) fail("retry contains unsupported fields");
55
+ if (!uint32(retry.maxAttempts)) fail("retry.maxAttempts must be an integer between 1 and 4294967295");
56
+ if (retry.backoff !== void 0 && retry.backoff !== "fixed" && retry.backoff !== "exponential") fail("retry.backoff must be fixed or exponential; callbacks are not supported");
57
+ if (retry.shouldRetry !== void 0) fail("retry.shouldRetry callbacks are not supported");
58
+ if (retry.baseMs !== void 0 && (typeof retry.baseMs !== "number" || !Number.isFinite(retry.baseMs) || retry.baseMs < 0)) fail("retry.baseMs must be finite and nonnegative");
59
+ }
60
+ //#endregion
61
+ export { assertLlmOptions as n, assertLlmRequest as r, assertLlmModel as t };
@@ -0,0 +1,60 @@
1
+ import { n as loadTypeScript, r as workflowHandlerSource } from "./graph-DSYE4aER.js";
2
+ //#region src/manifests/nested-operations.ts
3
+ const durableMethods = [
4
+ "step",
5
+ "llm",
6
+ "connector",
7
+ "approve",
8
+ "waitForEvent",
9
+ "sleep",
10
+ "sleepUntil",
11
+ "now",
12
+ "uuid"
13
+ ];
14
+ async function findNestedDurableOperations(handler) {
15
+ const api = await loadTypeScript();
16
+ if (!api) return [];
17
+ const ts = api;
18
+ const handlerSource = workflowHandlerSource(handler);
19
+ if (!handlerSource) return [];
20
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
21
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
22
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
23
+ const parameter = fn.parameters[0]?.name;
24
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
25
+ const context = parameter.text;
26
+ function methodOf(node) {
27
+ if (!ts.isCallExpression(node)) return void 0;
28
+ const expression = node.expression;
29
+ let name;
30
+ if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === context) name = expression.name.text;
31
+ 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;
32
+ return durableMethods.find((method) => method === name);
33
+ }
34
+ function stepIdOf(node) {
35
+ const argument = node.arguments[0];
36
+ return argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument)) ? argument.text : void 0;
37
+ }
38
+ const nested = [];
39
+ const visit = (node, parent) => {
40
+ const method = methodOf(node);
41
+ if (method && parent) nested.push({
42
+ method,
43
+ parentMethod: parent.method,
44
+ parentStepId: parent.stepId
45
+ });
46
+ if ((method === "step" || method === "connector") && ts.isCallExpression(node)) {
47
+ visit(node.expression, parent);
48
+ node.arguments.forEach((argument, index) => visit(argument, index === 1 ? {
49
+ method,
50
+ stepId: stepIdOf(node)
51
+ } : parent));
52
+ return;
53
+ }
54
+ ts.forEachChild(node, (child) => visit(child, parent));
55
+ };
56
+ visit(fn);
57
+ return nested;
58
+ }
59
+ //#endregion
60
+ export { findNestedDurableOperations };
@@ -0,0 +1,47 @@
1
+ import { n as loadTypeScript, r as workflowHandlerSource } from "./graph-DSYE4aER.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
+ llm: 1
11
+ };
12
+ async function findOperationDescriptionIssues(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 literalString(node) {
25
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
26
+ }
27
+ function property(node, name) {
28
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
29
+ for (const entry of node.properties) {
30
+ if (!ts.isPropertyAssignment(entry)) continue;
31
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
32
+ }
33
+ }
34
+ const issues = [];
35
+ const visit = (node) => {
36
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in optionsArgument) {
37
+ const method = node.expression.name.text;
38
+ const options = node.arguments[optionsArgument[method]];
39
+ if ((method === "approve" ? literalString(property(options, "description")) : literalString(property(property(options, "meta"), "description"))) === void 0) issues.push({ method });
40
+ }
41
+ ts.forEachChild(node, visit);
42
+ };
43
+ visit(fn);
44
+ return issues;
45
+ }
46
+ //#endregion
47
+ export { findOperationDescriptionIssues };
@@ -0,0 +1,379 @@
1
+ import { t as generateManifests } from "./generate-DGdzUQcG.js";
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { createServer } from "vite";
5
+ import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
6
+ //#region src/vite/loader.ts
7
+ /** Generates the manifests of the collection at `source.entry`; an app without the default entry has none. */
8
+ async function loadManifests(config, source, onModuleFile) {
9
+ const entryPath = resolve(config.root, source.entry);
10
+ if (!existsSync(entryPath)) {
11
+ if (source.entryIsDefault) return [];
12
+ throw new Error(`@lovable.dev/workflows-sdk: ${source.entry}, the entry set in workflowsPlugin(), does not exist`);
13
+ }
14
+ const server = await createServer({
15
+ configFile: false,
16
+ root: config.root,
17
+ mode: config.mode,
18
+ envDir: config.envDir,
19
+ define: config.define,
20
+ logLevel: "silent",
21
+ resolve: { alias: config.resolve.alias },
22
+ ssr: {
23
+ external: config.ssr.external,
24
+ noExternal: config.ssr.noExternal
25
+ },
26
+ server: {
27
+ middlewareMode: true,
28
+ hmr: false,
29
+ watch: null
30
+ },
31
+ optimizeDeps: { noDiscovery: true }
32
+ });
33
+ try {
34
+ const module = await server.ssrLoadModule(entryPath);
35
+ if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.triggers)) throw new Error(`@lovable.dev/workflows-sdk: ${source.entry} must default-export a registerWorkflows() collection`);
36
+ return await generateManifests(module.default, { routePath: source.path });
37
+ } finally {
38
+ if (onModuleFile) for (const file of server.moduleGraph.fileToModulesMap.keys()) onModuleFile(file);
39
+ await server.close();
40
+ }
41
+ }
42
+ //#endregion
43
+ //#region src/vite/manifest-files.ts
44
+ async function ensureDirectory(path) {
45
+ try {
46
+ await mkdir(path);
47
+ } catch (error) {
48
+ if (error.code !== "EEXIST") throw error;
49
+ }
50
+ if (!(await lstat(path)).isDirectory()) throw new Error(`@lovable.dev/workflows-sdk: ${path} must be a directory, not a file or symlink`);
51
+ }
52
+ async function writeManifests(root, manifests) {
53
+ const lovable = join(root, ".lovable");
54
+ await ensureDirectory(lovable);
55
+ const directory = join(lovable, "workflows");
56
+ await ensureDirectory(directory);
57
+ const staging = await mkdtemp(join(directory, ".tmp-"));
58
+ const nameOf = (manifest) => `${manifest.workflowId}.${manifest.workflowVersion}.json`;
59
+ const names = new Set(manifests.map(nameOf));
60
+ try {
61
+ for (const manifest of manifests) await writeFile(join(staging, nameOf(manifest)), JSON.stringify(manifest, null, 2) + "\n");
62
+ for (const name of names) await rename(join(staging, name), join(directory, name));
63
+ for (const entry of await readdir(directory, { withFileTypes: true })) if (entry.name.endsWith(".json") && !names.has(entry.name) && !entry.isDirectory()) await rm(join(directory, entry.name), { force: true });
64
+ } finally {
65
+ await rm(staging, {
66
+ recursive: true,
67
+ force: true
68
+ });
69
+ }
70
+ }
71
+ //#endregion
72
+ //#region src/vite/alias.ts
73
+ function normalize(path) {
74
+ return path.split(sep).join("/");
75
+ }
76
+ function parseTsconfig(text) {
77
+ const withoutComments = text.replace(/"(?:\\.|[^"\\])*"|(\/\/[^\n]*|\/\*[\s\S]*?\*\/)/g, (match, comment) => comment ? "" : match);
78
+ return JSON.parse(withoutComments.replace(/,(\s*[}\]])/g, "$1"));
79
+ }
80
+ function isRecord(value) {
81
+ return typeof value === "object" && value !== null;
82
+ }
83
+ /** Wildcard `paths` entries (`"@/*": ["./src/*"]`), the only shape an emitted import can use. */
84
+ function tsconfigAliases(root, tsconfigPath = "tsconfig.json") {
85
+ let parsed;
86
+ try {
87
+ parsed = parseTsconfig(readFileSync(resolve(root, tsconfigPath), "utf8"));
88
+ } catch {
89
+ return [];
90
+ }
91
+ if (!isRecord(parsed)) return [];
92
+ const options = parsed.compilerOptions;
93
+ if (!isRecord(options)) return [];
94
+ const paths = options.paths;
95
+ if (!isRecord(paths)) return [];
96
+ const baseUrl = typeof options.baseUrl === "string" ? resolve(root, options.baseUrl) : root;
97
+ const entries = [];
98
+ for (const [pattern, targets] of Object.entries(paths)) {
99
+ if (!pattern.endsWith("/*") || !Array.isArray(targets)) continue;
100
+ const target = targets[0];
101
+ if (typeof target !== "string" || !target.endsWith("/*")) continue;
102
+ entries.push({
103
+ prefix: pattern.slice(0, -2),
104
+ dir: resolve(baseUrl, target.slice(0, -2)),
105
+ sources: {
106
+ vite: false,
107
+ tsconfig: true
108
+ }
109
+ });
110
+ }
111
+ return entries;
112
+ }
113
+ /** String-`find` entries of a resolved Vite `resolve.alias`; a regex alias cannot be re-emitted. */
114
+ function viteAliases(alias) {
115
+ if (!alias) return [];
116
+ const entries = [];
117
+ for (const { find, replacement } of alias) {
118
+ if (typeof find !== "string" || !find || !isAbsolute(replacement)) continue;
119
+ entries.push({
120
+ prefix: find.replace(/\/$/, ""),
121
+ dir: replacement.replace(/\/$/, ""),
122
+ sources: {
123
+ vite: true,
124
+ tsconfig: false
125
+ }
126
+ });
127
+ }
128
+ return entries;
129
+ }
130
+ function merge(entries) {
131
+ const byKey = /* @__PURE__ */ new Map();
132
+ for (const entry of entries) {
133
+ const key = `${entry.prefix}::${normalize(entry.dir)}`;
134
+ const existing = byKey.get(key);
135
+ if (existing) {
136
+ existing.sources.vite ||= entry.sources.vite;
137
+ existing.sources.tsconfig ||= entry.sources.tsconfig;
138
+ } else byKey.set(key, {
139
+ ...entry,
140
+ sources: { ...entry.sources }
141
+ });
142
+ }
143
+ return [...byKey.values()];
144
+ }
145
+ function contains(dir, file) {
146
+ return normalize(file).startsWith(`${normalize(dir)}/`);
147
+ }
148
+ function score(entry) {
149
+ if (entry.sources.vite && entry.sources.tsconfig) return 2;
150
+ return entry.sources.vite ? 1 : 0;
151
+ }
152
+ function isResolvable(entry, tsconfigPathsPlugin) {
153
+ return entry.sources.vite || tsconfigPathsPlugin;
154
+ }
155
+ /**
156
+ * The aliased specifier for `target`, or `undefined` when no alias resolves it.
157
+ * Prefers an alias both sources agree on, then the deepest directory.
158
+ */
159
+ function aliasedSpecifier(target, entries, tsconfigPathsPlugin = false) {
160
+ const matches = merge(entries).filter((entry) => contains(entry.dir, target) && isResolvable(entry, tsconfigPathsPlugin));
161
+ if (matches.length === 0) return void 0;
162
+ matches.sort((a, b) => score(b) - score(a) || normalize(b.dir).length - normalize(a.dir).length);
163
+ const best = matches[0];
164
+ return `${best.prefix}/${normalize(relative(best.dir, target)).replace(/\.tsx?$/, "")}`;
165
+ }
166
+ //#endregion
167
+ //#region src/vite/route-emitter.ts
168
+ 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.";
169
+ function isFileMissing(error) {
170
+ const code = error?.code;
171
+ return code === "ENOENT" || code === "ENOTDIR";
172
+ }
173
+ function normalizePath(path) {
174
+ return path.split(sep).join("/");
175
+ }
176
+ function assertContains(parent, child, label) {
177
+ const from = normalizePath(parent).replace(/\/$/, "");
178
+ const to = normalizePath(child);
179
+ if (to !== from && !to.startsWith(`${from}/`)) throw new Error(`@lovable.dev/workflows-sdk: ${label} must resolve under ${from}, got ${to}`);
180
+ }
181
+ function assertUrlPathShape(urlPath) {
182
+ if (!urlPath.startsWith("/")) throw new Error(`@lovable.dev/workflows-sdk: path must start with "/", got "${urlPath}"`);
183
+ if (/\/{2,}/.test(urlPath)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains empty segments ("//")`);
184
+ const trimmed = urlPath.replace(/^\/+/, "").replace(/\/+$/, "");
185
+ if (!trimmed) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" has no route segment`);
186
+ if (!/^[a-zA-Z0-9_\-/]+$/.test(trimmed)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains unsupported characters`);
187
+ return trimmed;
188
+ }
189
+ function assertParamShape(param) {
190
+ if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param)) throw new Error(`@lovable.dev/workflows-sdk: workflowIdParam "${param}" must be a JavaScript identifier`);
191
+ return param;
192
+ }
193
+ function relativeImportSpecifier(routeFile, target) {
194
+ const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
195
+ return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
196
+ }
197
+ function collectionSpecifier(routeFile, entry, aliases, tsconfigPathsPlugin) {
198
+ return aliasedSpecifier(entry, aliases, tsconfigPathsPlugin) ?? relativeImportSpecifier(routeFile, entry);
199
+ }
200
+ const SURFACES = [{
201
+ segment: "steps",
202
+ factory: "createStepsHandler"
203
+ }];
204
+ function buildRouteSource(routeFile, routeLiteral, param, specifier, root, factory) {
205
+ return `${GENERATED_BANNER}
206
+ // route: ${routeLiteral}
207
+ // emitted to: ${normalizePath(relative(root, routeFile))}
208
+
209
+ import { createFileRoute } from "@tanstack/react-router";
210
+
211
+ import { ${factory} } from "@lovable.dev/workflows-sdk";
212
+
213
+ import workflows from "${specifier}";
214
+
215
+ export const Route = createFileRoute("${routeLiteral}")({
216
+ server: {
217
+ handlers: {
218
+ POST: ${factory}(workflows, { workflowIdParam: "${param}" }),
219
+ },
220
+ },
221
+ });
222
+ `;
223
+ }
224
+ function hasGeneratedBanner(content) {
225
+ return content.replace(/\r\n/g, "\n").startsWith(GENERATED_BANNER);
226
+ }
227
+ function writeIfChanged(file, content) {
228
+ let existing;
229
+ try {
230
+ existing = readFileSync(file, "utf8");
231
+ } catch (error) {
232
+ if (!isFileMissing(error)) throw error;
233
+ }
234
+ if (existing !== void 0 && (!hasGeneratedBanner(existing) || existing === content)) return;
235
+ mkdirSync(dirname(file), { recursive: true });
236
+ writeFileSync(file, content, "utf8");
237
+ }
238
+ function findAdoptedFiles(routesDir) {
239
+ const adopted = [];
240
+ const visit = (dir) => {
241
+ let entries;
242
+ try {
243
+ entries = readdirSync(dir);
244
+ } catch (error) {
245
+ if (isFileMissing(error)) return;
246
+ throw error;
247
+ }
248
+ for (const entry of entries) {
249
+ const full = join(dir, entry);
250
+ let stat;
251
+ try {
252
+ stat = lstatSync(full);
253
+ } catch (error) {
254
+ if (isFileMissing(error)) continue;
255
+ throw error;
256
+ }
257
+ if (stat.isDirectory()) visit(full);
258
+ else if (entry.endsWith(".ts")) try {
259
+ if (hasGeneratedBanner(readFileSync(full, "utf8"))) adopted.push(full);
260
+ } catch (error) {
261
+ if (!isFileMissing(error)) throw error;
262
+ }
263
+ }
264
+ };
265
+ visit(routesDir);
266
+ return adopted;
267
+ }
268
+ function createRouteEmitter(options) {
269
+ const param = assertParamShape(options.workflowIdParam);
270
+ const pathSegments = assertUrlPathShape(options.path);
271
+ const base = `/${pathSegments}/$${param}`;
272
+ const surfaces = SURFACES.map((surface) => ({
273
+ ...surface,
274
+ literal: surface.segment ? `${base}/${surface.segment}` : base,
275
+ fileName: surface.segment ? join(...pathSegments.split("/"), `$${param}`, `${surface.segment}.ts`) : join(...pathSegments.split("/"), `$${param}.ts`)
276
+ }));
277
+ let root = process.cwd();
278
+ let entry = resolve(root, options.entry);
279
+ let routesDir = resolve(root, options.routesDir);
280
+ let routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
281
+ let aliases = [];
282
+ let tsconfigPathsPlugin = false;
283
+ return {
284
+ entryPath: () => entry,
285
+ setRoot(next, context) {
286
+ root = next;
287
+ aliases = [...viteAliases(context?.alias), ...tsconfigAliases(next)];
288
+ tsconfigPathsPlugin = context?.tsconfigPathsPlugin === true;
289
+ entry = resolve(root, options.entry);
290
+ assertContains(root, entry, `entry "${options.entry}"`);
291
+ routesDir = resolve(root, options.routesDir);
292
+ assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
293
+ routeFiles = surfaces.map((surface) => resolve(routesDir, surface.fileName));
294
+ routeFiles.forEach((file, index) => assertContains(routesDir, file, `path "${surfaces[index].literal}"`));
295
+ },
296
+ regenerate() {
297
+ let entryExists = true;
298
+ try {
299
+ lstatSync(entry);
300
+ } catch (error) {
301
+ if (!isFileMissing(error)) throw error;
302
+ entryExists = false;
303
+ }
304
+ const expected = /* @__PURE__ */ new Set();
305
+ if (entryExists) surfaces.forEach((surface, index) => {
306
+ const file = routeFiles[index];
307
+ expected.add(file);
308
+ const specifier = collectionSpecifier(file, entry, aliases, tsconfigPathsPlugin);
309
+ writeIfChanged(file, buildRouteSource(file, surface.literal, param, specifier, root, surface.factory));
310
+ });
311
+ for (const file of findAdoptedFiles(routesDir)) {
312
+ if (expected.has(file)) continue;
313
+ try {
314
+ unlinkSync(file);
315
+ } catch (error) {
316
+ if (!isFileMissing(error)) throw error;
317
+ }
318
+ }
319
+ }
320
+ };
321
+ }
322
+ //#endregion
323
+ //#region src/vite/plugin.ts
324
+ const PLUGIN_NAME = "@lovable.dev/workflows-sdk";
325
+ const DEFAULT_ENTRY = "src/lib/workflows/index.ts";
326
+ const TSCONFIG_PATHS_PLUGINS = /* @__PURE__ */ new Set(["vite-tsconfig-paths", "vite-plugin-tsconfig-paths"]);
327
+ /**
328
+ * Build the collection's manifests and emit the route serving them; one `entry`
329
+ * feeds both, so the two can never describe different sets.
330
+ */
331
+ function workflowsPlugin(options = {}) {
332
+ const entry = options.entry ?? "src/lib/workflows/index.ts";
333
+ const path = options.path ?? "/api/workflows";
334
+ const source = {
335
+ entry,
336
+ path,
337
+ entryIsDefault: options.entry === void 0
338
+ };
339
+ const emitter = createRouteEmitter({
340
+ entry,
341
+ routesDir: options.routesDir ?? "src/routes",
342
+ path,
343
+ workflowIdParam: options.workflowIdParam ?? "workflowId"
344
+ });
345
+ let config;
346
+ return {
347
+ name: PLUGIN_NAME,
348
+ api: source,
349
+ configResolved(resolved) {
350
+ config = resolved;
351
+ emitter.setRoot(config.root, {
352
+ alias: config.resolve.alias,
353
+ tsconfigPathsPlugin: config.plugins.some((plugin) => TSCONFIG_PATHS_PLUGINS.has(plugin.name))
354
+ });
355
+ emitter.regenerate();
356
+ },
357
+ configureServer(server) {
358
+ const onChange = (file) => {
359
+ if (normalizePath(file) === normalizePath(emitter.entryPath())) emitter.regenerate();
360
+ };
361
+ server.watcher.on("add", onChange);
362
+ server.watcher.on("unlink", onChange);
363
+ server.watcher.once("close", () => {
364
+ server.watcher.off("add", onChange);
365
+ server.watcher.off("unlink", onChange);
366
+ });
367
+ },
368
+ buildStart() {
369
+ emitter.regenerate();
370
+ },
371
+ async generateBundle() {
372
+ this.addWatchFile(resolve(config.root, entry));
373
+ const manifests = await loadManifests(config, source, (file) => this.addWatchFile(file));
374
+ await writeManifests(config.root, manifests);
375
+ }
376
+ };
377
+ }
378
+ //#endregion
379
+ export { loadManifests as a, writeManifests as i, PLUGIN_NAME as n, workflowsPlugin as r, DEFAULT_ENTRY as t };
@@ -0,0 +1,105 @@
1
+ import { n as loadTypeScript, r as workflowHandlerSource } from "./graph-DSYE4aER.js";
2
+ //#region src/manifests/step-metadata.ts
3
+ async function findStepMetadataIssues(handler) {
4
+ const api = await loadTypeScript();
5
+ if (!api) return [];
6
+ const ts = api;
7
+ const handlerSource = workflowHandlerSource(handler);
8
+ if (!handlerSource) return [];
9
+ const declaration = ts.createSourceFile("handler.js", `const handler = ${handlerSource};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS).statements[0];
10
+ const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
11
+ if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return [];
12
+ const parameter = fn.parameters[0]?.name;
13
+ if (!parameter || !ts.isIdentifier(parameter)) return [];
14
+ const context = parameter.text;
15
+ function literalString(node) {
16
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
17
+ }
18
+ function property(node, name) {
19
+ if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
20
+ for (const entry of node.properties) {
21
+ if (!ts.isPropertyAssignment(entry)) continue;
22
+ if ((ts.isIdentifier(entry.name) || ts.isStringLiteral(entry.name) ? entry.name.text : void 0) === name) return entry.initializer;
23
+ }
24
+ }
25
+ function repeatedLoopRegion(parent, child) {
26
+ if (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) return parent.statement === child;
27
+ if (ts.isForStatement(parent)) return parent.statement === child || parent.condition === child || parent.incrementor === child;
28
+ return ts.isWhileStatement(parent) || ts.isDoStatement(parent);
29
+ }
30
+ function repeatable(call) {
31
+ let child = call;
32
+ let parent = call.parent;
33
+ while (parent && parent !== fn) {
34
+ if (repeatedLoopRegion(parent, child) || ts.isFunctionLike(parent)) return true;
35
+ child = parent;
36
+ parent = parent.parent;
37
+ }
38
+ return false;
39
+ }
40
+ function loopAncestors(call) {
41
+ const loops = [];
42
+ let child = call;
43
+ let parent = call.parent;
44
+ while (parent && parent !== fn) {
45
+ if (repeatedLoopRegion(parent, child)) loops.push(parent);
46
+ child = parent;
47
+ parent = parent.parent;
48
+ }
49
+ return loops;
50
+ }
51
+ function isDirectSequentialLoopStep(loop, call) {
52
+ if (!ts.isForOfStatement(loop) || loop.awaitModifier || !ts.isVariableDeclarationList(loop.initializer)) return false;
53
+ const declarations = loop.initializer.declarations;
54
+ if (declarations.length !== 1 || !ts.isIdentifier(declarations[0].name) || declarations[0].initializer) return false;
55
+ let statement = loop.statement;
56
+ if (ts.isBlock(statement)) statement = statement.statements.length === 1 ? statement.statements[0] : void 0;
57
+ if (!statement || !ts.isExpressionStatement(statement)) return false;
58
+ let expression = statement.expression;
59
+ while (ts.isParenthesizedExpression(expression)) expression = expression.expression;
60
+ if (!ts.isAwaitExpression(expression)) return false;
61
+ let awaited = expression.expression;
62
+ while (ts.isParenthesizedExpression(awaited)) awaited = awaited.expression;
63
+ return awaited === call;
64
+ }
65
+ const issues = [];
66
+ const groups = /* @__PURE__ */ new Set();
67
+ const visit = (node) => {
68
+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && (node.expression.name.text === "step" || node.expression.name.text === "llm" || node.expression.name.text === "connector")) {
69
+ const method = node.expression.name.text;
70
+ const stepId = literalString(method === "llm" ? property(node.arguments[1], "id") : node.arguments[0]);
71
+ const loops = loopAncestors(node);
72
+ if (loops.length > 0 && (loops.length !== 1 || !isDirectSequentialLoopStep(loops[0], node))) issues.push({
73
+ kind: "loop-form",
74
+ method,
75
+ ...stepId === void 0 ? {} : { stepId }
76
+ });
77
+ const meta = property(node.arguments[method === "llm" ? 1 : 2], "meta");
78
+ if (literalString(property(meta, "description")) === void 0) issues.push({
79
+ kind: "description",
80
+ method,
81
+ ...stepId === void 0 ? {} : { stepId }
82
+ });
83
+ if (repeatable(node)) {
84
+ const group = property(meta, "group");
85
+ const groupId = literalString(property(group, "id"));
86
+ const label = literalString(property(group, "label"));
87
+ if (groupId === void 0 || label === void 0) issues.push({
88
+ kind: "group",
89
+ method,
90
+ ...stepId === void 0 ? {} : { stepId }
91
+ });
92
+ else if (groups.has(groupId)) issues.push({
93
+ kind: "duplicate-group",
94
+ groupId
95
+ });
96
+ else groups.add(groupId);
97
+ }
98
+ }
99
+ ts.forEachChild(node, visit);
100
+ };
101
+ visit(fn);
102
+ return issues;
103
+ }
104
+ //#endregion
105
+ export { findStepMetadataIssues };
package/dist/vite.d.ts CHANGED
@@ -10,12 +10,10 @@ interface WorkflowsPluginOptions {
10
10
  path?: string;
11
11
  /** Route parameter carrying the workflow ID. @default "workflowId" */
12
12
  workflowIdParam?: string;
13
- /** @default false */
14
- runRoute?: boolean;
15
13
  }
16
14
  /**
17
- * Build the collection's manifests and, with `runRoute`, emit the route serving
18
- * them; one `entry` feeds both, so the two can never describe different sets.
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.
19
17
  */
20
18
  declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
21
19
  //#endregion