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 @@
1
+ {"version":3,"sources":["../../../src/providers/bunny/provider.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\n\nimport type {\n AssetPatch,\n CaptionTrack,\n DirectUpload,\n ImportInput,\n NeutralAsset,\n PlaybackOptions,\n PlaybackResult,\n PlaybackUrls,\n ProviderCapabilities,\n ProviderRef,\n ProviderWebhook,\n WebhookSetup,\n ServerUploadInput,\n StoredAsset,\n UploadInput,\n VideoProvider,\n} from '../../core/provider.js'\nimport type { BunnyStreamOptions, ResolvedBunnyStreamOptions } from './options.js'\nimport type { BunnyVideo, BunnyWebhookPayload } from './types.js'\n\nimport { BunnyStreamClient, BunnyStreamError } from './client.js'\nimport { captionToNeutral, metaTag, mp4FallbackFile, toMetaTags, videoToAsset } from './mapping.js'\nimport { resolveBunnyOptions } from './options.js'\nimport { cdnToken, tusUploadSignature } from './signing.js'\nimport { cdnFileUrl, embedUrl, hlsUrl, signedEmbedUrl, videoFileSigner } from './urls.js'\nimport { isBunnyWebhookPayload, parseBunnyDate, verifyBunnyWebhook } from './webhook.js'\n\nexport const BUNNY_CAPABILITIES: ProviderCapabilities = {\n adoptExisting: true,\n // Embedding is restricted per library (allowed referrers), not per video.\n allowedOrigins: false,\n captions: { generate: true, upload: true },\n dash: false,\n // MP4 fallback is a library setting (EnableMP4Fallback) that applies to new uploads.\n downloads: { managed: 'library', types: ['default'] },\n importFromUrl: true,\n progress: true,\n serverUpload: true,\n // Token authentication (embed and CDN) is a library setting.\n signedPlayback: 'library',\n // The poster position is applied when a video is created; Bunny has no API to move it afterwards.\n thumbnailTime: false,\n uploadProtocols: ['tus'],\n webhooks: true,\n}\n\nconst LIST_PAGE_SIZE = 1000\n/** How long a requested transcription is listed as `processing` before Bunny reports the track. */\nconst PENDING_CAPTION_TTL_MS = 60 * 60 * 1000\n\nconst requireGuid = (ref: ProviderRef): string => {\n if (!ref.assetId) {\n throw new Error('[payload-video-streaming] bunny: this video has no Bunny Stream video id')\n }\n return ref.assetId\n}\n\n/** Bunny Stream as a video provider. Create it with `bunnyStream({ … })`. */\nexport class BunnyStreamProvider implements VideoProvider {\n readonly capabilities = BUNNY_CAPABILITIES\n readonly captions: NonNullable<VideoProvider['captions']>\n readonly client: BunnyStreamClient\n readonly id: string\n readonly label: string\n readonly options: ResolvedBunnyStreamOptions\n readonly webhook?: ProviderWebhook\n readonly webhookSetup: WebhookSetup = {\n secret: 'BUNNY_STREAM_WEBHOOK_SECRET (`webhook.secret`)',\n secretLocation: \"the video library's Read-Only API key (Stream → your library → API), which Bunny signs webhooks with\",\n steps: [\n 'In the bunny.net dashboard, open Stream → your library → API and set the Webhook URL to {url}.',\n \"Set the library's Read-Only API key (same page) as BUNNY_STREAM_WEBHOOK_SECRET (or `webhook.secret`).\",\n ],\n }\n /** Transcriptions requested from this process, by video and language, until Bunny lists the track. */\n private readonly pendingCaptions = new Map<string, Map<string, number>>()\n\n constructor(options: BunnyStreamOptions) {\n this.options = resolveBunnyOptions(options)\n this.id = this.options.id\n this.label = this.options.label\n this.client = new BunnyStreamClient({\n apiBaseUrl: this.options.apiBaseUrl,\n apiKey: this.options.apiKey,\n fetch: this.options.fetch,\n libraryId: this.options.libraryId,\n })\n\n this.captions = {\n generate: (ref, language) => this.generateCaption(requireGuid(ref), language),\n list: (ref) => this.listCaptions(requireGuid(ref)),\n remove: async (ref, language) => {\n const guid = requireGuid(ref)\n this.pendingCaptions.get(guid)?.delete(language.replace(/-auto$/i, ''))\n await this.client.deleteCaption(guid, language)\n },\n upload: async (ref, language, vtt) => {\n await this.client.addCaption(requireGuid(ref), language, vtt)\n return { generated: false, label: language, language, status: 'ready' }\n },\n }\n\n if (this.options.webhook.secret) {\n this.webhook = { handle: (input) => this.handleWebhook(input) }\n }\n }\n\n /** True when the library uses token authentication, i.e. a token key is configured. */\n get signsPlayback(): boolean {\n return Boolean(this.options.embedTokenKey || this.options.cdnTokenKey)\n }\n\n private asset(video: BunnyVideo): NeutralAsset {\n return videoToAsset(video, { signedPlayback: this.signsPlayback })\n }\n\n // ---------------------------------------------------------------------------\n // Uploads\n // ---------------------------------------------------------------------------\n\n /** Creates a video, then stores meta tags (plugin `meta` and the creator) when there are any. */\n private async createVideo(input: Pick<UploadInput, 'creator' | 'meta' | 'thumbnailTime' | 'title'>): Promise<BunnyVideo> {\n const video = await this.client.createVideo({\n ...(this.options.collectionId ? { collectionId: this.options.collectionId } : {}),\n ...(typeof input.thumbnailTime === 'number' ? { thumbnailTime: Math.round(input.thumbnailTime * 1000) } : {}),\n title: input.title,\n })\n const metaTags = toMetaTags(input.meta, input.creator)\n if (metaTags.length) {\n try {\n await this.client.updateVideo(video.guid, { metaTags })\n } catch (err) {\n await this.client.deleteVideo(video.guid).catch(() => undefined)\n throw err\n }\n video.metaTags = metaTags\n }\n return video\n }\n\n /**\n * Creates the video, then signs a tus upload the browser sends straight to Bunny\n * (`AuthorizationSignature` = SHA256(libraryId + apiKey + expires + videoId)). The API key itself\n * never leaves the server.\n */\n async createDirectUpload(input: UploadInput): Promise<DirectUpload> {\n const video = await this.createVideo(input)\n const expires = Math.floor(Date.now() / 1000) + this.options.upload.tusSignatureTtlSeconds\n const { libraryId } = this.options\n return {\n ...(this.options.upload.tusChunkSize ? { chunkSize: this.options.upload.tusChunkSize } : {}),\n endpoint: this.options.upload.tusEndpoint,\n headers: {\n AuthorizationExpire: String(expires),\n AuthorizationSignature: tusUploadSignature({ apiKey: this.options.apiKey, expires, libraryId, videoId: video.guid }),\n LibraryId: libraryId,\n VideoId: video.guid,\n },\n metadata: {\n title: input.title,\n ...(this.options.collectionId ? { collection: this.options.collectionId } : {}),\n ...(typeof input.thumbnailTime === 'number' ? { thumbnailTime: String(Math.round(input.thumbnailTime * 1000)) } : {}),\n },\n protocol: 'tus',\n ref: { assetId: video.guid },\n }\n }\n\n /**\n * Has Bunny fetch the video. Bunny documents no video id in the response, so when it doesn't send\n * one the video is found by a unique temporary title, which is then replaced by the real one.\n */\n async importFromUrl(input: ImportInput): Promise<NeutralAsset> {\n const marker = `pvs-import-${randomBytes(8).toString('hex')}`\n const query = {\n ...(this.options.collectionId ? { collectionId: this.options.collectionId } : {}),\n ...(typeof input.thumbnailTime === 'number' ? { thumbnailTime: Math.round(input.thumbnailTime * 1000) } : {}),\n }\n const result = await this.client.fetchVideo({ title: marker, url: input.url }, query)\n let guid = result.guid\n if (!guid) {\n const found = await this.client.listVideos({ itemsPerPage: 100, orderBy: 'date', page: 1, search: marker })\n guid = (found.items ?? []).find((v) => v.title === marker)?.guid\n }\n if (!guid) {\n throw new BunnyStreamError('Bunny Stream accepted the import, but the new video could not be found', 502)\n }\n await this.client.updateVideo(guid, { metaTags: toMetaTags(input.meta, input.creator), title: input.title }).catch(async (err) => {\n await this.client.deleteVideo(guid).catch(() => undefined)\n throw err\n })\n const asset = this.asset(await this.client.getVideo(guid))\n // Bunny is fetching the file, so the video isn't waiting for an upload from us.\n return asset.status === 'waiting' ? { ...asset, status: 'queued' } : asset\n }\n\n async uploadFile(input: ServerUploadInput): Promise<NeutralAsset> {\n const video = await this.createVideo(input)\n try {\n await this.client.uploadVideo(video.guid, input.file)\n } catch (err) {\n await this.client.deleteVideo(video.guid).catch(() => undefined)\n throw err\n }\n return this.asset(await this.client.getVideo(video.guid))\n }\n\n // ---------------------------------------------------------------------------\n // Assets\n // ---------------------------------------------------------------------------\n\n async getAsset(ref: ProviderRef): Promise<NeutralAsset | null> {\n try {\n return this.asset(await this.client.getVideo(requireGuid(ref)))\n } catch (err) {\n if (err instanceof BunnyStreamError && err.isNotFound) {\n return null\n }\n throw err\n }\n }\n\n /** Pages through the library, newest first; the cursor is the next page number. */\n async listAssets({ creator, cursor }: { creator?: string; cursor?: string } = {}): Promise<{ assets: NeutralAsset[]; next?: string }> {\n const page = Math.max(1, Number.parseInt(cursor ?? '1', 10) || 1)\n const list = await this.client.listVideos({\n itemsPerPage: LIST_PAGE_SIZE,\n orderBy: 'date',\n page,\n ...(this.options.collectionId ? { collection: this.options.collectionId } : {}),\n })\n const items = list.items ?? []\n const perPage = list.itemsPerPage || LIST_PAGE_SIZE\n const total = list.totalItems ?? 0\n const next = items.length > 0 && page * perPage < total ? String(page + 1) : undefined\n const assets = items.filter((v) => !creator || metaTag(v.metaTags, 'creator') === creator).map((v) => this.asset(v))\n return { assets, next }\n }\n\n /** Pushes the title and meta tags. Signing, origins and the poster are library or creation settings. */\n async updateAsset(ref: ProviderRef, patch: AssetPatch): Promise<NeutralAsset | null> {\n if (patch.title === undefined && patch.meta === undefined) {\n return null\n }\n const guid = requireGuid(ref)\n const current = await this.client.getVideo(guid)\n await this.client.updateVideo(guid, {\n ...(patch.meta !== undefined ? { metaTags: toMetaTags(patch.meta, metaTag(current.metaTags, 'creator') ?? undefined) } : {}),\n ...(patch.title ? { title: patch.title } : {}),\n })\n return this.asset(await this.client.getVideo(guid))\n }\n\n async deleteAsset(ref: ProviderRef): Promise<void> {\n await this.client.deleteVideo(requireGuid(ref))\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /**\n * Playback URLs. Token authentication is library-wide, so whether URLs are signed follows the\n * configured keys (not the document): the embed URL gets a view token (`embedTokenKey`), the CDN\n * files a directory token (`cdnTokenKey`) that also covers HLS renditions and segments.\n */\n async playback(asset: StoredAsset, options: PlaybackOptions): Promise<PlaybackResult> {\n const { cdnBaseUrl, cdnTokenKey, embedBaseUrl, embedTokenKey, libraryId, playback } = this.options\n const guid = asset.assetId\n const signed = this.signsPlayback\n if (signed && !options.sign) {\n return { signed: false, urls: null }\n }\n const video = (asset.providerData ?? null) as null | Partial<BunnyVideo>\n const thumbnailFile = video?.thumbnailFileName || 'thumbnail.jpg'\n const mp4File = video?.hasMP4Fallback ? mp4FallbackFile(video as BunnyVideo) : undefined\n const expires = Math.floor(Date.now() / 1000) + options.expiresIn\n const iframeOptions = { ...playback.iframe, ...(options.providerOptions?.iframe as object | undefined) }\n\n const iframe = embedTokenKey\n ? signedEmbedUrl({ embedBaseUrl, expires, libraryId, tokenKey: embedTokenKey, videoId: guid }, iframeOptions)\n : embedUrl(embedBaseUrl, libraryId, guid, iframeOptions)\n\n let urls: PlaybackUrls\n let token: string | undefined\n if (cdnTokenKey) {\n const sign = videoFileSigner(cdnBaseUrl, guid, { countries: playback.tokenCountries, expires, key: cdnTokenKey })\n urls = {\n animated: sign('preview.webp'),\n hls: sign('playlist.m3u8', { directory: true }),\n iframe,\n thumbnail: sign(thumbnailFile),\n ...(mp4File ? { downloadMp4: sign(mp4File) } : {}),\n }\n token = cdnToken(cdnTokenKey, '', {\n countriesAllowed: playback.tokenCountries,\n expires,\n tokenPath: new URL(cdnFileUrl(cdnBaseUrl, guid, '')).pathname,\n }).token\n } else {\n urls = {\n animated: cdnFileUrl(cdnBaseUrl, guid, 'preview.webp'),\n hls: hlsUrl(cdnBaseUrl, guid),\n iframe,\n thumbnail: cdnFileUrl(cdnBaseUrl, guid, thumbnailFile),\n ...(mp4File ? { downloadMp4: cdnFileUrl(cdnBaseUrl, guid, mp4File) } : {}),\n }\n token = embedTokenKey ? (new URL(iframe).searchParams.get('token') ?? undefined) : undefined\n }\n return signed ? { expiresAt: new Date(expires * 1000).toISOString(), signed: true, token, urls } : { signed: false, urls }\n }\n\n // ---------------------------------------------------------------------------\n // Captions\n // ---------------------------------------------------------------------------\n\n private async listCaptions(guid: string): Promise<CaptionTrack[]> {\n const video = await this.client.getVideo(guid)\n const tracks = (video.captions ?? []).map(captionToNeutral).filter((c): c is CaptionTrack => c !== null)\n const pending = this.pendingCaptions.get(guid)\n if (pending) {\n const now = Date.now()\n for (const [language, requestedAt] of pending) {\n const done = tracks.some((t) => t.language.replace(/-auto$/i, '') === language && t.generated)\n if (done || now - requestedAt > PENDING_CAPTION_TTL_MS) {\n pending.delete(language)\n } else {\n tracks.push({ generated: true, label: `${language} (auto-generated)`, language: `${language}-auto`, status: 'processing' })\n }\n }\n if (!pending.size) {\n this.pendingCaptions.delete(guid)\n }\n }\n return tracks\n }\n\n /** Starts AI transcription (Bunny auto-detects the spoken language). The track appears as `<lang>-auto`. */\n private async generateCaption(guid: string, language: string): Promise<CaptionTrack> {\n const target = language.replace(/-auto$/i, '').split('-')[0]!.toLowerCase()\n if (!/^[a-z]{2}$/.test(target)) {\n // A request error (HTTP 400), not a provider failure.\n throw Object.assign(new Error(`Bunny transcribes into ISO 639-1 languages (two letters, e.g. \"en\"), not \"${language}\"`), { status: 400 })\n }\n await this.client.transcribe(guid, { targetLanguages: [target] })\n const pending = this.pendingCaptions.get(guid) ?? new Map<string, number>()\n pending.set(target, Date.now())\n this.pendingCaptions.set(guid, pending)\n return { generated: true, label: `${target} (auto-generated)`, language: `${target}-auto`, status: 'processing' }\n }\n\n // ---------------------------------------------------------------------------\n // Webhooks\n // ---------------------------------------------------------------------------\n\n /**\n * Verifies a notification and asks the core to re-fetch the video. Bunny's notifications carry only\n * a status code, so the current state is read from the API: that is robust to retries and to events\n * arriving out of order. Duplicates are dropped by `EventId`; very old events are rejected.\n */\n private async handleWebhook({ headers, rawBody }: { headers: Headers; rawBody: string }) {\n const verification = verifyBunnyWebhook({ headers, rawBody, secret: this.options.webhook.secret ?? '' })\n if (!verification.ok) {\n return { ok: false as const, reason: `invalid signature (${verification.reason})`, status: 401 as const }\n }\n let payload: unknown\n try {\n payload = JSON.parse(rawBody)\n } catch {\n return { ok: false as const, reason: 'Invalid JSON body', status: 400 as const }\n }\n if (!isBunnyWebhookPayload(payload)) {\n return { ok: false as const, reason: 'Webhook payload has no VideoGuid/Status', status: 400 as const }\n }\n const event = payload as BunnyWebhookPayload\n if (event.IsLiveStreamWebhook || String(event.VideoLibraryId) !== this.options.libraryId) {\n return { events: [], ok: true as const }\n }\n const tolerance = this.options.webhook.toleranceSeconds\n const at = parseBunnyDate(event.Timestamp)\n if (tolerance > 0 && at !== null && Date.now() - at > tolerance * 1000) {\n return { ok: false as const, reason: 'stale notification', status: 400 as const }\n }\n return { events: [{ ...(event.EventId ? { eventId: String(event.EventId) } : {}), ref: { assetId: event.VideoGuid } }], ok: true as const }\n }\n}\n\n/**\n * Bunny Stream as a video provider:\n *\n * ```ts\n * videoPlugin({ providers: [bunnyStream({ libraryId, apiKey, cdnHostname })] })\n * ```\n */\nexport const bunnyStream = (options: BunnyStreamOptions): BunnyStreamProvider => new BunnyStreamProvider(options)\n"],"names":["randomBytes","BunnyStreamClient","BunnyStreamError","captionToNeutral","metaTag","mp4FallbackFile","toMetaTags","videoToAsset","resolveBunnyOptions","cdnToken","tusUploadSignature","cdnFileUrl","embedUrl","hlsUrl","signedEmbedUrl","videoFileSigner","isBunnyWebhookPayload","parseBunnyDate","verifyBunnyWebhook","BUNNY_CAPABILITIES","adoptExisting","allowedOrigins","captions","generate","upload","dash","downloads","managed","types","importFromUrl","progress","serverUpload","signedPlayback","thumbnailTime","uploadProtocols","webhooks","LIST_PAGE_SIZE","PENDING_CAPTION_TTL_MS","requireGuid","ref","assetId","Error","BunnyStreamProvider","capabilities","client","id","label","options","webhook","webhookSetup","secret","secretLocation","steps","pendingCaptions","Map","apiBaseUrl","apiKey","fetch","libraryId","language","generateCaption","list","listCaptions","remove","guid","get","delete","replace","deleteCaption","vtt","addCaption","generated","status","handle","input","handleWebhook","signsPlayback","Boolean","embedTokenKey","cdnTokenKey","asset","video","createVideo","collectionId","Math","round","title","metaTags","meta","creator","length","updateVideo","err","deleteVideo","catch","undefined","createDirectUpload","expires","floor","Date","now","tusSignatureTtlSeconds","tusChunkSize","chunkSize","endpoint","tusEndpoint","headers","AuthorizationExpire","String","AuthorizationSignature","videoId","LibraryId","VideoId","metadata","collection","protocol","marker","toString","query","result","fetchVideo","url","found","listVideos","itemsPerPage","orderBy","page","search","items","find","v","getVideo","uploadFile","uploadVideo","file","getAsset","isNotFound","listAssets","cursor","max","Number","parseInt","perPage","total","totalItems","next","assets","filter","map","updateAsset","patch","current","deleteAsset","playback","cdnBaseUrl","embedBaseUrl","signed","sign","urls","providerData","thumbnailFile","thumbnailFileName","mp4File","hasMP4Fallback","expiresIn","iframeOptions","iframe","providerOptions","tokenKey","token","countries","tokenCountries","key","animated","hls","directory","thumbnail","downloadMp4","countriesAllowed","tokenPath","URL","pathname","searchParams","expiresAt","toISOString","tracks","c","pending","requestedAt","done","some","t","push","size","target","split","toLowerCase","test","Object","assign","transcribe","targetLanguages","set","rawBody","verification","ok","reason","payload","JSON","parse","event","IsLiveStreamWebhook","VideoLibraryId","events","tolerance","toleranceSeconds","at","Timestamp","EventId","eventId","VideoGuid","bunnyStream"],"mappings":"AAAA,SA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IAAIuI;QACJ,IAAI;YACFA,UAAUC,KAAKC,KAAK,CAACN;QACvB,EAAE,OAAM;YACN,OAAO;gBAAEE,IAAI;gBAAgBC,QAAQ;gBAAqBtI,QAAQ;YAAa;QACjF;QACA,IAAI,CAACxD,sBAAsB+L,UAAU;YACnC,OAAO;gBAAEF,IAAI;gBAAgBC,QAAQ;gBAA2CtI,QAAQ;YAAa;QACvG;QACA,MAAM0I,QAAQH;QACd,IAAIG,MAAMC,mBAAmB,IAAIvG,OAAOsG,MAAME,cAAc,MAAM,IAAI,CAACrK,OAAO,CAACW,SAAS,EAAE;YACxF,OAAO;gBAAE2J,QAAQ,EAAE;gBAAER,IAAI;YAAc;QACzC;QACA,MAAMS,YAAY,IAAI,CAACvK,OAAO,CAACC,OAAO,CAACuK,gBAAgB;QACvD,MAAMC,KAAKvM,eAAeiM,MAAMO,SAAS;QACzC,IAAIH,YAAY,KAAKE,OAAO,QAAQrH,KAAKC,GAAG,KAAKoH,KAAKF,YAAY,MAAM;YACtE,OAAO;gBAAET,IAAI;gBAAgBC,QAAQ;gBAAsBtI,QAAQ;YAAa;QAClF;QACA,OAAO;YAAE6I,QAAQ;gBAAC;oBAAE,GAAIH,MAAMQ,OAAO,GAAG;wBAAEC,SAAS/G,OAAOsG,MAAMQ,OAAO;oBAAE,IAAI,CAAC,CAAC;oBAAGnL,KAAK;wBAAEC,SAAS0K,MAAMU,SAAS;oBAAC;gBAAE;aAAE;YAAEf,IAAI;QAAc;IAC5I;AACF;AAEA;;;;;;CAMC,GACD,OAAO,MAAMgB,cAAc,CAAC9K,UAAqD,IAAIL,oBAAoBK,SAAQ"}
@@ -0,0 +1,61 @@
1
+ /** `AuthorizationSignature` for a tus upload: hex SHA256 of `libraryId + apiKey + expires + videoId`. */
2
+ export declare const tusUploadSignature: (args: {
3
+ apiKey: string;
4
+ expires: number;
5
+ libraryId: number | string;
6
+ videoId: string;
7
+ }) => string;
8
+ /** Embed view token: hex SHA256 of `tokenKey + videoId + expires` (the library's token authentication key). */
9
+ export declare const embedViewToken: (args: {
10
+ expires: number;
11
+ tokenKey: string;
12
+ videoId: string;
13
+ }) => string;
14
+ /** Constant-time comparison of two hex strings (case-insensitive). */
15
+ export declare const hexEquals: (a: string, b: string) => boolean;
16
+ /** The IP address as bytes for the CDN token: 4 bytes for IPv4, IPv6 masked to its /64 prefix. */
17
+ export declare const ipToTokenBytes: (ip: string) => Buffer;
18
+ export type CdnTokenOptions = {
19
+ /** Comma-separated ISO country codes allowed to use the token. */
20
+ countriesAllowed?: string;
21
+ /** Comma-separated ISO country codes blocked from using the token. */
22
+ countriesBlocked?: string;
23
+ /** Unix time (seconds) when the token expires. */
24
+ expires: number;
25
+ /** Signs a directory: every file whose path starts with this (e.g. `/{guid}/`) is covered. */
26
+ tokenPath?: string;
27
+ /** Lock the token to this IP (IPv6 is locked to its /64). */
28
+ userIp?: string;
29
+ };
30
+ /** Computes an advanced CDN token (`HS256-…`) for a URL path. */
31
+ export declare const cdnToken: (key: string, path: string, options: CdnTokenOptions) => {
32
+ params: [string, string][];
33
+ token: string;
34
+ };
35
+ /**
36
+ * Signs a CDN URL with advanced token authentication.
37
+ * - `directory: false`: `…/file?token=HS256-…&expires=…`
38
+ * - `directory: true`: `/bcdn_token=HS256-…&expires=…/file`, so relative URLs inside an HLS playlist
39
+ * (renditions, segments) inherit the token. Pass `tokenPath` to cover the whole directory.
40
+ */
41
+ export declare const signCdnUrl: (url: string, key: string, options: {
42
+ directory?: boolean;
43
+ } & CdnTokenOptions) => string;
44
+ /** Splits a path signed in directory form (`/bcdn_token=…&expires=…/rest`) into its token parameters and real path. */
45
+ export declare const parseDirectoryToken: (pathname: string) => {
46
+ params: URLSearchParams;
47
+ path: string;
48
+ } | null;
49
+ /**
50
+ * Verifies an advanced CDN token, as the CDN does (used by the fake; handy for your own tests).
51
+ * `params` are the request's token parameters (query string or directory segment).
52
+ */
53
+ export declare const verifyCdnToken: (key: string, path: string, params: URLSearchParams, { now, userIp }?: {
54
+ now?: number;
55
+ userIp?: string;
56
+ }) => {
57
+ ok: true;
58
+ } | {
59
+ ok: false;
60
+ reason: "expired" | "invalid" | "missing" | "path";
61
+ };
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Bunny signatures, all built with node:crypto:
3
+ * - the tus upload signature (`AuthorizationSignature`)
4
+ * - the embed (iframe) view token
5
+ * - CDN "advanced" token authentication (`HS256-…`), including directory tokens for HLS
6
+ * @see https://bunny.net/docs/stream/tus-resumable-uploads
7
+ * @see https://bunny.net/docs/stream/token-authentication
8
+ * @see https://bunny.net/docs/cdn/security/token-authentication/advanced
9
+ */ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
10
+ import { isIP } from 'node:net';
11
+ const sha256Hex = (value)=>createHash('sha256').update(value, 'utf8').digest('hex');
12
+ /** `AuthorizationSignature` for a tus upload: hex SHA256 of `libraryId + apiKey + expires + videoId`. */ export const tusUploadSignature = (args)=>sha256Hex(`${args.libraryId}${args.apiKey}${args.expires}${args.videoId}`);
13
+ /** Embed view token: hex SHA256 of `tokenKey + videoId + expires` (the library's token authentication key). */ export const embedViewToken = (args)=>sha256Hex(`${args.tokenKey}${args.videoId}${args.expires}`);
14
+ /** Constant-time comparison of two hex strings (case-insensitive). */ export const hexEquals = (a, b)=>{
15
+ if (!/^[0-9a-f]+$/i.test(a) || !/^[0-9a-f]+$/i.test(b) || a.length !== b.length) {
16
+ return false;
17
+ }
18
+ return timingSafeEqual(Buffer.from(a.toLowerCase(), 'hex'), Buffer.from(b.toLowerCase(), 'hex'));
19
+ };
20
+ /** The IP address as bytes for the CDN token: 4 bytes for IPv4, IPv6 masked to its /64 prefix. */ export const ipToTokenBytes = (ip)=>{
21
+ const family = isIP(ip);
22
+ if (family === 4) {
23
+ return Buffer.from(ip.split('.').map(Number));
24
+ }
25
+ if (family !== 6) {
26
+ throw new Error(`Invalid IP address "${ip}"`);
27
+ }
28
+ let value = ip;
29
+ let v4 = [];
30
+ const lastColon = value.lastIndexOf(':');
31
+ if (value.indexOf('.') > lastColon) {
32
+ v4 = value.slice(lastColon + 1).split('.').map(Number);
33
+ value = `${value.slice(0, lastColon)}:0:0`;
34
+ }
35
+ const [left = '', right] = value.split('::');
36
+ const head = left ? left.split(':') : [];
37
+ const tail = right ? right.split(':') : [];
38
+ const groups = right === undefined ? head : [
39
+ ...head,
40
+ ...Array(8 - head.length - tail.length).fill('0'),
41
+ ...tail
42
+ ];
43
+ const bytes = Buffer.alloc(16);
44
+ groups.forEach((group, i)=>bytes.writeUInt16BE(Number.parseInt(group, 16), i * 2));
45
+ v4.forEach((byte, i)=>bytes[12 + i] = byte);
46
+ bytes.fill(0, 8);
47
+ return bytes;
48
+ };
49
+ /** Computes an advanced CDN token (`HS256-…`) for a URL path. */ export const cdnToken = (key, path, options)=>{
50
+ if (!key) {
51
+ throw new Error('A CDN token authentication key is required');
52
+ }
53
+ const params = {};
54
+ if (options.countriesAllowed) {
55
+ params.token_countries = options.countriesAllowed;
56
+ }
57
+ if (options.countriesBlocked) {
58
+ params.token_countries_blocked = options.countriesBlocked;
59
+ }
60
+ if (options.tokenPath) {
61
+ params.token_path = options.tokenPath;
62
+ }
63
+ // Sorted by code point (the reference implementations agree on this for these keys).
64
+ const sorted = Object.entries(params).sort(([a], [b])=>a < b ? -1 : a > b ? 1 : 0);
65
+ const signingData = sorted.map(([k, v])=>`${k}=${v}`).join('&');
66
+ const ip = options.userIp ? ipToTokenBytes(options.userIp) : Buffer.alloc(0);
67
+ const digest = createHmac('sha256', key).update(options.tokenPath || path).update(String(options.expires)).update(ip).update(signingData).digest('base64url');
68
+ return {
69
+ params: sorted,
70
+ token: `HS256-${options.userIp ? '1-' : ''}${digest}`
71
+ };
72
+ };
73
+ /**
74
+ * Signs a CDN URL with advanced token authentication.
75
+ * - `directory: false`: `…/file?token=HS256-…&expires=…`
76
+ * - `directory: true`: `/bcdn_token=HS256-…&expires=…/file`, so relative URLs inside an HLS playlist
77
+ * (renditions, segments) inherit the token. Pass `tokenPath` to cover the whole directory.
78
+ */ export const signCdnUrl = (url, key, options)=>{
79
+ const parsed = new URL(url);
80
+ if (options.directory && parsed.search) {
81
+ throw new Error('Directory tokens do not support query parameters');
82
+ }
83
+ const { params, token } = cdnToken(key, parsed.pathname, options);
84
+ const tail = params.map(([k, v])=>`&${k}=${encodeURIComponent(v)}`).join('');
85
+ const base = `${parsed.protocol}//${parsed.host}`;
86
+ if (options.directory) {
87
+ return `${base}/bcdn_token=${token}${tail}&expires=${options.expires}${parsed.pathname}`;
88
+ }
89
+ const existing = parsed.search ? `${parsed.search}&` : '?';
90
+ return `${base}${parsed.pathname}${existing}token=${token}${tail}&expires=${options.expires}`;
91
+ };
92
+ /** Splits a path signed in directory form (`/bcdn_token=…&expires=…/rest`) into its token parameters and real path. */ export const parseDirectoryToken = (pathname)=>{
93
+ const match = /^\/(bcdn_token=[^/]*)(\/.*)$/.exec(pathname);
94
+ if (!match) {
95
+ return null;
96
+ }
97
+ return {
98
+ params: new URLSearchParams(match[1]),
99
+ path: match[2]
100
+ };
101
+ };
102
+ /**
103
+ * Verifies an advanced CDN token, as the CDN does (used by the fake; handy for your own tests).
104
+ * `params` are the request's token parameters (query string or directory segment).
105
+ */ export const verifyCdnToken = (key, path, params, { now = Math.floor(Date.now() / 1000), userIp } = {})=>{
106
+ const token = params.get('token') ?? params.get('bcdn_token');
107
+ const expires = Number(params.get('expires'));
108
+ if (!token || !Number.isFinite(expires)) {
109
+ return {
110
+ ok: false,
111
+ reason: 'missing'
112
+ };
113
+ }
114
+ if (expires < now) {
115
+ return {
116
+ ok: false,
117
+ reason: 'expired'
118
+ };
119
+ }
120
+ const tokenPath = params.get('token_path') ?? undefined;
121
+ if (tokenPath && !path.startsWith(tokenPath)) {
122
+ return {
123
+ ok: false,
124
+ reason: 'path'
125
+ };
126
+ }
127
+ const expected = cdnToken(key, path, {
128
+ countriesAllowed: params.get('token_countries') ?? undefined,
129
+ countriesBlocked: params.get('token_countries_blocked') ?? undefined,
130
+ expires,
131
+ tokenPath,
132
+ userIp: token.startsWith('HS256-1-') ? userIp : undefined
133
+ }).token;
134
+ const a = Buffer.from(token);
135
+ const b = Buffer.from(expected);
136
+ return a.length === b.length && timingSafeEqual(a, b) ? {
137
+ ok: true
138
+ } : {
139
+ ok: false,
140
+ reason: 'invalid'
141
+ };
142
+ };
143
+
144
+ //# sourceMappingURL=signing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/providers/bunny/signing.ts"],"sourcesContent":["/**\n * Bunny signatures, all built with node:crypto:\n * - the tus upload signature (`AuthorizationSignature`)\n * - the embed (iframe) view token\n * - CDN \"advanced\" token authentication (`HS256-…`), including directory tokens for HLS\n * @see https://bunny.net/docs/stream/tus-resumable-uploads\n * @see https://bunny.net/docs/stream/token-authentication\n * @see https://bunny.net/docs/cdn/security/token-authentication/advanced\n */\nimport { createHash, createHmac, timingSafeEqual } from 'node:crypto'\nimport { isIP } from 'node:net'\n\nconst sha256Hex = (value: string): string => createHash('sha256').update(value, 'utf8').digest('hex')\n\n/** `AuthorizationSignature` for a tus upload: hex SHA256 of `libraryId + apiKey + expires + videoId`. */\nexport const tusUploadSignature = (args: { apiKey: string; expires: number; libraryId: number | string; videoId: string }): string =>\n sha256Hex(`${args.libraryId}${args.apiKey}${args.expires}${args.videoId}`)\n\n/** Embed view token: hex SHA256 of `tokenKey + videoId + expires` (the library's token authentication key). */\nexport const embedViewToken = (args: { expires: number; tokenKey: string; videoId: string }): string =>\n sha256Hex(`${args.tokenKey}${args.videoId}${args.expires}`)\n\n/** Constant-time comparison of two hex strings (case-insensitive). */\nexport const hexEquals = (a: string, b: string): boolean => {\n if (!/^[0-9a-f]+$/i.test(a) || !/^[0-9a-f]+$/i.test(b) || a.length !== b.length) {\n return false\n }\n return timingSafeEqual(Buffer.from(a.toLowerCase(), 'hex'), Buffer.from(b.toLowerCase(), 'hex'))\n}\n\n/** The IP address as bytes for the CDN token: 4 bytes for IPv4, IPv6 masked to its /64 prefix. */\nexport const ipToTokenBytes = (ip: string): Buffer => {\n const family = isIP(ip)\n if (family === 4) {\n return Buffer.from(ip.split('.').map(Number))\n }\n if (family !== 6) {\n throw new Error(`Invalid IP address \"${ip}\"`)\n }\n let value = ip\n let v4: number[] = []\n const lastColon = value.lastIndexOf(':')\n if (value.indexOf('.') > lastColon) {\n v4 = value.slice(lastColon + 1).split('.').map(Number)\n value = `${value.slice(0, lastColon)}:0:0`\n }\n const [left = '', right] = value.split('::')\n const head = left ? left.split(':') : []\n const tail = right ? right.split(':') : []\n const groups = right === undefined ? head : [...head, ...Array<string>(8 - head.length - tail.length).fill('0'), ...tail]\n const bytes = Buffer.alloc(16)\n groups.forEach((group, i) => bytes.writeUInt16BE(Number.parseInt(group, 16), i * 2))\n v4.forEach((byte, i) => (bytes[12 + i] = byte))\n bytes.fill(0, 8)\n return bytes\n}\n\nexport type CdnTokenOptions = {\n /** Comma-separated ISO country codes allowed to use the token. */\n countriesAllowed?: string\n /** Comma-separated ISO country codes blocked from using the token. */\n countriesBlocked?: string\n /** Unix time (seconds) when the token expires. */\n expires: number\n /** Signs a directory: every file whose path starts with this (e.g. `/{guid}/`) is covered. */\n tokenPath?: string\n /** Lock the token to this IP (IPv6 is locked to its /64). */\n userIp?: string\n}\n\n/** Computes an advanced CDN token (`HS256-…`) for a URL path. */\nexport const cdnToken = (key: string, path: string, options: CdnTokenOptions): { params: [string, string][]; token: string } => {\n if (!key) {\n throw new Error('A CDN token authentication key is required')\n }\n const params: Record<string, string> = {}\n if (options.countriesAllowed) {\n params.token_countries = options.countriesAllowed\n }\n if (options.countriesBlocked) {\n params.token_countries_blocked = options.countriesBlocked\n }\n if (options.tokenPath) {\n params.token_path = options.tokenPath\n }\n // Sorted by code point (the reference implementations agree on this for these keys).\n const sorted = Object.entries(params).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n const signingData = sorted.map(([k, v]) => `${k}=${v}`).join('&')\n const ip = options.userIp ? ipToTokenBytes(options.userIp) : Buffer.alloc(0)\n const digest = createHmac('sha256', key)\n .update(options.tokenPath || path)\n .update(String(options.expires))\n .update(ip)\n .update(signingData)\n .digest('base64url')\n return { params: sorted, token: `HS256-${options.userIp ? '1-' : ''}${digest}` }\n}\n\n/**\n * Signs a CDN URL with advanced token authentication.\n * - `directory: false`: `…/file?token=HS256-…&expires=…`\n * - `directory: true`: `/bcdn_token=HS256-…&expires=…/file`, so relative URLs inside an HLS playlist\n * (renditions, segments) inherit the token. Pass `tokenPath` to cover the whole directory.\n */\nexport const signCdnUrl = (url: string, key: string, options: { directory?: boolean } & CdnTokenOptions): string => {\n const parsed = new URL(url)\n if (options.directory && parsed.search) {\n throw new Error('Directory tokens do not support query parameters')\n }\n const { params, token } = cdnToken(key, parsed.pathname, options)\n const tail = params.map(([k, v]) => `&${k}=${encodeURIComponent(v)}`).join('')\n const base = `${parsed.protocol}//${parsed.host}`\n if (options.directory) {\n return `${base}/bcdn_token=${token}${tail}&expires=${options.expires}${parsed.pathname}`\n }\n const existing = parsed.search ? `${parsed.search}&` : '?'\n return `${base}${parsed.pathname}${existing}token=${token}${tail}&expires=${options.expires}`\n}\n\n/** Splits a path signed in directory form (`/bcdn_token=…&expires=…/rest`) into its token parameters and real path. */\nexport const parseDirectoryToken = (pathname: string): { params: URLSearchParams; path: string } | null => {\n const match = /^\\/(bcdn_token=[^/]*)(\\/.*)$/.exec(pathname)\n if (!match) {\n return null\n }\n return { params: new URLSearchParams(match[1]!), path: match[2]! }\n}\n\n/**\n * Verifies an advanced CDN token, as the CDN does (used by the fake; handy for your own tests).\n * `params` are the request's token parameters (query string or directory segment).\n */\nexport const verifyCdnToken = (\n key: string,\n path: string,\n params: URLSearchParams,\n { now = Math.floor(Date.now() / 1000), userIp }: { now?: number; userIp?: string } = {},\n): { ok: true } | { ok: false; reason: 'expired' | 'invalid' | 'missing' | 'path' } => {\n const token = params.get('token') ?? params.get('bcdn_token')\n const expires = Number(params.get('expires'))\n if (!token || !Number.isFinite(expires)) {\n return { ok: false, reason: 'missing' }\n }\n if (expires < now) {\n return { ok: false, reason: 'expired' }\n }\n const tokenPath = params.get('token_path') ?? undefined\n if (tokenPath && !path.startsWith(tokenPath)) {\n return { ok: false, reason: 'path' }\n }\n const expected = cdnToken(key, path, {\n countriesAllowed: params.get('token_countries') ?? undefined,\n countriesBlocked: params.get('token_countries_blocked') ?? undefined,\n expires,\n tokenPath,\n userIp: token.startsWith('HS256-1-') ? userIp : undefined,\n }).token\n const a = Buffer.from(token)\n const b = Buffer.from(expected)\n return a.length === b.length && timingSafeEqual(a, b) ? { ok: true } : { ok: false, reason: 'invalid' }\n}\n"],"names":["createHash","createHmac","timingSafeEqual","isIP","sha256Hex","value","update","digest","tusUploadSignature","args","libraryId","apiKey","expires","videoId","embedViewToken","tokenKey","hexEquals","a","b","test","length","Buffer","from","toLowerCase","ipToTokenBytes","ip","family","split","map","Number","Error","v4","lastColon","lastIndexOf","indexOf","slice","left","right","head","tail","groups","undefined","Array","fill","bytes","alloc","forEach","group","i","writeUInt16BE","parseInt","byte","cdnToken","key","path","options","params","countriesAllowed","token_countries","countriesBlocked","token_countries_blocked","tokenPath","token_path","sorted","Object","entries","sort","signingData","k","v","join","userIp","String","token","signCdnUrl","url","parsed","URL","directory","search","pathname","encodeURIComponent","base","protocol","host","existing","parseDirectoryToken","match","exec","URLSearchParams","verifyCdnToken","now","Math","floor","Date","get","isFinite","ok","reason","startsWith","expected"],"mappings":"AAAA;;;;;;;;CAQC,GACD,SAASA,UAAU,EAAEC,UAAU,EAAEC,eAAe,QAAQ,cAAa;AACrE,SAASC,IAAI,QAAQ,WAAU;AAE/B,MAAMC,YAAY,CAACC,QAA0BL,WAAW,UAAUM,MAAM,CAACD,OAAO,QAAQE,MAAM,CAAC;AAE/F,uGAAuG,GACvG,OAAO,MAAMC,qBAAqB,CAACC,OACjCL,UAAU,GAAGK,KAAKC,SAAS,GAAGD,KAAKE,MAAM,GAAGF,KAAKG,OAAO,GAAGH,KAAKI,OAAO,EAAE,EAAC;AAE5E,6GAA6G,GAC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}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Hand-written types for the parts of the Bunny Stream API the plugin uses. They are checked against
3
+ * the types generated from Bunny's OpenAPI spec (`openapi.ts`, see `sdk-compat.ts`), but are kept
4
+ * separate so the published declarations never depend on the generated file.
5
+ * @see https://video.bunnycdn.com/openapi/bunnynet-video-api.public.json
6
+ */
7
+ /** `status` of a video in the Stream API (`VideoModelStatus`). */
8
+ export declare const BUNNY_VIDEO_STATUS: {
9
+ readonly Created: 0;
10
+ readonly Uploaded: 1;
11
+ readonly Processing: 2;
12
+ readonly Transcoding: 3;
13
+ readonly Finished: 4;
14
+ readonly Error: 5;
15
+ readonly UploadFailed: 6;
16
+ readonly JitSegmenting: 7;
17
+ readonly JitPlaylistsCreated: 8;
18
+ };
19
+ export type BunnyVideoStatus = (typeof BUNNY_VIDEO_STATUS)[keyof typeof BUNNY_VIDEO_STATUS];
20
+ /** `Status` of a webhook notification. These numbers differ from the API's `status`! */
21
+ export declare const BUNNY_WEBHOOK_STATUS: {
22
+ readonly Queued: 0;
23
+ readonly Processing: 1;
24
+ readonly Encoding: 2;
25
+ readonly Finished: 3;
26
+ readonly ResolutionFinished: 4;
27
+ readonly Failed: 5;
28
+ readonly PresignedUploadStarted: 6;
29
+ readonly PresignedUploadFinished: 7;
30
+ readonly PresignedUploadFailed: 8;
31
+ readonly CaptionsGenerated: 9;
32
+ readonly TitleOrDescriptionGenerated: 10;
33
+ readonly CaptionGenerationFailed: 11;
34
+ readonly ChaptersGenerated: 12;
35
+ readonly MomentsGenerated: 13;
36
+ readonly VideoDeleted: 32;
37
+ readonly SmartGenerationFailed: 33;
38
+ };
39
+ export type BunnyWebhookStatus = (typeof BUNNY_WEBHOOK_STATUS)[keyof typeof BUNNY_WEBHOOK_STATUS];
40
+ /** `IssueCodes` of a transcoding message, by number. */
41
+ export declare const BUNNY_ISSUE_CODES: readonly ["Undefined", "StreamLengthsDifference", "TranscodingWarnings", "IncompatibleResolution", "InvalidFramerate", "VideoExceededMaxDuration", "AudioExceededMaxDuration", "OriginalCorrupted", "TranscriptionFailed", "JitIncompatible", "JitFailed", "CaptionGenerationFailed", "UnsupportedFileType", "LiveNoEncoderCapacity", "LiveStreamBlocked", "LiveTooManyIngests", "LiveRegionConflict", "LivePublishAfterEnd", "LiveMediaStalled", "LiveEncoderLost", "LiveFailedOverToBackup", "LiveIngestRejected", "LiveIngestTimeout", "LiveMaxDurationReached", "LiveLibraryDisabled", "LiveDisconnectTimeout"];
42
+ export type BunnyCaption = {
43
+ label?: null | string;
44
+ srclang?: null | string;
45
+ version?: number;
46
+ };
47
+ export type BunnyMetaTag = {
48
+ property?: null | string;
49
+ value?: null | string;
50
+ };
51
+ export type BunnyTranscodingMessage = {
52
+ /** Number from `BUNNY_ISSUE_CODES`. */
53
+ issueCode?: number;
54
+ /** 0 Undefined, 1 Information, 2 Warning, 3 Error. */
55
+ level?: number;
56
+ message?: null | string;
57
+ timeStamp?: string;
58
+ value?: null | string;
59
+ };
60
+ /** A video as returned by `GET /library/{libraryId}/videos/{videoId}` (`VideoModel`, abridged). */
61
+ export type BunnyVideo = {
62
+ /** Comma-separated resolutions that finished encoding, e.g. `360p,720p`. */
63
+ availableResolutions?: null | string;
64
+ averageWatchTime?: number;
65
+ captions?: BunnyCaption[] | null;
66
+ category?: null | string;
67
+ collectionId?: null | string;
68
+ /** ISO date (Bunny may omit the time zone; it is UTC). */
69
+ dateUploaded: string;
70
+ description?: null | string;
71
+ /** Encoding progress, 0–100. */
72
+ encodeProgress: number;
73
+ framerate?: number;
74
+ guid: string;
75
+ /** MP4 fallback files (`play_720p.mp4`…) exist for this video. */
76
+ hasMP4Fallback: boolean;
77
+ height: number;
78
+ isPublic?: boolean;
79
+ jitEncodingEnabled?: boolean | null;
80
+ /** Duration in seconds. */
81
+ length: number;
82
+ metaTags?: BunnyMetaTag[] | null;
83
+ outputCodecs?: string;
84
+ status: BunnyVideoStatus;
85
+ /** Bytes. */
86
+ storageSize: number;
87
+ thumbnailCount?: number;
88
+ /** e.g. `thumbnail.jpg`. */
89
+ thumbnailFileName?: null | string;
90
+ title: string;
91
+ totalWatchTime?: number;
92
+ transcodingMessages?: BunnyTranscodingMessage[] | null;
93
+ videoLibraryId: number;
94
+ views?: number;
95
+ width: number;
96
+ };
97
+ /** `PaginationListOfVideoModel`. */
98
+ export type BunnyVideoList = {
99
+ currentPage?: number;
100
+ items?: BunnyVideo[] | null;
101
+ itemsPerPage?: number;
102
+ totalItems?: number;
103
+ };
104
+ /** `StatusModel`, the body of most write responses and of errors. */
105
+ export type BunnyStatusModel = {
106
+ message?: null | string;
107
+ statusCode?: number;
108
+ success?: boolean;
109
+ };
110
+ export type BunnyCreateVideoRequest = {
111
+ collectionId?: null | string;
112
+ /** Poster position in milliseconds. */
113
+ thumbnailTime?: null | number;
114
+ title: string;
115
+ };
116
+ export type BunnyUpdateVideoRequest = {
117
+ collectionId?: null | string;
118
+ metaTags?: BunnyMetaTag[] | null;
119
+ title?: null | string;
120
+ };
121
+ export type BunnyFetchVideoRequest = {
122
+ headers?: null | Record<string, string>;
123
+ title?: null | string;
124
+ url: string;
125
+ };
126
+ export type BunnyAddCaptionRequest = {
127
+ /** Base64-encoded caption file. */
128
+ captionsFile?: null | string;
129
+ label?: null | string;
130
+ /** Deprecated by Bunny (the path segment wins), still sent for older API versions. */
131
+ srclang?: null | string;
132
+ };
133
+ export type BunnyTranscribeRequest = {
134
+ generateChapters?: boolean | null;
135
+ generateDescription?: boolean | null;
136
+ generateMoments?: boolean | null;
137
+ generateTitle?: boolean | null;
138
+ /** ISO 639-1. Detected automatically when omitted. */
139
+ sourceLanguage?: null | string;
140
+ /** ISO 639-1 codes. */
141
+ targetLanguages?: null | string[];
142
+ };
143
+ /** The JSON body of a Bunny Stream webhook. */
144
+ export type BunnyWebhookPayload = {
145
+ EventId?: string;
146
+ IsLiveStreamWebhook?: boolean;
147
+ Reason?: null | string;
148
+ Status: number;
149
+ /** UTC timestamp of the event. */
150
+ Timestamp?: string;
151
+ VideoGuid: string;
152
+ VideoLibraryId: number | string;
153
+ };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Hand-written types for the parts of the Bunny Stream API the plugin uses. They are checked against
3
+ * the types generated from Bunny's OpenAPI spec (`openapi.ts`, see `sdk-compat.ts`), but are kept
4
+ * separate so the published declarations never depend on the generated file.
5
+ * @see https://video.bunnycdn.com/openapi/bunnynet-video-api.public.json
6
+ */ /** `status` of a video in the Stream API (`VideoModelStatus`). */ export const BUNNY_VIDEO_STATUS = {
7
+ Created: 0,
8
+ Uploaded: 1,
9
+ Processing: 2,
10
+ Transcoding: 3,
11
+ Finished: 4,
12
+ Error: 5,
13
+ UploadFailed: 6,
14
+ JitSegmenting: 7,
15
+ JitPlaylistsCreated: 8
16
+ };
17
+ /** `Status` of a webhook notification. These numbers differ from the API's `status`! */ export const BUNNY_WEBHOOK_STATUS = {
18
+ Queued: 0,
19
+ Processing: 1,
20
+ Encoding: 2,
21
+ Finished: 3,
22
+ ResolutionFinished: 4,
23
+ Failed: 5,
24
+ PresignedUploadStarted: 6,
25
+ PresignedUploadFinished: 7,
26
+ PresignedUploadFailed: 8,
27
+ CaptionsGenerated: 9,
28
+ TitleOrDescriptionGenerated: 10,
29
+ CaptionGenerationFailed: 11,
30
+ ChaptersGenerated: 12,
31
+ MomentsGenerated: 13,
32
+ VideoDeleted: 32,
33
+ SmartGenerationFailed: 33
34
+ };
35
+ /** `IssueCodes` of a transcoding message, by number. */ export const BUNNY_ISSUE_CODES = [
36
+ 'Undefined',
37
+ 'StreamLengthsDifference',
38
+ 'TranscodingWarnings',
39
+ 'IncompatibleResolution',
40
+ 'InvalidFramerate',
41
+ 'VideoExceededMaxDuration',
42
+ 'AudioExceededMaxDuration',
43
+ 'OriginalCorrupted',
44
+ 'TranscriptionFailed',
45
+ 'JitIncompatible',
46
+ 'JitFailed',
47
+ 'CaptionGenerationFailed',
48
+ 'UnsupportedFileType',
49
+ 'LiveNoEncoderCapacity',
50
+ 'LiveStreamBlocked',
51
+ 'LiveTooManyIngests',
52
+ 'LiveRegionConflict',
53
+ 'LivePublishAfterEnd',
54
+ 'LiveMediaStalled',
55
+ 'LiveEncoderLost',
56
+ 'LiveFailedOverToBackup',
57
+ 'LiveIngestRejected',
58
+ 'LiveIngestTimeout',
59
+ 'LiveMaxDurationReached',
60
+ 'LiveLibraryDisabled',
61
+ 'LiveDisconnectTimeout'
62
+ ];
63
+
64
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/providers/bunny/types.ts"],"sourcesContent":["/**\n * Hand-written types for the parts of the Bunny Stream API the plugin uses. They are checked against\n * the types generated from Bunny's OpenAPI spec (`openapi.ts`, see `sdk-compat.ts`), but are kept\n * separate so the published declarations never depend on the generated file.\n * @see https://video.bunnycdn.com/openapi/bunnynet-video-api.public.json\n */\n\n/** `status` of a video in the Stream API (`VideoModelStatus`). */\nexport const BUNNY_VIDEO_STATUS = {\n Created: 0,\n Uploaded: 1,\n Processing: 2,\n Transcoding: 3,\n Finished: 4,\n Error: 5,\n UploadFailed: 6,\n JitSegmenting: 7,\n JitPlaylistsCreated: 8,\n} as const\n\nexport type BunnyVideoStatus = (typeof BUNNY_VIDEO_STATUS)[keyof typeof BUNNY_VIDEO_STATUS]\n\n/** `Status` of a webhook notification. These numbers differ from the API's `status`! */\nexport const BUNNY_WEBHOOK_STATUS = {\n Queued: 0,\n Processing: 1,\n Encoding: 2,\n Finished: 3,\n ResolutionFinished: 4,\n Failed: 5,\n PresignedUploadStarted: 6,\n PresignedUploadFinished: 7,\n PresignedUploadFailed: 8,\n CaptionsGenerated: 9,\n TitleOrDescriptionGenerated: 10,\n CaptionGenerationFailed: 11,\n ChaptersGenerated: 12,\n MomentsGenerated: 13,\n VideoDeleted: 32,\n SmartGenerationFailed: 33,\n} as const\n\nexport type BunnyWebhookStatus = (typeof BUNNY_WEBHOOK_STATUS)[keyof typeof BUNNY_WEBHOOK_STATUS]\n\n/** `IssueCodes` of a transcoding message, by number. */\nexport const BUNNY_ISSUE_CODES = [\n 'Undefined',\n 'StreamLengthsDifference',\n 'TranscodingWarnings',\n 'IncompatibleResolution',\n 'InvalidFramerate',\n 'VideoExceededMaxDuration',\n 'AudioExceededMaxDuration',\n 'OriginalCorrupted',\n 'TranscriptionFailed',\n 'JitIncompatible',\n 'JitFailed',\n 'CaptionGenerationFailed',\n 'UnsupportedFileType',\n 'LiveNoEncoderCapacity',\n 'LiveStreamBlocked',\n 'LiveTooManyIngests',\n 'LiveRegionConflict',\n 'LivePublishAfterEnd',\n 'LiveMediaStalled',\n 'LiveEncoderLost',\n 'LiveFailedOverToBackup',\n 'LiveIngestRejected',\n 'LiveIngestTimeout',\n 'LiveMaxDurationReached',\n 'LiveLibraryDisabled',\n 'LiveDisconnectTimeout',\n] as const\n\nexport type BunnyCaption = {\n label?: null | string\n srclang?: null | string\n version?: number\n}\n\nexport type BunnyMetaTag = { property?: null | string; value?: null | string }\n\nexport type BunnyTranscodingMessage = {\n /** Number from `BUNNY_ISSUE_CODES`. */\n issueCode?: number\n /** 0 Undefined, 1 Information, 2 Warning, 3 Error. */\n level?: number\n message?: null | string\n timeStamp?: string\n value?: null | string\n}\n\n/** A video as returned by `GET /library/{libraryId}/videos/{videoId}` (`VideoModel`, abridged). */\nexport type BunnyVideo = {\n /** Comma-separated resolutions that finished encoding, e.g. `360p,720p`. */\n availableResolutions?: null | string\n averageWatchTime?: number\n captions?: BunnyCaption[] | null\n category?: null | string\n collectionId?: null | string\n /** ISO date (Bunny may omit the time zone; it is UTC). */\n dateUploaded: string\n description?: null | string\n /** Encoding progress, 0–100. */\n encodeProgress: number\n framerate?: number\n guid: string\n /** MP4 fallback files (`play_720p.mp4`…) exist for this video. */\n hasMP4Fallback: boolean\n height: number\n isPublic?: boolean\n jitEncodingEnabled?: boolean | null\n /** Duration in seconds. */\n length: number\n metaTags?: BunnyMetaTag[] | null\n outputCodecs?: string\n status: BunnyVideoStatus\n /** Bytes. */\n storageSize: number\n thumbnailCount?: number\n /** e.g. `thumbnail.jpg`. */\n thumbnailFileName?: null | string\n title: string\n totalWatchTime?: number\n transcodingMessages?: BunnyTranscodingMessage[] | null\n videoLibraryId: number\n views?: number\n width: number\n}\n\n/** `PaginationListOfVideoModel`. */\nexport type BunnyVideoList = {\n currentPage?: number\n items?: BunnyVideo[] | null\n itemsPerPage?: number\n totalItems?: number\n}\n\n/** `StatusModel`, the body of most write responses and of errors. */\nexport type BunnyStatusModel = {\n message?: null | string\n statusCode?: number\n success?: boolean\n}\n\nexport type BunnyCreateVideoRequest = {\n collectionId?: null | string\n /** Poster position in milliseconds. */\n thumbnailTime?: null | number\n title: string\n}\n\nexport type BunnyUpdateVideoRequest = {\n collectionId?: null | string\n metaTags?: BunnyMetaTag[] | null\n title?: null | string\n}\n\nexport type BunnyFetchVideoRequest = {\n headers?: null | Record<string, string>\n title?: null | string\n url: string\n}\n\nexport type BunnyAddCaptionRequest = {\n /** Base64-encoded caption file. */\n captionsFile?: null | string\n label?: null | string\n /** Deprecated by Bunny (the path segment wins), still sent for older API versions. */\n srclang?: null | string\n}\n\nexport type BunnyTranscribeRequest = {\n generateChapters?: boolean | null\n generateDescription?: boolean | null\n generateMoments?: boolean | null\n generateTitle?: boolean | null\n /** ISO 639-1. Detected automatically when omitted. */\n sourceLanguage?: null | string\n /** ISO 639-1 codes. */\n targetLanguages?: null | string[]\n}\n\n/** The JSON body of a Bunny Stream webhook. */\nexport type BunnyWebhookPayload = {\n EventId?: string\n IsLiveStreamWebhook?: boolean\n Reason?: null | string\n Status: number\n /** UTC timestamp of the event. */\n Timestamp?: string\n VideoGuid: string\n VideoLibraryId: number | string\n}\n"],"names":["BUNNY_VIDEO_STATUS","Created","Uploaded","Processing","Transcoding","Finished","Error","UploadFailed","JitSegmenting","JitPlaylistsCreated","BUNNY_WEBHOOK_STATUS","Queued","Encoding","ResolutionFinished","Failed","PresignedUploadStarted","PresignedUploadFinished","PresignedUploadFailed","CaptionsGenerated","TitleOrDescriptionGenerated","CaptionGenerationFailed","ChaptersGenerated","MomentsGenerated","VideoDeleted","SmartGenerationFailed","BUNNY_ISSUE_CODES"],"mappings":"AAAA;;;;;CAKC,GAED,gEAAgE,GAChE,OAAO,MAAMA,qBAAqB;IAChCC,SAAS;IACTC,UAAU;IACVC,YAAY;IACZC,aAAa;IACbC,UAAU;IACVC,OAAO;IACPC,cAAc;IACdC,eAAe;IACfC,qBAAqB;AACvB,EAAU;AAIV,sFAAsF,GACtF,OAAO,MAAMC,uBAAuB;IAClCC,QAAQ;IACRR,YAAY;IACZS,UAAU;IACVP,UAAU;IACVQ,oBAAoB;IACpBC,QAAQ;IACRC,wBAAwB;IACxBC,yBAAyB;IACzBC,uBAAuB;IACvBC,mBAAmB;IACnBC,6BAA6B;IAC7BC,yBAAyB;IACzBC,mBAAmB;IACnBC,kBAAkB;IAClBC,cAAc;IACdC,uBAAuB;AACzB,EAAU;AAIV,sDAAsD,GACtD,OAAO,MAAMC,oBAAoB;IAC/B;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS"}
@@ -0,0 +1,49 @@
1
+ export declare const BUNNY_EMBED_BASE_URL = "https://player.mediadelivery.net";
2
+ /** Bunny player (iframe) options. Bunny's player autoplays unless told otherwise. */
3
+ export type BunnyIframeOptions = {
4
+ autoplay?: boolean;
5
+ /** Caption language shown by default, e.g. `en` (auto captions: `en-auto`). */
6
+ captions?: string;
7
+ loop?: boolean;
8
+ muted?: boolean;
9
+ playsinline?: boolean;
10
+ preload?: boolean;
11
+ /** Adds `responsive=true` (seen in Bunny's examples; not in its parameter table). */
12
+ responsive?: boolean;
13
+ /** Start position: seconds, or a Bunny time string such as `1m30s`. */
14
+ startTime?: number | string;
15
+ };
16
+ /** `{cdn}/{guid}/{file}` */
17
+ export declare const cdnFileUrl: (cdnBaseUrl: string, guid: string, file: string) => string;
18
+ export declare const hlsUrl: (cdnBaseUrl: string, guid: string) => string;
19
+ export declare const thumbnailUrl: (cdnBaseUrl: string, guid: string, file?: string) => string;
20
+ export declare const previewUrl: (cdnBaseUrl: string, guid: string, format?: "gif" | "webp") => string;
21
+ export declare const mp4Url: (cdnBaseUrl: string, guid: string, file?: string) => string;
22
+ export declare const captionsUrl: (cdnBaseUrl: string, guid: string, language: string) => string;
23
+ /** Player query parameters. `autoplay` is always explicit. */
24
+ export declare const iframeParams: (options?: BunnyIframeOptions) => Record<string, string>;
25
+ /** The embeddable player, `https://player.mediadelivery.net/embed/{libraryId}/{guid}`, optionally with a view token. */
26
+ export declare const embedUrl: (embedBaseUrl: string, libraryId: number | string, guid: string, options?: BunnyIframeOptions, token?: {
27
+ expires: number;
28
+ token: string;
29
+ }) => string;
30
+ /** Signs the embed URL of a video with the library's embed token key. */
31
+ export declare const signedEmbedUrl: (args: {
32
+ embedBaseUrl: string;
33
+ expires: number;
34
+ libraryId: number | string;
35
+ tokenKey: string;
36
+ videoId: string;
37
+ }, options?: BunnyIframeOptions) => string;
38
+ export type BunnySignedFile = (file: string, options?: {
39
+ directory?: boolean;
40
+ }) => string;
41
+ /**
42
+ * A signer for every file of one video: one CDN token scoped to the video's directory
43
+ * (`token_path=/{guid}/`). HLS uses the path form so segment requests inherit the token.
44
+ */
45
+ export declare const videoFileSigner: (cdnBaseUrl: string, guid: string, args: {
46
+ countries?: string;
47
+ expires: number;
48
+ key: string;
49
+ }) => BunnySignedFile;