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

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
@@ -53,8 +53,8 @@ trigger: a clock. Triggers go in `registerWorkflows({ workflows, triggers })`,
53
53
  and each carries a `type` naming its kind. Webhook and app-event triggers will
54
54
  join the same array.
55
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.
56
+ A schedule's *cadence* is how often the clock fires. `hourly()`, `daily()`,
57
+ and `weekly()` build one; there is no raw cron.
58
58
 
59
59
  ## Schedules
60
60
 
@@ -66,25 +66,31 @@ IDs must be unique within the app's collection. This API declares schedules but
66
66
  does not install timers or start runs.
67
67
 
68
68
  ```ts
69
- import { daily, defineSchedule, every, hourly, weekly } from "@lovable.dev/workflows-sdk";
69
+ import { daily, defineSchedule, hourly, weekly } from "@lovable.dev/workflows-sdk";
70
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: {} });
71
+ defineSchedule({ id: "sweep", workflow: sync, cadence: hourly(), timeZone: "UTC", input: {} });
73
72
  defineSchedule({ id: "digest", workflow: digest, cadence: daily(), timeZone: "Europe/Stockholm", input: {} });
74
73
 
74
+ defineSchedule({
75
+ id: "refresh",
76
+ workflow: sync,
77
+ cadence: daily({ at: [0, 6, 12, 18] }),
78
+ timeZone: "UTC",
79
+ input: {},
80
+ });
81
+
75
82
  defineSchedule({
76
83
  id: "weekday-digest",
77
84
  workflow: digest,
78
- cadence: daily({ at: "09:00", days: ["mon", "tue", "wed", "thu", "fri"] }),
85
+ cadence: daily({ at: 9, days: ["mon", "tue", "wed", "thu", "fri"] }),
79
86
  timeZone: "America/New_York",
80
- smear: { window: "15m" },
81
87
  input: {},
82
88
  });
83
89
 
84
90
  defineSchedule({
85
91
  id: "monday-report",
86
92
  workflow: report,
87
- cadence: weekly({ on: "monday", at: "07:00" }),
93
+ cadence: weekly({ on: "monday", at: 7 }),
88
94
  timeZone: "Europe/Stockholm",
89
95
  input: {},
90
96
  });
@@ -92,90 +98,130 @@ defineSchedule({
92
98
 
93
99
  | Field | Default | Meaning |
94
100
  | --- | --- | --- |
95
- | `cadence` | — | `every()`, `hourly()`, `daily()`, or `weekly()` |
101
+ | `cadence` | — | `hourly()`, `daily()`, or `weekly()` |
96
102
  | `timeZone` | — | IANA region name the cadence is interpreted in |
97
- | `overlapPolicy` | `"skip"` | `skip`, `cancel-previous`, or `terminate-previous` |
103
+ | `overlapPolicy` | `"skip"` | `skip`, `allow`, or `buffer-one` |
98
104
  | `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.
