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,75 @@
1
+ /**
2
+ * Bunny Stream webhook verification. Bunny signs the raw body with HMAC-SHA256, keyed with the
3
+ * library's Read-Only API key, and sends no timestamp header.
4
+ * @see https://bunny.net/docs/stream/webhooks
5
+ */ import { createHmac } from 'node:crypto';
6
+ import { hexEquals } from './signing.js';
7
+ export const BUNNY_SIGNATURE_HEADER = 'x-bunnystream-signature';
8
+ export const BUNNY_SIGNATURE_VERSION_HEADER = 'x-bunnystream-signature-version';
9
+ export const BUNNY_SIGNATURE_ALGORITHM_HEADER = 'x-bunnystream-signature-algorithm';
10
+ /** Lowercase hex HMAC-SHA256 of the raw body. */ export const computeBunnyWebhookSignature = (secret, rawBody)=>createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex');
11
+ /** The headers Bunny sends with a webhook. Handy for tests and local tooling. */ export const bunnyWebhookHeaders = (secret, rawBody)=>({
12
+ 'content-type': 'application/json',
13
+ [BUNNY_SIGNATURE_ALGORITHM_HEADER]: 'hmac-sha256',
14
+ [BUNNY_SIGNATURE_HEADER]: computeBunnyWebhookSignature(secret, rawBody),
15
+ [BUNNY_SIGNATURE_VERSION_HEADER]: 'v1'
16
+ });
17
+ const header = (headers, name)=>{
18
+ if (typeof headers.get === 'function') {
19
+ return headers.get(name);
20
+ }
21
+ const record = headers;
22
+ const key = Object.keys(record).find((k)=>k.toLowerCase() === name);
23
+ return key ? record[key] ?? null : null;
24
+ };
25
+ /**
26
+ * Verifies a Bunny Stream webhook.
27
+ * @param rawBody the exact request body string; do not re-serialise parsed JSON.
28
+ * @param secret the library's Read-Only API key (or the webhook signing secret, if Bunny gave you one).
29
+ */ export const verifyBunnyWebhook = ({ headers, rawBody, secret })=>{
30
+ const signature = header(headers, BUNNY_SIGNATURE_HEADER);
31
+ if (!signature) {
32
+ return {
33
+ ok: false,
34
+ reason: 'missing_header'
35
+ };
36
+ }
37
+ const version = header(headers, BUNNY_SIGNATURE_VERSION_HEADER);
38
+ if (version && version.toLowerCase() !== 'v1') {
39
+ return {
40
+ ok: false,
41
+ reason: 'unsupported_version'
42
+ };
43
+ }
44
+ const algorithm = header(headers, BUNNY_SIGNATURE_ALGORITHM_HEADER);
45
+ if (algorithm && algorithm.toLowerCase() !== 'hmac-sha256') {
46
+ return {
47
+ ok: false,
48
+ reason: 'unsupported_algorithm'
49
+ };
50
+ }
51
+ return hexEquals(signature.trim(), computeBunnyWebhookSignature(secret, rawBody)) ? {
52
+ ok: true
53
+ } : {
54
+ ok: false,
55
+ reason: 'invalid_signature'
56
+ };
57
+ };
58
+ /** Parses Bunny's UTC timestamps, which may come without a time zone. Returns ms, or null. */ export const parseBunnyDate = (value)=>{
59
+ if (!value) {
60
+ return null;
61
+ }
62
+ const withZone = /(?:Z|[+-]\d\d:?\d\d)$/i.test(value) ? value : `${value}Z`;
63
+ const ms = Date.parse(withZone);
64
+ return Number.isFinite(ms) ? ms : null;
65
+ };
66
+ /** Normalises a Bunny date to an ISO string (UTC), or null. */ export const bunnyDateToIso = (value)=>{
67
+ const ms = parseBunnyDate(value);
68
+ return ms === null ? null : new Date(ms).toISOString();
69
+ };
70
+ /** Checks the shape of a parsed webhook body. */ export const isBunnyWebhookPayload = (value)=>{
71
+ const v = value;
72
+ return Boolean(v && typeof v === 'object' && typeof v.VideoGuid === 'string' && typeof v.Status === 'number');
73
+ };
74
+
75
+ //# sourceMappingURL=webhook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/providers/bunny/webhook.ts"],"sourcesContent":["/**\n * Bunny Stream webhook verification. Bunny signs the raw body with HMAC-SHA256, keyed with the\n * library's Read-Only API key, and sends no timestamp header.\n * @see https://bunny.net/docs/stream/webhooks\n */\nimport { createHmac } from 'node:crypto'\n\nimport type { BunnyWebhookPayload } from './types.js'\n\nimport { hexEquals } from './signing.js'\n\nexport const BUNNY_SIGNATURE_HEADER = 'x-bunnystream-signature'\nexport const BUNNY_SIGNATURE_VERSION_HEADER = 'x-bunnystream-signature-version'\nexport const BUNNY_SIGNATURE_ALGORITHM_HEADER = 'x-bunnystream-signature-algorithm'\n\n/** Lowercase hex HMAC-SHA256 of the raw body. */\nexport const computeBunnyWebhookSignature = (secret: string, rawBody: string): string =>\n createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex')\n\n/** The headers Bunny sends with a webhook. Handy for tests and local tooling. */\nexport const bunnyWebhookHeaders = (secret: string, rawBody: string): Record<string, string> => ({\n 'content-type': 'application/json',\n [BUNNY_SIGNATURE_ALGORITHM_HEADER]: 'hmac-sha256',\n [BUNNY_SIGNATURE_HEADER]: computeBunnyWebhookSignature(secret, rawBody),\n [BUNNY_SIGNATURE_VERSION_HEADER]: 'v1',\n})\n\nexport type BunnyWebhookVerification =\n | { ok: false; reason: 'invalid_signature' | 'missing_header' | 'unsupported_algorithm' | 'unsupported_version' }\n | { ok: true }\n\ntype HeaderSource = Headers | Record<string, string | undefined>\n\nconst header = (headers: HeaderSource, name: string): null | string => {\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(name)\n }\n const record = headers as Record<string, string | undefined>\n const key = Object.keys(record).find((k) => k.toLowerCase() === name)\n return key ? (record[key] ?? null) : null\n}\n\n/**\n * Verifies a Bunny Stream webhook.\n * @param rawBody the exact request body string; do not re-serialise parsed JSON.\n * @param secret the library's Read-Only API key (or the webhook signing secret, if Bunny gave you one).\n */\nexport const verifyBunnyWebhook = ({\n headers,\n rawBody,\n secret,\n}: {\n headers: HeaderSource\n rawBody: string\n secret: string\n}): BunnyWebhookVerification => {\n const signature = header(headers, BUNNY_SIGNATURE_HEADER)\n if (!signature) {\n return { ok: false, reason: 'missing_header' }\n }\n const version = header(headers, BUNNY_SIGNATURE_VERSION_HEADER)\n if (version && version.toLowerCase() !== 'v1') {\n return { ok: false, reason: 'unsupported_version' }\n }\n const algorithm = header(headers, BUNNY_SIGNATURE_ALGORITHM_HEADER)\n if (algorithm && algorithm.toLowerCase() !== 'hmac-sha256') {\n return { ok: false, reason: 'unsupported_algorithm' }\n }\n return hexEquals(signature.trim(), computeBunnyWebhookSignature(secret, rawBody)) ? { ok: true } : { ok: false, reason: 'invalid_signature' }\n}\n\n/** Parses Bunny's UTC timestamps, which may come without a time zone. Returns ms, or null. */\nexport const parseBunnyDate = (value: null | string | undefined): null | number => {\n if (!value) {\n return null\n }\n const withZone = /(?:Z|[+-]\\d\\d:?\\d\\d)$/i.test(value) ? value : `${value}Z`\n const ms = Date.parse(withZone)\n return Number.isFinite(ms) ? ms : null\n}\n\n/** Normalises a Bunny date to an ISO string (UTC), or null. */\nexport const bunnyDateToIso = (value: null | string | undefined): null | string => {\n const ms = parseBunnyDate(value)\n return ms === null ? null : new Date(ms).toISOString()\n}\n\n/** Checks the shape of a parsed webhook body. */\nexport const isBunnyWebhookPayload = (value: unknown): value is BunnyWebhookPayload => {\n const v = value as null | Partial<BunnyWebhookPayload>\n return Boolean(v && typeof v === 'object' && typeof v.VideoGuid === 'string' && typeof v.Status === 'number')\n}\n"],"names":["createHmac","hexEquals","BUNNY_SIGNATURE_HEADER","BUNNY_SIGNATURE_VERSION_HEADER","BUNNY_SIGNATURE_ALGORITHM_HEADER","computeBunnyWebhookSignature","secret","rawBody","update","digest","bunnyWebhookHeaders","header","headers","name","get","record","key","Object","keys","find","k","toLowerCase","verifyBunnyWebhook","signature","ok","reason","version","algorithm","trim","parseBunnyDate","value","withZone","test","ms","Date","parse","Number","isFinite","bunnyDateToIso","toISOString","isBunnyWebhookPayload","v","Boolean","VideoGuid","Status"],"mappings":"AAAA;;;;CAIC,GACD,SAASA,UAAU,QAAQ,cAAa;AAIxC,SAASC,SAAS,QAAQ,eAAc;AAExC,OAAO,MAAMC,yBAAyB,0BAAyB;AAC/D,OAAO,MAAMC,iCAAiC,kCAAiC;AAC/E,OAAO,MAAMC,mCAAmC,oCAAmC;AAEnF,+CAA+C,GAC/C,OAAO,MAAMC,+BAA+B,CAACC,QAAgBC,UAC3DP,WAAW,UAAUM,QAAQE,MAAM,CAACD,SAAS,QAAQE,MAAM,CAAC,OAAM;AAEpE,+EAA+E,GAC/E,OAAO,MAAMC,sBAAsB,CAACJ,QAAgBC,UAA6C,CAAA;QAC/F,gBAAgB;QAChB,CAACH,iCAAiC,EAAE;QACpC,CAACF,uBAAuB,EAAEG,6BAA6BC,QAAQC;QAC/D,CAACJ,+BAA+B,EAAE;IACpC,CAAA,EAAE;AAQF,MAAMQ,SAAS,CAACC,SAAuBC;IACrC,IAAI,OAAO,AAACD,QAAoBE,GAAG,KAAK,YAAY;QAClD,OAAO,AAACF,QAAoBE,GAAG,CAACD;IAClC;IACA,MAAME,SAASH;IACf,MAAMI,MAAMC,OAAOC,IAAI,CAACH,QAAQI,IAAI,CAAC,CAACC,IAAMA,EAAEC,WAAW,OAAOR;IAChE,OAAOG,MAAOD,MAAM,CAACC,IAAI,IAAI,OAAQ;AACvC;AAEA;;;;CAIC,GACD,OAAO,MAAMM,qBAAqB,CAAC,EACjCV,OAAO,EACPL,OAAO,EACPD,MAAM,EAKP;IACC,MAAMiB,YAAYZ,OAAOC,SAASV;IAClC,IAAI,CAACqB,WAAW;QACd,OAAO;YAAEC,IAAI;YAAOC,QAAQ;QAAiB;IAC/C;IACA,MAAMC,UAAUf,OAAOC,SAAST;IAChC,IAAIuB,WAAWA,QAAQL,WAAW,OAAO,MAAM;QAC7C,OAAO;YAAEG,IAAI;YAAOC,QAAQ;QAAsB;IACpD;IACA,MAAME,YAAYhB,OAAOC,SAASR;IAClC,IAAIuB,aAAaA,UAAUN,WAAW,OAAO,eAAe;QAC1D,OAAO;YAAEG,IAAI;YAAOC,QAAQ;QAAwB;IACtD;IACA,OAAOxB,UAAUsB,UAAUK,IAAI,IAAIvB,6BAA6BC,QAAQC,YAAY;QAAEiB,IAAI;IAAK,IAAI;QAAEA,IAAI;QAAOC,QAAQ;IAAoB;AAC9I,EAAC;AAED,4FAA4F,GAC5F,OAAO,MAAMI,iBAAiB,CAACC;IAC7B,IAAI,CAACA,OAAO;QACV,OAAO;IACT;IACA,MAAMC,WAAW,yBAAyBC,IAAI,CAACF,SAASA,QAAQ,GAAGA,MAAM,CAAC,CAAC;IAC3E,MAAMG,KAAKC,KAAKC,KAAK,CAACJ;IACtB,OAAOK,OAAOC,QAAQ,CAACJ,MAAMA,KAAK;AACpC,EAAC;AAED,6DAA6D,GAC7D,OAAO,MAAMK,iBAAiB,CAACR;IAC7B,MAAMG,KAAKJ,eAAeC;IAC1B,OAAOG,OAAO,OAAO,OAAO,IAAIC,KAAKD,IAAIM,WAAW;AACtD,EAAC;AAED,+CAA+C,GAC/C,OAAO,MAAMC,wBAAwB,CAACV;IACpC,MAAMW,IAAIX;IACV,OAAOY,QAAQD,KAAK,OAAOA,MAAM,YAAY,OAAOA,EAAEE,SAAS,KAAK,YAAY,OAAOF,EAAEG,MAAM,KAAK;AACtG,EAAC"}
@@ -0,0 +1,93 @@
1
+ import type { CopyFromUrlRequest, CreateTokenRequest, DirectUploadRequest, DirectUploadResult, ListVideosQuery, StreamApiMessage, StreamCaption, StreamDownloads, StreamDownloadType, StreamSigningKey, StreamStorageUsage, StreamVideo, StreamVideoSettings, StreamWebhook, TusUploadRequest, TusUploadResult } from './types.js';
2
+ import { ProviderError } from '../../core/errors.js';
3
+ export declare const DEFAULT_API_BASE_URL = "https://api.cloudflare.com/client/v4";
4
+ /** Cloudflare's limit for basic (single POST) uploads. */
5
+ export declare const BASIC_UPLOAD_MAX_BYTES: number;
6
+ export type StreamClientOptions = {
7
+ accountId: string;
8
+ /** Override the API base URL (used by tests / proxies). */
9
+ apiBaseUrl?: string;
10
+ apiToken: string;
11
+ /** Custom fetch implementation. Defaults to global fetch. */
12
+ fetch?: typeof fetch;
13
+ /** How many times to retry 429 / 5xx responses. Default 3. */
14
+ maxRetries?: number;
15
+ /** Base delay for exponential backoff in ms. Default 500. */
16
+ retryBaseDelayMs?: number;
17
+ };
18
+ export declare class CloudflareStreamError extends ProviderError {
19
+ readonly errors: StreamApiMessage[];
20
+ constructor(message: string, status: number, errors?: StreamApiMessage[]);
21
+ /** True when Cloudflare reports the resource doesn't exist. */
22
+ get isNotFound(): boolean;
23
+ }
24
+ type RequestOptions = {
25
+ body?: BodyInit | null;
26
+ headers?: Record<string, string>;
27
+ json?: unknown;
28
+ method?: string;
29
+ query?: Record<string, boolean | number | string | undefined>;
30
+ /** Return the raw Response instead of unwrapping the JSON envelope. */
31
+ raw?: boolean;
32
+ };
33
+ /**
34
+ * Minimal, dependency-free client for the Cloudflare Stream REST API.
35
+ */
36
+ export declare class StreamClient {
37
+ readonly accountId: string;
38
+ readonly apiBaseUrl: string;
39
+ private readonly apiToken;
40
+ private readonly fetchImpl;
41
+ private readonly maxRetries;
42
+ private readonly retryBaseDelayMs;
43
+ constructor(options: StreamClientOptions);
44
+ /** Base URL for this account's Stream endpoints. */
45
+ get streamUrl(): string;
46
+ request(path: string, options: RequestOptions & {
47
+ raw: true;
48
+ }): Promise<Response>;
49
+ request<T>(path: string, options?: RequestOptions): Promise<T>;
50
+ private toError;
51
+ private unwrap;
52
+ /** Creates a one-time URL for a basic (≤200MB) browser upload. */
53
+ createDirectUpload(body: DirectUploadRequest): Promise<DirectUploadResult>;
54
+ /**
55
+ * Creates a tus upload on behalf of an end user (`direct_user=true`) and returns the one-time
56
+ * upload URL. The client then PATCHes chunks to `location` without credentials.
57
+ */
58
+ createTusUpload(input: TusUploadRequest): Promise<TusUploadResult>;
59
+ /** Asks Cloudflare to fetch a video from a public URL. */
60
+ uploadFromUrl(body: CopyFromUrlRequest): Promise<StreamVideo>;
61
+ /**
62
+ * Uploads a file from the server. Files ≤200MB use a single multipart POST; bigger files use tus.
63
+ */
64
+ uploadFile(file: Blob | Uint8Array, options?: {
65
+ chunkSize?: number;
66
+ filename?: string;
67
+ } & StreamVideoSettings): Promise<StreamVideo>;
68
+ /** Uploads a blob to a tus endpoint in Cloudflare-compatible chunks. */
69
+ tusPatchAll(location: string, blob: Blob, chunkSize?: number): Promise<void>;
70
+ getVideo(uid: string): Promise<StreamVideo>;
71
+ listVideos(query?: ListVideosQuery): Promise<StreamVideo[]>;
72
+ updateVideo(uid: string, settings: StreamVideoSettings): Promise<StreamVideo>;
73
+ /** Deletes a video. Resolves `false` if the video did not exist. */
74
+ deleteVideo(uid: string): Promise<boolean>;
75
+ storageUsage(creator?: string): Promise<StreamStorageUsage>;
76
+ /** Asks Cloudflare to mint a signed token (rate-limited – prefer self-signing at scale). */
77
+ createToken(uid: string, body?: CreateTokenRequest): Promise<string>;
78
+ createSigningKey(): Promise<StreamSigningKey>;
79
+ listSigningKeys(): Promise<StreamSigningKey[]>;
80
+ deleteSigningKey(id: string): Promise<void>;
81
+ listCaptions(uid: string): Promise<StreamCaption[]>;
82
+ uploadCaption(uid: string, language: string, vtt: Blob | string, filename?: string): Promise<StreamCaption>;
83
+ generateCaption(uid: string, language: string): Promise<StreamCaption>;
84
+ getCaptionVtt(uid: string, language: string): Promise<string>;
85
+ deleteCaption(uid: string, language: string): Promise<void>;
86
+ getDownloads(uid: string): Promise<StreamDownloads>;
87
+ createDownload(uid: string, type?: StreamDownloadType): Promise<StreamDownloads>;
88
+ deleteDownload(uid: string, type?: StreamDownloadType): Promise<void>;
89
+ setWebhook(notificationUrl: string): Promise<StreamWebhook>;
90
+ getWebhook(): Promise<null | StreamWebhook>;
91
+ deleteWebhook(): Promise<void>;
92
+ }
93
+ export {};
@@ -0,0 +1,436 @@
1
+ import { ProviderError } from '../../core/errors.js';
2
+ import { encodeTusMetadata, normalizeTusChunkSize } from './tus.js';
3
+ export const DEFAULT_API_BASE_URL = 'https://api.cloudflare.com/client/v4';
4
+ /** Cloudflare's limit for basic (single POST) uploads. */ export const BASIC_UPLOAD_MAX_BYTES = 200 * 1024 * 1024;
5
+ export class CloudflareStreamError extends ProviderError {
6
+ errors;
7
+ constructor(message, status, errors = []){
8
+ super(message, {
9
+ details: errors,
10
+ provider: 'cloudflare',
11
+ status
12
+ });
13
+ this.name = 'CloudflareStreamError';
14
+ this.errors = errors;
15
+ }
16
+ /** True when Cloudflare reports the resource doesn't exist. */ get isNotFound() {
17
+ return this.status === 404 || this.errors.some((e)=>e.code === 10003 || /not found/i.test(e.message));
18
+ }
19
+ }
20
+ /** Formats Cloudflare errors, appending the (often more useful) `messages` details. */ const describeMessages = (errors, messages)=>{
21
+ const parts = errors.map((e)=>`${e.code}: ${e.message}`);
22
+ for (const m of messages){
23
+ if (!errors.some((e)=>e.message === m.message)) {
24
+ parts.push(m.message);
25
+ }
26
+ }
27
+ return parts.join('; ');
28
+ };
29
+ const sleep = (ms)=>new Promise((resolve)=>setTimeout(resolve, ms));
30
+ /**
31
+ * Minimal, dependency-free client for the Cloudflare Stream REST API.
32
+ */ export class StreamClient {
33
+ accountId;
34
+ apiBaseUrl;
35
+ apiToken;
36
+ fetchImpl;
37
+ maxRetries;
38
+ retryBaseDelayMs;
39
+ constructor(options){
40
+ if (!options.accountId) {
41
+ throw new Error('StreamClient: accountId is required');
42
+ }
43
+ if (!options.apiToken) {
44
+ throw new Error('StreamClient: apiToken is required');
45
+ }
46
+ this.accountId = options.accountId;
47
+ this.apiToken = options.apiToken;
48
+ this.apiBaseUrl = (options.apiBaseUrl || DEFAULT_API_BASE_URL).replace(/\/+$/, '');
49
+ this.fetchImpl = options.fetch ?? ((...args)=>globalThis.fetch(...args));
50
+ this.maxRetries = options.maxRetries ?? 3;
51
+ this.retryBaseDelayMs = options.retryBaseDelayMs ?? 500;
52
+ }
53
+ /** Base URL for this account's Stream endpoints. */ get streamUrl() {
54
+ return `${this.apiBaseUrl}/accounts/${encodeURIComponent(this.accountId)}/stream`;
55
+ }
56
+ async request(path, options = {}) {
57
+ const url = new URL(`${this.streamUrl}${path}`);
58
+ for (const [key, value] of Object.entries(options.query ?? {})){
59
+ if (value !== undefined) {
60
+ url.searchParams.set(key, String(value));
61
+ }
62
+ }
63
+ const headers = {
64
+ Authorization: `Bearer ${this.apiToken}`,
65
+ ...options.headers
66
+ };
67
+ let body = options.body;
68
+ if (options.json !== undefined) {
69
+ headers['Content-Type'] = 'application/json';
70
+ body = JSON.stringify(options.json);
71
+ }
72
+ const method = (options.method ?? 'GET').toUpperCase();
73
+ // Network failures are retried only for idempotent requests (a retried POST could create duplicates).
74
+ const idempotent = [
75
+ 'DELETE',
76
+ 'GET',
77
+ 'HEAD',
78
+ 'PUT'
79
+ ].includes(method);
80
+ let attempt = 0;
81
+ while(true){
82
+ let response;
83
+ try {
84
+ response = await this.fetchImpl(url, {
85
+ body,
86
+ headers,
87
+ method
88
+ });
89
+ } catch (err) {
90
+ if (idempotent && attempt < this.maxRetries) {
91
+ attempt++;
92
+ await sleep(this.retryBaseDelayMs * 2 ** (attempt - 1));
93
+ continue;
94
+ }
95
+ const cause = err;
96
+ const detail = cause.cause?.code ?? cause.cause?.message ?? cause.message;
97
+ throw new CloudflareStreamError(`Could not reach the Cloudflare Stream API (${method} ${url.pathname}): ${detail}`, 0);
98
+ }
99
+ const retryable = response.status === 429 || response.status >= 500;
100
+ if (retryable && attempt < this.maxRetries) {
101
+ attempt++;
102
+ const retryAfter = Number(response.headers.get('retry-after'));
103
+ const delay = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, 30_000) : this.retryBaseDelayMs * 2 ** (attempt - 1);
104
+ await response.body?.cancel().catch(()=>undefined);
105
+ await sleep(delay);
106
+ continue;
107
+ }
108
+ if (options.raw) {
109
+ if (!response.ok) {
110
+ throw await this.toError(response);
111
+ }
112
+ return response;
113
+ }
114
+ return this.unwrap(response);
115
+ }
116
+ }
117
+ async toError(response) {
118
+ let errors = [];
119
+ let messages = [];
120
+ let text = '';
121
+ try {
122
+ text = await response.text();
123
+ const parsed = JSON.parse(text);
124
+ errors = parsed.errors ?? [];
125
+ messages = parsed.messages ?? [];
126
+ } catch {
127
+ // non-JSON error body
128
+ }
129
+ const detail = errors.length ? describeMessages(errors, messages) : text.slice(0, 200);
130
+ return new CloudflareStreamError(`Cloudflare Stream API error (HTTP ${response.status})${detail ? `: ${detail}` : ''}`, response.status, errors);
131
+ }
132
+ async unwrap(response) {
133
+ if (!response.ok) {
134
+ throw await this.toError(response);
135
+ }
136
+ const text = await response.text();
137
+ if (!text) {
138
+ return undefined;
139
+ }
140
+ let envelope;
141
+ try {
142
+ envelope = JSON.parse(text);
143
+ } catch {
144
+ // Some endpoints (e.g. caption VTT) return plain text
145
+ return text;
146
+ }
147
+ if (envelope && typeof envelope === 'object' && 'success' in envelope) {
148
+ if (!envelope.success) {
149
+ const detail = describeMessages(envelope.errors ?? [], envelope.messages ?? []);
150
+ throw new CloudflareStreamError(`Cloudflare Stream API error${detail ? `: ${detail}` : ''}`, response.status, envelope.errors ?? []);
151
+ }
152
+ return envelope.result;
153
+ }
154
+ return envelope;
155
+ }
156
+ // ---------------------------------------------------------------------------
157
+ // Uploads
158
+ // ---------------------------------------------------------------------------
159
+ /** Creates a one-time URL for a basic (≤200MB) browser upload. */ createDirectUpload(body) {
160
+ return this.request('/direct_upload', {
161
+ json: body,
162
+ method: 'POST'
163
+ });
164
+ }
165
+ /**
166
+ * Creates a tus upload on behalf of an end user (`direct_user=true`) and returns the one-time
167
+ * upload URL. The client then PATCHes chunks to `location` without credentials.
168
+ */ async createTusUpload(input) {
169
+ if (!(input.uploadLength > 0)) {
170
+ throw new Error('createTusUpload: uploadLength must be a positive number of bytes');
171
+ }
172
+ const headers = {
173
+ 'Tus-Resumable': '1.0.0',
174
+ 'Upload-Length': String(input.uploadLength)
175
+ };
176
+ const metadata = encodeTusMetadata({
177
+ allowedorigins: input.allowedOrigins?.length ? input.allowedOrigins.join(',') : undefined,
178
+ expiry: input.expiry,
179
+ maxdurationseconds: input.maxDurationSeconds,
180
+ name: input.name,
181
+ requiresignedurls: input.requireSignedURLs === true,
182
+ scheduleddeletion: input.scheduledDeletion ?? undefined,
183
+ thumbnailtimestamppct: input.thumbnailTimestampPct,
184
+ watermark: input.watermarkUID
185
+ });
186
+ if (metadata) {
187
+ headers['Upload-Metadata'] = metadata;
188
+ }
189
+ if (input.creator) {
190
+ headers['Upload-Creator'] = input.creator;
191
+ }
192
+ const response = await this.request('', {
193
+ headers,
194
+ method: 'POST',
195
+ query: {
196
+ direct_user: true
197
+ },
198
+ raw: true
199
+ });
200
+ const location = response.headers.get('location');
201
+ const uid = response.headers.get('stream-media-id');
202
+ await response.body?.cancel().catch(()=>undefined);
203
+ if (!location || !uid) {
204
+ throw new CloudflareStreamError('Cloudflare Stream did not return Location / stream-media-id headers for the tus upload', response.status);
205
+ }
206
+ return {
207
+ location,
208
+ uid
209
+ };
210
+ }
211
+ /** Asks Cloudflare to fetch a video from a public URL. */ uploadFromUrl(body) {
212
+ return this.request('/copy', {
213
+ json: body,
214
+ method: 'POST'
215
+ });
216
+ }
217
+ /**
218
+ * Uploads a file from the server. Files ≤200MB use a single multipart POST; bigger files use tus.
219
+ */ async uploadFile(file, options = {}) {
220
+ const blob = file instanceof Blob ? file : new Blob([
221
+ file
222
+ ]);
223
+ const name = options.filename ?? options.meta?.name ?? 'upload';
224
+ if (blob.size > BASIC_UPLOAD_MAX_BYTES) {
225
+ const { location, uid } = await this.createTusUpload({
226
+ allowedOrigins: options.allowedOrigins,
227
+ creator: options.creator,
228
+ maxDurationSeconds: options.maxDurationSeconds,
229
+ name,
230
+ requireSignedURLs: options.requireSignedURLs,
231
+ scheduledDeletion: options.scheduledDeletion,
232
+ thumbnailTimestampPct: options.thumbnailTimestampPct,
233
+ uploadLength: blob.size
234
+ });
235
+ await this.tusPatchAll(location, blob, options.chunkSize);
236
+ return this.getVideo(uid);
237
+ }
238
+ const form = new FormData();
239
+ form.append('file', blob, name);
240
+ const headers = {};
241
+ if (options.creator) {
242
+ headers['Upload-Creator'] = options.creator;
243
+ }
244
+ const video = await this.request('', {
245
+ body: form,
246
+ headers,
247
+ method: 'POST'
248
+ });
249
+ const settings = {};
250
+ if (options.meta || name) {
251
+ settings.meta = {
252
+ name,
253
+ ...options.meta
254
+ };
255
+ }
256
+ if (options.requireSignedURLs !== undefined) {
257
+ settings.requireSignedURLs = options.requireSignedURLs;
258
+ }
259
+ if (options.allowedOrigins) {
260
+ settings.allowedOrigins = options.allowedOrigins;
261
+ }
262
+ if (options.thumbnailTimestampPct !== undefined) {
263
+ settings.thumbnailTimestampPct = options.thumbnailTimestampPct;
264
+ }
265
+ if (options.scheduledDeletion !== undefined) {
266
+ settings.scheduledDeletion = options.scheduledDeletion;
267
+ }
268
+ return Object.keys(settings).length ? this.updateVideo(video.uid, settings) : video;
269
+ }
270
+ /** Uploads a blob to a tus endpoint in Cloudflare-compatible chunks. */ async tusPatchAll(location, blob, chunkSize) {
271
+ const size = normalizeTusChunkSize(chunkSize);
272
+ let offset = 0;
273
+ while(offset < blob.size){
274
+ const chunk = blob.slice(offset, Math.min(offset + size, blob.size));
275
+ const response = await this.fetchImpl(location, {
276
+ body: chunk,
277
+ headers: {
278
+ 'Content-Type': 'application/offset+octet-stream',
279
+ 'Tus-Resumable': '1.0.0',
280
+ 'Upload-Offset': String(offset)
281
+ },
282
+ method: 'PATCH'
283
+ });
284
+ if (!response.ok) {
285
+ throw await this.toError(response);
286
+ }
287
+ const next = Number(response.headers.get('upload-offset'));
288
+ await response.body?.cancel().catch(()=>undefined);
289
+ offset = Number.isFinite(next) && next > offset ? next : offset + chunk.size;
290
+ }
291
+ }
292
+ // ---------------------------------------------------------------------------
293
+ // Videos
294
+ // ---------------------------------------------------------------------------
295
+ getVideo(uid) {
296
+ return this.request(`/${encodeURIComponent(uid)}`);
297
+ }
298
+ listVideos(query = {}) {
299
+ return this.request('', {
300
+ query: {
301
+ after: query.after,
302
+ asc: query.asc,
303
+ before: query.before,
304
+ creator: query.creator,
305
+ limit: query.limit,
306
+ search: query.search,
307
+ status: query.status
308
+ }
309
+ });
310
+ }
311
+ updateVideo(uid, settings) {
312
+ return this.request(`/${encodeURIComponent(uid)}`, {
313
+ json: settings,
314
+ method: 'POST'
315
+ });
316
+ }
317
+ /** Deletes a video. Resolves `false` if the video did not exist. */ async deleteVideo(uid) {
318
+ try {
319
+ await this.request(`/${encodeURIComponent(uid)}`, {
320
+ method: 'DELETE'
321
+ });
322
+ return true;
323
+ } catch (err) {
324
+ if (err instanceof CloudflareStreamError && err.isNotFound) {
325
+ return false;
326
+ }
327
+ throw err;
328
+ }
329
+ }
330
+ storageUsage(creator) {
331
+ return this.request('/storage-usage', {
332
+ query: {
333
+ creator
334
+ }
335
+ });
336
+ }
337
+ // ---------------------------------------------------------------------------
338
+ // Signed URLs
339
+ // ---------------------------------------------------------------------------
340
+ /** Asks Cloudflare to mint a signed token (rate-limited – prefer self-signing at scale). */ async createToken(uid, body = {}) {
341
+ const result = await this.request(`/${encodeURIComponent(uid)}/token`, {
342
+ json: body,
343
+ method: 'POST'
344
+ });
345
+ return result.token;
346
+ }
347
+ createSigningKey() {
348
+ return this.request('/keys', {
349
+ method: 'POST'
350
+ });
351
+ }
352
+ listSigningKeys() {
353
+ return this.request('/keys');
354
+ }
355
+ async deleteSigningKey(id) {
356
+ await this.request(`/keys/${encodeURIComponent(id)}`, {
357
+ method: 'DELETE'
358
+ });
359
+ }
360
+ // ---------------------------------------------------------------------------
361
+ // Captions
362
+ // ---------------------------------------------------------------------------
363
+ listCaptions(uid) {
364
+ return this.request(`/${encodeURIComponent(uid)}/captions`);
365
+ }
366
+ uploadCaption(uid, language, vtt, filename = `${language}.vtt`) {
367
+ const form = new FormData();
368
+ const blob = typeof vtt === 'string' ? new Blob([
369
+ vtt
370
+ ], {
371
+ type: 'text/vtt'
372
+ }) : vtt;
373
+ form.append('file', blob, filename);
374
+ return this.request(`/${encodeURIComponent(uid)}/captions/${encodeURIComponent(language)}`, {
375
+ body: form,
376
+ method: 'PUT'
377
+ });
378
+ }
379
+ generateCaption(uid, language) {
380
+ return this.request(`/${encodeURIComponent(uid)}/captions/${encodeURIComponent(language)}/generate`, {
381
+ method: 'POST'
382
+ });
383
+ }
384
+ getCaptionVtt(uid, language) {
385
+ return this.request(`/${encodeURIComponent(uid)}/captions/${encodeURIComponent(language)}/vtt`);
386
+ }
387
+ async deleteCaption(uid, language) {
388
+ await this.request(`/${encodeURIComponent(uid)}/captions/${encodeURIComponent(language)}`, {
389
+ method: 'DELETE'
390
+ });
391
+ }
392
+ // ---------------------------------------------------------------------------
393
+ // Downloads
394
+ // ---------------------------------------------------------------------------
395
+ getDownloads(uid) {
396
+ return this.request(`/${encodeURIComponent(uid)}/downloads`);
397
+ }
398
+ createDownload(uid, type = 'default') {
399
+ return this.request(`/${encodeURIComponent(uid)}/downloads${type === 'audio' ? '/audio' : ''}`, {
400
+ method: 'POST'
401
+ });
402
+ }
403
+ async deleteDownload(uid, type = 'default') {
404
+ await this.request(`/${encodeURIComponent(uid)}/downloads/${type}`, {
405
+ method: 'DELETE'
406
+ });
407
+ }
408
+ // ---------------------------------------------------------------------------
409
+ // Webhooks
410
+ // ---------------------------------------------------------------------------
411
+ setWebhook(notificationUrl) {
412
+ return this.request('/webhook', {
413
+ json: {
414
+ notificationUrl
415
+ },
416
+ method: 'PUT'
417
+ });
418
+ }
419
+ async getWebhook() {
420
+ try {
421
+ return await this.request('/webhook');
422
+ } catch (err) {
423
+ if (err instanceof CloudflareStreamError && err.isNotFound) {
424
+ return null;
425
+ }
426
+ throw err;
427
+ }
428
+ }
429
+ async deleteWebhook() {
430
+ await this.request('/webhook', {
431
+ method: 'DELETE'
432
+ });
433
+ }
434
+ }
435
+
436
+ //# sourceMappingURL=client.js.map