@lovable.dev/workflows-sdk 0.0.0-dev.3 → 0.0.0-dev.5
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 +210 -19
- package/dist/generate-IXn3QGVb.js +333 -0
- package/dist/index.d.ts +66 -8
- package/dist/index.js +16 -2
- package/dist/stacks/tanstack/index.d.ts +31 -0
- package/dist/stacks/tanstack/index.js +99 -0
- package/dist/vite.d.ts +21 -4
- package/dist/vite.js +177 -7
- package/package.json +6 -2
- package/dist/generate-DFS-ezZy.js +0 -115
package/README.md
CHANGED
|
@@ -46,37 +46,154 @@ 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,
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
64
|
-
|
|
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
|
|
|
68
|
-
Add `
|
|
69
|
-
|
|
70
|
-
default-export
|
|
182
|
+
Add `workflowsPlugin()` from `@lovable.dev/workflows-sdk/vite` to the app's Vite
|
|
183
|
+
plugins. Its `entry` defaults to `src/lib/workflows/index.ts` and must
|
|
184
|
+
default-export the app's `registerWorkflows()` collection. Each production build writes
|
|
71
185
|
one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
|
|
72
186
|
to the app root. For example, `greet` produces `.lovable/workflows/greet.json`.
|
|
73
187
|
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
|
-
`
|
|
78
|
-
|
|
79
|
-
|
|
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
|
|
@@ -136,10 +253,83 @@ unsupported code are not expanded. The UI should show these unknown nodes and
|
|
|
136
253
|
mark partial graphs. Transforms that rewrite the handler may also produce a
|
|
137
254
|
partial graph. A handler with no steps can have an empty graph.
|
|
138
255
|
|
|
256
|
+
## Run endpoint (TanStack Start)
|
|
257
|
+
|
|
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:
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
|
|
265
|
+
import { workflowsPlugin } from "@lovable.dev/workflows-sdk/vite";
|
|
266
|
+
|
|
267
|
+
export default defineConfig({
|
|
268
|
+
plugins: [workflowsPlugin({ runRoute: true }), tanstackStart()],
|
|
269
|
+
});
|
|
270
|
+
```
|
|
271
|
+
|
|
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.
|
|
275
|
+
|
|
276
|
+
The emitted file is thin — it imports the collection and mounts
|
|
277
|
+
`createTanStackWorkflowHandler` from `@lovable.dev/workflows-sdk/stacks/tanstack`
|
|
278
|
+
as the route's `POST` handler. All runtime logic stays in the package. The file
|
|
279
|
+
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.
|
|
284
|
+
|
|
285
|
+
| Option | Default | Meaning |
|
|
286
|
+
| --- | --- | --- |
|
|
287
|
+
| `entry` | `src/lib/workflows/index.ts` | Collection entry; a missing file means no route |
|
|
288
|
+
| `routesDir` | `src/routes` | Where the route file is written |
|
|
289
|
+
| `path` | `/api/workflows` | URL prefix; the workflow ID is the next segment |
|
|
290
|
+
| `workflowIdParam` | `workflowId` | Route parameter, and the emitted file name |
|
|
291
|
+
| `runRoute` | `false` | Emit the route at all |
|
|
292
|
+
|
|
293
|
+
### Calling it
|
|
294
|
+
|
|
295
|
+
`POST /api/workflows/{workflow-id}` with a JSON body. The body is decoded by
|
|
296
|
+
`parseWorkflowRequest`, so one route takes every traffic shape: `{ "input": ... }`
|
|
297
|
+
starts a run, `{ "runId", "approval" }` delivers an approval decision, and
|
|
298
|
+
`{ "runId", "signal" }` delivers a signal. A run that parks on `ctx.approve` or
|
|
299
|
+
`ctx.waitForEvent` resumes on this same route — there is no separate resume
|
|
300
|
+
endpoint. An unknown workflow ID returns 404, an unparseable body 400, and
|
|
301
|
+
`{ "abort": true }` returns 501 until a shared run registry exists.
|
|
302
|
+
|
|
303
|
+
The response is `text/event-stream`. Each engine event becomes one SSE message
|
|
304
|
+
whose event name is the event `type` and whose data is the whole event as JSON:
|
|
305
|
+
|
|
306
|
+
```text
|
|
307
|
+
event: RUN_STARTED
|
|
308
|
+
data: {"type":"RUN_STARTED","ts":1790505539351,"runId":"run_1790505539350_yin41cp"}
|
|
309
|
+
|
|
310
|
+
event: STEP_FINISHED
|
|
311
|
+
data: {"type":"STEP_FINISHED","ts":1790505539352,"stepId":"greeting","result":"Hello, YEHYA!"}
|
|
312
|
+
|
|
313
|
+
event: RUN_FINISHED
|
|
314
|
+
data: {"type":"RUN_FINISHED","ts":1790505539352,"runId":"run_1790505539350_yin41cp","output":{"message":"Hello, YEHYA!"}}
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
Run state lives in a process-local `inMemoryRunStore()`: runs are lost on restart
|
|
318
|
+
and are invisible to other instances. Pass `runStore` to
|
|
319
|
+
`createTanStackWorkflowHandler` to supply another one. The control-plane store is
|
|
320
|
+
a follow-up.
|
|
321
|
+
|
|
322
|
+
The path carries no build ID. Version pinning belongs to the signed invocation,
|
|
323
|
+
which leaves this path stable across deployments and safe to publish in a
|
|
324
|
+
manifest. Triggers name a workflow rather than an endpoint, so firing one is a
|
|
325
|
+
POST to that workflow's path with the trigger's input; no trigger identifier
|
|
326
|
+
appears in the URL.
|
|
327
|
+
|
|
139
328
|
## Next PRs
|
|
140
329
|
|
|
141
330
|
Connect the manifest and app code to Lovable deployment and runtime execution.
|
|
142
331
|
Define support for TanStack primitives, version routing, and schedule policies.
|
|
332
|
+
Add webhook and app-event triggers to the same `triggers` array.
|
|
143
333
|
|
|
144
334
|
## Publishing dev builds
|
|
145
335
|
|
|
@@ -155,7 +345,8 @@ Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
|
|
|
155
345
|
the exact version shown in the workflow run's summary. `latest` tracks every dev
|
|
156
346
|
publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
|
|
157
347
|
|
|
158
|
-
The
|
|
348
|
+
The engine's embedded SDK
|
|
349
|
+
([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
|
|
159
350
|
provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
|
|
160
351
|
for separating authoring, manifest extraction, and framework integration. The
|
|
161
352
|
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
|
|
7
|
-
readonly timeZone
|
|
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
|
-
|
|
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
|
|
68
|
+
readonly triggers: readonly ResolvedTrigger[];
|
|
16
69
|
}
|
|
17
|
-
declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows,
|
|
70
|
+
declare function registerWorkflows<const TWorkflows extends readonly AnyWorkflowDefinition$1[]>({ workflows, triggers }: {
|
|
18
71
|
workflows: TWorkflows;
|
|
19
|
-
|
|
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
|
-
|
|
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-
|
|
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 };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { AnyWorkflowDefinition, RunStore, WorkflowEvent } from "@tanstack/workflow-core";
|
|
2
|
+
//#region src/stacks/tanstack/handlers.d.ts
|
|
3
|
+
/** The shape `registerWorkflows()` returns; only the list is needed to dispatch. */
|
|
4
|
+
interface WorkflowCollection {
|
|
5
|
+
readonly workflows: readonly AnyWorkflowDefinition[];
|
|
6
|
+
}
|
|
7
|
+
interface TanStackWorkflowHandlerOptions {
|
|
8
|
+
/** @default a process-local `inMemoryRunStore()`, lost on restart */
|
|
9
|
+
runStore?: RunStore;
|
|
10
|
+
/**
|
|
11
|
+
* Route parameter carrying the workflow ID.
|
|
12
|
+
* @default "workflowId"
|
|
13
|
+
*/
|
|
14
|
+
workflowIdParam?: string;
|
|
15
|
+
}
|
|
16
|
+
interface TanStackRouteCtx {
|
|
17
|
+
request: Request;
|
|
18
|
+
params?: Record<string, string | undefined>;
|
|
19
|
+
}
|
|
20
|
+
type TanStackWorkflowHandler = (ctx: TanStackRouteCtx) => Promise<Response>;
|
|
21
|
+
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
22
|
+
declare function createTanStackWorkflowHandler(collection: WorkflowCollection, options?: TanStackWorkflowHandlerOptions): TanStackWorkflowHandler;
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/stacks/tanstack/sse.d.ts
|
|
25
|
+
/**
|
|
26
|
+
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
27
|
+
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
28
|
+
*/
|
|
29
|
+
declare function toServerSentEventsResponse(events: AsyncIterable<WorkflowEvent>): Response;
|
|
30
|
+
//#endregion
|
|
31
|
+
export { type TanStackWorkflowHandler, type TanStackWorkflowHandlerOptions, type WorkflowCollection, createTanStackWorkflowHandler, toServerSentEventsResponse };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { WorkflowRequestParseError, inMemoryRunStore, parseWorkflowRequest, runWorkflow } from "@tanstack/workflow-core";
|
|
2
|
+
//#region src/stacks/tanstack/sse.ts
|
|
3
|
+
const HEADERS = {
|
|
4
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
5
|
+
"cache-control": "no-cache, no-transform",
|
|
6
|
+
connection: "keep-alive",
|
|
7
|
+
"x-accel-buffering": "no"
|
|
8
|
+
};
|
|
9
|
+
function describe(error) {
|
|
10
|
+
return error instanceof Error ? error.message : String(error);
|
|
11
|
+
}
|
|
12
|
+
function frame(name, data) {
|
|
13
|
+
return `event: ${name}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Encode a workflow event stream as `text/event-stream`. Each event keeps its
|
|
17
|
+
* engine `type` as the SSE event name and its whole JSON as the data line.
|
|
18
|
+
*/
|
|
19
|
+
function toServerSentEventsResponse(events) {
|
|
20
|
+
const encoder = new TextEncoder();
|
|
21
|
+
const body = new ReadableStream({ async start(controller) {
|
|
22
|
+
let connected = true;
|
|
23
|
+
const write = (text) => {
|
|
24
|
+
if (!connected) return;
|
|
25
|
+
try {
|
|
26
|
+
controller.enqueue(encoder.encode(text));
|
|
27
|
+
} catch {
|
|
28
|
+
connected = false;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
const send = (name, data) => {
|
|
32
|
+
try {
|
|
33
|
+
write(frame(name, data));
|
|
34
|
+
} catch (error) {
|
|
35
|
+
write(frame("STREAM_ERRORED", { message: `cannot serialize ${name}: ${describe(error)}` }));
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
try {
|
|
39
|
+
for await (const event of events) send(event.type, event);
|
|
40
|
+
} catch (error) {
|
|
41
|
+
send("STREAM_ERRORED", { message: describe(error) });
|
|
42
|
+
} finally {
|
|
43
|
+
try {
|
|
44
|
+
controller.close();
|
|
45
|
+
} catch {
|
|
46
|
+
connected = false;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
} });
|
|
50
|
+
return new Response(body, { headers: HEADERS });
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/stacks/tanstack/handlers.ts
|
|
54
|
+
function json(status, body) {
|
|
55
|
+
return new Response(JSON.stringify(body), {
|
|
56
|
+
status,
|
|
57
|
+
headers: { "content-type": "application/json; charset=utf-8" }
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function resolveWorkflowId(ctx, param) {
|
|
61
|
+
const fromParams = ctx.params?.[param];
|
|
62
|
+
if (fromParams) return fromParams;
|
|
63
|
+
return new URL(ctx.request.url).pathname.split("/").filter(Boolean).at(-1);
|
|
64
|
+
}
|
|
65
|
+
/** Build a TanStack Start `POST` handler serving every workflow in the collection. */
|
|
66
|
+
function createTanStackWorkflowHandler(collection, options = {}) {
|
|
67
|
+
const runStore = options.runStore ?? inMemoryRunStore();
|
|
68
|
+
const param = options.workflowIdParam ?? "workflowId";
|
|
69
|
+
const byId = new Map(collection.workflows.map((workflow) => [workflow.id, workflow]));
|
|
70
|
+
return async (ctx) => {
|
|
71
|
+
const workflowId = resolveWorkflowId(ctx, param);
|
|
72
|
+
const workflow = workflowId === void 0 ? void 0 : byId.get(workflowId);
|
|
73
|
+
if (!workflow) return json(404, {
|
|
74
|
+
error: "unknown_workflow",
|
|
75
|
+
workflowId: workflowId ?? ""
|
|
76
|
+
});
|
|
77
|
+
let params;
|
|
78
|
+
try {
|
|
79
|
+
params = await parseWorkflowRequest(ctx.request);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof WorkflowRequestParseError) return json(400, {
|
|
82
|
+
error: "invalid_request",
|
|
83
|
+
message: error.message
|
|
84
|
+
});
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
if (params.abort) return json(501, {
|
|
88
|
+
error: "abort_unsupported",
|
|
89
|
+
message: "Cancelling an in-flight run needs a shared run registry (WOR-53)."
|
|
90
|
+
});
|
|
91
|
+
return toServerSentEventsResponse(runWorkflow({
|
|
92
|
+
workflow,
|
|
93
|
+
runStore,
|
|
94
|
+
...params
|
|
95
|
+
}));
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
//#endregion
|
|
99
|
+
export { createTanStackWorkflowHandler, toServerSentEventsResponse };
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,7 +1,24 @@
|
|
|
1
1
|
import { Plugin } from "vite";
|
|
2
2
|
//#region src/vite/plugin.d.ts
|
|
3
|
-
|
|
4
|
-
entry
|
|
5
|
-
|
|
3
|
+
interface WorkflowsPluginOptions {
|
|
4
|
+
/** Collection entry, relative to the project root. @default "src/lib/workflows/index.ts" */
|
|
5
|
+
entry?: string;
|
|
6
|
+
/** Where TanStack route files live; the plugin emits under this directory.
|
|
7
|
+
* @default "src/routes" */
|
|
8
|
+
routesDir?: string;
|
|
9
|
+
/** URL prefix; the workflow ID is appended as a dynamic segment. @default "/api/workflows" */
|
|
10
|
+
path?: string;
|
|
11
|
+
/** Route parameter carrying the workflow ID. @default "workflowId" */
|
|
12
|
+
workflowIdParam?: string;
|
|
13
|
+
/** @default false */
|
|
14
|
+
runRoute?: boolean;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
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.
|
|
19
|
+
*/
|
|
20
|
+
declare function workflowsPlugin(options?: WorkflowsPluginOptions): Plugin;
|
|
21
|
+
/** @deprecated Renamed to `workflowsPlugin`, which also emits the run route. */
|
|
22
|
+
declare const workflowsManifest: typeof workflowsPlugin;
|
|
6
23
|
//#endregion
|
|
7
|
-
export { workflowsManifest };
|
|
24
|
+
export { type WorkflowsPluginOptions, workflowsManifest, workflowsPlugin };
|
package/dist/vite.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { t as generateManifests } from "./generate-
|
|
2
|
-
import { join, resolve } from "node:path";
|
|
1
|
+
import { t as generateManifests } from "./generate-IXn3QGVb.js";
|
|
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";
|
|
5
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
5
6
|
//#region src/vite/manifest-files.ts
|
|
6
7
|
async function ensureDirectory(path) {
|
|
7
8
|
try {
|
|
@@ -30,14 +31,181 @@ async function writeManifests(root, manifests) {
|
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
33
|
//#endregion
|
|
34
|
+
//#region src/vite/route-emitter.ts
|
|
35
|
+
const GENERATED_BANNER = "// AUTO-GENERATED by @lovable.dev/workflows-sdk — do not edit. Regenerated by the Vite plugin.\n// To take ownership, delete this banner line; the plugin then leaves the file alone.";
|
|
36
|
+
function isFileMissing(error) {
|
|
37
|
+
const code = error?.code;
|
|
38
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
39
|
+
}
|
|
40
|
+
function normalizePath(path) {
|
|
41
|
+
return path.split(sep).join("/");
|
|
42
|
+
}
|
|
43
|
+
function assertContains(parent, child, label) {
|
|
44
|
+
const from = normalizePath(parent).replace(/\/$/, "");
|
|
45
|
+
const to = normalizePath(child);
|
|
46
|
+
if (to !== from && !to.startsWith(`${from}/`)) throw new Error(`@lovable.dev/workflows-sdk: ${label} must resolve under ${from}, got ${to}`);
|
|
47
|
+
}
|
|
48
|
+
function assertUrlPathShape(urlPath) {
|
|
49
|
+
if (!urlPath.startsWith("/")) throw new Error(`@lovable.dev/workflows-sdk: path must start with "/", got "${urlPath}"`);
|
|
50
|
+
if (/\/{2,}/.test(urlPath)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains empty segments ("//")`);
|
|
51
|
+
const trimmed = urlPath.replace(/^\/+/, "").replace(/\/+$/, "");
|
|
52
|
+
if (!trimmed) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" has no route segment`);
|
|
53
|
+
if (!/^[a-zA-Z0-9_\-/]+$/.test(trimmed)) throw new Error(`@lovable.dev/workflows-sdk: path "${urlPath}" contains unsupported characters`);
|
|
54
|
+
return trimmed;
|
|
55
|
+
}
|
|
56
|
+
function assertParamShape(param) {
|
|
57
|
+
if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(param)) throw new Error(`@lovable.dev/workflows-sdk: workflowIdParam "${param}" must be a JavaScript identifier`);
|
|
58
|
+
return param;
|
|
59
|
+
}
|
|
60
|
+
function relativeImportSpecifier(routeFile, target) {
|
|
61
|
+
const withoutExt = normalizePath(relative(dirname(routeFile), target)).replace(/\.tsx?$/, "");
|
|
62
|
+
return withoutExt.startsWith(".") ? withoutExt : `./${withoutExt}`;
|
|
63
|
+
}
|
|
64
|
+
function buildRouteSource(routeFile, routeLiteral, param, entry, root) {
|
|
65
|
+
return `${GENERATED_BANNER}
|
|
66
|
+
// route: ${routeLiteral}
|
|
67
|
+
// emitted to: ${normalizePath(relative(root, routeFile))}
|
|
68
|
+
// This route is unauthenticated: any caller can run any declared workflow.
|
|
69
|
+
|
|
70
|
+
import { createFileRoute } from "@tanstack/react-router";
|
|
71
|
+
|
|
72
|
+
import { createTanStackWorkflowHandler } from "@lovable.dev/workflows-sdk/stacks/tanstack";
|
|
73
|
+
|
|
74
|
+
import workflows from "${relativeImportSpecifier(routeFile, entry)}";
|
|
75
|
+
|
|
76
|
+
export const Route = createFileRoute("${routeLiteral}")({
|
|
77
|
+
server: {
|
|
78
|
+
handlers: {
|
|
79
|
+
POST: createTanStackWorkflowHandler(workflows, { workflowIdParam: "${param}" }),
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
`;
|
|
84
|
+
}
|
|
85
|
+
function hasGeneratedBanner(content) {
|
|
86
|
+
return content.replace(/\r\n/g, "\n").startsWith(GENERATED_BANNER);
|
|
87
|
+
}
|
|
88
|
+
function writeIfChanged(file, content) {
|
|
89
|
+
let existing;
|
|
90
|
+
try {
|
|
91
|
+
existing = readFileSync(file, "utf8");
|
|
92
|
+
} catch (error) {
|
|
93
|
+
if (!isFileMissing(error)) throw error;
|
|
94
|
+
}
|
|
95
|
+
if (existing !== void 0 && (!hasGeneratedBanner(existing) || existing === content)) return;
|
|
96
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
97
|
+
writeFileSync(file, content, "utf8");
|
|
98
|
+
}
|
|
99
|
+
function findAdoptedFiles(routesDir) {
|
|
100
|
+
const adopted = [];
|
|
101
|
+
const visit = (dir) => {
|
|
102
|
+
let entries;
|
|
103
|
+
try {
|
|
104
|
+
entries = readdirSync(dir);
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (isFileMissing(error)) return;
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
for (const entry of entries) {
|
|
110
|
+
const full = join(dir, entry);
|
|
111
|
+
let stat;
|
|
112
|
+
try {
|
|
113
|
+
stat = lstatSync(full);
|
|
114
|
+
} catch (error) {
|
|
115
|
+
if (isFileMissing(error)) continue;
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
if (stat.isDirectory()) visit(full);
|
|
119
|
+
else if (entry.endsWith(".ts")) try {
|
|
120
|
+
if (hasGeneratedBanner(readFileSync(full, "utf8"))) adopted.push(full);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (!isFileMissing(error)) throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
visit(routesDir);
|
|
127
|
+
return adopted;
|
|
128
|
+
}
|
|
129
|
+
function createRouteEmitter(options) {
|
|
130
|
+
const param = assertParamShape(options.workflowIdParam);
|
|
131
|
+
const pathSegments = assertUrlPathShape(options.path);
|
|
132
|
+
const routeLiteral = `/${pathSegments}/$${param}`;
|
|
133
|
+
const routeFileName = join(...pathSegments.split("/"), `$${param}.ts`);
|
|
134
|
+
let root = process.cwd();
|
|
135
|
+
let entry = resolve(root, options.entry);
|
|
136
|
+
let routesDir = resolve(root, options.routesDir);
|
|
137
|
+
let routeFile = resolve(routesDir, routeFileName);
|
|
138
|
+
return {
|
|
139
|
+
entryPath: () => entry,
|
|
140
|
+
setRoot(next) {
|
|
141
|
+
root = next;
|
|
142
|
+
entry = resolve(root, options.entry);
|
|
143
|
+
assertContains(root, entry, `entry "${options.entry}"`);
|
|
144
|
+
routesDir = resolve(root, options.routesDir);
|
|
145
|
+
assertContains(root, routesDir, `routesDir "${options.routesDir}"`);
|
|
146
|
+
routeFile = resolve(routesDir, routeFileName);
|
|
147
|
+
assertContains(routesDir, routeFile, `path "${routeLiteral}"`);
|
|
148
|
+
},
|
|
149
|
+
regenerate() {
|
|
150
|
+
let entryExists = true;
|
|
151
|
+
try {
|
|
152
|
+
lstatSync(entry);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (!isFileMissing(error)) throw error;
|
|
155
|
+
entryExists = false;
|
|
156
|
+
}
|
|
157
|
+
const expected = /* @__PURE__ */ new Set();
|
|
158
|
+
if (entryExists && options.runRoute) {
|
|
159
|
+
expected.add(routeFile);
|
|
160
|
+
writeIfChanged(routeFile, buildRouteSource(routeFile, routeLiteral, param, entry, root));
|
|
161
|
+
}
|
|
162
|
+
for (const file of findAdoptedFiles(routesDir)) {
|
|
163
|
+
if (expected.has(file)) continue;
|
|
164
|
+
try {
|
|
165
|
+
unlinkSync(file);
|
|
166
|
+
} catch (error) {
|
|
167
|
+
if (!isFileMissing(error)) throw error;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
//#endregion
|
|
33
174
|
//#region src/vite/plugin.ts
|
|
34
|
-
|
|
175
|
+
/**
|
|
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.
|
|
178
|
+
*/
|
|
179
|
+
function workflowsPlugin(options = {}) {
|
|
180
|
+
const entry = options.entry ?? "src/lib/workflows/index.ts";
|
|
181
|
+
const emitter = createRouteEmitter({
|
|
182
|
+
entry,
|
|
183
|
+
routesDir: options.routesDir ?? "src/routes",
|
|
184
|
+
path: options.path ?? "/api/workflows",
|
|
185
|
+
workflowIdParam: options.workflowIdParam ?? "workflowId",
|
|
186
|
+
runRoute: options.runRoute === true
|
|
187
|
+
});
|
|
35
188
|
let config;
|
|
36
189
|
return {
|
|
37
|
-
name: "@lovable.dev/workflows-sdk
|
|
38
|
-
apply: "build",
|
|
190
|
+
name: "@lovable.dev/workflows-sdk",
|
|
39
191
|
configResolved(resolved) {
|
|
40
192
|
config = resolved;
|
|
193
|
+
emitter.setRoot(config.root);
|
|
194
|
+
emitter.regenerate();
|
|
195
|
+
},
|
|
196
|
+
configureServer(server) {
|
|
197
|
+
const onChange = (file) => {
|
|
198
|
+
if (normalizePath(file) === normalizePath(emitter.entryPath())) emitter.regenerate();
|
|
199
|
+
};
|
|
200
|
+
server.watcher.on("add", onChange);
|
|
201
|
+
server.watcher.on("unlink", onChange);
|
|
202
|
+
server.watcher.once("close", () => {
|
|
203
|
+
server.watcher.off("add", onChange);
|
|
204
|
+
server.watcher.off("unlink", onChange);
|
|
205
|
+
});
|
|
206
|
+
},
|
|
207
|
+
buildStart() {
|
|
208
|
+
emitter.regenerate();
|
|
41
209
|
},
|
|
42
210
|
async generateBundle() {
|
|
43
211
|
const entryPath = resolve(config.root, entry);
|
|
@@ -63,7 +231,7 @@ function workflowsManifest({ entry }) {
|
|
|
63
231
|
});
|
|
64
232
|
try {
|
|
65
233
|
const module = await server.ssrLoadModule(entryPath);
|
|
66
|
-
if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.
|
|
234
|
+
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
235
|
const manifests = await generateManifests(module.default);
|
|
68
236
|
await writeManifests(config.root, manifests);
|
|
69
237
|
} finally {
|
|
@@ -73,5 +241,7 @@ function workflowsManifest({ entry }) {
|
|
|
73
241
|
}
|
|
74
242
|
};
|
|
75
243
|
}
|
|
244
|
+
/** @deprecated Renamed to `workflowsPlugin`, which also emits the run route. */
|
|
245
|
+
const workflowsManifest = workflowsPlugin;
|
|
76
246
|
//#endregion
|
|
77
|
-
export { workflowsManifest };
|
|
247
|
+
export { workflowsManifest, workflowsPlugin };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lovable.dev/workflows-sdk",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.5",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"tag": "dev",
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
"./vite": {
|
|
23
23
|
"types": "./dist/vite.d.ts",
|
|
24
24
|
"import": "./dist/vite.js"
|
|
25
|
+
},
|
|
26
|
+
"./stacks/tanstack": {
|
|
27
|
+
"types": "./dist/stacks/tanstack/index.d.ts",
|
|
28
|
+
"import": "./dist/stacks/tanstack/index.js"
|
|
25
29
|
}
|
|
26
30
|
},
|
|
27
31
|
"files": [
|
|
@@ -52,7 +56,7 @@
|
|
|
52
56
|
},
|
|
53
57
|
"scripts": {
|
|
54
58
|
"build": "tsdown",
|
|
55
|
-
"test": "node --test tests
|
|
59
|
+
"test": "node --test tests/*.test.mjs",
|
|
56
60
|
"typecheck": "tsc -p tsconfig.typecheck.json",
|
|
57
61
|
"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
62
|
}
|
|
@@ -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 };
|