105
+
106
+ There are three cadences and no raw cron:
107
+
108
+ | Cadence | Says | Example |
109
+ | --- | --- | --- |
110
+ | `hourly()` | once an hour | `hourly()` |
111
+ | `daily({ at, days })` | hours of the day, days of the week | `daily({ at: [0, 6, 12, 18] })` |
112
+ | `weekly({ on, at })` | one weekday, hours of the day | `weekly({ on: "monday", at: 7 })` |
113
+
114
+ **The SDK never derives a cron.** The manifest carries the cadence, and the
115
+ `app-workflows-service` backend translates it when it registers the schedule.
116
+ An app declares intent; one service owns the translation, so there is no second
117
+ implementation to drift. Every cadence here is shaped to be exactly
118
+ translatable — that constraint is why the vocabulary is closed and why `at` is
119
+ whole hours.
120
+
121
+ ### Hours, never minutes
122
+
123
+ `at` is a whole hour, `0` through `23`, or a list of them. There is no minute:
124
+ an app says *which hours*, and the platform picks where inside the hour a run
125
+ actually starts (see [Timing](#timing)). `hourly()` takes no options for the
126
+ same reason. An app that could pin a minute would opt itself out of the smear,
127
+ and the herd would come back.
128
+
129
+ This is also what keeps the vocabulary exactly translatable by the backend.
130
+ Cron pairs every value in its minute field with every value in its hour field,
131
+ so a cadence that could say 09:15 and 17:45 has no faithful cron — it would
132
+ become `15,45 9,17 * * *` and fire four times a day instead of twice. With the
133
+ minute fixed, any set of hours translates exactly.
134
+
135
+ `at` accepts a list, so several runs a day need one schedule rather than
136
+ several: `daily({ at: [0, 6, 12, 18] })` is four evenly spaced runs, and
137
+ `daily({ at: [9, 17] })` is two uneven ones — the start and end of a working
138
+ day, which no fixed interval can express. The list is sorted and deduplicated,
139
+ so two orderings are one schedule.
140
+
141
+ ### One schedule, one representation
118
142
 
119
143
  `weekly({ on, at })` is the single-day shorthand for `daily({ at, days: [on] })`
120
144
  and resolves into exactly that cadence. There is one internal representation of
121
145
  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
146
+ and hash alike.
147
+
148
+ There is no `"weekdays"` or `"weekends"` shorthand: it would add a third
149
+ spelling of a set `days` already states, and "the weekend" is Friday and
124
150
  Saturday in much of the world, so the word would quietly mean the wrong days.
125
151
 
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.
152
+ There is no interval cadence — no `every("6h")`, no `every("3d")`. Intervals
153
+ are not calendar positions and have no faithful cron: `0 0 */3 * *` restarts its
154
+ count every month, so it means "every 3 days" only until the 28th and then fires
155
+ twice in two days. The sub-daily intervals that *are* faithful are exactly the
156
+ ones `daily({ at })` already covers, and `daily({ at: [0, 6, 12, 18] })` says the
157
+ same thing as "every 6 hours" while staying anchored to the calendar and to the
158
+ app's time zone.
159
+
160
+ ## Timing
161
+
162
+ **A declared hour is approximate, and an app does not control how approximate.**
163
+ Tens of thousands of apps declaring `daily()` must not fire in the same minute,
164
+ so the platform spreads each schedule over a window — a *smear* — and then keeps
165
+ that schedule on the same offset for every later run.
166
+
167
+ Apps do not declare the smear, and there is no field for it. The platform
168
+ derives the window per schedule from the cadence, so what an app leaves
169
+ unspecified is exactly what the platform is free to choose:
170
+
171
+ | Cadence | Smeared across |
172
+ | --- | --- |
173
+ | `daily()` | the whole day |
174
+ | `daily({ at })`, `weekly({ on, at })` | a window around each declared hour |
175
+ | `hourly()` | the hour |
176
+
177
+ Higher plans get tighter windows, so a declared 07:00 lands nearer to 07:00 the
178
+ more an app pays; the exact windows belong to the platform and can change
179
+ without an SDK release.
180
+
181
+ Two consequences worth designing around. A schedule that must run at an exact
182
+ instant is not expressible, by design. And the offset is stable per schedule,
183
+ not random per run, so a report that reads "yesterday's rows" reads the same
184
+ shape every day.
185
+
186
+ Neither the smear nor the schedule itself runs yet; see
187
+ [Next PRs](#next-prs).
129
188
 
130
189
  ### Time zone
131
190
 
132
191
  `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`.
192
+ available default is wrong: `daily({ at: 9 })` in UTC is not the 09:00 a reader
193
+ of the digest expects, and the build machine's own zone would make one app
194
+ source fire at different times depending on where it was built.
195
+
196
+ It must be `"UTC"` or a canonical IANA name as `Intl.supportedValuesOf("timeZone")`
197
+ lists it, such as `"Europe/Stockholm"`. That rejects the fixed-offset family
198
+ `Intl` otherwise accepts — `"+05:00"`, `"-0800"`, `"EST"`, `"GMT"`,
199
+ `"Etc/GMT+5"` — none of which observe daylight saving, so `"EST"` is an hour
200
+ off US Eastern for two-thirds of the year, and `"Etc/GMT+5"` is UTC-5 rather
201
+ than UTC+5. It also rejects tzdata's backward-compatibility aliases such as
202
+ `"US/Pacific"`; write the canonical `"America/Los_Angeles"`, so one zone has
203
+ one spelling and one manifest.
204
+
205
+ ### Overlap policy
206
+
207
+ `overlapPolicy` says what happens when an occurrence comes due while the
208
+ previous run is still going: `skip` drops it, `allow` lets runs overlap, and
209
+ `buffer-one` holds the earliest due occurrence and fires it once the in-flight
210
+ run finishes.
211
+
212
+ ### Validation
213
+
214
+ Everything is validated when the schedule is defined, at build time: an hour
215
+ outside `0`-`23`, a fractional hour, a weekday name that is not a weekday, an
216
+ unknown `overlapPolicy`, a missing or non-canonical zone, and a hand-written
217
+ cadence object no constructor produced all fail the build. `registerWorkflows`
218
+ likewise rejects any key other than `workflows` and `triggers`, so a collection
219
+ left on the old `schedules:` name fails the build instead of emitting an empty
220
+ manifest.
175
221
 
176
222
  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.
223
+ Europe/Stockholm, a weekday greeting in America/New_York, a Monday report, a
224
+ four-times-daily refresh, an hourly sweep, and a paused daily digest.
179
225
 
180
226
  ## Manifest generation
181
227
 
@@ -190,8 +236,7 @@ Each version-1 manifest contains a single `workflow` with its ID, description,
190
236
  version, and input/output/state JSON Schemas, a `graph` for visualization, and a
191
237
  `triggers` array containing only that workflow's triggers and static inputs. Each
192
238
  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
239
+ its `cadence`, `timeZone`, `enabled`, `overlapPolicy`, and `input`. It is an SDK discovery format, not the engine's deployment or execution
195
240
  contract. Handlers and middleware stay in app code. Triggers and JSON object keys
196
241
  are sorted for stable output.
197
242
 
@@ -255,32 +300,60 @@ partial graph. A handler with no steps can have an empty graph.
255
300
 
256
301
  ## Run endpoint (TanStack Start)
257
302
 
258
- Pass `runRoute: true` to the same `workflowsPlugin` that writes the manifests. It
259
- then also emits one dynamic route, `src/routes/api/workflows/$workflowId.ts`,
260
- serving every registered workflow. One plugin and one `entry` cover both, so a
261
- manifest can never describe a collection the route does not serve:
303
+ The same `workflowsPlugin` that writes the manifests also emits one dynamic
304
+ route, `src/routes/api/workflows/$workflowId.ts`, serving every registered
305
+ workflow. There is no opt-in: a declared workflow with no endpoint cannot run.
306
+ One plugin and one `entry` cover both, so a manifest can never describe a
307
+ collection the route does not serve:
262
308
 
263
309
  ```ts
264
310
  import { tanstackStart } from "@tanstack/react-start/plugin/vite";
265
311
  import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
266
312
 
267
313
  export default defineConfig({
268
- plugins: [workflowsPlugin({ runRoute: true }), tanstackStart()],
314
+ plugins: [workflowsPlugin(), tanstackStart()],
269
315
  });
270
316
  ```
271
317
 
272
- `runRoute` defaults to `false`. The route is unauthenticated: any caller who
273
- reaches it runs any declared workflow. Turn it on only where that is acceptable,
274
- until signed invocation lands.
318
+ A missing `entry` file is the only thing that suppresses the route: an app with
319
+ no collection gets no endpoint.
320
+
321
+ ### The route is unauthenticated
322
+
323
+ **Any caller who reaches the route can run any declared workflow.** The SDK
324
+ ships no request authentication today; signed invocation is the next piece of
325
+ work on this endpoint. Until it lands, treat the endpoint as public and keep
326
+ anything a stranger must not trigger — spend, mutation of another user's data,
327
+ outbound mail — out of a declared workflow, or guard it inside the handler.
328
+
329
+ Reachability is the lever an app has in the meantime. Public apps expose the
330
+ route to the internet. Workspace and private apps are gated by the Lovable host,
331
+ which is why `path` matters (below).
332
+
333
+ ### Relocating the route with `path`
334
+
335
+ `path` sets the URL prefix; the workflow ID is appended as a dynamic segment,
336
+ and the emitted file name follows the path. Workspace and private apps reach
337
+ anonymous traffic only under an `/api/public` prefix — everything else is
338
+ blocked by the host before it reaches the app — so those projects must move the
339
+ route there for it to be reachable at all:
340
+
341
+ ```ts
342
+ workflowsPlugin({ path: "/api/public/workflows" });
343
+ ```
344
+
345
+ That emits `src/routes/api/public/workflows/$workflowId.ts` and serves
346
+ `POST /api/public/workflows/{workflow-id}`. The trade is explicit: the prefix
347
+ that makes the route reachable also makes it anonymously reachable.
275
348
 
276
349
  The emitted file is thin — it imports the collection and mounts
277
350
  `createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
278
351
  as the route's `POST` handler. All runtime logic stays in the package. The file
279
352
  carries a generated banner, which is the plugin's ownership token: it rewrites
280
- and deletes only files that have it, and deletes its own orphans when `path`,
281
- `workflowIdParam`, or `runRoute` changes. Delete the banner line to take the
282
- route over — the plugin then leaves that file alone, and the build keeps
283
- working.
353
+ and deletes only files that have it, and deletes its own orphans when `path` or
354
+ `workflowIdParam` changes. Delete the banner line to take the route over — the
355
+ plugin then leaves that file alone, and the build keeps working. That is also
356
+ the supported way to add a check of your own in front of the handler.
284
357
 
285
358
  | Option | Default | Meaning |
286
359
  | --- | --- | --- |
@@ -288,7 +361,6 @@ working.
288
361
  | `routesDir` | `src/routes` | Where the route file is written |
289
362
  | `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
290
363
  | `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
291
- | `runRoute` | `false` | Emit the route at all |
292
364
 
293
365
  ### Calling it
294
366
 
@@ -328,7 +400,8 @@ appears in the URL.
328
400
  ## Next PRs
329
401
 
330
402
  Connect the manifest and app code to Lovable deployment and runtime execution.
331
- Define support for TanStack primitives, version routing, and schedule policies.
403
+ Derive and apply the per-schedule smear on the control plane. Define support for
404
+ TanStack primitives, version routing, and schedule policies.
332
405
  Add webhook and app-event triggers to the same `triggers` array.
333
406
 
334
407
  ## Publishing dev builds
@@ -5,28 +5,6 @@ function assertIdentifier(kind, id) {
5
5
  }
6
6
  //#endregion
7
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
8
  const WEEKDAYS = [
31
9
  "mon",
32
10
  "tue",
@@ -52,15 +30,6 @@ const WEEKDAY_NAMES = {
52
30
  sun: "sun",
53
31
  sunday: "sun"
54
32
  };
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
33
  function fail$1(message) {
65
34
  throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
66
35
  }
@@ -74,141 +43,71 @@ function parseDays(value, label) {
74
43
  const days = [...new Set(value.map((entry) => parseWeekday(entry, label)))].sort((a, b) => WEEKDAYS.indexOf(a) - WEEKDAYS.indexOf(b));
75
44
  return days.length === WEEKDAYS.length ? null : days;
76
45
  }
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
- };
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);
93
51
  }
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
- };
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" };
104
55
  }
105
56
  function daily(options = {}) {
106
57
  return {
107
58
  kind: "daily",
108
- at: options.at === void 0 ? null : parseTimeOfDay(options.at, "daily({ at })"),
59
+ at: options.at === void 0 ? null : parseHoursOfDay(options.at, "daily({ at })"),
109
60
  days: options.days === void 0 ? null : parseDays(options.days, "daily({ days })")
110
61
  };
111
62
  }
112
63
  function weekly(options) {
113
- if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: "07:00" }`);
64
+ if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: 7 }`);
114
65
  return {
115
66
  kind: "daily",
116
- at: options.at === void 0 ? null : parseTimeOfDay(options.at, "weekly({ at })"),
67
+ at: options.at === void 0 ? null : parseHoursOfDay(options.at, "weekly({ at })"),
117
68
  days: [parseWeekday(options.on, "weekly({ on })")]
118
69
  };
119
70
  }
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)}`;
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]));
148
75
  }
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;
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]));
157
81
  }
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;
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;
165
88
  }
