@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/pdf.js ADDED
@@ -0,0 +1,332 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ export class PdfError extends Error {
6
+ }
7
+ const PAPER = {
8
+ A3: [11.69, 16.54],
9
+ A4: [8.27, 11.69],
10
+ A5: [5.83, 8.27],
11
+ Letter: [8.5, 11],
12
+ Legal: [8.5, 14],
13
+ };
14
+ const FILENAME = /^[A-Za-z0-9][A-Za-z0-9 ._()-]{0,99}\.pdf$/;
15
+ export function checkPdfRoute(raw, where) {
16
+ if (raw === true)
17
+ return true;
18
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
19
+ throw new TypeError(`${where}: pdf is true or { filename, format, landscape }`);
20
+ }
21
+ const o = raw;
22
+ for (const k of Object.keys(o)) {
23
+ if (k !== "filename" && k !== "format" && k !== "landscape")
24
+ throw new TypeError(`${where}: pdf.${k} is not filename, format or landscape`);
25
+ }
26
+ if (o.filename !== undefined && (typeof o.filename !== "string" || !FILENAME.test(o.filename))) {
27
+ throw new TypeError(`${where}: pdf.filename is a plain file name ending in .pdf`);
28
+ }
29
+ if (o.format !== undefined && !(typeof o.format === "string" && o.format in PAPER)) {
30
+ throw new TypeError(`${where}: pdf.format is one of ${Object.keys(PAPER).join(", ")}`);
31
+ }
32
+ if (o.landscape !== undefined && typeof o.landscape !== "boolean")
33
+ throw new TypeError(`${where}: pdf.landscape is true or false`);
34
+ return o;
35
+ }
36
+ export function pdfFilename(path, spec) {
37
+ if (spec !== true && spec.filename)
38
+ return spec.filename;
39
+ const last = decodeURIComponent(path.split("/").filter(Boolean).pop() ?? "page").replace(/[^A-Za-z0-9._()-]+/g, "-");
40
+ const name = (last.replace(/^[^A-Za-z0-9]+/, "") || "page").slice(0, 90);
41
+ return `${name}.pdf`;
42
+ }
43
+ export function findBrowser(env = process.env) {
44
+ if (env.WEFT_BROWSER)
45
+ return existsSync(env.WEFT_BROWSER) ? env.WEFT_BROWSER : null;
46
+ const fixed = [
47
+ join(env.ProgramFiles ?? "C:\\Program Files", "Google", "Chrome", "Application", "chrome.exe"),
48
+ join(env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)", "Google", "Chrome", "Application", "chrome.exe"),
49
+ join(env.LOCALAPPDATA ?? "", "Google", "Chrome", "Application", "chrome.exe"),
50
+ join(env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)", "Microsoft", "Edge", "Application", "msedge.exe"),
51
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
52
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
53
+ "/usr/bin/google-chrome",
54
+ "/usr/bin/google-chrome-stable",
55
+ "/usr/bin/chromium",
56
+ "/usr/bin/chromium-browser",
57
+ ];
58
+ for (const p of fixed)
59
+ if (p && existsSync(p))
60
+ return p;
61
+ const roots = [env.PLAYWRIGHT_BROWSERS_PATH, join(env.LOCALAPPDATA ?? "", "ms-playwright"), join(homedir(), ".cache", "ms-playwright")];
62
+ for (const root of roots) {
63
+ if (!root || !existsSync(root))
64
+ continue;
65
+ const dirs = readdirSync(root).filter((d) => /^chromium-\d+$/.test(d)).sort((a, b) => Number(b.slice(9)) - Number(a.slice(9)));
66
+ for (const d of dirs) {
67
+ for (const rel of [["chrome-win64", "chrome.exe"], ["chrome-win", "chrome.exe"], ["chrome-linux", "chrome"], ["chrome-linux64", "chrome"]]) {
68
+ const p = join(root, d, ...rel);
69
+ if (existsSync(p))
70
+ return p;
71
+ }
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+ class Chromium {
77
+ #proc;
78
+ #in;
79
+ #profile;
80
+ #next = 1;
81
+ #buf = "";
82
+ #calls = new Map();
83
+ #events = new Map();
84
+ closed = false;
85
+ constructor(exe, args) {
86
+ this.#profile = mkdtempSync(join(tmpdir(), "weft-pdf-"));
87
+ this.#proc = spawn(exe, [
88
+ "--headless=new",
89
+ "--remote-debugging-pipe",
90
+ `--user-data-dir=${this.#profile}`,
91
+ "--no-first-run",
92
+ "--no-default-browser-check",
93
+ "--disable-extensions",
94
+ "--disable-background-networking",
95
+ "--disable-component-update",
96
+ "--disable-default-apps",
97
+ "--disable-sync",
98
+ "--mute-audio",
99
+ ...args,
100
+ "about:blank",
101
+ ], { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] });
102
+ this.#in = this.#proc.stdio[3];
103
+ const out = this.#proc.stdio[4];
104
+ out.setEncoding("utf8");
105
+ out.on("data", (chunk) => {
106
+ this.#buf += chunk;
107
+ for (let end = this.#buf.indexOf("\0"); end >= 0; end = this.#buf.indexOf("\0")) {
108
+ const text = this.#buf.slice(0, end);
109
+ this.#buf = this.#buf.slice(end + 1);
110
+ let msg;
111
+ try {
112
+ msg = JSON.parse(text);
113
+ }
114
+ catch {
115
+ continue;
116
+ }
117
+ this.#dispatch(msg);
118
+ }
119
+ });
120
+ this.#in.on("error", () => this.#gone());
121
+ this.#proc.on("error", () => this.#gone());
122
+ this.#proc.on("exit", () => this.#gone());
123
+ }
124
+ #dispatch(msg) {
125
+ if (msg.id !== undefined) {
126
+ const call = this.#calls.get(msg.id);
127
+ this.#calls.delete(msg.id);
128
+ if (!call)
129
+ return;
130
+ if (msg.error)
131
+ call.reject(new PdfError(`${call.method}: ${msg.error.message}`));
132
+ else
133
+ call.resolve(msg.result ?? {});
134
+ return;
135
+ }
136
+ if (msg.sessionId)
137
+ this.#events.get(msg.sessionId)?.(msg);
138
+ }
139
+ #gone() {
140
+ if (this.closed)
141
+ return;
142
+ this.closed = true;
143
+ for (const [, call] of this.#calls)
144
+ call.reject(new PdfError(`${call.method}: the browser stopped`));
145
+ this.#calls.clear();
146
+ try {
147
+ rmSync(this.#profile, { recursive: true, force: true });
148
+ }
149
+ catch {
150
+ }
151
+ }
152
+ send(method, params = {}, sessionId) {
153
+ if (this.closed)
154
+ return Promise.reject(new PdfError("the browser stopped"));
155
+ const id = this.#next++;
156
+ return new Promise((resolve, reject) => {
157
+ this.#calls.set(id, { resolve, reject, method });
158
+ this.#in.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + "\0");
159
+ });
160
+ }
161
+ on(sessionId, fn) {
162
+ if (fn)
163
+ this.#events.set(sessionId, fn);
164
+ else
165
+ this.#events.delete(sessionId);
166
+ }
167
+ kill() {
168
+ this.#proc.kill();
169
+ this.#gone();
170
+ }
171
+ }
172
+ const b64 = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
173
+ class Printer {
174
+ #o;
175
+ #browser = null;
176
+ #running = 0;
177
+ #waiting = [];
178
+ constructor(o) {
179
+ const concurrency = o.concurrency ?? 2;
180
+ const timeoutMs = o.timeoutMs ?? 30_000;
181
+ const maxBytes = o.maxBytes ?? 20 * 1024 * 1024;
182
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
183
+ throw new RangeError("definePdf: concurrency is 1-16");
184
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1000)
185
+ throw new RangeError("definePdf: timeoutMs is at least 1000");
186
+ if (!Number.isInteger(maxBytes) || maxBytes < 1024)
187
+ throw new RangeError("definePdf: maxBytes is at least 1024");
188
+ if (o.args !== undefined && (!Array.isArray(o.args) || !o.args.every((a) => typeof a === "string" && a.startsWith("--")))) {
189
+ throw new TypeError("definePdf: args are browser flags (\"--...\")");
190
+ }
191
+ this.#o = { browser: o.browser, concurrency, timeoutMs, maxBytes, args: o.args ?? [] };
192
+ }
193
+ #chromium() {
194
+ if (this.#browser && !this.#browser.closed)
195
+ return this.#browser;
196
+ const exe = this.#o.browser ?? findBrowser();
197
+ if (!exe || !existsSync(exe)) {
198
+ throw new PdfError("no browser to print with: install Chrome, Edge or Chromium, or set definePdf({ browser }) or WEFT_BROWSER");
199
+ }
200
+ this.#browser = new Chromium(exe, this.#o.args);
201
+ return this.#browser;
202
+ }
203
+ print(job) {
204
+ return this.#queued(() => this.#render(job, undefined, async (call) => {
205
+ const [w, h] = PAPER[job.format ?? "A4"];
206
+ const out = (await call("Page.printToPDF", {
207
+ printBackground: true,
208
+ preferCSSPageSize: true,
209
+ landscape: job.landscape === true,
210
+ paperWidth: w,
211
+ paperHeight: h,
212
+ marginTop: 0.4,
213
+ marginBottom: 0.4,
214
+ marginLeft: 0.4,
215
+ marginRight: 0.4,
216
+ }));
217
+ if (typeof out.data !== "string")
218
+ throw new PdfError("the browser returned no PDF");
219
+ return out.data;
220
+ }));
221
+ }
222
+ capture(job) {
223
+ const size = (n) => Number.isInteger(n) && n >= 16 && n <= 4096;
224
+ if (!size(job.width) || !size(job.height))
225
+ throw new RangeError("capture: width and height are 16-4096");
226
+ return this.#queued(() => this.#render(job, { width: job.width, height: job.height }, async (call) => {
227
+ const out = (await call("Page.captureScreenshot", {
228
+ format: "png",
229
+ clip: { x: 0, y: 0, width: job.width, height: job.height, scale: 1 },
230
+ captureBeyondViewport: false,
231
+ }));
232
+ if (typeof out.data !== "string")
233
+ throw new PdfError("the browser returned no image");
234
+ return out.data;
235
+ }));
236
+ }
237
+ async #queued(fn) {
238
+ if (this.#running >= this.#o.concurrency)
239
+ await new Promise((r) => this.#waiting.push(r));
240
+ this.#running += 1;
241
+ try {
242
+ return await fn();
243
+ }
244
+ finally {
245
+ this.#running -= 1;
246
+ this.#waiting.shift()?.();
247
+ }
248
+ }
249
+ async #render(job, viewport, produce) {
250
+ const page = new URL(job.url);
251
+ const browser = this.#chromium();
252
+ const { targetId } = (await browser.send("Target.createTarget", { url: "about:blank" }));
253
+ let sessionId = "";
254
+ let timer;
255
+ try {
256
+ ({ sessionId } = (await browser.send("Target.attachToTarget", { targetId, flatten: true })));
257
+ const call = (method, params = {}) => browser.send(method, params, sessionId);
258
+ let requests = 0;
259
+ let loaded;
260
+ const load = new Promise((r) => (loaded = r));
261
+ browser.on(sessionId, (m) => {
262
+ if (m.method === "Page.loadEventFired")
263
+ loaded();
264
+ if (m.method !== "Fetch.requestPaused")
265
+ return;
266
+ const p = m.params;
267
+ void (async () => {
268
+ try {
269
+ const asked = new URL(p.request.url);
270
+ if (p.request.method === "GET" && asked.href.split("#")[0] === page.href.split("#")[0]) {
271
+ await call("Fetch.fulfillRequest", {
272
+ requestId: p.requestId,
273
+ responseCode: 200,
274
+ responseHeaders: [{ name: "content-type", value: "text/html; charset=utf-8" }],
275
+ body: b64(new TextEncoder().encode(job.html)),
276
+ });
277
+ return;
278
+ }
279
+ const own = asked.origin === page.origin && p.request.method === "GET" && asked.pathname !== "/favicon.ico";
280
+ if (!own || ++requests > 200)
281
+ throw new Error("refused");
282
+ const res = await job.fetch(asked.href);
283
+ const body = new Uint8Array(await res.arrayBuffer());
284
+ if (body.byteLength > 10 * 1024 * 1024)
285
+ throw new Error("too large");
286
+ const type = res.headers.get("content-type");
287
+ await call("Fetch.fulfillRequest", {
288
+ requestId: p.requestId,
289
+ responseCode: res.status >= 200 && res.status < 600 ? res.status : 502,
290
+ responseHeaders: type ? [{ name: "content-type", value: type }] : [],
291
+ body: b64(body),
292
+ });
293
+ }
294
+ catch {
295
+ await call("Fetch.failRequest", { requestId: p.requestId, errorReason: "BlockedByClient" }).catch(() => { });
296
+ }
297
+ })();
298
+ });
299
+ const run = (async () => {
300
+ await call("Emulation.setScriptExecutionDisabled", { value: true });
301
+ if (viewport)
302
+ await call("Emulation.setDeviceMetricsOverride", { ...viewport, deviceScaleFactor: 1, mobile: false });
303
+ await call("Fetch.enable", { patterns: [{ urlPattern: "*" }] });
304
+ await call("Page.enable");
305
+ await call("Page.navigate", { url: page.href });
306
+ await load;
307
+ const data = await produce(call);
308
+ if (data.length * 0.75 > this.#o.maxBytes)
309
+ throw new PdfError(`the output is larger than ${this.#o.maxBytes} bytes`);
310
+ return new Uint8Array(Buffer.from(data, "base64"));
311
+ })();
312
+ const limit = new Promise((_, reject) => {
313
+ timer = setTimeout(() => reject(new PdfError(`printing took longer than ${this.#o.timeoutMs} ms`)), this.#o.timeoutMs);
314
+ });
315
+ run.catch(() => { });
316
+ return await Promise.race([run, limit]);
317
+ }
318
+ finally {
319
+ clearTimeout(timer);
320
+ if (sessionId)
321
+ browser.on(sessionId, null);
322
+ await browser.send("Target.closeTarget", { targetId }).catch(() => { });
323
+ }
324
+ }
325
+ async close() {
326
+ this.#browser?.kill();
327
+ this.#browser = null;
328
+ }
329
+ }
330
+ export function definePdf(o = {}) {
331
+ return new Printer(o);
332
+ }
@@ -0,0 +1,22 @@
1
+ import { type ErasePlan, type PersonalData } from "@weft-framework/data";
2
+ import { type Compiler } from "./compiler.js";
3
+ export declare class PersonalDataError extends Error {
4
+ }
5
+ export interface PersonalDataCommand {
6
+ compiler: Compiler;
7
+ command: "export" | "erase";
8
+ key: string;
9
+ model?: string;
10
+ plan?: Record<string, ErasePlan>;
11
+ dryRun?: boolean;
12
+ }
13
+ export interface PersonalDataResult {
14
+ data: Omit<PersonalData, "steps">;
15
+ erased?: {
16
+ removed: Record<string, number>;
17
+ unlinked: Record<string, number>;
18
+ };
19
+ summary: string[];
20
+ }
21
+ export declare function parsePlan(text: string | undefined): Record<string, ErasePlan>;
22
+ export declare function personalDataCommand(root: string, opts: PersonalDataCommand): Promise<PersonalDataResult>;
@@ -0,0 +1,148 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { eraseData, personalData } from "@weft-framework/data";
7
+ import { CompileError, findCompiler } from "./compiler.js";
8
+ import { ConfigError } from "./config.js";
9
+ import { ProjectError, loadProject } from "./project.js";
10
+ import { ModelStorage } from "./storage.js";
11
+ export class PersonalDataError extends Error {
12
+ }
13
+ export function parsePlan(text) {
14
+ const plan = {};
15
+ if (!text)
16
+ return plan;
17
+ for (const part of text.split(",")) {
18
+ const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(delete|unlink|keep)\s*$/.exec(part);
19
+ if (!m)
20
+ throw new PersonalDataError(`--plan: expected Model=delete|unlink|keep, got ${JSON.stringify(part)}`);
21
+ plan[m[1]] = m[2];
22
+ }
23
+ return plan;
24
+ }
25
+ export async function personalDataCommand(root, opts) {
26
+ root = resolve(root);
27
+ if (typeof opts.key !== "string" || opts.key === "")
28
+ throw new PersonalDataError("--key <id> is required: the person's key");
29
+ const outDir = join(root, ".weft", "data", randomUUID());
30
+ const storage = new ModelStorage();
31
+ try {
32
+ const project = await loadProject(root, { compiler: opts.compiler, outDir, browserAssets: false, cacheKey: outDir });
33
+ const database = project.database;
34
+ if (database === undefined || database === ":memory:") {
35
+ throw new PersonalDataError("no `database` file in weft.config.ts");
36
+ }
37
+ const models = Object.values(project.models);
38
+ const name = opts.model ?? "User";
39
+ const subject = project.models[name];
40
+ if (!subject)
41
+ throw new PersonalDataError(`no model ${name}; name the model people are rows of with --model`);
42
+ await storage.attach(models, { database });
43
+ const keyField = subject.fields.find((f) => f.name === subject.key);
44
+ const key = keyField && keyField.type === "number" && /^-?\d+$/.test(opts.key) ? Number(opts.key) : opts.key;
45
+ let data;
46
+ try {
47
+ data = personalData(models, subject, key, { plan: opts.plan ?? {} });
48
+ }
49
+ catch (err) {
50
+ throw new PersonalDataError(err instanceof Error ? err.message.replace(/^personalData: /, "") : String(err));
51
+ }
52
+ const summary = describe(data);
53
+ const { steps: _steps, ...visible } = data;
54
+ if (opts.command === "export" || opts.dryRun)
55
+ return { data: visible, summary };
56
+ return { data: visible, erased: eraseData(data), summary };
57
+ }
58
+ finally {
59
+ storage.close();
60
+ rmSync(outDir, { recursive: true, force: true });
61
+ }
62
+ }
63
+ function describe(data) {
64
+ const lines = [];
65
+ for (const s of data.steps) {
66
+ const what = s.action === "delete" ? "delete" : `clear ${s.fields.join(", ")} on`;
67
+ lines.push(`${what} ${s.keys.length} ${s.model.name}`);
68
+ }
69
+ if (data.files.length)
70
+ lines.push(`${data.files.length} file(s) held by these rows: delete them from storage`);
71
+ if (data.missing.length)
72
+ lines.push(`not searched (no such model): ${data.missing.join(", ")}`);
73
+ return lines;
74
+ }
75
+ async function main() {
76
+ const { values, positionals } = parseArgs({
77
+ allowPositionals: true,
78
+ options: {
79
+ command: { type: "string" },
80
+ key: { type: "string" },
81
+ model: { type: "string" },
82
+ out: { type: "string" },
83
+ plan: { type: "string" },
84
+ "dry-run": { type: "boolean" },
85
+ yes: { type: "boolean" },
86
+ },
87
+ });
88
+ const root = resolve(positionals[0] ?? ".");
89
+ const command = values.command;
90
+ try {
91
+ if (command !== "export" && command !== "erase")
92
+ throw new PersonalDataError("expected `export` or `erase`");
93
+ if (command === "erase" && values.yes !== true && values["dry-run"] !== true) {
94
+ throw new PersonalDataError("`weft data erase` deletes data for good; check with --dry-run, then run it with --yes");
95
+ }
96
+ const result = await personalDataCommand(root, {
97
+ compiler: findCompiler(root),
98
+ command,
99
+ key: values.key ?? "",
100
+ ...(values.model ? { model: values.model } : {}),
101
+ plan: parsePlan(values.plan),
102
+ dryRun: values["dry-run"] === true,
103
+ });
104
+ if (command === "export") {
105
+ const json = JSON.stringify(result.data, (_k, v) => (typeof v === "bigint" ? v.toString() : v), 2) + "\n";
106
+ if (values.out) {
107
+ writeFileSync(resolve(values.out), json, { flag: "wx", mode: 0o600 });
108
+ console.error(`[weft] wrote ${Object.values(result.data.rows).flat().length} rows to ${values.out}`);
109
+ }
110
+ else {
111
+ process.stdout.write(json);
112
+ }
113
+ for (const line of result.summary.filter((l) => l.startsWith("not searched")))
114
+ console.error(`[weft] ${line}`);
115
+ return;
116
+ }
117
+ for (const line of result.summary)
118
+ console.log(`[weft] ${result.erased ? "" : "would "}${line}`);
119
+ if (result.erased)
120
+ console.log("[weft] erased");
121
+ }
122
+ catch (err) {
123
+ if (err instanceof CompileError) {
124
+ console.error(err.diagnostics);
125
+ }
126
+ else if (err instanceof PersonalDataError || err instanceof ProjectError || err instanceof ConfigError) {
127
+ console.error(`[weft] ${err.message}`);
128
+ }
129
+ else if (err && typeof err === "object" && err.code === "EEXIST") {
130
+ console.error(`[weft] ${values.out} exists; choose another --out`);
131
+ }
132
+ else {
133
+ console.error("[weft] data:", err instanceof Error ? (err.stack ?? err.message) : err);
134
+ }
135
+ process.exit(1);
136
+ }
137
+ }
138
+ function isEntry() {
139
+ try {
140
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ }
146
+ if (isEntry()) {
147
+ await main();
148
+ }
@@ -0,0 +1,9 @@
1
+ import { type PointMessage, type ServerMessage } from "@weft-framework/runtime";
2
+ import type { PageContext } from "./context.js";
3
+ import { type Presence } from "./presence.js";
4
+ type Send = (msg: ServerMessage) => void;
5
+ export declare function pointerArea(presence: Presence<any>, room: string): Readonly<Record<string, string>>;
6
+ export declare function pointMessage(entry: object, ctx: PageContext, msg: PointMessage, send: Send): void;
7
+ export declare function pointLeave(entry: object): void;
8
+ export declare function resetPointers(): void;
9
+ export {};
@@ -0,0 +1,148 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { runtimeAttrs } from "@weft-framework/runtime";
3
+ import { pointerPresence, presenceIn, watchRooms } from "./presence.js";
4
+ const BROADCAST_MS = 50;
5
+ const areas = new Map();
6
+ const tokenOf = (presence, room) => "p." + Buffer.from(JSON.stringify([presence, room]), "utf8").toString("base64url");
7
+ function parseToken(token) {
8
+ if (!token.startsWith("p."))
9
+ return null;
10
+ try {
11
+ const v = JSON.parse(Buffer.from(token.slice(2), "base64url").toString("utf8"));
12
+ if (!Array.isArray(v) || v.length !== 2 || typeof v[0] !== "string" || typeof v[1] !== "string")
13
+ return null;
14
+ return tokenOf(v[0], v[1]) === token ? { presence: v[0], room: v[1] } : null;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export function pointerArea(presence, room) {
21
+ if (!pointerPresence(presence.name)) {
22
+ throw new Error(`@weft-framework/server: presence ${presence.name} does not share pointers; define it with \`pointers: {}\``);
23
+ }
24
+ if (typeof room !== "string" || room === "" || room.length > 256) {
25
+ throw new Error("@weft-framework/server: a room is a string of 1-256 characters");
26
+ }
27
+ return runtimeAttrs({ "data-weft-point": tokenOf(presence.name, room) });
28
+ }
29
+ const SALT = randomBytes(32);
30
+ let counter = 0;
31
+ const memberId = (area, tab) => tab === undefined
32
+ ? `p${(++counter).toString(36)}${randomBytes(3).toString("hex")}`
33
+ : "t" + createHash("sha256").update(SALT).update(area).update("\0").update(tab).digest("base64url").slice(0, 16);
34
+ function prune(a) {
35
+ for (const [entry, m] of a.members) {
36
+ if (!presenceIn(m.ctx, a.presence, a.room))
37
+ a.members.delete(entry);
38
+ }
39
+ if (a.members.size === 0) {
40
+ if (a.timer !== null)
41
+ clearTimeout(a.timer);
42
+ areas.delete(a.token);
43
+ }
44
+ }
45
+ function soon(a) {
46
+ if (a.timer !== null)
47
+ return;
48
+ a.timer = setTimeout(() => {
49
+ a.timer = null;
50
+ broadcast(a);
51
+ }, BROADCAST_MS);
52
+ a.timer.unref?.();
53
+ }
54
+ function broadcast(a) {
55
+ prune(a);
56
+ if (a.members.size === 0)
57
+ return;
58
+ const p = pointerPresence(a.presence);
59
+ const shown = [];
60
+ const of = new Map();
61
+ for (const m of a.members.values()) {
62
+ if (!m.at && !m.sel && !m.view)
63
+ continue;
64
+ const ptr = { id: m.id };
65
+ if (p?.label) {
66
+ try {
67
+ const info = presenceIn(m.ctx, a.presence, a.room)?.info;
68
+ const label = p.label(info);
69
+ if (typeof label === "string" && label !== "")
70
+ ptr.label = label.slice(0, 200);
71
+ }
72
+ catch {
73
+ }
74
+ }
75
+ if (m.at)
76
+ ptr.at = m.at;
77
+ if (m.sel)
78
+ ptr.sel = m.sel;
79
+ if (m.view)
80
+ ptr.view = m.view;
81
+ shown.push(ptr);
82
+ of.set(m, ptr);
83
+ }
84
+ for (const m of a.members.values()) {
85
+ const mine = of.get(m);
86
+ m.send({ t: "point", area: a.token, list: mine ? shown.filter((x) => x !== mine) : shown });
87
+ }
88
+ }
89
+ export function pointMessage(entry, ctx, msg, send) {
90
+ const name = parseToken(msg.area);
91
+ if (!name || !pointerPresence(name.presence) || !presenceIn(ctx, name.presence, name.room)) {
92
+ const a = areas.get(msg.area);
93
+ if (a?.members.delete(entry))
94
+ soon(a);
95
+ return;
96
+ }
97
+ let a = areas.get(msg.area);
98
+ if (!a) {
99
+ a = { token: msg.area, presence: name.presence, room: name.room, members: new Map(), timer: null };
100
+ areas.set(a.token, a);
101
+ }
102
+ let m = a.members.get(entry);
103
+ if (!m) {
104
+ m = { id: memberId(a.token, msg.tab), ctx, send, at: null, sel: null, view: null };
105
+ a.members.set(entry, m);
106
+ }
107
+ m.ctx = ctx;
108
+ m.send = send;
109
+ if (msg.join) {
110
+ if (msg.tab !== undefined)
111
+ m.id = memberId(a.token, msg.tab);
112
+ m.at = m.sel = m.view = null;
113
+ }
114
+ else {
115
+ if (msg.at !== undefined)
116
+ m.at = msg.at;
117
+ if (msg.sel !== undefined)
118
+ m.sel = msg.sel;
119
+ if (msg.view !== undefined)
120
+ m.view = msg.view;
121
+ }
122
+ soon(a);
123
+ }
124
+ export function pointLeave(entry) {
125
+ for (const a of [...areas.values()]) {
126
+ if (a.members.delete(entry)) {
127
+ if (a.members.size === 0) {
128
+ if (a.timer !== null)
129
+ clearTimeout(a.timer);
130
+ areas.delete(a.token);
131
+ }
132
+ else {
133
+ soon(a);
134
+ }
135
+ }
136
+ }
137
+ }
138
+ watchRooms((presence, room) => {
139
+ const a = areas.get(tokenOf(presence, room));
140
+ if (a)
141
+ soon(a);
142
+ });
143
+ export function resetPointers() {
144
+ for (const a of areas.values())
145
+ if (a.timer !== null)
146
+ clearTimeout(a.timer);
147
+ areas.clear();
148
+ }
@@ -0,0 +1,3 @@
1
+ export type CssPass = (css: string, file: string) => Promise<string>;
2
+ export declare function postcssConfig(root: string): string | null;
3
+ export declare function loadPostcss(root: string, production: boolean): Promise<CssPass | null>;