@weft-framework/server 0.0.0-stage → 0.0.3

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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
package/dist/replay.js ADDED
@@ -0,0 +1,259 @@
1
+ import { realpathSync, writeFileSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ export class ReplayError extends Error {
7
+ }
8
+ export const RECORDING_MAX = 500;
9
+ const VALUE_MAX = 256;
10
+ const SECRET_NAME = /pass|secret|token|code|key|sig|otp|csrf|auth|session/i;
11
+ const blank = (v) => "x".repeat(Math.min(v.length, VALUE_MAX));
12
+ export function redactPayload(ev) {
13
+ const out = { type: ev.type };
14
+ if (ev.value !== undefined)
15
+ out.value = blank(ev.value);
16
+ if (ev.checked !== undefined)
17
+ out.checked = ev.checked;
18
+ if (ev.key !== undefined)
19
+ out.key = ev.key.length > 1 && /^[A-Z][A-Za-z0-9]*$/.test(ev.key) ? ev.key : "x";
20
+ if (ev.form !== undefined) {
21
+ out.form = {};
22
+ for (const [name, value] of Object.entries(ev.form))
23
+ out.form[name] = blank(value);
24
+ }
25
+ return out;
26
+ }
27
+ export function redactPath(url) {
28
+ const q = new URLSearchParams();
29
+ for (const [k, v] of url.searchParams)
30
+ q.append(k, SECRET_NAME.test(k) ? "redacted" : v);
31
+ const s = q.toString();
32
+ return url.pathname + (s ? "?" + s : "");
33
+ }
34
+ export function outcomeOf(msgs) {
35
+ const out = [];
36
+ for (const m of msgs) {
37
+ if (m.t === "patch")
38
+ out.push(`patch ${m.id}`);
39
+ else if (m.t === "redirect")
40
+ out.push(`redirect ${m.to}`);
41
+ else if (m.t === "error")
42
+ out.push("error");
43
+ else if (m.t === "conflict")
44
+ out.push("conflict");
45
+ else if (m.t === "ack")
46
+ out.push("ack");
47
+ }
48
+ return [...new Set(out)];
49
+ }
50
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
51
+ const isStr = (v, max) => typeof v === "string" && v.length <= max;
52
+ export function parseRecording(text) {
53
+ let v;
54
+ try {
55
+ v = JSON.parse(text);
56
+ }
57
+ catch {
58
+ throw new ReplayError("not a recording: the file is not JSON");
59
+ }
60
+ if (!isObj(v) || v.weft !== "recording" || v.v !== 1)
61
+ throw new ReplayError("not a recording (weft: \"recording\", v: 1)");
62
+ if (!isStr(v.path, 4096) || !v.path.startsWith("/") || v.path.startsWith("//"))
63
+ throw new ReplayError("recording: path must be a same-site path");
64
+ if (!isStr(v.actor, 256) || typeof v.at !== "number")
65
+ throw new ReplayError("recording: actor and at are required");
66
+ if (!Array.isArray(v.steps) || v.steps.length > RECORDING_MAX)
67
+ throw new ReplayError(`recording: at most ${RECORDING_MAX} steps`);
68
+ const steps = [];
69
+ for (const [i, s] of v.steps.entries()) {
70
+ const bad = () => new ReplayError(`recording: step ${i + 1} is malformed`);
71
+ if (!isObj(s) || typeof s.at !== "number" || !isStr(s.id, 128) || !isStr(s.handler, 128) || !isObj(s.event))
72
+ throw bad();
73
+ if (!isStr(s.event.type, 64) || (s.args !== undefined && !isStr(s.args, 8192)))
74
+ throw bad();
75
+ if (!Array.isArray(s.outcome) || !s.outcome.every((o) => isStr(o, 4096)))
76
+ throw bad();
77
+ const ev = s.event;
78
+ const event = { type: ev.type };
79
+ if (ev.value !== undefined)
80
+ event.value = isStr(ev.value, VALUE_MAX) ? ev.value : (() => { throw bad(); })();
81
+ if (ev.checked !== undefined)
82
+ event.checked = typeof ev.checked === "boolean" ? ev.checked : (() => { throw bad(); })();
83
+ if (ev.key !== undefined)
84
+ event.key = isStr(ev.key, 32) ? ev.key : (() => { throw bad(); })();
85
+ if (ev.form !== undefined) {
86
+ if (!isObj(ev.form) || !Object.values(ev.form).every((x) => isStr(x, VALUE_MAX)))
87
+ throw bad();
88
+ event.form = { ...ev.form };
89
+ }
90
+ steps.push({ at: s.at, id: s.id, handler: s.handler, event, ...(s.args !== undefined ? { args: s.args } : {}), outcome: s.outcome });
91
+ }
92
+ return { weft: "recording", v: 1, path: v.path, actor: v.actor, at: v.at, steps };
93
+ }
94
+ export async function replay(rec, opts) {
95
+ const f = opts.fetch ?? fetch;
96
+ const origin = new URL(opts.url).origin;
97
+ const wait = opts.timeoutMs ?? 5000;
98
+ let cookie = opts.cookie ?? "";
99
+ const page = await f(origin + rec.path, { headers: cookie ? { cookie } : {}, redirect: "manual" });
100
+ if (page.status !== 200)
101
+ throw new ReplayError(`GET ${rec.path} answered ${page.status}`);
102
+ const html = await page.text();
103
+ const set = page.headers.get("set-cookie");
104
+ if (set && !cookie)
105
+ cookie = set.split(";")[0];
106
+ const lid = /name="weft-live" content="([^"]+)"/.exec(html)?.[1];
107
+ const csrf = /name="weft-csrf" content="([^"]+)"/.exec(html)?.[1] ?? "";
108
+ if (!lid)
109
+ throw new ReplayError(`${rec.path} is not a live page here: nothing to replay`);
110
+ const ac = new AbortController();
111
+ const sse = await f(`${origin}/_weft/live/sse?lid=${encodeURIComponent(lid)}`, { headers: { cookie }, signal: ac.signal });
112
+ if (sse.status !== 200 || !sse.body)
113
+ throw new ReplayError(`the live stream answered ${sse.status}`);
114
+ const reader = sse.body.getReader();
115
+ const dec = new TextDecoder();
116
+ let buf = "";
117
+ let pending = null;
118
+ const next = async (ms) => {
119
+ const end = Date.now() + ms;
120
+ for (;;) {
121
+ const m = /data: (.*)\n\n/.exec(buf);
122
+ if (m) {
123
+ buf = buf.slice(m.index + m[0].length);
124
+ return JSON.parse(m[1]);
125
+ }
126
+ pending ??= reader.read();
127
+ const got = await Promise.race([pending, new Promise((r) => setTimeout(() => r(null), Math.max(0, end - Date.now())))]);
128
+ if (got === null)
129
+ return null;
130
+ pending = null;
131
+ if (got.done)
132
+ return null;
133
+ buf += dec.decode(got.value, { stream: true });
134
+ }
135
+ };
136
+ try {
137
+ const hello = await next(wait);
138
+ if (!hello || hello.t !== "hello")
139
+ throw new ReplayError("the live stream sent no hello");
140
+ const headers = {
141
+ cookie,
142
+ origin,
143
+ "content-type": "application/json",
144
+ "x-weft-csrf": csrf,
145
+ "x-weft-session": hello.session,
146
+ };
147
+ const steps = [];
148
+ for (const [i, s] of rec.steps.entries()) {
149
+ const seq = i + 1;
150
+ const body = { t: "event", id: s.id, handler: s.handler, event: s.event, seq, ...(s.args ? { args: s.args } : {}) };
151
+ const res = await f(`${origin}/_weft/live/event`, { method: "POST", headers, body: JSON.stringify(body) });
152
+ const answer = [];
153
+ if (res.status !== 204) {
154
+ answer.push({ t: "error", message: `HTTP ${res.status}` });
155
+ }
156
+ else {
157
+ let deadline = wait;
158
+ for (;;) {
159
+ const m = await next(deadline);
160
+ if (!m)
161
+ break;
162
+ if (m.t === "expired") {
163
+ answer.push({ t: "error", message: "expired" });
164
+ break;
165
+ }
166
+ if (m.t === "redirect" || ("ack" in m && m.ack === seq)) {
167
+ answer.push(m);
168
+ deadline = 50;
169
+ }
170
+ }
171
+ }
172
+ const got = outcomeOf(answer);
173
+ const same = got.length === s.outcome.length && got.every((o, k) => o === s.outcome[k]);
174
+ const step = { n: seq, what: `${s.event.type} -> ${s.handler} on ${s.id}`, expected: s.outcome, got, same };
175
+ steps.push(step);
176
+ opts.onStep?.(step);
177
+ if (answer.some((m) => m.t === "redirect"))
178
+ break;
179
+ }
180
+ return { steps, ok: steps.length === rec.steps.length && steps.every((s) => s.same) };
181
+ }
182
+ finally {
183
+ ac.abort();
184
+ await reader.cancel().catch(() => { });
185
+ }
186
+ }
187
+ export function recordingTest(rec, name, url) {
188
+ const json = JSON.stringify(rec, null, 2).replace(/<\/script/gi, "<\\/script");
189
+ return `// Made by \`weft replay --test\` from a recording of ${rec.path} (as ${rec.actor}).
190
+ // It replays the recorded events on a running server (\`weft dev\`, or
191
+ // WEFT_URL) and checks each is answered as it was when recorded.
192
+
193
+ import { test } from "node:test";
194
+ import assert from "node:assert/strict";
195
+ import { parseRecording, replay } from "@weft-framework/server/replay";
196
+
197
+ const recording = parseRecording(JSON.stringify(${json}));
198
+
199
+ test(${JSON.stringify(name)}, async () => {
200
+ const result = await replay(recording, { url: process.env.WEFT_URL ?? ${JSON.stringify(url)}, cookie: process.env.WEFT_REPLAY_COOKIE });
201
+ for (const s of result.steps) assert.deepEqual(s.got, s.expected, \`step \${s.n}: \${s.what}\`);
202
+ assert.equal(result.steps.length, recording.steps.length, "every step ran");
203
+ });
204
+ `;
205
+ }
206
+ async function main() {
207
+ const { values, positionals } = parseArgs({
208
+ allowPositionals: true,
209
+ options: { url: { type: "string" }, cookie: { type: "string" }, test: { type: "string" }, file: { type: "string" } },
210
+ });
211
+ const file = values.file ?? positionals[1] ?? positionals[0];
212
+ const url = values.url ?? process.env.WEFT_URL ?? "http://127.0.0.1:3000";
213
+ try {
214
+ if (!file)
215
+ throw new ReplayError("which recording? weft replay <file>");
216
+ const rec = parseRecording(await readFile(resolve(file), "utf8"));
217
+ if (values.test) {
218
+ const name = `replays ${rec.path} (${rec.steps.length} steps)`;
219
+ writeFileSync(resolve(values.test), recordingTest(rec, name, url), { flag: "wx" });
220
+ console.log(`[weft] wrote ${values.test}`);
221
+ return;
222
+ }
223
+ console.log(`[weft] replaying ${rec.steps.length} step(s) of ${rec.path}, recorded as ${rec.actor}, on ${url}`);
224
+ const cookie = values.cookie ?? process.env.WEFT_REPLAY_COOKIE;
225
+ const result = await replay(rec, {
226
+ url,
227
+ ...(cookie ? { cookie } : {}),
228
+ onStep: (s) => console.log(`${s.same ? " ok " : " DIFF"} ${s.n}. ${s.what}: ${s.got.join(", ") || "no answer"}` +
229
+ (s.same ? "" : ` (recorded: ${s.expected.join(", ") || "no answer"})`)),
230
+ });
231
+ if (!result.ok) {
232
+ console.error("[weft] the replay differs from the recording");
233
+ process.exit(1);
234
+ }
235
+ console.log("[weft] every step answered as recorded");
236
+ }
237
+ catch (err) {
238
+ if (err instanceof ReplayError)
239
+ console.error(`[weft] ${err.message}`);
240
+ else if (err && typeof err === "object" && err.code === "EEXIST")
241
+ console.error(`[weft] ${values.test} exists; choose another --test`);
242
+ else if (err && typeof err === "object" && err.cause?.code === "ECONNREFUSED")
243
+ console.error(`[weft] nothing answers on ${url}: start \`weft dev\` first`);
244
+ else
245
+ console.error("[weft] replay:", err instanceof Error ? (err.stack ?? err.message) : err);
246
+ process.exit(1);
247
+ }
248
+ }
249
+ function isEntry() {
250
+ try {
251
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
252
+ }
253
+ catch {
254
+ return false;
255
+ }
256
+ }
257
+ if (isEntry()) {
258
+ void main();
259
+ }
@@ -0,0 +1,29 @@
1
+ export type Params = Record<string, string | string[]>;
2
+ type Segment = {
3
+ kind: "static";
4
+ value: string;
5
+ } | {
6
+ kind: "param";
7
+ name: string;
8
+ } | {
9
+ kind: "rest";
10
+ name: string;
11
+ optional: boolean;
12
+ };
13
+ export interface CompiledRoute<T> {
14
+ pattern: string;
15
+ value: T;
16
+ segments: Segment[];
17
+ }
18
+ export declare function parsePattern(pattern: string): Segment[];
19
+ export declare class Router<T> {
20
+ readonly routes: CompiledRoute<T>[];
21
+ constructor(table: Record<string, T> | [string, T][]);
22
+ match(path: string): {
23
+ route: CompiledRoute<T>;
24
+ params: Params;
25
+ } | null;
26
+ }
27
+ export declare function splitPath(path: string): string[] | null;
28
+ export declare function patternForFile(rel: string): string;
29
+ export {};
package/dist/router.js ADDED
@@ -0,0 +1,146 @@
1
+ const PARAM = /^\[([A-Za-z_$][\w$]*)\]$/;
2
+ const REST = /^\[\.\.\.([A-Za-z_$][\w$]*)\]$/;
3
+ const OPT_REST = /^\[\[\.\.\.([A-Za-z_$][\w$]*)\]\]$/;
4
+ export function parsePattern(pattern) {
5
+ if (!pattern.startsWith("/")) {
6
+ throw new Error(`route pattern must start with "/": ${pattern}`);
7
+ }
8
+ const parts = pattern === "/" ? [] : pattern.slice(1).replace(/\/$/, "").split("/");
9
+ const names = new Set();
10
+ const segments = parts.map((part, i) => {
11
+ let m;
12
+ let seg;
13
+ if ((m = OPT_REST.exec(part))) {
14
+ seg = { kind: "rest", name: m[1], optional: true };
15
+ }
16
+ else if ((m = REST.exec(part))) {
17
+ seg = { kind: "rest", name: m[1], optional: false };
18
+ }
19
+ else if ((m = PARAM.exec(part))) {
20
+ seg = { kind: "param", name: m[1] };
21
+ }
22
+ else if (part === "" || part.includes("[") || part.includes("]")) {
23
+ throw new Error(`invalid route segment "${part}" in ${pattern}`);
24
+ }
25
+ else {
26
+ return { kind: "static", value: part };
27
+ }
28
+ if (names.has(seg.name)) {
29
+ throw new Error(`duplicate route parameter "${seg.name}" in ${pattern}`);
30
+ }
31
+ names.add(seg.name);
32
+ if (seg.kind === "rest" && i !== parts.length - 1) {
33
+ throw new Error(`catch-all must be the last segment: ${pattern}`);
34
+ }
35
+ return seg;
36
+ });
37
+ return segments;
38
+ }
39
+ function rank(segments) {
40
+ return segments.map((s) => s.kind === "static" ? 0 : s.kind === "param" ? 1 : s.optional ? 3 : 2);
41
+ }
42
+ function compareRank(a, b) {
43
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
44
+ const x = a[i] ?? -1;
45
+ const y = b[i] ?? -1;
46
+ if (x !== y) {
47
+ return x - y;
48
+ }
49
+ }
50
+ return 0;
51
+ }
52
+ function shape(segments) {
53
+ return segments
54
+ .map((s) => (s.kind === "static" ? `s:${s.value}` : s.kind === "param" ? "p" : s.optional ? "o" : "r"))
55
+ .join("/");
56
+ }
57
+ export class Router {
58
+ routes;
59
+ constructor(table) {
60
+ const entries = Array.isArray(table) ? table : Object.entries(table);
61
+ const seen = new Map();
62
+ this.routes = entries.map(([pattern, value]) => {
63
+ const segments = parsePattern(pattern);
64
+ const key = shape(segments);
65
+ const other = seen.get(key);
66
+ if (other !== undefined) {
67
+ throw new Error(`route conflict: ${other} and ${pattern} match the same paths`);
68
+ }
69
+ seen.set(key, pattern);
70
+ return { pattern, value, segments };
71
+ });
72
+ this.routes.sort((a, b) => compareRank(rank(a.segments), rank(b.segments)));
73
+ }
74
+ match(path) {
75
+ const parts = splitPath(path);
76
+ if (!parts) {
77
+ return null;
78
+ }
79
+ for (const route of this.routes) {
80
+ const params = matchSegments(route.segments, parts);
81
+ if (params) {
82
+ return { route, params };
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+ }
88
+ export function splitPath(path) {
89
+ if (!path.startsWith("/")) {
90
+ return null;
91
+ }
92
+ const trimmed = path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
93
+ if (trimmed === "/") {
94
+ return [];
95
+ }
96
+ const out = [];
97
+ for (const raw of trimmed.slice(1).split("/")) {
98
+ let seg;
99
+ try {
100
+ seg = decodeURIComponent(raw);
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ if (seg === "" || seg === "." || seg === ".." || seg.includes("\0")) {
106
+ return null;
107
+ }
108
+ out.push(seg);
109
+ }
110
+ return out;
111
+ }
112
+ function matchSegments(segments, parts) {
113
+ const params = Object.create(null);
114
+ for (let i = 0; i < segments.length; i++) {
115
+ const seg = segments[i];
116
+ if (seg.kind === "rest") {
117
+ const rest = parts.slice(i);
118
+ if (rest.length === 0 && !seg.optional) {
119
+ return null;
120
+ }
121
+ params[seg.name] = rest;
122
+ return params;
123
+ }
124
+ const part = parts[i];
125
+ if (part === undefined) {
126
+ return null;
127
+ }
128
+ if (seg.kind === "static") {
129
+ if (seg.value !== part) {
130
+ return null;
131
+ }
132
+ }
133
+ else {
134
+ params[seg.name] = part;
135
+ }
136
+ }
137
+ return parts.length === segments.length ? params : null;
138
+ }
139
+ export function patternForFile(rel) {
140
+ const noExt = rel.replace(/\\/g, "/").replace(/\.(wx|ts)$/, "");
141
+ const parts = noExt.split("/");
142
+ if (parts[parts.length - 1] === "index") {
143
+ parts.pop();
144
+ }
145
+ return "/" + parts.join("/");
146
+ }
@@ -0,0 +1,18 @@
1
+ import { type RulesDiff } from "@weft-framework/data";
2
+ import { type Compiler } from "./compiler.js";
3
+ export declare class RulesDiffError extends Error {
4
+ }
5
+ export interface RulesDiffOptions {
6
+ compiler: Compiler;
7
+ runs?: number;
8
+ seed?: number;
9
+ }
10
+ export interface RulesDiffResult {
11
+ diffs: RulesDiff[];
12
+ widened: boolean;
13
+ text: string;
14
+ }
15
+ export declare function checkoutProject(root: string, ref: string, into: string): boolean;
16
+ export declare function widens(d: RulesDiff): boolean;
17
+ export declare function rulesDiffText(d: RulesDiff): string;
18
+ export declare function diffProjectRules(root: string, ref: string, opts: RulesDiffOptions): Promise<RulesDiffResult>;
@@ -0,0 +1,165 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
+ import { diffRules } from "@weft-framework/data";
8
+ import { CompileError, findCompiler } from "./compiler.js";
9
+ import { ConfigError } from "./config.js";
10
+ import { ProjectError, loadProject } from "./project.js";
11
+ export class RulesDiffError extends Error {
12
+ }
13
+ const EXPLAIN = Symbol.for("weft.access.explain");
14
+ const SKIP = /^(node_modules|\.weft|dist|data)(\/|$)/;
15
+ function git(cwd, args) {
16
+ try {
17
+ return execFileSync("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024 });
18
+ }
19
+ catch (err) {
20
+ const stderr = err.stderr?.toString().trim();
21
+ throw new RulesDiffError(`git ${args[0]}: ${stderr || err.message}`);
22
+ }
23
+ }
24
+ export function checkoutProject(root, ref, into) {
25
+ if (ref === "" || ref.startsWith("-") || /[\0\n]/.test(ref))
26
+ throw new RulesDiffError(`not a revision: ${JSON.stringify(ref)}`);
27
+ const commit = git(root, ["rev-parse", "--verify", "--end-of-options", `${ref}^{commit}`]).toString().trim();
28
+ const prefix = git(root, ["rev-parse", "--show-prefix"]).toString().trim();
29
+ const listed = git(root, ["ls-tree", "-r", "-z", "--full-name", "--name-only", commit, "--", "."]).toString().split("\0");
30
+ let wrote = 0;
31
+ for (const full of listed) {
32
+ if (full === "" || !full.startsWith(prefix))
33
+ continue;
34
+ const rel = full.slice(prefix.length);
35
+ if (SKIP.test(rel) || rel.split("/").some((p) => p === ".." || p === ""))
36
+ continue;
37
+ const blob = git(root, ["cat-file", "blob", `${commit}:${full}`]);
38
+ const to = join(into, ...rel.split("/"));
39
+ mkdirSync(dirname(to), { recursive: true });
40
+ writeFileSync(to, blob);
41
+ wrote++;
42
+ }
43
+ return wrote > 0;
44
+ }
45
+ const own = (models) => new Map(Object.values(models)
46
+ .filter((m) => typeof m[EXPLAIN] !== "function")
47
+ .map((m) => [m.name, m]));
48
+ const short = (v) => {
49
+ const s = JSON.stringify(v) ?? String(v);
50
+ return s.length > 200 ? s.slice(0, 199) + "…" : s;
51
+ };
52
+ export function widens(d) {
53
+ if (d.status === "added")
54
+ return (d.passed.after?.read ?? 0) + (d.passed.after?.write ?? 0) > 0;
55
+ return d.changes.some((c) => c.change === "widened") || (d.tenant !== undefined && d.tenant.after === null);
56
+ }
57
+ export function rulesDiffText(d) {
58
+ const pct = (n) => `${n} of ${d.checks} actor/row pairs`;
59
+ if (d.status === "added") {
60
+ return `Model ${d.model}: added; read admits ${pct(d.passed.after.read)}, write ${pct(d.passed.after.write)}`;
61
+ }
62
+ if (d.status === "removed")
63
+ return `Model ${d.model}: removed`;
64
+ const lines = [`Model ${d.model}: ${widens(d) ? "access WIDENED" : d.changes.length ? "access narrowed" : "changed"}`];
65
+ if (d.tenant)
66
+ lines.push(` tenant field: ${d.tenant.before ?? "none"} -> ${d.tenant.after ?? "none (rows no longer kept inside a tenant)"}`);
67
+ for (const c of d.changes) {
68
+ const what = c.change === "widened" ? "now admits" : "now refuses";
69
+ lines.push(` ${c.rule} ${c.change}: ${what} ${pct(c.pairs)}, for example`);
70
+ lines.push(` actor: ${short(c.actor)}`);
71
+ lines.push(` row: ${short(c.row)}`);
72
+ }
73
+ if (d.fields.added.length)
74
+ lines.push(` fields added: ${d.fields.added.join(", ")}`);
75
+ if (d.fields.removed.length)
76
+ lines.push(` fields removed: ${d.fields.removed.join(", ")}`);
77
+ return lines.join("\n");
78
+ }
79
+ export async function diffProjectRules(root, ref, opts) {
80
+ root = resolve(root);
81
+ const run = join(root, ".weft", "rules-diff", randomUUID());
82
+ try {
83
+ const old = join(run, "before");
84
+ const existed = checkoutProject(root, ref, old);
85
+ const load = (dir, out) => loadProject(dir, { compiler: opts.compiler, outDir: join(run, out), browserAssets: false, cacheKey: join(run, out) });
86
+ const after = own((await load(root, "after-out")).models);
87
+ let before = new Map();
88
+ if (existed) {
89
+ try {
90
+ before = own((await load(old, "before-out")).models);
91
+ }
92
+ catch (err) {
93
+ if (err instanceof CompileError)
94
+ throw new RulesDiffError(`the project at ${ref} does not compile:\n${err.diagnostics}`);
95
+ throw err;
96
+ }
97
+ }
98
+ const names = [...new Set([...before.keys(), ...after.keys()])].sort();
99
+ const diffs = names.map((n) => diffRules(before.get(n), after.get(n), { runs: opts.runs, seed: opts.seed }));
100
+ const shown = diffs.filter((d) => d.status !== "same");
101
+ const widened = diffs.some(widens);
102
+ const text = shown.length
103
+ ? shown.map(rulesDiffText).join("\n\n") + "\n"
104
+ : `No rule changes against ${ref} (${names.length} model${names.length === 1 ? "" : "s"} compared).\n`;
105
+ return { diffs, widened, text };
106
+ }
107
+ finally {
108
+ rmSync(run, { recursive: true, force: true });
109
+ }
110
+ }
111
+ const whole = (name, v) => {
112
+ if (v === undefined)
113
+ return undefined;
114
+ const n = Number(v);
115
+ if (!Number.isSafeInteger(n) || n < (name === "--seed" ? 0 : 1))
116
+ throw new RulesDiffError(`${name} is a whole number`);
117
+ return n;
118
+ };
119
+ async function main() {
120
+ try {
121
+ const { values, positionals } = parseArgs({
122
+ allowPositionals: true,
123
+ options: {
124
+ ref: { type: "string" },
125
+ runs: { type: "string" },
126
+ seed: { type: "string" },
127
+ "fail-on-widen": { type: "boolean" },
128
+ },
129
+ });
130
+ if (values.ref === undefined)
131
+ throw new RulesDiffError("usage: weft rules diff <ref> [dir]");
132
+ const root = resolve(positionals[0] ?? ".");
133
+ const result = await diffProjectRules(root, values.ref, {
134
+ compiler: findCompiler(root),
135
+ runs: whole("--runs", values.runs),
136
+ seed: whole("--seed", values.seed),
137
+ });
138
+ process.stdout.write(result.text);
139
+ if (values["fail-on-widen"] && result.widened)
140
+ process.exit(1);
141
+ }
142
+ catch (err) {
143
+ if (err instanceof CompileError) {
144
+ console.error(err.diagnostics);
145
+ }
146
+ else if (err instanceof RulesDiffError || err instanceof ProjectError || err instanceof ConfigError) {
147
+ console.error(`[weft] ${err.message}`);
148
+ }
149
+ else {
150
+ console.error("[weft] rules diff:", err instanceof Error ? err.message : err);
151
+ }
152
+ process.exit(1);
153
+ }
154
+ }
155
+ function isEntry() {
156
+ try {
157
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ }
163
+ if (isEntry()) {
164
+ await main();
165
+ }
@@ -0,0 +1,17 @@
1
+ import { type FuzzReport } from "@weft-framework/data";
2
+ import { type Compiler } from "./compiler.js";
3
+ export declare class RulesTestError extends Error {
4
+ }
5
+ export interface RulesTestOptions {
6
+ compiler: Compiler;
7
+ runs?: number;
8
+ seed?: number;
9
+ model?: string;
10
+ }
11
+ export interface RulesTestResult {
12
+ reports: FuzzReport[];
13
+ ok: boolean;
14
+ text: string;
15
+ }
16
+ export declare function rulesReportText(r: FuzzReport): string;
17
+ export declare function testRules(root: string, opts: RulesTestOptions): Promise<RulesTestResult>;