166
89
  //#endregion
167
90
  //#region src/core/schedule.ts
168
91
  const OVERLAP_POLICIES = [
169
92
  "skip",
170
- "cancel-previous",
171
- "terminate-previous"
93
+ "allow",
94
+ "buffer-one"
172
95
  ];
173
96
  function fail(message) {
174
97
  throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
175
98
  }
99
+ const CANONICAL_ZONES = new Set(typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []);
176
100
  function resolveTimeZone(schedule) {
177
101
  const timeZone = schedule.timeZone;
178
102
  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`);
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`);
180
104
  new Intl.DateTimeFormat("en", { timeZone });
181
105
  return timeZone;
182
106
  }
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
107
  function defineSchedule(schedule) {
208
108
  assertIdentifier("schedule", schedule.id);
209
- if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from every(), hourly(), daily(), or weekly()`);
109
+ if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from hourly(), daily(), or weekly()`);
210
110
  const cadence = schedule.cadence;
211
- const cron = cadenceCron(cadence);
212
111
  const timeZone = resolveTimeZone(schedule);
213
112
  const overlapPolicy = schedule.overlapPolicy ?? "skip";
214
113
  if (!OVERLAP_POLICIES.includes(overlapPolicy)) fail(`schedule "${schedule.id}" overlapPolicy must be one of ${OVERLAP_POLICIES.join(", ")}`);
