payload-video-streaming 0.0.0-stage → 0.2.0-beta.0

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 (252) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +658 -2
  3. package/dist/bin/args.d.ts +24 -0
  4. package/dist/bin/args.js +96 -0
  5. package/dist/bin/args.js.map +1 -0
  6. package/dist/bin/cli.d.ts +2 -0
  7. package/dist/bin/cli.js +17 -0
  8. package/dist/bin/cli.js.map +1 -0
  9. package/dist/bin/fake.d.ts +2 -0
  10. package/dist/bin/fake.js +14 -0
  11. package/dist/bin/fake.js.map +1 -0
  12. package/dist/bin/migrate.d.ts +5 -0
  13. package/dist/bin/migrate.js +47 -0
  14. package/dist/bin/migrate.js.map +1 -0
  15. package/dist/bin/runFake.d.ts +2 -0
  16. package/dist/bin/runFake.js +24 -0
  17. package/dist/bin/runFake.js.map +1 -0
  18. package/dist/blocks.d.ts +42 -0
  19. package/dist/blocks.js +150 -0
  20. package/dist/blocks.js.map +1 -0
  21. package/dist/collection.d.ts +10 -0
  22. package/dist/collection.js +550 -0
  23. package/dist/collection.js.map +1 -0
  24. package/dist/components/CaptionsManager.d.ts +9 -0
  25. package/dist/components/CaptionsManager.js +174 -0
  26. package/dist/components/CaptionsManager.js.map +1 -0
  27. package/dist/components/DownloadsPanel.d.ts +9 -0
  28. package/dist/components/DownloadsPanel.js +147 -0
  29. package/dist/components/DownloadsPanel.js.map +1 -0
  30. package/dist/components/ListUploader.d.ts +11 -0
  31. package/dist/components/ListUploader.js +116 -0
  32. package/dist/components/ListUploader.js.map +1 -0
  33. package/dist/components/ThumbnailCell.d.ts +5 -0
  34. package/dist/components/ThumbnailCell.js +28 -0
  35. package/dist/components/ThumbnailCell.js.map +1 -0
  36. package/dist/components/Uploader.d.ts +17 -0
  37. package/dist/components/Uploader.js +162 -0
  38. package/dist/components/Uploader.js.map +1 -0
  39. package/dist/components/VideoBlockLabel.d.ts +11 -0
  40. package/dist/components/VideoBlockLabel.js +86 -0
  41. package/dist/components/VideoBlockLabel.js.map +1 -0
  42. package/dist/components/VideoField.d.ts +17 -0
  43. package/dist/components/VideoField.js +418 -0
  44. package/dist/components/VideoField.js.map +1 -0
  45. package/dist/components/api.d.ts +46 -0
  46. package/dist/components/api.js +74 -0
  47. package/dist/components/api.js.map +1 -0
  48. package/dist/components/chunkedUpload.d.ts +28 -0
  49. package/dist/components/chunkedUpload.js +49 -0
  50. package/dist/components/chunkedUpload.js.map +1 -0
  51. package/dist/components/styles.d.ts +95 -0
  52. package/dist/components/styles.js +148 -0
  53. package/dist/components/styles.js.map +1 -0
  54. package/dist/components/usePluginApi.d.ts +41 -0
  55. package/dist/components/usePluginApi.js +21 -0
  56. package/dist/components/usePluginApi.js.map +1 -0
  57. package/dist/components/useVideoUpload.d.ts +37 -0
  58. package/dist/components/useVideoUpload.js +181 -0
  59. package/dist/components/useVideoUpload.js.map +1 -0
  60. package/dist/core/errors.d.ts +27 -0
  61. package/dist/core/errors.js +29 -0
  62. package/dist/core/errors.js.map +1 -0
  63. package/dist/core/provider.d.ts +331 -0
  64. package/dist/core/provider.js +13 -0
  65. package/dist/core/provider.js.map +1 -0
  66. package/dist/core/registry.d.ts +17 -0
  67. package/dist/core/registry.js +110 -0
  68. package/dist/core/registry.js.map +1 -0
  69. package/dist/core/status.d.ts +15 -0
  70. package/dist/core/status.js +29 -0
  71. package/dist/core/status.js.map +1 -0
  72. package/dist/endpoints/index.d.ts +3 -0
  73. package/dist/endpoints/index.js +464 -0
  74. package/dist/endpoints/index.js.map +1 -0
  75. package/dist/env.d.ts +40 -0
  76. package/dist/env.js +105 -0
  77. package/dist/env.js.map +1 -0
  78. package/dist/exports/bunny.d.ts +16 -0
  79. package/dist/exports/bunny.js +13 -0
  80. package/dist/exports/bunny.js.map +1 -0
  81. package/dist/exports/client.d.ts +13 -0
  82. package/dist/exports/client.js +13 -0
  83. package/dist/exports/client.js.map +1 -0
  84. package/dist/exports/cloudflare.d.ts +18 -0
  85. package/dist/exports/cloudflare.js +15 -0
  86. package/dist/exports/cloudflare.js.map +1 -0
  87. package/dist/exports/mux.d.ts +18 -0
  88. package/dist/exports/mux.js +15 -0
  89. package/dist/exports/mux.js.map +1 -0
  90. package/dist/exports/react.d.ts +13 -0
  91. package/dist/exports/react.js +11 -0
  92. package/dist/exports/react.js.map +1 -0
  93. package/dist/exports/rsc.d.ts +1 -0
  94. package/dist/exports/rsc.js +4 -0
  95. package/dist/exports/rsc.js.map +1 -0
  96. package/dist/exports/testing.d.ts +13 -0
  97. package/dist/exports/testing.js +9 -0
  98. package/dist/exports/testing.js.map +1 -0
  99. package/dist/fields.d.ts +13 -0
  100. package/dist/fields.js +13 -0
  101. package/dist/fields.js.map +1 -0
  102. package/dist/frontend/ClientVideo.d.ts +14 -0
  103. package/dist/frontend/ClientVideo.js +43 -0
  104. package/dist/frontend/ClientVideo.js.map +1 -0
  105. package/dist/frontend/Video.d.ts +32 -0
  106. package/dist/frontend/Video.js +73 -0
  107. package/dist/frontend/Video.js.map +1 -0
  108. package/dist/frontend/VideoIframe.d.ts +35 -0
  109. package/dist/frontend/VideoIframe.js +60 -0
  110. package/dist/frontend/VideoIframe.js.map +1 -0
  111. package/dist/frontend/constants.d.ts +10 -0
  112. package/dist/frontend/constants.js +10 -0
  113. package/dist/frontend/constants.js.map +1 -0
  114. package/dist/frontend/converters.d.ts +25 -0
  115. package/dist/frontend/converters.js +24 -0
  116. package/dist/frontend/converters.js.map +1 -0
  117. package/dist/frontend/source.d.ts +80 -0
  118. package/dist/frontend/source.js +159 -0
  119. package/dist/frontend/source.js.map +1 -0
  120. package/dist/frontend/useVideoSource.d.ts +27 -0
  121. package/dist/frontend/useVideoSource.js +108 -0
  122. package/dist/frontend/useVideoSource.js.map +1 -0
  123. package/dist/index.d.ts +20 -0
  124. package/dist/index.js +14 -0
  125. package/dist/index.js.map +1 -0
  126. package/dist/migrate/cfStream.d.ts +108 -0
  127. package/dist/migrate/cfStream.js +418 -0
  128. package/dist/migrate/cfStream.js.map +1 -0
  129. package/dist/options.d.ts +4 -0
  130. package/dist/options.js +90 -0
  131. package/dist/options.js.map +1 -0
  132. package/dist/plugin.d.ts +9 -0
  133. package/dist/plugin.js +98 -0
  134. package/dist/plugin.js.map +1 -0
  135. package/dist/providers/bunny/client.d.ts +78 -0
  136. package/dist/providers/bunny/client.js +231 -0
  137. package/dist/providers/bunny/client.js.map +1 -0
  138. package/dist/providers/bunny/env.d.ts +18 -0
  139. package/dist/providers/bunny/env.js +31 -0
  140. package/dist/providers/bunny/env.js.map +1 -0
  141. package/dist/providers/bunny/mapping.d.ts +39 -0
  142. package/dist/providers/bunny/mapping.js +123 -0
  143. package/dist/providers/bunny/mapping.js.map +1 -0
  144. package/dist/providers/bunny/options.d.ts +92 -0
  145. package/dist/providers/bunny/options.js +85 -0
  146. package/dist/providers/bunny/options.js.map +1 -0
  147. package/dist/providers/bunny/provider.d.ts +69 -0
  148. package/dist/providers/bunny/provider.js +472 -0
  149. package/dist/providers/bunny/provider.js.map +1 -0
  150. package/dist/providers/bunny/signing.d.ts +61 -0
  151. package/dist/providers/bunny/signing.js +144 -0
  152. package/dist/providers/bunny/signing.js.map +1 -0
  153. package/dist/providers/bunny/types.d.ts +153 -0
  154. package/dist/providers/bunny/types.js +64 -0
  155. package/dist/providers/bunny/types.js.map +1 -0
  156. package/dist/providers/bunny/urls.d.ts +49 -0
  157. package/dist/providers/bunny/urls.js +70 -0
  158. package/dist/providers/bunny/urls.js.map +1 -0
  159. package/dist/providers/bunny/webhook.d.ts +32 -0
  160. package/dist/providers/bunny/webhook.js +75 -0
  161. package/dist/providers/bunny/webhook.js.map +1 -0
  162. package/dist/providers/cloudflare/client.d.ts +93 -0
  163. package/dist/providers/cloudflare/client.js +436 -0
  164. package/dist/providers/cloudflare/client.js.map +1 -0
  165. package/dist/providers/cloudflare/env.d.ts +22 -0
  166. package/dist/providers/cloudflare/env.js +57 -0
  167. package/dist/providers/cloudflare/env.js.map +1 -0
  168. package/dist/providers/cloudflare/mapping.d.ts +15 -0
  169. package/dist/providers/cloudflare/mapping.js +95 -0
  170. package/dist/providers/cloudflare/mapping.js.map +1 -0
  171. package/dist/providers/cloudflare/options.d.ts +104 -0
  172. package/dist/providers/cloudflare/options.js +91 -0
  173. package/dist/providers/cloudflare/options.js.map +1 -0
  174. package/dist/providers/cloudflare/provider.d.ts +62 -0
  175. package/dist/providers/cloudflare/provider.js +434 -0
  176. package/dist/providers/cloudflare/provider.js.map +1 -0
  177. package/dist/providers/cloudflare/signing.d.ts +41 -0
  178. package/dist/providers/cloudflare/signing.js +97 -0
  179. package/dist/providers/cloudflare/signing.js.map +1 -0
  180. package/dist/providers/cloudflare/tus.d.ts +24 -0
  181. package/dist/providers/cloudflare/tus.js +55 -0
  182. package/dist/providers/cloudflare/tus.js.map +1 -0
  183. package/dist/providers/cloudflare/types.d.ts +156 -0
  184. package/dist/providers/cloudflare/types.js +14 -0
  185. package/dist/providers/cloudflare/types.js.map +1 -0
  186. package/dist/providers/cloudflare/urls.d.ts +55 -0
  187. package/dist/providers/cloudflare/urls.js +87 -0
  188. package/dist/providers/cloudflare/urls.js.map +1 -0
  189. package/dist/providers/cloudflare/webhook.d.ts +36 -0
  190. package/dist/providers/cloudflare/webhook.js +83 -0
  191. package/dist/providers/cloudflare/webhook.js.map +1 -0
  192. package/dist/providers/mux/client.d.ts +82 -0
  193. package/dist/providers/mux/client.js +283 -0
  194. package/dist/providers/mux/client.js.map +1 -0
  195. package/dist/providers/mux/env.d.ts +21 -0
  196. package/dist/providers/mux/env.js +61 -0
  197. package/dist/providers/mux/env.js.map +1 -0
  198. package/dist/providers/mux/mapping.d.ts +38 -0
  199. package/dist/providers/mux/mapping.js +111 -0
  200. package/dist/providers/mux/mapping.js.map +1 -0
  201. package/dist/providers/mux/options.d.ts +96 -0
  202. package/dist/providers/mux/options.js +83 -0
  203. package/dist/providers/mux/options.js.map +1 -0
  204. package/dist/providers/mux/provider.d.ts +62 -0
  205. package/dist/providers/mux/provider.js +546 -0
  206. package/dist/providers/mux/provider.js.map +1 -0
  207. package/dist/providers/mux/signing.d.ts +45 -0
  208. package/dist/providers/mux/signing.js +84 -0
  209. package/dist/providers/mux/signing.js.map +1 -0
  210. package/dist/providers/mux/types.d.ts +173 -0
  211. package/dist/providers/mux/types.js +42 -0
  212. package/dist/providers/mux/types.js.map +1 -0
  213. package/dist/providers/mux/urls.d.ts +58 -0
  214. package/dist/providers/mux/urls.js +59 -0
  215. package/dist/providers/mux/urls.js.map +1 -0
  216. package/dist/providers/mux/webhook.d.ts +38 -0
  217. package/dist/providers/mux/webhook.js +115 -0
  218. package/dist/providers/mux/webhook.js.map +1 -0
  219. package/dist/service.d.ts +166 -0
  220. package/dist/service.js +857 -0
  221. package/dist/service.js.map +1 -0
  222. package/dist/testing/bunny.d.ts +113 -0
  223. package/dist/testing/bunny.js +776 -0
  224. package/dist/testing/bunny.js.map +1 -0
  225. package/dist/testing/cloudflare.d.ts +101 -0
  226. package/dist/testing/cloudflare.js +913 -0
  227. package/dist/testing/cloudflare.js.map +1 -0
  228. package/dist/testing/index.d.ts +45 -0
  229. package/dist/testing/index.js +42 -0
  230. package/dist/testing/index.js.map +1 -0
  231. package/dist/testing/mux.d.ts +139 -0
  232. package/dist/testing/mux.js +1053 -0
  233. package/dist/testing/mux.js.map +1 -0
  234. package/dist/testing/types.d.ts +90 -0
  235. package/dist/testing/types.js +9 -0
  236. package/dist/testing/types.js.map +1 -0
  237. package/dist/types.d.ts +250 -0
  238. package/dist/types.js +3 -0
  239. package/dist/types.js.map +1 -0
  240. package/dist/utils/access.d.ts +22 -0
  241. package/dist/utils/access.js +66 -0
  242. package/dist/utils/access.js.map +1 -0
  243. package/dist/utils/localReq.d.ts +11 -0
  244. package/dist/utils/localReq.js +23 -0
  245. package/dist/utils/localReq.js.map +1 -0
  246. package/dist/utils/request.d.ts +12 -0
  247. package/dist/utils/request.js +55 -0
  248. package/dist/utils/request.js.map +1 -0
  249. package/dist/utils/version.d.ts +5 -0
  250. package/dist/utils/version.js +7 -0
  251. package/dist/utils/version.js.map +1 -0
  252. package/package.json +174 -4
