@lovable.dev/workflows-sdk 0.0.0-dev.3 → 0.0.0-dev.4

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
@@ -46,22 +46,136 @@ definitions as immutable after registration.
46
46
  See [the authoring example](examples/src/lib/workflows/greet/index.ts) for schemas,
47
47
  typed middleware, and a durable step. The package typecheck includes this example.
48
48
 
49
+ ## Triggers
50
+
51
+ A workflow runs when something triggers it, and a schedule is the first kind of
52
+ trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
53
+ and each carries a `type` naming its kind. Webhook and app-event triggers will
54
+ join the same array.
55
+
56
+ A schedule's *cadence* is how often the clock fires. `every()`, `hourly()`,
57
+ `daily()`, and `weekly()` build one; there is no raw cron.
58
+
49
59
  ## Schedules
50
60
 
51
- Declare a schedule with `defineSchedule({ id, workflow, cron, timeZone, input })`
52
- and include it in `registerWorkflows({ workflows, schedules })`. `workflow` refers
53
- to the same definition object included in `workflows`; `input` is required and
54
- inferred from that workflow. Multiple schedules can target one workflow.
61
+ Declare a schedule with `defineSchedule({ id, workflow, cadence, timeZone, input })` and
62
+ include it in `registerWorkflows({ workflows, triggers })`. `workflow` refers to
63
+ the same definition object included in `workflows`; `input` is required and
64
+ inferred from that workflow. Multiple schedules can target one workflow. Schedule
65
+ IDs must be unique within the app's collection. This API declares schedules but
66
+ does not install timers or start runs.
55
67
 
56
- Use a five-field cron expression (minute, hour, day, month, weekday) and an IANA
57
- time zone; the default is UTC. Schedule IDs must be unique within the app's
58
- collection. Registration checks field count and time zone; cron syntax and
59
- calendar semantics remain the engine's responsibility. This API declares
60
- schedules but does not install timers or start runs. Periodic intervals,
61
- catch-up, and overlap policies remain follow-ups.
68
+ ```ts
69
+ import { daily, defineSchedule, every, hourly, weekly } from "@lovable.dev/workflows-sdk";
70
+
71
+ defineSchedule({ id: "heartbeat", workflow: sync, cadence: every("5m"), timeZone: "UTC", input: {} });
72
+ defineSchedule({ id: "sweep", workflow: sync, cadence: hourly({ at: ":30" }), timeZone: "UTC", input: {} });
73
+ defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
74
+
75
+ defineSchedule({
76
+ id: "weekday-digest",
77
+ workflow: digest,
78
+ cadence: daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] }),
79
+ timeZone: "America/New_York",
80
+ smear: { window: "15m" },
81
+ input: {},
82
+ });
83
+
84
+ defineSchedule({
85
+ id: "monday-report",
86
+ workflow: report,
87
+ cadence: weekly({ on: "monday", at: "07:00" }),
88
+ timeZone: "Europe/Stockholm",
89
+ input: {},
90
+ });
91
+ ```
62
92
 