@@ -218,16 +117,19 @@ function defineSchedule(schedule) {
218
117
  ...schedule,
219
118
  type: "schedule",
220
119
  cadence,
221
- cron,
222
120
  timeZone,
223
121
  overlapPolicy,
224
- enabled,
225
- smear: resolveSmear(schedule, cadence)
122
+ enabled
226
123
  };
227
124
  }
228
125
  //#endregion
229
126
  //#region src/core/workflow.ts
230
- function registerWorkflows({ workflows, triggers = [] }) {
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;
231
133
  const ids = /* @__PURE__ */ new Set();
232
134
  for (const workflow of workflows) {
233
135
  if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
@@ -306,11 +208,9 @@ async function generateManifests(definition) {
306
208
  type: schedule.type,
307
209
  id: schedule.id,
308
210
  cadence: schedule.cadence,
309
- cron: schedule.cron,
310
211
  timeZone: schedule.timeZone,
311
212
  enabled: schedule.enabled,
312
213
  overlapPolicy: schedule.overlapPolicy,
313
- smear: schedule.smear,
314
214
  input
315
215
  });
316
216
  }
@@ -330,4 +230,4 @@ async function generateManifests(definition) {
330
230
  return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
331
231
  }
332
232
  //#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 };
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 };
package/dist/index.d.ts CHANGED
@@ -2,43 +2,24 @@ import { AnyWorkflowDefinition, AnyWorkflowDefinition as AnyWorkflowDefinition$1
2
2
  //#region src/core/cadence.d.ts
3
3
  type Weekday = "mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun";
4
4
  type Cadence = {
5
- readonly kind: "every";
6
- readonly seconds: number;
7
- } | {
8
5
  readonly kind: "hourly";
9
- readonly minute: number | null;
10
6
  } | {
11
7
  readonly kind: "daily";
12
- readonly at: string | null;
8
+ readonly at: readonly number[] | null;
13
9
  readonly days: readonly Weekday[] | null;
14
10
  };
15
- declare function every(interval: string): Cadence;
16
- declare function hourly(options?: {
17
- at?: string;
18
- }): Cadence;
11
+ declare function hourly(options?: never): Cadence;
19
12
  declare function daily(options?: {
20
- at?: string;
13
+ at?: number | readonly number[];
21
14
  days?: readonly string[];
22
15
  }): Cadence;
23
16
  declare function weekly(options: {
24
17
  on: string;
25
- at?: string;
18
+ at?: number | readonly number[];
26
19
  }): Cadence;
27
20
  //#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
37
21
  //#region src/core/schedule.d.ts
38
- type OverlapPolicy = "skip" | "cancel-previous" | "terminate-previous";
39
- type SmearOption = false | {
40
- readonly window: string;
41
- } | SmearPolicy;
22
+ type OverlapPolicy = "skip" | "allow" | "buffer-one";
42
23
  interface ScheduleDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> {
43
24
  readonly id: string;
44
25
  readonly workflow: TWorkflow;
@@ -46,15 +27,12 @@ interface ScheduleDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWork
46
27
  readonly timeZone: string;
47
28
  readonly overlapPolicy?: OverlapPolicy;
48
29
  readonly enabled?: boolean;
49
- readonly smear?: SmearOption;
50
30
  readonly input: WorkflowInput$1<NoInfer<TWorkflow>>;
51
31
  }
52
32
  interface ResolvedSchedule<TWorkflow extends AnyWorkflowDefinition$1 = AnyWorkflowDefinition$1> extends ScheduleDefinition<TWorkflow> {
53
33
  readonly type: "schedule";
54
- readonly cron: string;
55
34
  readonly overlapPolicy: OverlapPolicy;
56
35
  readonly enabled: boolean;
57
- readonly smear: SmearPolicy;
58
36
  }
59
37
  declare function defineSchedule<TWorkflow extends AnyWorkflowDefinition$1>(schedule: ScheduleDefinition<TWorkflow>): ResolvedSchedule<TWorkflow>;
60
38
  //#endregion
@@ -67,7 +45,7 @@ interface WorkflowsDefinition<TWorkflow extends AnyWorkflowDefinition$1 = AnyWor
67
45
  readonly workflows: readonly TWorkflow[];
68
46
  readonly triggers: readonly ResolvedTrigger[];
69
47
  }
