@lovable.dev/workflows-sdk 0.0.0-dev.1 → 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.
@@ -0,0 +1,233 @@
1
+ import { createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
+ //#region src/core/identifier.ts
3
+ function assertIdentifier(kind, id) {
4
+ if (typeof id !== "string" || id.trim() === "" || id !== id.trim()) throw new Error(`@lovable.dev/workflows-sdk: ${kind} IDs must be non-empty and have no surrounding whitespace`);
5
+ }
6
+ //#endregion
7
+ //#region src/core/cadence.ts
8
+ const WEEKDAYS = [
9
+ "mon",
10
+ "tue",
11
+ "wed",
12
+ "thu",
13
+ "fri",
14
+ "sat",
15
+ "sun"
16
+ ];
17
+ const WEEKDAY_NAMES = {
18
+ mon: "mon",
19
+ monday: "mon",
20
+ tue: "tue",
21
+ tuesday: "tue",
22
+ wed: "wed",
23
+ wednesday: "wed",
24
+ thu: "thu",
25
+ thursday: "thu",
26
+ fri: "fri",
27
+ friday: "fri",
28
+ sat: "sat",
29
+ saturday: "sat",
30
+ sun: "sun",
31
+ sunday: "sun"
32
+ };
33
+ function fail$1(message) {
34
+ throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
35
+ }
36
+ function parseWeekday(value, label) {
37
+ const day = typeof value === "string" ? WEEKDAY_NAMES[value.toLowerCase()] : void 0;
38
+ if (day === void 0) fail$1(`${label} names an unknown day "${String(value)}"; use ${WEEKDAYS.join(", ")}`);
39
+ return day;
40
+ }
41
+ function parseDays(value, label) {
42
+ if (!Array.isArray(value) || value.length === 0) fail$1(`${label} must be a non-empty array of days`);
43
+ const days = [...new Set(value.map((entry) => parseWeekday(entry, label)))].sort((a, b) => WEEKDAYS.indexOf(a) - WEEKDAYS.indexOf(b));
44
+ return days.length === WEEKDAYS.length ? null : days;
45
+ }
46
+ function parseHoursOfDay(value, label) {
47
+ const entries = Array.isArray(value) ? value : [value];
48
+ if (entries.length === 0) fail$1(`${label} must name at least one hour`);
49
+ for (const entry of entries) if (!Number.isInteger(entry) || entry < 0 || entry > 23) fail$1(`${label}: ${JSON.stringify(entry)} must be a whole hour from 0 to 23; the platform picks the minute`);
50
+ return [...new Set(entries)].sort((a, b) => a - b);
51
+ }
52
+ function hourly(options) {
53
+ if (options !== void 0) fail$1(`hourly() takes no options; the platform decides where in the hour a schedule runs`);
54
+ return { kind: "hourly" };
55
+ }
56
+ function daily(options = {}) {
57
+ return {
58
+ kind: "daily",
59
+ at: options.at === void 0 ? null : parseHoursOfDay(options.at, "daily({ at })"),
60
+ days: options.days === void 0 ? null : parseDays(options.days, "daily({ days })")
61
+ };
62
+ }
63
+ function weekly(options) {
64
+ if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: 7 }`);
65
+ return {
66
+ kind: "daily",
67
+ at: options.at === void 0 ? null : parseHoursOfDay(options.at, "weekly({ at })"),
68
+ days: [parseWeekday(options.on, "weekly({ on })")]
69
+ };
70
+ }
71
+ function isHourSet(value) {
72
+ if (value === null) return true;
73
+ if (!Array.isArray(value) || value.length === 0) return false;
74
+ return value.every((hour, index) => Number.isInteger(hour) && hour >= 0 && hour <= 23 && (index === 0 || hour > value[index - 1]));
75
+ }
76
+ function isDaySet(value) {
77
+ if (value === null) return true;
78
+ if (!Array.isArray(value) || value.length === 0 || value.length >= WEEKDAYS.length) return false;
79
+ const indexes = value.map((day) => WEEKDAYS.indexOf(day));
80
+ return indexes.every((index, position) => index >= 0 && (position === 0 || index > indexes[position - 1]));
81
+ }
82
+ function isCadence(value) {
83
+ if (typeof value !== "object" || value === null) return false;
84
+ const cadence = value;
85
+ if (cadence.kind === "hourly") return Object.keys(cadence).length === 1;
86
+ if (cadence.kind === "daily") return isHourSet(cadence.at) && isDaySet(cadence.days);
87
+ return false;
88
+ }
89
+ //#endregion
90
+ //#region src/core/schedule.ts
91
+ const OVERLAP_POLICIES = [
92
+ "skip",
93
+ "allow",
94
+ "buffer-one"
95
+ ];
96
+ function fail(message) {
97
+ throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
98
+ }
99
+ const CANONICAL_ZONES = new Set(typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []);
100
+ function resolveTimeZone(schedule) {
101
+ const timeZone = schedule.timeZone;
102
+ if (typeof timeZone !== "string" || timeZone === "") fail(`schedule "${schedule.id}" needs a timeZone, such as "Europe/Stockholm" or "UTC"`);
103
+ if (timeZone !== "UTC" && CANONICAL_ZONES.size > 0 && !CANONICAL_ZONES.has(timeZone)) fail(`schedule "${schedule.id}" timeZone "${timeZone}" must be "UTC" or a canonical IANA name such as "Europe/Stockholm"; fixed offsets and aliases such as "EST", "GMT", "Etc/GMT+5", and "US/Pacific" are not accepted`);
104
+ new Intl.DateTimeFormat("en", { timeZone });
105
+ return timeZone;
106
+ }
107
+ function defineSchedule(schedule) {
108
+ assertIdentifier("schedule", schedule.id);
109
+ if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from hourly(), daily(), or weekly()`);
110
+ const cadence = schedule.cadence;
111
+ const timeZone = resolveTimeZone(schedule);
112
+ const overlapPolicy = schedule.overlapPolicy ?? "skip";
113
+ if (!OVERLAP_POLICIES.includes(overlapPolicy)) fail(`schedule "${schedule.id}" overlapPolicy must be one of ${OVERLAP_POLICIES.join(", ")}`);
114
+ const enabled = schedule.enabled ?? true;
115
+ if (typeof enabled !== "boolean") fail(`schedule "${schedule.id}" enabled must be a boolean`);
116
+ return {
117
+ ...schedule,
118
+ type: "schedule",
119
+ cadence,
120
+ timeZone,
121
+ overlapPolicy,
122
+ enabled
123
+ };
124
+ }
125
+ //#endregion
126
+ //#region src/core/workflow.ts
127
+ function registerWorkflows(definition) {
128
+ for (const key of Object.keys(definition)) {
129
+ if (key === "workflows" || key === "triggers") continue;
130
+ throw new Error(key === "schedules" ? `@lovable.dev/workflows-sdk: registerWorkflows() no longer takes "schedules"; rename the key to "triggers"` : `@lovable.dev/workflows-sdk: registerWorkflows() does not take "${key}"`);
131
+ }
132
+ const { workflows, triggers = [] } = definition;
133
+ const ids = /* @__PURE__ */ new Set();
134
+ for (const workflow of workflows) {
135
+ if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
136
+ assertIdentifier("workflow", workflow.id);
137
+ if (!/^[a-z0-9][a-z0-9_-]{0,127}$/.test(workflow.id)) throw new Error("@lovable.dev/workflows-sdk: workflow names must be 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
138
+ if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
139
+ ids.add(workflow.id);
140
+ }
141
+ const scheduleIds = /* @__PURE__ */ new Set();
142
+ const registeredTriggers = triggers.map((trigger) => {
143
+ const definition = defineSchedule(trigger);
144
+ if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
145
+ if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
146
+ scheduleIds.add(definition.id);
147
+ return definition;
148
+ });
149
+ return {
150
+ workflows: [...workflows],
151
+ triggers: registeredTriggers
152
+ };
153
+ }
154
+ //#endregion
155
+ //#region src/manifests/json.ts
156
+ function toJson(value, jsonPath, ancestors = /* @__PURE__ */ new Set()) {
157
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
158
+ if (typeof value === "number" && Number.isFinite(value)) return value;
159
+ if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain finite, acyclic JSON values`);
160
+ ancestors.add(value);
161
+ try {
162
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must not contain symbol keys`);
163
+ if (Array.isArray(value)) {
164
+ if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must be a dense JSON array without extra properties`);
165
+ return Array.from(value, (item, index) => toJson(item, `${jsonPath}[${index}]`, ancestors));
166
+ }
167
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain plain JSON objects`);
168
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${jsonPath}.${key}`, ancestors)]));
169
+ } finally {
170
+ ancestors.delete(value);
171
+ }
172
+ }
173
+ //#endregion
174
+ //#region src/manifests/generate.ts
175
+ function serializeSchema(schema, direction, label) {
176
+ if (!schema) return void 0;
177
+ const standard = schema["~standard"];
178
+ if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
179
+ try {
180
+ return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
181
+ } catch (cause) {
182
+ throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
183
+ }
184
+ }
185
+ async function generateManifests(definition) {
186
+ const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
187
+ const collection = registerWorkflows(definition);
188
+ const manifests = [];
189
+ for (const workflow of collection.workflows) {
190
+ if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
191
+ const metadata = {
192
+ id: workflow.id,
193
+ ...workflow.description === void 0 ? {} : { description: workflow.description },
194
+ ...workflow.version === void 0 ? {} : { version: workflow.version },
195
+ ...workflow.inputSchema ? { inputSchema: serializeSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
196
+ ...workflow.outputSchema ? { outputSchema: serializeSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
197
+ ...workflow.stateSchema ? { stateSchema: serializeSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
198
+ };
199
+ const triggers = [];
200
+ for (const schedule of collection.triggers.filter((trigger) => trigger.workflow === workflow)) {
201
+ const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
202
+ const schema = schedule.workflow.inputSchema;
203
+ if (schema) {
204
+ const result = await schema["~standard"].validate(input);
205
+ if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
206
+ }
207
+ triggers.push({
208
+ type: schedule.type,
209
+ id: schedule.id,
210
+ cadence: schedule.cadence,
211
+ timeZone: schedule.timeZone,
212
+ enabled: schedule.enabled,
213
+ overlapPolicy: schedule.overlapPolicy,
214
+ input
215
+ });
216
+ }
217
+ triggers.sort((a, b) => {
218
+ const key = (entry) => `${entry.type}\u0000${entry.id}`;
219
+ return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0;
220
+ });
221
+ const manifest = {
222
+ version: 1,
223
+ workflow: metadata,
224
+ triggers,
225
+ graph: await extractWorkflowGraph(workflow.handler)
226
+ };
227
+ toJson(manifest, "manifest");
228
+ manifests.push(manifest);
229
+ }
230
+ return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
231
+ }
232
+ //#endregion
233
+ export { defineSchedule as a, weekly as c, registerWorkflows as i, createMiddleware as n, daily as o, createWorkflow as r, hourly as s, generateManifests as t };
@@ -1,6 +1,24 @@
1
- import * as ts from "typescript";
2
- //#region src/graph-extract.ts
3
- function extractWorkflowGraph(handler) {
1
+ //#region src/manifests/graph.ts
2
+ const durableMethods = {
3
+ step: 0,
4
+ approve: 0,
5
+ waitForEvent: 0,
6
+ sleep: 0,
7
+ sleepUntil: 0
8
+ };
9
+ let loaded;
10
+ async function loadTypeScript() {
11
+ if (loaded !== void 0) return loaded;
12
+ try {
13
+ const module = await import("typescript");
14
+ const api = module.default ?? module;
15
+ loaded = typeof api?.createSourceFile === "function" ? api : null;
16
+ } catch {
17
+ loaded = null;
18
+ }
19
+ return loaded;
20
+ }
21
+ async function extractWorkflowGraph(handler) {
4
22
  const graph = {
5
23
  source: "inferred",
6
24
  scope: "handler",
@@ -9,7 +27,6 @@ function extractWorkflowGraph(handler) {
9
27
  edges: [],
10
28
  diagnostics: []
11
29
  };
12
- const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
13
30
  function addNode(node, parents) {
14
31
  const id = `node-${graph.nodes.length}`;
15
32
  graph.nodes.push({
@@ -23,14 +40,24 @@ function extractWorkflowGraph(handler) {
23
40
  });
24
41
  return [id];
25
42
  }
26
- function unknown(reason, parents) {
43
+ function degrade(reason) {
27
44
  graph.complete = false;
28
45
  if (!graph.diagnostics.includes(reason)) graph.diagnostics.push(reason);
46
+ }
47
+ function unknown(reason, parents) {
48
+ degrade(reason);
29
49
  return addNode({
30
50
  kind: "unknown",
31
51
  label: reason
32
52
  }, parents);
33
53
  }
54
+ const api = await loadTypeScript();
55
+ if (!api) {
56
+ unknown("Install typescript to infer step graphs", []);
57
+ return graph;
58
+ }
59
+ const ts = api;
60
+ const source = ts.createSourceFile("handler.js", `const handler = ${Function.prototype.toString.call(handler)};`, ts.ScriptTarget.ESNext, true, ts.ScriptKind.JS);
34
61
  const declaration = source.statements[0];
35
62
  const fn = declaration && ts.isVariableStatement(declaration) ? declaration.declarationList.declarations[0]?.initializer : void 0;
36
63
  if (!fn || !ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn) || source.text.includes("[native code]")) {
@@ -47,22 +74,94 @@ function extractWorkflowGraph(handler) {
47
74
  if (skipFunctions && ts.isFunctionLike(node)) return false;
48
75
  return predicate(node) || Boolean(ts.forEachChild(node, (child) => contains(child, predicate, skipFunctions) || void 0));
49
76
  }
50
- function contextStep(node) {
51
- return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text === "step";
77
+ function durableCall(node) {
78
+ return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in durableMethods;
79
+ }
80
+ function stringLiteral(node) {
81
+ return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
82
+ }
83
+ function numberLiteral(node) {
84
+ if (!node || !ts.isNumericLiteral(node)) return void 0;
85
+ const value = Number(node.text);
86
+ return Number.isFinite(value) ? value : void 0;
87
+ }
88
+ function readableOptions(node) {
89
+ return node && ts.isObjectLiteralExpression(node) && node.properties.every(ts.isPropertyAssignment) ? node : void 0;
90
+ }
91
+ function option(options, name) {
92
+ for (const property of options?.properties ?? []) {
93
+ if (!ts.isPropertyAssignment(property)) continue;
94
+ if ((ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0) === name) return property.initializer;
95
+ }
96
+ }
97
+ function durableNode(call, parents) {
98
+ const method = call.expression.name.text;
99
+ if (method === "step") {
100
+ const stepId = stringLiteral(call.arguments[0]);
101
+ if (stepId === void 0) return unknown("Dynamic step IDs are not supported yet", parents);
102
+ return addNode({
103
+ kind: "step",
104
+ stepId,
105
+ label: stepId
106
+ }, parents);
107
+ }
108
+ if (method === "approve") {
109
+ const options = readableOptions(call.arguments[0]);
110
+ const title = stringLiteral(option(options, "title"));
111
+ if (title === void 0) return unknown("Dynamic approval titles are not supported yet", parents);
112
+ const given = option(options, "description");
113
+ const description = stringLiteral(given);
114
+ if (given && description === void 0) degrade("Dynamic approval descriptions are not recorded");
115
+ return addNode({
116
+ kind: "approve",
117
+ config: {
118
+ title,
119
+ ...description === void 0 ? {} : { description }
120
+ },
121
+ label: title
122
+ }, parents);
123
+ }
124
+ if (method === "waitForEvent") {
125
+ const event = stringLiteral(call.arguments[0]);
126
+ if (event === void 0) return unknown("Dynamic event names are not supported yet", parents);
127
+ const options = readableOptions(call.arguments[1]);
128
+ if (call.arguments[1] && !options) degrade("Dynamic waitForEvent options are not recorded");
129
+ const given = option(options, "deadline");
130
+ const deadline = numberLiteral(given);
131
+ if (given && deadline === void 0) degrade("Dynamic waitForEvent deadlines are not recorded");
132
+ return addNode({
133
+ kind: "wait-for-event",
134
+ config: {
135
+ event,
136
+ ...deadline === void 0 ? {} : { deadline }
137
+ },
138
+ label: event
139
+ }, parents);
140
+ }
141
+ if (method === "sleep") {
142
+ const ms = numberLiteral(call.arguments[0]);
143
+ if (ms === void 0) return unknown("Dynamic sleep durations are not supported yet", parents);
144
+ return addNode({
145
+ kind: "sleep",
146
+ config: { ms },
147
+ label: `sleep ${ms}ms`
148
+ }, parents);
149
+ }
150
+ const timestamp = numberLiteral(call.arguments[0]);
151
+ if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
152
+ return addNode({
153
+ kind: "sleep-until",
154
+ config: { timestamp },
155
+ label: `sleep until ${timestamp}`
156
+ }, parents);
52
157
  }
53
158
  function expression(node, parents, awaited = false) {
54
159
  if (ts.isParenthesizedExpression(node)) return expression(node.expression, parents, awaited);
55
160
  if (ts.isAwaitExpression(node)) return expression(node.expression, parents, true);
56
- if (contextStep(node)) {
57
- if (!awaited) return unknown("Unawaited steps are not supported yet", parents);
58
- const stepId = node.arguments[0];
59
- if (!stepId || !ts.isStringLiteral(stepId) && !ts.isNoSubstitutionTemplateLiteral(stepId)) return unknown("Dynamic step IDs are not supported yet", parents);
60
- const tails = addNode({
61
- kind: "step",
62
- stepId: stepId.text,
63
- label: stepId.text
64
- }, parents);
65
- if (node.arguments.slice(1).some((argument) => contains(argument, contextStep))) return unknown("Nested steps are not supported yet", tails);
161
+ if (durableCall(node)) {
162
+ if (!awaited) return unknown("Unawaited durable calls are not supported yet", parents);
163
+ const tails = durableNode(node, parents);
164
+ if (node.arguments.some((argument) => contains(argument, durableCall))) return unknown("Nested durable calls are not supported yet", tails);
66
165
  return tails;
67
166
  }
68
167
  if (awaited && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Promise" && node.expression.name.text === "all" && node.arguments.length === 1 && ts.isArrayLiteralExpression(node.arguments[0])) {
package/dist/index.d.ts CHANGED
@@ -1,35 +1,93 @@
1
- import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1, Ctx, StepContext, StepOptions, WorkflowDefinition, WorkflowInput, WorkflowInput as WorkflowInput$1, WorkflowOutput, WorkflowState, createMiddleware, createWorkflow } from "@tanstack/workflow-core";
2
- //#region src/schedule.d.ts
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
+ //#region src/core/cadence.d.ts
3
+ type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
+ type Cadence = {
5
+ readonly kind: "hourly";
6
+ } | {
7
+ readonly kind: "daily";
8
+ readonly at: readonly number[] | null;
9
+ readonly days: readonly Weekday[] | null;
10
+ };
11
+ declare function hourly(options?: never): Cadence;
12
+ declare function daily(options?: {
13
+ at?: number | readonly number[];
14
+ days?: readonly string[];
15
+ }): Cadence;
16
+ declare function weekly(options: {
17
+ on: string;
18
+ at?: number | readonly number[];
19
+ }): Cadence;
20
+ //#endregion
21
+ //#region src/core/schedule.d.ts
22
+ type OverlapPolicy = "skip" | "allow" | "buffer-one";
3
23
  interface ScheduleDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> {
4
24
  readonly id: string;
5
25
  readonly workflow: TWorkflow;
6
- readonly cron: string;
7
- readonly timeZone?: string;
26
+ readonly cadence: Cadence;
27
+ readonly timeZone: string;
28
+ readonly overlapPolicy?: OverlapPolicy;
29
+ readonly enabled?: boolean;
8
30
  readonly input: WorkflowInput$1<NoInfer<TWorkflow>>;
9
31
  }
10
- declare function defineSchedule<TWorkflow extends AnyWorkflowDefinition$1>(schedule: ScheduleDefinition<TWorkflow>): ScheduleDefinition<TWorkflow>;
32
+ interface ResolvedSchedule<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> extends ScheduleDefinition<TWorkflow> {
33
+ readonly type: "schedule";
34
+ readonly overlapPolicy: OverlapPolicy;
35
+ readonly enabled: boolean;
36
+ }
37
+ declare function defineSchedule<TWorkflow extends AnyWorkflowDefinition$1>(schedule: ScheduleDefinition<TWorkflow>): ResolvedSchedule<TWorkflow>;
38
+ //#endregion
39
+ //#region src/core/trigger.d.ts
40
+ type TriggerDefinition = ScheduleDefinition;
41
+ type ResolvedTrigger = ResolvedSchedule;
11
42
  //#endregion
12
- //#region src/register.d.ts
43
+ //#region src/core/workflow.d.ts
13
44
  interface WorkflowsDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> {
14
45
  readonly workflows: readonly TWorkflow[];
15
- readonly schedules: readonly ScheduleDefinition[];
46
+ readonly triggers: readonly ResolvedTrigger[];
16
47
  }
17
- declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows, schedules }: {
48
+ declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>(definition: {
18
49
  workflows: TWorkflows;
19
- schedules?: readonly ScheduleDefinition[];
50
+ triggers?: readonly TriggerDefinition[];
20
51
  }): WorkflowsDefinition<TWorkflows[number]>;
21
52
  //#endregion
22
- //#region src/graph.d.ts
53
+ //#region src/manifests/graph.d.ts
54
+ type WorkflowGraphNodeDetails = {
55
+ kind: "step";
56
+ stepId: string;
57
+ } | {
58
+ kind: "approve";
59
+ config: {
60
+ title: string;
61
+ description?: string;
62
+ };
63
+ } | {
64
+ kind: "wait-for-event";
65
+ config: {
66
+ event: string;
67
+ deadline?: number;
68
+ };
69
+ } | {
70
+ kind: "sleep";
71
+ config: {
72
+ ms: number;
73
+ };
74
+ } | {
75
+ kind: "sleep-until";
76
+ config: {
77
+ timestamp: number;
78
+ };
79
+ } | {
80
+ kind: "unknown";
81
+ };
82
+ type WorkflowGraphNode = {
83
+ id: string;
84
+ label: string;
85
+ } & WorkflowGraphNodeDetails;
23
86
  interface WorkflowGraph {
24
87
  source: "inferred";
25
88
  scope: "handler";
26
89
  complete: boolean;
27
- nodes: {
28
- id: string;
29
- kind: "step" | "unknown";
30
- label: string;
31
- stepId?: string;
32
- }[];
90
+ nodes: WorkflowGraphNode[];
33
91
  edges: {
34
92
  source: string;
35
93
  target: string;
@@ -38,12 +96,12 @@ interface WorkflowGraph {
38
96
  diagnostics: string[];
39
97
  }
40
98
  //#endregion
41
- //#region src/json.d.ts
99
+ //#region src/manifests/json.d.ts
42
100
  type JsonValue = null | boolean | number | string | JsonValue[] | {
43
101
  [key: string]: JsonValue;
44
102
  };
45
103
  //#endregion
46
- //#region src/manifest.d.ts
104
+ //#region src/manifests/generate.d.ts
47
105
  interface WorkflowManifest {
48
106
  version: 1;
49
107
  workflow: {
@@ -54,14 +112,129 @@ interface WorkflowManifest {
54
112
  outputSchema?: JsonValue;
55
113
  stateSchema?: JsonValue;
56
114
  };
57
- schedules: {
115
+ triggers: {
116
+ type: "schedule";
58
117
  id: string;
59
- cron: string;
118
+ cadence: Cadence;
60
119
  timeZone: string;
120
+ enabled: boolean;
121
+ overlapPolicy: OverlapPolicy;
61
122
  input: JsonValue;
62
123
  }[];
63
124
  graph: WorkflowGraph;
64
125
  }
65
126
  declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
66
127
  //#endregion
67
- export { type AnyWorkflowDefinition, type Ctx, type ScheduleDefinition, type StepContext, type StepOptions, type WorkflowDefinition, type WorkflowGraph, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, defineSchedule, generateManifests, registerWorkflows };
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/steps.d.ts
151
+ interface StepsHandlerOptions {
152
+ /** Route parameter carrying the workflow ID. @default "workflowId" */
153
+ workflowIdParam?: string;
154
+ }
155
+ interface RouteCtx {
156
+ request: Request;
157
+ params?: Record<string, string | undefined>;
158
+ }
159
+ type StepsHandler = (ctx: RouteCtx) => Promise<Response>;
160
+ /** Report what a run is waiting on, running nothing. Pins ctx.now/ctx.uuid into
161
+ * `memo` so a later executeSteps replays the same values. */
162
+ declare function createNextStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
163
+ /** Run the requested steps; omitting `steps` runs whatever `nextSteps` would
164
+ * report, advancing the run one wave per call. */
165
+ declare function createExecuteStepsHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
166
+ //#endregion
167
+ //#region src/stacks/tanstack/run.d.ts
168
+ declare function createRunHandler(collection: WorkflowCollection, options?: StepsHandlerOptions): StepsHandler;
169
+ //#endregion
170
+ //#region src/stacks/tanstack/sse.d.ts
171
+ /**
172
+ * Encode a workflow event stream as `text/event-stream`. Each event keeps its
173
+ * engine `type` as the SSE event name and its whole JSON as the data line.
174
+ */
175
+ declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
176
+ //#endregion
177
+ //#region src/runtime/types.d.ts
178
+ /** Durable operations a replay can answer from the memo. */
179
+ type StepKind = "step" | "sleep" | "waitForEvent" | "approve" | "now" | "uuid";
180
+ /**
181
+ * One settled durable operation. The memo is the whole run state: the caller
182
+ * carries it between calls, so no run store is involved.
183
+ */
184
+ interface MemoEntry {
185
+ /** Call order within the pass that recorded it. Reporting only: racing
186
+ * branches can order differently on a later pass, so it is not the key. */
187
+ seq: number;
188
+ stepId: string;
189
+ /** Which call of this `stepId` in the run, from 0. */
190
+ occurrence: number;
191
+ /** Key of the step whose body recorded this, if any; a memoized parent hides it. */
192
+ parent?: string;
193
+ kind: StepKind;
194
+ status: "completed" | "failed";
195
+ result?: unknown;
196
+ error?: string;
197
+ }
198
+ /** A durable operation the replay reached but could not answer. */
199
+ interface StepIntent {
200
+ seq: number;
201
+ stepId: string;
202
+ occurrence: number;
203
+ kind: StepKind;
204
+ /** Kind-specific detail: sleep `ms`, `waitForEvent` name, approval title. */
205
+ config?: Record<string, unknown>;
206
+ }
207
+ interface StepResult {
208
+ seq: number;
209
+ stepId: string;
210
+ occurrence: number;
211
+ kind: StepKind;
212
+ status: "completed" | "failed";
213
+ result?: unknown;
214
+ error?: string;
215
+ }
216
+ type ReplayStatus = "completed" | "failed" | "pending";
217
+ interface ReplayOutcome {
218
+ status: ReplayStatus;
219
+ /** The memo the next call should send back, including entries this pass settled. */
220
+ memo: MemoEntry[];
221
+ /** Operations that still need an answer; empty unless `status` is `pending`. */
222
+ steps: StepIntent[];
223
+ /** Operations this pass executed, in execution order. */
224
+ results: StepResult[];
225
+ /** `ctx.emit` payloads; diagnostic only, never part of replay. */
226
+ emitted: {
227
+ name: string;
228
+ value: Record<string, unknown>;
229
+ }[];
230
+ output?: unknown;
231
+ error?: string;
232
+ }
233
+ /** Identifies one durable operation for `executeSteps`. */
234
+ interface StepSelector {
235
+ stepId: string;
236
+ /** Defaults to 0; needed only when a run calls the same `stepId` more than once. */
237
+ occurrence?: number;
238
+ }
239
+ //#endregion
240
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type MemoEntry, type OverlapPolicy, type ReplayOutcome, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepIntent, type StepKind, type StepOptions, type StepResult, type StepSelector, type StepsHandler, type StepsHandlerOptions, 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, createExecuteStepsHandler, createMiddleware, createNextStepsHandler, createRunHandler, createTanStackWorkflowHandler, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, toServerSentEventsResponse, weekly };