@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.
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
@@ -0,0 +1,282 @@
1
+ import { deflateSync, inflateSync } from "node:zlib";
2
+ import { ImageError } from "./bitmap.js";
3
+ const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
4
+ export function isPng(b) {
5
+ return b.length > 8 && SIGNATURE.every((v, i) => b[i] === v);
6
+ }
7
+ const u32 = (b, at) => ((b[at] << 24) | (b[at + 1] << 16) | (b[at + 2] << 8) | b[at + 3]) >>> 0;
8
+ export function pngSize(b) {
9
+ if (!isPng(b) || b.length < 24)
10
+ throw new ImageError("not a PNG");
11
+ return { width: u32(b, 16), height: u32(b, 20) };
12
+ }
13
+ export function decodePng(b, maxPixels) {
14
+ if (!isPng(b))
15
+ throw new ImageError("not a PNG");
16
+ let at = 8;
17
+ let width = 0;
18
+ let height = 0;
19
+ let depth = 0;
20
+ let type = -1;
21
+ let interlace = 0;
22
+ let palette = null;
23
+ let trns = null;
24
+ const idat = [];
25
+ while (at + 8 <= b.length) {
26
+ const len = u32(b, at);
27
+ const name = String.fromCharCode(b[at + 4], b[at + 5], b[at + 6], b[at + 7]);
28
+ const data = b.subarray(at + 8, at + 8 + len);
29
+ if (data.length !== len)
30
+ throw new ImageError("PNG is cut short");
31
+ at += 12 + len;
32
+ if (name === "IHDR") {
33
+ width = u32(data, 0);
34
+ height = u32(data, 4);
35
+ depth = data[8];
36
+ type = data[9];
37
+ interlace = data[12];
38
+ if (data[10] !== 0 || data[11] !== 0 || interlace > 1)
39
+ throw new ImageError("unsupported PNG compression or interlace");
40
+ const ok = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
41
+ if (!ok[type]?.includes(depth))
42
+ throw new ImageError("unsupported PNG colour type or depth");
43
+ if (width < 1 || height < 1 || width * height > maxPixels)
44
+ throw new ImageError("image too large");
45
+ }
46
+ else if (name === "PLTE")
47
+ palette = data;
48
+ else if (name === "tRNS")
49
+ trns = data;
50
+ else if (name === "IDAT")
51
+ idat.push(data);
52
+ else if (name === "IEND")
53
+ break;
54
+ }
55
+ if (!width || !idat.length)
56
+ throw new ImageError("PNG has no image data");
57
+ if (type === 3 && !palette)
58
+ throw new ImageError("PNG palette missing");
59
+ const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[type];
60
+ const bpp = Math.max(1, (channels * depth) >> 3);
61
+ const rowBytes = (w) => ((w * channels * depth + 7) >> 3) + 1;
62
+ const passes = interlace
63
+ ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]]
64
+ : [[0, 0, 1, 1]];
65
+ let expected = 0;
66
+ const dims = passes.map(([x0, y0, dx, dy]) => {
67
+ const w = Math.ceil((width - x0) / dx);
68
+ const h = Math.ceil((height - y0) / dy);
69
+ if (w > 0 && h > 0)
70
+ expected += rowBytes(w) * h;
71
+ return [w, h];
72
+ });
73
+ let raw;
74
+ try {
75
+ raw = inflateSync(Buffer.concat(idat), { maxOutputLength: expected + 1024 });
76
+ }
77
+ catch {
78
+ throw new ImageError("PNG data is damaged");
79
+ }
80
+ if (raw.length < expected)
81
+ throw new ImageError("PNG data is cut short");
82
+ const out = new Uint8Array(width * height * 4);
83
+ let pos = 0;
84
+ passes.forEach(([x0, y0, dx, dy], p) => {
85
+ const [w, h] = dims[p];
86
+ if (w <= 0 || h <= 0)
87
+ return;
88
+ const rb = rowBytes(w) - 1;
89
+ let prev = new Uint8Array(rb);
90
+ for (let y = 0; y < h; y++) {
91
+ const filter = raw[pos++];
92
+ const line = new Uint8Array(raw.buffer, raw.byteOffset + pos, rb).slice();
93
+ pos += rb;
94
+ unfilter(filter, line, prev, bpp);
95
+ prev = line;
96
+ for (let x = 0; x < w; x++) {
97
+ const px = ((y0 + y * dy) * width + x0 + x * dx) * 4;
98
+ pixel(line, x, out, px);
99
+ }
100
+ }
101
+ });
102
+ return { width, height, data: out };
103
+ function sample(line, i) {
104
+ if (depth === 8)
105
+ return line[i];
106
+ if (depth === 16)
107
+ return line[i * 2];
108
+ const perByte = 8 / depth;
109
+ const byte = line[Math.floor(i / perByte)];
110
+ const shift = 8 - depth - (i % perByte) * depth;
111
+ const v = (byte >> shift) & ((1 << depth) - 1);
112
+ return type === 3 ? v : Math.round((v * 255) / ((1 << depth) - 1));
113
+ }
114
+ function raw16(line, i) {
115
+ return depth === 16 ? (line[i * 2] << 8) | line[i * 2 + 1] : -1;
116
+ }
117
+ function pixel(line, x, o, px) {
118
+ if (type === 3) {
119
+ const i = sample(line, x);
120
+ o[px] = palette[i * 3] ?? 0;
121
+ o[px + 1] = palette[i * 3 + 1] ?? 0;
122
+ o[px + 2] = palette[i * 3 + 2] ?? 0;
123
+ o[px + 3] = trns && i < trns.length ? trns[i] : 255;
124
+ return;
125
+ }
126
+ const c = x * channels;
127
+ if (type === 0 || type === 4) {
128
+ const g = sample(line, c);
129
+ o[px] = o[px + 1] = o[px + 2] = g;
130
+ let a = type === 4 ? sample(line, c + 1) : 255;
131
+ if (type === 0 && trns && trns.length >= 2) {
132
+ const key = (trns[0] << 8) | trns[1];
133
+ const v = depth === 16 ? raw16(line, c) : depth === 8 ? line[c] : rawLow(line, c);
134
+ if (v === key)
135
+ a = 0;
136
+ }
137
+ o[px + 3] = a;
138
+ return;
139
+ }
140
+ o[px] = sample(line, c);
141
+ o[px + 1] = sample(line, c + 1);
142
+ o[px + 2] = sample(line, c + 2);
143
+ let a = type === 6 ? sample(line, c + 3) : 255;
144
+ if (type === 2 && trns && trns.length >= 6) {
145
+ const k = [(trns[0] << 8) | trns[1], (trns[2] << 8) | trns[3], (trns[4] << 8) | trns[5]];
146
+ const v = depth === 16 ? [raw16(line, c), raw16(line, c + 1), raw16(line, c + 2)] : [line[c], line[c + 1], line[c + 2]];
147
+ if (v[0] === k[0] && v[1] === k[1] && v[2] === k[2])
148
+ a = 0;
149
+ }
150
+ o[px + 3] = a;
151
+ }
152
+ function rawLow(line, i) {
153
+ const perByte = 8 / depth;
154
+ const byte = line[Math.floor(i / perByte)];
155
+ return (byte >> (8 - depth - (i % perByte) * depth)) & ((1 << depth) - 1);
156
+ }
157
+ }
158
+ function unfilter(filter, line, prev, bpp) {
159
+ const n = line.length;
160
+ switch (filter) {
161
+ case 0:
162
+ return;
163
+ case 1:
164
+ for (let i = bpp; i < n; i++)
165
+ line[i] = (line[i] + line[i - bpp]) & 255;
166
+ return;
167
+ case 2:
168
+ for (let i = 0; i < n; i++)
169
+ line[i] = (line[i] + prev[i]) & 255;
170
+ return;
171
+ case 3:
172
+ for (let i = 0; i < n; i++)
173
+ line[i] = (line[i] + (((i >= bpp ? line[i - bpp] : 0) + prev[i]) >> 1)) & 255;
174
+ return;
175
+ case 4:
176
+ for (let i = 0; i < n; i++) {
177
+ const a = i >= bpp ? line[i - bpp] : 0;
178
+ const b = prev[i];
179
+ const c = i >= bpp ? prev[i - bpp] : 0;
180
+ line[i] = (line[i] + paeth(a, b, c)) & 255;
181
+ }
182
+ return;
183
+ default:
184
+ throw new ImageError("PNG row filter is invalid");
185
+ }
186
+ }
187
+ function paeth(a, b, c) {
188
+ const p = a + b - c;
189
+ const pa = Math.abs(p - a);
190
+ const pb = Math.abs(p - b);
191
+ const pc = Math.abs(p - c);
192
+ return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
193
+ }
194
+ const CRC = (() => {
195
+ const t = new Uint32Array(256);
196
+ for (let n = 0; n < 256; n++) {
197
+ let c = n;
198
+ for (let k = 0; k < 8; k++)
199
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
200
+ t[n] = c >>> 0;
201
+ }
202
+ return t;
203
+ })();
204
+ function crc32(parts) {
205
+ let c = 0xffffffff;
206
+ for (const p of parts)
207
+ for (let i = 0; i < p.length; i++)
208
+ c = CRC[(c ^ p[i]) & 255] ^ (c >>> 8);
209
+ return (c ^ 0xffffffff) >>> 0;
210
+ }
211
+ function chunk(name, data) {
212
+ const out = new Uint8Array(12 + data.length);
213
+ const v = new DataView(out.buffer);
214
+ v.setUint32(0, data.length);
215
+ const tag = new TextEncoder().encode(name);
216
+ out.set(tag, 4);
217
+ out.set(data, 8);
218
+ v.setUint32(8 + data.length, crc32([tag, data]));
219
+ return out;
220
+ }
221
+ export function encodePng(img) {
222
+ const { width, height, data } = img;
223
+ let opaque = true;
224
+ for (let i = 3; i < data.length; i += 4) {
225
+ if (data[i] !== 255) {
226
+ opaque = false;
227
+ break;
228
+ }
229
+ }
230
+ const ch = opaque ? 3 : 4;
231
+ const rb = width * ch;
232
+ const raw = new Uint8Array((rb + 1) * height);
233
+ let prev = new Uint8Array(rb);
234
+ const cur = new Uint8Array(rb);
235
+ const trial = new Uint8Array(rb);
236
+ for (let y = 0; y < height; y++) {
237
+ for (let x = 0; x < width; x++) {
238
+ const s = (y * width + x) * 4;
239
+ cur[x * ch] = data[s];
240
+ cur[x * ch + 1] = data[s + 1];
241
+ cur[x * ch + 2] = data[s + 2];
242
+ if (ch === 4)
243
+ cur[x * ch + 3] = data[s + 3];
244
+ }
245
+ let best = 0;
246
+ let bestSum = Infinity;
247
+ for (let f = 0; f < 5; f++) {
248
+ let sum = 0;
249
+ for (let i = 0; i < rb; i++) {
250
+ const a = i >= ch ? cur[i - ch] : 0;
251
+ const b = prev[i];
252
+ const c = i >= ch ? prev[i - ch] : 0;
253
+ const p = f === 0 ? 0 : f === 1 ? a : f === 2 ? b : f === 3 ? (a + b) >> 1 : paeth(a, b, c);
254
+ const v = (cur[i] - p) & 255;
255
+ trial[i] = v;
256
+ sum += v < 128 ? v : 256 - v;
257
+ }
258
+ if (sum < bestSum) {
259
+ bestSum = sum;
260
+ best = f;
261
+ raw.set(trial, y * (rb + 1) + 1);
262
+ }
263
+ }
264
+ raw[y * (rb + 1)] = best;
265
+ prev = cur.slice();
266
+ }
267
+ const ihdr = new Uint8Array(13);
268
+ const v = new DataView(ihdr.buffer);
269
+ v.setUint32(0, width);
270
+ v.setUint32(4, height);
271
+ ihdr[8] = 8;
272
+ ihdr[9] = opaque ? 2 : 6;
273
+ const idat = deflateSync(raw, { level: 9 });
274
+ const parts = [new Uint8Array(SIGNATURE), chunk("IHDR", ihdr), chunk("IDAT", idat), chunk("IEND", new Uint8Array(0))];
275
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
276
+ let at = 0;
277
+ for (const p of parts) {
278
+ out.set(p, at);
279
+ at += p.length;
280
+ }
281
+ return out;
282
+ }
@@ -0,0 +1,20 @@
1
+ export type ImageFormat = "jpeg" | "png";
2
+ export interface Variant {
3
+ width: number;
4
+ aspect?: [number, number];
5
+ focus?: [number, number];
6
+ format: ImageFormat | "auto";
7
+ quality: number;
8
+ }
9
+ export interface Transformed {
10
+ bytes: Uint8Array;
11
+ type: "image/jpeg" | "image/png";
12
+ width: number;
13
+ height: number;
14
+ }
15
+ export declare function probe(src: Uint8Array): {
16
+ format: ImageFormat;
17
+ width: number;
18
+ height: number;
19
+ } | null;
20
+ export declare function transform(src: Uint8Array, v: Variant, maxPixels: number): Transformed;
@@ -0,0 +1,52 @@
1
+ import { crop, flatten, ImageError, orient, resize } from "./bitmap.js";
2
+ import { decodeJpeg, encodeJpeg, isJpeg, jpegSize } from "./jpeg.js";
3
+ import { decodePng, encodePng, isPng, pngSize } from "./png.js";
4
+ export function probe(src) {
5
+ if (isJpeg(src))
6
+ return { format: "jpeg", ...jpegSize(src) };
7
+ if (isPng(src))
8
+ return { format: "png", ...pngSize(src) };
9
+ return null;
10
+ }
11
+ export function transform(src, v, maxPixels) {
12
+ const kind = probe(src);
13
+ if (!kind)
14
+ throw new ImageError("not a JPEG or PNG image");
15
+ if (kind.width * kind.height > maxPixels || kind.width < 1 || kind.height < 1)
16
+ throw new ImageError("image too large");
17
+ let img;
18
+ if (kind.format === "jpeg") {
19
+ const d = decodeJpeg(src, maxPixels);
20
+ img = orient(d, d.orientation);
21
+ }
22
+ else {
23
+ img = decodePng(src, maxPixels);
24
+ }
25
+ if (v.aspect) {
26
+ const [aw, ah] = v.aspect;
27
+ const fx = v.focus?.[0] ?? 0.5;
28
+ const fy = v.focus?.[1] ?? 0.5;
29
+ let w = img.width;
30
+ let h = Math.round((w * ah) / aw);
31
+ if (h > img.height) {
32
+ h = img.height;
33
+ w = Math.round((h * aw) / ah);
34
+ }
35
+ img = crop(img, (img.width - w) * fx, (img.height - h) * fy, w, h);
36
+ }
37
+ const width = Math.min(v.width, img.width);
38
+ if (width !== img.width)
39
+ img = resize(img, width, Math.max(1, Math.round((img.height * width) / img.width)));
40
+ let format = v.format;
41
+ if (format === "auto") {
42
+ format = "jpeg";
43
+ for (let i = 3; i < img.data.length; i += 4) {
44
+ if (img.data[i] !== 255) {
45
+ format = "png";
46
+ break;
47
+ }
48
+ }
49
+ }
50
+ const bytes = format === "png" ? encodePng(img) : encodeJpeg(flatten(img), v.quality);
51
+ return { bytes, type: format === "png" ? "image/png" : "image/jpeg", width: img.width, height: img.height };
52
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import { transform } from "./transform.js";
3
+ parentPort?.on("message", (m) => {
4
+ try {
5
+ const r = transform(m.src, m.variant, m.maxPixels);
6
+ parentPort.postMessage({ id: m.id, ok: r }, [r.bytes.buffer]);
7
+ }
8
+ catch (err) {
9
+ parentPort.postMessage({ id: m.id, error: err instanceof Error ? err.message : String(err) });
10
+ }
11
+ });
@@ -0,0 +1,39 @@
1
+ import { ImageError } from "./image/bitmap.js";
2
+ import { transform as transformSync, type ImageFormat, type Transformed, type Variant } from "./image/transform.js";
3
+ export { ImageError, type ImageFormat, type Transformed, type Variant };
4
+ export declare const IMAGES_PATH = "/_weft/img";
5
+ export interface ImagesOptions {
6
+ widths?: number[];
7
+ aspects?: string[];
8
+ formats?: (ImageFormat | "auto")[];
9
+ quality?: number;
10
+ maxPixels?: number;
11
+ maxBytes?: number;
12
+ workers?: number;
13
+ queue?: number;
14
+ cacheBytes?: number;
15
+ timeoutMs?: number;
16
+ }
17
+ export interface ImageUrlOptions {
18
+ width: number;
19
+ aspect?: string;
20
+ format?: ImageFormat | "auto";
21
+ }
22
+ export interface Images {
23
+ url(src: string, o: ImageUrlOptions): string;
24
+ srcset(src: string, o?: {
25
+ aspect?: string;
26
+ format?: ImageFormat | "auto";
27
+ widths?: number[];
28
+ }): string;
29
+ transform(src: Uint8Array, v: {
30
+ width: number;
31
+ aspect?: string;
32
+ format?: ImageFormat | "auto";
33
+ focus?: [number, number];
34
+ }): Promise<Transformed>;
35
+ handle(req: Request, read: (path: string, ifNoneMatch?: string) => Promise<Response>): Promise<Response>;
36
+ close(): Promise<void>;
37
+ }
38
+ export declare function defineImages(o?: ImagesOptions): Images;
39
+ export { transformSync };
package/dist/images.js ADDED
@@ -0,0 +1,283 @@
1
+ import { createHash } from "node:crypto";
2
+ import { availableParallelism } from "node:os";
3
+ import { Worker } from "node:worker_threads";
4
+ import { ImageError } from "./image/bitmap.js";
5
+ import { probe, transform as transformSync } from "./image/transform.js";
6
+ export { ImageError };
7
+ export const IMAGES_PATH = "/_weft/img";
8
+ const ASPECT = /^([1-9]\d{0,2})x([1-9]\d{0,2})$/;
9
+ const SRC = /^\/(?![/\\])[^\s#\\]{0,1023}$/;
10
+ class Pool {
11
+ #size;
12
+ #queue;
13
+ #timeout;
14
+ #idle = [];
15
+ #all = 0;
16
+ #waiting = [];
17
+ #next = 1;
18
+ constructor(size, queue, timeout) {
19
+ this.#size = size;
20
+ this.#queue = queue;
21
+ this.#timeout = timeout;
22
+ }
23
+ run(src, variant, maxPixels) {
24
+ return new Promise((resolve, reject) => {
25
+ const job = { id: this.#next++, src, variant, maxPixels, resolve, reject };
26
+ const w = this.#idle.pop() ?? (this.#all < this.#size ? this.#spawn() : null);
27
+ if (w)
28
+ this.#start(w, job);
29
+ else if (this.#waiting.length >= this.#queue)
30
+ reject(new ImageBusy());
31
+ else
32
+ this.#waiting.push({ job });
33
+ });
34
+ }
35
+ #spawn() {
36
+ this.#all += 1;
37
+ const w = new Worker(new URL("./image/worker.ts", import.meta.url));
38
+ w.unref();
39
+ return w;
40
+ }
41
+ #start(w, job) {
42
+ const timer = setTimeout(() => {
43
+ done();
44
+ this.#all -= 1;
45
+ void w.terminate();
46
+ job.reject(new ImageError(`processing took longer than ${this.#timeout} ms`));
47
+ this.#drain();
48
+ }, this.#timeout);
49
+ const onMessage = (m) => {
50
+ if (m.id !== job.id)
51
+ return;
52
+ done();
53
+ if (m.ok)
54
+ job.resolve({ ...m.ok, bytes: new Uint8Array(m.ok.bytes) });
55
+ else
56
+ job.reject(new ImageError(m.error ?? "image processing failed"));
57
+ this.#idle.push(w);
58
+ this.#drain();
59
+ };
60
+ const onError = (err) => {
61
+ done();
62
+ this.#all -= 1;
63
+ job.reject(new ImageError(err.message));
64
+ this.#drain();
65
+ };
66
+ const done = () => {
67
+ clearTimeout(timer);
68
+ w.off("message", onMessage);
69
+ w.off("error", onError);
70
+ };
71
+ w.on("message", onMessage);
72
+ w.on("error", onError);
73
+ const copy = job.src.slice();
74
+ w.postMessage({ id: job.id, src: copy, variant: job.variant, maxPixels: job.maxPixels }, [copy.buffer]);
75
+ }
76
+ #drain() {
77
+ while (this.#waiting.length) {
78
+ const w = this.#idle.pop() ?? (this.#all < this.#size ? this.#spawn() : null);
79
+ if (!w)
80
+ return;
81
+ this.#start(w, this.#waiting.shift().job);
82
+ }
83
+ }
84
+ async close() {
85
+ const idle = this.#idle.splice(0);
86
+ this.#all -= idle.length;
87
+ await Promise.all(idle.map((w) => w.terminate()));
88
+ }
89
+ }
90
+ class ImageBusy extends Error {
91
+ }
92
+ const sha = (b) => createHash("sha256").update(b).digest("base64url").slice(0, 32);
93
+ export function defineImages(o = {}) {
94
+ const widths = [...(o.widths ?? [320, 640, 960, 1280, 1920, 2560])].sort((a, b) => a - b);
95
+ const aspects = o.aspects ?? [];
96
+ const formats = o.formats ?? ["auto", "jpeg", "png"];
97
+ const quality = o.quality ?? 80;
98
+ const maxPixels = o.maxPixels ?? 40_000_000;
99
+ const maxBytes = o.maxBytes ?? 30 * 1024 * 1024;
100
+ const cacheBytes = o.cacheBytes ?? 64 * 1024 * 1024;
101
+ const timeoutMs = o.timeoutMs ?? 30_000;
102
+ const workers = o.workers ?? Math.max(1, Math.min(2, availableParallelism() - 1));
103
+ const int = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
104
+ if (!widths.length || widths.length > 16 || !widths.every((w) => int(w, 16, 8192)))
105
+ throw new RangeError("defineImages: widths are 1-16 whole numbers, 16-8192");
106
+ if (aspects.length > 8 || !aspects.every((a) => ASPECT.test(a)))
107
+ throw new RangeError('defineImages: aspects are up to 8 ratios like "16x9"');
108
+ if (!formats.length || !formats.every((f) => f === "auto" || f === "jpeg" || f === "png"))
109
+ throw new RangeError('defineImages: formats are "auto", "jpeg" or "png"');
110
+ if (!int(quality, 1, 100))
111
+ throw new RangeError("defineImages: quality is 1-100");
112
+ if (!int(maxPixels, 1, 200_000_000) || !int(maxBytes, 1024, 512 * 1024 * 1024))
113
+ throw new RangeError("defineImages: maxPixels or maxBytes out of range");
114
+ if (!int(workers, 1, 32) || !int(o.queue ?? 32, 0, 10_000) || !int(timeoutMs, 1000, 600_000))
115
+ throw new RangeError("defineImages: workers, queue or timeoutMs out of range");
116
+ const pool = new Pool(workers, o.queue ?? 32, timeoutMs);
117
+ const cache = new Map();
118
+ let held = 0;
119
+ const keep = (key, c) => {
120
+ const old = cache.get(key);
121
+ if (old)
122
+ held -= old.out.bytes.byteLength;
123
+ cache.delete(key);
124
+ if (c.out.bytes.byteLength > cacheBytes / 4)
125
+ return;
126
+ cache.set(key, c);
127
+ held += c.out.bytes.byteLength;
128
+ for (const [k, v] of cache) {
129
+ if (held <= cacheBytes)
130
+ break;
131
+ cache.delete(k);
132
+ held -= v.out.bytes.byteLength;
133
+ }
134
+ };
135
+ const ratio = (a) => {
136
+ if (a === undefined)
137
+ return undefined;
138
+ const m = ASPECT.exec(a);
139
+ return [Number(m[1]), Number(m[2])];
140
+ };
141
+ const local = (src) => {
142
+ if (typeof src !== "string" || !SRC.test(src))
143
+ return false;
144
+ const u = new URL(src, "http://app.invalid");
145
+ const path = u.pathname.toLowerCase();
146
+ return u.origin === "http://app.invalid" && path !== IMAGES_PATH && !path.startsWith(`${IMAGES_PATH}/`);
147
+ };
148
+ const check = (src, width, aspect, format) => {
149
+ if (!local(src))
150
+ throw new TypeError(`images: ${JSON.stringify(src)} is not a path of this app`);
151
+ if (!widths.includes(width))
152
+ throw new TypeError(`images: width ${width} is not one of ${widths.join(", ")}`);
153
+ if (aspect !== undefined && !aspects.includes(aspect))
154
+ throw new TypeError(`images: aspect ${aspect} is not one of ${aspects.join(", ") || "(none)"}`);
155
+ if (format !== undefined && !formats.includes(format))
156
+ throw new TypeError(`images: format ${format} is not one of ${formats.join(", ")}`);
157
+ };
158
+ const url = (src, u) => {
159
+ check(src, u.width, u.aspect, u.format);
160
+ const q = new URLSearchParams({ src, w: String(u.width) });
161
+ if (u.aspect)
162
+ q.set("ar", u.aspect);
163
+ if (u.format && u.format !== formats[0])
164
+ q.set("f", u.format);
165
+ return `${IMAGES_PATH}?${q}`;
166
+ };
167
+ return {
168
+ url,
169
+ srcset(src, s = {}) {
170
+ return (s.widths ?? widths).map((w) => `${url(src, { width: w, aspect: s.aspect, format: s.format })} ${w}w`).join(", ");
171
+ },
172
+ async transform(src, v) {
173
+ if (!int(v.width, 1, 16384))
174
+ throw new RangeError("images.transform: width is 1-16384");
175
+ if (v.aspect !== undefined && !ASPECT.test(v.aspect))
176
+ throw new RangeError('images.transform: aspect is like "16x9"');
177
+ if (!probe(src))
178
+ throw new ImageError("not a JPEG or PNG image");
179
+ return pool.run(src, { width: v.width, aspect: ratio(v.aspect), focus: v.focus, format: v.format ?? "auto", quality }, maxPixels);
180
+ },
181
+ async handle(req, read) {
182
+ const q = new URL(req.url).searchParams;
183
+ const src = q.get("src") ?? "";
184
+ const width = Number(q.get("w"));
185
+ const aspect = q.get("ar") ?? undefined;
186
+ const format = (q.get("f") ?? formats[0]);
187
+ try {
188
+ check(src, width, aspect, format);
189
+ }
190
+ catch (err) {
191
+ return text(400, err.message);
192
+ }
193
+ const key = `${src}\n${width}\n${aspect ?? ""}\n${format}`;
194
+ const entry = cache.get(key);
195
+ const res = await read(src, entry?.tag.startsWith("e:") ? entry.tag.slice(2) : undefined);
196
+ let hit;
197
+ if (res.status === 304 && entry) {
198
+ hit = entry;
199
+ }
200
+ else if (res.status !== 200) {
201
+ await res.body?.cancel();
202
+ return text(res.status === 404 || res.status === 401 || res.status === 403 ? res.status : 502, "image unavailable");
203
+ }
204
+ else {
205
+ const body = await readCapped(res, maxBytes);
206
+ if (!body)
207
+ return text(413, "image too large");
208
+ const etag = res.headers.get("etag");
209
+ const tag = etag ? `e:${etag}` : `h:${sha(body)}`;
210
+ const publicTtl = /\bpublic\b/.test(res.headers.get("cache-control") ?? "");
211
+ if (entry && entry.tag === tag) {
212
+ hit = { ...entry, publicTtl };
213
+ }
214
+ else {
215
+ const kind = probe(body);
216
+ if (!kind)
217
+ return text(415, "not a JPEG or PNG image");
218
+ if (kind.width * kind.height > maxPixels)
219
+ return text(413, "image too large");
220
+ let out;
221
+ try {
222
+ out = await pool.run(body, { width, aspect: ratio(aspect), format, quality }, maxPixels);
223
+ }
224
+ catch (err) {
225
+ if (err instanceof ImageBusy)
226
+ return text(503, "busy; try again", { "retry-after": "2" });
227
+ return text(422, err.message);
228
+ }
229
+ hit = { tag, out, etag: `"${sha(out.bytes)}"`, publicTtl };
230
+ }
231
+ keep(key, hit);
232
+ }
233
+ const { publicTtl } = hit;
234
+ const headers = {
235
+ "content-type": hit.out.type,
236
+ etag: hit.etag,
237
+ "cache-control": publicTtl ? "public, max-age=86400" : "private, no-cache",
238
+ "x-content-type-options": "nosniff",
239
+ "content-security-policy": "default-src 'none'; sandbox",
240
+ };
241
+ if (!publicTtl)
242
+ headers.vary = "Cookie";
243
+ if (req.headers.get("if-none-match")?.split(",").some((t) => t.trim().replace(/^W\//, "") === hit.etag)) {
244
+ return new Response(null, { status: 304, headers });
245
+ }
246
+ return new Response(hit.out.bytes, { headers });
247
+ },
248
+ close: () => pool.close(),
249
+ };
250
+ }
251
+ function text(status, body, extra = {}) {
252
+ return new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store", ...extra } });
253
+ }
254
+ async function readCapped(res, max) {
255
+ if (Number(res.headers.get("content-length") ?? "0") > max) {
256
+ await res.body?.cancel();
257
+ return null;
258
+ }
259
+ const reader = res.body?.getReader();
260
+ if (!reader)
261
+ return new Uint8Array(0);
262
+ const parts = [];
263
+ let size = 0;
264
+ for (;;) {
265
+ const { done, value } = await reader.read();
266
+ if (done)
267
+ break;
268
+ size += value.byteLength;
269
+ if (size > max) {
270
+ void reader.cancel();
271
+ return null;
272
+ }
273
+ parts.push(value);
274
+ }
275
+ const out = new Uint8Array(size);
276
+ let at = 0;
277
+ for (const p of parts) {
278
+ out.set(p, at);
279
+ at += p.length;
280
+ }
281
+ return out;
282
+ }
283
+ export { transformSync };