@lovable.dev/workflows-sdk 0.0.0-dev.2 → 0.0.0-dev.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +145 -25
- package/dist/generate-IXn3QGVb.js +333 -0
- package/dist/{graph-extract-CGLWzaln.js → graph-BgdiEUHq.js} +96 -14
- package/dist/index.d.ts +104 -19
- package/dist/index.js +16 -3
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +4 -4
- package/package.json +2 -2
- package/dist/manifest-DIeHMgS8.js +0 -114
package/README.md
CHANGED
|
@@ -15,11 +15,11 @@ from [`@tanstack/workflow-core`](https://github.com/TanStack/workflow).
|
|
|
15
15
|
Schema validation libraries implementing Standard Schema, such as Zod, provide
|
|
16
16
|
input and output inference.
|
|
17
17
|
|
|
18
|
-
Keep the app's workflow collection in `
|
|
19
|
-
lives in `
|
|
18
|
+
Keep the app's workflow collection in `src/lib/workflows/index.ts`. Each workflow
|
|
19
|
+
lives in `src/lib/workflows/{workflow-name}/index.ts`, with its helpers alongside it:
|
|
20
20
|
|
|
21
21
|
```text
|
|
22
|
-
|
|
22
|
+
src/lib/workflows/
|
|
23
23
|
├── index.ts
|
|
24
24
|
└── greet/
|
|
25
25
|
├── index.ts
|
|
@@ -43,29 +43,143 @@ names. An empty collection is valid. Registration copies the list, retains the
|
|
|
43
43
|
definitions, and does not execute handlers or register global state. Treat
|
|
44
44
|
definitions as immutable after registration.
|
|
45
45
|
|
|
46
|
-
See [the authoring example](examples/workflows.ts) for schemas,
|
|
47
|
-
and a durable step. The package typecheck includes this example.
|
|
46
|
+
See [the authoring example](examples/src/lib/workflows/greet/index.ts) for schemas,
|
|
47
|
+
typed middleware, and a durable step. The package typecheck includes this example.
|
|
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.
|
|
48
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 `workflowsManifest({ entry: "
|
|
182
|
+
Add `workflowsManifest({ entry: "src/lib/workflows/index.ts" })` from
|
|
69
183
|
`@lovable.dev/workflows-sdk/vite` to the app's Vite plugins. The entry must
|
|
70
184
|
default-export its `registerWorkflows()` collection. Each production build writes
|
|
71
185
|
one manifest per workflow to `.lovable/workflows/{workflow-name}.json` relative
|
|
@@ -74,9 +188,12 @@ Generation errors fail the build. See [the Vite example](examples/vite.config.ts
|
|
|
74
188
|
|
|
75
189
|
Each version-1 manifest contains a single `workflow` with its ID, description,
|
|
76
190
|
version, and input/output/state JSON Schemas, a `graph` for visualization, and a
|
|
77
|
-
`
|
|
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
|
|
@@ -140,21 +257,24 @@ partial graph. A handler with no steps can have an empty graph.
|
|
|
140
257
|
|
|
141
258
|
Connect the manifest and app code to Lovable deployment and runtime execution.
|
|
142
259
|
Define support for TanStack primitives, version routing, and schedule policies.
|
|
260
|
+
Add webhook and app-event triggers to the same `triggers` array.
|
|
143
261
|
|
|
144
262
|
## Publishing dev builds
|
|
145
263
|
|
|
146
264
|
The [publishing workflow](../../.github/workflows/publish-workflows-sdk.yml)
|
|
147
|
-
publishes the version committed in `package.json` to npm's `
|
|
265
|
+
publishes the version committed in `package.json` to npm's `latest` tag when SDK
|
|
148
266
|
changes land on `main`. Manage versions manually: `0.0.0-dev`, `0.0.0-dev.1`,
|
|
149
267
|
`0.0.0-dev.2`, and so on. The workflow rejects versions outside this series and
|
|
150
268
|
skips versions already published. Manual runs default to a dry run.
|
|
151
269
|
See [the setup guide](PUBLISHING.md) for the
|
|
152
270
|
one-time bootstrap and npm trusted-publisher configuration.
|
|
153
271
|
|
|
154
|
-
Install
|
|
155
|
-
|
|
272
|
+
Install the newest build with `npm install @lovable.dev/workflows-sdk`, or pin
|
|
273
|
+
the exact version shown in the workflow run's summary. `latest` tracks every dev
|
|
274
|
+
publish while the SDK is pre-1.0; the older `dev` tag is frozen at `0.0.0-dev.2`.
|
|
156
275
|
|
|
157
|
-
The
|
|
276
|
+
The engine's embedded SDK
|
|
277
|
+
([`sdk_embed/index.ts`](../../go/workflows/services/workflows/internal/bundler/sdk_embed/index.ts))
|
|
158
278
|
provides the engine contract. Use [`mcp-js`](../lovable-mcp-js) as the reference
|
|
159
279
|
for separating authoring, manifest extraction, and framework integration. The
|
|
160
280
|
workflow prototype's `ts/workflow-sdk` supplies adapter and manifest examples.
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { createMiddleware, createWorkflow } from "@tanstack/workflow-core";
|
|
2
|
+
//#region src/core/identifier.ts
|
|
3
|
+
function assertIdentifier(kind, id) {
|
|
4
|
+
if (typeof id !== "string" || id.trim() === "" || id !== id.trim()) throw new Error(`@lovable.dev/workflows-sdk: ${kind} IDs must be non-empty and have no surrounding whitespace`);
|
|
5
|
+
}
|
|
6
|
+
//#endregion
|
|
7
|
+
//#region src/core/cadence.ts
|
|
8
|
+
const MINUTE_DIVISORS = [
|
|
9
|
+
1,
|
|
10
|
+
2,
|
|
11
|
+
3,
|
|
12
|
+
4,
|
|
13
|
+
5,
|
|
14
|
+
6,
|
|
15
|
+
10,
|
|
16
|
+
12,
|
|
17
|
+
15,
|
|
18
|
+
20,
|
|
19
|
+
30
|
|
20
|
+
];
|
|
21
|
+
const HOUR_DIVISORS = [
|
|
22
|
+
1,
|
|
23
|
+
2,
|
|
24
|
+
3,
|
|
25
|
+
4,
|
|
26
|
+
6,
|
|
27
|
+
8,
|
|
28
|
+
12
|
|
29
|
+
];
|
|
30
|
+
const WEEKDAYS = [
|
|
31
|
+
"mon",
|
|
32
|
+
"tue",
|
|
33
|
+
"wed",
|
|
34
|
+
"thu",
|
|
35
|
+
"fri",
|
|
36
|
+
"sat",
|
|
37
|
+
"sun"
|
|
38
|
+
];
|
|
39
|
+
const WEEKDAY_NAMES = {
|
|
40
|
+
mon: "mon",
|
|
41
|
+
monday: "mon",
|
|
42
|
+
tue: "tue",
|
|
43
|
+
tuesday: "tue",
|
|
44
|
+
wed: "wed",
|
|
45
|
+
wednesday: "wed",
|
|
46
|
+
thu: "thu",
|
|
47
|
+
thursday: "thu",
|
|
48
|
+
fri: "fri",
|
|
49
|
+
friday: "fri",
|
|
50
|
+
sat: "sat",
|
|
51
|
+
saturday: "sat",
|
|
52
|
+
sun: "sun",
|
|
53
|
+
sunday: "sun"
|
|
54
|
+
};
|
|
55
|
+
const CRON_DAY = {
|
|
56
|
+
sun: 0,
|
|
57
|
+
mon: 1,
|
|
58
|
+
tue: 2,
|
|
59
|
+
wed: 3,
|
|
60
|
+
thu: 4,
|
|
61
|
+
fri: 5,
|
|
62
|
+
sat: 6
|
|
63
|
+
};
|
|
64
|
+
function fail$1(message) {
|
|
65
|
+
throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
|
|
66
|
+
}
|
|
67
|
+
function parseWeekday(value, label) {
|
|
68
|
+
const day = typeof value === "string" ? WEEKDAY_NAMES[value.toLowerCase()] : void 0;
|
|
69
|
+
if (day === void 0) fail$1(`${label} names an unknown day "${String(value)}"; use ${WEEKDAYS.join(", ")}`);
|
|
70
|
+
return day;
|
|
71
|
+
}
|
|
72
|
+
function parseDays(value, label) {
|
|
73
|
+
if (!Array.isArray(value) || value.length === 0) fail$1(`${label} must be a non-empty array of days`);
|
|
74
|
+
const days = [...new Set(value.map((entry) => parseWeekday(entry, label)))].sort((a, b) => WEEKDAYS.indexOf(a) - WEEKDAYS.indexOf(b));
|
|
75
|
+
return days.length === WEEKDAYS.length ? null : days;
|
|
76
|
+
}
|
|
77
|
+
function parseTimeOfDay(value, label) {
|
|
78
|
+
if (typeof value !== "string" || !/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(value)) fail$1(`${label}: "${String(value)}" must be a 24-hour "HH:MM" time`);
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
function every(interval) {
|
|
82
|
+
if (typeof interval !== "string" || !/^[0-9]+[mhd]$/.test(interval)) fail$1(`every("${String(interval)}") must be a whole number of minutes, hours, or days, such as "5m", "2h", or "1d"`);
|
|
83
|
+
const amount = Number(interval.slice(0, -1));
|
|
84
|
+
const unit = interval.slice(-1);
|
|
85
|
+
if (amount < 1) fail$1(`every("${interval}") must be at least one unit`);
|
|
86
|
+
if (unit === "m" && !MINUTE_DIVISORS.includes(amount)) fail$1(`every("${interval}") must divide an hour evenly: ${MINUTE_DIVISORS.map((n) => `${n}m`).join(", ")}`);
|
|
87
|
+
if (unit === "h" && !HOUR_DIVISORS.includes(amount)) fail$1(`every("${interval}") must divide a day evenly: ${HOUR_DIVISORS.map((n) => `${n}h`).join(", ")}`);
|
|
88
|
+
if (unit === "d" && amount !== 1) fail$1(`every("${interval}") supports only "1d"; use daily() for calendar days`);
|
|
89
|
+
return {
|
|
90
|
+
kind: "every",
|
|
91
|
+
seconds: amount * (unit === "m" ? 60 : unit === "h" ? 3600 : 86400)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function hourly(options = {}) {
|
|
95
|
+
if (options.at === void 0) return {
|
|
96
|
+
kind: "hourly",
|
|
97
|
+
minute: null
|
|
98
|
+
};
|
|
99
|
+
if (typeof options.at !== "string" || !/^:[0-5][0-9]$/.test(options.at)) fail$1(`hourly({ at: "${String(options.at)}" }) must pin a minute past the hour, such as ":30"`);
|
|
100
|
+
return {
|
|
101
|
+
kind: "hourly",
|
|
102
|
+
minute: Number(options.at.slice(1))
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
function daily(options = {}) {
|
|
106
|
+
return {
|
|
107
|
+
kind: "daily",
|
|
108
|
+
at: options.at === void 0 ? null : parseTimeOfDay(options.at, "daily({ at })"),
|
|
109
|
+
days: options.days === void 0 ? null : parseDays(options.days, "daily({ days })")
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function weekly(options) {
|
|
113
|
+
if (typeof options !== "object" || options === null) fail$1(`weekly() requires { on: "monday", at: "07:00" }`);
|
|
114
|
+
return {
|
|
115
|
+
kind: "daily",
|
|
116
|
+
at: options.at === void 0 ? null : parseTimeOfDay(options.at, "weekly({ at })"),
|
|
117
|
+
days: [parseWeekday(options.on, "weekly({ on })")]
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
function isCadence(value) {
|
|
121
|
+
if (typeof value !== "object" || value === null) return false;
|
|
122
|
+
const kind = value.kind;
|
|
123
|
+
return kind === "every" || kind === "hourly" || kind === "daily";
|
|
124
|
+
}
|
|
125
|
+
function cronDayField(days) {
|
|
126
|
+
if (days === null) return "*";
|
|
127
|
+
const numbers = days.map((day) => CRON_DAY[day]).sort((a, b) => a - b);
|
|
128
|
+
const parts = [];
|
|
129
|
+
let start = 0;
|
|
130
|
+
for (let index = 1; index <= numbers.length; index += 1) {
|
|
131
|
+
if (index < numbers.length && numbers[index] === numbers[index - 1] + 1) continue;
|
|
132
|
+
const run = numbers.slice(start, index);
|
|
133
|
+
parts.push(run.length >= 3 ? `${run[0]}-${run[run.length - 1]}` : run.join(","));
|
|
134
|
+
start = index;
|
|
135
|
+
}
|
|
136
|
+
return parts.join(",");
|
|
137
|
+
}
|
|
138
|
+
function cadenceCron(cadence) {
|
|
139
|
+
if (cadence.kind === "every") {
|
|
140
|
+
const seconds = cadence.seconds;
|
|
141
|
+
if (seconds < 3600) return `*/${seconds / 60} * * * *`;
|
|
142
|
+
if (seconds < 86400) return `0 */${seconds / 3600} * * *`;
|
|
143
|
+
return "0 0 * * *";
|
|
144
|
+
}
|
|
145
|
+
if (cadence.kind === "hourly") return `${cadence.minute ?? 0} * * * *`;
|
|
146
|
+
const [hour, minute] = (cadence.at ?? "00:00").split(":");
|
|
147
|
+
return `${Number(minute)} ${Number(hour)} * * ${cronDayField(cadence.days)}`;
|
|
148
|
+
}
|
|
149
|
+
function cadencePeriodSeconds(cadence) {
|
|
150
|
+
if (cadence.kind === "every") return cadence.seconds;
|
|
151
|
+
if (cadence.kind === "hourly") return 3600;
|
|
152
|
+
if (cadence.days === null) return 86400;
|
|
153
|
+
const indexes = cadence.days.map((day) => WEEKDAYS.indexOf(day)).sort((a, b) => a - b);
|
|
154
|
+
let gap = WEEKDAYS.length - indexes[indexes.length - 1] + indexes[0];
|
|
155
|
+
for (let index = 1; index < indexes.length; index += 1) gap = Math.min(gap, indexes[index] - indexes[index - 1]);
|
|
156
|
+
return gap * 86400;
|
|
157
|
+
}
|
|
158
|
+
function parseWindowSeconds(interval, id) {
|
|
159
|
+
if (typeof interval !== "string" || !/^[0-9]+[mhd]$/.test(interval)) fail$1(`schedule "${id}" smear window must be an interval such as "15m", "1h", or "1d"`);
|
|
160
|
+
const amount = Number(interval.slice(0, -1));
|
|
161
|
+
const unit = interval.slice(-1);
|
|
162
|
+
const seconds = amount * (unit === "m" ? 60 : unit === "h" ? 3600 : 86400);
|
|
163
|
+
if (seconds < 60 || seconds > 86400) fail$1(`schedule "${id}" smear window must be between "1m" and "1d"`);
|
|
164
|
+
return seconds;
|
|
165
|
+
}
|
|
166
|
+
//#endregion
|
|
167
|
+
//#region src/core/schedule.ts
|
|
168
|
+
const OVERLAP_POLICIES = [
|
|
169
|
+
"skip",
|
|
170
|
+
"cancel-previous",
|
|
171
|
+
"terminate-previous"
|
|
172
|
+
];
|
|
173
|
+
function fail(message) {
|
|
174
|
+
throw new Error(`@lovable.dev/workflows-sdk: ${message}`);
|
|
175
|
+
}
|
|
176
|
+
function resolveTimeZone(schedule) {
|
|
177
|
+
const timeZone = schedule.timeZone;
|
|
178
|
+
if (typeof timeZone !== "string" || timeZone === "") fail(`schedule "${schedule.id}" needs a timeZone, such as "Europe/Stockholm" or "UTC"`);
|
|
179
|
+
if (timeZone !== "UTC" && !timeZone.includes("/")) fail(`schedule "${schedule.id}" timeZone "${timeZone}" must be an IANA region name such as "Europe/Stockholm", not a fixed offset or abbreviation`);
|
|
180
|
+
new Intl.DateTimeFormat("en", { timeZone });
|
|
181
|
+
return timeZone;
|
|
182
|
+
}
|
|
183
|
+
function unpinnedWindowSeconds(cadence) {
|
|
184
|
+
if (cadence.kind === "daily" && cadence.at === null) return 86400;
|
|
185
|
+
if (cadence.kind === "hourly" && cadence.minute === null) return 3600;
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
function resolveSmear(schedule, cadence) {
|
|
189
|
+
const unpinned = unpinnedWindowSeconds(cadence);
|
|
190
|
+
if (schedule.smear === void 0) return unpinned === null ? { strategy: "none" } : {
|
|
191
|
+
strategy: "hash",
|
|
192
|
+
windowSeconds: unpinned
|
|
193
|
+
};
|
|
194
|
+
if (schedule.smear === false || typeof schedule.smear === "object" && "strategy" in schedule.smear && schedule.smear.strategy === "none") {
|
|
195
|
+
if (unpinned !== null) fail(`schedule "${schedule.id}" uses ${cadence.kind}() with no time; pass { at } or keep the smear`);
|
|
196
|
+
return { strategy: "none" };
|
|
197
|
+
}
|
|
198
|
+
if (typeof schedule.smear !== "object") fail(`schedule "${schedule.id}" smear must be false or { window }`);
|
|
199
|
+
const windowSeconds = "window" in schedule.smear ? parseWindowSeconds(schedule.smear.window, schedule.id) : schedule.smear.windowSeconds;
|
|
200
|
+
const period = cadencePeriodSeconds(cadence);
|
|
201
|
+
if (windowSeconds > period) fail(`schedule "${schedule.id}" smear window must not exceed its ${period}s firing period`);
|
|
202
|
+
return {
|
|
203
|
+
strategy: "hash",
|
|
204
|
+
windowSeconds
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
function defineSchedule(schedule) {
|
|
208
|
+
assertIdentifier("schedule", schedule.id);
|
|
209
|
+
if (!isCadence(schedule.cadence)) fail(`schedule "${schedule.id}" cadence must come from every(), hourly(), daily(), or weekly()`);
|
|
210
|
+
const cadence = schedule.cadence;
|
|
211
|
+
const cron = cadenceCron(cadence);
|
|
212
|
+
const timeZone = resolveTimeZone(schedule);
|
|
213
|
+
const overlapPolicy = schedule.overlapPolicy ?? "skip";
|
|
214
|
+
if (!OVERLAP_POLICIES.includes(overlapPolicy)) fail(`schedule "${schedule.id}" overlapPolicy must be one of ${OVERLAP_POLICIES.join(", ")}`);
|
|
215
|
+
const enabled = schedule.enabled ?? true;
|
|
216
|
+
if (typeof enabled !== "boolean") fail(`schedule "${schedule.id}" enabled must be a boolean`);
|
|
217
|
+
return {
|
|
218
|
+
...schedule,
|
|
219
|
+
type: "schedule",
|
|
220
|
+
cadence,
|
|
221
|
+
cron,
|
|
222
|
+
timeZone,
|
|
223
|
+
overlapPolicy,
|
|
224
|
+
enabled,
|
|
225
|
+
smear: resolveSmear(schedule, cadence)
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
//#endregion
|
|
229
|
+
//#region src/core/workflow.ts
|
|
230
|
+
function registerWorkflows({ workflows, triggers = [] }) {
|
|
231
|
+
const ids = /* @__PURE__ */ new Set();
|
|
232
|
+
for (const workflow of workflows) {
|
|
233
|
+
if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
|
|
234
|
+
assertIdentifier("workflow", workflow.id);
|
|
235
|
+
if (!/^[a-z0-9][a-z0-9_-]{0,127}$/.test(workflow.id)) throw new Error("@lovable.dev/workflows-sdk: workflow names must be 1–128 lowercase letters, digits, hyphens or underscores, starting with a letter or digit");
|
|
236
|
+
if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
|
|
237
|
+
ids.add(workflow.id);
|
|
238
|
+
}
|
|
239
|
+
const scheduleIds = /* @__PURE__ */ new Set();
|
|
240
|
+
const registeredTriggers = triggers.map((trigger) => {
|
|
241
|
+
const definition = defineSchedule(trigger);
|
|
242
|
+
if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
|
|
243
|
+
if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
|
|
244
|
+
scheduleIds.add(definition.id);
|
|
245
|
+
return definition;
|
|
246
|
+
});
|
|
247
|
+
return {
|
|
248
|
+
workflows: [...workflows],
|
|
249
|
+
triggers: registeredTriggers
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/manifests/json.ts
|
|
254
|
+
function toJson(value, jsonPath, ancestors = /* @__PURE__ */ new Set()) {
|
|
255
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
256
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
257
|
+
if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain finite, acyclic JSON values`);
|
|
258
|
+
ancestors.add(value);
|
|
259
|
+
try {
|
|
260
|
+
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must not contain symbol keys`);
|
|
261
|
+
if (Array.isArray(value)) {
|
|
262
|
+
if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must be a dense JSON array without extra properties`);
|
|
263
|
+
return Array.from(value, (item, index) => toJson(item, `${jsonPath}[${index}]`, ancestors));
|
|
264
|
+
}
|
|
265
|
+
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${jsonPath} must contain plain JSON objects`);
|
|
266
|
+
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${jsonPath}.${key}`, ancestors)]));
|
|
267
|
+
} finally {
|
|
268
|
+
ancestors.delete(value);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
//#endregion
|
|
272
|
+
//#region src/manifests/generate.ts
|
|
273
|
+
function serializeSchema(schema, direction, label) {
|
|
274
|
+
if (!schema) return void 0;
|
|
275
|
+
const standard = schema["~standard"];
|
|
276
|
+
if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
|
|
277
|
+
try {
|
|
278
|
+
return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
|
|
279
|
+
} catch (cause) {
|
|
280
|
+
throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
async function generateManifests(definition) {
|
|
284
|
+
const { extractWorkflowGraph } = await import("./graph-BgdiEUHq.js");
|
|
285
|
+
const collection = registerWorkflows(definition);
|
|
286
|
+
const manifests = [];
|
|
287
|
+
for (const workflow of collection.workflows) {
|
|
288
|
+
if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
|
|
289
|
+
const metadata = {
|
|
290
|
+
id: workflow.id,
|
|
291
|
+
...workflow.description === void 0 ? {} : { description: workflow.description },
|
|
292
|
+
...workflow.version === void 0 ? {} : { version: workflow.version },
|
|
293
|
+
...workflow.inputSchema ? { inputSchema: serializeSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
|
|
294
|
+
...workflow.outputSchema ? { outputSchema: serializeSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
|
|
295
|
+
...workflow.stateSchema ? { stateSchema: serializeSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
|
|
296
|
+
};
|
|
297
|
+
const triggers = [];
|
|
298
|
+
for (const schedule of collection.triggers.filter((trigger) => trigger.workflow === workflow)) {
|
|
299
|
+
const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
|
|
300
|
+
const schema = schedule.workflow.inputSchema;
|
|
301
|
+
if (schema) {
|
|
302
|
+
const result = await schema["~standard"].validate(input);
|
|
303
|
+
if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
|
|
304
|
+
}
|
|
305
|
+
triggers.push({
|
|
306
|
+
type: schedule.type,
|
|
307
|
+
id: schedule.id,
|
|
308
|
+
cadence: schedule.cadence,
|
|
309
|
+
cron: schedule.cron,
|
|
310
|
+
timeZone: schedule.timeZone,
|
|
311
|
+
enabled: schedule.enabled,
|
|
312
|
+
overlapPolicy: schedule.overlapPolicy,
|
|
313
|
+
smear: schedule.smear,
|
|
314
|
+
input
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
triggers.sort((a, b) => {
|
|
318
|
+
const key = (entry) => `${entry.type}\u0000${entry.id}`;
|
|
319
|
+
return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0;
|
|
320
|
+
});
|
|
321
|
+
const manifest = {
|
|
322
|
+
version: 1,
|
|
323
|
+
workflow: metadata,
|
|
324
|
+
triggers,
|
|
325
|
+
graph: await extractWorkflowGraph(workflow.handler)
|
|
326
|
+
};
|
|
327
|
+
toJson(manifest, "manifest");
|
|
328
|
+
manifests.push(manifest);
|
|
329
|
+
}
|
|
330
|
+
return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
|
|
331
|
+
}
|
|
332
|
+
//#endregion
|
|
333
|
+
export { defineSchedule as a, hourly as c, registerWorkflows as i, weekly as l, createMiddleware as n, daily as o, createWorkflow as r, every as s, generateManifests as t };
|
|
@@ -1,4 +1,11 @@
|
|
|
1
|
-
//#region src/graph
|
|
1
|
+
//#region src/manifests/graph.ts
|
|
2
|
+
const durableMethods = {
|
|
3
|
+
step: 0,
|
|
4
|
+
approve: 0,
|
|
5
|
+
waitForEvent: 0,
|
|
6
|
+
sleep: 0,
|
|
7
|
+
sleepUntil: 0
|
|
8
|
+
};
|
|
2
9
|
let loaded;
|
|
3
10
|
async function loadTypeScript() {
|
|
4
11
|
if (loaded !== void 0) return loaded;
|
|
@@ -33,9 +40,12 @@ async function extractWorkflowGraph(handler) {
|
|
|
33
40
|
});
|
|
34
41
|
return [id];
|
|
35
42
|
}
|
|
36
|
-
function
|
|
43
|
+
function degrade(reason) {
|
|
37
44
|
graph.complete = false;
|
|
38
45
|
if (!graph.diagnostics.includes(reason)) graph.diagnostics.push(reason);
|
|
46
|
+
}
|
|
47
|
+
function unknown(reason, parents) {
|
|
48
|
+
degrade(reason);
|
|
39
49
|
return addNode({
|
|
40
50
|
kind: "unknown",
|
|
41
51
|
label: reason
|
|
@@ -64,22 +74,94 @@ async function extractWorkflowGraph(handler) {
|
|
|
64
74
|
if (skipFunctions && ts.isFunctionLike(node)) return false;
|
|
65
75
|
return predicate(node) || Boolean(ts.forEachChild(node, (child) => contains(child, predicate, skipFunctions) || void 0));
|
|
66
76
|
}
|
|
67
|
-
function
|
|
68
|
-
return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text
|
|
77
|
+
function durableCall(node) {
|
|
78
|
+
return ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === context && node.expression.name.text in durableMethods;
|
|
79
|
+
}
|
|
80
|
+
function stringLiteral(node) {
|
|
81
|
+
return node && (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) ? node.text : void 0;
|
|
82
|
+
}
|
|
83
|
+
function numberLiteral(node) {
|
|
84
|
+
if (!node || !ts.isNumericLiteral(node)) return void 0;
|
|
85
|
+
const value = Number(node.text);
|
|
86
|
+
return Number.isFinite(value) ? value : void 0;
|
|
87
|
+
}
|
|
88
|
+
function readableOptions(node) {
|
|
89
|
+
return node && ts.isObjectLiteralExpression(node) && node.properties.every(ts.isPropertyAssignment) ? node : void 0;
|
|
90
|
+
}
|
|
91
|
+
function option(options, name) {
|
|
92
|
+
for (const property of options?.properties ?? []) {
|
|
93
|
+
if (!ts.isPropertyAssignment(property)) continue;
|
|
94
|
+
if ((ts.isIdentifier(property.name) || ts.isStringLiteral(property.name) ? property.name.text : void 0) === name) return property.initializer;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
function durableNode(call, parents) {
|
|
98
|
+
const method = call.expression.name.text;
|
|
99
|
+
if (method === "step") {
|
|
100
|
+
const stepId = stringLiteral(call.arguments[0]);
|
|
101
|
+
if (stepId === void 0) return unknown("Dynamic step IDs are not supported yet", parents);
|
|
102
|
+
return addNode({
|
|
103
|
+
kind: "step",
|
|
104
|
+
stepId,
|
|
105
|
+
label: stepId
|
|
106
|
+
}, parents);
|
|
107
|
+
}
|
|
108
|
+
if (method === "approve") {
|
|
109
|
+
const options = readableOptions(call.arguments[0]);
|
|
110
|
+
const title = stringLiteral(option(options, "title"));
|
|
111
|
+
if (title === void 0) return unknown("Dynamic approval titles are not supported yet", parents);
|
|
112
|
+
const given = option(options, "description");
|
|
113
|
+
const description = stringLiteral(given);
|
|
114
|
+
if (given && description === void 0) degrade("Dynamic approval descriptions are not recorded");
|
|
115
|
+
return addNode({
|
|
116
|
+
kind: "approve",
|
|
117
|
+
config: {
|
|
118
|
+
title,
|
|
119
|
+
...description === void 0 ? {} : { description }
|
|
120
|
+
},
|
|
121
|
+
label: title
|
|
122
|
+
}, parents);
|
|
123
|
+
}
|
|
124
|
+
if (method === "waitForEvent") {
|
|
125
|
+
const event = stringLiteral(call.arguments[0]);
|
|
126
|
+
if (event === void 0) return unknown("Dynamic event names are not supported yet", parents);
|
|
127
|
+
const options = readableOptions(call.arguments[1]);
|
|
128
|
+
if (call.arguments[1] && !options) degrade("Dynamic waitForEvent options are not recorded");
|
|
129
|
+
const given = option(options, "deadline");
|
|
130
|
+
const deadline = numberLiteral(given);
|
|
131
|
+
if (given && deadline === void 0) degrade("Dynamic waitForEvent deadlines are not recorded");
|
|
132
|
+
return addNode({
|
|
133
|
+
kind: "wait-for-event",
|
|
134
|
+
config: {
|
|
135
|
+
event,
|
|
136
|
+
...deadline === void 0 ? {} : { deadline }
|
|
137
|
+
},
|
|
138
|
+
label: event
|
|
139
|
+
}, parents);
|
|
140
|
+
}
|
|
141
|
+
if (method === "sleep") {
|
|
142
|
+
const ms = numberLiteral(call.arguments[0]);
|
|
143
|
+
if (ms === void 0) return unknown("Dynamic sleep durations are not supported yet", parents);
|
|
144
|
+
return addNode({
|
|
145
|
+
kind: "sleep",
|
|
146
|
+
config: { ms },
|
|
147
|
+
label: `sleep ${ms}ms`
|
|
148
|
+
}, parents);
|
|
149
|
+
}
|
|
150
|
+
const timestamp = numberLiteral(call.arguments[0]);
|
|
151
|
+
if (timestamp === void 0) return unknown("Dynamic sleepUntil timestamps are not supported yet", parents);
|
|
152
|
+
return addNode({
|
|
153
|
+
kind: "sleep-until",
|
|
154
|
+
config: { timestamp },
|
|
155
|
+
label: `sleep until ${timestamp}`
|
|
156
|
+
}, parents);
|
|
69
157
|
}
|
|
70
158
|
function expression(node, parents, awaited = false) {
|
|
71
159
|
if (ts.isParenthesizedExpression(node)) return expression(node.expression, parents, awaited);
|
|
72
160
|
if (ts.isAwaitExpression(node)) return expression(node.expression, parents, true);
|
|
73
|
-
if (
|
|
74
|
-
if (!awaited) return unknown("Unawaited
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
77
|
-
const tails = addNode({
|
|
78
|
-
kind: "step",
|
|
79
|
-
stepId: stepId.text,
|
|
80
|
-
label: stepId.text
|
|
81
|
-
}, parents);
|
|
82
|
-
if (node.arguments.slice(1).some((argument) => contains(argument, contextStep))) return unknown("Nested steps are not supported yet", tails);
|
|
161
|
+
if (durableCall(node)) {
|
|
162
|
+
if (!awaited) return unknown("Unawaited durable calls are not supported yet", parents);
|
|
163
|
+
const tails = durableNode(node, parents);
|
|
164
|
+
if (node.arguments.some((argument) => contains(argument, durableCall))) return unknown("Nested durable calls are not supported yet", tails);
|
|
83
165
|
return tails;
|
|
84
166
|
}
|
|
85
167
|
if (awaited && ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && ts.isIdentifier(node.expression.expression) && node.expression.expression.text === "Promise" && node.expression.name.text === "all" && node.arguments.length === 1 && ts.isArrayLiteralExpression(node.arguments[0])) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,35 +1,115 @@
|
|
|
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/
|
|
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
|
|
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
|
-
//#region src/
|
|
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
|
-
//#region src/graph.d.ts
|
|
75
|
+
//#region src/manifests/graph.d.ts
|
|
76
|
+
type WorkflowGraphNodeDetails = {
|
|
77
|
+
kind: "step";
|
|
78
|
+
stepId: string;
|
|
79
|
+
} | {
|
|
80
|
+
kind: "approve";
|
|
81
|
+
config: {
|
|
82
|
+
title: string;
|
|
83
|
+
description?: string;
|
|
84
|
+
};
|
|
85
|
+
} | {
|
|
86
|
+
kind: "wait-for-event";
|
|
87
|
+
config: {
|
|
88
|
+
event: string;
|
|
89
|
+
deadline?: number;
|
|
90
|
+
};
|
|
91
|
+
} | {
|
|
92
|
+
kind: "sleep";
|
|
93
|
+
config: {
|
|
94
|
+
ms: number;
|
|
95
|
+
};
|
|
96
|
+
} | {
|
|
97
|
+
kind: "sleep-until";
|
|
98
|
+
config: {
|
|
99
|
+
timestamp: number;
|
|
100
|
+
};
|
|
101
|
+
} | {
|
|
102
|
+
kind: "unknown";
|
|
103
|
+
};
|
|
104
|
+
type WorkflowGraphNode = {
|
|
105
|
+
id: string;
|
|
106
|
+
label: string;
|
|
107
|
+
} & WorkflowGraphNodeDetails;
|
|
23
108
|
interface WorkflowGraph {
|
|
24
109
|
source: "inferred";
|
|
25
110
|
scope: "handler";
|
|
26
111
|
complete: boolean;
|
|
27
|
-
nodes:
|
|
28
|
-
id: string;
|
|
29
|
-
kind: "step" | "unknown";
|
|
30
|
-
label: string;
|
|
31
|
-
stepId?: string;
|
|
32
|
-
}[];
|
|
112
|
+
nodes: WorkflowGraphNode[];
|
|
33
113
|
edges: {
|
|
34
114
|
source: string;
|
|
35
115
|
target: string;
|
|
@@ -38,12 +118,12 @@ interface WorkflowGraph {
|
|
|
38
118
|
diagnostics: string[];
|
|
39
119
|
}
|
|
40
120
|
//#endregion
|
|
41
|
-
//#region src/json.d.ts
|
|
121
|
+
//#region src/manifests/json.d.ts
|
|
42
122
|
type JsonValue = null | boolean | number | string | JsonValue[] | {
|
|
43
123
|
[key: string]: JsonValue;
|
|
44
124
|
};
|
|
45
125
|
//#endregion
|
|
46
|
-
//#region src/
|
|
126
|
+
//#region src/manifests/generate.d.ts
|
|
47
127
|
interface WorkflowManifest {
|
|
48
128
|
version: 1;
|
|
49
129
|
workflow: {
|
|
@@ -54,14 +134,19 @@ interface WorkflowManifest {
|
|
|
54
134
|
outputSchema?: JsonValue;
|
|
55
135
|
stateSchema?: JsonValue;
|
|
56
136
|
};
|
|
57
|
-
|
|
137
|
+
triggers: {
|
|
138
|
+
type: "schedule";
|
|
58
139
|
id: string;
|
|
140
|
+
cadence: Cadence;
|
|
59
141
|
cron: string;
|
|
60
142
|
timeZone: string;
|
|
143
|
+
enabled: boolean;
|
|
144
|
+
overlapPolicy: OverlapPolicy;
|
|
145
|
+
smear: SmearPolicy;
|
|
61
146
|
input: JsonValue;
|
|
62
147
|
}[];
|
|
63
148
|
graph: WorkflowGraph;
|
|
64
149
|
}
|
|
65
150
|
declare function generateManifests(definition: WorkflowsDefinition): Promise<WorkflowManifest[]>;
|
|
66
151
|
//#endregion
|
|
67
|
-
export { type AnyWorkflowDefinition, type Ctx, type ScheduleDefinition, type StepContext, type StepOptions, type WorkflowDefinition, type WorkflowGraph, type WorkflowInput, type WorkflowManifest, type WorkflowOutput, type WorkflowState, type WorkflowsDefinition, createMiddleware, createWorkflow, defineSchedule, generateManifests, registerWorkflows };
|
|
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,3 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { a as defineSchedule, c as hourly, i as registerWorkflows, l as weekly, n as createMiddleware, o as daily, r as createWorkflow, s as every, t as generateManifests } from "./generate-IXn3QGVb.js";
|
|
2
|
+
//#region src/core/smear.ts
|
|
3
|
+
const FNV_OFFSET = 14695981039346656037n;
|
|
4
|
+
const FNV_PRIME = 1099511628211n;
|
|
5
|
+
const MASK = (1n << 64n) - 1n;
|
|
6
|
+
function fnv1a64(value) {
|
|
7
|
+
let hash = FNV_OFFSET;
|
|
8
|
+
for (const byte of new TextEncoder().encode(value)) hash = (hash ^ BigInt(byte)) * FNV_PRIME & MASK;
|
|
9
|
+
return hash;
|
|
10
|
+
}
|
|
11
|
+
function smearOffsetSeconds(projectId, scheduleId, windowSeconds) {
|
|
12
|
+
if (!Number.isSafeInteger(windowSeconds) || windowSeconds <= 0) throw new Error("@lovable.dev/workflows-sdk: smear window must be a positive whole number of seconds");
|
|
13
|
+
return Number(fnv1a64(`${projectId}\u0000${scheduleId}`) % BigInt(windowSeconds));
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
export { createMiddleware, createWorkflow, daily, defineSchedule, every, generateManifests, hourly, registerWorkflows, smearOffsetSeconds, weekly };
|
package/dist/vite.d.ts
CHANGED
package/dist/vite.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as generateManifests } from "./
|
|
1
|
+
import { t as generateManifests } from "./generate-IXn3QGVb.js";
|
|
2
2
|
import { join, resolve } from "node:path";
|
|
3
3
|
import { createServer } from "vite";
|
|
4
4
|
import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
-
//#region src/manifest-files.ts
|
|
5
|
+
//#region src/vite/manifest-files.ts
|
|
6
6
|
async function ensureDirectory(path) {
|
|
7
7
|
try {
|
|
8
8
|
await mkdir(path);
|
|
@@ -30,7 +30,7 @@ async function writeManifests(root, manifests) {
|
|
|
30
30
|
}
|
|
31
31
|
}
|
|
32
32
|
//#endregion
|
|
33
|
-
//#region src/vite.ts
|
|
33
|
+
//#region src/vite/plugin.ts
|
|
34
34
|
function workflowsManifest({ entry }) {
|
|
35
35
|
let config;
|
|
36
36
|
return {
|
|
@@ -63,7 +63,7 @@ function workflowsManifest({ entry }) {
|
|
|
63
63
|
});
|
|
64
64
|
try {
|
|
65
65
|
const module = await server.ssrLoadModule(entryPath);
|
|
66
|
-
if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.
|
|
66
|
+
if (!module.default || !Array.isArray(module.default.workflows) || !Array.isArray(module.default.triggers)) throw new Error(`@lovable.dev/workflows-sdk: ${entry} must default-export a registerWorkflows() collection`);
|
|
67
67
|
const manifests = await generateManifests(module.default);
|
|
68
68
|
await writeManifests(config.root, manifests);
|
|
69
69
|
} finally {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lovable.dev/workflows-sdk",
|
|
3
|
-
"version": "0.0.0-dev.
|
|
3
|
+
"version": "0.0.0-dev.4",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"tag": "dev",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"scripts": {
|
|
54
54
|
"build": "tsdown",
|
|
55
|
-
"test": "node --test
|
|
55
|
+
"test": "node --test tests/*.test.mjs",
|
|
56
56
|
"typecheck": "tsc -p tsconfig.typecheck.json",
|
|
57
57
|
"check:package": "tmp=$(mktemp -d) && pnpm pack --out \"$tmp/pkg.tgz\" && tar -xzf \"$tmp/pkg.tgz\" -C \"$tmp\" && publint \"$tmp/package\" --strict && attw \"$tmp/pkg.tgz\" && node scripts/check-deps.mjs \"$tmp/package/package.json\""
|
|
58
58
|
}
|
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
//#region src/validation.ts
|
|
2
|
-
function assertIdentifier(kind, id) {
|
|
3
|
-
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`);
|
|
4
|
-
}
|
|
5
|
-
//#endregion
|
|
6
|
-
//#region src/schedule.ts
|
|
7
|
-
function defineSchedule(schedule) {
|
|
8
|
-
assertIdentifier("schedule", schedule.id);
|
|
9
|
-
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`);
|
|
10
|
-
const timeZone = schedule.timeZone ?? "UTC";
|
|
11
|
-
new Intl.DateTimeFormat("en", { timeZone });
|
|
12
|
-
return {
|
|
13
|
-
...schedule,
|
|
14
|
-
timeZone
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
//#endregion
|
|
18
|
-
//#region src/register.ts
|
|
19
|
-
function registerWorkflows({ workflows, schedules = [] }) {
|
|
20
|
-
const ids = /* @__PURE__ */ new Set();
|
|
21
|
-
for (const workflow of workflows) {
|
|
22
|
-
if (workflow.__kind !== "workflow" || typeof workflow.handler !== "function") throw new Error("@lovable.dev/workflows-sdk: expected a completed createWorkflow().handler() definition");
|
|
23
|
-
assertIdentifier("workflow", workflow.id);
|
|
24
|
-
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");
|
|
25
|
-
if (ids.has(workflow.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate workflow ID "${workflow.id}"`);
|
|
26
|
-
ids.add(workflow.id);
|
|
27
|
-
}
|
|
28
|
-
const scheduleIds = /* @__PURE__ */ new Set();
|
|
29
|
-
const registeredSchedules = schedules.map((schedule) => {
|
|
30
|
-
const definition = defineSchedule(schedule);
|
|
31
|
-
if (scheduleIds.has(definition.id)) throw new Error(`@lovable.dev/workflows-sdk: duplicate schedule ID "${definition.id}"`);
|
|
32
|
-
if (!workflows.includes(definition.workflow)) throw new Error(`@lovable.dev/workflows-sdk: schedule "${definition.id}" references an unregistered workflow`);
|
|
33
|
-
scheduleIds.add(definition.id);
|
|
34
|
-
return definition;
|
|
35
|
-
});
|
|
36
|
-
return {
|
|
37
|
-
workflows: [...workflows],
|
|
38
|
-
schedules: registeredSchedules
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
//#endregion
|
|
42
|
-
//#region src/json.ts
|
|
43
|
-
function toJson(value, path, ancestors = /* @__PURE__ */ new Set()) {
|
|
44
|
-
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
45
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
46
|
-
if (typeof value !== "object" || ancestors.has(value)) throw new Error(`@lovable.dev/workflows-sdk: ${path} must contain finite, acyclic JSON values`);
|
|
47
|
-
ancestors.add(value);
|
|
48
|
-
try {
|
|
49
|
-
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`@lovable.dev/workflows-sdk: ${path} must not contain symbol keys`);
|
|
50
|
-
if (Array.isArray(value)) {
|
|
51
|
-
if (Object.keys(value).length !== value.length) throw new Error(`@lovable.dev/workflows-sdk: ${path} must be a dense JSON array without extra properties`);
|
|
52
|
-
return Array.from(value, (item, index) => toJson(item, `${path}[${index}]`, ancestors));
|
|
53
|
-
}
|
|
54
|
-
if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new Error(`@lovable.dev/workflows-sdk: ${path} must contain plain JSON objects`);
|
|
55
|
-
return Object.fromEntries(Object.keys(value).sort().map((key) => [key, toJson(value[key], `${path}.${key}`, ancestors)]));
|
|
56
|
-
} finally {
|
|
57
|
-
ancestors.delete(value);
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
//#endregion
|
|
61
|
-
//#region src/manifest.ts
|
|
62
|
-
function jsonSchema(schema, direction, label) {
|
|
63
|
-
if (!schema) return void 0;
|
|
64
|
-
const standard = schema["~standard"];
|
|
65
|
-
if (typeof standard.jsonSchema?.[direction] !== "function") throw new Error(`@lovable.dev/workflows-sdk: ${label} must support Standard JSON Schema conversion`);
|
|
66
|
-
try {
|
|
67
|
-
return toJson(standard.jsonSchema[direction]({ target: "draft-2020-12" }), label);
|
|
68
|
-
} catch (cause) {
|
|
69
|
-
throw new Error(`@lovable.dev/workflows-sdk: cannot serialize ${label}`, { cause });
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
async function generateManifests(definition) {
|
|
73
|
-
const { extractWorkflowGraph } = await import("./graph-extract-CGLWzaln.js");
|
|
74
|
-
const collection = registerWorkflows(definition);
|
|
75
|
-
const manifests = [];
|
|
76
|
-
for (const workflow of collection.workflows) {
|
|
77
|
-
if (workflow.previousVersions?.length) throw new Error(`@lovable.dev/workflows-sdk: workflow "${workflow.id}" previousVersions are not supported yet`);
|
|
78
|
-
const metadata = {
|
|
79
|
-
id: workflow.id,
|
|
80
|
-
...workflow.description === void 0 ? {} : { description: workflow.description },
|
|
81
|
-
...workflow.version === void 0 ? {} : { version: workflow.version },
|
|
82
|
-
...workflow.inputSchema ? { inputSchema: jsonSchema(workflow.inputSchema, "input", `${workflow.id}.input`) } : {},
|
|
83
|
-
...workflow.outputSchema ? { outputSchema: jsonSchema(workflow.outputSchema, "output", `${workflow.id}.output`) } : {},
|
|
84
|
-
...workflow.stateSchema ? { stateSchema: jsonSchema(workflow.stateSchema, "output", `${workflow.id}.state`) } : {}
|
|
85
|
-
};
|
|
86
|
-
const schedules = [];
|
|
87
|
-
for (const schedule of collection.schedules.filter((schedule) => schedule.workflow === workflow)) {
|
|
88
|
-
const input = toJson(schedule.input, `schedule "${schedule.id}" input`);
|
|
89
|
-
const schema = schedule.workflow.inputSchema;
|
|
90
|
-
if (schema) {
|
|
91
|
-
const result = await schema["~standard"].validate(input);
|
|
92
|
-
if (result.issues) throw new Error(`@lovable.dev/workflows-sdk: schedule "${schedule.id}" input is invalid: ${result.issues.map((issue) => issue.message).join("; ")}`);
|
|
93
|
-
}
|
|
94
|
-
schedules.push({
|
|
95
|
-
id: schedule.id,
|
|
96
|
-
cron: schedule.cron,
|
|
97
|
-
timeZone: schedule.timeZone ?? "UTC",
|
|
98
|
-
input
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
schedules.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
102
|
-
const manifest = {
|
|
103
|
-
version: 1,
|
|
104
|
-
workflow: metadata,
|
|
105
|
-
schedules,
|
|
106
|
-
graph: await extractWorkflowGraph(workflow.handler)
|
|
107
|
-
};
|
|
108
|
-
toJson(manifest, "manifest");
|
|
109
|
-
manifests.push(manifest);
|
|
110
|
-
}
|
|
111
|
-
return manifests.sort((a, b) => a.workflow.id < b.workflow.id ? -1 : a.workflow.id > b.workflow.id ? 1 : 0);
|
|
112
|
-
}
|
|
113
|
-
//#endregion
|
|
114
|
-
export { registerWorkflows as n, defineSchedule as r, generateManifests as t };
|