63
- The [example](examples/src/lib/workflows/index.ts) declares a daily greeting at 09:00 in
64
- Europe/Stockholm with static workflow input.
93
+ | Field | Default | Meaning |
94
+ | --- | --- | --- |
95
+ | `cadence` | — | `every()`, `hourly()`, `daily()`, or `weekly()` |
96
+ | `timeZone` | — | IANA region name the cadence is interpreted in |
97
+ | `overlapPolicy` | `"skip"` | `skip`, `cancel-previous`, or `terminate-previous` |
98
+ | `enabled` | `true` | `false` declares a paused schedule without deleting it |
99
+ | `smear` | see below | `false`, or `{ window: "15m" }` to spread firings over a window |
100
+
101
+ There are four cadences and no raw cron, so every schedule has a firing period
102
+ the SDK can compute and a calendar the SDK can check. `at` pins the position
103
+ inside the period on all three calendar cadences, and omitting it hands that
104
+ position to the smear:
105
+
106
+ | Cadence | Pins | Example | Derived `cron` |
107
+ | --- | --- | --- | --- |
108
+ | `every(interval)` | — | `every("5m")` | `*/5 * * * *` |
109
+ | `hourly({ at })` | minute past the hour | `hourly({ at: ":30" })` | `30 * * * *` |
110
+ | `daily({ at, days })` | time of day, days of week | `daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] })` | `0 9 * * 1-5` |
111
+ | `weekly({ on, at })` | one day, time of day | `weekly({ on: "monday", at: "07:00" })` | `0 7 * * 1` |
112
+
113
+ `every` takes a whole number of minutes, hours, or days that divides its unit
114
+ evenly — `1m` through `30m`, `1h` through `12h`, or `1d`. `hourly({ at: ":30" })`
115
+ carries the leading colon so a minute past the hour can never be misread as an
116
+ hour of the day. `days` accepts `"mon"` or `"monday"` in any case and is stored
117
+ sorted and deduplicated, so two orderings of one weekday set are one schedule.
118
+
119
+ `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
120
+ and resolves into exactly that cadence. There is one internal representation of
121
+ a day-restricted schedule, so the two spellings emit byte-identical manifests
122
+ and hash alike. There is no `"weekdays"` or `"weekends"` shorthand: it would add
123
+ a third spelling of a set `days` already states, and "the weekend" is Friday and
124
+ Saturday in much of the world, so the word would quietly mean the wrong days.
125
+
126
+ The manifest still carries a five-field `cron` string derived from the cadence,
127
+ because the engine registers native schedules that take cron. Apps no longer
128
+ write it.
129
+
130
+ ### Time zone
131
+
132
+ `timeZone` is required on every schedule. There is no default, because every
133
+ available default is wrong: `daily({ at: "09:00" })` in UTC is not the 09:00 a
134
+ reader of the digest expects, and the build machine's own zone would make one
135
+ app source fire at different times depending on where it was built.
136
+
137
+ It must be an IANA region name such as `"Europe/Stockholm"`, or `"UTC"`.
138
+ Fixed offsets and abbreviations — `"+05:00"`, `"-0800"`, `"EST"` — are
139
+ rejected even though the platform accepts them: they do not observe daylight
140
+ saving, so `"EST"` is an hour off US Eastern for two-thirds of the year.
141
+ `every()` needs one too, since its derived cron anchors to hour and day
142
+ boundaries that a DST change moves.
143
+
144
+ Everything is validated when the schedule is defined, at build time: a malformed
145
+ interval, time of day, or weekday name, an unknown `overlapPolicy`, a missing or
146
+ non-IANA zone, and a smear window wider than the cadence's own firing period all
147
+ fail the build.
148
+
149
+ ### Smear
150
+
151
+ Tens of thousands of apps declaring `daily()` must not fire in the same minute.
152
+ A schedule therefore carries a smear *policy*, not a concrete offset. A cadence
153
+ that leaves its position in the period unpinned defaults to spreading over that
154
+ whole period: bare `daily()` to `{ strategy: "hash", windowSeconds: 86400 }` and
155
+ bare `hourly()` to `{ strategy: "hash", windowSeconds: 3600 }`. Every pinned
156
+ cadence — `every`, `hourly({ at })`, `daily({ at })`, `weekly({ on, at })` —
157
+ defaults to `{ strategy: "none" }`, because the app author chose the time.
158
+ `smear: false` on an unpinned cadence is rejected: pass `{ at }` instead.
159
+
160
+ The concrete offset is derived once, when the control plane registers the
161
+ manifest, as `fnv1a64(projectId + "\0" + scheduleId) % windowSeconds` seconds
162
+ after the manifest's `cron`. That keeps the manifest project-independent and
163
+ therefore content-addressable, while giving two projects that both name a
164
+ schedule `digest` different fire minutes, and giving one project the same fire
165
+ minute across every rebuild. `smearOffsetSeconds(projectId, scheduleId,
166
+ windowSeconds)` is the reference implementation the engine and the run UI agree
167
+ with.
168
+
169
+ Any cadence can opt in with `smear: { window }`. The window may never exceed the
170
+ cadence's own firing period, or two firings would overrun each other; the bound
171
+ applies to every cadence, since every cadence's period is computable. For a day
172
+ set the period is the shortest gap between two firings, not the repeat length:
173
+ `daily({ days: ["mon", "fri"] })` fires again in three days and then in four, so
174
+ its bound is three days — capped, as every window is, at `1d`.
175
+
176
+ The [example](examples/src/lib/workflows/index.ts) declares a 09:00 greeting in
177
+ Europe/Stockholm, a smeared weekday greeting in America/New_York, a Monday
178
+ report, a five-minute heartbeat, an hourly sweep, and a paused daily digest.
65
179
 
66
180
  ## Manifest generation
67
181
 
@@ -74,9 +188,12 @@ Generation errors fail the build. See [the Vite example](examples/vite.config.ts
74
188
 
75
189
  Each version-1 manifest contains a single `workflow` with its ID, description,
76
190
  version, and input/output/state JSON Schemas, a `graph` for visualization, and a
77
- `schedules` array containing only that workflow's schedules and static inputs. It is an SDK discovery format,
78
- not the engine's deployment or execution contract. Handlers and middleware stay
79
- in app code. Schedule IDs and JSON object keys are sorted for stable output.
191
+ `triggers` array containing only that workflow's triggers and static inputs. Each
192
+ entry names its kind in `type` — `"schedule"` today — and a schedule entry carries
193
+ its `cadence`, derived `cron`, `timeZone`, `enabled`, `overlapPolicy`, `smear`, and
194
+ `input`. It is an SDK discovery format, not the engine's deployment or execution
195
+ contract. Handlers and middleware stay in app code. Triggers and JSON object keys
196
+ are sorted for stable output.
80
197
 
81
198
  The SDK manages the JSON files in `.lovable/workflows/`. Successful generation
82
199
  removes manifests for deleted or renamed workflows; an empty collection removes
@@ -140,6 +257,7 @@ partial graph. A handler with no steps can have an empty graph.
140
257
 
141
258
  Connect the manifest and app code to Lovable deployment and runtime execution.
142
259
  Define support for TanStack primitives, version routing, and schedule policies.
260
+ Add webhook and app-event triggers to the same `triggers` array.
143
261
 
144
262
  ## Publishing dev builds
145
263
 
@@ -155,7 +273,8 @@ Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
155
273
  the exact version shown in the workflow run's summary. `latest` tracks every dev
156
274
  publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
157
275
 
158
- The existing internal [`@lovable/workflow-sdk`](../../packages/workflow-sdk)
276
+ The engine's embedded SDK
277
+ ([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
159
278
  provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
160
279
  for separating authoring, manifest extraction, and framework integration. The
161
280
  workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
@@ -0,0 +1,333 @@
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 MINUTE_DIVISORS = [
9
+ 1,
10
+ 2,
11
+ 3,
12
+ 4,
13
+ 5,
14
+ 6,
15
+ 10,
16
+ 12,
17
+ 15,
18
+ 20,
19
+ 30
20
+ ];
21
+ const HOUR_DIVISORS = [
22
+ 1,
23
+ 2,
24
+ 3,
25
+ 4,
26
+ 6,
27
+ 8,
28
+ 12
29
+ ];
30
+ const WEEKDAYS = [
31
+ "mon",
32
+ "tue",
33
+ "wed",
34
+ "thu",
35
+ "fri",
36
+ "sat",
37
+ "sun"
38
+ ];
39
+ const WEEKDAY_NAMES = {
40
+ mon: "mon",
41
+ monday: "mon",
42
+ tue: "tue",
43
+ tuesday: "tue",
44
+ wed: "wed",
45
+ wednesday: "wed",
46
+ thu: "thu",
47
+ thursday: "thu",
48
+ fri: "fri",
49
+ friday: "fri",
50
+ sat: "sat",
51
+ saturday: "sat",
52
+ sun: "sun",
53
+ sunday: "sun"
54
+ };
55
+ const CRON_DAY = {
56
+ sun: 0,
57
+ mon: 1,
58
+ tue: 2,
59
+ wed: 3,
60
+ thu: 4,
61
+ fri: 5,
62
+ sat: 6
63
+ };
64
+ function fail$1(message) {
65
+ throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
66
+ }
67
+ function parseWeekday(value, label) {
68
+ const day = typeof value === "string" ? WEEKDAY_NAMES[value.toLowerCase()] : void 0;
69
+ if (day === void 0) fail$1(`${label} names an unknown day "${String(value)}"; use ${WEEKDAYS.join(", ")}`);
70
+ return day;
71
+ }
72
+ function parseDays(value, label) {
73
+ if (!Array.isArray(value) || value.length === 0) fail$1(`${label} must be a non-empty array of days`);
74
+ const days = [...new Set(value.map((entry) => parseWeekday(entry, label)))].sort((a, b) => WEEKDAYS.indexOf(a) - WEEKDAYS.indexOf(b));
75
+ return days.length === WEEKDAYS.length ? null : days;
76
+ }
77
+ function parseTimeOfDay(value, label) {
78
+ if (typeof value !== "string" || !/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(value)) fail$1(`${label}: "${String(value)}" must be a 24-hour "HH:MM" time`);
79
+ return value;
80
+ }
81
+ function every(interval) {
82
+ if (typeof interval !== "string" || !/^[0-9]+[mhd]$/.test(interval)) fail$1(`every("${String(interval)}") must be a whole number of minutes, hours, or days, such as "5m", "2h", or "1d"`);
83
+ const amount = Number(interval.slice(0, -1));
84
+ const unit = interval.slice(-1);
85
+ if (amount < 1) fail$1(`every("${interval}") must be at least one unit`);
86
+ if (unit === "m" && !MINUTE_DIVISORS.includes(amount)) fail$1(`every("${interval}") must divide an hour evenly: ${MINUTE_DIVISORS.map((n) => `${n}m`).join(", ")}`);
87
+ if (unit === "h" && !HOUR_DIVISORS.includes(amount)) fail$1(`every("${interval}") must divide a day evenly: ${HOUR_DIVISORS.map((n) => `${n}h`).join(", ")}`);
88
+ if (unit === "d" && amount !== 1) fail$1(`every("${interval}") supports only "1d"; use daily() for calendar days`);
89
+ return {
90
+ kind: "every",
91
+ seconds: amount * (unit === "m" ? 60 : unit === "h" ? 3600 : 86400)
92
+ };
93
+ }
94
+ function hourly(options = {}) {
95
+ if (options.at === void 0) return {
96
+ kind: "hourly",
97
+ minute: null
98
+ };
99
+ if (typeof options.at !== "string" || !/^:[0-5][0-9]$/.test(options.at)) fail$1(`hourly({ at: "${String(options.at)}" }) must pin a minute past the hour, such as ":30"`);
100
+ return {
101
+ kind: "hourly",
102
+ minute: Number(options.at.slice(1))
103
+ };
104
+ }
105
+ function daily(options = {}) {
106
+ return {
107
+ kind: "daily",
108
+ at: options.at === void 0 ? null : parseTimeOfDay(options.at, "daily({ at })"),
109
+ days: options.days === void 0 ? null : parseDays(options.days, "daily({ days })")
110
+ };
111
+ }
112
+ function weekly(options) {
113
+ if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: "07:00" }`);
114
+ return {
115
+ kind: "daily",
116
+ at: options.at === void 0 ? null : parseTimeOfDay(options.at, "weekly({ at })"),
117
+ days: [parseWeekday(options.on, "weekly({ on })")]
118
+ };
119
+ }
120
+ function isCadence(value) {
121
+ if (typeof value !== "object" || value === null) return false;
122
+ const kind = value.kind;
123
+ return kind === "every" || kind === "hourly" || kind === "daily";
124
+ }
125
+ function cronDayField(days) {
126
+ if (days === null) return "*";
127
+ const numbers = days.map((day) => CRON_DAY[day]).sort((a, b) => a - b);
128
+ const parts = [];
129
+ let start = 0;
130
+ for (let index = 1; index <= numbers.length; index += 1) {
131
+ if (index < numbers.length && numbers[index] === numbers[index - 1] + 1) continue;
132
+ const run = numbers.slice(start, index);
133
+ parts.push(run.length >= 3 ? `${run[0]}-${run[run.length - 1]}` : run.join(","));
134
+ start = index;
135
+ }
136
+ return parts.join(",");
137
+ }
138
+ function cadenceCron(cadence) {
139
+ if (cadence.kind === "every") {
140
+ const seconds = cadence.seconds;
141
+ if (seconds < 3600) return `*/${seconds / 60} * * * *`;
142
+ if (seconds < 86400) return `0 */${seconds / 3600} * * *`;
143
+ return "0 0 * * *";
144
+ }
145
+ if (cadence.kind === "hourly") return `${cadence.minute ?? 0} * * * *`;
146
+ const [hour, minute] = (cadence.at ?? "00:00").split(":");
147
+ return `${Number(minute)} ${Number(hour)} * * ${cronDayField(cadence.days)}`;
148
+ }
149
+ function cadencePeriodSeconds(cadence) {
150
+ if (cadence.kind === "every") return cadence.seconds;
151
+ if (cadence.kind === "hourly") return 3600;
152
+ if (cadence.days === null) return 86400;
153
+ const indexes = cadence.days.map((day) => WEEKDAYS.indexOf(day)).sort((a, b) => a - b);
154
+ let gap = WEEKDAYS.length - indexes[indexes.length - 1] + indexes[0];
155
+ for (let index = 1; index < indexes.length; index += 1) gap = Math.min(gap, indexes[index] - indexes[index - 1]);
156
+ return gap * 86400;
157
+ }
158
+ function parseWindowSeconds(interval, id) {
159
+ if (typeof interval !== "string" || !/^[0-9]+[mhd]$/.test(interval)) fail$1(`schedule "${id}" smear window must be an interval such as "15m", "1h", or "1d"`);
160
+ const amount = Number(interval.slice(0, -1));
161
+ const unit = interval.slice(-1);
162
+ const seconds = amount * (unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
163
+ if (seconds < 60 || seconds > 86400) fail$1(`schedule "${id}" smear window must be between "1m" and "1d"`);
164
+ return seconds;
165
+ }
166
+ //#endregion
167
+ //#region src/core/schedule.ts
168
+ const OVERLAP_POLICIES = [
169
+ "skip",
170
+ "cancel-previous",
171
+ "terminate-previous"
172
+ ];
173
+ function fail(message) {
174
+ throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
175
+ }
176
+ function resolveTimeZone(schedule) {
177
+ const timeZone = schedule.timeZone;
178
+ if (typeof timeZone !== "string" || timeZone === "") fail(`schedule "${schedule.id}" needs a timeZone, such as "Europe/Stockholm" or "UTC"`);
179
+ if (timeZone !== "UTC" && !timeZone.includes("/")) fail(`schedule "${schedule.id}" timeZone "${timeZone}" must be an IANA region name such as "Europe/Stockholm", not a fixed offset or abbreviation`);
180
+ new Intl.DateTimeFormat("en", { timeZone });
181
+ return timeZone;
182
+ }
183
+ function unpinnedWindowSeconds(cadence) {
184
+ if (cadence.kind === "daily" && cadence.at === null) return 86400;
185
+ if (cadence.kind === "hourly" && cadence.minute === null) return 3600;
186
+ return null;
187
+ }
188
+ function resolveSmear(schedule, cadence) {
189
+ const unpinned = unpinnedWindowSeconds(cadence);
190
+ if (schedule.smear === void 0) return unpinned === null ? { strategy: "none" } : {
191
+ strategy: "hash",
192
+ windowSeconds: unpinned
193
+ };
194
+ if (schedule.smear === false || typeof schedule.smear === "object" && "strategy" in schedule.smear && schedule.smear.strategy === "none") {
195
+ if (unpinned !== null) fail(`schedule "${schedule.id}" uses ${cadence.kind}() with no time; pass { at } or keep the smear`);
196
+ return { strategy: "none" };
197
+ }
198
+ if (typeof schedule.smear !== "object") fail(`schedule "${schedule.id}" smear must be false or { window }`);
199
+ const windowSeconds = "window" in schedule.smear ? parseWindowSeconds(schedule.smear.window, schedule.id) : schedule.smear.windowSeconds;
200
+ const period = cadencePeriodSeconds(cadence);
201
+ if (windowSeconds > period) fail(`schedule "${schedule.id}" smear window must not exceed its ${period}s firing period`);
202
+ return {
203
+ strategy: "hash",
204
+ windowSeconds
205
+ };
206
+ }
207
+ function defineSchedule(schedule) {
208
+ assertIdentifier("schedule", schedule.id);
209
+ if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from every(), hourly(), daily(), or weekly()`);
210
+ const cadence = schedule.cadence;
211
+ const cron = cadenceCron(cadence);
212
+ const timeZone = resolveTimeZone(schedule);
213
+ const overlapPolicy = schedule.overlapPolicy ?? "skip";
214
+ if (!OVERLAP_POLICIES.includes(overlapPolicy)) fail(`schedule "${schedule.id}" overlapPolicy must be one of ${OVERLAP_POLICIES.join(", ")}`);
215
+ const enabled = schedule.enabled ?? true;
216
+ if (typeof enabled !== "boolean") fail(`schedule "${schedule.id}" enabled must be a boolean`);
217
+ return {
218
+ ...schedule,
219
+ type: "schedule",
220
+ cadence,
221
+ cron,
222
+ timeZone,
223
+ overlapPolicy,
224
+ enabled,
225
+ smear: resolveSmear(schedule, cadence)
226
+ };
227
+ }
228
+ //#endregion
229
+ //#region src/core/workflow.ts
230
+ function registerWorkflows({ workflows, triggers = [] }) {
231
+ const ids = /* @__PURE__ */ new Set();
232
+ for (const workflow of workflows) {
233
+ if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
234
+ assertIdentifier("workflow", workflow.id);
235
+ 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");
236
+ if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
237
+ ids.add(workflow.id);
238
+ }
239
+ const scheduleIds = /* @__PURE__ */ new Set();
240
+ const registeredTriggers = triggers.map((trigger) => {
241
+ const definition = defineSchedule(trigger);
242
+ if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
243
+ if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
244
+ scheduleIds.add(definition.id);
245
+ return definition;
246
+ });
247
+ return {
248
+ workflows: [...workflows],
249
+ triggers: registeredTriggers
250
+ };
251
+ }
252
+ //#endregion
253
+ //#region src/manifests/json.ts
254
+ function toJson(value, jsonPath, ancestors = /* @__PURE__ */ new Set()) {
255
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
256
+ if (typeof value === "number" && Number.isFinite(value)) return value;
257
+ if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain finite, acyclic JSON values`);
258
+ ancestors.add(value);
259
+ try {
260
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must not contain symbol keys`);
261
+ if (Array.isArray(value)) {
262
+ if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must be a dense JSON array without extra properties`);
263
+ return Array.from(value, (item, index) => toJson(item, `${jsonPath}[${index}]`, ancestors));
264
+ }
265
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain plain JSON objects`);
266
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${jsonPath}.${key}`, ancestors)]));
267
+ } finally {
268
+ ancestors.delete(value);
269
+ }
270
+ }
271
+ //#endregion
272
+ //#region src/manifests/generate.ts
273
+ function serializeSchema(schema, direction, label) {
274
+ if (!schema) return void 0;
275
+ const standard = schema["~standard"];
276
+ if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
277
+ try {
278
+ return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
279
+ } catch (cause) {
280
+ throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
281
+ }
282
+ }
283
+ async function generateManifests(definition) {
284
+ const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
285
+ const collection = registerWorkflows(definition);
286
+ const manifests = [];
287
+ for (const workflow of collection.workflows) {
288
+ if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
289
+ const metadata = {
290
+ id: workflow.id,
291
+ ...workflow.description === void 0 ? {} : { description: workflow.description },
292
+ ...workflow.version === void 0 ? {} : { version: workflow.version },
293
+ ...workflow.inputSchema ? { inputSchema: serializeSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
294
+ ...workflow.outputSchema ? { outputSchema: serializeSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
295
+ ...workflow.stateSchema ? { stateSchema: serializeSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
296
+ };
297
+ const triggers = [];
298
+ for (const schedule of collection.triggers.filter((trigger) => trigger.workflow === workflow)) {
299
+ const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
300
+ const schema = schedule.workflow.inputSchema;
301
+ if (schema) {
302
+ const result = await schema["~standard"].validate(input);
303
+ if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
304
+ }
305
+ triggers.push({
306
+ type: schedule.type,
307
+ id: schedule.id,
308
+ cadence: schedule.cadence,
309
+ cron: schedule.cron,
310
+ timeZone: schedule.timeZone,
311
+ enabled: schedule.enabled,
312
+ overlapPolicy: schedule.overlapPolicy,
313
+ smear: schedule.smear,
314
+ input
315
+ });
316
+ }
317
+ triggers.sort((a, b) => {
318
+ const key = (entry) => `${entry.type}\u0000${entry.id}`;
319
+ return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0;
320
+ });
321
+ const manifest = {
322
+ version: 1,
323
+ workflow: metadata,
324
+ triggers,
325
+ graph: await extractWorkflowGraph(workflow.handler)
326
+ };
327
+ toJson(manifest, "manifest");
328
+ manifests.push(manifest);
329
+ }
330
+ return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
331
+ }
332
+ //#endregion
333
+ export { defineSchedule as a, hourly as c, registerWorkflows as i, weekly as l, createMiddleware as n, daily as o, createWorkflow as r, every as s, generateManifests as t };
package/dist/index.d.ts CHANGED
@@ -1,22 +1,75 @@
1
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/core/cadence.d.ts
3
+ type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
+ type Cadence = {
5
+ readonly kind: "every";
6
+ readonly seconds: number;
7
+ } | {
8
+ readonly kind: "hourly";
9
+ readonly minute: number | null;
10
+ } | {
11
+ readonly kind: "daily";
12
+ readonly at: string | null;
13
+ readonly days: readonly Weekday[] | null;
14
+ };
15
+ declare function every(interval: string): Cadence;
16
+ declare function hourly(options?: {
17
+ at?: string;
18
+ }): Cadence;
19
+ declare function daily(options?: {
20
+ at?: string;
21
+ days?: readonly string[];
22
+ }): Cadence;
23
+ declare function weekly(options: {
24
+ on: string;
25
+ at?: string;
26
+ }): Cadence;
27
+ //#endregion
28
+ //#region src/core/smear.d.ts
29
+ type SmearPolicy = {
30
+ readonly strategy: "none";
31
+ } | {
32
+ readonly strategy: "hash";
33
+ readonly windowSeconds: number;
34
+ };
35
+ declare function smearOffsetSeconds(projectId: string, scheduleId: string, windowSeconds: number): number;
36
+ //#endregion
2
37
  //#region src/core/schedule.d.ts
38
+ type OverlapPolicy = "skip" | "cancel-previous" | "terminate-previous";
39
+ type SmearOption = false | {
40
+ readonly window: string;
41
+ } | SmearPolicy;
3
42
  interface ScheduleDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> {
4
43
  readonly id: string;
5
44
  readonly workflow: TWorkflow;
6
- readonly cron: string;
7
- readonly timeZone?: string;
45
+ readonly cadence: Cadence;
46
+ readonly timeZone: string;
47
+ readonly overlapPolicy?: OverlapPolicy;
48
+ readonly enabled?: boolean;
49
+ readonly smear?: SmearOption;
8
50
  readonly input: WorkflowInput$1<NoInfer<TWorkflow>>;
9
51
  }
10
- declare function defineSchedule<TWorkflow extends AnyWorkflowDefinition$1>(schedule: ScheduleDefinition<TWorkflow>): ScheduleDefinition<TWorkflow>;
52
+ interface ResolvedSchedule<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> extends ScheduleDefinition<TWorkflow> {
53
+ readonly type: "schedule";
54
+ readonly cron: string;
55
+ readonly overlapPolicy: OverlapPolicy;
56
+ readonly enabled: boolean;
57
+ readonly smear: SmearPolicy;
58
+ }
59
+ declare function defineSchedule<TWorkflow extends AnyWorkflowDefinition$1>(schedule: ScheduleDefinition<TWorkflow>): ResolvedSchedule<TWorkflow>;
60
+ //#endregion
61
+ //#region src/core/trigger.d.ts
62
+ type TriggerDefinition = ScheduleDefinition;
63
+ type ResolvedTrigger = ResolvedSchedule;
11
64
  //#endregion
12
65
  //#region src/core/workflow.d.ts
13
66
  interface WorkflowsDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> {
14
67
  readonly workflows: readonly TWorkflow[];
15
- readonly schedules: readonly ScheduleDefinition[];
68
+ readonly triggers: readonly ResolvedTrigger[];
16
69
  }
17
- declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows, schedules }: {
70
+ declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows, triggers }: {
18
71
  workflows: TWorkflows;
19
- schedules?: readonly ScheduleDefinition[];
72
+ triggers?: readonly TriggerDefinition[];
20
73
  }): WorkflowsDefinition<TWorkflows[number]>;
21
74
  //#endregion
22
75
  //#region src/manifests/graph.d.ts
@@ -81,14 +134,19 @@ interface WorkflowManifest {
81
134
  outputSchema?: JsonValue;
82
135
  stateSchema?: JsonValue;
83
136
  };
84
- schedules: {
137
+ triggers: {
138
+ type: "schedule";
85
139
  id: string;
140
+ cadence: Cadence;
86
141
  cron: string;
87
142
  timeZone: string;
143
+ enabled: boolean;
144
+ overlapPolicy: OverlapPolicy;
145
+ smear: SmearPolicy;
88
146
  input: JsonValue;
89
147
  }[];
90
148
  graph: WorkflowGraph;
91
149
  }
92
150
  declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
93
151
  //#endregion
94
- export { type AnyWorkflowDefinition, type Ctx, type ScheduleDefinition, type StepContext, type StepOptions, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, defineSchedule, generateManifests, registerWorkflows };
152
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type SmearOption, type SmearPolicy, 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, every, generateManifests, hourly, registerWorkflows, smearOffsetSeconds, weekly };
package/dist/index.js CHANGED
@@ -1,2 +1,16 @@
1
- import { a as defineSchedule, i as registerWorkflows, n as createMiddleware, r as createWorkflow, t as generateManifests } from "./generate-DFS-ezZy.js";
2
- export { createMiddleware, createWorkflow, defineSchedule, generateManifests, registerWorkflows };
1
+ import { a as defineSchedule, c as hourly, i as registerWorkflows, l as weekly, n as createMiddleware, o as daily, r as createWorkflow, s as every, t as generateManifests } from "./generate-IXn3QGVb.js";
2
+ //#region src/core/smear.ts
3
+ const FNV_OFFSET = 14695981039346656037n;
4
+ const FNV_PRIME = 1099511628211n;
5
+ const MASK = (1n << 64n) - 1n;
6
+ function fnv1a64(value) {
7
+ let hash = FNV_OFFSET;
8
+ for (const byte of new TextEncoder().encode(value)) hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK;
9
+ return hash;
10
+ }
11
+ function smearOffsetSeconds(projectId, scheduleId, windowSeconds) {
12
+ if (!Number.isSafeInteger(windowSeconds) || windowSeconds <= 0) throw new Error("@lovable.dev/workflows-sdk: smear window must be a positive whole number of seconds");
13
+ return Number(fnv1a64(`${projectId}\u0000${scheduleId}`) % BigInt(windowSeconds));
14
+ }
15
+ //#endregion
16
+ export { createMiddleware, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, smearOffsetSeconds, weekly };
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as generateManifests } from "./generate-DFS-ezZy.js";
1
+ import { t as generateManifests } from "./generate-IXn3QGVb.js";
2
2
  import { join, resolve } from "node:path";
