@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
@@ -0,0 +1,129 @@
1
+ import { type SqlDatabase } from "@weft-framework/data";
2
+ import type { Uploads } from "./uploads.js";
3
+ export type Revealable = string | {
4
+ reveal(): string;
5
+ };
6
+ export declare class MediaError extends Error {
7
+ constructor(message: string);
8
+ }
9
+ export interface MediaProbe {
10
+ container: "mp4" | "wav";
11
+ duration: number | null;
12
+ width: number | null;
13
+ height: number | null;
14
+ video: boolean;
15
+ audio: boolean;
16
+ }
17
+ export declare function probeMedia(bytes: Uint8Array): MediaProbe | null;
18
+ export interface ProviderAsset {
19
+ asset: string;
20
+ }
21
+ export interface ProviderEvent {
22
+ asset: string;
23
+ status: "ready" | "errored" | "processing" | "deleted";
24
+ playback?: string;
25
+ duration?: number | null;
26
+ aspect?: string | null;
27
+ error?: string;
28
+ }
29
+ export interface MediaProvider {
30
+ readonly name: string;
31
+ create(input: {
32
+ source: string;
33
+ tag: string;
34
+ }): Promise<ProviderAsset>;
35
+ remove(asset: string): Promise<void>;
36
+ verify(body: string, headers: Headers, nowSeconds: number): ProviderEvent | {
37
+ ignored: true;
38
+ } | null;
39
+ links(playback: string, expires: number): {
40
+ hls: string;
41
+ poster: string;
42
+ };
43
+ }
44
+ type Fetch = typeof fetch;
45
+ export interface MuxOptions {
46
+ tokenId: Revealable;
47
+ tokenSecret: Revealable;
48
+ webhookSecret: Revealable | readonly Revealable[];
49
+ signingKeyId: string;
50
+ signingKey: Revealable;
51
+ fetch?: Fetch;
52
+ api?: string;
53
+ }
54
+ export declare function muxProvider(o: MuxOptions): MediaProvider;
55
+ export interface CloudflareStreamOptions {
56
+ accountId: string;
57
+ apiToken: Revealable;
58
+ webhookSecret: Revealable | readonly Revealable[];
59
+ customerCode: string;
60
+ signingKeyId: string;
61
+ signingKey: Revealable;
62
+ fetch?: Fetch;
63
+ api?: string;
64
+ }
65
+ export declare function cloudflareStreamProvider(o: CloudflareStreamOptions): MediaProvider;
66
+ export type MediaStatus = "processing" | "ready" | "errored";
67
+ export interface MediaRecord {
68
+ file: string;
69
+ provider: string;
70
+ asset: string;
71
+ tag: string;
72
+ status: MediaStatus;
73
+ playback: string | null;
74
+ duration: number | null;
75
+ aspect: string | null;
76
+ error: string | null;
77
+ created: number;
78
+ }
79
+ export interface MediaStore {
80
+ put(r: MediaRecord): void | Promise<void>;
81
+ get(file: string): MediaRecord | null | Promise<MediaRecord | null>;
82
+ byAsset(provider: string, asset: string): MediaRecord | null | Promise<MediaRecord | null>;
83
+ remove(file: string): void | Promise<void>;
84
+ }
85
+ export declare class MemoryMediaStore implements MediaStore {
86
+ #private;
87
+ put(r: MediaRecord): void;
88
+ get(file: string): MediaRecord | null;
89
+ byAsset(provider: string, asset: string): MediaRecord | null;
90
+ remove(file: string): void;
91
+ }
92
+ export declare class SqlMediaStore implements MediaStore {
93
+ #private;
94
+ constructor(db: SqlDatabase, table?: string);
95
+ put(r: MediaRecord): void;
96
+ get(file: string): MediaRecord | null;
97
+ byAsset(provider: string, asset: string): MediaRecord | null;
98
+ remove(file: string): void;
99
+ }
100
+ export interface MediaOptions {
101
+ uploads: Uploads<string>;
102
+ provider: MediaProvider;
103
+ store: MediaStore;
104
+ origin: string;
105
+ onReady?: (r: MediaRecord) => void | Promise<void>;
106
+ onError?: (err: unknown) => void;
107
+ now?: () => number;
108
+ }
109
+ export interface Playback {
110
+ status: MediaStatus;
111
+ hls: string | null;
112
+ poster: string | null;
113
+ duration: number | null;
114
+ aspect: string | null;
115
+ expires: number | null;
116
+ }
117
+ export declare class Media {
118
+ #private;
119
+ constructor(o: MediaOptions);
120
+ process(file: string): Promise<MediaRecord>;
121
+ webhook(req: Request): Promise<Response>;
122
+ playback(file: string | null | undefined, o?: {
123
+ ttlSeconds?: number;
124
+ }): Promise<Playback | null>;
125
+ remove(file: string): Promise<boolean>;
126
+ track(): () => void;
127
+ }
128
+ export declare function defineMedia(o: MediaOptions): Media;
129
+ export {};
package/dist/media.js ADDED
@@ -0,0 +1,470 @@
1
+ import { createPrivateKey, sign as rsaSign, timingSafeEqual, createHmac, randomBytes } from "node:crypto";
2
+ import { onFileRelease } from "@weft-framework/data";
3
+ const reveal = (v) => (typeof v === "string" ? v : v.reveal());
4
+ export class MediaError extends Error {
5
+ constructor(message) {
6
+ super(message);
7
+ this.name = "MediaError";
8
+ }
9
+ }
10
+ export function probeMedia(bytes) {
11
+ if (!(bytes instanceof Uint8Array))
12
+ throw new TypeError("probeMedia: bytes is a Uint8Array");
13
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14
+ const tag = (at) => String.fromCharCode(bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]);
15
+ if (bytes.length >= 12 && tag(0) === "RIFF" && tag(8) === "WAVE")
16
+ return wav(bytes, v, tag);
17
+ if (bytes.length >= 8 && (tag(4) === "ftyp" || tag(4) === "moov" || tag(4) === "mdat" || tag(4) === "wide"))
18
+ return mp4(bytes, v, tag);
19
+ return null;
20
+ }
21
+ function wav(bytes, v, tag) {
22
+ let byteRate = 0;
23
+ let data = -1;
24
+ for (let p = 12, n = 0; p + 8 <= bytes.length && n < 1000; n++) {
25
+ const size = v.getUint32(p + 4, true);
26
+ if (tag(p) === "fmt " && p + 20 <= bytes.length)
27
+ byteRate = v.getUint32(p + 16, true);
28
+ if (tag(p) === "data") {
29
+ data = size;
30
+ break;
31
+ }
32
+ p += 8 + size + (size & 1);
33
+ }
34
+ if (data < 0)
35
+ return null;
36
+ return { container: "wav", duration: byteRate > 0 ? round(data / byteRate) : null, width: null, height: null, video: false, audio: true };
37
+ }
38
+ function mp4(bytes, v, tag) {
39
+ const out = { container: "mp4", duration: null, width: null, height: null, video: false, audio: false };
40
+ let boxes = 0;
41
+ const walk = (from, to, fn) => {
42
+ let p = from;
43
+ while (p + 8 <= to) {
44
+ if (++boxes > 10_000)
45
+ return false;
46
+ let size = v.getUint32(p);
47
+ let head = 8;
48
+ if (size === 1) {
49
+ if (p + 16 > to)
50
+ return false;
51
+ const big = v.getBigUint64(p + 8);
52
+ if (big > BigInt(Number.MAX_SAFE_INTEGER))
53
+ return false;
54
+ size = Number(big);
55
+ head = 16;
56
+ }
57
+ else if (size === 0)
58
+ size = to - p;
59
+ if (size < head)
60
+ return false;
61
+ const end = p + size;
62
+ if (end > to) {
63
+ if (to === bytes.length)
64
+ return true;
65
+ return false;
66
+ }
67
+ fn(tag(p + 4), p + head, end);
68
+ p = end;
69
+ }
70
+ return true;
71
+ };
72
+ let found = false;
73
+ let ok = true;
74
+ const top = walk(0, bytes.length, (type, s, e) => {
75
+ if (type !== "moov")
76
+ return;
77
+ found = true;
78
+ ok &&= walk(s, e, (t, s2, e2) => {
79
+ if (t === "mvhd" && e2 - s2 >= 32) {
80
+ const ver = bytes[s2];
81
+ const scale = v.getUint32(s2 + (ver === 1 ? 20 : 12));
82
+ const dur = ver === 1 ? Number(v.getBigUint64(s2 + 24)) : v.getUint32(s2 + 16);
83
+ if (scale > 0 && dur !== 0xffffffff)
84
+ out.duration = round(dur / scale);
85
+ }
86
+ if (t !== "trak")
87
+ return;
88
+ let w = 0;
89
+ let h = 0;
90
+ let kind = "";
91
+ ok &&= walk(s2, e2, (t3, s3, e3) => {
92
+ if (t3 === "tkhd" && e3 - s3 >= 84) {
93
+ w = v.getUint32(e3 - 8) / 65536;
94
+ h = v.getUint32(e3 - 4) / 65536;
95
+ }
96
+ if (t3 === "mdia") {
97
+ ok &&= walk(s3, e3, (t4, s4, e4) => {
98
+ if (t4 === "hdlr" && e4 - s4 >= 12)
99
+ kind = tag(s4 + 8);
100
+ });
101
+ }
102
+ });
103
+ if (kind === "vide") {
104
+ out.video = true;
105
+ if (out.width === null && w > 0 && h > 0)
106
+ [out.width, out.height] = [Math.round(w), Math.round(h)];
107
+ }
108
+ else if (kind === "soun")
109
+ out.audio = true;
110
+ });
111
+ });
112
+ return top && ok && found ? out : null;
113
+ }
114
+ const round = (s) => Math.round(s * 1000) / 1000;
115
+ function hmacHeader(body, header, keys, secrets, now) {
116
+ if (typeof header !== "string" || header.length > 4096)
117
+ return false;
118
+ let t = NaN;
119
+ const sigs = [];
120
+ for (const part of header.split(",")) {
121
+ const eq = part.indexOf("=");
122
+ if (eq < 0)
123
+ continue;
124
+ const k = part.slice(0, eq).trim();
125
+ const val = part.slice(eq + 1).trim();
126
+ if (k === keys.time && /^\d{1,12}$/.test(val))
127
+ t = Number(val);
128
+ else if (k === keys.sig && /^[0-9a-f]{64}$/i.test(val))
129
+ sigs.push(val.toLowerCase());
130
+ }
131
+ if (!Number.isFinite(t) || sigs.length === 0 || Math.abs(now - t) > 300)
132
+ return false;
133
+ let ok = false;
134
+ for (const secret of secrets) {
135
+ const want = Buffer.from(createHmac("sha256", secret).update(`${t}.${body}`).digest("hex"));
136
+ for (const s of sigs)
137
+ ok = timingSafeEqual(Buffer.from(s), want) || ok;
138
+ }
139
+ return ok;
140
+ }
141
+ const b64url = (b) => Buffer.from(b).toString("base64url");
142
+ function jwt(key, kid, claims) {
143
+ let pem = reveal(key).trim();
144
+ if (!pem.startsWith("-----BEGIN"))
145
+ pem = Buffer.from(pem, "base64").toString("utf8");
146
+ const head = b64url(JSON.stringify({ alg: "RS256", typ: "JWT", kid }));
147
+ const body = b64url(JSON.stringify(claims));
148
+ const sig = rsaSign("sha256", Buffer.from(`${head}.${body}`), createPrivateKey(pem));
149
+ return `${head}.${body}.${b64url(sig)}`;
150
+ }
151
+ function secretsOf(v, what) {
152
+ const list = (Array.isArray(v) ? v : [v]).map((x) => reveal(x));
153
+ if (list.length === 0 || list.some((s) => typeof s !== "string" || s.length < 16))
154
+ throw new MediaError(`${what}: the webhook secret is the provider's signing secret`);
155
+ return list;
156
+ }
157
+ function checkKey(key, what) {
158
+ try {
159
+ jwt(key, "check", { sub: "check" });
160
+ }
161
+ catch {
162
+ throw new MediaError(`${what}: signingKey is an RSA private key (PEM, or base64 of the PEM)`);
163
+ }
164
+ }
165
+ async function call(f, what, url, init) {
166
+ const res = await f(url, { ...init, signal: AbortSignal.timeout(15_000) });
167
+ const text = await res.text();
168
+ if (init.method === "DELETE" && res.status === 404)
169
+ return null;
170
+ if (!res.ok)
171
+ throw new MediaError(`${what}: ${res.status} ${text.slice(0, 200)}`);
172
+ try {
173
+ return text ? JSON.parse(text) : null;
174
+ }
175
+ catch {
176
+ throw new MediaError(`${what}: the reply is not JSON`);
177
+ }
178
+ }
179
+ export function muxProvider(o) {
180
+ const secrets = secretsOf(o.webhookSecret, "muxProvider");
181
+ if (typeof o.signingKeyId !== "string" || !o.signingKeyId)
182
+ throw new MediaError("muxProvider: signingKeyId is the signing key's id");
183
+ checkKey(o.signingKey, "muxProvider");
184
+ const f = o.fetch ?? fetch;
185
+ const api = o.api ?? "https://api.mux.com";
186
+ const auth = () => `Basic ${Buffer.from(`${reveal(o.tokenId)}:${reveal(o.tokenSecret)}`).toString("base64")}`;
187
+ return {
188
+ name: "mux",
189
+ async create({ source, tag }) {
190
+ const r = (await call(f, "mux", `${api}/video/v1/assets`, {
191
+ method: "POST",
192
+ headers: { authorization: auth(), "content-type": "application/json" },
193
+ body: JSON.stringify({ inputs: [{ url: source }], playback_policies: ["signed"], passthrough: tag, video_quality: "basic" }),
194
+ }));
195
+ if (typeof r?.data?.id !== "string")
196
+ throw new MediaError("mux: no asset id in the reply");
197
+ return { asset: r.data.id };
198
+ },
199
+ async remove(asset) {
200
+ await call(f, "mux", `${api}/video/v1/assets/${encodeURIComponent(asset)}`, { method: "DELETE", headers: { authorization: auth() } });
201
+ },
202
+ verify(body, headers, now) {
203
+ if (!hmacHeader(body, headers.get("mux-signature"), { time: "t", sig: "v1" }, secrets, now))
204
+ return null;
205
+ const e = JSON.parse(body);
206
+ const d = e.data ?? {};
207
+ if (typeof d.id !== "string")
208
+ return { ignored: true };
209
+ switch (e.type) {
210
+ case "video.asset.ready": {
211
+ const pid = d.playback_ids?.find((p) => p.policy === "signed")?.id;
212
+ if (!pid)
213
+ return { asset: d.id, status: "errored", error: "no signed playback id" };
214
+ return { asset: d.id, status: "ready", playback: pid, duration: typeof d.duration === "number" ? d.duration : null, aspect: typeof d.aspect_ratio === "string" ? d.aspect_ratio : null };
215
+ }
216
+ case "video.asset.errored":
217
+ return { asset: d.id, status: "errored", error: String(d.errors?.messages?.join("; ") ?? "failed") };
218
+ case "video.asset.deleted":
219
+ return { asset: d.id, status: "deleted" };
220
+ default:
221
+ return { ignored: true };
222
+ }
223
+ },
224
+ links(playback, expires) {
225
+ const tok = (aud) => jwt(o.signingKey, o.signingKeyId, { sub: playback, aud, exp: expires, kid: o.signingKeyId });
226
+ const id = encodeURIComponent(playback);
227
+ return { hls: `https://stream.mux.com/${id}.m3u8?token=${tok("v")}`, poster: `https://image.mux.com/${id}/thumbnail.jpg?token=${tok("t")}` };
228
+ },
229
+ };
230
+ }
231
+ export function cloudflareStreamProvider(o) {
232
+ const secrets = secretsOf(o.webhookSecret, "cloudflareStreamProvider");
233
+ for (const k of ["accountId", "customerCode", "signingKeyId"]) {
234
+ if (typeof o[k] !== "string" || !/^[A-Za-z0-9_-]+$/.test(o[k]))
235
+ throw new MediaError(`cloudflareStreamProvider: ${k} is required`);
236
+ }
237
+ checkKey(o.signingKey, "cloudflareStreamProvider");
238
+ const f = o.fetch ?? fetch;
239
+ const base = `${o.api ?? "https://api.cloudflare.com/client/v4"}/accounts/${o.accountId}/stream`;
240
+ const auth = () => `Bearer ${reveal(o.apiToken)}`;
241
+ return {
242
+ name: "cloudflare",
243
+ async create({ source, tag }) {
244
+ const r = (await call(f, "cloudflare", `${base}/copy`, {
245
+ method: "POST",
246
+ headers: { authorization: auth(), "content-type": "application/json" },
247
+ body: JSON.stringify({ url: source, requireSignedURLs: true, meta: { weft: tag } }),
248
+ }));
249
+ if (typeof r?.result?.uid !== "string")
250
+ throw new MediaError("cloudflare: no video uid in the reply");
251
+ return { asset: r.result.uid };
252
+ },
253
+ async remove(asset) {
254
+ await call(f, "cloudflare", `${base}/${encodeURIComponent(asset)}`, { method: "DELETE", headers: { authorization: auth() } });
255
+ },
256
+ verify(body, headers, now) {
257
+ if (!hmacHeader(body, headers.get("webhook-signature"), { time: "time", sig: "sig1" }, secrets, now))
258
+ return null;
259
+ const d = JSON.parse(body);
260
+ if (typeof d.uid !== "string")
261
+ return { ignored: true };
262
+ const state = d.status?.state;
263
+ if (d.readyToStream === true || state === "ready") {
264
+ const w = d.input?.width;
265
+ const h = d.input?.height;
266
+ return { asset: d.uid, status: "ready", playback: d.uid, duration: typeof d.duration === "number" && d.duration >= 0 ? d.duration : null, aspect: w > 0 && h > 0 ? `${w}:${h}` : null };
267
+ }
268
+ if (state === "error")
269
+ return { asset: d.uid, status: "errored", error: String(d.status?.errorReasonText ?? d.status?.errorReasonCode ?? "failed") };
270
+ return { ignored: true };
271
+ },
272
+ links(playback, expires) {
273
+ const tok = jwt(o.signingKey, o.signingKeyId, { sub: playback, kid: o.signingKeyId, exp: expires });
274
+ const host = `https://customer-${o.customerCode}.cloudflarestream.com/${tok}`;
275
+ return { hls: `${host}/manifest/video.m3u8`, poster: `${host}/thumbnails/thumbnail.jpg` };
276
+ },
277
+ };
278
+ }
279
+ export class MemoryMediaStore {
280
+ #rows = new Map();
281
+ put(r) {
282
+ this.#rows.set(r.file, { ...r });
283
+ }
284
+ get(file) {
285
+ const r = this.#rows.get(file);
286
+ return r ? { ...r } : null;
287
+ }
288
+ byAsset(provider, asset) {
289
+ for (const r of this.#rows.values())
290
+ if (r.provider === provider && r.asset === asset)
291
+ return { ...r };
292
+ return null;
293
+ }
294
+ remove(file) {
295
+ this.#rows.delete(file);
296
+ }
297
+ }
298
+ export class SqlMediaStore {
299
+ #db;
300
+ #t;
301
+ constructor(db, table = "weft_media") {
302
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
303
+ throw new Error(`@weft-framework/server: not a valid table name: ${table}`);
304
+ this.#db = db;
305
+ this.#t = `"${table}"`;
306
+ db.exec(`CREATE TABLE IF NOT EXISTS ${this.#t} (file TEXT PRIMARY KEY NOT NULL, provider TEXT NOT NULL, asset TEXT NOT NULL, ` +
307
+ `tag TEXT NOT NULL, status TEXT NOT NULL, playback TEXT, duration REAL, aspect TEXT, error TEXT, created INTEGER NOT NULL)`);
308
+ db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS "${table}_asset" ON ${this.#t} (provider, asset)`);
309
+ }
310
+ put(r) {
311
+ this.#db
312
+ .prepare(`INSERT OR REPLACE INTO ${this.#t} (file, provider, asset, tag, status, playback, duration, aspect, error, created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
313
+ .run(r.file, r.provider, r.asset, r.tag, r.status, r.playback, r.duration, r.aspect, r.error, r.created);
314
+ }
315
+ static #row(x) {
316
+ if (!x)
317
+ return null;
318
+ const opt = (v) => (v === null || v === undefined ? null : String(v));
319
+ return {
320
+ file: String(x.file),
321
+ provider: String(x.provider),
322
+ asset: String(x.asset),
323
+ tag: String(x.tag),
324
+ status: String(x.status),
325
+ playback: opt(x.playback),
326
+ duration: x.duration === null || x.duration === undefined ? null : Number(x.duration),
327
+ aspect: opt(x.aspect),
328
+ error: opt(x.error),
329
+ created: Number(x.created),
330
+ };
331
+ }
332
+ get(file) {
333
+ return SqlMediaStore.#row(this.#db.prepare(`SELECT * FROM ${this.#t} WHERE file = ?`).all(file)[0]);
334
+ }
335
+ byAsset(provider, asset) {
336
+ return SqlMediaStore.#row(this.#db.prepare(`SELECT * FROM ${this.#t} WHERE provider = ? AND asset = ?`).all(provider, asset)[0]);
337
+ }
338
+ remove(file) {
339
+ this.#db.prepare(`DELETE FROM ${this.#t} WHERE file = ?`).run(file);
340
+ }
341
+ }
342
+ export class Media {
343
+ #o;
344
+ #stopTracking = null;
345
+ constructor(o) {
346
+ if (!o || !o.uploads || !o.provider || !o.store)
347
+ throw new MediaError("defineMedia: needs uploads, provider and store");
348
+ let origin;
349
+ try {
350
+ origin = new URL(o.origin);
351
+ }
352
+ catch {
353
+ throw new MediaError("defineMedia: origin is the app's public URL (https://...)");
354
+ }
355
+ if (origin.protocol !== "https:")
356
+ throw new MediaError("defineMedia: origin must be https (the provider fetches files from it)");
357
+ this.#o = { onError: () => { }, now: Date.now, ...o, origin: origin.origin };
358
+ }
359
+ async process(file) {
360
+ const existing = await this.#o.store.get(file);
361
+ if (existing && existing.status !== "errored")
362
+ return existing;
363
+ const info = await this.#o.uploads.info(file);
364
+ if (!info)
365
+ throw new MediaError("process: no such ready file");
366
+ if (!/^(video|audio)\//.test(info.type))
367
+ throw new MediaError(`process: ${info.type} is not video or audio`);
368
+ const link = await this.#o.uploads.url(file, { ttlSeconds: 3600 });
369
+ if (link === null)
370
+ throw new MediaError("process: no such ready file");
371
+ const source = new URL(link, this.#o.origin).href;
372
+ const tag = randomBytes(12).toString("base64url");
373
+ const { asset } = await this.#o.provider.create({ source, tag });
374
+ const r = {
375
+ file,
376
+ provider: this.#o.provider.name,
377
+ asset,
378
+ tag,
379
+ status: "processing",
380
+ playback: null,
381
+ duration: null,
382
+ aspect: null,
383
+ error: null,
384
+ created: this.#o.now(),
385
+ };
386
+ await this.#o.store.put(r);
387
+ if (existing && existing.asset !== asset)
388
+ await this.#o.provider.remove(existing.asset).catch(this.#o.onError);
389
+ return r;
390
+ }
391
+ async webhook(req) {
392
+ if (req.method !== "POST")
393
+ return new Response("Method not allowed", { status: 405 });
394
+ const declared = Number(req.headers.get("content-length") ?? "0");
395
+ if (declared > 1_000_000)
396
+ return new Response("Too large", { status: 413 });
397
+ const body = await req.text();
398
+ if (body.length > 1_000_000)
399
+ return new Response("Too large", { status: 413 });
400
+ let e;
401
+ try {
402
+ e = this.#o.provider.verify(body, req.headers, Math.floor(this.#o.now() / 1000));
403
+ }
404
+ catch {
405
+ e = null;
406
+ }
407
+ if (e === null)
408
+ return new Response("Bad signature", { status: 400 });
409
+ if ("ignored" in e)
410
+ return new Response("ok");
411
+ const r = await this.#o.store.byAsset(this.#o.provider.name, e.asset);
412
+ if (!r)
413
+ return new Response("ok");
414
+ if (e.status === "deleted") {
415
+ await this.#o.store.remove(r.file);
416
+ return new Response("ok");
417
+ }
418
+ if (e.status === "processing" || r.status === e.status)
419
+ return new Response("ok");
420
+ r.status = e.status;
421
+ r.playback = e.playback ?? r.playback;
422
+ r.duration = e.duration ?? r.duration;
423
+ r.aspect = e.aspect ?? r.aspect;
424
+ r.error = e.status === "errored" ? (e.error ?? "failed").slice(0, 500) : null;
425
+ await this.#o.store.put(r);
426
+ try {
427
+ await this.#o.onReady?.(r);
428
+ }
429
+ catch (err) {
430
+ this.#o.onError(err);
431
+ }
432
+ return new Response("ok");
433
+ }
434
+ async playback(file, o = {}) {
435
+ if (typeof file !== "string")
436
+ return null;
437
+ const r = await this.#o.store.get(file);
438
+ if (!r)
439
+ return null;
440
+ const ttl = o.ttlSeconds ?? 3600;
441
+ if (!Number.isInteger(ttl) || ttl < 60 || ttl > 86_400)
442
+ throw new MediaError("playback: ttlSeconds is 60 seconds to 1 day");
443
+ if (r.status !== "ready" || r.playback === null)
444
+ return { status: r.status, hls: null, poster: null, duration: r.duration, aspect: r.aspect, expires: null };
445
+ const expires = Math.floor(this.#o.now() / 1000) + ttl;
446
+ return { status: "ready", ...this.#o.provider.links(r.playback, expires), duration: r.duration, aspect: r.aspect, expires };
447
+ }
448
+ async remove(file) {
449
+ const r = await this.#o.store.get(file);
450
+ if (!r)
451
+ return false;
452
+ await this.#o.provider.remove(r.asset);
453
+ await this.#o.store.remove(file);
454
+ return true;
455
+ }
456
+ track() {
457
+ this.#stopTracking ??= onFileRelease((id) => {
458
+ this.remove(id).catch(this.#o.onError);
459
+ });
460
+ return () => {
461
+ this.#stopTracking?.();
462
+ this.#stopTracking = null;
463
+ };
464
+ }
465
+ }
466
+ export function defineMedia(o) {
467
+ const m = new Media(o);
468
+ m.track();
469
+ return m;
470
+ }
package/dist/meta.d.ts ADDED
@@ -0,0 +1,54 @@
1
+ export interface MetaTag {
2
+ name?: string;
3
+ property?: string;
4
+ httpEquiv?: string;
5
+ content: string;
6
+ }
7
+ export interface LinkTag {
8
+ rel: string;
9
+ href: string;
10
+ type?: string;
11
+ sizes?: string;
12
+ hreflang?: string;
13
+ media?: string;
14
+ }
15
+ export interface OpenGraph {
16
+ title?: string;
17
+ description?: string;
18
+ type?: string;
19
+ url?: string;
20
+ image?: string;
21
+ imageAlt?: string;
22
+ siteName?: string;
23
+ locale?: string;
24
+ }
25
+ export interface TwitterCard {
26
+ card?: "summary" | "summary_large_image" | "app" | "player";
27
+ site?: string;
28
+ creator?: string;
29
+ title?: string;
30
+ description?: string;
31
+ image?: string;
32
+ }
33
+ export interface PageMeta {
34
+ title?: string;
35
+ titleTemplate?: string;
36
+ description?: string;
37
+ canonical?: string;
38
+ robots?: string;
39
+ lang?: string;
40
+ themeColor?: string;
41
+ openGraph?: OpenGraph;
42
+ twitter?: TwitterCard;
43
+ jsonLd?: unknown;
44
+ tags?: MetaTag[];
45
+ links?: LinkTag[];
46
+ }
47
+ export declare function mergeMeta(...layers: (PageMeta | undefined)[]): PageMeta;
48
+ export declare function applySite(meta: PageMeta, siteUrl: string | undefined): PageMeta;
49
+ export declare function resolveTitle(meta: PageMeta): string;
50
+ export declare function resolveLang(meta: PageMeta): string;
51
+ export declare function scriptJson(value: unknown): string;
52
+ export declare function renderMeta(meta: PageMeta, opts?: {
53
+ nonce?: string;
54
+ }): string;