@@ -0,0 +1,776 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createServer } from 'node:http';
4
+ import nodePath from 'node:path';
5
+ import { NEUTRAL_TO_BUNNY_WEBHOOK_STATUS } from '../providers/bunny/mapping.js';
6
+ import { embedViewToken, hexEquals, parseDirectoryToken, tusUploadSignature, verifyCdnToken } from '../providers/bunny/signing.js';
7
+ import { BUNNY_ISSUE_CODES, BUNNY_VIDEO_STATUS, BUNNY_WEBHOOK_STATUS } from '../providers/bunny/types.js';
8
+ import { bunnyWebhookHeaders } from '../providers/bunny/webhook.js';
9
+ import { decodeTusMetadata } from '../providers/cloudflare/tus.js';
10
+ const CORS = {
11
+ 'access-control-allow-headers': '*',
12
+ 'access-control-allow-methods': 'GET,POST,PATCH,HEAD,OPTIONS,PUT,DELETE',
13
+ 'access-control-allow-origin': '*',
14
+ 'access-control-expose-headers': 'Location, Upload-Offset, Upload-Length, Tus-Resumable'
15
+ };
16
+ const json = (res, status, body, headers = {})=>{
17
+ res.writeHead(status, {
18
+ 'content-type': 'application/json',
19
+ ...CORS,
20
+ ...headers
21
+ });
22
+ res.end(JSON.stringify(body));
23
+ };
24
+ const statusModel = (statusCode, message)=>({
25
+ message,
26
+ statusCode,
27
+ success: statusCode < 400
28
+ });
29
+ const readBody = (req)=>new Promise((resolve, reject)=>{
30
+ const chunks = [];
31
+ req.on('data', (c)=>chunks.push(c));
32
+ req.on('end', ()=>resolve(Buffer.concat(chunks)));
33
+ req.on('error', reject);
34
+ });
35
+ /** Bunny's dates have no time zone. */ const bunnyNow = ()=>new Date().toISOString().replace(/Z$/, '');
36
+ const IMAGE = '<svg xmlns="http://www.w3.org/2000/svg" width="160" height="90"><rect width="160" height="90" fill="#433"/><polygon points="65,30 65,60 95,45" fill="#fff"/></svg>';
37
+ /**
38
+ * An in-memory fake of Bunny Stream for local development and tests: the Stream API, the tus upload
39
+ * endpoint (with signature checks), a library CDN (HLS, thumbnails, previews, MP4 fallback, captions)
40
+ * and the embed player, with token authentication when the library has it on. No Bunny account needed.
41
+ *
42
+ * ```ts
43
+ * const fake = await startFakeBunnyStream()
44
+ * videoPlugin({ providers: [bunnyStream(fake.providerOptions)] })
45
+ * ```
46
+ */ export class FakeBunnyStream {
47
+ /** The options `bunnyStream()` needs to talk to a fake running at `url` (e.g. in another process). */ static optionsForUrl(url, libraryId = '424242', apiKey = 'fake-bunny-api-key') {
48
+ const base = url.replace(/\/+$/, '');
49
+ return {
50
+ apiBaseUrl: base,
51
+ apiKey,
52
+ cdnHostname: `${base}/cdn`,
53
+ embedBaseUrl: base,
54
+ libraryId
55
+ };
56
+ }
57
+ provider = 'bunny';
58
+ apiKey;
59
+ cdnTokenKey;
60
+ embedTokenKey;
61
+ libraryId;
62
+ library;
63
+ readOnlyApiKey;
64
+ requests = [];
65
+ videos = new Map();
66
+ /** Webhooks the fake sent (for assertions). */ sentWebhooks = [];
67
+ baseUrl = '';
68
+ options;
69
+ server = null;
70
+ timers = new Set();
71
+ constructor(options = {}){
72
+ this.libraryId = options.libraryId ?? '424242';
73
+ this.apiKey = options.apiKey ?? 'fake-bunny-api-key';
74
+ this.readOnlyApiKey = options.readOnlyApiKey ?? 'fake-bunny-read-only-key';
75
+ this.embedTokenKey = options.embedTokenKey ?? 'fake-bunny-embed-token-key';
76
+ this.cdnTokenKey = options.cdnTokenKey ?? 'fake-bunny-cdn-token-key';
77
+ this.library = {
78
+ mp4Fallback: false,
79
+ tokenAuth: false,
80
+ webhookSecret: this.readOnlyApiKey,
81
+ webhookUrl: null
82
+ };
83
+ this.options = {
84
+ autoProcess: options.autoProcess ?? true,
85
+ hlsFixtureDir: options.hlsFixtureDir,
86
+ maxItemsPerPage: options.maxItemsPerPage ?? 1000,
87
+ port: options.port ?? 0,
88
+ processingDelayMs: options.processingDelayMs ?? 300,
89
+ publicUrl: options.publicUrl?.replace(/\/+$/, '') || undefined
90
+ };
91
+ }
92
+ get url() {
93
+ return this.baseUrl;
94
+ }
95
+ get cdnBaseUrl() {
96
+ return `${this.baseUrl}/cdn`;
97
+ }
98
+ get providerOptions() {
99
+ return FakeBunnyStream.optionsForUrl(this.baseUrl, this.libraryId, this.apiKey);
100
+ }
101
+ /** Turns on the library's token authentication and returns the keys that sign for it. */ localSigningOptions() {
102
+ this.library.tokenAuth = true;
103
+ return {
104
+ cdnTokenKey: this.cdnTokenKey,
105
+ embedTokenKey: this.embedTokenKey
106
+ };
107
+ }
108
+ /** Webhooks from this fake are signed with `secret` (on Bunny: the library's Read-Only API key). */ webhookOptions(secret) {
109
+ this.library.webhookSecret = secret;
110
+ return {
111
+ webhookSecret: secret
112
+ };
113
+ }
114
+ async start() {
115
+ this.server = createServer((req, res)=>{
116
+ this.route(req, res).catch((err)=>json(res, 500, statusModel(500, err.message)));
117
+ });
118
+ await new Promise((resolve, reject)=>{
119
+ this.server.once('error', reject);
120
+ this.server.listen(this.options.port, '127.0.0.1', ()=>{
121
+ this.server.off('error', reject);
122
+ resolve();
123
+ });
124
+ }).catch((err)=>{
125
+ this.server = null;
126
+ throw err;
127
+ });
128
+ const { port } = this.server.address();
129
+ this.baseUrl = this.options.publicUrl ?? `http://127.0.0.1:${port}`;
130
+ return this;
131
+ }
132
+ async stop() {
133
+ for (const t of this.timers){
134
+ clearTimeout(t);
135
+ }
136
+ this.timers.clear();
137
+ if (this.server) {
138
+ await new Promise((resolve)=>this.server.close(()=>resolve()));
139
+ this.server.closeAllConnections?.();
140
+ this.server = null;
141
+ }
142
+ }
143
+ reset() {
144
+ this.videos.clear();
145
+ this.requests.length = 0;
146
+ this.sentWebhooks.length = 0;
147
+ Object.assign(this.library, {
148
+ mp4Fallback: false,
149
+ tokenAuth: false,
150
+ webhookSecret: this.readOnlyApiKey,
151
+ webhookUrl: null
152
+ });
153
+ }
154
+ // ---------------------------------------------------------------------------
155
+ // Test helpers
156
+ // ---------------------------------------------------------------------------
157
+ /** Creates a video directly (bypassing upload). Ready unless `status` says otherwise. Untitled videos are named by their id. */ addVideo(partial = {}) {
158
+ const video = this.newVideo(partial.title ?? '', partial);
159
+ if ((partial.status ?? BUNNY_VIDEO_STATUS.Finished) === BUNNY_VIDEO_STATUS.Finished) {
160
+ this.markReady(video);
161
+ }
162
+ return video;
163
+ }
164
+ addAsset(input = {}) {
165
+ const video = this.addVideo({
166
+ ...input.createdAt ? {
167
+ dateUploaded: input.createdAt.replace(/Z$/, '')
168
+ } : {},
169
+ ...input.creator ? {
170
+ metaTags: [
171
+ {
172
+ property: 'creator',
173
+ value: input.creator
174
+ }
175
+ ]
176
+ } : {},
177
+ status: BUNNY_VIDEO_STATUS.Created,
178
+ ...input.title ? {
179
+ title: input.title
180
+ } : {}
181
+ });
182
+ // `signedPlayback` is a library setting on Bunny: see `library.tokenAuth`.
183
+ this.setStatus(video.guid, input.status ?? 'ready');
184
+ return {
185
+ assetId: video.guid
186
+ };
187
+ }
188
+ assetIds() {
189
+ return [
190
+ ...this.videos.keys()
191
+ ];
192
+ }
193
+ hasAsset(assetId) {
194
+ return this.videos.has(assetId);
195
+ }
196
+ removeAsset(assetId) {
197
+ this.videos.delete(assetId);
198
+ }
199
+ simulateUpload(ref) {
200
+ const video = this.mustGet(ref.assetId ?? '');
201
+ if (video.status === BUNNY_VIDEO_STATUS.Created) {
202
+ video.storageSize = video.upload?.length ?? 1;
203
+ this.onUploaded(video);
204
+ }
205
+ return {
206
+ assetId: video.guid
207
+ };
208
+ }
209
+ setStatus(assetId, status, error) {
210
+ const video = this.mustGet(assetId);
211
+ video.transcodingMessages = [];
212
+ switch(status){
213
+ case 'error':
214
+ {
215
+ video.status = BUNNY_VIDEO_STATUS.Error;
216
+ const issueCode = Math.max(0, BUNNY_ISSUE_CODES.indexOf(error?.code ?? ''));
217
+ video.transcodingMessages = [
218
+ {
219
+ issueCode,
220
+ level: 3,
221
+ message: error?.message ?? 'Encoding failed',
222
+ timeStamp: bunnyNow(),
223
+ value: issueCode ? '' : error?.code ?? ''
224
+ }
225
+ ];
226
+ break;
227
+ }
228
+ case 'processing':
229
+ video.status = BUNNY_VIDEO_STATUS.Transcoding;
230
+ video.encodeProgress = 50;
231
+ break;
232
+ case 'queued':
233
+ video.status = BUNNY_VIDEO_STATUS.Uploaded;
234
+ video.encodeProgress = 0;
235
+ break;
236
+ case 'ready':
237
+ this.markReady(video);
238
+ break;
239
+ case 'waiting':
240
+ video.status = BUNNY_VIDEO_STATUS.Created;
241
+ video.encodeProgress = 0;
242
+ break;
243
+ }
244
+ }
245
+ /** A signed webhook for a video's current state, as Bunny sends it. */ buildWebhook(assetId, secret = this.library.webhookSecret, overrides = {}) {
246
+ const payload = this.webhookPayload(this.mustGet(assetId), undefined, overrides);
247
+ const body = JSON.stringify(payload);
248
+ return {
249
+ body,
250
+ headers: bunnyWebhookHeaders(secret, body),
251
+ payload
252
+ };
253
+ }
254
+ // ---------------------------------------------------------------------------
255
+ // Internals
256
+ // ---------------------------------------------------------------------------
257
+ mustGet(guid) {
258
+ const video = this.videos.get(guid);
259
+ if (!video) {
260
+ throw new Error(`FakeBunnyStream: unknown video ${guid}`);
261
+ }
262
+ return video;
263
+ }
264
+ newVideo(title, partial = {}) {
265
+ const guid = partial.guid ?? randomUUID();
266
+ const video = {
267
+ availableResolutions: null,
268
+ averageWatchTime: 0,
269
+ captionFiles: new Map(),
270
+ captions: [],
271
+ collectionId: null,
272
+ dateUploaded: bunnyNow(),
273
+ encodeProgress: 0,
274
+ framerate: 0,
275
+ hasMP4Fallback: false,
276
+ height: 0,
277
+ isPublic: false,
278
+ length: 0,
279
+ metaTags: [],
280
+ outputCodecs: 'x264',
281
+ status: BUNNY_VIDEO_STATUS.Created,
282
+ storageSize: 0,
283
+ thumbnailCount: 0,
284
+ thumbnailFileName: 'thumbnail.jpg',
285
+ totalWatchTime: 0,
286
+ transcodingMessages: [],
287
+ videoLibraryId: Number(this.libraryId),
288
+ views: 0,
289
+ width: 0,
290
+ ...partial,
291
+ guid,
292
+ title: title || guid
293
+ };
294
+ this.videos.set(guid, video);
295
+ return video;
296
+ }
297
+ markReady(video) {
298
+ video.status = BUNNY_VIDEO_STATUS.Finished;
299
+ video.encodeProgress = 100;
300
+ video.length = video.length > 0 ? video.length : 5;
301
+ video.width = 1280;
302
+ video.height = 720;
303
+ video.framerate = 30;
304
+ video.availableResolutions = '240p,360p,720p';
305
+ video.thumbnailCount = 5;
306
+ video.storageSize ||= 1024;
307
+ video.hasMP4Fallback = this.library.mp4Fallback;
308
+ }
309
+ schedule(fn, delay) {
310
+ const timer = setTimeout(()=>{
311
+ this.timers.delete(timer);
312
+ fn();
313
+ }, delay);
314
+ this.timers.add(timer);
315
+ }
316
+ onUploaded(video) {
317
+ video.status = BUNNY_VIDEO_STATUS.Uploaded;
318
+ video.encodeProgress = 0;
319
+ void this.sendWebhook(video, BUNNY_WEBHOOK_STATUS.Queued);
320
+ if (!this.options.autoProcess) {
321
+ return;
322
+ }
323
+ const delay = this.options.processingDelayMs;
324
+ this.schedule(()=>{
325
+ if (!this.videos.has(video.guid) || video.status !== BUNNY_VIDEO_STATUS.Uploaded) {
326
+ return;
327
+ }
328
+ video.status = BUNNY_VIDEO_STATUS.Transcoding;
329
+ video.encodeProgress = 50;
330
+ void this.sendWebhook(video, BUNNY_WEBHOOK_STATUS.Encoding);
331
+ this.schedule(()=>{
332
+ if (!this.videos.has(video.guid) || video.status !== BUNNY_VIDEO_STATUS.Transcoding) {
333
+ return;
334
+ }
335
+ this.markReady(video);
336
+ void this.sendWebhook(video, BUNNY_WEBHOOK_STATUS.Finished);
337
+ }, delay / 2);
338
+ }, delay / 2);
339
+ }
340
+ webhookPayload(video, status, overrides = {}) {
341
+ const neutral = video.status === BUNNY_VIDEO_STATUS.Finished ? 'ready' : video.status === BUNNY_VIDEO_STATUS.Error || video.status === BUNNY_VIDEO_STATUS.UploadFailed ? 'error' : video.status === BUNNY_VIDEO_STATUS.Created ? 'waiting' : video.status === BUNNY_VIDEO_STATUS.Uploaded ? 'queued' : 'processing';
342
+ return {
343
+ EventId: randomUUID(),
344
+ IsLiveStreamWebhook: false,
345
+ Status: status ?? NEUTRAL_TO_BUNNY_WEBHOOK_STATUS[neutral],
346
+ Timestamp: bunnyNow(),
347
+ VideoGuid: video.guid,
348
+ VideoLibraryId: Number(this.libraryId),
349
+ ...overrides
350
+ };
351
+ }
352
+ async sendWebhook(video, status) {
353
+ if (!this.library.webhookUrl) {
354
+ return;
355
+ }
356
+ const payload = this.webhookPayload(video, status);
357
+ this.sentWebhooks.push(payload);
358
+ const body = JSON.stringify(payload);
359
+ await fetch(this.library.webhookUrl, {
360
+ body,
361
+ headers: bunnyWebhookHeaders(this.library.webhookSecret, body),
362
+ method: 'POST'
363
+ }).catch(()=>undefined);
364
+ }
365
+ publicVideo(video) {
366
+ const { captionFiles: _c, upload: _u, ...rest } = video;
367
+ return rest;
368
+ }
369
+ /** Checks the tus signature headers. Returns an HTTP status on failure. */ checkTusHeaders(req) {
370
+ const signature = req.headers.authorizationsignature;
371
+ const expire = Number(req.headers.authorizationexpire);
372
+ const videoId = req.headers.videoid;
373
+ const libraryId = req.headers.libraryid;
374
+ if (!signature || !videoId || !req.headers.authorizationexpire) {
375
+ return 401;
376
+ }
377
+ if (!libraryId || libraryId !== this.libraryId || !(expire >= Math.floor(Date.now() / 1000))) {
378
+ return 400;
379
+ }
380
+ const expected = tusUploadSignature({
381
+ apiKey: this.apiKey,
382
+ expires: expire,
383
+ libraryId,
384
+ videoId
385
+ });
386
+ if (!hexEquals(signature, expected)) {
387
+ return 401;
388
+ }
389
+ return this.videos.get(videoId) ?? 404;
390
+ }
391
+ /** Token authentication on the CDN. Returns the real path, or an HTTP status. */ checkCdn(url) {
392
+ const directory = parseDirectoryToken(url.pathname);
393
+ const path = directory?.path ?? url.pathname;
394
+ if (!this.library.tokenAuth) {
395
+ return path;
396
+ }
397
+ const params = directory?.params ?? url.searchParams;
398
+ return verifyCdnToken(this.cdnTokenKey, decodeURIComponent(path), params).ok ? path : 403;
399
+ }
400
+ async serveFixture(res, file) {
401
+ const type = file.endsWith('.m3u8') ? 'application/vnd.apple.mpegurl' : file.endsWith('.m4s') ? 'video/iso.segment' : 'video/mp4';
402
+ if (!this.options.hlsFixtureDir) {
403
+ if (file === 'video.m3u8') {
404
+ res.writeHead(200, {
405
+ ...CORS,
406
+ 'content-type': type
407
+ });
408
+ res.end('#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-ENDLIST\n');
409
+ return;
410
+ }
411
+ res.writeHead(404, CORS);
412
+ res.end();
413
+ return;
414
+ }
415
+ try {
416
+ const body = await readFile(nodePath.join(this.options.hlsFixtureDir, file));
417
+ res.writeHead(200, {
418
+ ...CORS,
419
+ 'content-type': type
420
+ });
421
+ res.end(body);
422
+ } catch {
423
+ res.writeHead(404, CORS);
424
+ res.end('Not Found');
425
+ }
426
+ }
427
+ async route(req, res) {
428
+ const url = new URL(req.url ?? '/', this.baseUrl);
429
+ const method = (req.method ?? 'GET').toUpperCase();
430
+ this.requests.push({
431
+ method,
432
+ path: `${url.pathname}${url.search}`
433
+ });
434
+ if (method === 'OPTIONS') {
435
+ res.writeHead(204, {
436
+ ...CORS,
437
+ 'tus-resumable': '1.0.0'
438
+ });
439
+ res.end();
440
+ return;
441
+ }
442
+ // ---- Test controls ----
443
+ const assetControl = /^\/__fake\/assets\/([^/]+)\/status$/.exec(url.pathname);
444
+ if (assetControl && method === 'POST') {
445
+ const id = decodeURIComponent(assetControl[1]);
446
+ if (!this.videos.has(id)) {
447
+ return json(res, 404, statusModel(404, 'Not Found'));
448
+ }
449
+ const body = JSON.parse((await readBody(req)).toString() || '{}');
450
+ if (!body.status || !(body.status in NEUTRAL_TO_BUNNY_WEBHOOK_STATUS)) {
451
+ return json(res, 400, statusModel(400, 'status is required'));
452
+ }
453
+ this.setStatus(id, body.status, body.error);
454
+ return json(res, 200, this.publicVideo(this.mustGet(id)));
455
+ }
456
+ if (url.pathname === '/__fake/library' && (method === 'POST' || method === 'GET')) {
457
+ if (method === 'POST') {
458
+ const body = JSON.parse((await readBody(req)).toString() || '{}');
459
+ Object.assign(this.library, body);
460
+ }
461
+ return json(res, 200, this.library);
462
+ }
463
+ // ---- tus: POST /tusupload creates, HEAD/PATCH /tusupload/:videoId ----
464
+ if (url.pathname === '/tusupload' && method === 'POST') {
465
+ const checked = this.checkTusHeaders(req);
466
+ if (typeof checked === 'number') {
467
+ res.writeHead(checked, CORS);
468
+ res.end(checked === 401 ? 'Unauthorized' : checked === 400 ? 'Bad Request' : 'Not Found');
469
+ return;
470
+ }
471
+ const length = Number(req.headers['upload-length']);
472
+ const meta = decodeTusMetadata(req.headers['upload-metadata']);
473
+ if (!(length > 0) || typeof meta.title !== 'string' || !meta.title || typeof meta.filetype !== 'string') {
474
+ res.writeHead(400, CORS);
475
+ res.end('Upload-Length and the title and filetype metadata are required');
476
+ return;
477
+ }
478
+ checked.title = meta.title;
479
+ checked.upload = {
480
+ length,
481
+ offset: 0
482
+ };
483
+ res.writeHead(201, {
484
+ ...CORS,
485
+ location: `${this.baseUrl}/tusupload/${checked.guid}`,
486
+ 'tus-resumable': '1.0.0'
487
+ });
488
+ res.end();
489
+ return;
490
+ }
491
+ const tusMatch = /^\/tusupload\/([^/]+)$/.exec(url.pathname);
492
+ if (tusMatch && (method === 'HEAD' || method === 'PATCH')) {
493
+ const checked = this.checkTusHeaders(req);
494
+ if (typeof checked === 'number' || checked.guid !== decodeURIComponent(tusMatch[1]) || !checked.upload) {
495
+ res.writeHead(typeof checked === 'number' ? checked : 404, CORS);
496
+ res.end();
497
+ return;
498
+ }
499
+ const upload = checked.upload;
500
+ const headers = {
501
+ ...CORS,
502
+ 'tus-resumable': '1.0.0',
503
+ 'upload-length': String(upload.length),
504
+ 'upload-offset': String(upload.offset)
505
+ };
506
+ if (method === 'HEAD') {
507
+ res.writeHead(200, {
508
+ ...headers,
509
+ 'cache-control': 'no-store'
510
+ });
511
+ res.end();
512
+ return;
513
+ }
514
+ const offset = Number(req.headers['upload-offset']);
515
+ if (offset !== upload.offset) {
516
+ res.writeHead(409, headers);
517
+ res.end('offset mismatch');
518
+ return;
519
+ }
520
+ const chunk = await readBody(req);
521
+ upload.offset = Math.min(offset + chunk.length, upload.length);
522
+ checked.storageSize = upload.offset;
523
+ if (upload.offset >= upload.length && checked.status === BUNNY_VIDEO_STATUS.Created) {
524
+ this.onUploaded(checked);
525
+ }
526
+ res.writeHead(204, {
527
+ ...headers,
528
+ 'upload-offset': String(upload.offset)
529
+ });
530
+ res.end();
531
+ return;
532
+ }
533
+ // ---- Embed player: /embed/:libraryId/:guid ----
534
+ const embedMatch = /^\/embed\/([^/]+)\/([^/]+)$/.exec(url.pathname);
535
+ if (embedMatch && method === 'GET') {
536
+ const video = embedMatch[1] === this.libraryId ? this.videos.get(decodeURIComponent(embedMatch[2])) : undefined;
537
+ if (!video) {
538
+ res.writeHead(404, {
539
+ 'content-type': 'text/html'
540
+ });
541
+ res.end('Video not found');
542
+ return;
543
+ }
544
+ if (this.library.tokenAuth) {
545
+ const expires = Number(url.searchParams.get('expires'));
546
+ const token = url.searchParams.get('token') ?? '';
547
+ const expected = embedViewToken({
548
+ expires,
549
+ tokenKey: this.embedTokenKey,
550
+ videoId: video.guid
551
+ });
552
+ if (!(expires >= Math.floor(Date.now() / 1000)) || !hexEquals(token, expected)) {
553
+ res.writeHead(403, {
554
+ 'content-type': 'text/html'
555
+ });
556
+ res.end('Token authentication failed');
557
+ return;
558
+ }
559
+ }
560
+ res.writeHead(200, {
561
+ 'content-type': 'text/html'
562
+ });
563
+ 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" data-autoplay="${url.searchParams.get('autoplay') ?? ''}">Fake Bunny player: ${video.guid}</div></body></html>`);
564
+ return;
565
+ }
566
+ // ---- CDN: /cdn/:guid/:file, optionally behind /bcdn_token=…/ ----
567
+ if (url.pathname.startsWith('/cdn/') || url.pathname.startsWith('/bcdn_token=')) {
568
+ const checked = this.checkCdn(url);
569
+ if (typeof checked === 'number') {
570
+ res.writeHead(checked, CORS);
571
+ res.end('Forbidden');
572
+ return;
573
+ }
574
+ const match = /^\/cdn\/([^/]+)\/(.+)$/.exec(checked);
575
+ const video = match ? this.videos.get(decodeURIComponent(match[1])) : undefined;
576
+ if (!match || !video || method !== 'GET') {
577
+ res.writeHead(404, CORS);
578
+ res.end('Not Found');
579
+ return;
580
+ }
581
+ const file = match[2];
582
+ const mp4 = /^play_(\d+)p\.mp4$/.exec(file);
583
+ if (mp4) {
584
+ const available = (video.availableResolutions ?? '').split(',').includes(`${mp4[1]}p`);
585
+ res.writeHead(video.hasMP4Fallback && available ? 200 : 404, {
586
+ ...CORS,
587
+ 'content-type': 'video/mp4'
588
+ });
589
+ res.end();
590
+ return;
591
+ }
592
+ if (/^(thumbnail(_\d)?\.jpg|preview\.(webp|gif))$/.test(file)) {
593
+ res.writeHead(200, {
594
+ ...CORS,
595
+ 'content-type': 'image/svg+xml'
596
+ });
597
+ res.end(IMAGE);
598
+ return;
599
+ }
600
+ const caption = /^captions\/([^/]+)\.vtt$/.exec(file);
601
+ if (caption) {
602
+ const content = video.captionFiles.get(decodeURIComponent(caption[1]));
603
+ res.writeHead(content ? 200 : 404, {
604
+ ...CORS,
605
+ 'content-type': 'text/vtt'
606
+ });
607
+ res.end(content ?? '');
608
+ return;
609
+ }
610
+ if (file === 'playlist.m3u8') {
611
+ return this.serveFixture(res, 'video.m3u8');
612
+ }
613
+ if (/^[\w-]+\.(m3u8|m4s|mp4)$/.test(file)) {
614
+ return this.serveFixture(res, file);
615
+ }
616
+ res.writeHead(404, CORS);
617
+ res.end();
618
+ return;
619
+ }
620
+ // ---- Stream API ----
621
+ const prefix = `/library/${this.libraryId}/videos`;
622
+ if (!url.pathname.startsWith(prefix)) {
623
+ return json(res, 404, statusModel(404, 'Not Found'));
624
+ }
625
+ if (req.headers.accesskey !== this.apiKey) {
626
+ return json(res, 401, statusModel(401, 'Authorization has been denied for this request.'));
627
+ }
628
+ const segments = url.pathname.slice(prefix.length).split('/').filter(Boolean).map(decodeURIComponent);
629
+ const rawBody = await readBody(req);
630
+ const isJson = (req.headers['content-type'] ?? '').includes('application/json');
631
+ const body = isJson && rawBody.length ? JSON.parse(rawBody.toString('utf8')) : {};
632
+ const [first, second, third] = segments;
633
+ if (!first && method === 'POST') {
634
+ if (typeof body.title !== 'string' || !body.title) {
635
+ return json(res, 400, statusModel(400, 'The Title field is required.'));
636
+ }
637
+ const video = this.newVideo(body.title, {
638
+ collectionId: body.collectionId ?? null
639
+ });
640
+ return json(res, 200, this.publicVideo(video));
641
+ }
642
+ if (!first && method === 'GET') {
643
+ let list = [
644
+ ...this.videos.values()
645
+ ];
646
+ const search = url.searchParams.get('search');
647
+ const collection = url.searchParams.get('collection');
648
+ if (search) {
649
+ list = list.filter((v)=>v.title.toLowerCase().includes(search.toLowerCase()) || v.guid === search);
650
+ }
651
+ if (collection) {
652
+ list = list.filter((v)=>v.collectionId === collection);
653
+ }
654
+ list.sort((a, b)=>a.dateUploaded < b.dateUploaded ? 1 : a.dateUploaded > b.dateUploaded ? -1 : 0);
655
+ const page = Math.max(1, Number(url.searchParams.get('page') ?? 1));
656
+ const perPage = Math.min(Math.max(Number(url.searchParams.get('itemsPerPage') ?? 100), 1), this.options.maxItemsPerPage);
657
+ return json(res, 200, {
658
+ currentPage: page,
659
+ items: list.slice((page - 1) * perPage, page * perPage).map((v)=>this.publicVideo(v)),
660
+ itemsPerPage: perPage,
661
+ totalItems: list.length
662
+ });
663
+ }
664
+ if (first === 'fetch' && !second && method === 'POST') {
665
+ if (typeof body.url !== 'string' || !/^https?:\/\//.test(body.url)) {
666
+ return json(res, 400, statusModel(400, 'Invalid URL'));
667
+ }
668
+ const fallback = decodeURIComponent(new URL(body.url).pathname.split('/').pop() || '') || 'Fetched Video';
669
+ const video = this.newVideo(typeof body.title === 'string' && body.title ? body.title : fallback, {
670
+ collectionId: url.searchParams.get('collectionId')
671
+ });
672
+ this.schedule(()=>this.videos.has(video.guid) && this.onUploaded(video), 10);
673
+ return json(res, 200, statusModel(200, 'OK'));
674
+ }
675
+ const video = first ? this.videos.get(first) : undefined;
676
+ if (!video) {
677
+ return json(res, 404, statusModel(404, 'Video not found'));
678
+ }
679
+ if (!second) {
680
+ if (method === 'GET') {
681
+ return json(res, 200, this.publicVideo(video));
682
+ }
683
+ if (method === 'POST') {
684
+ if (typeof body.title === 'string' && body.title) {
685
+ video.title = body.title;
686
+ }
687
+ if (Array.isArray(body.metaTags)) {
688
+ video.metaTags = body.metaTags;
689
+ }
690
+ if (typeof body.collectionId === 'string') {
691
+ video.collectionId = body.collectionId || null;
692
+ }
693
+ return json(res, 200, statusModel(200, 'OK'));
694
+ }
695
+ if (method === 'PUT') {
696
+ // Unverified on Bunny whether a second PUT replaces the file; the fake only accepts the first.
697
+ if (video.status !== BUNNY_VIDEO_STATUS.Created || !rawBody.length) {
698
+ return json(res, 400, statusModel(400, 'The video has already been uploaded'));
699
+ }
700
+ video.storageSize = rawBody.length;
701
+ this.onUploaded(video);
702
+ return json(res, 200, statusModel(200, 'OK'));
703
+ }
704
+ if (method === 'DELETE') {
705
+ this.videos.delete(video.guid);
706
+ void this.sendWebhook(video, BUNNY_WEBHOOK_STATUS.VideoDeleted);
707
+ return json(res, 200, statusModel(200, 'OK'));
708
+ }
709
+ }
710
+ if (second === 'thumbnail' && method === 'POST') {
711
+ const thumb = url.searchParams.get('thumbnailUrl');
712
+ if (thumb && /^thumbnail_\d\.jpg$/.test(thumb)) {
713
+ video.thumbnailFileName = thumb;
714
+ }
715
+ return json(res, 200, statusModel(200, 'OK'));
716
+ }
717
+ if (second === 'captions' && third) {
718
+ if (method === 'POST') {
719
+ const content = Buffer.from(String(body.captionsFile ?? ''), 'base64').toString('utf8');
720
+ if (!/^(\uFEFF)?WEBVTT/.test(content) && !/^\d+\r?\n\d\d:/.test(content)) {
721
+ return json(res, 400, statusModel(400, 'Invalid captions file'));
722
+ }
723
+ const caption = {
724
+ label: body.label ?? third,
725
+ srclang: third,
726
+ version: 1
727
+ };
728
+ video.captions = [
729
+ ...(video.captions ?? []).filter((c)=>c.srclang !== third),
730
+ caption
731
+ ];
732
+ video.captionFiles.set(third, content);
733
+ return json(res, 200, statusModel(200, 'OK'));
734
+ }
735
+ if (method === 'DELETE') {
736
+ if (!(video.captions ?? []).some((c)=>c.srclang === third)) {
737
+ return json(res, 404, statusModel(404, 'Caption not found'));
738
+ }
739
+ video.captions = (video.captions ?? []).filter((c)=>c.srclang !== third);
740
+ video.captionFiles.delete(third);
741
+ return json(res, 200, statusModel(200, 'OK'));
742
+ }
743
+ }
744
+ if (second === 'transcribe' && !third && method === 'POST') {
745
+ const languages = Array.isArray(body.targetLanguages) ? body.targetLanguages : [];
746
+ if (video.status !== BUNNY_VIDEO_STATUS.Finished) {
747
+ return json(res, 400, statusModel(400, 'The video is not ready'));
748
+ }
749
+ this.schedule(()=>{
750
+ if (!this.videos.has(video.guid)) {
751
+ return;
752
+ }
753
+ for (const language of languages.length ? languages : [
754
+ 'en'
755
+ ]){
756
+ const srclang = `${language}-auto`;
757
+ video.captions = [
758
+ ...(video.captions ?? []).filter((c)=>c.srclang !== srclang),
759
+ {
760
+ label: `${language} (auto-generated)`,
761
+ srclang,
762
+ version: 1
763
+ }
764
+ ];
765
+ video.captionFiles.set(srclang, `WEBVTT\n\n00:00.000 --> 00:01.000\n[${language}]\n`);
766
+ }
767
+ void this.sendWebhook(video, BUNNY_WEBHOOK_STATUS.CaptionsGenerated);
768
+ }, this.options.processingDelayMs);
769
+ return json(res, 200, statusModel(200, 'OK'));
770
+ }
771
+ return json(res, 404, statusModel(404, 'Not Found'));
772
+ }
773
+ }
774
+ /** Starts a fake Bunny Stream server. Remember to `await fake.stop()`. */ export const startFakeBunnyStream = (options)=>new FakeBunnyStream(options).start();
775
+
776
+ //# sourceMappingURL=bunny.js.map