70
- declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows, triggers }: {
48
+ declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>(definition: {
71
49
  workflows: TWorkflows;
72
50
  triggers?: readonly TriggerDefinition[];
73
51
  }): WorkflowsDefinition<TWorkflows[number]>;
@@ -138,15 +116,13 @@ interface WorkflowManifest {
138
116
  type: "schedule";
139
117
  id: string;
140
118
  cadence: Cadence;
141
- cron: string;
142
119
  timeZone: string;
143
120
  enabled: boolean;
144
121
  overlapPolicy: OverlapPolicy;
145
- smear: SmearPolicy;
146
122
  input: JsonValue;
147
123
  }[];
148
124
  graph: WorkflowGraph;
149
125
  }
150
126
  declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
151
127
  //#endregion
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 };
128
+ export { type AnyWorkflowDefinition, type Cadence, type Ctx, type OverlapPolicy, type ResolvedSchedule, type ResolvedTrigger, type ScheduleDefinition, type StepContext, type StepOptions, type TriggerDefinition, type Weekday, type WorkflowDefinition, type WorkflowGraph, type WorkflowGraphNode, type WorkflowGraphNodeDetails, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
package/dist/index.js CHANGED
@@ -1,16 +1,2 @@
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 };
1
+ import { a as defineSchedule, c as weekly, i as registerWorkflows, n as createMiddleware, o as daily, r as createWorkflow, s as hourly, t as generateManifests } from "./generate-DyUHbtre.js";
2
+ export { createMiddleware, createWorkflow, daily, defineSchedule, generateManifests, hourly, registerWorkflows, weekly };
package/dist/vite.d.ts CHANGED
@@ -10,15 +10,11 @@ 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
- /** @deprecated Renamed to `workflowsPlugin`, which also emits the run route. */
22
- declare const workflowsManifest: typeof workflowsPlugin;
23
19
  //#endregion
