payload-video-streaming 0.0.0-stage → 0.2.0-beta.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 (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +289 -2
  3. package/dist/access.d.ts +35 -0
  4. package/dist/access.js +53 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/bin/args.d.ts +37 -0
  7. package/dist/bin/args.js +157 -0
  8. package/dist/bin/args.js.map +1 -0
  9. package/dist/bin/cli.d.ts +2 -0
  10. package/dist/bin/cli.js +25 -0
  11. package/dist/bin/cli.js.map +1 -0
  12. package/dist/bin/fake.d.ts +2 -0
  13. package/dist/bin/fake.js +14 -0
  14. package/dist/bin/fake.js.map +1 -0
  15. package/dist/bin/migrate.d.ts +5 -0
  16. package/dist/bin/migrate.js +47 -0
  17. package/dist/bin/migrate.js.map +1 -0
  18. package/dist/bin/runFake.d.ts +2 -0
  19. package/dist/bin/runFake.js +24 -0
  20. package/dist/bin/runFake.js.map +1 -0
  21. package/dist/bin/webhooks.d.ts +15 -0
  22. package/dist/bin/webhooks.js +149 -0
  23. package/dist/bin/webhooks.js.map +1 -0
  24. package/dist/blocks.d.ts +42 -0
  25. package/dist/blocks.js +150 -0
  26. package/dist/blocks.js.map +1 -0
  27. package/dist/collection.d.ts +10 -0
  28. package/dist/collection.js +697 -0
  29. package/dist/collection.js.map +1 -0
  30. package/dist/components/BulkUploader.d.ts +16 -0
  31. package/dist/components/BulkUploader.js +226 -0
  32. package/dist/components/BulkUploader.js.map +1 -0
  33. package/dist/components/CaptionsManager.d.ts +9 -0
  34. package/dist/components/CaptionsManager.js +174 -0
  35. package/dist/components/CaptionsManager.js.map +1 -0
  36. package/dist/components/DownloadsPanel.d.ts +9 -0
  37. package/dist/components/DownloadsPanel.js +147 -0
  38. package/dist/components/DownloadsPanel.js.map +1 -0
  39. package/dist/components/ListUploader.d.ts +11 -0
  40. package/dist/components/ListUploader.js +138 -0
  41. package/dist/components/ListUploader.js.map +1 -0
  42. package/dist/components/ThumbnailCell.d.ts +5 -0
  43. package/dist/components/ThumbnailCell.js +28 -0
  44. package/dist/components/ThumbnailCell.js.map +1 -0
  45. package/dist/components/Uploader.d.ts +22 -0
  46. package/dist/components/Uploader.js +171 -0
  47. package/dist/components/Uploader.js.map +1 -0
  48. package/dist/components/VideoBlockLabel.d.ts +11 -0
  49. package/dist/components/VideoBlockLabel.js +86 -0
  50. package/dist/components/VideoBlockLabel.js.map +1 -0
  51. package/dist/components/VideoField.d.ts +17 -0
  52. package/dist/components/VideoField.js +422 -0
  53. package/dist/components/VideoField.js.map +1 -0
  54. package/dist/components/VideoRelationshipField.d.ts +16 -0
  55. package/dist/components/VideoRelationshipField.js +106 -0
  56. package/dist/components/VideoRelationshipField.js.map +1 -0
  57. package/dist/components/WebhookStatusPanel.d.ts +6 -0
  58. package/dist/components/WebhookStatusPanel.js +143 -0
  59. package/dist/components/WebhookStatusPanel.js.map +1 -0
  60. package/dist/components/api.d.ts +52 -0
  61. package/dist/components/api.js +76 -0
  62. package/dist/components/api.js.map +1 -0
  63. package/dist/components/chunkedUpload.d.ts +28 -0
  64. package/dist/components/chunkedUpload.js +49 -0
  65. package/dist/components/chunkedUpload.js.map +1 -0
  66. package/dist/components/styles.d.ts +95 -0
  67. package/dist/components/styles.js +148 -0
  68. package/dist/components/styles.js.map +1 -0
  69. package/dist/components/uploadFile.d.ts +30 -0
  70. package/dist/components/uploadFile.js +140 -0
  71. package/dist/components/uploadFile.js.map +1 -0
  72. package/dist/components/usePluginApi.d.ts +46 -0
  73. package/dist/components/usePluginApi.js +21 -0
  74. package/dist/components/usePluginApi.js.map +1 -0
  75. package/dist/components/useUploadQueue.d.ts +35 -0
  76. package/dist/components/useUploadQueue.js +135 -0
  77. package/dist/components/useUploadQueue.js.map +1 -0
  78. package/dist/components/useVideoUpload.d.ts +33 -0
  79. package/dist/components/useVideoUpload.js +87 -0
  80. package/dist/components/useVideoUpload.js.map +1 -0
  81. package/dist/core/errors.d.ts +27 -0
  82. package/dist/core/errors.js +29 -0
  83. package/dist/core/errors.js.map +1 -0
  84. package/dist/core/provider.d.ts +347 -0
  85. package/dist/core/provider.js +13 -0
  86. package/dist/core/provider.js.map +1 -0
  87. package/dist/core/registry.d.ts +17 -0
  88. package/dist/core/registry.js +110 -0
  89. package/dist/core/registry.js.map +1 -0
  90. package/dist/core/status.d.ts +15 -0
  91. package/dist/core/status.js +29 -0
  92. package/dist/core/status.js.map +1 -0
  93. package/dist/endpoints/index.d.ts +3 -0
  94. package/dist/endpoints/index.js +500 -0
  95. package/dist/endpoints/index.js.map +1 -0
  96. package/dist/env.d.ts +40 -0
  97. package/dist/env.js +105 -0
  98. package/dist/env.js.map +1 -0
  99. package/dist/exports/bunny.d.ts +16 -0
  100. package/dist/exports/bunny.js +13 -0
  101. package/dist/exports/bunny.js.map +1 -0
  102. package/dist/exports/client.d.ts +22 -0
  103. package/dist/exports/client.js +18 -0
  104. package/dist/exports/client.js.map +1 -0
  105. package/dist/exports/cloudflare.d.ts +18 -0
  106. package/dist/exports/cloudflare.js +15 -0
  107. package/dist/exports/cloudflare.js.map +1 -0
  108. package/dist/exports/mux.d.ts +18 -0
  109. package/dist/exports/mux.js +15 -0
  110. package/dist/exports/mux.js.map +1 -0
  111. package/dist/exports/react.d.ts +25 -0
  112. package/dist/exports/react.js +18 -0
  113. package/dist/exports/react.js.map +1 -0
  114. package/dist/exports/rsc.d.ts +1 -0
  115. package/dist/exports/rsc.js +4 -0
  116. package/dist/exports/rsc.js.map +1 -0
  117. package/dist/exports/testing.d.ts +13 -0
  118. package/dist/exports/testing.js +9 -0
  119. package/dist/exports/testing.js.map +1 -0
  120. package/dist/fields.d.ts +22 -0
  121. package/dist/fields.js +73 -0
  122. package/dist/fields.js.map +1 -0
  123. package/dist/frontend/ClientVideo.d.ts +14 -0
  124. package/dist/frontend/ClientVideo.js +43 -0
  125. package/dist/frontend/ClientVideo.js.map +1 -0
  126. package/dist/frontend/Video.d.ts +32 -0
  127. package/dist/frontend/Video.js +73 -0
  128. package/dist/frontend/Video.js.map +1 -0
  129. package/dist/frontend/VideoIframe.d.ts +35 -0
  130. package/dist/frontend/VideoIframe.js +60 -0
  131. package/dist/frontend/VideoIframe.js.map +1 -0
  132. package/dist/frontend/VideoUploader.d.ts +65 -0
  133. package/dist/frontend/VideoUploader.js +260 -0
  134. package/dist/frontend/VideoUploader.js.map +1 -0
  135. package/dist/frontend/constants.d.ts +10 -0
  136. package/dist/frontend/constants.js +10 -0
  137. package/dist/frontend/constants.js.map +1 -0
  138. package/dist/frontend/converters.d.ts +25 -0
  139. package/dist/frontend/converters.js +24 -0
  140. package/dist/frontend/converters.js.map +1 -0
  141. package/dist/frontend/source.d.ts +80 -0
  142. package/dist/frontend/source.js +159 -0
  143. package/dist/frontend/source.js.map +1 -0
  144. package/dist/frontend/useVideoSource.d.ts +27 -0
  145. package/dist/frontend/useVideoSource.js +108 -0
  146. package/dist/frontend/useVideoSource.js.map +1 -0
  147. package/dist/frontend/useVideoStatus.d.ts +26 -0
  148. package/dist/frontend/useVideoStatus.js +68 -0
  149. package/dist/frontend/useVideoStatus.js.map +1 -0
  150. package/dist/index.d.ts +21 -0
  151. package/dist/index.js +15 -0
  152. package/dist/index.js.map +1 -0
  153. package/dist/migrate/cfStream.d.ts +108 -0
  154. package/dist/migrate/cfStream.js +418 -0
  155. package/dist/migrate/cfStream.js.map +1 -0
  156. package/dist/options.d.ts +9 -0
  157. package/dist/options.js +153 -0
  158. package/dist/options.js.map +1 -0
  159. package/dist/plugin.d.ts +9 -0
  160. package/dist/plugin.js +177 -0
  161. package/dist/plugin.js.map +1 -0
  162. package/dist/providers/bunny/client.d.ts +78 -0
  163. package/dist/providers/bunny/client.js +231 -0
  164. package/dist/providers/bunny/client.js.map +1 -0
  165. package/dist/providers/bunny/env.d.ts +18 -0
  166. package/dist/providers/bunny/env.js +31 -0
  167. package/dist/providers/bunny/env.js.map +1 -0
  168. package/dist/providers/bunny/mapping.d.ts +39 -0
  169. package/dist/providers/bunny/mapping.js +123 -0
  170. package/dist/providers/bunny/mapping.js.map +1 -0
  171. package/dist/providers/bunny/options.d.ts +92 -0
  172. package/dist/providers/bunny/options.js +85 -0
  173. package/dist/providers/bunny/options.js.map +1 -0
  174. package/dist/providers/bunny/provider.d.ts +70 -0
  175. package/dist/providers/bunny/provider.js +480 -0
  176. package/dist/providers/bunny/provider.js.map +1 -0
  177. package/dist/providers/bunny/signing.d.ts +61 -0
  178. package/dist/providers/bunny/signing.js +144 -0
  179. package/dist/providers/bunny/signing.js.map +1 -0
  180. package/dist/providers/bunny/types.d.ts +153 -0
  181. package/dist/providers/bunny/types.js +64 -0
  182. package/dist/providers/bunny/types.js.map +1 -0
  183. package/dist/providers/bunny/urls.d.ts +49 -0
  184. package/dist/providers/bunny/urls.js +70 -0
  185. package/dist/providers/bunny/urls.js.map +1 -0
  186. package/dist/providers/bunny/webhook.d.ts +32 -0
  187. package/dist/providers/bunny/webhook.js +75 -0
  188. package/dist/providers/bunny/webhook.js.map +1 -0
  189. package/dist/providers/cloudflare/client.d.ts +93 -0
  190. package/dist/providers/cloudflare/client.js +436 -0
  191. package/dist/providers/cloudflare/client.js.map +1 -0
  192. package/dist/providers/cloudflare/env.d.ts +22 -0
  193. package/dist/providers/cloudflare/env.js +57 -0
  194. package/dist/providers/cloudflare/env.js.map +1 -0
  195. package/dist/providers/cloudflare/mapping.d.ts +15 -0
  196. package/dist/providers/cloudflare/mapping.js +95 -0
  197. package/dist/providers/cloudflare/mapping.js.map +1 -0
  198. package/dist/providers/cloudflare/options.d.ts +104 -0
  199. package/dist/providers/cloudflare/options.js +91 -0
  200. package/dist/providers/cloudflare/options.js.map +1 -0
  201. package/dist/providers/cloudflare/provider.d.ts +63 -0
  202. package/dist/providers/cloudflare/provider.js +445 -0
  203. package/dist/providers/cloudflare/provider.js.map +1 -0
  204. package/dist/providers/cloudflare/signing.d.ts +41 -0
  205. package/dist/providers/cloudflare/signing.js +97 -0
  206. package/dist/providers/cloudflare/signing.js.map +1 -0
  207. package/dist/providers/cloudflare/tus.d.ts +24 -0
  208. package/dist/providers/cloudflare/tus.js +55 -0
  209. package/dist/providers/cloudflare/tus.js.map +1 -0
  210. package/dist/providers/cloudflare/types.d.ts +156 -0
  211. package/dist/providers/cloudflare/types.js +14 -0
  212. package/dist/providers/cloudflare/types.js.map +1 -0
  213. package/dist/providers/cloudflare/urls.d.ts +55 -0
  214. package/dist/providers/cloudflare/urls.js +87 -0
  215. package/dist/providers/cloudflare/urls.js.map +1 -0
  216. package/dist/providers/cloudflare/webhook.d.ts +36 -0
  217. package/dist/providers/cloudflare/webhook.js +83 -0
  218. package/dist/providers/cloudflare/webhook.js.map +1 -0
  219. package/dist/providers/mux/client.d.ts +82 -0
  220. package/dist/providers/mux/client.js +283 -0
  221. package/dist/providers/mux/client.js.map +1 -0
  222. package/dist/providers/mux/env.d.ts +21 -0
  223. package/dist/providers/mux/env.js +61 -0
  224. package/dist/providers/mux/env.js.map +1 -0
  225. package/dist/providers/mux/mapping.d.ts +38 -0
  226. package/dist/providers/mux/mapping.js +111 -0
  227. package/dist/providers/mux/mapping.js.map +1 -0
  228. package/dist/providers/mux/options.d.ts +96 -0
  229. package/dist/providers/mux/options.js +83 -0
  230. package/dist/providers/mux/options.js.map +1 -0
  231. package/dist/providers/mux/provider.d.ts +63 -0
  232. package/dist/providers/mux/provider.js +555 -0
  233. package/dist/providers/mux/provider.js.map +1 -0
  234. package/dist/providers/mux/signing.d.ts +45 -0
  235. package/dist/providers/mux/signing.js +84 -0
  236. package/dist/providers/mux/signing.js.map +1 -0
  237. package/dist/providers/mux/types.d.ts +173 -0
  238. package/dist/providers/mux/types.js +42 -0
  239. package/dist/providers/mux/types.js.map +1 -0
  240. package/dist/providers/mux/urls.d.ts +58 -0
  241. package/dist/providers/mux/urls.js +59 -0
  242. package/dist/providers/mux/urls.js.map +1 -0
  243. package/dist/providers/mux/webhook.d.ts +38 -0
  244. package/dist/providers/mux/webhook.js +115 -0
  245. package/dist/providers/mux/webhook.js.map +1 -0
  246. package/dist/service.d.ts +193 -0
  247. package/dist/service.js +967 -0
  248. package/dist/service.js.map +1 -0
  249. package/dist/testing/bunny.d.ts +113 -0
  250. package/dist/testing/bunny.js +776 -0
  251. package/dist/testing/bunny.js.map +1 -0
  252. package/dist/testing/cloudflare.d.ts +101 -0
  253. package/dist/testing/cloudflare.js +913 -0
  254. package/dist/testing/cloudflare.js.map +1 -0
  255. package/dist/testing/index.d.ts +45 -0
  256. package/dist/testing/index.js +42 -0
  257. package/dist/testing/index.js.map +1 -0
  258. package/dist/testing/mux.d.ts +139 -0
  259. package/dist/testing/mux.js +1053 -0
  260. package/dist/testing/mux.js.map +1 -0
  261. package/dist/testing/types.d.ts +90 -0
  262. package/dist/testing/types.js +9 -0
  263. package/dist/testing/types.js.map +1 -0
  264. package/dist/types.d.ts +404 -0
  265. package/dist/types.js +3 -0
  266. package/dist/types.js.map +1 -0
  267. package/dist/utils/access.d.ts +22 -0
  268. package/dist/utils/access.js +66 -0
  269. package/dist/utils/access.js.map +1 -0
  270. package/dist/utils/localReq.d.ts +11 -0
  271. package/dist/utils/localReq.js +23 -0
  272. package/dist/utils/localReq.js.map +1 -0
  273. package/dist/utils/request.d.ts +12 -0
  274. package/dist/utils/request.js +55 -0
  275. package/dist/utils/request.js.map +1 -0
  276. package/dist/utils/version.d.ts +5 -0
  277. package/dist/utils/version.js +7 -0
  278. package/dist/utils/version.js.map +1 -0
  279. package/package.json +175 -4
@@ -0,0 +1,913 @@
1
+ import { generateKeyPairSync, randomBytes, verify } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createServer } from 'node:http';
4
+ import nodePath from 'node:path';
5
+ import { decodeTusMetadata, TUS_CHUNK_MULTIPLE } from '../providers/cloudflare/tus.js';
6
+ import { STREAM_VIDEO_STATES } from '../providers/cloudflare/types.js';
7
+ import { createWebhookSignatureHeader, WEBHOOK_SIGNATURE_HEADER } from '../providers/cloudflare/webhook.js';
8
+ const NEUTRAL_TO_STATE = {
9
+ error: 'error',
10
+ processing: 'inprogress',
11
+ queued: 'queued',
12
+ ready: 'ready',
13
+ waiting: 'pendingupload'
14
+ };
15
+ const json = (res, status, body, headers = {})=>{
16
+ res.writeHead(status, {
17
+ 'content-type': 'application/json',
18
+ ...headers
19
+ });
20
+ res.end(JSON.stringify(body));
21
+ };
22
+ const envelope = (result, extra = {})=>({
23
+ errors: [],
24
+ messages: [],
25
+ result,
26
+ success: true,
27
+ ...extra
28
+ });
29
+ const failure = (code, message)=>({
30
+ errors: [
31
+ {
32
+ code,
33
+ message
34
+ }
35
+ ],
36
+ messages: [],
37
+ result: null,
38
+ success: false
39
+ });
40
+ const CORS = {
41
+ 'access-control-allow-headers': '*',
42
+ 'access-control-allow-methods': 'GET,POST,PATCH,HEAD,OPTIONS,PUT,DELETE',
43
+ 'access-control-allow-origin': '*',
44
+ 'access-control-expose-headers': 'Location, Upload-Offset, Upload-Length, Tus-Resumable, stream-media-id'
45
+ };
46
+ const readBody = (req)=>new Promise((resolve, reject)=>{
47
+ const chunks = [];
48
+ req.on('data', (c)=>chunks.push(c));
49
+ req.on('end', ()=>resolve(Buffer.concat(chunks)));
50
+ req.on('error', reject);
51
+ });
52
+ /**
53
+ * An in-memory fake of the Cloudflare Stream API, upload endpoints (basic + tus) and delivery
54
+ * (manifests, iframe, thumbnails) for local development and tests – no Cloudflare account needed.
55
+ *
56
+ * ```ts
57
+ * const fake = await startFakeCloudflareStream()
58
+ * videoPlugin({ providers: [cloudflareStream(fake.providerOptions)] })
59
+ * ```
60
+ */ export class FakeCloudflareStream {
61
+ /** The options `cloudflareStream()` needs to talk to a fake running at `url` (e.g. in another process). */ static optionsForUrl(url, accountId = 'fake-account', apiToken = 'fake-token') {
62
+ const base = url.replace(/\/+$/, '');
63
+ return {
64
+ accountId,
65
+ apiBaseUrl: `${base}/client/v4`,
66
+ apiToken,
67
+ deliveryBaseUrl: `${base}/delivery`
68
+ };
69
+ }
70
+ provider = 'cloudflare';
71
+ accountId;
72
+ apiToken;
73
+ /** Every request received (for assertions). */ requests = [];
74
+ videos = new Map();
75
+ webhook = null;
76
+ baseUrl = '';
77
+ keys = new Map();
78
+ options;
79
+ server = null;
80
+ timers = new Set();
81
+ constructor(options = {}){
82
+ this.accountId = options.accountId ?? 'fake-account';
83
+ this.apiToken = options.apiToken ?? 'fake-token';
84
+ this.options = {
85
+ autoProcess: options.autoProcess ?? true,
86
+ enforceTusChunkMultiple: options.enforceTusChunkMultiple ?? true,
87
+ hlsFixtureDir: options.hlsFixtureDir,
88
+ port: options.port ?? 0,
89
+ processingDelayMs: options.processingDelayMs ?? 300,
90
+ publicUrl: options.publicUrl?.replace(/\/+$/, '') || undefined
91
+ };
92
+ }
93
+ /** Base URL to pass as the plugin's `apiBaseUrl`. */ get apiBaseUrl() {
94
+ return `${this.baseUrl}/client/v4`;
95
+ }
96
+ /** Pass as the plugin's `customerCode` so playback URLs point at the fake delivery server. */ get deliveryBaseUrl() {
97
+ return `${this.baseUrl}/delivery`;
98
+ }
99
+ get url() {
100
+ return this.baseUrl;
101
+ }
102
+ get providerOptions() {
103
+ return FakeCloudflareStream.optionsForUrl(this.baseUrl, this.accountId, this.apiToken);
104
+ }
105
+ localSigningOptions() {
106
+ const { privateKey, publicKey } = generateKeyPairSync('rsa', {
107
+ modulusLength: 2048
108
+ });
109
+ const keyId = randomBytes(16).toString('hex');
110
+ this.keys.set(keyId, publicKey);
111
+ return {
112
+ signingKey: {
113
+ keyId,
114
+ pem: privateKey.export({
115
+ format: 'pem',
116
+ type: 'pkcs1'
117
+ }).toString()
118
+ }
119
+ };
120
+ }
121
+ webhookOptions(secret) {
122
+ return {
123
+ webhook: {
124
+ secret
125
+ }
126
+ };
127
+ }
128
+ async start() {
129
+ this.server = createServer((req, res)=>{
130
+ this.route(req, res).catch((err)=>{
131
+ json(res, 500, failure(10000, err.message));
132
+ });
133
+ });
134
+ await new Promise((resolve, reject)=>{
135
+ this.server.once('error', reject);
136
+ this.server.listen(this.options.port, '127.0.0.1', ()=>{
137
+ this.server.off('error', reject);
138
+ resolve();
139
+ });
140
+ }).catch((err)=>{
141
+ this.server = null;
142
+ throw err;
143
+ });
144
+ const { port } = this.server.address();
145
+ this.baseUrl = this.options.publicUrl ?? `http://127.0.0.1:${port}`;
146
+ return this;
147
+ }
148
+ async stop() {
149
+ for (const t of this.timers){
150
+ clearTimeout(t);
151
+ }
152
+ this.timers.clear();
153
+ if (this.server) {
154
+ await new Promise((resolve)=>this.server.close(()=>resolve()));
155
+ this.server.closeAllConnections?.();
156
+ this.server = null;
157
+ }
158
+ }
159
+ reset() {
160
+ this.videos.clear();
161
+ this.requests.length = 0;
162
+ this.webhook = null;
163
+ this.keys.clear();
164
+ }
165
+ // ---------------------------------------------------------------------------
166
+ // Test helpers
167
+ // ---------------------------------------------------------------------------
168
+ /** Creates a video directly (bypassing upload). */ addVideo(partial = {}) {
169
+ const video = this.newVideo(partial.status?.state ?? 'ready', partial);
170
+ if (video.status?.state === 'ready') {
171
+ this.markReady(video);
172
+ }
173
+ return video;
174
+ }
175
+ /** Forces a video into a state (optionally with an error). */ setState(uid, state, error) {
176
+ const video = this.mustGet(uid);
177
+ if (state === 'ready') {
178
+ this.markReady(video);
179
+ } else {
180
+ video.readyToStream = false;
181
+ video.status = {
182
+ pctComplete: state === 'inprogress' ? '50.000000' : '0.000000',
183
+ state,
184
+ ...error ? {
185
+ errorReasonCode: error.code,
186
+ errorReasonText: error.text
187
+ } : {}
188
+ };
189
+ }
190
+ video.modified = new Date().toISOString();
191
+ return video;
192
+ }
193
+ // Provider-neutral controls (FakeProviderServer)
194
+ addAsset(input = {}) {
195
+ const video = this.addVideo({
196
+ ...input.createdAt ? {
197
+ created: input.createdAt
198
+ } : {},
199
+ ...input.creator ? {
200
+ creator: input.creator
201
+ } : {},
202
+ ...input.title ? {
203
+ meta: {
204
+ name: input.title
205
+ }
206
+ } : {},
207
+ requireSignedURLs: Boolean(input.signedPlayback),
208
+ status: {
209
+ state: NEUTRAL_TO_STATE[input.status ?? 'ready']
210
+ }
211
+ });
212
+ return {
213
+ assetId: video.uid
214
+ };
215
+ }
216
+ assetIds() {
217
+ return [
218
+ ...this.videos.keys()
219
+ ];
220
+ }
221
+ hasAsset(assetId) {
222
+ return this.videos.has(assetId);
223
+ }
224
+ removeAsset(assetId) {
225
+ this.videos.delete(assetId);
226
+ }
227
+ simulateUpload(ref) {
228
+ const video = this.mustGet(ref.assetId ?? '');
229
+ if (video.status?.state === 'pendingupload') {
230
+ video.size = video.uploadLength ?? 1;
231
+ video.uploadOffset = video.size;
232
+ this.onUploaded(video);
233
+ }
234
+ return {
235
+ assetId: video.uid
236
+ };
237
+ }
238
+ setStatus(assetId, status, error) {
239
+ this.setState(assetId, NEUTRAL_TO_STATE[status], error ? {
240
+ code: error.code,
241
+ text: error.message
242
+ } : undefined);
243
+ }
244
+ /** Builds a signed webhook body/header pair for a video, as Cloudflare would send it. */ buildWebhook(uid, secret = this.webhook?.secret ?? 'fake-secret') {
245
+ const body = JSON.stringify(this.publicVideo(this.mustGet(uid)));
246
+ const signature = createWebhookSignatureHeader(secret, body);
247
+ return {
248
+ body,
249
+ headers: {
250
+ 'content-type': 'application/json',
251
+ [WEBHOOK_SIGNATURE_HEADER]: signature
252
+ },
253
+ signature
254
+ };
255
+ }
256
+ // ---------------------------------------------------------------------------
257
+ // Internals
258
+ // ---------------------------------------------------------------------------
259
+ mustGet(uid) {
260
+ const video = this.videos.get(uid);
261
+ if (!video) {
262
+ throw new Error(`FakeCloudflareStream: unknown video ${uid}`);
263
+ }
264
+ return video;
265
+ }
266
+ newVideo(state, partial = {}) {
267
+ const uid = partial.uid ?? randomBytes(16).toString('hex');
268
+ const now = new Date().toISOString();
269
+ const video = {
270
+ allowedOrigins: [],
271
+ captions: [],
272
+ created: now,
273
+ creator: null,
274
+ downloads: {},
275
+ duration: -1,
276
+ input: {
277
+ height: -1,
278
+ width: -1
279
+ },
280
+ maxDurationSeconds: null,
281
+ meta: {},
282
+ modified: now,
283
+ playback: {
284
+ dash: '',
285
+ hls: ''
286
+ },
287
+ preview: `${this.deliveryBaseUrl}/${uid}/watch`,
288
+ readyToStream: false,
289
+ readyToStreamAt: null,
290
+ requireSignedURLs: false,
291
+ scheduledDeletion: null,
292
+ size: 0,
293
+ thumbnail: `${this.deliveryBaseUrl}/${uid}/thumbnails/thumbnail.jpg`,
294
+ thumbnailTimestampPct: 0,
295
+ uploaded: null,
296
+ uploadExpiry: null,
297
+ uploadOffset: 0,
298
+ ...partial,
299
+ status: {
300
+ pctComplete: '0.000000',
301
+ state,
302
+ ...partial.status
303
+ },
304
+ uid
305
+ };
306
+ video.playback = {
307
+ dash: `${this.deliveryBaseUrl}/${uid}/manifest/video.mpd`,
308
+ hls: `${this.deliveryBaseUrl}/${uid}/manifest/video.m3u8`
309
+ };
310
+ this.videos.set(uid, video);
311
+ return video;
312
+ }
313
+ markReady(video) {
314
+ const now = new Date().toISOString();
315
+ video.status = {
316
+ pctComplete: '100.000000',
317
+ state: 'ready'
318
+ };
319
+ video.readyToStream = true;
320
+ video.readyToStreamAt = now;
321
+ video.duration = video.duration && video.duration > 0 ? video.duration : 5;
322
+ video.input = {
323
+ height: 720,
324
+ width: 1280
325
+ };
326
+ video.uploaded ??= now;
327
+ video.modified = now;
328
+ }
329
+ schedule(fn, delay) {
330
+ const timer = setTimeout(()=>{
331
+ this.timers.delete(timer);
332
+ fn();
333
+ }, delay);
334
+ this.timers.add(timer);
335
+ }
336
+ onUploaded(video) {
337
+ video.uploaded = new Date().toISOString();
338
+ video.status = {
339
+ pctComplete: '0.000000',
340
+ state: 'queued'
341
+ };
342
+ if (!this.options.autoProcess) {
343
+ return;
344
+ }
345
+ const delay = this.options.processingDelayMs;
346
+ // Each automatic step only runs if nothing (e.g. a test's setState) moved the video meanwhile.
347
+ this.schedule(()=>{
348
+ if (!this.videos.has(video.uid) || video.status?.state !== 'queued') {
349
+ return;
350
+ }
351
+ video.status = {
352
+ pctComplete: '50.000000',
353
+ state: 'inprogress'
354
+ };
355
+ this.schedule(()=>{
356
+ if (!this.videos.has(video.uid) || video.status?.state !== 'inprogress') {
357
+ return;
358
+ }
359
+ this.markReady(video);
360
+ void this.sendWebhook(video);
361
+ }, delay / 2);
362
+ }, delay / 2);
363
+ }
364
+ async sendWebhook(video) {
365
+ if (!this.webhook) {
366
+ return;
367
+ }
368
+ const body = JSON.stringify(this.publicVideo(video));
369
+ await fetch(this.webhook.notificationUrl, {
370
+ body,
371
+ headers: {
372
+ 'content-type': 'application/json',
373
+ 'webhook-signature': createWebhookSignatureHeader(this.webhook.secret, body)
374
+ },
375
+ method: 'POST'
376
+ }).catch(()=>undefined);
377
+ }
378
+ publicVideo(video) {
379
+ const { captions: _c, downloads: _d, uploadLength: _l, uploadOffset: _o, ...rest } = video;
380
+ return rest;
381
+ }
382
+ applySettings(video, body) {
383
+ if (typeof body.requireSignedURLs === 'boolean') {
384
+ video.requireSignedURLs = body.requireSignedURLs;
385
+ }
386
+ if (Array.isArray(body.allowedOrigins)) {
387
+ video.allowedOrigins = body.allowedOrigins;
388
+ }
389
+ if (typeof body.thumbnailTimestampPct === 'number') {
390
+ video.thumbnailTimestampPct = body.thumbnailTimestampPct;
391
+ }
392
+ if (body.meta && typeof body.meta === 'object') {
393
+ video.meta = body.meta;
394
+ }
395
+ if (typeof body.creator === 'string') {
396
+ video.creator = body.creator;
397
+ }
398
+ if (typeof body.maxDurationSeconds === 'number') {
399
+ video.maxDurationSeconds = body.maxDurationSeconds;
400
+ }
401
+ if (body.scheduledDeletion !== undefined) {
402
+ video.scheduledDeletion = body.scheduledDeletion;
403
+ }
404
+ video.modified = new Date().toISOString();
405
+ }
406
+ /** Verifies a delivery id (uid or JWT) and returns the video, or an HTTP status on failure. */ resolveDelivery(id) {
407
+ if (this.videos.has(id)) {
408
+ const video = this.videos.get(id);
409
+ return video.requireSignedURLs ? 401 : video;
410
+ }
411
+ const [h, p, s] = id.split('.');
412
+ if (!h || !p || !s) {
413
+ return 404;
414
+ }
415
+ try {
416
+ const header = JSON.parse(Buffer.from(h, 'base64url').toString());
417
+ const payload = JSON.parse(Buffer.from(p, 'base64url').toString());
418
+ const key = header.kid ? this.keys.get(header.kid) : undefined;
419
+ if (header.alg !== 'RS256' || !key) {
420
+ return 401;
421
+ }
422
+ if (!verify('RSA-SHA256', Buffer.from(`${h}.${p}`), key, Buffer.from(s, 'base64url'))) {
423
+ return 401;
424
+ }
425
+ const now = Date.now() / 1000;
426
+ if (!payload.exp || payload.exp < now || payload.nbf && payload.nbf > now) {
427
+ return 401;
428
+ }
429
+ const video = payload.sub ? this.videos.get(payload.sub) : undefined;
430
+ return video ?? 404;
431
+ } catch {
432
+ return 401;
433
+ }
434
+ }
435
+ async route(req, res) {
436
+ const url = new URL(req.url ?? '/', this.baseUrl);
437
+ const method = (req.method ?? 'GET').toUpperCase();
438
+ this.requests.push({
439
+ method,
440
+ path: `${url.pathname}${url.search}`
441
+ });
442
+ if (method === 'OPTIONS') {
443
+ res.writeHead(204, {
444
+ ...CORS,
445
+ 'tus-resumable': '1.0.0'
446
+ });
447
+ res.end();
448
+ return;
449
+ }
450
+ // ---- Test control, the same on every fake: POST /__fake/assets/:id/status { status, error? } ----
451
+ const assetControl = /^\/__fake\/assets\/([^/]+)\/status$/.exec(url.pathname);
452
+ if (assetControl && method === 'POST') {
453
+ const id = decodeURIComponent(assetControl[1]);
454
+ if (!this.videos.has(id)) {
455
+ return json(res, 404, failure(10003, 'Not Found'), CORS);
456
+ }
457
+ const body = JSON.parse((await readBody(req)).toString() || '{}');
458
+ if (!body.status || !(body.status in NEUTRAL_TO_STATE)) {
459
+ return json(res, 400, failure(10005, 'status is required'), CORS);
460
+ }
461
+ this.setStatus(id, body.status, body.error);
462
+ return json(res, 200, envelope(this.publicVideo(this.mustGet(id))), CORS);
463
+ }
464
+ // ---- Test control (Cloudflare fake only): POST /__fake/videos/:uid/state { state, error? } ----
465
+ const controlMatch = /^\/__fake\/videos\/([a-f0-9]+)\/state$/.exec(url.pathname);
466
+ if (controlMatch && method === 'POST') {
467
+ if (!this.videos.has(controlMatch[1])) {
468
+ return json(res, 404, failure(10003, 'Not Found'), CORS);
469
+ }
470
+ const body = JSON.parse((await readBody(req)).toString() || '{}');
471
+ if (!body.state || !STREAM_VIDEO_STATES.includes(body.state)) {
472
+ return json(res, 400, failure(10005, 'state is required'), CORS);
473
+ }
474
+ const video = this.setState(controlMatch[1], body.state, body.error);
475
+ return json(res, 200, envelope(this.publicVideo(video)), CORS);
476
+ }
477
+ // ---- Basic browser upload: POST /upload/:uid (multipart, field "file") ----
478
+ const uploadMatch = /^\/upload\/([a-f0-9]+)$/.exec(url.pathname);
479
+ if (uploadMatch && method === 'POST') {
480
+ const video = this.videos.get(uploadMatch[1]);
481
+ if (!video || video.status?.state !== 'pendingupload') {
482
+ return json(res, 404, failure(10003, 'Not Found'), CORS);
483
+ }
484
+ const body = await readBody(req);
485
+ const contentType = req.headers['content-type'] ?? '';
486
+ if (!contentType.includes('multipart/form-data') || !body.includes(Buffer.from('name="file"'))) {
487
+ return json(res, 400, failure(10005, 'Expected multipart upload with a "file" field'), CORS);
488
+ }
489
+ video.size = body.length;
490
+ this.onUploaded(video);
491
+ res.writeHead(200, CORS);
492
+ res.end();
493
+ return;
494
+ }
495
+ // ---- tus upload: HEAD/PATCH /tus/:uid ----
496
+ const tusMatch = /^\/tus\/([a-f0-9]+)$/.exec(url.pathname);
497
+ if (tusMatch) {
498
+ const video = this.videos.get(tusMatch[1]);
499
+ if (!video || video.uploadLength === undefined) {
500
+ res.writeHead(404, CORS);
501
+ res.end();
502
+ return;
503
+ }
504
+ const tusHeaders = {
505
+ ...CORS,
506
+ 'tus-resumable': '1.0.0',
507
+ 'upload-length': String(video.uploadLength),
508
+ 'upload-offset': String(video.uploadOffset)
509
+ };
510
+ if (method === 'HEAD') {
511
+ res.writeHead(200, {
512
+ ...tusHeaders,
513
+ 'cache-control': 'no-store'
514
+ });
515
+ res.end();
516
+ return;
517
+ }
518
+ if (method === 'PATCH') {
519
+ const offset = Number(req.headers['upload-offset']);
520
+ if (offset !== video.uploadOffset) {
521
+ res.writeHead(409, tusHeaders);
522
+ res.end('offset mismatch');
523
+ return;
524
+ }
525
+ const chunk = await readBody(req);
526
+ const isLast = offset + chunk.length >= video.uploadLength;
527
+ if (this.options.enforceTusChunkMultiple && !isLast && chunk.length % TUS_CHUNK_MULTIPLE !== 0) {
528
+ res.writeHead(400, tusHeaders);
529
+ res.end('chunk size must be a multiple of 256KiB');
530
+ return;
531
+ }
532
+ video.uploadOffset = Math.min(offset + chunk.length, video.uploadLength);
533
+ video.size = video.uploadOffset;
534
+ if (video.uploadOffset >= video.uploadLength) {
535
+ this.onUploaded(video);
536
+ }
537
+ res.writeHead(204, {
538
+ ...tusHeaders,
539
+ 'upload-offset': String(video.uploadOffset)
540
+ });
541
+ res.end();
542
+ return;
543
+ }
544
+ }
545
+ // ---- Delivery ----
546
+ const deliveryMatch = /^\/delivery\/([^/]+)\/(.+)$/.exec(url.pathname);
547
+ if (deliveryMatch && method === 'GET') {
548
+ const resolved = this.resolveDelivery(decodeURIComponent(deliveryMatch[1]));
549
+ if (typeof resolved === 'number') {
550
+ res.writeHead(resolved, CORS);
551
+ res.end(resolved === 401 ? 'Unauthorized' : 'Not Found');
552
+ return;
553
+ }
554
+ const asset = deliveryMatch[2];
555
+ const fixtureFile = /^manifest\/([\w-]+\.(?:m3u8|m4s|mp4))$/.exec(asset)?.[1];
556
+ if (fixtureFile && this.options.hlsFixtureDir) {
557
+ try {
558
+ const body = await readFile(nodePath.join(this.options.hlsFixtureDir, fixtureFile));
559
+ const type = fixtureFile.endsWith('.m3u8') ? 'application/vnd.apple.mpegurl' : fixtureFile.endsWith('.m4s') ? 'video/iso.segment' : 'video/mp4';
560
+ res.writeHead(200, {
561
+ ...CORS,
562
+ 'content-type': type
563
+ });
564
+ res.end(body);
565
+ } catch {
566
+ res.writeHead(404, CORS);
567
+ res.end('Not Found');
568
+ }
569
+ return;
570
+ }
571
+ if (asset === 'manifest/video.m3u8') {
572
+ res.writeHead(200, {
573
+ ...CORS,
574
+ 'content-type': 'application/vnd.apple.mpegurl'
575
+ });
576
+ res.end('#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-ENDLIST\n');
577
+ return;
578
+ }
579
+ if (asset === 'manifest/video.mpd') {
580
+ res.writeHead(200, {
581
+ ...CORS,
582
+ 'content-type': 'application/dash+xml'
583
+ });
584
+ res.end('<?xml version="1.0"?><MPD xmlns="urn:mpeg:dash:schema:mpd:2011"/>');
585
+ return;
586
+ }
587
+ if (asset === 'iframe' || asset === 'watch') {
588
+ res.writeHead(200, {
589
+ 'content-type': 'text/html'
590
+ });
591
+ res.end(`<!doctype html><html><body style="margin:0;background:#111;color:#eee;font:14px sans-serif;display:grid;place-items:center;height:100vh"><div data-testid="fake-player">Fake Stream player: ${resolved.uid}</div></body></html>`);
592
+ return;
593
+ }
594
+ if (asset.startsWith('thumbnails/')) {
595
+ res.writeHead(200, {
596
+ ...CORS,
597
+ 'content-type': 'image/svg+xml'
598
+ });
599
+ res.end('<svg xmlns="http://www.w3.org/2000/svg" width="160" height="90"><rect width="160" height="90" fill="#334"/><polygon points="65,30 65,60 95,45" fill="#fff"/></svg>');
600
+ return;
601
+ }
602
+ if (asset.startsWith('downloads/')) {
603
+ res.writeHead(resolved.downloads.default?.status === 'ready' ? 200 : 404, {
604
+ 'content-type': 'video/mp4'
605
+ });
606
+ res.end();
607
+ return;
608
+ }
609
+ if (asset.startsWith('captions/')) {
610
+ res.writeHead(200, {
611
+ ...CORS,
612
+ 'content-type': 'text/vtt'
613
+ });
614
+ res.end('WEBVTT\n');
615
+ return;
616
+ }
617
+ res.writeHead(404);
618
+ res.end();
619
+ return;
620
+ }
621
+ // ---- API ----
622
+ const apiPrefix = `/client/v4/accounts/${this.accountId}/stream`;
623
+ if (!url.pathname.startsWith(apiPrefix)) {
624
+ return json(res, 404, failure(7003, 'Could not route to the requested resource'));
625
+ }
626
+ if (req.headers.authorization !== `Bearer ${this.apiToken}`) {
627
+ return json(res, 403, failure(10002, 'Authorization Failure'));
628
+ }
629
+ const path = url.pathname.slice(apiPrefix.length) || '/';
630
+ const segments = path.split('/').filter(Boolean);
631
+ const rawBody = await readBody(req);
632
+ const contentType = req.headers['content-type'] ?? '';
633
+ const body = contentType.includes('application/json') && rawBody.length ? JSON.parse(rawBody.toString('utf8')) : {};
634
+ // POST /stream?direct_user=true (tus creation) | POST /stream (multipart server upload)
635
+ if (segments.length === 0 && method === 'POST') {
636
+ if (req.headers['tus-resumable']) {
637
+ const length = Number(req.headers['upload-length']);
638
+ if (!(length > 0)) {
639
+ return json(res, 400, failure(10005, 'Upload-Length required'));
640
+ }
641
+ const meta = decodeTusMetadata(req.headers['upload-metadata']);
642
+ const video = this.newVideo('pendingupload', {
643
+ creator: req.headers['upload-creator'] ?? null,
644
+ maxDurationSeconds: meta.maxdurationseconds ? Number(meta.maxdurationseconds) : null,
645
+ meta: typeof meta.name === 'string' ? {
646
+ name: meta.name
647
+ } : {},
648
+ requireSignedURLs: meta.requiresignedurls === true,
649
+ ...typeof meta.allowedorigins === 'string' ? {
650
+ allowedOrigins: meta.allowedorigins.split(',')
651
+ } : {}
652
+ });
653
+ video.uploadLength = length;
654
+ res.writeHead(201, {
655
+ ...CORS,
656
+ location: `${this.baseUrl}/tus/${video.uid}`,
657
+ 'stream-media-id': video.uid,
658
+ 'tus-resumable': '1.0.0'
659
+ });
660
+ res.end();
661
+ return;
662
+ }
663
+ if (contentType.includes('multipart/form-data')) {
664
+ const video = this.newVideo('queued', {
665
+ creator: req.headers['upload-creator'] ?? null,
666
+ size: rawBody.length
667
+ });
668
+ this.onUploaded(video);
669
+ return json(res, 200, envelope(this.publicVideo(video)));
670
+ }
671
+ return json(res, 400, failure(10005, 'Unsupported upload'));
672
+ }
673
+ // GET /stream (list)
674
+ if (segments.length === 0 && method === 'GET') {
675
+ let list = [
676
+ ...this.videos.values()
677
+ ];
678
+ const creator = url.searchParams.get('creator');
679
+ const status = url.searchParams.get('status');
680
+ if (creator) {
681
+ list = list.filter((v)=>v.creator === creator);
682
+ }
683
+ if (status) {
684
+ list = list.filter((v)=>v.status?.state === status);
685
+ }
686
+ const before = url.searchParams.get('before');
687
+ const after = url.searchParams.get('after');
688
+ if (before) {
689
+ list = list.filter((v)=>(v.created ?? '') < before);
690
+ }
691
+ if (after) {
692
+ list = list.filter((v)=>(v.created ?? '') > after);
693
+ }
694
+ const asc = url.searchParams.get('asc') === 'true';
695
+ list.sort((a, b)=>((a.created ?? '') < (b.created ?? '') ? -1 : 1) * (asc ? 1 : -1));
696
+ const limit = Number(url.searchParams.get('limit') ?? 1000);
697
+ return json(res, 200, envelope(list.slice(0, limit).map((v)=>this.publicVideo(v)), {
698
+ total: list.length
699
+ }));
700
+ }
701
+ const [first, second, third, fourth] = segments;
702
+ if (first === 'direct_upload' && method === 'POST') {
703
+ const video = this.newVideo('pendingupload');
704
+ this.applySettings(video, body);
705
+ video.uploadExpiry = body.expiry ?? null;
706
+ return json(res, 200, envelope({
707
+ uid: video.uid,
708
+ uploadURL: `${this.baseUrl}/upload/${video.uid}`
709
+ }));
710
+ }
711
+ if (first === 'copy' && method === 'POST') {
712
+ if (typeof body.url !== 'string') {
713
+ return json(res, 400, failure(10005, 'url is required'));
714
+ }
715
+ const video = this.newVideo('downloading');
716
+ this.applySettings(video, body);
717
+ this.schedule(()=>this.videos.has(video.uid) && this.onUploaded(video), 10);
718
+ return json(res, 200, envelope(this.publicVideo(video)));
719
+ }
720
+ if (first === 'keys') {
721
+ if (method === 'POST' && !second) {
722
+ const { privateKey, publicKey } = generateKeyPairSync('rsa', {
723
+ modulusLength: 2048
724
+ });
725
+ const id = randomBytes(16).toString('hex');
726
+ this.keys.set(id, publicKey);
727
+ return json(res, 200, envelope({
728
+ created: new Date().toISOString(),
729
+ id,
730
+ jwk: Buffer.from(JSON.stringify(privateKey.export({
731
+ format: 'jwk'
732
+ }))).toString('base64'),
733
+ pem: Buffer.from(privateKey.export({
734
+ format: 'pem',
735
+ type: 'pkcs1'
736
+ }).toString()).toString('base64')
737
+ }));
738
+ }
739
+ if (method === 'GET' && !second) {
740
+ return json(res, 200, envelope([
741
+ ...this.keys.keys()
742
+ ].map((id)=>({
743
+ id
744
+ }))));
745
+ }
746
+ if (method === 'DELETE' && second) {
747
+ this.keys.delete(second);
748
+ return json(res, 200, envelope(''));
749
+ }
750
+ }
751
+ if (first === 'webhook') {
752
+ if (method === 'PUT') {
753
+ this.webhook = {
754
+ notificationUrl: String(body.notificationUrl),
755
+ secret: randomBytes(16).toString('hex')
756
+ };
757
+ return json(res, 200, envelope({
758
+ ...this.webhook,
759
+ modified: new Date().toISOString()
760
+ }));
761
+ }
762
+ if (method === 'GET') {
763
+ return this.webhook ? json(res, 200, envelope(this.webhook)) : json(res, 404, failure(10003, 'Not Found'));
764
+ }
765
+ if (method === 'DELETE') {
766
+ this.webhook = null;
767
+ return json(res, 200, envelope(''));
768
+ }
769
+ }
770
+ if (first === 'storage-usage' && method === 'GET') {
771
+ const minutes = [
772
+ ...this.videos.values()
773
+ ].reduce((sum, v)=>sum + Math.max(v.duration ?? 0, 0) / 60, 0);
774
+ return json(res, 200, envelope({
775
+ totalStorageMinutes: minutes,
776
+ totalStorageMinutesLimit: 1000,
777
+ videoCount: this.videos.size
778
+ }));
779
+ }
780
+ const video = first ? this.videos.get(first) : undefined;
781
+ if (!video) {
782
+ return json(res, 404, failure(10003, 'Not Found'));
783
+ }
784
+ if (!second) {
785
+ if (method === 'GET') {
786
+ return json(res, 200, envelope(this.publicVideo(video)));
787
+ }
788
+ if (method === 'POST') {
789
+ this.applySettings(video, body);
790
+ return json(res, 200, envelope(this.publicVideo(video)));
791
+ }
792
+ if (method === 'DELETE') {
793
+ this.videos.delete(video.uid);
794
+ res.writeHead(200);
795
+ res.end();
796
+ return;
797
+ }
798
+ }
799
+ if (second === 'token' && method === 'POST') {
800
+ // Cloudflare-minted tokens: emulate by signing with an internal key
801
+ let kid = [
802
+ ...this.keys.keys()
803
+ ][0];
804
+ if (!kid) {
805
+ const created = generateKeyPairSync('rsa', {
806
+ modulusLength: 2048
807
+ });
808
+ kid = 'internal';
809
+ this.keys.set(kid, created.publicKey);
810
+ this.internalKey = created.privateKey;
811
+ }
812
+ const internal = this.internalKey;
813
+ if (!internal) {
814
+ return json(res, 500, failure(10000, 'no internal key'));
815
+ }
816
+ const { signStreamToken } = await import('../providers/cloudflare/signing.js');
817
+ const exp = typeof body.exp === 'number' ? body.exp : Math.floor(Date.now() / 1000) + 3600;
818
+ const token = signStreamToken({
819
+ expiresIn: Math.max(1, exp - Math.floor(Date.now() / 1000)),
820
+ keyId: kid,
821
+ pem: internal.export({
822
+ format: 'pem',
823
+ type: 'pkcs1'
824
+ }).toString(),
825
+ videoUID: video.uid
826
+ });
827
+ return json(res, 200, envelope({
828
+ token
829
+ }));
830
+ }
831
+ if (second === 'captions') {
832
+ if (!third && method === 'GET') {
833
+ return json(res, 200, envelope(video.captions));
834
+ }
835
+ if (third && !fourth && method === 'PUT') {
836
+ if (!contentType.includes('multipart/form-data') || !rawBody.includes(Buffer.from('WEBVTT'))) {
837
+ return json(res, 400, failure(10005, 'Expected a WebVTT file'));
838
+ }
839
+ const caption = {
840
+ generated: false,
841
+ label: third,
842
+ language: third,
843
+ status: 'ready'
844
+ };
845
+ video.captions = [
846
+ ...video.captions.filter((c)=>c.language !== third),
847
+ caption
848
+ ];
849
+ return json(res, 200, envelope(caption));
850
+ }
851
+ if (third && fourth === 'generate' && method === 'POST') {
852
+ const caption = {
853
+ generated: true,
854
+ label: `${third} (auto-generated)`,
855
+ language: third,
856
+ status: 'inprogress'
857
+ };
858
+ video.captions = [
859
+ ...video.captions.filter((c)=>c.language !== third),
860
+ caption
861
+ ];
862
+ this.schedule(()=>{
863
+ caption.status = 'ready';
864
+ }, this.options.processingDelayMs);
865
+ return json(res, 200, envelope(caption));
866
+ }
867
+ if (third && fourth === 'vtt' && method === 'GET') {
868
+ res.writeHead(200, {
869
+ 'content-type': 'text/vtt'
870
+ });
871
+ res.end('WEBVTT\n');
872
+ return;
873
+ }
874
+ if (third && !fourth && method === 'DELETE') {
875
+ video.captions = video.captions.filter((c)=>c.language !== third);
876
+ return json(res, 200, envelope(''));
877
+ }
878
+ }
879
+ if (second === 'downloads') {
880
+ if (!third && method === 'GET') {
881
+ return json(res, 200, envelope(video.downloads));
882
+ }
883
+ if (method === 'POST' && (!third || third === 'audio')) {
884
+ const type = third === 'audio' ? 'audio' : 'default';
885
+ const ext = type === 'audio' ? 'audio.m4a' : 'default.mp4';
886
+ const entry = {
887
+ percentComplete: 0,
888
+ status: 'inprogress',
889
+ url: `${this.deliveryBaseUrl}/${video.uid}/downloads/${ext}`
890
+ };
891
+ video.downloads[type] = entry;
892
+ this.schedule(()=>{
893
+ video.downloads[type] = {
894
+ ...entry,
895
+ percentComplete: 100,
896
+ status: 'ready'
897
+ };
898
+ }, this.options.processingDelayMs);
899
+ return json(res, 200, envelope({
900
+ [type]: entry
901
+ }));
902
+ }
903
+ if (method === 'DELETE' && (third === 'default' || third === 'audio')) {
904
+ delete video.downloads[third];
905
+ return json(res, 200, envelope(''));
906
+ }
907
+ }
908
+ return json(res, 404, failure(10003, 'Not Found'));
909
+ }
910
+ }
911
+ /** Starts a fake Cloudflare Stream server. Remember to `await fake.stop()`. */ export const startFakeCloudflareStream = (options)=>new FakeCloudflareStream(options).start();
912
+
913
+ //# sourceMappingURL=cloudflare.js.map