payload-video-streaming 0.2.0-beta.0 → 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.
- package/README.md +174 -543
- package/dist/access.d.ts +35 -0
- package/dist/access.js +53 -0
- package/dist/access.js.map +1 -0
- package/dist/bin/args.d.ts +13 -0
- package/dist/bin/args.js +61 -0
- package/dist/bin/args.js.map +1 -1
- package/dist/bin/cli.js +9 -1
- package/dist/bin/cli.js.map +1 -1
- package/dist/bin/webhooks.d.ts +15 -0
- package/dist/bin/webhooks.js +149 -0
- package/dist/bin/webhooks.js.map +1 -0
- package/dist/collection.js +148 -1
- package/dist/collection.js.map +1 -1
- package/dist/components/BulkUploader.d.ts +16 -0
- package/dist/components/BulkUploader.js +226 -0
- package/dist/components/BulkUploader.js.map +1 -0
- package/dist/components/ListUploader.js +22 -0
- package/dist/components/ListUploader.js.map +1 -1
- package/dist/components/Uploader.d.ts +5 -0
- package/dist/components/Uploader.js +13 -4
- package/dist/components/Uploader.js.map +1 -1
- package/dist/components/VideoField.js +9 -5
- package/dist/components/VideoField.js.map +1 -1
- package/dist/components/VideoRelationshipField.d.ts +16 -0
- package/dist/components/VideoRelationshipField.js +106 -0
- package/dist/components/VideoRelationshipField.js.map +1 -0
- package/dist/components/WebhookStatusPanel.d.ts +6 -0
- package/dist/components/WebhookStatusPanel.js +143 -0
- package/dist/components/WebhookStatusPanel.js.map +1 -0
- package/dist/components/api.d.ts +7 -1
- package/dist/components/api.js +2 -0
- package/dist/components/api.js.map +1 -1
- package/dist/components/uploadFile.d.ts +30 -0
- package/dist/components/uploadFile.js +140 -0
- package/dist/components/uploadFile.js.map +1 -0
- package/dist/components/usePluginApi.d.ts +5 -0
- package/dist/components/useUploadQueue.d.ts +35 -0
- package/dist/components/useUploadQueue.js +135 -0
- package/dist/components/useUploadQueue.js.map +1 -0
- package/dist/components/useVideoUpload.d.ts +3 -7
- package/dist/components/useVideoUpload.js +29 -123
- package/dist/components/useVideoUpload.js.map +1 -1
- package/dist/core/provider.d.ts +16 -0
- package/dist/core/provider.js.map +1 -1
- package/dist/endpoints/index.js +38 -2
- package/dist/endpoints/index.js.map +1 -1
- package/dist/exports/client.d.ts +9 -0
- package/dist/exports/client.js +5 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/react.d.ts +12 -0
- package/dist/exports/react.js +7 -0
- package/dist/exports/react.js.map +1 -1
- package/dist/fields.d.ts +11 -2
- package/dist/fields.js +62 -2
- package/dist/fields.js.map +1 -1
- package/dist/frontend/VideoUploader.d.ts +65 -0
- package/dist/frontend/VideoUploader.js +260 -0
- package/dist/frontend/VideoUploader.js.map +1 -0
- package/dist/frontend/useVideoStatus.d.ts +26 -0
- package/dist/frontend/useVideoStatus.js +68 -0
- package/dist/frontend/useVideoStatus.js.map +1 -0
- package/dist/index.d.ts +5 -4
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +7 -2
- package/dist/options.js +65 -2
- package/dist/options.js.map +1 -1
- package/dist/plugin.js +80 -1
- package/dist/plugin.js.map +1 -1
- package/dist/providers/bunny/provider.d.ts +2 -1
- package/dist/providers/bunny/provider.js +8 -0
- package/dist/providers/bunny/provider.js.map +1 -1
- package/dist/providers/cloudflare/provider.d.ts +2 -1
- package/dist/providers/cloudflare/provider.js +11 -0
- package/dist/providers/cloudflare/provider.js.map +1 -1
- package/dist/providers/mux/provider.d.ts +2 -1
- package/dist/providers/mux/provider.js +9 -0
- package/dist/providers/mux/provider.js.map +1 -1
- package/dist/service.d.ts +28 -1
- package/dist/service.js +114 -4
- package/dist/service.js.map +1 -1
- package/dist/types.d.ts +155 -1
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/providers/cloudflare/provider.ts"],"sourcesContent":["import type {\n AssetPatch,\n DirectUpload,\n Downloads,\n ImportInput,\n NeutralAsset,\n PlaybackOptions,\n PlaybackResult,\n ProviderCapabilities,\n ProviderRef,\n ProviderWebhook,\n ServerUploadInput,\n StoredAsset,\n UploadInput,\n VideoProvider,\n} from '../../core/provider.js'\nimport type { CloudflareStreamOptions, ResolvedCloudflareStreamOptions } from './options.js'\nimport type { StreamAccessRule, StreamVideo, StreamVideoSettings } from './types.js'\n\nimport { CloudflareStreamError, StreamClient } from './client.js'\nimport { captionToNeutral, downloadsToNeutral, secondsToPct, videoToAsset } from './mapping.js'\nimport { MAX_TOKEN_TTL_SECONDS, resolveCloudflareOptions } from './options.js'\nimport { signStreamToken } from './signing.js'\nimport { buildPlaybackUrls, downloadUrl, extractCustomerCode } from './urls.js'\nimport { verifyWebhookSignature, WEBHOOK_SIGNATURE_HEADER } from './webhook.js'\n\nexport const CLOUDFLARE_CAPABILITIES: ProviderCapabilities = {\n adoptExisting: true,\n allowedOrigins: true,\n captions: { generate: true, upload: true },\n dash: true,\n downloads: { managed: 'video', types: ['default', 'audio'] },\n importFromUrl: true,\n progress: true,\n serverUpload: true,\n signedPlayback: 'video',\n thumbnailTime: true,\n uploadProtocols: ['post', 'tus'],\n webhooks: true,\n}\n\nconst LIST_PAGE_SIZE = 1000\n\nconst isoSeconds = (date: Date): string => date.toISOString().replace(/\\.\\d{3}Z$/, 'Z')\n\nconst requireAssetId = (ref: ProviderRef): string => {\n if (!ref.assetId) {\n throw new Error('[payload-video-streaming] cloudflare: this video has no Cloudflare uid')\n }\n return ref.assetId\n}\n\n/** The Cloudflare Stream provider. Create it with `cloudflareStream({ … })`. */\nexport class CloudflareStreamProvider implements VideoProvider {\n readonly capabilities = CLOUDFLARE_CAPABILITIES\n readonly captions: NonNullable<VideoProvider['captions']>\n readonly client: StreamClient\n readonly downloads: NonNullable<VideoProvider['downloads']>\n readonly id: string\n readonly label: string\n readonly maxTokenTtlSeconds = MAX_TOKEN_TTL_SECONDS\n readonly options: ResolvedCloudflareStreamOptions\n readonly webhook?: ProviderWebhook\n private customerCode?: string\n\n constructor(options: CloudflareStreamOptions) {\n this.options = resolveCloudflareOptions(options)\n this.id = this.options.id\n this.label = this.options.label\n this.customerCode = this.options.customerCode\n this.client = new StreamClient({\n accountId: this.options.accountId,\n apiBaseUrl: this.options.apiBaseUrl,\n apiToken: this.options.apiToken,\n fetch: this.options.fetch,\n })\n\n this.captions = {\n generate: async (ref, language) => captionToNeutral(await this.client.generateCaption(requireAssetId(ref), language)),\n list: async (ref) => (await this.client.listCaptions(requireAssetId(ref))).map(captionToNeutral),\n remove: async (ref, language) => this.client.deleteCaption(requireAssetId(ref), language),\n upload: async (ref, language, vtt) => captionToNeutral(await this.client.uploadCaption(requireAssetId(ref), language, vtt)),\n }\n\n this.downloads = {\n create: async (ref, type) => this.listDownloads(ref, downloadsToNeutral(await this.client.createDownload(requireAssetId(ref), type))),\n list: (ref) => this.listDownloads(ref),\n remove: async (ref, type) => this.client.deleteDownload(requireAssetId(ref), type),\n }\n\n if (this.options.webhook.secret) {\n this.webhook = {\n handle: async ({ headers, rawBody }) => {\n const verification = verifyWebhookSignature({\n header: headers.get(WEBHOOK_SIGNATURE_HEADER),\n rawBody,\n // Read on every call, so the secret can be rotated at runtime.\n secret: this.options.webhook.secret ?? '',\n toleranceSeconds: this.options.webhook.toleranceSeconds,\n })\n if (!verification.ok) {\n return { ok: false, reason: `invalid signature (${verification.reason})`, status: 401 }\n }\n let payload: unknown\n try {\n payload = JSON.parse(rawBody)\n } catch {\n return { ok: false, reason: 'Invalid JSON body', status: 400 }\n }\n const video = payload as null | Partial<StreamVideo>\n if (!video || typeof video !== 'object' || typeof video.uid !== 'string') {\n return { ok: false, reason: 'Webhook payload has no uid', status: 400 }\n }\n this.learnCustomerCode(video)\n return { events: [{ asset: videoToAsset(video as StreamVideo), ref: { assetId: video.uid } }], ok: true }\n },\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Customer code\n // ---------------------------------------------------------------------------\n\n /** Remembers the customer code from any Cloudflare video payload. */\n learnCustomerCode(video: null | Partial<StreamVideo> | Record<string, unknown> | undefined): void {\n if (this.customerCode || !video) {\n return\n }\n const v = video as Partial<StreamVideo>\n const code = extractCustomerCode(v.playback?.hls) ?? extractCustomerCode(v.preview) ?? extractCustomerCode(v.thumbnail)\n if (code) {\n this.customerCode = code\n }\n }\n\n /** Resolves the customer code: options → cache → stored payload → Cloudflare API lookup. */\n async getCustomerCode(hint?: null | Pick<StoredAsset, 'assetId' | 'providerData'>): Promise<string> {\n if (this.options.deliveryBaseUrl) {\n return this.options.deliveryBaseUrl\n }\n if (this.customerCode) {\n return this.customerCode\n }\n this.learnCustomerCode(hint?.providerData)\n if (this.customerCode) {\n return this.customerCode\n }\n if (hint?.assetId) {\n this.learnCustomerCode(await this.client.getVideo(hint.assetId))\n }\n if (!this.customerCode) {\n const [first] = await this.client.listVideos({ limit: 1 })\n this.learnCustomerCode(first)\n }\n if (!this.customerCode) {\n throw new Error(\n '[payload-video-streaming] Could not determine your Cloudflare Stream customer code. Set the `customerCode` option of cloudflareStream().',\n )\n }\n return this.customerCode\n }\n\n private asset(video: StreamVideo): NeutralAsset {\n this.learnCustomerCode(video)\n return videoToAsset(video)\n }\n\n // ---------------------------------------------------------------------------\n // Uploads\n // ---------------------------------------------------------------------------\n\n private scheduledDeletion(): string | undefined {\n const days = this.options.upload.scheduledDeletionDays\n return days ? isoSeconds(new Date(Date.now() + days * 86_400_000)) : undefined\n }\n\n private allowedOrigins(requested: string[] | undefined): string[] | undefined {\n const origins = requested ?? this.options.upload.allowedOrigins\n return origins.length ? origins : undefined\n }\n\n async createDirectUpload(input: UploadInput): Promise<DirectUpload> {\n const { upload } = this.options\n const maxDurationSeconds = Math.min(input.maxDurationSeconds ?? upload.maxDurationSeconds, upload.maxDurationSeconds)\n const expiry = isoSeconds(new Date(Date.now() + upload.expiryMinutes * 60_000))\n const allowedOrigins = this.allowedOrigins(input.allowedOrigins)\n if (input.size > upload.directUploadMaxBytes) {\n const tus = await this.client.createTusUpload({\n allowedOrigins,\n creator: input.creator,\n expiry,\n maxDurationSeconds,\n name: input.title,\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n uploadLength: input.size,\n watermarkUID: upload.watermarkUID,\n })\n return { chunkSize: upload.tusChunkSize, protocol: 'tus', ref: { assetId: tus.uid }, uploadUrl: tus.location }\n }\n const direct = await this.client.createDirectUpload({\n allowedOrigins,\n creator: input.creator,\n expiry,\n maxDurationSeconds,\n meta: { ...input.meta, name: input.title },\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n ...(upload.watermarkUID ? { watermark: { uid: upload.watermarkUID } } : {}),\n })\n return { protocol: 'post', ref: { assetId: direct.uid }, url: direct.uploadURL }\n }\n\n async importFromUrl(input: ImportInput): Promise<NeutralAsset> {\n const video = await this.client.uploadFromUrl({\n allowedOrigins: this.allowedOrigins(input.allowedOrigins),\n creator: input.creator,\n meta: { ...input.meta, name: input.title },\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n url: input.url,\n ...(this.options.upload.watermarkUID ? { watermark: { uid: this.options.upload.watermarkUID } } : {}),\n })\n return this.asset(video)\n }\n\n async uploadFile(input: ServerUploadInput): Promise<NeutralAsset> {\n const video = await this.client.uploadFile(input.file, {\n allowedOrigins: this.allowedOrigins(input.allowedOrigins),\n chunkSize: this.options.upload.tusChunkSize,\n creator: input.creator,\n filename: input.filename,\n maxDurationSeconds: this.options.upload.maxDurationSeconds,\n meta: { ...input.meta, name: input.title },\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n })\n return this.asset(video)\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(requireAssetId(ref)))\n } catch (err) {\n if (err instanceof CloudflareStreamError && err.isNotFound) {\n return null\n }\n throw err\n }\n }\n\n /** Pages through the account's videos, newest first, using each page's last `created` as the cursor. */\n async listAssets({ creator, cursor }: { creator?: string; cursor?: string } = {}): Promise<{ assets: NeutralAsset[]; next?: string }> {\n const page = await this.client.listVideos({ before: cursor, creator, limit: LIST_PAGE_SIZE })\n const last = page.at(-1)?.created\n const next = page.length >= LIST_PAGE_SIZE && last && last !== cursor ? last : undefined\n return { assets: page.map((video) => this.asset(video)), next }\n }\n\n async updateAsset(ref: ProviderRef, patch: AssetPatch, context: { duration?: null | number } = {}): Promise<NeutralAsset | null> {\n const uid = requireAssetId(ref)\n const settings: StreamVideoSettings = {}\n if (patch.signedPlayback !== undefined) {\n settings.requireSignedURLs = patch.signedPlayback\n }\n if (patch.allowedOrigins !== undefined) {\n settings.allowedOrigins = patch.allowedOrigins\n }\n if (patch.thumbnailTime !== undefined) {\n // Cloudflare stores the poster position as a fraction of the duration.\n let duration = context.duration\n if (!duration || duration <= 0) {\n const video = await this.client.getVideo(uid)\n duration = typeof video.duration === 'number' ? video.duration : null\n }\n const pct = secondsToPct(patch.thumbnailTime, duration)\n if (pct !== null) {\n settings.thumbnailTimestampPct = pct\n }\n }\n if (patch.title !== undefined || patch.meta !== undefined) {\n settings.meta = { ...patch.meta, name: patch.title }\n }\n if (!Object.keys(settings).length) {\n return null\n }\n return this.asset(await this.client.updateVideo(uid, settings))\n }\n\n async deleteAsset(ref: ProviderRef): Promise<void> {\n if (!ref.assetId) {\n // Cloudflare uploads are assets from the start: an upload id alone refers to nothing here.\n return\n }\n await this.client.deleteVideo(ref.assetId)\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /** Creates a signed playback token (self-signed when a signing key is configured, else via the /token API). */\n async signToken(\n uid: string,\n opts: { accessRules?: StreamAccessRule[]; downloadable?: boolean; expiresIn?: number } = {},\n ): Promise<{ expiresAt: string; token: string }> {\n const expiresIn = Math.min(opts.expiresIn ?? 3600, MAX_TOKEN_TTL_SECONDS)\n const accessRules = opts.accessRules ?? this.options.playback.accessRules\n const now = Math.floor(Date.now() / 1000)\n const expiresAt = new Date((now + expiresIn) * 1000).toISOString()\n if (this.options.signingKey) {\n const { jwk, keyId, pem } = this.options.signingKey\n const token = signStreamToken({\n accessRules,\n downloadable: opts.downloadable,\n expiresIn,\n keyId,\n now,\n videoUID: uid,\n ...(pem ? { pem } : { jwk: jwk! }),\n })\n return { expiresAt, token }\n }\n const token = await this.client.createToken(uid, { accessRules, downloadable: opts.downloadable, exp: now + expiresIn })\n return { expiresAt, token }\n }\n\n async playback(asset: StoredAsset, options: PlaybackOptions): Promise<PlaybackResult> {\n const code = await this.getCustomerCode(asset)\n const mp4Ready = asset.downloads?.mp4 === 'ready'\n const urlOptions = { iframe: this.options.playback.iframe, thumbnail: this.options.playback.thumbnail }\n\n if (!asset.signedPlayback) {\n const urls = buildPlaybackUrls(code, asset.assetId, urlOptions)\n return { signed: false, urls: { ...urls, ...(mp4Ready ? { downloadMp4: downloadUrl(code, asset.assetId) } : {}) } }\n }\n const canSign = options.sign && (options.allowNetwork || Boolean(this.options.signingKey))\n if (!canSign) {\n return { signed: false, urls: null }\n }\n const { expiresAt, token } = await this.signToken(asset.assetId, {\n accessRules: options.providerOptions?.accessRules as StreamAccessRule[] | undefined,\n downloadable: options.downloadable ?? mp4Ready,\n expiresIn: options.expiresIn,\n })\n const urls = buildPlaybackUrls(code, token, urlOptions)\n return { expiresAt, signed: true, token, urls: { ...urls, ...(mp4Ready ? { downloadMp4: downloadUrl(code, token) } : {}) } }\n }\n\n // ---------------------------------------------------------------------------\n // Downloads\n // ---------------------------------------------------------------------------\n\n /** The full download state; `created` (a POST response, which only has the new type) is merged in. */\n private async listDownloads(ref: ProviderRef, created?: Downloads): Promise<Downloads> {\n const uid = requireAssetId(ref)\n if (created) {\n const current = await this.client.getDownloads(uid).catch(() => ({}))\n return { ...downloadsToNeutral(current), ...created }\n }\n return downloadsToNeutral(await this.client.getDownloads(uid))\n }\n}\n\n/**\n * Cloudflare Stream as a video provider:\n *\n * ```ts\n * videoPlugin({ providers: [cloudflareStream({ accountId, apiToken })] })\n * ```\n */\nexport const cloudflareStream = (options: CloudflareStreamOptions): CloudflareStreamProvider => new CloudflareStreamProvider(options)\n"],"names":["CloudflareStreamError","StreamClient","captionToNeutral","downloadsToNeutral","secondsToPct","videoToAsset","MAX_TOKEN_TTL_SECONDS","resolveCloudflareOptions","signStreamToken","buildPlaybackUrls","downloadUrl","extractCustomerCode","verifyWebhookSignature","WEBHOOK_SIGNATURE_HEADER","CLOUDFLARE_CAPABILITIES","adoptExisting","allowedOrigins","captions","generate","upload","dash","downloads","managed","types","importFromUrl","progress","serverUpload","signedPlayback","thumbnailTime","uploadProtocols","webhooks","LIST_PAGE_SIZE","isoSeconds","date","toISOString","replace","requireAssetId","ref","assetId","Error","CloudflareStreamProvider","capabilities","client","id","label","maxTokenTtlSeconds","options","webhook","customerCode","accountId","apiBaseUrl","apiToken","fetch","language","generateCaption","list","listCaptions","map","remove","deleteCaption","vtt","uploadCaption","create","type","listDownloads","createDownload","deleteDownload","secret","handle","headers","rawBody","verification","header","get","toleranceSeconds","ok","reason","status","payload","JSON","parse","video","uid","learnCustomerCode","events","asset","v","code","playback","hls","preview","thumbnail","getCustomerCode","hint","deliveryBaseUrl","providerData","getVideo","first","listVideos","limit","scheduledDeletion","days","scheduledDeletionDays","Date","now","undefined","requested","origins","length","createDirectUpload","input","maxDurationSeconds","Math","min","expiry","expiryMinutes","size","directUploadMaxBytes","tus","createTusUpload","creator","name","title","requireSignedURLs","uploadLength","watermarkUID","chunkSize","tusChunkSize","protocol","uploadUrl","location","direct","meta","watermark","url","uploadURL","uploadFromUrl","uploadFile","file","filename","getAsset","err","isNotFound","listAssets","cursor","page","before","last","at","created","next","assets","updateAsset","patch","context","settings","duration","pct","thumbnailTimestampPct","Object","keys","updateVideo","deleteAsset","deleteVideo","signToken","opts","expiresIn","accessRules","floor","expiresAt","signingKey","jwk","keyId","pem","token","downloadable","videoUID","createToken","exp","mp4Ready","mp4","urlOptions","iframe","urls","signed","downloadMp4","canSign","s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yBAAyBM,SAAQ"}
|
|
1
|
+
{"version":3,"sources":["../../../src/providers/cloudflare/provider.ts"],"sourcesContent":["import type {\n AssetPatch,\n DirectUpload,\n Downloads,\n ImportInput,\n NeutralAsset,\n PlaybackOptions,\n PlaybackResult,\n ProviderCapabilities,\n ProviderRef,\n ProviderWebhook,\n WebhookSetup,\n ServerUploadInput,\n StoredAsset,\n UploadInput,\n VideoProvider,\n} from '../../core/provider.js'\nimport type { CloudflareStreamOptions, ResolvedCloudflareStreamOptions } from './options.js'\nimport type { StreamAccessRule, StreamVideo, StreamVideoSettings } from './types.js'\n\nimport { CloudflareStreamError, StreamClient } from './client.js'\nimport { captionToNeutral, downloadsToNeutral, secondsToPct, videoToAsset } from './mapping.js'\nimport { MAX_TOKEN_TTL_SECONDS, resolveCloudflareOptions } from './options.js'\nimport { signStreamToken } from './signing.js'\nimport { buildPlaybackUrls, downloadUrl, extractCustomerCode } from './urls.js'\nimport { verifyWebhookSignature, WEBHOOK_SIGNATURE_HEADER } from './webhook.js'\n\nexport const CLOUDFLARE_CAPABILITIES: ProviderCapabilities = {\n adoptExisting: true,\n allowedOrigins: true,\n captions: { generate: true, upload: true },\n dash: true,\n downloads: { managed: 'video', types: ['default', 'audio'] },\n importFromUrl: true,\n progress: true,\n serverUpload: true,\n signedPlayback: 'video',\n thumbnailTime: true,\n uploadProtocols: ['post', 'tus'],\n webhooks: true,\n}\n\nconst LIST_PAGE_SIZE = 1000\n\nconst isoSeconds = (date: Date): string => date.toISOString().replace(/\\.\\d{3}Z$/, 'Z')\n\nconst requireAssetId = (ref: ProviderRef): string => {\n if (!ref.assetId) {\n throw new Error('[payload-video-streaming] cloudflare: this video has no Cloudflare uid')\n }\n return ref.assetId\n}\n\n/** The Cloudflare Stream provider. Create it with `cloudflareStream({ … })`. */\nexport class CloudflareStreamProvider implements VideoProvider {\n readonly capabilities = CLOUDFLARE_CAPABILITIES\n readonly captions: NonNullable<VideoProvider['captions']>\n readonly client: StreamClient\n readonly downloads: NonNullable<VideoProvider['downloads']>\n readonly id: string\n readonly label: string\n readonly maxTokenTtlSeconds = MAX_TOKEN_TTL_SECONDS\n readonly options: ResolvedCloudflareStreamOptions\n readonly webhook?: ProviderWebhook\n readonly webhookSetup: WebhookSetup = {\n apiRegistration: true,\n secret: 'CLOUDFLARE_STREAM_WEBHOOK_SECRET (`webhook.secret`)',\n secretLocation: 'the `secret` Cloudflare returned when the webhook URL was registered; registering again issues a new one',\n steps: [\n 'Register the URL through the API: `npx payload-video-streaming webhooks --url <your site> --register cloudflare`. It prints the secret.',\n 'Or call `PUT /accounts/<account id>/stream/webhook` with `{ \"notificationUrl\": \"{url}\" }` and keep the returned `result.secret`.',\n 'Each Cloudflare account has one webhook URL: registering replaces the previous one.',\n 'Set the secret as CLOUDFLARE_STREAM_WEBHOOK_SECRET (or `webhook.secret`).',\n ],\n }\n private customerCode?: string\n\n constructor(options: CloudflareStreamOptions) {\n this.options = resolveCloudflareOptions(options)\n this.id = this.options.id\n this.label = this.options.label\n this.customerCode = this.options.customerCode\n this.client = new StreamClient({\n accountId: this.options.accountId,\n apiBaseUrl: this.options.apiBaseUrl,\n apiToken: this.options.apiToken,\n fetch: this.options.fetch,\n })\n\n this.captions = {\n generate: async (ref, language) => captionToNeutral(await this.client.generateCaption(requireAssetId(ref), language)),\n list: async (ref) => (await this.client.listCaptions(requireAssetId(ref))).map(captionToNeutral),\n remove: async (ref, language) => this.client.deleteCaption(requireAssetId(ref), language),\n upload: async (ref, language, vtt) => captionToNeutral(await this.client.uploadCaption(requireAssetId(ref), language, vtt)),\n }\n\n this.downloads = {\n create: async (ref, type) => this.listDownloads(ref, downloadsToNeutral(await this.client.createDownload(requireAssetId(ref), type))),\n list: (ref) => this.listDownloads(ref),\n remove: async (ref, type) => this.client.deleteDownload(requireAssetId(ref), type),\n }\n\n if (this.options.webhook.secret) {\n this.webhook = {\n handle: async ({ headers, rawBody }) => {\n const verification = verifyWebhookSignature({\n header: headers.get(WEBHOOK_SIGNATURE_HEADER),\n rawBody,\n // Read on every call, so the secret can be rotated at runtime.\n secret: this.options.webhook.secret ?? '',\n toleranceSeconds: this.options.webhook.toleranceSeconds,\n })\n if (!verification.ok) {\n return { ok: false, reason: `invalid signature (${verification.reason})`, status: 401 }\n }\n let payload: unknown\n try {\n payload = JSON.parse(rawBody)\n } catch {\n return { ok: false, reason: 'Invalid JSON body', status: 400 }\n }\n const video = payload as null | Partial<StreamVideo>\n if (!video || typeof video !== 'object' || typeof video.uid !== 'string') {\n return { ok: false, reason: 'Webhook payload has no uid', status: 400 }\n }\n this.learnCustomerCode(video)\n return { events: [{ asset: videoToAsset(video as StreamVideo), ref: { assetId: video.uid } }], ok: true }\n },\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Customer code\n // ---------------------------------------------------------------------------\n\n /** Remembers the customer code from any Cloudflare video payload. */\n learnCustomerCode(video: null | Partial<StreamVideo> | Record<string, unknown> | undefined): void {\n if (this.customerCode || !video) {\n return\n }\n const v = video as Partial<StreamVideo>\n const code = extractCustomerCode(v.playback?.hls) ?? extractCustomerCode(v.preview) ?? extractCustomerCode(v.thumbnail)\n if (code) {\n this.customerCode = code\n }\n }\n\n /** Resolves the customer code: options → cache → stored payload → Cloudflare API lookup. */\n async getCustomerCode(hint?: null | Pick<StoredAsset, 'assetId' | 'providerData'>): Promise<string> {\n if (this.options.deliveryBaseUrl) {\n return this.options.deliveryBaseUrl\n }\n if (this.customerCode) {\n return this.customerCode\n }\n this.learnCustomerCode(hint?.providerData)\n if (this.customerCode) {\n return this.customerCode\n }\n if (hint?.assetId) {\n this.learnCustomerCode(await this.client.getVideo(hint.assetId))\n }\n if (!this.customerCode) {\n const [first] = await this.client.listVideos({ limit: 1 })\n this.learnCustomerCode(first)\n }\n if (!this.customerCode) {\n throw new Error(\n '[payload-video-streaming] Could not determine your Cloudflare Stream customer code. Set the `customerCode` option of cloudflareStream().',\n )\n }\n return this.customerCode\n }\n\n private asset(video: StreamVideo): NeutralAsset {\n this.learnCustomerCode(video)\n return videoToAsset(video)\n }\n\n // ---------------------------------------------------------------------------\n // Uploads\n // ---------------------------------------------------------------------------\n\n private scheduledDeletion(): string | undefined {\n const days = this.options.upload.scheduledDeletionDays\n return days ? isoSeconds(new Date(Date.now() + days * 86_400_000)) : undefined\n }\n\n private allowedOrigins(requested: string[] | undefined): string[] | undefined {\n const origins = requested ?? this.options.upload.allowedOrigins\n return origins.length ? origins : undefined\n }\n\n async createDirectUpload(input: UploadInput): Promise<DirectUpload> {\n const { upload } = this.options\n const maxDurationSeconds = Math.min(input.maxDurationSeconds ?? upload.maxDurationSeconds, upload.maxDurationSeconds)\n const expiry = isoSeconds(new Date(Date.now() + upload.expiryMinutes * 60_000))\n const allowedOrigins = this.allowedOrigins(input.allowedOrigins)\n if (input.size > upload.directUploadMaxBytes) {\n const tus = await this.client.createTusUpload({\n allowedOrigins,\n creator: input.creator,\n expiry,\n maxDurationSeconds,\n name: input.title,\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n uploadLength: input.size,\n watermarkUID: upload.watermarkUID,\n })\n return { chunkSize: upload.tusChunkSize, protocol: 'tus', ref: { assetId: tus.uid }, uploadUrl: tus.location }\n }\n const direct = await this.client.createDirectUpload({\n allowedOrigins,\n creator: input.creator,\n expiry,\n maxDurationSeconds,\n meta: { ...input.meta, name: input.title },\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n ...(upload.watermarkUID ? { watermark: { uid: upload.watermarkUID } } : {}),\n })\n return { protocol: 'post', ref: { assetId: direct.uid }, url: direct.uploadURL }\n }\n\n async importFromUrl(input: ImportInput): Promise<NeutralAsset> {\n const video = await this.client.uploadFromUrl({\n allowedOrigins: this.allowedOrigins(input.allowedOrigins),\n creator: input.creator,\n meta: { ...input.meta, name: input.title },\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n url: input.url,\n ...(this.options.upload.watermarkUID ? { watermark: { uid: this.options.upload.watermarkUID } } : {}),\n })\n return this.asset(video)\n }\n\n async uploadFile(input: ServerUploadInput): Promise<NeutralAsset> {\n const video = await this.client.uploadFile(input.file, {\n allowedOrigins: this.allowedOrigins(input.allowedOrigins),\n chunkSize: this.options.upload.tusChunkSize,\n creator: input.creator,\n filename: input.filename,\n maxDurationSeconds: this.options.upload.maxDurationSeconds,\n meta: { ...input.meta, name: input.title },\n requireSignedURLs: input.signedPlayback,\n scheduledDeletion: this.scheduledDeletion(),\n })\n return this.asset(video)\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(requireAssetId(ref)))\n } catch (err) {\n if (err instanceof CloudflareStreamError && err.isNotFound) {\n return null\n }\n throw err\n }\n }\n\n /** Pages through the account's videos, newest first, using each page's last `created` as the cursor. */\n async listAssets({ creator, cursor }: { creator?: string; cursor?: string } = {}): Promise<{ assets: NeutralAsset[]; next?: string }> {\n const page = await this.client.listVideos({ before: cursor, creator, limit: LIST_PAGE_SIZE })\n const last = page.at(-1)?.created\n const next = page.length >= LIST_PAGE_SIZE && last && last !== cursor ? last : undefined\n return { assets: page.map((video) => this.asset(video)), next }\n }\n\n async updateAsset(ref: ProviderRef, patch: AssetPatch, context: { duration?: null | number } = {}): Promise<NeutralAsset | null> {\n const uid = requireAssetId(ref)\n const settings: StreamVideoSettings = {}\n if (patch.signedPlayback !== undefined) {\n settings.requireSignedURLs = patch.signedPlayback\n }\n if (patch.allowedOrigins !== undefined) {\n settings.allowedOrigins = patch.allowedOrigins\n }\n if (patch.thumbnailTime !== undefined) {\n // Cloudflare stores the poster position as a fraction of the duration.\n let duration = context.duration\n if (!duration || duration <= 0) {\n const video = await this.client.getVideo(uid)\n duration = typeof video.duration === 'number' ? video.duration : null\n }\n const pct = secondsToPct(patch.thumbnailTime, duration)\n if (pct !== null) {\n settings.thumbnailTimestampPct = pct\n }\n }\n if (patch.title !== undefined || patch.meta !== undefined) {\n settings.meta = { ...patch.meta, name: patch.title }\n }\n if (!Object.keys(settings).length) {\n return null\n }\n return this.asset(await this.client.updateVideo(uid, settings))\n }\n\n async deleteAsset(ref: ProviderRef): Promise<void> {\n if (!ref.assetId) {\n // Cloudflare uploads are assets from the start: an upload id alone refers to nothing here.\n return\n }\n await this.client.deleteVideo(ref.assetId)\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /** Creates a signed playback token (self-signed when a signing key is configured, else via the /token API). */\n async signToken(\n uid: string,\n opts: { accessRules?: StreamAccessRule[]; downloadable?: boolean; expiresIn?: number } = {},\n ): Promise<{ expiresAt: string; token: string }> {\n const expiresIn = Math.min(opts.expiresIn ?? 3600, MAX_TOKEN_TTL_SECONDS)\n const accessRules = opts.accessRules ?? this.options.playback.accessRules\n const now = Math.floor(Date.now() / 1000)\n const expiresAt = new Date((now + expiresIn) * 1000).toISOString()\n if (this.options.signingKey) {\n const { jwk, keyId, pem } = this.options.signingKey\n const token = signStreamToken({\n accessRules,\n downloadable: opts.downloadable,\n expiresIn,\n keyId,\n now,\n videoUID: uid,\n ...(pem ? { pem } : { jwk: jwk! }),\n })\n return { expiresAt, token }\n }\n const token = await this.client.createToken(uid, { accessRules, downloadable: opts.downloadable, exp: now + expiresIn })\n return { expiresAt, token }\n }\n\n async playback(asset: StoredAsset, options: PlaybackOptions): Promise<PlaybackResult> {\n const code = await this.getCustomerCode(asset)\n const mp4Ready = asset.downloads?.mp4 === 'ready'\n const urlOptions = { iframe: this.options.playback.iframe, thumbnail: this.options.playback.thumbnail }\n\n if (!asset.signedPlayback) {\n const urls = buildPlaybackUrls(code, asset.assetId, urlOptions)\n return { signed: false, urls: { ...urls, ...(mp4Ready ? { downloadMp4: downloadUrl(code, asset.assetId) } : {}) } }\n }\n const canSign = options.sign && (options.allowNetwork || Boolean(this.options.signingKey))\n if (!canSign) {\n return { signed: false, urls: null }\n }\n const { expiresAt, token } = await this.signToken(asset.assetId, {\n accessRules: options.providerOptions?.accessRules as StreamAccessRule[] | undefined,\n downloadable: options.downloadable ?? mp4Ready,\n expiresIn: options.expiresIn,\n })\n const urls = buildPlaybackUrls(code, token, urlOptions)\n return { expiresAt, signed: true, token, urls: { ...urls, ...(mp4Ready ? { downloadMp4: downloadUrl(code, token) } : {}) } }\n }\n\n // ---------------------------------------------------------------------------\n // Downloads\n // ---------------------------------------------------------------------------\n\n /** The full download state; `created` (a POST response, which only has the new type) is merged in. */\n private async listDownloads(ref: ProviderRef, created?: Downloads): Promise<Downloads> {\n const uid = requireAssetId(ref)\n if (created) {\n const current = await this.client.getDownloads(uid).catch(() => ({}))\n return { ...downloadsToNeutral(current), ...created }\n }\n return downloadsToNeutral(await this.client.getDownloads(uid))\n }\n}\n\n/**\n * Cloudflare Stream as a video provider:\n *\n * ```ts\n * videoPlugin({ providers: [cloudflareStream({ accountId, apiToken })] })\n * ```\n */\nexport const cloudflareStream = (options: CloudflareStreamOptions): CloudflareStreamProvider => new CloudflareStreamProvider(options)\n"],"names":["CloudflareStreamError","StreamClient","captionToNeutral","downloadsToNeutral","secondsToPct","videoToAsset","MAX_TOKEN_TTL_SECONDS","resolveCloudflareOptions","signStreamToken","buildPlaybackUrls","downloadUrl","extractCustomerCode","verifyWebhookSignature","WEBHOOK_SIGNATURE_HEADER","CLOUDFLARE_CAPABILITIES","adoptExisting","allowedOrigins","captions","generate","upload","dash","downloads","managed","types","importFromUrl","progress","serverUpload","signedPlayback","thumbnailTime","uploadProtocols","webhooks","LIST_PAGE_SIZE","isoSeconds","date","toISOString","replace","requireAssetId","ref","assetId","Error","CloudflareStreamProvider","capabilities","client","id","label","maxTokenTtlSeconds","options","webhook","webhookSetup","apiRegistration","secret","secretLocation","steps","customerCode","accountId","apiBaseUrl","apiToken","fetch","language","generateCaption","list","listCaptions","map","remove","deleteCaption","vtt","uploadCaption","create","type","listDownloads","createDownload","deleteDownload","handle","headers","rawBody","verification","header","get","toleranceSeconds","ok","reason","status","payload","JSON","parse","video","uid","learnCustomerCode","events","asset","v","code","playback","hls","preview","thumbnail","getCustomerCode","hint","deliveryBaseUrl","providerData","getVideo","first","listVideos","limit","scheduledDeletion","days","scheduledDeletionDays","Date","now","undefined","requested","origins","length","createDirectUpload","input","maxDurationSeconds","Math","min","expiry","expiryMinutes","size","directUploadMaxBytes","tus","createTusUpload","creator","name","title","requireSignedURLs","uploadLength","watermarkUID","chunkSize","tusChunkSize","protocol","uploadUrl","location","direct","meta","watermark","url","uploadURL","uploadFromUrl","uploadFile","file","filename","getAsset","err","isNotFound","listAssets","cursor","page","before","last","at","created","next","assets","updateAsset","patch","context","settings","duration","pct","thumbnailTimestampPct","Object","keys","updateVideo","deleteAsset","deleteVideo","signToken","opts","expiresIn","accessRules","floor","expiresAt","signingKey","jwk","keyId","pem","token","downloadable","videoUID","createToken","exp","mp4Ready","mp4","urlOptions","iframe","urls","signed","downloadMp4","canSign","sign","allowNetwork","Boolean","providerOptions","current","getDownloads","catch","cloudflareStream"],"mappings":"AAoBA,SAASA,qBAAqB,EAAEC,YAAY,QAAQ,cAAa;AACjE,SAASC,gBAAgB,EAAEC,kBAAkB,EAAEC,YAAY,EAAEC,YAAY,QAAQ,eAAc;AAC/F,SAASC,qBAAqB,EAAEC,wBAAwB,QAAQ,eAAc;AAC9E,SAASC,eAAe,QAAQ,eAAc;AAC9C,SAASC,iBAAiB,EAAEC,WAAW,EAAEC,mBAAmB,QAAQ,YAAW;AAC/E,SAASC,sBAAsB,EAAEC,wBAAwB,QAAQ,eAAc;AAE/E,OAAO,MAAMC,0BAAgD;IAC3DC,eAAe;IACfC,gBAAgB;IAChBC,UAAU;QAAEC,UAAU;QAAMC,QAAQ;IAAK;IACzCC,MAAM;IACNC,WAAW;QAAEC,SAAS;QAASC,OAAO;YAAC;YAAW;SAAQ;IAAC;IAC3DC,eAAe;IACfC,UAAU;IACVC,cAAc;IACdC,gBAAgB;IAChBC,eAAe;IACfC,iBAAiB;QAAC;QAAQ;KAA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AOO;QAC5C,OAAO;YAAEZ;YAAWe,QAAQ;YAAMV;YAAOS,MAAM;gBAAE,GAAGA,IAAI;gBAAE,GAAIJ,WAAW;oBAAEM,aAAanL,YAAYiF,MAAMuF;gBAAO,IAAI,CAAC,CAAC;YAAE;QAAE;IAC7H;IAEA,8EAA8E;IAC9E,YAAY;IACZ,8EAA8E;IAE9E,oGAAoG,GACpG,MAAc7G,cAAchC,GAAgB,EAAEoH,OAAmB,EAAsB;QACrF,MAAMnE,MAAMlD,eAAeC;QAC3B,IAAIoH,SAAS;YACX,MAAM0C,UAAU,MAAM,IAAI,CAACzJ,MAAM,CAAC0J,YAAY,CAAC9G,KAAK+G,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;YAClE,OAAO;gBAAE,GAAGlM,mBAAmBgM,QAAQ;gBAAE,GAAG1C,OAAO;YAAC;QACtD;QACA,OAAOtJ,mBAAmB,MAAM,IAAI,CAACuC,MAAM,CAAC0J,YAAY,CAAC9G;IAC3D;AACF;AAEA;;;;;;CAMC,GACD,OAAO,MAAMgH,mBAAmB,CAACxJ,UAA+D,IAAIN,yBAAyBM,SAAQ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AssetPatch, DirectUpload, ImportInput, NeutralAsset, PlaybackOptions, PlaybackResult, ProviderCapabilities, ProviderRef, ProviderWebhook, ServerUploadInput, StoredAsset, UploadInput, UploadResolution, VideoProvider } from '../../core/provider.js';
|
|
1
|
+
import type { AssetPatch, DirectUpload, ImportInput, NeutralAsset, PlaybackOptions, PlaybackResult, ProviderCapabilities, ProviderRef, ProviderWebhook, WebhookSetup, ServerUploadInput, StoredAsset, UploadInput, UploadResolution, VideoProvider } from '../../core/provider.js';
|
|
2
2
|
import type { MuxVideoOptions, ResolvedMuxVideoOptions } from './options.js';
|
|
3
3
|
import type { MuxAsset } from './types.js';
|
|
4
4
|
import type { MuxPlaybackTokens } from './urls.js';
|
|
@@ -16,6 +16,7 @@ export declare class MuxVideoProvider implements VideoProvider {
|
|
|
16
16
|
readonly label: string;
|
|
17
17
|
readonly options: ResolvedMuxVideoOptions;
|
|
18
18
|
readonly webhook?: ProviderWebhook;
|
|
19
|
+
readonly webhookSetup: WebhookSetup;
|
|
19
20
|
constructor(options: MuxVideoOptions);
|
|
20
21
|
/** `new_asset_settings` / create-asset settings for the plugin's neutral settings. */
|
|
21
22
|
private assetSettings;
|
|
@@ -73,6 +73,15 @@ const languageName = (language)=>{
|
|
|
73
73
|
label;
|
|
74
74
|
options;
|
|
75
75
|
webhook;
|
|
76
|
+
webhookSetup = {
|
|
77
|
+
secret: 'MUX_WEBHOOK_SECRET (`webhook.secret`)',
|
|
78
|
+
secretLocation: "the webhook's signing secret in the Mux dashboard (Settings → Webhooks)",
|
|
79
|
+
steps: [
|
|
80
|
+
'In the Mux dashboard, open Settings → Webhooks and select the environment your access token belongs to.',
|
|
81
|
+
'Create a webhook with the URL {url}.',
|
|
82
|
+
"Copy the webhook's signing secret into MUX_WEBHOOK_SECRET (or `webhook.secret`)."
|
|
83
|
+
]
|
|
84
|
+
};
|
|
76
85
|
constructor(options){
|
|
77
86
|
this.options = resolveMuxOptions(options);
|
|
78
87
|
this.id = this.options.id;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/providers/mux/provider.ts"],"sourcesContent":["import type {\n AssetPatch,\n AssetSettings,\n CaptionTrack,\n CaptionUploadContext,\n DirectUpload,\n Downloads,\n DownloadType,\n ImportInput,\n NeutralAsset,\n PlaybackOptions,\n PlaybackResult,\n ProviderCapabilities,\n ProviderRef,\n ProviderWebhook,\n ServerUploadInput,\n StoredAsset,\n UploadInput,\n UploadResolution,\n VideoProvider,\n} from '../../core/provider.js'\nimport type { MuxVideoOptions, ResolvedMuxVideoOptions } from './options.js'\nimport type { MuxAudience } from './signing.js'\nimport type { MuxAsset, MuxNewAssetSettings, MuxTrack, MuxUpdateAssetRequest, MuxWebhookEvent } from './types.js'\nimport type { MuxPlaybackTokens } from './urls.js'\n\nimport { MUX_CHUNK_MULTIPLE, MuxClient, MuxError } from './client.js'\nimport {\n currentPlaybackId,\n findStaticRendition,\n isSignedAsset,\n MUX_DOWNLOAD_RESOLUTIONS,\n muxAssetToNeutral,\n muxDownloadsToNeutral,\n muxTracksToCaptions,\n muxUploadError,\n} from './mapping.js'\nimport { resolveMuxOptions } from './options.js'\nimport { signMuxToken } from './signing.js'\nimport { MUX_GENERATED_CAPTION_LANGUAGES } from './types.js'\nimport { buildMuxPlaybackUrls, muxStaticRenditionUrl } from './urls.js'\nimport { MUX_SIGNATURE_HEADER, muxEventRef, verifyMuxWebhookSignature } from './webhook.js'\n\nexport const MUX_CAPABILITIES: ProviderCapabilities = {\n adoptExisting: true,\n allowedOrigins: false,\n captions: { generate: true, upload: true },\n dash: false,\n downloads: { managed: 'video', types: ['default', 'audio'] },\n importFromUrl: true,\n progress: true,\n serverUpload: true,\n signedPlayback: 'video',\n thumbnailTime: true,\n uploadProtocols: ['put-chunked'],\n webhooks: true,\n}\n\nconst PKG = 'payload-video-streaming'\nconst LIST_PAGE_SIZE = 100\n/** Mux limits: `passthrough` 255 characters, `meta.title` 512, `meta.creator_id` / `external_id` 128. */\nconst PASSTHROUGH_MAX = 255\n\nconst httpError = (status: number, message: string): Error => Object.assign(new Error(`[${PKG}] mux: ${message}`), { status })\n\nconst requireAssetId = (ref: ProviderRef): string => {\n if (!ref.assetId) {\n throw httpError(409, 'this video has no Mux asset yet (the upload has not finished)')\n }\n return ref.assetId\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nconst languageName = (language: string): string => {\n try {\n return new Intl.DisplayNames(['en'], { type: 'language' }).of(language) ?? language\n } catch {\n return language\n }\n}\n\n/** The plugin's `meta` object, stored as JSON in the asset's `passthrough` (max 255 characters). */\nexport const metaToPassthrough = (meta: Record<string, unknown> | undefined): string | undefined => {\n if (!meta || !Object.keys(meta).length) {\n return undefined\n }\n const json = JSON.stringify(meta)\n if (json.length > PASSTHROUGH_MAX) {\n throw httpError(400, `\\`meta\\` is stored in the Mux asset's passthrough, which holds at most ${PASSTHROUGH_MAX} characters as JSON`)\n }\n return json\n}\n\n/** The Mux Video provider. Create it with `muxVideo({ … })`. */\nexport class MuxVideoProvider implements VideoProvider {\n readonly capabilities = MUX_CAPABILITIES\n readonly captions: NonNullable<VideoProvider['captions']>\n readonly client: MuxClient\n readonly downloads: NonNullable<VideoProvider['downloads']>\n readonly id: string\n readonly label: string\n readonly options: ResolvedMuxVideoOptions\n readonly webhook?: ProviderWebhook\n\n constructor(options: MuxVideoOptions) {\n this.options = resolveMuxOptions(options)\n this.id = this.options.id\n this.label = this.options.label\n this.client = new MuxClient({\n apiBaseUrl: this.options.apiBaseUrl,\n fetch: this.options.fetch,\n tokenId: this.options.tokenId,\n tokenSecret: this.options.tokenSecret,\n })\n\n this.captions = {\n generate: (ref, language) => this.generateCaption(ref, language),\n list: async (ref) => muxTracksToCaptions((await this.client.getAsset(requireAssetId(ref))).tracks),\n remove: async (ref, language) => {\n const asset = await this.client.getAsset(requireAssetId(ref))\n for (const track of this.textTracks(asset, language)) {\n await this.client.deleteTrack(asset.id, track.id)\n }\n },\n upload: (ref, language, vtt, context) => this.uploadCaption(ref, language, vtt, context),\n }\n\n this.downloads = {\n create: (ref, type) => this.createDownload(ref, type),\n list: async (ref) => this.downloadsOf(await this.client.getAsset(requireAssetId(ref))),\n remove: async (ref, type) => {\n const asset = await this.client.getAsset(requireAssetId(ref))\n const file = findStaticRendition(asset, type)\n if (file?.id) {\n await this.client.deleteStaticRendition(asset.id, file.id)\n }\n },\n }\n\n if (this.options.webhook.secret) {\n this.webhook = {\n handle: async ({ headers, rawBody }) => {\n const verification = verifyMuxWebhookSignature({\n header: headers.get(MUX_SIGNATURE_HEADER),\n rawBody,\n // Read on every call, so the secret can be rotated at runtime.\n secret: this.options.webhook.secret ?? '',\n toleranceSeconds: this.options.webhook.toleranceSeconds,\n })\n if (!verification.ok) {\n return { ok: false, reason: `invalid signature (${verification.reason})`, status: 401 }\n }\n let event: MuxWebhookEvent\n try {\n event = JSON.parse(rawBody) as MuxWebhookEvent\n } catch {\n return { ok: false, reason: 'Invalid JSON body', status: 400 }\n }\n if (!event || typeof event !== 'object' || typeof event.type !== 'string') {\n return { ok: false, reason: 'Webhook payload has no type', status: 400 }\n }\n const ref = muxEventRef(event)\n // No `asset`: the core reads the current state, so duplicate or out-of-order deliveries are harmless.\n return { events: ref ? [{ eventId: typeof event.id === 'string' ? event.id : undefined, ref }] : [], ok: true }\n },\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Uploads\n // ---------------------------------------------------------------------------\n\n /** `new_asset_settings` / create-asset settings for the plugin's neutral settings. */\n private assetSettings(input: AssetSettings & { docId?: number | string }): MuxNewAssetSettings {\n const meta = {\n ...(input.title ? { title: input.title.slice(0, 512) } : {}),\n ...(input.creator ? { creator_id: input.creator.slice(0, 128) } : {}),\n ...(input.docId !== undefined ? { external_id: String(input.docId).slice(0, 128) } : {}),\n }\n const { upload } = this.options\n return {\n ...(Object.keys(meta).length ? { meta } : {}),\n ...(upload.maxResolutionTier ? { max_resolution_tier: upload.maxResolutionTier } : {}),\n ...(metaToPassthrough(input.meta) ? { passthrough: metaToPassthrough(input.meta) } : {}),\n playback_policies: [input.signedPlayback ? 'signed' : 'public'],\n ...(upload.test ? { test: true } : {}),\n ...(upload.videoQuality ? { video_quality: upload.videoQuality } : {}),\n }\n }\n\n async createDirectUpload(input: UploadInput): Promise<DirectUpload> {\n const upload = await this.client.createUpload({\n cors_origin: this.options.upload.corsOrigin ?? input.origin ?? '*',\n new_asset_settings: this.assetSettings(input),\n ...(this.options.upload.test ? { test: true } : {}),\n timeout: this.options.upload.timeoutSeconds,\n })\n if (!upload.url) {\n throw new MuxError('Mux did not return an upload URL', 502)\n }\n return {\n chunkMultiple: MUX_CHUNK_MULTIPLE,\n chunkSize: this.options.upload.chunkSize,\n protocol: 'put-chunked',\n ref: { uploadId: upload.id },\n url: upload.url,\n }\n }\n\n async importFromUrl(input: ImportInput): Promise<NeutralAsset> {\n const asset = await this.client.createAsset({ ...this.assetSettings(input), inputs: [{ url: input.url }] })\n return muxAssetToNeutral(asset)\n }\n\n /** Uploads through a direct upload (cors `*`), then waits for Mux to create the asset. */\n async uploadFile(input: ServerUploadInput): Promise<NeutralAsset> {\n const upload = await this.client.createUpload({\n cors_origin: this.options.upload.corsOrigin ?? '*',\n new_asset_settings: this.assetSettings(input),\n ...(this.options.upload.test ? { test: true } : {}),\n timeout: this.options.upload.timeoutSeconds,\n })\n const blob = input.file instanceof Blob ? input.file : new Blob([input.file as Uint8Array<ArrayBuffer>])\n await this.client.putFile(upload.url!, blob, this.options.upload.chunkSize)\n const deadline = Date.now() + this.options.upload.serverUploadTimeoutMs\n let delay = 200\n for (;;) {\n const resolved = await this.resolveUpload(upload.id)\n if (resolved?.assetId) {\n return muxAssetToNeutral(await this.client.getAsset(resolved.assetId))\n }\n if (!resolved || resolved.error) {\n throw new MuxError(`Mux did not create an asset for upload ${upload.id}: ${resolved?.error?.message ?? 'upload not found'}`, 502)\n }\n if (Date.now() > deadline) {\n throw new MuxError(`Mux did not create an asset for upload ${upload.id} in time`, 504)\n }\n await sleep(delay)\n delay = Math.min(delay * 2, 2000)\n }\n }\n\n async resolveUpload(uploadId: string): Promise<null | UploadResolution> {\n let upload\n try {\n upload = await this.client.getUpload(uploadId)\n } catch (err) {\n if (err instanceof MuxError && err.isNotFound) {\n return null\n }\n throw err\n }\n if (upload.asset_id) {\n return { assetId: upload.asset_id, uploadId }\n }\n const error = muxUploadError(upload)\n return error ? { error, uploadId } : { uploadId }\n }\n\n // ---------------------------------------------------------------------------\n // Assets\n // ---------------------------------------------------------------------------\n\n async getAsset(ref: ProviderRef): Promise<NeutralAsset | null> {\n try {\n return muxAssetToNeutral(await this.client.getAsset(requireAssetId(ref)))\n } catch (err) {\n if (err instanceof MuxError && err.isNotFound) {\n return null\n }\n throw err\n }\n }\n\n /** Pages through the environment's assets with Mux's cursor. `creator` matches `meta.creator_id`. */\n async listAssets({ creator, cursor }: { creator?: string; cursor?: string } = {}): Promise<{ assets: NeutralAsset[]; next?: string }> {\n const page = await this.client.listAssets({ cursor, limit: LIST_PAGE_SIZE })\n const assets = (page.data ?? []).filter((a) => !a.is_live && (!creator || a.meta?.creator_id === creator)).map(muxAssetToNeutral)\n return { assets, next: page.next_cursor || undefined }\n }\n\n async updateAsset(ref: ProviderRef, patch: AssetPatch): Promise<NeutralAsset | null> {\n const assetId = requireAssetId(ref)\n let asset = await this.client.getAsset(assetId)\n let changed = false\n const body: MuxUpdateAssetRequest = {}\n if (patch.title !== undefined || patch.meta !== undefined) {\n body.meta = { ...asset.meta, title: (patch.title ?? '').slice(0, 512) }\n const passthrough = metaToPassthrough(patch.meta)\n if (passthrough !== undefined || asset.passthrough) {\n body.passthrough = passthrough ?? ''\n }\n }\n if (patch.thumbnailTime !== undefined) {\n body.thumbnail_time = patch.thumbnailTime\n }\n if (Object.keys(body).length) {\n asset = await this.client.updateAsset(assetId, body)\n changed = true\n }\n if (patch.signedPlayback !== undefined && patch.signedPlayback !== isSignedAsset(asset)) {\n asset = await this.setPlaybackPolicy(asset, patch.signedPlayback ? 'signed' : 'public')\n changed = true\n }\n return changed ? muxAssetToNeutral(asset) : null\n }\n\n /**\n * Switches an asset between public and signed playback: adds a playback id with the new policy, then\n * deletes the ones with the old policy (Mux can't change a playback id's policy).\n */\n async setPlaybackPolicy(asset: MuxAsset, policy: 'public' | 'signed'): Promise<MuxAsset> {\n const ids = asset.playback_ids ?? []\n const keep = ids.find((p) => p.policy === policy) ?? (await this.client.createPlaybackId(asset.id, policy))\n const old = ids.filter((p) => p.policy !== policy && p.policy !== 'drm')\n for (const p of old) {\n await this.client.deletePlaybackId(asset.id, p.id).catch((err: unknown) => {\n if (!(err instanceof MuxError && err.isNotFound)) {\n throw err\n }\n })\n }\n return { ...asset, playback_ids: [...ids.filter((p) => p.policy === 'drm' || p.policy === policy), ...(ids.includes(keep) ? [] : [keep])] }\n }\n\n /** Deletes an asset, or cancels an upload that has no asset yet. */\n async deleteAsset(ref: ProviderRef): Promise<void> {\n if (ref.assetId) {\n await this.client.deleteAsset(ref.assetId)\n return\n }\n if (!ref.uploadId) {\n return\n }\n try {\n await this.client.cancelUpload(ref.uploadId)\n } catch (err) {\n if (err instanceof MuxError && err.isNotFound) {\n return\n }\n // The file may have arrived meanwhile: delete the asset it became.\n const upload = await this.client.getUpload(ref.uploadId).catch(() => null)\n if (upload?.asset_id) {\n await this.client.deleteAsset(upload.asset_id)\n return\n }\n throw err\n }\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /** Signs one token per audience for a signed playback id. Requires `signingKey`. */\n signTokens(playbackId: string, expiresIn: number): MuxPlaybackTokens {\n const key = this.options.signingKey\n if (!key) {\n throw new Error(`[${PKG}] mux: signed playback needs a signing key (\\`signingKey\\`, or MUX_SIGNING_KEY_ID + MUX_SIGNING_KEY_PRIVATE)`)\n }\n const { animated, playbackRestrictionId, thumbnail } = this.options.playback\n const restriction = playbackRestrictionId ? { playback_restriction_id: playbackRestrictionId } : {}\n const sign = (type: MuxAudience, claims: Record<string, number | string | undefined> = {}) =>\n signMuxToken({\n claims: Object.fromEntries(Object.entries({ ...claims, ...restriction }).filter(([, v]) => v !== undefined)) as Record<string, number | string>,\n expiresIn,\n keyId: key.keyId,\n playbackId,\n privateKey: key.privateKey,\n type,\n })\n return {\n gif: sign('gif', animated),\n storyboard: sign('storyboard'),\n thumbnail: sign('thumbnail', thumbnail),\n video: sign('video'),\n }\n }\n\n private async playbackIdFor(asset: StoredAsset, allowNetwork: boolean): Promise<null | string> {\n if (asset.playbackId) {\n return asset.playbackId\n }\n const stored = asset.providerData as MuxAsset | null | undefined\n const fromStored = stored?.playback_ids ? currentPlaybackId(stored) : null\n if (fromStored || !allowNetwork) {\n return fromStored\n }\n return currentPlaybackId(await this.client.getAsset(asset.assetId))\n }\n\n async playback(asset: StoredAsset, options: PlaybackOptions): Promise<PlaybackResult> {\n const mp4 = asset.downloads?.mp4 === 'ready'\n const base = { animated: this.options.playback.animated, bases: this.options.delivery, mp4, thumbnail: this.options.playback.thumbnail }\n if (asset.signedPlayback && !(options.sign && this.options.signingKey)) {\n return { signed: false, urls: null }\n }\n const playbackId = await this.playbackIdFor(asset, options.allowNetwork)\n if (!playbackId) {\n return { signed: false, urls: null }\n }\n if (!asset.signedPlayback) {\n const { storyboard: _s, ...urls } = buildMuxPlaybackUrls(playbackId, base)\n return { signed: false, urls }\n }\n const expiresAt = new Date((Math.floor(Date.now() / 1000) + options.expiresIn) * 1000).toISOString()\n const tokens = this.signTokens(playbackId, options.expiresIn)\n const { storyboard: _s, ...urls } = buildMuxPlaybackUrls(playbackId, { ...base, tokens })\n return { expiresAt, signed: true, token: tokens.video, urls }\n }\n\n // ---------------------------------------------------------------------------\n // Captions\n // ---------------------------------------------------------------------------\n\n private textTracks(asset: MuxAsset, language: string): MuxTrack[] {\n return (asset.tracks ?? []).filter((t) => t.type === 'text' && t.language_code === language && t.status !== 'deleted')\n }\n\n /** Adds a text track from a signed URL the plugin serves (Mux fetches captions by URL). Replaces the language's existing track. */\n private async uploadCaption(ref: ProviderRef, language: string, _vtt: Blob | string, context: CaptionUploadContext): Promise<CaptionTrack> {\n const asset = await this.client.getAsset(requireAssetId(ref))\n const url = await context.publicUrl()\n for (const track of this.textTracks(asset, language)) {\n await this.client.deleteTrack(asset.id, track.id)\n }\n const track = await this.client.createTrack(asset.id, {\n closed_captions: false,\n language_code: language,\n name: languageName(language),\n text_type: 'subtitles',\n type: 'text',\n url,\n })\n return muxTracksToCaptions([{ language_code: language, ...track, type: 'text' }])[0] ?? { language, status: 'processing' }\n }\n\n private async generateCaption(ref: ProviderRef, language: string): Promise<CaptionTrack> {\n if (!(MUX_GENERATED_CAPTION_LANGUAGES as readonly string[]).includes(language)) {\n throw httpError(400, `Mux generates captions in ${MUX_GENERATED_CAPTION_LANGUAGES.join(', ')} (got \"${language}\")`)\n }\n const asset = await this.client.getAsset(requireAssetId(ref))\n const audio = (asset.tracks ?? []).filter((t) => t.type === 'audio' && t.status !== 'deleted')\n const source = audio.find((t) => t.primary) ?? audio[0]\n if (!source) {\n throw httpError(400, 'Missing audio: the video has no audio track to generate captions from')\n }\n const name = `${language === 'auto' ? 'Captions' : languageName(language)} (auto-generated)`\n const created = await this.client.generateSubtitles(asset.id, source.id, [{ language_code: language, name }])\n const track = (created ?? []).find((t) => t.language_code === language) ?? created?.[0]\n return {\n generated: true,\n label: track?.name ?? name,\n language: track?.language_code ?? language,\n status: track?.status === 'ready' ? 'ready' : track?.status === 'errored' ? 'error' : 'processing',\n }\n }\n\n // ---------------------------------------------------------------------------\n // Downloads (static renditions)\n // ---------------------------------------------------------------------------\n\n private downloadsOf(asset: MuxAsset): Downloads {\n const publicId = isSignedAsset(asset) ? null : currentPlaybackId(asset)\n return muxDownloadsToNeutral(asset, (file) => (publicId ? muxStaticRenditionUrl(publicId, file, this.options.delivery.stream) : null))\n }\n\n private async createDownload(ref: ProviderRef, type: DownloadType): Promise<Downloads> {\n const assetId = requireAssetId(ref)\n const asset = await this.client.getAsset(assetId)\n const existing = findStaticRendition(asset, type)\n if (existing?.id && (existing.status === 'errored' || existing.status === 'skipped')) {\n await this.client.deleteStaticRendition(assetId, existing.id)\n } else if (existing) {\n return this.downloadsOf(asset)\n }\n await this.client.createStaticRendition(assetId, MUX_DOWNLOAD_RESOLUTIONS[type])\n return this.downloadsOf(await this.client.getAsset(assetId))\n }\n}\n\n/**\n * Mux Video as a video provider:\n *\n * ```ts\n * videoPlugin({ providers: [muxVideo({ tokenId, tokenSecret })] })\n * ```\n */\nexport const muxVideo = (options: MuxVideoOptions): MuxVideoProvider => new MuxVideoProvider(options)\n"],"names":["MUX_CHUNK_MULTIPLE","MuxClient","MuxError","currentPlaybackId","findStaticRendition","isSignedAsset","MUX_DOWNLOAD_RESOLUTIONS","muxAssetToNeutral","muxDownloadsToNeutral","muxTracksToCaptions","muxUploadError","resolveMuxOptions","signMuxToken","MUX_GENERATED_CAPTION_LANGUAGES","buildMuxPlaybackUrls","muxStaticRenditionUrl","MUX_SIGNATURE_HEADER","muxEventRef","verifyMuxWebhookSignature","MUX_CAPABILITIES","adoptExisting","allowedOrigins","captions","generate","upload","dash","downloads","managed","types","importFromUrl","progress","serverUpload","signedPlayback","thumbnailTime","uploadProtocols","webhooks","PKG","LIST_PAGE_SIZE","PASSTHROUGH_MAX","httpError","status","message","Object","assign","Error","requireAssetId","ref","assetId","sleep","ms","Promise","resolve","setTimeout","languageName","language","Intl","DisplayNames","type","of","metaToPassthrough","meta","keys","length","undefined","json","JSON","stringify","MuxVideoProvider","capabilities","client","id","label","options","webhook","apiBaseUrl","fetch","tokenId","tokenSecret","generateCaption","list","getAsset","tracks","remove","asset","track","textTracks","deleteTrack","vtt","context","uploadCaption","create","createDownload","downloadsOf","file","deleteStaticRendition","secret","handle","headers","rawBody","verification","header","get","toleranceSeconds","ok","reason","event","parse","events","eventId","assetSettings","input","title","slice","creator","creator_id","docId","external_id","String","maxResolutionTier","max_resolution_tier","passthrough","playback_policies","test","videoQuality","video_quality","createDirectUpload","createUpload","cors_origin","corsOrigin","origin","new_asset_settings","timeout","timeoutSeconds","url","chunkMultiple","chunkSize","protocol","uploadId","createAsset","inputs","uploadFile","blob","Blob","putFile","deadline","Date","now","serverUploadTimeoutMs","delay","resolved","resolveUpload","error","Math","min","getUpload","err","isNotFound","asset_id","listAssets","cursor","page","limit","assets","data","filter","a","is_live","map","next","next_cursor","updateAsset","patch","changed","body","thumbnail_time","setPlaybackPolicy","policy","ids","playback_ids","keep","find","p","createPlaybackId","old","deletePlaybackId","catch","includes","deleteAsset","cancelUpload","signTokens","playbackId","expiresIn","key","signingKey","animated","playbackRestrictionId","thumbnail","playback","restriction","playback_restriction_id","sign","claims","fromEntries","entries","v","keyId","privateKey","gif","storyboard","video","playbackIdFor","allowNetwork","stored","providerData","fromStored","mp4","base","bases","delivery","signed","urls","_s","expiresAt","floor","toISOString","tokens","token","t","language_code","_vtt","publicUrl","createTrack","closed_captions","name","text_type","join","audio","source","primary","created","generateSubtitles","generated","publicId","stream","existing","createStaticRendition","muxVideo"],"mappings":"AA0BA,SAASA,kBAAkB,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,cAAa;AACrE,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,EACxBC,iBAAiB,EACjBC,qBAAqB,EACrBC,mBAAmB,EACnBC,cAAc,QACT,eAAc;AACrB,SAASC,iBAAiB,QAAQ,eAAc;AAChD,SAASC,YAAY,QAAQ,eAAc;AAC3C,SAASC,+BAA+B,QAAQ,aAAY;AAC5D,SAASC,oBAAoB,EAAEC,qBAAqB,QAAQ,YAAW;AACvE,SAASC,oBAAoB,EAAEC,WAAW,EAAEC,yBAAyB,QAAQ,eAAc;AAE3F,OAAO,MAAMC,mBAAyC;IACpDC,eAAe;IACfC,gBAAgB;IAChBC,UAAU;QAAEC,UAAU;QAAMC,QAAQ;IAAK;IACzCC,MAAM;IACNC,WAAW;QAAEC,SAAS;QAASC,OAAO;YAAC;YAAW;SAAQ;IAAC;IAC3DC,eAAe;IACfC,UAAU;IACVC,cAAc;IACdC,gBAAgB;IAChBC,eAAe;IACfC,iBAAiB;QAAC;KAAc;IAChCC,UAAU;AACZ,EAAC;AAED,MAAMC,MAAM;AACZ,MAAMC,iBAAiB;AACvB,uGAAuG,GACvG,MAAMC,kBAAkB;AAExB,MAAMC,YAAY,CAACC,QAAgBC,UAA2BC,OAAOC,MAAM,CAAC,IAAIC,MAAM,CAAC,CAAC,EAAER,IAAI,OAAO,EAAEK,SAAS,GAAG;QAAED;IAAO;AAE5H,MAAMK,iBAAiB,CAACC;IACtB,IAAI,CAACA,IAAIC,OAAO,EAAE;QAChB,MAAMR,UAAU,KAAK;IACvB;IACA,OAAOO,IAAIC,OAAO;AACpB;AAEA,MAAMC,QAAQ,CAACC,KAAe,IAAIC,QAAQ,CAACC,UAAYC,WAAWD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4C,OAAO5C,WAAW,UAAU,UAAU4C,OAAO5C,WAAW,YAAY,UAAU;QACxF;IACF;IAEA,8EAA8E;IAC9E,gCAAgC;IAChC,8EAA8E;IAEtEoD,YAAYT,KAAe,EAAa;QAC9C,MAAM+J,WAAW7O,cAAc8E,SAAS,OAAOhF,kBAAkBgF;QACjE,OAAO3E,sBAAsB2E,OAAO,CAACU,OAAUqJ,WAAWnO,sBAAsBmO,UAAUrJ,MAAM,IAAI,CAACrB,OAAO,CAACkJ,QAAQ,CAACyB,MAAM,IAAI;IAClI;IAEA,MAAcxJ,eAAe7C,GAAgB,EAAEW,IAAkB,EAAsB;QACrF,MAAMV,UAAUF,eAAeC;QAC/B,MAAMqC,QAAQ,MAAM,IAAI,CAACd,MAAM,CAACW,QAAQ,CAACjC;QACzC,MAAMqM,WAAWhP,oBAAoB+E,OAAO1B;QAC5C,IAAI2L,UAAU9K,MAAO8K,CAAAA,SAAS5M,MAAM,KAAK,aAAa4M,SAAS5M,MAAM,KAAK,SAAQ,GAAI;YACpF,MAAM,IAAI,CAAC6B,MAAM,CAACyB,qBAAqB,CAAC/C,SAASqM,SAAS9K,EAAE;QAC9D,OAAO,IAAI8K,UAAU;YACnB,OAAO,IAAI,CAACxJ,WAAW,CAACT;QAC1B;QACA,MAAM,IAAI,CAACd,MAAM,CAACgL,qBAAqB,CAACtM,SAASzC,wBAAwB,CAACmD,KAAK;QAC/E,OAAO,IAAI,CAACmC,WAAW,CAAC,MAAM,IAAI,CAACvB,MAAM,CAACW,QAAQ,CAACjC;IACrD;AACF;AAEA;;;;;;CAMC,GACD,OAAO,MAAMuM,WAAW,CAAC9K,UAA+C,IAAIL,iBAAiBK,SAAQ"}
|
|
1
|
+
{"version":3,"sources":["../../../src/providers/mux/provider.ts"],"sourcesContent":["import type {\n AssetPatch,\n AssetSettings,\n CaptionTrack,\n CaptionUploadContext,\n DirectUpload,\n Downloads,\n DownloadType,\n ImportInput,\n NeutralAsset,\n PlaybackOptions,\n PlaybackResult,\n ProviderCapabilities,\n ProviderRef,\n ProviderWebhook,\n WebhookSetup,\n ServerUploadInput,\n StoredAsset,\n UploadInput,\n UploadResolution,\n VideoProvider,\n} from '../../core/provider.js'\nimport type { MuxVideoOptions, ResolvedMuxVideoOptions } from './options.js'\nimport type { MuxAudience } from './signing.js'\nimport type { MuxAsset, MuxNewAssetSettings, MuxTrack, MuxUpdateAssetRequest, MuxWebhookEvent } from './types.js'\nimport type { MuxPlaybackTokens } from './urls.js'\n\nimport { MUX_CHUNK_MULTIPLE, MuxClient, MuxError } from './client.js'\nimport {\n currentPlaybackId,\n findStaticRendition,\n isSignedAsset,\n MUX_DOWNLOAD_RESOLUTIONS,\n muxAssetToNeutral,\n muxDownloadsToNeutral,\n muxTracksToCaptions,\n muxUploadError,\n} from './mapping.js'\nimport { resolveMuxOptions } from './options.js'\nimport { signMuxToken } from './signing.js'\nimport { MUX_GENERATED_CAPTION_LANGUAGES } from './types.js'\nimport { buildMuxPlaybackUrls, muxStaticRenditionUrl } from './urls.js'\nimport { MUX_SIGNATURE_HEADER, muxEventRef, verifyMuxWebhookSignature } from './webhook.js'\n\nexport const MUX_CAPABILITIES: ProviderCapabilities = {\n adoptExisting: true,\n allowedOrigins: false,\n captions: { generate: true, upload: true },\n dash: false,\n downloads: { managed: 'video', types: ['default', 'audio'] },\n importFromUrl: true,\n progress: true,\n serverUpload: true,\n signedPlayback: 'video',\n thumbnailTime: true,\n uploadProtocols: ['put-chunked'],\n webhooks: true,\n}\n\nconst PKG = 'payload-video-streaming'\nconst LIST_PAGE_SIZE = 100\n/** Mux limits: `passthrough` 255 characters, `meta.title` 512, `meta.creator_id` / `external_id` 128. */\nconst PASSTHROUGH_MAX = 255\n\nconst httpError = (status: number, message: string): Error => Object.assign(new Error(`[${PKG}] mux: ${message}`), { status })\n\nconst requireAssetId = (ref: ProviderRef): string => {\n if (!ref.assetId) {\n throw httpError(409, 'this video has no Mux asset yet (the upload has not finished)')\n }\n return ref.assetId\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))\n\nconst languageName = (language: string): string => {\n try {\n return new Intl.DisplayNames(['en'], { type: 'language' }).of(language) ?? language\n } catch {\n return language\n }\n}\n\n/** The plugin's `meta` object, stored as JSON in the asset's `passthrough` (max 255 characters). */\nexport const metaToPassthrough = (meta: Record<string, unknown> | undefined): string | undefined => {\n if (!meta || !Object.keys(meta).length) {\n return undefined\n }\n const json = JSON.stringify(meta)\n if (json.length > PASSTHROUGH_MAX) {\n throw httpError(400, `\\`meta\\` is stored in the Mux asset's passthrough, which holds at most ${PASSTHROUGH_MAX} characters as JSON`)\n }\n return json\n}\n\n/** The Mux Video provider. Create it with `muxVideo({ … })`. */\nexport class MuxVideoProvider implements VideoProvider {\n readonly capabilities = MUX_CAPABILITIES\n readonly captions: NonNullable<VideoProvider['captions']>\n readonly client: MuxClient\n readonly downloads: NonNullable<VideoProvider['downloads']>\n readonly id: string\n readonly label: string\n readonly options: ResolvedMuxVideoOptions\n readonly webhook?: ProviderWebhook\n readonly webhookSetup: WebhookSetup = {\n secret: 'MUX_WEBHOOK_SECRET (`webhook.secret`)',\n secretLocation: \"the webhook's signing secret in the Mux dashboard (Settings → Webhooks)\",\n steps: [\n 'In the Mux dashboard, open Settings → Webhooks and select the environment your access token belongs to.',\n 'Create a webhook with the URL {url}.',\n \"Copy the webhook's signing secret into MUX_WEBHOOK_SECRET (or `webhook.secret`).\",\n ],\n }\n\n constructor(options: MuxVideoOptions) {\n this.options = resolveMuxOptions(options)\n this.id = this.options.id\n this.label = this.options.label\n this.client = new MuxClient({\n apiBaseUrl: this.options.apiBaseUrl,\n fetch: this.options.fetch,\n tokenId: this.options.tokenId,\n tokenSecret: this.options.tokenSecret,\n })\n\n this.captions = {\n generate: (ref, language) => this.generateCaption(ref, language),\n list: async (ref) => muxTracksToCaptions((await this.client.getAsset(requireAssetId(ref))).tracks),\n remove: async (ref, language) => {\n const asset = await this.client.getAsset(requireAssetId(ref))\n for (const track of this.textTracks(asset, language)) {\n await this.client.deleteTrack(asset.id, track.id)\n }\n },\n upload: (ref, language, vtt, context) => this.uploadCaption(ref, language, vtt, context),\n }\n\n this.downloads = {\n create: (ref, type) => this.createDownload(ref, type),\n list: async (ref) => this.downloadsOf(await this.client.getAsset(requireAssetId(ref))),\n remove: async (ref, type) => {\n const asset = await this.client.getAsset(requireAssetId(ref))\n const file = findStaticRendition(asset, type)\n if (file?.id) {\n await this.client.deleteStaticRendition(asset.id, file.id)\n }\n },\n }\n\n if (this.options.webhook.secret) {\n this.webhook = {\n handle: async ({ headers, rawBody }) => {\n const verification = verifyMuxWebhookSignature({\n header: headers.get(MUX_SIGNATURE_HEADER),\n rawBody,\n // Read on every call, so the secret can be rotated at runtime.\n secret: this.options.webhook.secret ?? '',\n toleranceSeconds: this.options.webhook.toleranceSeconds,\n })\n if (!verification.ok) {\n return { ok: false, reason: `invalid signature (${verification.reason})`, status: 401 }\n }\n let event: MuxWebhookEvent\n try {\n event = JSON.parse(rawBody) as MuxWebhookEvent\n } catch {\n return { ok: false, reason: 'Invalid JSON body', status: 400 }\n }\n if (!event || typeof event !== 'object' || typeof event.type !== 'string') {\n return { ok: false, reason: 'Webhook payload has no type', status: 400 }\n }\n const ref = muxEventRef(event)\n // No `asset`: the core reads the current state, so duplicate or out-of-order deliveries are harmless.\n return { events: ref ? [{ eventId: typeof event.id === 'string' ? event.id : undefined, ref }] : [], ok: true }\n },\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Uploads\n // ---------------------------------------------------------------------------\n\n /** `new_asset_settings` / create-asset settings for the plugin's neutral settings. */\n private assetSettings(input: AssetSettings & { docId?: number | string }): MuxNewAssetSettings {\n const meta = {\n ...(input.title ? { title: input.title.slice(0, 512) } : {}),\n ...(input.creator ? { creator_id: input.creator.slice(0, 128) } : {}),\n ...(input.docId !== undefined ? { external_id: String(input.docId).slice(0, 128) } : {}),\n }\n const { upload } = this.options\n return {\n ...(Object.keys(meta).length ? { meta } : {}),\n ...(upload.maxResolutionTier ? { max_resolution_tier: upload.maxResolutionTier } : {}),\n ...(metaToPassthrough(input.meta) ? { passthrough: metaToPassthrough(input.meta) } : {}),\n playback_policies: [input.signedPlayback ? 'signed' : 'public'],\n ...(upload.test ? { test: true } : {}),\n ...(upload.videoQuality ? { video_quality: upload.videoQuality } : {}),\n }\n }\n\n async createDirectUpload(input: UploadInput): Promise<DirectUpload> {\n const upload = await this.client.createUpload({\n cors_origin: this.options.upload.corsOrigin ?? input.origin ?? '*',\n new_asset_settings: this.assetSettings(input),\n ...(this.options.upload.test ? { test: true } : {}),\n timeout: this.options.upload.timeoutSeconds,\n })\n if (!upload.url) {\n throw new MuxError('Mux did not return an upload URL', 502)\n }\n return {\n chunkMultiple: MUX_CHUNK_MULTIPLE,\n chunkSize: this.options.upload.chunkSize,\n protocol: 'put-chunked',\n ref: { uploadId: upload.id },\n url: upload.url,\n }\n }\n\n async importFromUrl(input: ImportInput): Promise<NeutralAsset> {\n const asset = await this.client.createAsset({ ...this.assetSettings(input), inputs: [{ url: input.url }] })\n return muxAssetToNeutral(asset)\n }\n\n /** Uploads through a direct upload (cors `*`), then waits for Mux to create the asset. */\n async uploadFile(input: ServerUploadInput): Promise<NeutralAsset> {\n const upload = await this.client.createUpload({\n cors_origin: this.options.upload.corsOrigin ?? '*',\n new_asset_settings: this.assetSettings(input),\n ...(this.options.upload.test ? { test: true } : {}),\n timeout: this.options.upload.timeoutSeconds,\n })\n const blob = input.file instanceof Blob ? input.file : new Blob([input.file as Uint8Array<ArrayBuffer>])\n await this.client.putFile(upload.url!, blob, this.options.upload.chunkSize)\n const deadline = Date.now() + this.options.upload.serverUploadTimeoutMs\n let delay = 200\n for (;;) {\n const resolved = await this.resolveUpload(upload.id)\n if (resolved?.assetId) {\n return muxAssetToNeutral(await this.client.getAsset(resolved.assetId))\n }\n if (!resolved || resolved.error) {\n throw new MuxError(`Mux did not create an asset for upload ${upload.id}: ${resolved?.error?.message ?? 'upload not found'}`, 502)\n }\n if (Date.now() > deadline) {\n throw new MuxError(`Mux did not create an asset for upload ${upload.id} in time`, 504)\n }\n await sleep(delay)\n delay = Math.min(delay * 2, 2000)\n }\n }\n\n async resolveUpload(uploadId: string): Promise<null | UploadResolution> {\n let upload\n try {\n upload = await this.client.getUpload(uploadId)\n } catch (err) {\n if (err instanceof MuxError && err.isNotFound) {\n return null\n }\n throw err\n }\n if (upload.asset_id) {\n return { assetId: upload.asset_id, uploadId }\n }\n const error = muxUploadError(upload)\n return error ? { error, uploadId } : { uploadId }\n }\n\n // ---------------------------------------------------------------------------\n // Assets\n // ---------------------------------------------------------------------------\n\n async getAsset(ref: ProviderRef): Promise<NeutralAsset | null> {\n try {\n return muxAssetToNeutral(await this.client.getAsset(requireAssetId(ref)))\n } catch (err) {\n if (err instanceof MuxError && err.isNotFound) {\n return null\n }\n throw err\n }\n }\n\n /** Pages through the environment's assets with Mux's cursor. `creator` matches `meta.creator_id`. */\n async listAssets({ creator, cursor }: { creator?: string; cursor?: string } = {}): Promise<{ assets: NeutralAsset[]; next?: string }> {\n const page = await this.client.listAssets({ cursor, limit: LIST_PAGE_SIZE })\n const assets = (page.data ?? []).filter((a) => !a.is_live && (!creator || a.meta?.creator_id === creator)).map(muxAssetToNeutral)\n return { assets, next: page.next_cursor || undefined }\n }\n\n async updateAsset(ref: ProviderRef, patch: AssetPatch): Promise<NeutralAsset | null> {\n const assetId = requireAssetId(ref)\n let asset = await this.client.getAsset(assetId)\n let changed = false\n const body: MuxUpdateAssetRequest = {}\n if (patch.title !== undefined || patch.meta !== undefined) {\n body.meta = { ...asset.meta, title: (patch.title ?? '').slice(0, 512) }\n const passthrough = metaToPassthrough(patch.meta)\n if (passthrough !== undefined || asset.passthrough) {\n body.passthrough = passthrough ?? ''\n }\n }\n if (patch.thumbnailTime !== undefined) {\n body.thumbnail_time = patch.thumbnailTime\n }\n if (Object.keys(body).length) {\n asset = await this.client.updateAsset(assetId, body)\n changed = true\n }\n if (patch.signedPlayback !== undefined && patch.signedPlayback !== isSignedAsset(asset)) {\n asset = await this.setPlaybackPolicy(asset, patch.signedPlayback ? 'signed' : 'public')\n changed = true\n }\n return changed ? muxAssetToNeutral(asset) : null\n }\n\n /**\n * Switches an asset between public and signed playback: adds a playback id with the new policy, then\n * deletes the ones with the old policy (Mux can't change a playback id's policy).\n */\n async setPlaybackPolicy(asset: MuxAsset, policy: 'public' | 'signed'): Promise<MuxAsset> {\n const ids = asset.playback_ids ?? []\n const keep = ids.find((p) => p.policy === policy) ?? (await this.client.createPlaybackId(asset.id, policy))\n const old = ids.filter((p) => p.policy !== policy && p.policy !== 'drm')\n for (const p of old) {\n await this.client.deletePlaybackId(asset.id, p.id).catch((err: unknown) => {\n if (!(err instanceof MuxError && err.isNotFound)) {\n throw err\n }\n })\n }\n return { ...asset, playback_ids: [...ids.filter((p) => p.policy === 'drm' || p.policy === policy), ...(ids.includes(keep) ? [] : [keep])] }\n }\n\n /** Deletes an asset, or cancels an upload that has no asset yet. */\n async deleteAsset(ref: ProviderRef): Promise<void> {\n if (ref.assetId) {\n await this.client.deleteAsset(ref.assetId)\n return\n }\n if (!ref.uploadId) {\n return\n }\n try {\n await this.client.cancelUpload(ref.uploadId)\n } catch (err) {\n if (err instanceof MuxError && err.isNotFound) {\n return\n }\n // The file may have arrived meanwhile: delete the asset it became.\n const upload = await this.client.getUpload(ref.uploadId).catch(() => null)\n if (upload?.asset_id) {\n await this.client.deleteAsset(upload.asset_id)\n return\n }\n throw err\n }\n }\n\n // ---------------------------------------------------------------------------\n // Playback\n // ---------------------------------------------------------------------------\n\n /** Signs one token per audience for a signed playback id. Requires `signingKey`. */\n signTokens(playbackId: string, expiresIn: number): MuxPlaybackTokens {\n const key = this.options.signingKey\n if (!key) {\n throw new Error(`[${PKG}] mux: signed playback needs a signing key (\\`signingKey\\`, or MUX_SIGNING_KEY_ID + MUX_SIGNING_KEY_PRIVATE)`)\n }\n const { animated, playbackRestrictionId, thumbnail } = this.options.playback\n const restriction = playbackRestrictionId ? { playback_restriction_id: playbackRestrictionId } : {}\n const sign = (type: MuxAudience, claims: Record<string, number | string | undefined> = {}) =>\n signMuxToken({\n claims: Object.fromEntries(Object.entries({ ...claims, ...restriction }).filter(([, v]) => v !== undefined)) as Record<string, number | string>,\n expiresIn,\n keyId: key.keyId,\n playbackId,\n privateKey: key.privateKey,\n type,\n })\n return {\n gif: sign('gif', animated),\n storyboard: sign('storyboard'),\n thumbnail: sign('thumbnail', thumbnail),\n video: sign('video'),\n }\n }\n\n private async playbackIdFor(asset: StoredAsset, allowNetwork: boolean): Promise<null | string> {\n if (asset.playbackId) {\n return asset.playbackId\n }\n const stored = asset.providerData as MuxAsset | null | undefined\n const fromStored = stored?.playback_ids ? currentPlaybackId(stored) : null\n if (fromStored || !allowNetwork) {\n return fromStored\n }\n return currentPlaybackId(await this.client.getAsset(asset.assetId))\n }\n\n async playback(asset: StoredAsset, options: PlaybackOptions): Promise<PlaybackResult> {\n const mp4 = asset.downloads?.mp4 === 'ready'\n const base = { animated: this.options.playback.animated, bases: this.options.delivery, mp4, thumbnail: this.options.playback.thumbnail }\n if (asset.signedPlayback && !(options.sign && this.options.signingKey)) {\n return { signed: false, urls: null }\n }\n const playbackId = await this.playbackIdFor(asset, options.allowNetwork)\n if (!playbackId) {\n return { signed: false, urls: null }\n }\n if (!asset.signedPlayback) {\n const { storyboard: _s, ...urls } = buildMuxPlaybackUrls(playbackId, base)\n return { signed: false, urls }\n }\n const expiresAt = new Date((Math.floor(Date.now() / 1000) + options.expiresIn) * 1000).toISOString()\n const tokens = this.signTokens(playbackId, options.expiresIn)\n const { storyboard: _s, ...urls } = buildMuxPlaybackUrls(playbackId, { ...base, tokens })\n return { expiresAt, signed: true, token: tokens.video, urls }\n }\n\n // ---------------------------------------------------------------------------\n // Captions\n // ---------------------------------------------------------------------------\n\n private textTracks(asset: MuxAsset, language: string): MuxTrack[] {\n return (asset.tracks ?? []).filter((t) => t.type === 'text' && t.language_code === language && t.status !== 'deleted')\n }\n\n /** Adds a text track from a signed URL the plugin serves (Mux fetches captions by URL). Replaces the language's existing track. */\n private async uploadCaption(ref: ProviderRef, language: string, _vtt: Blob | string, context: CaptionUploadContext): Promise<CaptionTrack> {\n const asset = await this.client.getAsset(requireAssetId(ref))\n const url = await context.publicUrl()\n for (const track of this.textTracks(asset, language)) {\n await this.client.deleteTrack(asset.id, track.id)\n }\n const track = await this.client.createTrack(asset.id, {\n closed_captions: false,\n language_code: language,\n name: languageName(language),\n text_type: 'subtitles',\n type: 'text',\n url,\n })\n return muxTracksToCaptions([{ language_code: language, ...track, type: 'text' }])[0] ?? { language, status: 'processing' }\n }\n\n private async generateCaption(ref: ProviderRef, language: string): Promise<CaptionTrack> {\n if (!(MUX_GENERATED_CAPTION_LANGUAGES as readonly string[]).includes(language)) {\n throw httpError(400, `Mux generates captions in ${MUX_GENERATED_CAPTION_LANGUAGES.join(', ')} (got \"${language}\")`)\n }\n const asset = await this.client.getAsset(requireAssetId(ref))\n const audio = (asset.tracks ?? []).filter((t) => t.type === 'audio' && t.status !== 'deleted')\n const source = audio.find((t) => t.primary) ?? audio[0]\n if (!source) {\n throw httpError(400, 'Missing audio: the video has no audio track to generate captions from')\n }\n const name = `${language === 'auto' ? 'Captions' : languageName(language)} (auto-generated)`\n const created = await this.client.generateSubtitles(asset.id, source.id, [{ language_code: language, name }])\n const track = (created ?? []).find((t) => t.language_code === language) ?? created?.[0]\n return {\n generated: true,\n label: track?.name ?? name,\n language: track?.language_code ?? language,\n status: track?.status === 'ready' ? 'ready' : track?.status === 'errored' ? 'error' : 'processing',\n }\n }\n\n // ---------------------------------------------------------------------------\n // Downloads (static renditions)\n // ---------------------------------------------------------------------------\n\n private downloadsOf(asset: MuxAsset): Downloads {\n const publicId = isSignedAsset(asset) ? null : currentPlaybackId(asset)\n return muxDownloadsToNeutral(asset, (file) => (publicId ? muxStaticRenditionUrl(publicId, file, this.options.delivery.stream) : null))\n }\n\n private async createDownload(ref: ProviderRef, type: DownloadType): Promise<Downloads> {\n const assetId = requireAssetId(ref)\n const asset = await this.client.getAsset(assetId)\n const existing = findStaticRendition(asset, type)\n if (existing?.id && (existing.status === 'errored' || existing.status === 'skipped')) {\n await this.client.deleteStaticRendition(assetId, existing.id)\n } else if (existing) {\n return this.downloadsOf(asset)\n }\n await this.client.createStaticRendition(assetId, MUX_DOWNLOAD_RESOLUTIONS[type])\n return this.downloadsOf(await this.client.getAsset(assetId))\n }\n}\n\n/**\n * Mux Video as a video provider:\n *\n * ```ts\n * videoPlugin({ providers: [muxVideo({ tokenId, tokenSecret })] })\n * ```\n */\nexport const muxVideo = (options: MuxVideoOptions): MuxVideoProvider => new MuxVideoProvider(options)\n"],"names":["MUX_CHUNK_MULTIPLE","MuxClient","MuxError","currentPlaybackId","findStaticRendition","isSignedAsset","MUX_DOWNLOAD_RESOLUTIONS","muxAssetToNeutral","muxDownloadsToNeutral","muxTracksToCaptions","muxUploadError","resolveMuxOptions","signMuxToken","MUX_GENERATED_CAPTION_LANGUAGES","buildMuxPlaybackUrls","muxStaticRenditionUrl","MUX_SIGNATURE_HEADER","muxEventRef","verifyMuxWebhookSignature","MUX_CAPABILITIES","adoptExisting","allowedOrigins","captions","generate","upload","dash","downloads","managed","types","importFromUrl","progress","serverUpload","signedPlayback","thumbnailTime","uploadProtocols","webhooks","PKG","LIST_PAGE_SIZE","PASSTHROUGH_MAX","httpError","status","message","Object","assign","Error","requireAssetId","ref","assetId","sleep","ms","Promise","resolve","setTimeout","languageName","language","Intl","DisplayNames","type","of","metaToPassthrough","meta","keys","length","undefined","json","JSON","stringify","MuxVideoProvider","capabilities","client","id","label","options","webhook","webhookSetup","secret","secretLocation","steps","apiBaseUrl","fetch","tokenId","tokenSecret","generateCaption","list","getAsset","tracks","remove","asset","track","textTracks","deleteTrack","vtt","context","uploadCaption","create","createDownload","downloadsOf","file","deleteStaticRendition","handle","headers","rawBody","verification","header","get","toleranceSeconds","ok","reason","event","parse","events","eventId","assetSettings","input","title","slice","creator","creator_id","docId","external_id","String","maxResolutionTier","max_resolution_tier","passthrough","playback_policies","test","videoQuality","video_quality","createDirectUpload","createUpload","cors_origin","corsOrigin","origin","new_asset_settings","timeout","timeoutSeconds","url","chunkMultiple","chunkSize","protocol","uploadId","createAsset","inputs","uploadFile","blob","Blob","putFile","deadline","Date","now","serverUploadTimeoutMs","delay","resolved","resolveUpload","error","Math","min","getUpload","err","isNotFound","asset_id","listAssets","cursor","page","limit","assets","data","filter","a","is_live","map","next","next_cursor","updateAsset","patch","changed","body","thumbnail_time","setPlaybackPolicy","policy","ids","playback_ids","keep","find","p","createPlaybackId","old","deletePlaybackId","catch","includes","deleteAsset","cancelUpload","signTokens","playbackId","expiresIn","key","signingKey","animated","playbackRestrictionId","thumbnail","playback","restriction","playback_restriction_id","sign","claims","fromEntries","entries","v","keyId","privateKey","gif","storyboard","video","playbackIdFor","allowNetwork","stored","providerData","fromStored","mp4","base","bases","delivery","signed","urls","_s","expiresAt","floor","toISOString","tokens","token","t","language_code","_vtt","publicUrl","createTrack","closed_captions","name","text_type","join","audio","source","primary","created","generateSubtitles","generated","publicId","stream","existing","createStaticRendition","muxVideo"],"mappings":"AA2BA,SAASA,kBAAkB,EAAEC,SAAS,EAAEC,QAAQ,QAAQ,cAAa;AACrE,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,aAAa,EACbC,wBAAwB,EACxBC,iBAAiB,EACjBC,qBAAqB,EACrBC,mBAAmB,EACnBC,cAAc,QACT,eAAc;AACrB,SAASC,iBAAiB,QAAQ,eAAc;AAChD,SAASC,YAAY,QAAQ,eAAc;AAC3C,SAASC,+BAA+B,QAAQ,aAAY;AAC5D,SAASC,oBAAoB,EAAEC,qBAAqB,QAAQ,YAAW;AACvE,SAASC,oBAAoB,EAAEC,WAAW,EAAEC,yBAAyB,QAAQ,eAAc;AAE3F,OAAO,MAAMC,mBAAyC;IACpDC,eAAe;IACfC,gBAAgB;IAChBC,UAAU;QAAEC,UAAU;QAAMC,QAAQ;IAAK;IACzCC,MAAM;IACNC,WAAW;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UjL,MAAOiL,CAAAA,SAAS/M,MAAM,KAAK,aAAa+M,SAAS/M,MAAM,KAAK,SAAQ,GAAI;YACpF,MAAM,IAAI,CAAC6B,MAAM,CAAC6B,qBAAqB,CAACnD,SAASwM,SAASjL,EAAE;QAC9D,OAAO,IAAIiL,UAAU;YACnB,OAAO,IAAI,CAACvJ,WAAW,CAACT;QAC1B;QACA,MAAM,IAAI,CAAClB,MAAM,CAACmL,qBAAqB,CAACzM,SAASzC,wBAAwB,CAACmD,KAAK;QAC/E,OAAO,IAAI,CAACuC,WAAW,CAAC,MAAM,IAAI,CAAC3B,MAAM,CAACe,QAAQ,CAACrC;IACrD;AACF;AAEA;;;;;;CAMC,GACD,OAAO,MAAM0M,WAAW,CAACjL,UAA+C,IAAIL,iBAAiBK,SAAQ"}
|
package/dist/service.d.ts
CHANGED
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
import type { Payload, PayloadRequest, Where } from 'payload';
|
|
2
2
|
import type { CaptionTrack, Downloads, DownloadType, NeutralAsset, ProviderRef, VideoProvider } from './core/provider.js';
|
|
3
|
-
import type { AdoptExistingResult, CreateUploadResult, ResolvedVideoOptions, SyncPendingResult, VideoAccess, VideoDoc, VideoPlayback } from './types.js';
|
|
3
|
+
import type { AdoptExistingResult, WebhookStatus, CreateUploadResult, ResolvedVideoOptions, SyncPendingResult, VideoAccess, VideoDoc, VideoPlayback } from './types.js';
|
|
4
4
|
import { ProviderRegistry } from './core/registry.js';
|
|
5
5
|
/** `req.context` flag that stops the plugin's beforeChange hook from pushing changes back to the provider. */
|
|
6
6
|
export declare const SKIP_SYNC_CONTEXT_KEY = "videoSkipSync";
|
|
7
7
|
/** Key used to store the service on `config.custom`. */
|
|
8
8
|
export declare const SERVICE_KEY = "payloadVideoStreaming";
|
|
9
9
|
type DocData = Partial<Omit<VideoDoc, 'id'>>;
|
|
10
|
+
/** Whether a file matches one of `allowedTypes` (MIME types, `type/*` wildcards or `.ext` extensions). */
|
|
11
|
+
export declare const matchesAllowedType: (allowed: string[], file: {
|
|
12
|
+
filename?: string;
|
|
13
|
+
type?: string;
|
|
14
|
+
}) => boolean;
|
|
10
15
|
export declare const CAPTION_SOURCE_TTL_SECONDS = 3600;
|
|
11
16
|
/** Maps a neutral asset onto document fields. Fields the provider doesn't report are left untouched. */
|
|
12
17
|
export declare const assetToDocData: (providerId: string, asset: NeutralAsset) => DocData;
|
|
@@ -34,6 +39,20 @@ export declare class VideoService {
|
|
|
34
39
|
updateDocSilently(id: number | string, data: DocData, req: PayloadRequest): Promise<VideoDoc>;
|
|
35
40
|
private createDocSilently;
|
|
36
41
|
private creatorFor;
|
|
42
|
+
/**
|
|
43
|
+
* Applies `upload.maxFileSize`, `upload.allowedTypes` and `upload.validate` to a browser upload
|
|
44
|
+
* (`size`) or an import (`url`). Throws an HTTP error (413, 415 or 400) when one refuses it. The
|
|
45
|
+
* endpoints call it; server code calling `createUpload()` or `importFromUrl()` directly is trusted.
|
|
46
|
+
*/
|
|
47
|
+
checkUploadRules(input: {
|
|
48
|
+
doc?: VideoDoc;
|
|
49
|
+
filename?: string;
|
|
50
|
+
provider?: string;
|
|
51
|
+
req: PayloadRequest;
|
|
52
|
+
size?: number;
|
|
53
|
+
type?: string;
|
|
54
|
+
url?: string;
|
|
55
|
+
}): Promise<void>;
|
|
37
56
|
/**
|
|
38
57
|
* Creates an upload for a browser (or any client) and a document to track it. Pass `id` to replace the
|
|
39
58
|
* video of an existing document (it keeps its provider). The result says how to send the file.
|
|
@@ -108,6 +127,14 @@ export declare class VideoService {
|
|
|
108
127
|
}, req: PayloadRequest): Promise<{
|
|
109
128
|
matched: boolean;
|
|
110
129
|
}>;
|
|
130
|
+
/** Remembers the latest delivery and rejection per provider (Payload's KV store), for `webhookStatus()`. */
|
|
131
|
+
private recordWebhook;
|
|
132
|
+
/**
|
|
133
|
+
* For each provider: whether it supports and has configured webhooks, the URL to register, how to set
|
|
134
|
+
* it up, and the latest delivery and rejection this server saw.
|
|
135
|
+
* @param baseUrl the site's public origin, e.g. `https://example.com`. Default: `serverURL` from the config.
|
|
136
|
+
*/
|
|
137
|
+
webhookStatus(reqArg?: PayloadRequest, baseUrl?: string): Promise<WebhookStatus[]>;
|
|
111
138
|
/**
|
|
112
139
|
* Default lifetime of a playback token for a video, in seconds: `playback.expiresIn`, extended to
|
|
113
140
|
* outlast the video when `playback.coverDuration` is on (capped at the providers' maximum).
|
package/dist/service.js
CHANGED
|
@@ -6,9 +6,40 @@ const PKG = 'payload-video-streaming';
|
|
|
6
6
|
/** `req.context` flag that stops the plugin's beforeChange hook from pushing changes back to the provider. */ export const SKIP_SYNC_CONTEXT_KEY = 'videoSkipSync';
|
|
7
7
|
/** Key used to store the service on `config.custom`. */ export const SERVICE_KEY = 'payloadVideoStreaming';
|
|
8
8
|
/** How many webhook delivery ids are remembered (per provider) to drop duplicate deliveries. */ const WEBHOOK_DEDUPE_SIZE = 1000;
|
|
9
|
+
const WEBHOOK_STATUS_KV_PREFIX = 'payload-video-streaming:webhook:';
|
|
9
10
|
const httpError = (status, message)=>Object.assign(new Error(message), {
|
|
10
11
|
status
|
|
11
12
|
});
|
|
13
|
+
const formatSize = (bytes)=>{
|
|
14
|
+
const units = [
|
|
15
|
+
'bytes',
|
|
16
|
+
'KB',
|
|
17
|
+
'MB',
|
|
18
|
+
'GB',
|
|
19
|
+
'TB'
|
|
20
|
+
];
|
|
21
|
+
let value = bytes;
|
|
22
|
+
let unit = 0;
|
|
23
|
+
while(value >= 1024 && unit < units.length - 1){
|
|
24
|
+
value /= 1024;
|
|
25
|
+
unit++;
|
|
26
|
+
}
|
|
27
|
+
return `${Number.isInteger(value) ? value : value.toFixed(1)} ${units[unit]}`;
|
|
28
|
+
};
|
|
29
|
+
const shorterOf = (a, b)=>a === undefined ? b : b === undefined ? a : Math.min(a, b);
|
|
30
|
+
/** Whether a file matches one of `allowedTypes` (MIME types, `type/*` wildcards or `.ext` extensions). */ export const matchesAllowedType = (allowed, file)=>{
|
|
31
|
+
const type = file.type?.toLowerCase().split(';')[0]?.trim();
|
|
32
|
+
const name = file.filename?.toLowerCase();
|
|
33
|
+
return allowed.some((rule)=>{
|
|
34
|
+
if (rule.startsWith('.')) {
|
|
35
|
+
return Boolean(name?.endsWith(rule));
|
|
36
|
+
}
|
|
37
|
+
if (rule.endsWith('/*')) {
|
|
38
|
+
return Boolean(type?.startsWith(rule.slice(0, -1)));
|
|
39
|
+
}
|
|
40
|
+
return type === rule;
|
|
41
|
+
});
|
|
42
|
+
};
|
|
12
43
|
/** KV key prefix and lifetime of caption files published for providers that fetch them by URL. */ const CAPTION_SOURCE_KV_PREFIX = `${PKG}:caption-source:`;
|
|
13
44
|
export const CAPTION_SOURCE_TTL_SECONDS = 3600;
|
|
14
45
|
const captionSourceSignature = (secret, id, expires)=>createHmac('sha256', secret).update(`caption-source:${id}:${expires}`).digest('base64url');
|
|
@@ -192,6 +223,29 @@ const docTitle = (doc, fallback)=>doc?.title && String(doc.title) || fallback ||
|
|
|
192
223
|
return value ? value.slice(0, 64) : undefined;
|
|
193
224
|
}
|
|
194
225
|
/**
|
|
226
|
+
* Applies `upload.maxFileSize`, `upload.allowedTypes` and `upload.validate` to a browser upload
|
|
227
|
+
* (`size`) or an import (`url`). Throws an HTTP error (413, 415 or 400) when one refuses it. The
|
|
228
|
+
* endpoints call it; server code calling `createUpload()` or `importFromUrl()` directly is trusted.
|
|
229
|
+
*/ async checkUploadRules(input) {
|
|
230
|
+
const { allowedTypes, maxFileSize, validate } = this.options.upload;
|
|
231
|
+
if (input.size !== undefined && maxFileSize !== undefined && input.size > maxFileSize) {
|
|
232
|
+
throw httpError(413, `Videos can be at most ${formatSize(maxFileSize)}`);
|
|
233
|
+
}
|
|
234
|
+
if (input.size !== undefined && allowedTypes?.length && !matchesAllowedType(allowedTypes, input)) {
|
|
235
|
+
throw httpError(415, `This file type isn't allowed. Allowed: ${allowedTypes.join(', ')}`);
|
|
236
|
+
}
|
|
237
|
+
if (validate) {
|
|
238
|
+
const provider = input.doc?.provider || input.provider || this.providers.defaultId || '';
|
|
239
|
+
const result = await validate({
|
|
240
|
+
...input,
|
|
241
|
+
provider
|
|
242
|
+
});
|
|
243
|
+
if (result !== true) {
|
|
244
|
+
throw httpError(400, typeof result === 'string' && result ? result : 'This upload was refused');
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
195
249
|
* Creates an upload for a browser (or any client) and a document to track it. Pass `id` to replace the
|
|
196
250
|
* video of an existing document (it keeps its provider). The result says how to send the file.
|
|
197
251
|
*/ async createUpload(args) {
|
|
@@ -216,7 +270,7 @@ const docTitle = (doc, fallback)=>doc?.title && String(doc.title) || fallback ||
|
|
|
216
270
|
creator,
|
|
217
271
|
docId: existing?.id,
|
|
218
272
|
filename: args.filename,
|
|
219
|
-
maxDurationSeconds: args.maxDurationSeconds,
|
|
273
|
+
maxDurationSeconds: shorterOf(args.maxDurationSeconds, this.options.upload.maxDurationSeconds),
|
|
220
274
|
meta: args.data?.meta ?? existing?.meta ?? undefined,
|
|
221
275
|
origin: args.origin,
|
|
222
276
|
signedPlayback,
|
|
@@ -630,16 +684,26 @@ const docTitle = (doc, fallback)=>doc?.title && String(doc.title) || fallback ||
|
|
|
630
684
|
}
|
|
631
685
|
/** Handles a provider webhook: verifies it and applies its events. */ async handleWebhook(providerId, input, req) {
|
|
632
686
|
if (!this.providers.has(providerId)) {
|
|
633
|
-
throw httpError(404, `Unknown video provider "${providerId}"`);
|
|
687
|
+
throw httpError(404, `Unknown video provider "${providerId}". Configured: ${this.providers.all.map((p)=>p.id).join(', ')}`);
|
|
634
688
|
}
|
|
635
689
|
const provider = this.provider(providerId);
|
|
636
690
|
this.providers.require(provider, 'webhooks', provider.capabilities.webhooks);
|
|
637
691
|
if (!provider.webhook) {
|
|
638
|
-
|
|
692
|
+
const how = provider.webhookSetup ? ` Set ${provider.webhookSetup.secret} to turn it on.` : '';
|
|
693
|
+
req.payload.logger.warn(`[${PKG}] received a ${provider.label} webhook, but no webhook secret is configured.${how}`);
|
|
694
|
+
throw httpError(404, `Webhooks are not configured for ${provider.label}.${how}`);
|
|
639
695
|
}
|
|
640
696
|
const result = await provider.webhook.handle(input);
|
|
641
697
|
if (!result.ok) {
|
|
642
|
-
|
|
698
|
+
const hint = result.status === 401 && provider.webhookSetup ? ` Check that ${provider.webhookSetup.secret} is ${provider.webhookSetup.secretLocation}.` : '';
|
|
699
|
+
req.payload.logger.warn(`[${PKG}] rejected ${provider.id} webhook: ${result.reason}.${hint}`);
|
|
700
|
+
await this.recordWebhook(provider.id, {
|
|
701
|
+
lastRejection: {
|
|
702
|
+
at: new Date().toISOString(),
|
|
703
|
+
reason: result.reason,
|
|
704
|
+
status: result.status
|
|
705
|
+
}
|
|
706
|
+
}, req);
|
|
643
707
|
throw httpError(result.status, result.status === 401 ? 'Invalid webhook signature' : result.reason);
|
|
644
708
|
}
|
|
645
709
|
let matched = false;
|
|
@@ -671,10 +735,56 @@ const docTitle = (doc, fallback)=>doc?.title && String(doc.title) || fallback ||
|
|
|
671
735
|
await this.applyAsset(provider, asset, req, doc, event.ref);
|
|
672
736
|
}
|
|
673
737
|
}
|
|
738
|
+
await this.recordWebhook(provider.id, {
|
|
739
|
+
lastDelivery: {
|
|
740
|
+
at: new Date().toISOString(),
|
|
741
|
+
matched
|
|
742
|
+
}
|
|
743
|
+
}, req);
|
|
674
744
|
return {
|
|
675
745
|
matched
|
|
676
746
|
};
|
|
677
747
|
}
|
|
748
|
+
/** Remembers the latest delivery and rejection per provider (Payload's KV store), for `webhookStatus()`. */ async recordWebhook(providerId, change, req) {
|
|
749
|
+
try {
|
|
750
|
+
const key = WEBHOOK_STATUS_KV_PREFIX + providerId;
|
|
751
|
+
const previous = await req.payload.kv.get(key) ?? {};
|
|
752
|
+
await req.payload.kv.set(key, {
|
|
753
|
+
...previous,
|
|
754
|
+
...change
|
|
755
|
+
});
|
|
756
|
+
} catch (err) {
|
|
757
|
+
req.payload.logger.debug({
|
|
758
|
+
err,
|
|
759
|
+
msg: `[${PKG}] could not record webhook status`
|
|
760
|
+
});
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* For each provider: whether it supports and has configured webhooks, the URL to register, how to set
|
|
765
|
+
* it up, and the latest delivery and rejection this server saw.
|
|
766
|
+
* @param baseUrl the site's public origin, e.g. `https://example.com`. Default: `serverURL` from the config.
|
|
767
|
+
*/ async webhookStatus(reqArg, baseUrl) {
|
|
768
|
+
const req = await this.resolveReq(reqArg);
|
|
769
|
+
const origin = (baseUrl ?? req.payload.config.serverURL ?? '').replace(/\/+$/, '');
|
|
770
|
+
const apiRoute = req.payload.config.routes?.api ?? '/api';
|
|
771
|
+
return Promise.all(this.providers.all.map(async (provider)=>{
|
|
772
|
+
const url = `${origin}${apiRoute}/${this.collectionSlug}/webhook/${provider.id}`;
|
|
773
|
+
const health = await req.payload.kv.get(WEBHOOK_STATUS_KV_PREFIX + provider.id).catch(()=>null);
|
|
774
|
+
return {
|
|
775
|
+
configured: Boolean(provider.webhook),
|
|
776
|
+
label: provider.label,
|
|
777
|
+
provider: provider.id,
|
|
778
|
+
setup: provider.webhookSetup ? {
|
|
779
|
+
...provider.webhookSetup,
|
|
780
|
+
steps: provider.webhookSetup.steps.map((step)=>step.replaceAll('{url}', url))
|
|
781
|
+
} : undefined,
|
|
782
|
+
supported: provider.capabilities.webhooks,
|
|
783
|
+
url,
|
|
784
|
+
...health ?? {}
|
|
785
|
+
};
|
|
786
|
+
}));
|
|
787
|
+
}
|
|
678
788
|
// ---------------------------------------------------------------------------
|
|
679
789
|
// Playback
|
|
680
790
|
// ---------------------------------------------------------------------------
|