3
3
  import { createServer } from "vite";
4
4
  import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
@@ -63,7 +63,7 @@ function workflowsManifest({ entry }) {
63
63
  });
64
64
  try {
65
65
  const module = await server.ssrLoadModule(entryPath);
66
- if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.schedules)) throw new Error(`@lovable.dev/workflows-sdk: ${entry} must default-export a registerWorkflows() collection`);
66
+ if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.triggers)) throw new Error(`@lovable.dev/workflows-sdk: ${entry} must default-export a registerWorkflows() collection`);
67
67
  const manifests = await generateManifests(module.default);
68
68
  await writeManifests(config.root, manifests);
69
69
  } finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.3",
3
+ "version": "0.0.0-dev.4",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "scripts": {
54
54
  "build": "tsdown",
55
- "test": "node --test tests/graph.test.mjs",
55
+ "test": "node --test tests/*.test.mjs",
56
56
  "typecheck": "tsc -p tsconfig.typecheck.json",
57
57
  "check:package": "tmp=$(mktemp -d) && pnpm pack --out \"$tmp/pkg.tgz\" && tar -xzf \"$tmp/pkg.tgz\" -C \"$tmp\" && publint \"$tmp/package\" --strict && attw \"$tmp/pkg.tgz\" && node scripts/check-deps.mjs \"$tmp/package/package.json\""
58
58
  }
