@weft-framework/server 0.0.0-stage → 0.0.1
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/LICENSE +21 -0
- package/README.md +4 -2
- package/dist/account.d.ts +124 -0
- package/dist/account.js +344 -0
- package/dist/action.d.ts +43 -0
- package/dist/action.js +135 -0
- package/dist/admin.d.ts +99 -0
- package/dist/admin.js +431 -0
- package/dist/api.d.ts +21 -0
- package/dist/api.js +72 -0
- package/dist/app.d.ts +202 -0
- package/dist/app.js +3692 -0
- package/dist/assets.d.ts +4 -0
- package/dist/assets.js +91 -0
- package/dist/auth.d.ts +150 -0
- package/dist/auth.js +215 -0
- package/dist/backup.d.ts +46 -0
- package/dist/backup.js +345 -0
- package/dist/build.d.ts +33 -0
- package/dist/build.js +274 -0
- package/dist/bun.d.ts +30 -0
- package/dist/bun.js +53 -0
- package/dist/calendar.d.ts +161 -0
- package/dist/calendar.js +690 -0
- package/dist/compiler.d.ts +13 -0
- package/dist/compiler.js +58 -0
- package/dist/compress.d.ts +6 -0
- package/dist/compress.js +78 -0
- package/dist/config.d.ts +26 -0
- package/dist/config.js +317 -0
- package/dist/context.d.ts +9 -0
- package/dist/context.js +1 -0
- package/dist/contract.d.ts +18 -0
- package/dist/contract.js +171 -0
- package/dist/datamap.d.ts +24 -0
- package/dist/datamap.js +365 -0
- package/dist/db-backup.d.ts +27 -0
- package/dist/db-backup.js +115 -0
- package/dist/dev-events.d.ts +14 -0
- package/dist/dev-events.js +135 -0
- package/dist/dev.d.ts +1 -0
- package/dist/dev.js +240 -0
- package/dist/devtools-client.d.ts +1 -0
- package/dist/devtools-client.js +362 -0
- package/dist/devtools.d.ts +87 -0
- package/dist/devtools.js +68 -0
- package/dist/edge.d.ts +3 -0
- package/dist/edge.js +7 -0
- package/dist/email-signin.d.ts +92 -0
- package/dist/email-signin.js +259 -0
- package/dist/env.d.ts +1 -0
- package/dist/env.js +15 -0
- package/dist/explain.d.ts +12 -0
- package/dist/explain.js +217 -0
- package/dist/files.d.ts +6 -0
- package/dist/files.js +170 -0
- package/dist/grants.d.ts +69 -0
- package/dist/grants.js +206 -0
- package/dist/image/bitmap.d.ts +11 -0
- package/dist/image/bitmap.js +172 -0
- package/dist/image/jpeg.d.ts +10 -0
- package/dist/image/jpeg.js +697 -0
- package/dist/image/png.d.ts +8 -0
- package/dist/image/png.js +282 -0
- package/dist/image/transform.d.ts +20 -0
- package/dist/image/transform.js +52 -0
- package/dist/image/worker.d.ts +1 -0
- package/dist/image/worker.js +11 -0
- package/dist/images.d.ts +39 -0
- package/dist/images.js +283 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +31 -0
- package/dist/inspect-hub.d.ts +42 -0
- package/dist/inspect-hub.js +14 -0
- package/dist/inspector.d.ts +51 -0
- package/dist/inspector.js +193 -0
- package/dist/job-admin.d.ts +55 -0
- package/dist/job-admin.js +89 -0
- package/dist/jobs.d.ts +222 -0
- package/dist/jobs.js +789 -0
- package/dist/live.d.ts +72 -0
- package/dist/live.js +481 -0
- package/dist/load-config.d.ts +2 -0
- package/dist/load-config.js +41 -0
- package/dist/log.d.ts +20 -0
- package/dist/log.js +143 -0
- package/dist/mail.d.ts +189 -0
- package/dist/mail.js +999 -0
- package/dist/media.d.ts +129 -0
- package/dist/media.js +470 -0
- package/dist/meta.d.ts +54 -0
- package/dist/meta.js +146 -0
- package/dist/middleware.d.ts +20 -0
- package/dist/middleware.js +101 -0
- package/dist/migrate.d.ts +12 -0
- package/dist/migrate.js +88 -0
- package/dist/node.d.ts +26 -0
- package/dist/node.js +96 -0
- package/dist/notice.d.ts +21 -0
- package/dist/notice.js +48 -0
- package/dist/npm.d.ts +16 -0
- package/dist/npm.js +347 -0
- package/dist/oauth.d.ts +76 -0
- package/dist/oauth.js +408 -0
- package/dist/otel.d.ts +57 -0
- package/dist/otel.js +293 -0
- package/dist/passkey.d.ts +99 -0
- package/dist/passkey.js +572 -0
- package/dist/password.d.ts +8 -0
- package/dist/password.js +65 -0
- package/dist/pdf.d.ts +46 -0
- package/dist/pdf.js +332 -0
- package/dist/personal-data.d.ts +22 -0
- package/dist/personal-data.js +148 -0
- package/dist/pointers.d.ts +9 -0
- package/dist/pointers.js +148 -0
- package/dist/postcss.d.ts +3 -0
- package/dist/postcss.js +89 -0
- package/dist/presence.d.ts +27 -0
- package/dist/presence.js +161 -0
- package/dist/preview.d.ts +25 -0
- package/dist/preview.js +353 -0
- package/dist/production.d.ts +16 -0
- package/dist/production.js +119 -0
- package/dist/project.d.ts +23 -0
- package/dist/project.js +536 -0
- package/dist/regions.d.ts +47 -0
- package/dist/regions.js +511 -0
- package/dist/replay.d.ts +44 -0
- package/dist/replay.js +259 -0
- package/dist/router.d.ts +29 -0
- package/dist/router.js +146 -0
- package/dist/rules-diff.d.ts +18 -0
- package/dist/rules-diff.js +165 -0
- package/dist/rules-test.d.ts +17 -0
- package/dist/rules-test.js +108 -0
- package/dist/saml.d.ts +160 -0
- package/dist/saml.js +959 -0
- package/dist/seal.d.ts +35 -0
- package/dist/seal.js +107 -0
- package/dist/secret.d.ts +14 -0
- package/dist/secret.js +110 -0
- package/dist/security.d.ts +53 -0
- package/dist/security.js +250 -0
- package/dist/seed.d.ts +16 -0
- package/dist/seed.js +94 -0
- package/dist/seo.d.ts +42 -0
- package/dist/seo.js +175 -0
- package/dist/settings.d.ts +79 -0
- package/dist/settings.js +212 -0
- package/dist/shared.d.ts +15 -0
- package/dist/shared.js +283 -0
- package/dist/shell.d.ts +12 -0
- package/dist/shell.js +118 -0
- package/dist/storage.d.ts +13 -0
- package/dist/storage.js +55 -0
- package/dist/support.d.ts +83 -0
- package/dist/support.js +236 -0
- package/dist/sync.d.ts +35 -0
- package/dist/sync.js +167 -0
- package/dist/tailwind.d.ts +14 -0
- package/dist/tailwind.js +117 -0
- package/dist/two-factor.d.ts +103 -0
- package/dist/two-factor.js +435 -0
- package/dist/uploads.d.ts +185 -0
- package/dist/uploads.js +991 -0
- package/dist/webhooks.d.ts +169 -0
- package/dist/webhooks.js +758 -0
- package/dist/webpush.d.ts +97 -0
- package/dist/webpush.js +372 -0
- package/dist/wizard.d.ts +141 -0
- package/dist/wizard.js +410 -0
- package/dist/workflows.d.ts +134 -0
- package/dist/workflows.js +511 -0
- package/package.json +186 -4
package/dist/wizard.js
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
const NAME = /^[A-Za-z0-9._-]{1,64}$/;
|
|
2
|
+
const FIELD = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
3
|
+
const EMAIL = /^[^\s@"<>()\[\],;:\\]{1,64}@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/;
|
|
4
|
+
const TEL = /^\+?[0-9 ().-]{3,32}$/;
|
|
5
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
6
|
+
const DAY = 86_400_000;
|
|
7
|
+
function validDate(s) {
|
|
8
|
+
const m = DATE.exec(s);
|
|
9
|
+
if (!m)
|
|
10
|
+
return false;
|
|
11
|
+
const d = new Date(Date.UTC(+m[1], +m[2] - 1, +m[3]));
|
|
12
|
+
return d.getUTCFullYear() === +m[1] && d.getUTCMonth() === +m[2] - 1 && d.getUTCDate() === +m[3];
|
|
13
|
+
}
|
|
14
|
+
function checkField(step, name, f) {
|
|
15
|
+
const where = `defineWizard: ${step}.${name}`;
|
|
16
|
+
if (!FIELD.test(name) || name === "__proto__")
|
|
17
|
+
throw new Error(`${where}: bad field name`);
|
|
18
|
+
switch (f.type) {
|
|
19
|
+
case "text":
|
|
20
|
+
case "textarea":
|
|
21
|
+
case "email":
|
|
22
|
+
case "url":
|
|
23
|
+
case "tel":
|
|
24
|
+
for (const k of ["minLength", "maxLength"]) {
|
|
25
|
+
const v = f[k];
|
|
26
|
+
if (v !== undefined && (!Number.isInteger(v) || v < 0))
|
|
27
|
+
throw new Error(`${where}: ${k} is a whole number`);
|
|
28
|
+
}
|
|
29
|
+
if (f.pattern !== undefined && (!(f.pattern instanceof RegExp) || f.pattern.global || f.pattern.sticky)) {
|
|
30
|
+
throw new Error(`${where}: pattern is a RegExp without g or y`);
|
|
31
|
+
}
|
|
32
|
+
return;
|
|
33
|
+
case "number":
|
|
34
|
+
for (const k of ["min", "max"]) {
|
|
35
|
+
if (f[k] !== undefined && !Number.isFinite(f[k]))
|
|
36
|
+
throw new Error(`${where}: ${k} is a number`);
|
|
37
|
+
}
|
|
38
|
+
return;
|
|
39
|
+
case "choice":
|
|
40
|
+
if (!Array.isArray(f.options) || f.options.length === 0 || f.options.some((o) => typeof o !== "string")) {
|
|
41
|
+
throw new Error(`${where}: options are strings`);
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
case "date":
|
|
45
|
+
for (const k of ["min", "max"]) {
|
|
46
|
+
if (f[k] !== undefined && !validDate(f[k]))
|
|
47
|
+
throw new Error(`${where}: ${k} is a YYYY-MM-DD date`);
|
|
48
|
+
}
|
|
49
|
+
return;
|
|
50
|
+
case "boolean":
|
|
51
|
+
return;
|
|
52
|
+
default:
|
|
53
|
+
throw new Error(`${where}: unknown type ${f.type}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function parse(f, raw) {
|
|
57
|
+
if (f.type === "boolean") {
|
|
58
|
+
const on = raw === true || raw === "on" || raw === "true" || raw === "1";
|
|
59
|
+
if (f.required && !on)
|
|
60
|
+
return { error: "Required." };
|
|
61
|
+
return { value: on };
|
|
62
|
+
}
|
|
63
|
+
if (raw === undefined || raw === null || raw === "")
|
|
64
|
+
return f.required ? { error: "Required." } : {};
|
|
65
|
+
if (f.type === "number") {
|
|
66
|
+
const n = typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() !== "" ? Number(raw) : NaN;
|
|
67
|
+
if (!Number.isFinite(n))
|
|
68
|
+
return { error: "Enter a number." };
|
|
69
|
+
if (f.integer && !Number.isInteger(n))
|
|
70
|
+
return { error: "Enter a whole number." };
|
|
71
|
+
if (f.min !== undefined && n < f.min)
|
|
72
|
+
return { error: `At least ${f.min}.` };
|
|
73
|
+
if (f.max !== undefined && n > f.max)
|
|
74
|
+
return { error: `At most ${f.max}.` };
|
|
75
|
+
return { value: n };
|
|
76
|
+
}
|
|
77
|
+
if (typeof raw !== "string")
|
|
78
|
+
return { error: "Not a valid answer." };
|
|
79
|
+
const s = f.type === "textarea" ? raw.replace(/\r\n?/g, "\n") : raw.trim();
|
|
80
|
+
if (s === "")
|
|
81
|
+
return f.required ? { error: "Required." } : {};
|
|
82
|
+
switch (f.type) {
|
|
83
|
+
case "choice":
|
|
84
|
+
return f.options.includes(s) ? { value: s } : { error: "Choose one of the options." };
|
|
85
|
+
case "date":
|
|
86
|
+
if (!validDate(s))
|
|
87
|
+
return { error: "Enter a date." };
|
|
88
|
+
if (f.min !== undefined && s < f.min)
|
|
89
|
+
return { error: `On or after ${f.min}.` };
|
|
90
|
+
if (f.max !== undefined && s > f.max)
|
|
91
|
+
return { error: `On or before ${f.max}.` };
|
|
92
|
+
return { value: s };
|
|
93
|
+
default: {
|
|
94
|
+
if ((f.type === "textarea" ? /[\u0000-\u0008\u000b-\u001f\u007f]/ : /[\u0000-\u001f\u007f]/).test(s)) {
|
|
95
|
+
return { error: "Not a valid answer." };
|
|
96
|
+
}
|
|
97
|
+
const max = f.maxLength ?? (f.type === "textarea" ? 10_000 : 1_000);
|
|
98
|
+
const length = [...s].length;
|
|
99
|
+
if (length > max)
|
|
100
|
+
return { error: `At most ${max} characters.` };
|
|
101
|
+
if (f.minLength !== undefined && length < f.minLength)
|
|
102
|
+
return { error: `At least ${f.minLength} characters.` };
|
|
103
|
+
if (f.type === "email" && (s.length > 254 || !EMAIL.test(s)))
|
|
104
|
+
return { error: "Enter an email address." };
|
|
105
|
+
if (f.type === "tel" && !TEL.test(s))
|
|
106
|
+
return { error: "Enter a phone number." };
|
|
107
|
+
if (f.type === "url") {
|
|
108
|
+
let u = null;
|
|
109
|
+
try {
|
|
110
|
+
u = new URL(s);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
}
|
|
114
|
+
if (!u || (u.protocol !== "https:" && u.protocol !== "http:"))
|
|
115
|
+
return { error: "Enter a web address." };
|
|
116
|
+
}
|
|
117
|
+
if (f.pattern && !f.pattern.test(s))
|
|
118
|
+
return { error: "Not in the expected format." };
|
|
119
|
+
return { value: s };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function field(input, name) {
|
|
124
|
+
if (input instanceof URLSearchParams || (typeof FormData !== "undefined" && input instanceof FormData)) {
|
|
125
|
+
const v = input.get(name);
|
|
126
|
+
return v === null ? undefined : typeof v === "string" ? v : undefined;
|
|
127
|
+
}
|
|
128
|
+
if (input && typeof input === "object" && Object.hasOwn(input, name))
|
|
129
|
+
return input[name];
|
|
130
|
+
return undefined;
|
|
131
|
+
}
|
|
132
|
+
export function defineWizard(o) {
|
|
133
|
+
if (!NAME.test(o.name))
|
|
134
|
+
throw new Error("defineWizard: name is 1-64 of A-Z a-z 0-9 . _ -");
|
|
135
|
+
if (!Array.isArray(o.steps) || o.steps.length === 0)
|
|
136
|
+
throw new Error("defineWizard: at least one step");
|
|
137
|
+
if (typeof o.complete !== "function")
|
|
138
|
+
throw new Error("defineWizard: complete is a function");
|
|
139
|
+
const ttlDays = o.ttlDays ?? 30;
|
|
140
|
+
if (!Number.isFinite(ttlDays) || ttlDays <= 0)
|
|
141
|
+
throw new Error("defineWizard: ttlDays is more than 0");
|
|
142
|
+
const now = o.now ?? Date.now;
|
|
143
|
+
const steps = o.steps.map((s) => ({ ...s, fields: { ...s.fields } }));
|
|
144
|
+
const ids = new Set();
|
|
145
|
+
const owners = new Map();
|
|
146
|
+
for (const s of steps) {
|
|
147
|
+
if (!NAME.test(s.id))
|
|
148
|
+
throw new Error(`defineWizard: bad step id ${String(s.id)}`);
|
|
149
|
+
if (ids.has(s.id))
|
|
150
|
+
throw new Error(`defineWizard: step ${s.id} twice`);
|
|
151
|
+
ids.add(s.id);
|
|
152
|
+
for (const [name, f] of Object.entries(s.fields)) {
|
|
153
|
+
checkField(s.id, name, f);
|
|
154
|
+
const other = owners.get(name);
|
|
155
|
+
if (other)
|
|
156
|
+
throw new Error(`defineWizard: field ${name} is in steps ${other} and ${s.id}`);
|
|
157
|
+
owners.set(name, s.id);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const ownerOf = (ctx) => {
|
|
161
|
+
const user = ctx.user;
|
|
162
|
+
if (user && (typeof user.id === "string" || typeof user.id === "number"))
|
|
163
|
+
return `user:${user.id}`;
|
|
164
|
+
return o.anonymous && typeof ctx.session === "string" && ctx.session !== "" ? `session:${ctx.session}` : null;
|
|
165
|
+
};
|
|
166
|
+
const fresh = () => ({ step: steps[0].id, values: {}, done: [], updated: 0 });
|
|
167
|
+
const load = async (owner) => {
|
|
168
|
+
const d = await o.store.get(o.name, owner);
|
|
169
|
+
if (!d || now() - d.updated > ttlDays * DAY)
|
|
170
|
+
return fresh();
|
|
171
|
+
const values = {};
|
|
172
|
+
for (const [k, v] of Object.entries(d.values ?? {})) {
|
|
173
|
+
if (owners.has(k) && (typeof v === "string" || typeof v === "number" || typeof v === "boolean"))
|
|
174
|
+
values[k] = v;
|
|
175
|
+
}
|
|
176
|
+
return { step: ids.has(d.step) ? d.step : steps[0].id, values, done: (d.done ?? []).filter((s) => ids.has(s)), updated: d.updated };
|
|
177
|
+
};
|
|
178
|
+
const applying = (all) => steps.filter((s) => !s.when || s.when(all));
|
|
179
|
+
const reachable = (d, list, step) => {
|
|
180
|
+
for (const s of list) {
|
|
181
|
+
if (s.id === step)
|
|
182
|
+
return true;
|
|
183
|
+
if (!d.done.includes(s.id))
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
return false;
|
|
187
|
+
};
|
|
188
|
+
const errorsOf = async (ctx, s, input, all) => {
|
|
189
|
+
const values = {};
|
|
190
|
+
const errors = {};
|
|
191
|
+
for (const [name, f] of Object.entries(s.fields)) {
|
|
192
|
+
const r = parse(f, field(input, name));
|
|
193
|
+
if (r.error)
|
|
194
|
+
errors[name] = r.error;
|
|
195
|
+
else if (r.value !== undefined)
|
|
196
|
+
values[name] = r.value;
|
|
197
|
+
}
|
|
198
|
+
if (Object.keys(errors).length === 0 && s.check) {
|
|
199
|
+
const more = await s.check(values, { ...all, ...values }, ctx);
|
|
200
|
+
for (const [k, v] of Object.entries(more ?? {})) {
|
|
201
|
+
if (typeof v === "string" && v !== "")
|
|
202
|
+
errors[Object.hasOwn(s.fields, k) ? k : ""] = v;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return { values, errors };
|
|
206
|
+
};
|
|
207
|
+
const withStep = (all, s, values) => {
|
|
208
|
+
const next = {};
|
|
209
|
+
for (const [k, v] of Object.entries(all))
|
|
210
|
+
if (!Object.hasOwn(s.fields, k))
|
|
211
|
+
next[k] = v;
|
|
212
|
+
return Object.assign(next, values);
|
|
213
|
+
};
|
|
214
|
+
return {
|
|
215
|
+
name: o.name,
|
|
216
|
+
async view(ctx) {
|
|
217
|
+
const owner = ownerOf(ctx);
|
|
218
|
+
if (!owner)
|
|
219
|
+
return null;
|
|
220
|
+
const d = await load(owner);
|
|
221
|
+
const list = applying(d.values);
|
|
222
|
+
const asked = ctx.url?.searchParams.get("step");
|
|
223
|
+
let current = list.find((s) => s.id === (asked && reachable(d, list, asked) ? asked : d.step));
|
|
224
|
+
if (!current || !reachable(d, list, current.id))
|
|
225
|
+
current = list.find((s) => !d.done.includes(s.id)) ?? list.at(-1);
|
|
226
|
+
const index = list.indexOf(current);
|
|
227
|
+
return {
|
|
228
|
+
step: current.id,
|
|
229
|
+
label: current.label ?? current.id,
|
|
230
|
+
index,
|
|
231
|
+
total: list.length,
|
|
232
|
+
steps: list.map((s) => ({
|
|
233
|
+
id: s.id,
|
|
234
|
+
label: s.label ?? s.id,
|
|
235
|
+
done: d.done.includes(s.id),
|
|
236
|
+
current: s === current,
|
|
237
|
+
reachable: reachable(d, list, s.id),
|
|
238
|
+
})),
|
|
239
|
+
fields: Object.entries(current.fields).map(([name, f]) => ({
|
|
240
|
+
name,
|
|
241
|
+
label: f.label ?? name,
|
|
242
|
+
description: f.description ?? null,
|
|
243
|
+
type: f.type,
|
|
244
|
+
required: f.required === true,
|
|
245
|
+
value: Object.hasOwn(d.values, name) ? d.values[name] : null,
|
|
246
|
+
options: f.type === "choice" ? f.options : null,
|
|
247
|
+
min: f.type === "number" || f.type === "date" ? (f.min ?? null) : null,
|
|
248
|
+
max: f.type === "number" || f.type === "date" ? (f.max ?? null) : null,
|
|
249
|
+
maxLength: "maxLength" in f ? (f.maxLength ?? null) : null,
|
|
250
|
+
})),
|
|
251
|
+
back: index > 0 ? list[index - 1].id : null,
|
|
252
|
+
last: index === list.length - 1,
|
|
253
|
+
saved: d.updated || null,
|
|
254
|
+
};
|
|
255
|
+
},
|
|
256
|
+
async save(ctx, step, input, opts = {}) {
|
|
257
|
+
const owner = ownerOf(ctx);
|
|
258
|
+
if (!owner)
|
|
259
|
+
return { ok: false, reason: "not-found" };
|
|
260
|
+
const go = opts.go ?? "next";
|
|
261
|
+
const d = await load(owner);
|
|
262
|
+
let list = applying(d.values);
|
|
263
|
+
const s = list.find((x) => x.id === step);
|
|
264
|
+
if (!s || !reachable(d, list, step))
|
|
265
|
+
return { ok: false, reason: "unreachable" };
|
|
266
|
+
if (go === "back") {
|
|
267
|
+
const kept = {};
|
|
268
|
+
for (const [name, f] of Object.entries(s.fields)) {
|
|
269
|
+
const r = parse({ ...f, required: false }, field(input, name));
|
|
270
|
+
if (!r.error && r.value !== undefined)
|
|
271
|
+
kept[name] = r.value;
|
|
272
|
+
}
|
|
273
|
+
const values = withStep(d.values, s, { ...Object.fromEntries(Object.entries(d.values).filter(([k]) => Object.hasOwn(s.fields, k))), ...kept });
|
|
274
|
+
list = applying(values);
|
|
275
|
+
const at = list.indexOf(list.find((x) => x.id === step) ?? list[0]);
|
|
276
|
+
const prev = list[Math.max(0, at - 1)].id;
|
|
277
|
+
await o.store.put(o.name, owner, { step: prev, values, done: d.done, updated: now() });
|
|
278
|
+
return { ok: true, step: prev };
|
|
279
|
+
}
|
|
280
|
+
const { values, errors } = await errorsOf(ctx, s, input, d.values);
|
|
281
|
+
if (Object.keys(errors).length)
|
|
282
|
+
return { ok: false, reason: "invalid", errors };
|
|
283
|
+
const all = withStep(d.values, s, values);
|
|
284
|
+
list = applying(all);
|
|
285
|
+
const done = [...new Set([...d.done, step])];
|
|
286
|
+
const at = list.findIndex((x) => x.id === step);
|
|
287
|
+
const next = go === "stay" ? step : (list.slice(at + 1).find((x) => !done.includes(x.id)) ?? list.find((x) => !done.includes(x.id)))?.id ?? null;
|
|
288
|
+
await o.store.put(o.name, owner, { step: next ?? step, values: all, done, updated: now() });
|
|
289
|
+
return { ok: true, step: go === "stay" ? step : next };
|
|
290
|
+
},
|
|
291
|
+
async finish(ctx) {
|
|
292
|
+
const owner = ownerOf(ctx);
|
|
293
|
+
if (!owner)
|
|
294
|
+
return { ok: false, reason: "not-found" };
|
|
295
|
+
const d = await load(owner);
|
|
296
|
+
if (!d.updated)
|
|
297
|
+
return { ok: false, reason: "incomplete" };
|
|
298
|
+
const list = applying(d.values);
|
|
299
|
+
const values = {};
|
|
300
|
+
for (const s of list) {
|
|
301
|
+
if (!d.done.includes(s.id))
|
|
302
|
+
return { ok: false, reason: "incomplete" };
|
|
303
|
+
const { values: v, errors } = await errorsOf(ctx, s, d.values, d.values);
|
|
304
|
+
if (Object.keys(errors).length)
|
|
305
|
+
return { ok: false, reason: "invalid", step: s.id, errors };
|
|
306
|
+
Object.assign(values, v);
|
|
307
|
+
}
|
|
308
|
+
const claimed = await o.store.take(o.name, owner);
|
|
309
|
+
if (!claimed || claimed.updated !== d.updated) {
|
|
310
|
+
if (claimed)
|
|
311
|
+
await o.store.put(o.name, owner, claimed);
|
|
312
|
+
return { ok: false, reason: "incomplete" };
|
|
313
|
+
}
|
|
314
|
+
try {
|
|
315
|
+
return { ok: true, result: await o.complete(ctx, values) };
|
|
316
|
+
}
|
|
317
|
+
catch (err) {
|
|
318
|
+
await o.store.put(o.name, owner, claimed);
|
|
319
|
+
throw err;
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
async discard(ctx) {
|
|
323
|
+
const owner = ownerOf(ctx);
|
|
324
|
+
if (owner)
|
|
325
|
+
await o.store.take(o.name, owner);
|
|
326
|
+
},
|
|
327
|
+
async values(ctx) {
|
|
328
|
+
const owner = ownerOf(ctx);
|
|
329
|
+
if (!owner)
|
|
330
|
+
return null;
|
|
331
|
+
const d = await load(owner);
|
|
332
|
+
const out = {};
|
|
333
|
+
for (const s of applying(d.values)) {
|
|
334
|
+
for (const k of Object.keys(s.fields))
|
|
335
|
+
if (Object.hasOwn(d.values, k))
|
|
336
|
+
out[k] = d.values[k];
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
},
|
|
340
|
+
async sweep() {
|
|
341
|
+
return await o.store.sweep(now() - ttlDays * DAY);
|
|
342
|
+
},
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
export class MemoryDraftStore {
|
|
346
|
+
drafts = new Map();
|
|
347
|
+
get(wizard, owner) {
|
|
348
|
+
const d = this.drafts.get(`${wizard}\n${owner}`);
|
|
349
|
+
return d ? structuredClone(d) : null;
|
|
350
|
+
}
|
|
351
|
+
put(wizard, owner, draft) {
|
|
352
|
+
this.drafts.set(`${wizard}\n${owner}`, structuredClone(draft));
|
|
353
|
+
}
|
|
354
|
+
take(wizard, owner) {
|
|
355
|
+
const key = `${wizard}\n${owner}`;
|
|
356
|
+
const d = this.drafts.get(key) ?? null;
|
|
357
|
+
this.drafts.delete(key);
|
|
358
|
+
return d;
|
|
359
|
+
}
|
|
360
|
+
sweep(before) {
|
|
361
|
+
let n = 0;
|
|
362
|
+
for (const [k, d] of this.drafts) {
|
|
363
|
+
if (d.updated < before) {
|
|
364
|
+
this.drafts.delete(k);
|
|
365
|
+
n++;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return n;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
export class SqlDraftStore {
|
|
372
|
+
db;
|
|
373
|
+
table;
|
|
374
|
+
constructor(db, table = "weft_drafts") {
|
|
375
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
|
|
376
|
+
throw new Error(`SqlDraftStore: bad table name ${table}`);
|
|
377
|
+
this.db = db;
|
|
378
|
+
this.table = table;
|
|
379
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${table} (wizard TEXT NOT NULL, owner TEXT NOT NULL, data TEXT NOT NULL, ` +
|
|
380
|
+
`updated INTEGER NOT NULL, PRIMARY KEY (wizard, owner))`);
|
|
381
|
+
db.exec(`CREATE INDEX IF NOT EXISTS ${table}_updated ON ${table} (updated)`);
|
|
382
|
+
}
|
|
383
|
+
decode(r) {
|
|
384
|
+
if (!r || typeof r !== "object")
|
|
385
|
+
return null;
|
|
386
|
+
try {
|
|
387
|
+
const d = JSON.parse(String(r.data));
|
|
388
|
+
return { step: String(d.step), values: d.values ?? {}, done: Array.isArray(d.done) ? d.done.map(String) : [], updated: Number(r.updated) };
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
get(wizard, owner) {
|
|
395
|
+
return this.decode(this.db.prepare(`SELECT data, updated FROM ${this.table} WHERE wizard = ? AND owner = ?`).all(wizard, owner)[0]);
|
|
396
|
+
}
|
|
397
|
+
put(wizard, owner, draft) {
|
|
398
|
+
const data = JSON.stringify({ step: draft.step, values: draft.values, done: draft.done });
|
|
399
|
+
this.db
|
|
400
|
+
.prepare(`INSERT INTO ${this.table} (wizard, owner, data, updated) VALUES (?, ?, ?, ?) ` +
|
|
401
|
+
`ON CONFLICT (wizard, owner) DO UPDATE SET data = excluded.data, updated = excluded.updated`)
|
|
402
|
+
.run(wizard, owner, data, draft.updated);
|
|
403
|
+
}
|
|
404
|
+
take(wizard, owner) {
|
|
405
|
+
return this.decode(this.db.prepare(`DELETE FROM ${this.table} WHERE wizard = ? AND owner = ? RETURNING data, updated`).all(wizard, owner)[0]);
|
|
406
|
+
}
|
|
407
|
+
sweep(before) {
|
|
408
|
+
return Number(this.db.prepare(`DELETE FROM ${this.table} WHERE updated < ?`).run(before).changes ?? 0);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { type ParamSpec } from "./action.js";
|
|
2
|
+
import type { PageContext } from "./context.js";
|
|
3
|
+
import { type Job, type JobActor, type Jobs } from "./jobs.js";
|
|
4
|
+
import type { SqlDatabase } from "@weft-framework/data";
|
|
5
|
+
type Maybe<T> = T | Promise<T>;
|
|
6
|
+
export type WorkflowStatus = "running" | "done" | "failed" | "cancelled";
|
|
7
|
+
export interface WorkflowRun {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
args: unknown[];
|
|
11
|
+
actor: JobActor | null;
|
|
12
|
+
status: WorkflowStatus;
|
|
13
|
+
history: Record<string, unknown>;
|
|
14
|
+
waiting: {
|
|
15
|
+
event: string;
|
|
16
|
+
key: string;
|
|
17
|
+
} | null;
|
|
18
|
+
wakeAt: number | null;
|
|
19
|
+
result: unknown;
|
|
20
|
+
error: string | null;
|
|
21
|
+
key: string | null;
|
|
22
|
+
created: number;
|
|
23
|
+
updated: number;
|
|
24
|
+
holder: string | null;
|
|
25
|
+
holdUntil: number;
|
|
26
|
+
}
|
|
27
|
+
export interface WorkflowSignal {
|
|
28
|
+
id: string;
|
|
29
|
+
event: string;
|
|
30
|
+
key: string;
|
|
31
|
+
payload: unknown;
|
|
32
|
+
at: number;
|
|
33
|
+
}
|
|
34
|
+
export interface WorkflowFilter {
|
|
35
|
+
status?: WorkflowStatus;
|
|
36
|
+
name?: string;
|
|
37
|
+
limit?: number;
|
|
38
|
+
}
|
|
39
|
+
type Patch = Partial<Pick<WorkflowRun, "history" | "waiting" | "wakeAt" | "status" | "result" | "error">>;
|
|
40
|
+
export interface WorkflowStore {
|
|
41
|
+
create(run: WorkflowRun): Maybe<boolean>;
|
|
42
|
+
get(id: string): Maybe<WorkflowRun | null | undefined>;
|
|
43
|
+
acquire(id: string, holder: string, until: number, now: number): Maybe<WorkflowRun | null | undefined>;
|
|
44
|
+
save(id: string, holder: string, patch: Patch, now: number): Maybe<boolean>;
|
|
45
|
+
release(id: string, holder: string): Maybe<void>;
|
|
46
|
+
waitingFor(event: string, key: string): Maybe<string[]>;
|
|
47
|
+
addSignal(s: WorkflowSignal): Maybe<void>;
|
|
48
|
+
signals(event: string, key: string, since: number, limit: number): Maybe<WorkflowSignal[]>;
|
|
49
|
+
cancel(id: string, now: number): Maybe<boolean>;
|
|
50
|
+
list(f: WorkflowFilter): Maybe<WorkflowRun[]>;
|
|
51
|
+
sweep(before: number): Maybe<void>;
|
|
52
|
+
}
|
|
53
|
+
export declare class MemoryWorkflowStore implements WorkflowStore {
|
|
54
|
+
#private;
|
|
55
|
+
create(run: WorkflowRun): boolean;
|
|
56
|
+
get(id: string): WorkflowRun | null;
|
|
57
|
+
acquire(id: string, holder: string, until: number, now: number): WorkflowRun | null;
|
|
58
|
+
save(id: string, holder: string, patch: Patch, now: number): boolean;
|
|
59
|
+
release(id: string, holder: string): void;
|
|
60
|
+
waitingFor(event: string, key: string): string[];
|
|
61
|
+
addSignal(s: WorkflowSignal): void;
|
|
62
|
+
signals(event: string, key: string, since: number, limit: number): WorkflowSignal[];
|
|
63
|
+
cancel(id: string, now: number): boolean;
|
|
64
|
+
list(f: WorkflowFilter): WorkflowRun[];
|
|
65
|
+
sweep(before: number): void;
|
|
66
|
+
}
|
|
67
|
+
export declare class SqlWorkflowStore implements WorkflowStore {
|
|
68
|
+
#private;
|
|
69
|
+
constructor(db: SqlDatabase, table?: string);
|
|
70
|
+
create(run: WorkflowRun): boolean;
|
|
71
|
+
get(id: string): WorkflowRun | null;
|
|
72
|
+
acquire(id: string, holder: string, until: number, now: number): WorkflowRun | null;
|
|
73
|
+
save(id: string, holder: string, patch: Patch, now: number): boolean;
|
|
74
|
+
release(id: string, holder: string): void;
|
|
75
|
+
waitingFor(event: string, key: string): string[];
|
|
76
|
+
addSignal(s: WorkflowSignal): void;
|
|
77
|
+
signals(event: string, key: string, since: number, limit: number): WorkflowSignal[];
|
|
78
|
+
cancel(id: string, now: number): boolean;
|
|
79
|
+
list(f: WorkflowFilter): WorkflowRun[];
|
|
80
|
+
sweep(before: number): void;
|
|
81
|
+
}
|
|
82
|
+
export interface WorkflowContext {
|
|
83
|
+
user: unknown;
|
|
84
|
+
run: {
|
|
85
|
+
id: string;
|
|
86
|
+
name: string;
|
|
87
|
+
};
|
|
88
|
+
step<R>(name: string, fn: () => R | Promise<R>): Promise<R>;
|
|
89
|
+
sleep(name: string, ms: number): Promise<void>;
|
|
90
|
+
sleepUntil(name: string, at: number): Promise<void>;
|
|
91
|
+
waitFor<P = unknown>(name: string, event: string, o: {
|
|
92
|
+
key: string;
|
|
93
|
+
timeoutMs?: number;
|
|
94
|
+
}): Promise<{
|
|
95
|
+
payload: P;
|
|
96
|
+
at: number;
|
|
97
|
+
} | null>;
|
|
98
|
+
}
|
|
99
|
+
declare const WORKFLOW: unique symbol;
|
|
100
|
+
export interface Workflow<A extends unknown[] = never[]> {
|
|
101
|
+
readonly [WORKFLOW]: true;
|
|
102
|
+
readonly name: string;
|
|
103
|
+
readonly params: readonly ParamSpec[];
|
|
104
|
+
run(wf: WorkflowContext, ...args: A): unknown;
|
|
105
|
+
}
|
|
106
|
+
export declare function defineWorkflow<A extends unknown[]>(name: string, params: readonly ParamSpec[], run: (wf: WorkflowContext, ...args: A) => unknown): Workflow<A>;
|
|
107
|
+
export declare function isWorkflow(v: unknown): v is Workflow<unknown[]>;
|
|
108
|
+
export interface WorkflowsOptions {
|
|
109
|
+
workflows: readonly Workflow<never[]>[] | readonly Workflow<unknown[]>[];
|
|
110
|
+
store?: WorkflowStore;
|
|
111
|
+
attempts?: number;
|
|
112
|
+
timeoutMs?: number;
|
|
113
|
+
keepMs?: number;
|
|
114
|
+
jobName?: string;
|
|
115
|
+
onError?(err: unknown, run: WorkflowRun | null): void;
|
|
116
|
+
now?(): number;
|
|
117
|
+
}
|
|
118
|
+
export interface StartOptions {
|
|
119
|
+
key?: string;
|
|
120
|
+
as?: JobActor | null;
|
|
121
|
+
}
|
|
122
|
+
export declare class Workflows {
|
|
123
|
+
#private;
|
|
124
|
+
readonly job: Job<[string]>;
|
|
125
|
+
constructor(o: WorkflowsOptions);
|
|
126
|
+
use(jobs: Jobs): this;
|
|
127
|
+
start<A extends unknown[]>(ctx: PageContext | null, workflow: Workflow<A>, args?: Record<string, unknown>, o?: StartOptions): Promise<string | false>;
|
|
128
|
+
signal(event: string, key: string, payload?: unknown): Promise<number>;
|
|
129
|
+
get(id: string): Promise<WorkflowRun | null>;
|
|
130
|
+
list(f?: WorkflowFilter): Promise<WorkflowRun[]>;
|
|
131
|
+
cancel(id: string): Promise<boolean>;
|
|
132
|
+
}
|
|
133
|
+
export declare function createWorkflows(o: WorkflowsOptions): Workflows;
|
|
134
|
+
export {};
|