24
- export { type WorkflowsPluginOptions, workflowsManifest, workflowsPlugin };
20
+ export { type WorkflowsPluginOptions, workflowsPlugin };
package/dist/vite.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as generateManifests } from "./generate-IXn3QGVb.js";
1
+ import { t as generateManifests } from "./generate-DyUHbtre.js";
2
2
  import { dirname, join, relative, resolve, sep } from "node:path";
3
3
  import { createServer } from "vite";
4
4
  import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
@@ -65,7 +65,8 @@ function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
65
65
  return `${GENERATED_BANNER}
66
66
  // route: ${routeLiteral}
67
67
  // emitted to: ${normalizePath(relative(root, routeFile))}
68
- // This route is unauthenticated: any caller can run any declared workflow.
68
+ // This route is unauthenticated: any caller who reaches it can run any declared
69
+ // workflow. Signed invocation is not available yet.
69
70
 
70
71
  import { createFileRoute } from "@tanstack/react-router";
71
72
 
@@ -155,7 +156,7 @@ function createRouteEmitter(options) {
155
156
  entryExists = false;
156
157
  }
157
158
  const expected = /* @__PURE__ */ new Set();
158
- if (entryExists && options.runRoute) {
159
+ if (entryExists) {
159
160
  expected.add(routeFile);
160
161
  writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, entry, root));
161
162
  }
@@ -173,8 +174,8 @@ function createRouteEmitter(options) {
173
174
  //#endregion
174
175
  //#region src/vite/plugin.ts
175
176
  /**
176
- * Build the collection's manifests and, with `runRoute`, emit the route serving
177
- * them; one `entry` feeds both, so the two can never describe different sets.
177
+ * Build the collection's manifests and emit the route serving them; one `entry`
178
+ * feeds both, so the two can never describe different sets.
178
179
  */
179
180
  function workflowsPlugin(options = {}) {
180
181
  const entry = options.entry ?? "src/lib/workflows/index.ts";
@@ -182,8 +183,7 @@ function workflowsPlugin(options = {}) {
182
183
  entry,
183
184
  routesDir: options.routesDir ?? "src/routes",
184
185
  path: options.path ?? "/api/workflows",
185
- workflowIdParam: options.workflowIdParam ?? "workflowId",
186
- runRoute: options.runRoute === true
186
+ workflowIdParam: options.workflowIdParam ?? "workflowId"
187
187
  });
188
188
  let config;
189
189
  return {
@@ -241,7 +241,5 @@ function workflowsPlugin(options = {}) {
241
241
  }
242
242
  };
243
243
  }
244
- /** @deprecated Renamed to `workflowsPlugin`, which also emits the run route. */
245
- const workflowsManifest = workflowsPlugin;
246
244
  //#endregion
247
- export { workflowsManifest, workflowsPlugin };
245
+ export { workflowsPlugin };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lovable.dev/workflows-sdk",
3
- "version": "0.0.0-dev.5",
3
+ "version": "0.0.0-dev.7",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "dev",