@@ -1,115 +0,0 @@
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/schedule.ts
8
- function defineSchedule(schedule) {
9
- assertIdentifier("schedule", schedule.id);
10
- if (typeof schedule.cron !== "string" || schedule.cron.trim().split(/\s+/).length !== 5) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" requires a five-field cron expression`);
11
- const timeZone = schedule.timeZone ?? "UTC";
12
- new Intl.DateTimeFormat("en", { timeZone });
13
- return {
14
- ...schedule,
15
- timeZone
16
- };
17
- }
18
- //#endregion
19
- //#region src/core/workflow.ts
20
- function registerWorkflows({ workflows, schedules = [] }) {
21
- const ids = /* @__PURE__ */ new Set();
22
- for (const workflow of workflows) {
23
- if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
24
- assertIdentifier("workflow", workflow.id);
25
- 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");
26
- if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
27
- ids.add(workflow.id);
28
- }
29
- const scheduleIds = /* @__PURE__ */ new Set();
30
- const registeredSchedules = schedules.map((schedule) => {
31
- const definition = defineSchedule(schedule);
32
- if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
33
- if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
34
- scheduleIds.add(definition.id);
35
- return definition;
36
- });
37
- return {
38
- workflows: [...workflows],
39
- schedules: registeredSchedules
40
- };
41
- }
42
- //#endregion
43
- //#region src/manifests/json.ts
44
- function toJson(value, jsonPath, ancestors = /* @__PURE__ */ new Set()) {
45
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
46
- if (typeof value === "number" && Number.isFinite(value)) return value;
47
- if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain finite, acyclic JSON values`);
48
- ancestors.add(value);
49
- try {
50
- if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must not contain symbol keys`);
51
- if (Array.isArray(value)) {
52
- if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must be a dense JSON array without extra properties`);
53
- return Array.from(value, (item, index) => toJson(item, `${jsonPath}[${index}]`, ancestors));
54
- }
55
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain plain JSON objects`);
56
- return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${jsonPath}.${key}`, ancestors)]));
57
- } finally {
58
- ancestors.delete(value);
59
- }
60
- }
61
- //#endregion
62
- //#region src/manifests/generate.ts
63
- function serializeSchema(schema, direction, label) {
64
- if (!schema) return void 0;
65
- const standard = schema["~standard"];
66
- if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
67
- try {
68
- return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
69
- } catch (cause) {
70
- throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
71
- }
72
- }
73
- async function generateManifests(definition) {
74
- const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
75
- const collection = registerWorkflows(definition);
76
- const manifests = [];
77
- for (const workflow of collection.workflows) {
78
- if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
79
- const metadata = {
80
- id: workflow.id,
81
- ...workflow.description === void 0 ? {} : { description: workflow.description },
82
- ...workflow.version === void 0 ? {} : { version: workflow.version },
83
- ...workflow.inputSchema ? { inputSchema: serializeSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
84
- ...workflow.outputSchema ? { outputSchema: serializeSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
85
- ...workflow.stateSchema ? { stateSchema: serializeSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
86
- };
87
- const schedules = [];
88
- for (const schedule of collection.schedules.filter((schedule) => schedule.workflow === workflow)) {
89
- const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
90
- const schema = schedule.workflow.inputSchema;
91
- if (schema) {
92
- const result = await schema["~standard"].validate(input);
93
- if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
94
- }
95
- schedules.push({
96
- id: schedule.id,
97
- cron: schedule.cron,
98
- timeZone: schedule.timeZone ?? "UTC",
99
- input
100
- });
101
- }
102
- schedules.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
103
- const manifest = {
104
- version: 1,
105
- workflow: metadata,
106
- schedules,
107
- graph: await extractWorkflowGraph(workflow.handler)
108
- };
109
- toJson(manifest, "manifest");
110
- manifests.push(manifest);
111
- }
112
- return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
113
- }
114
- //#endregion
115
- export { defineSchedule as a, registerWorkflows as i, createMiddleware as n, createWorkflow as r, generateManifests as t };