@mux/ai 0.61.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // package.json
8
- var version = "0.61.0";
8
+ var version = "0.62.0";
9
9
 
10
10
  // node_modules/@workflow/serde/dist/index.js
11
11
  var WORKFLOW_SERIALIZE = /* @__PURE__ */ Symbol.for("workflow-serialize");
@@ -627,7 +627,17 @@ var MUX_AI_ERROR_CODES = {
627
627
  /** The dubbing provider doesn't support the requested language. Facts: `language` and `which` (`target` or `source`). */
628
628
  DUBBING_LANGUAGE_UNSUPPORTED: "dubbing_language_unsupported",
629
629
  /** The dubbing provider ran the dub and reported it failed. Facts: `providerError`, the provider's display text, when it gave one. */
630
- DUBBING_FAILED: "dubbing_failed"
630
+ DUBBING_FAILED: "dubbing_failed",
631
+ /** The dubbing provider didn't finish the dub within the polling budget. Facts: `dubbingId`, `timeoutSeconds`, `lastStatus`. */
632
+ DUBBING_TIMEOUT: "dubbing_timeout",
633
+ /** The asset has no audio track, so there is no audio to work with. Facts: `assetId`. */
634
+ AUDIO_TRACK_MISSING: "audio_track_missing",
635
+ /** Writing an audio track would replace the asset's primary audio track, which can't be replaced. Facts: `languageCode`, `conflictingTracks`. */
636
+ PRIMARY_AUDIO_TRACK_CONFLICT: "primary_audio_track_conflict",
637
+ /** The asset's static rendition settings changed while waiting for its rendition. A new job uses the new settings. Facts: `assetId`. */
638
+ STATIC_RENDITION_CHANGED: "static_rendition_changed",
639
+ /** Mux didn't finish the static rendition within the polling budget. Facts: `assetId`, `attempts`, `pollIntervalMs`, `lastStatus`. */
640
+ STATIC_RENDITION_TIMEOUT: "static_rendition_timeout"
631
641
  };
632
642
  var MUX_AI_ERROR_CODE_VALUES = Object.values(MUX_AI_ERROR_CODES);
633
643
  var MUX_AI_ERROR_CATALOG = {
@@ -663,8 +673,8 @@ var MUX_AI_ERROR_CATALOG = {
663
673
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_MISSING]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: false },
664
674
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_INVALID]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: false },
665
675
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_SUPPRESSED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: false },
666
- // Not transient: a step retry would repeat a full generation; the job can be resubmitted.
667
- [MUX_AI_ERROR_CODES.MODEL_OUTPUT_INCOMPLETE]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false },
676
+ // Not transient: a step retry would repeat a full generation. Retryable: the job can be resubmitted.
677
+ [MUX_AI_ERROR_CODES.MODEL_OUTPUT_INCOMPLETE]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: true },
668
678
  [MUX_AI_ERROR_CODES.MODEL_OUTPUT_TRUNCATED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.INTERNAL, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER },
669
679
  // Mux Video.
670
680
  // Reported by Mux: a step retry would find the same errored rendition, and resubmitting the same asset errors again.
@@ -672,7 +682,16 @@ var MUX_AI_ERROR_CATALOG = {
672
682
  // Audio dubbing.
673
683
  [MUX_AI_ERROR_CODES.DUBBING_LANGUAGE_UNSUPPORTED]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.REQUEST, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER },
674
684
  // Reported by the dubbing provider: a step retry would find the same failed dub.
675
- [MUX_AI_ERROR_CODES.DUBBING_FAILED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false }
685
+ // Retryable by default; each failure sets it from the provider's report.
686
+ [MUX_AI_ERROR_CODES.DUBBING_FAILED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: true },
687
+ // Polling timeouts: not transient, since the whole polling budget was already spent,
688
+ // but retryable, since a later attempt may finish in time.
689
+ [MUX_AI_ERROR_CODES.DUBBING_TIMEOUT]: { type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER, transient: false, retryable: true },
690
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT]: { type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR, source: MUX_AI_ERROR_SOURCES.UPSTREAM, dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO, transient: false, retryable: true },
691
+ [MUX_AI_ERROR_CODES.AUDIO_TRACK_MISSING]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
692
+ [MUX_AI_ERROR_CODES.PRIMARY_AUDIO_TRACK_CONFLICT]: { type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET },
693
+ // Retryable although asset-sourced: the asset changed mid-run, and a new job uses the new settings.
694
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_CHANGED]: { type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR, source: MUX_AI_ERROR_SOURCES.ASSET, retryable: true }
676
695
  };
677
696
  function isTransientStatus(status) {
678
697
  return status === void 0 || status === 408 || status === 425 || status === 429 || status >= 500;
@@ -1834,13 +1853,6 @@ function planTextTrackReplacement(asset, target, policy) {
1834
1853
  tracks: tracks.map(summarizeTextTrack),
1835
1854
  conflictsOnLanguage: tracks.some((track) => sameLanguageIds.has(track.id))
1836
1855
  });
1837
- if (policy === "fail") {
1838
- return blocked(
1839
- "policy_fail",
1840
- `${countTracks(conflicting, label, "already exists", "already exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(conflicting)}. Set replaceExistingTracks to replace ${itOrThem(conflicting)}.`,
1841
- conflicting
1842
- );
1843
- }
1844
1856
  const primary = conflicting.filter((track) => track.type === "audio" && track.primary === true);
1845
1857
  if (primary.length > 0) {
1846
1858
  return blocked(
@@ -1849,6 +1861,13 @@ function planTextTrackReplacement(asset, target, policy) {
1849
1861
  primary
1850
1862
  );
1851
1863
  }
1864
+ if (policy === "fail") {
1865
+ return blocked(
1866
+ "policy_fail",
1867
+ `${countTracks(conflicting, label, "already exists", "already exist")} for language '${target.languageCode}' or name '${target.name}': ${describeTracks(conflicting)}. Set replaceExistingTracks to replace ${itOrThem(conflicting)}.`,
1868
+ conflicting
1869
+ );
1870
+ }
1852
1871
  if (policy === "replace_generated") {
1853
1872
  const notGenerated = conflicting.filter((track) => track.type !== "text" || !isMuxGeneratedTextTrack(track));
1854
1873
  if (notGenerated.length > 0) {
@@ -1923,6 +1942,7 @@ function trackReplacementBlockedError(blocked, options = {}) {
1923
1942
  };
1924
1943
  if (blocked.code === "primary_audio" && blocked.conflictsOnLanguage) {
1925
1944
  return new MuxAiError(message, {
1945
+ code: MUX_AI_ERROR_CODES.PRIMARY_AUDIO_TRACK_CONFLICT,
1926
1946
  type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
1927
1947
  source: MUX_AI_ERROR_SOURCES.ASSET,
1928
1948
  facts
@@ -2361,6 +2381,23 @@ var MUX_AI_ERROR_PUBLIC_MAPPINGS = {
2361
2381
  facts: ["language", "which"],
2362
2382
  message: (facts) => `Audio dubbing doesn't support the ${text(facts.which) || "requested"} language "${text(facts.language)}".`
2363
2383
  },
2384
+ [MUX_AI_ERROR_CODES.DUBBING_TIMEOUT]: {
2385
+ message: "Audio dubbing didn't finish in time. Please try again."
2386
+ },
2387
+ [MUX_AI_ERROR_CODES.AUDIO_TRACK_MISSING]: {
2388
+ facts: ["assetId"],
2389
+ message: (facts) => `${facts.assetId ? `Asset ${text(facts.assetId)}` : "The asset"} has no audio track, so there is no audio to work with.`
2390
+ },
2391
+ [MUX_AI_ERROR_CODES.PRIMARY_AUDIO_TRACK_CONFLICT]: {
2392
+ facts: ["languageCode"],
2393
+ message: (facts) => `The asset's primary audio track${facts.languageCode ? ` is in language '${text(facts.languageCode)}' and` : ""} can't be replaced. Choose a different target language.`
2394
+ },
2395
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_CHANGED]: {
2396
+ message: "The asset's static rendition settings changed while it was being processed. Please try again."
2397
+ },
2398
+ [MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT]: {
2399
+ message: "The asset's static rendition wasn't ready in time. Please try again in a moment."
2400
+ },
2364
2401
  [MUX_AI_ERROR_CODES.DUBBING_FAILED]: {
2365
2402
  // The dubbing provider documents this text as safe to display.
2366
2403
  facts: ["providerError"],
@@ -10493,17 +10530,34 @@ import { sleep as sleep2 } from "workflow";
10493
10530
  // src/lib/elevenlabs-errors.ts
10494
10531
  var MAX_ERROR_BODY_CHARS = 500;
10495
10532
  function isRetryableElevenLabsStatus(status) {
10496
- return status === 408 || status === 425 || status === 429 || status >= 500;
10533
+ return isTransientStatus(status);
10534
+ }
10535
+ function elevenLabsFailureError(message, call, failure, facts) {
10536
+ return dependencyError(message, {
10537
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10538
+ call,
10539
+ status: failure.httpStatus,
10540
+ requestId: failure.requestId,
10541
+ timedOut: failure.reason === "timeout",
10542
+ facts: {
10543
+ provider: "elevenlabs",
10544
+ ...failure.reason && { providerCode: failure.reason },
10545
+ ...failure.detail && { detail: errorDetailFact(failure.detail) },
10546
+ ...facts
10547
+ },
10548
+ transient: false,
10549
+ retryable: failure.retryable
10550
+ });
10497
10551
  }
10498
10552
  async function elevenLabsResponseFailure(response) {
10499
10553
  const body = await response.text().catch(() => "");
10500
- return httpFailure(response.status, response.statusText, body);
10554
+ return httpFailure(response.status, response.statusText, body, response.headers);
10501
10555
  }
10502
10556
  function elevenLabsSdkFailure(error) {
10503
10557
  const failure = error;
10504
10558
  if (typeof failure?.statusCode === "number") {
10505
10559
  const body = typeof failure.body === "string" ? failure.body : JSON.stringify(failure.body ?? "");
10506
- return httpFailure(failure.statusCode, failure.rawResponse?.statusText, body);
10560
+ return httpFailure(failure.statusCode, failure.rawResponse?.statusText, body, failure.rawResponse?.headers);
10507
10561
  }
10508
10562
  const message = failure?.message ?? String(error);
10509
10563
  switch (failure?.name) {
@@ -10520,12 +10574,14 @@ function elevenLabsSdkFailure(error) {
10520
10574
  return { retryable: false, detail: message };
10521
10575
  }
10522
10576
  }
10523
- function httpFailure(status, statusText, body) {
10577
+ function httpFailure(status, statusText, body, headers) {
10524
10578
  const statusLine = [status, statusText].filter(Boolean).join(" ");
10525
- const { reason, detail } = parseElevenLabsErrorBody(body);
10579
+ const { reason, detail, requestId } = parseElevenLabsErrorBody(body);
10580
+ const responseRequestId = requestId ?? requestIdOf(headers);
10526
10581
  return {
10527
10582
  httpStatus: status,
10528
10583
  reason,
10584
+ ...responseRequestId && { requestId: responseRequestId },
10529
10585
  retryable: isRetryableElevenLabsStatus(status),
10530
10586
  detail: detail ? `${statusLine}: ${detail}` : statusLine
10531
10587
  };
@@ -10555,7 +10611,11 @@ function parseElevenLabsErrorBody(body) {
10555
10611
  const reasonText = [reasonCode, message].filter(Boolean).join(": ");
10556
10612
  const context = [param && `param: ${param}`, requestId && `request_id: ${requestId}`].filter(Boolean).join(", ");
10557
10613
  if (reasonText) {
10558
- return { reason: reasonCode, detail: context ? `${reasonText} (${context})` : reasonText };
10614
+ return {
10615
+ reason: reasonCode,
10616
+ detail: context ? `${reasonText} (${context})` : reasonText,
10617
+ ...typeof requestId === "string" && requestId && { requestId }
10618
+ };
10559
10619
  }
10560
10620
  }
10561
10621
  return { detail: trimmed.slice(0, MAX_ERROR_BODY_CHARS) };
@@ -10610,7 +10670,7 @@ async function requestStaticRenditionCreation(assetId, credentials) {
10610
10670
  if (statusCode === 409 || alreadyDefined) {
10611
10671
  return void 0;
10612
10672
  }
10613
- legacyWrapError(error, "Failed to request static rendition from Mux");
10673
+ throw muxVideoCallError("Failed to request static rendition from Mux", "create_static_rendition", error, { assetId });
10614
10674
  }
10615
10675
  }
10616
10676
  async function deleteCreatedStaticRendition(assetId, staticRenditionId, credentials) {
@@ -10638,7 +10698,11 @@ async function retrieveAsset(assetId, credentials) {
10638
10698
  "use step";
10639
10699
  const muxClient = await resolveMuxClient(credentials);
10640
10700
  const mux = await muxClient.createClient();
10641
- return mux.video.assets.retrieve(assetId);
10701
+ try {
10702
+ return await mux.video.assets.retrieve(assetId);
10703
+ } catch (error) {
10704
+ throw muxVideoCallError("Failed to fetch the asset from Mux", "get_asset", error, { assetId });
10705
+ }
10642
10706
  }
10643
10707
  async function waitForAudioStaticRendition({
10644
10708
  assetId,
@@ -10660,14 +10724,36 @@ async function waitForAudioStaticRendition({
10660
10724
  `\u231B Waiting for static rendition (attempt ${attempt}/${STATIC_RENDITION_MAX_ATTEMPTS}) \u2192 ${currentStatus}`
10661
10725
  );
10662
10726
  if (currentStatus === "errored") {
10663
- throw new LegacyMuxAiError(
10664
- "Mux failed to create the static rendition for this asset. Please check the asset in the Mux dashboard."
10727
+ throw new MuxAiError(
10728
+ "Mux failed to create the static rendition for this asset. Please check the asset in the Mux dashboard.",
10729
+ {
10730
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_FAILED,
10731
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10732
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10733
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
10734
+ facts: { call: "get_asset", assetId, renditionStatus: currentStatus }
10735
+ }
10665
10736
  );
10666
10737
  }
10667
10738
  }
10668
- throw new LegacyMuxAiError(
10739
+ throw new MuxAiError(
10669
10740
  "Timed out waiting for the static rendition to become ready. Please try again in a moment.",
10670
- { type: "timeout_error", retryable: true }
10741
+ {
10742
+ // Mux didn't finish the rendition in time; the asset itself is fine.
10743
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT,
10744
+ type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR,
10745
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10746
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
10747
+ facts: {
10748
+ call: "get_asset",
10749
+ assetId,
10750
+ attempts: STATIC_RENDITION_MAX_ATTEMPTS,
10751
+ pollIntervalMs: STATIC_RENDITION_POLL_INTERVAL_MS,
10752
+ lastStatus: getAudioStaticRenditionStatus(currentAsset)
10753
+ },
10754
+ // Not transient: this already polled for the whole budget.
10755
+ transient: false
10756
+ }
10671
10757
  );
10672
10758
  }
10673
10759
  async function waitForLegacyMp4SupportRendition({
@@ -10684,23 +10770,48 @@ async function waitForLegacyMp4SupportRendition({
10684
10770
  rendition = resolveLegacyMp4SupportRendition(await retrieveAsset(assetId, credentials));
10685
10771
  }
10686
10772
  if (!rendition) {
10687
- throw new LegacyMuxAiError(
10773
+ throw new MuxAiError(
10688
10774
  "The asset's static rendition settings changed while waiting for them. Please try again.",
10689
- { type: "processing_error", retryable: true }
10775
+ {
10776
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_CHANGED,
10777
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
10778
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10779
+ facts: { assetId },
10780
+ // Retryable although asset-sourced: the asset changed mid-run, and a new job uses the new settings.
10781
+ retryable: true
10782
+ }
10690
10783
  );
10691
10784
  }
10692
10785
  if (rendition.kind === "preparing") {
10693
- throw new LegacyMuxAiError(
10786
+ throw new MuxAiError(
10694
10787
  "Timed out waiting for the static rendition to become ready. Please try again in a moment.",
10695
- { type: "timeout_error", retryable: true }
10788
+ {
10789
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_TIMEOUT,
10790
+ type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR,
10791
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
10792
+ dependency: MUX_AI_ERROR_DEPENDENCIES.MUX_VIDEO,
10793
+ facts: { call: "get_asset", assetId, attempts: STATIC_RENDITION_MAX_ATTEMPTS, pollIntervalMs: STATIC_RENDITION_POLL_INTERVAL_MS },
10794
+ // Not transient: this already polled for the whole budget.
10795
+ transient: false
10796
+ }
10696
10797
  );
10697
10798
  }
10698
10799
  if (rendition.kind === "unusable") {
10699
- throw new LegacyMuxAiError(rendition.reason, { type: "validation_error" });
10800
+ throw new MuxAiError(rendition.reason, {
10801
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_UNSUPPORTED,
10802
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10803
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10804
+ facts: { reason: "unusable", assetId, mp4Support: rendition.mp4Support, ...rendition.status && { renditionStatus: rendition.status } }
10805
+ });
10700
10806
  }
10701
10807
  const sizeError = getLegacyMp4SupportRenditionSizeError(rendition, MAX_DUBBING_SOURCE_BYTES);
10702
10808
  if (sizeError) {
10703
- throw new LegacyMuxAiError(sizeError, { type: "validation_error" });
10809
+ throw new MuxAiError(sizeError, {
10810
+ code: MUX_AI_ERROR_CODES.STATIC_RENDITION_UNSUPPORTED,
10811
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10812
+ source: MUX_AI_ERROR_SOURCES.ASSET,
10813
+ facts: { reason: "too_large", assetId, renditionName: rendition.name, sizeBytes: rendition.filesizeBytes, maxBytes: MAX_DUBBING_SOURCE_BYTES }
10814
+ });
10704
10815
  }
10705
10816
  return rendition.name;
10706
10817
  }
@@ -10710,33 +10821,49 @@ function toBaseLanguageCode(code) {
10710
10821
  function audioTrackUnsupportedReason(asset) {
10711
10822
  const useDubbedFile = "skip uploading to Mux and use the dubbed audio file directly.";
10712
10823
  if (asset.ingest_type === "on_demand_clip" || asset.source_asset_id) {
10713
- return `is a clip, and Mux does not support adding audio tracks to clipped assets. Dub the source asset instead, or ${useDubbedFile}`;
10824
+ return { reason: "clip", message: `is a clip, and Mux does not support adding audio tracks to clipped assets. Dub the source asset instead, or ${useDubbedFile}` };
10714
10825
  }
10715
10826
  if (asset.is_live || asset.live_stream_id) {
10716
- return `comes from a live stream, and Mux does not support adding audio tracks to live stream assets. Instead, ${useDubbedFile}`;
10827
+ return { reason: "live_stream", message: `comes from a live stream, and Mux does not support adding audio tracks to live stream assets. Instead, ${useDubbedFile}` };
10717
10828
  }
10718
10829
  if (isAudioOnlyAsset(asset)) {
10719
- return `is audio-only, and Mux does not support adding audio tracks to audio-only assets. Instead, ${useDubbedFile}`;
10830
+ return { reason: "audio_only", message: `is audio-only, and Mux does not support adding audio tracks to audio-only assets. Instead, ${useDubbedFile}` };
10720
10831
  }
10721
10832
  return void 0;
10722
10833
  }
10723
- function dubbingProviderError(message, failure) {
10724
- if (failure.reason === "timeout") {
10725
- return new LegacyMuxAiError(`${message} The dubbing service timed out. Please try again.`, { type: "timeout_error", retryable: true });
10726
- }
10727
- if (failure.retryable) {
10728
- return new LegacyMuxAiError(`${message} The dubbing service is temporarily unavailable. Please try again.`, { type: "processing_error", retryable: true });
10729
- }
10730
- return new LegacyMuxAiError(message, { type: "processing_error" });
10834
+ function dubbingProviderError(message, call, failure, facts) {
10835
+ const detailed = failure.reason === "timeout" ? `${message} The dubbing service timed out. Please try again.` : failure.retryable ? `${message} The dubbing service is temporarily unavailable. Please try again.` : message;
10836
+ return elevenLabsFailureError(detailed, call, failure, facts);
10731
10837
  }
10732
- function dubbingStartError(failure, languages) {
10733
- if (failure.reason === "unsupported_target_language") {
10734
- return new LegacyMuxAiError(`Audio dubbing does not support the target language "${languages.target}".`, { type: "validation_error" });
10735
- }
10736
- if (failure.reason === "unsupported_source_language" && languages.source) {
10737
- return new LegacyMuxAiError(`Audio dubbing does not support the source language "${languages.source}".`, { type: "validation_error" });
10838
+ function dubbingStartError(failure, languages, facts) {
10839
+ const call = "elevenlabs_create_dubbing_project";
10840
+ const unsupported = failure.reason === "unsupported_target_language" ? { language: languages.target, which: "target" } : failure.reason === "unsupported_source_language" && languages.source ? { language: languages.source, which: "source" } : void 0;
10841
+ if (unsupported) {
10842
+ return new MuxAiError(`Audio dubbing does not support the ${unsupported.which} language "${unsupported.language}".`, {
10843
+ code: MUX_AI_ERROR_CODES.DUBBING_LANGUAGE_UNSUPPORTED,
10844
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
10845
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
10846
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
10847
+ facts: {
10848
+ language: unsupported.language,
10849
+ which: unsupported.which,
10850
+ call,
10851
+ provider: "elevenlabs",
10852
+ ...failure.httpStatus !== void 0 && { status: failure.httpStatus },
10853
+ ...failure.requestId && { requestId: failure.requestId },
10854
+ providerCode: failure.reason,
10855
+ ...facts
10856
+ }
10857
+ });
10738
10858
  }
10739
- return dubbingProviderError("Audio dubbing could not be started.", failure);
10859
+ return dubbingProviderError("Audio dubbing could not be started.", call, failure, facts);
10860
+ }
10861
+ function stagedAudioFacts(presignedUrl, bucket) {
10862
+ const key = presignedUrl?.split("?")[0].match(/audio-translations\/[^?#]+$/)?.[0];
10863
+ return {
10864
+ ...bucket && { stagedAudioBucket: bucket },
10865
+ ...key && { stagedAudioKey: key }
10866
+ };
10740
10867
  }
10741
10868
  async function createElevenLabsDubbingJob({
10742
10869
  sourceUrl,
@@ -10969,15 +11096,25 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10969
11096
  trackPassthrough: providedTrackPassthrough
10970
11097
  } = options;
10971
11098
  if (provider !== "elevenlabs") {
10972
- throw new LegacyMuxAiError("Only ElevenLabs provider is currently supported for audio translation.", { type: "validation_error" });
11099
+ throw new MuxAiError("Only ElevenLabs provider is currently supported for audio translation.", {
11100
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
11101
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
11102
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
11103
+ facts: { parameter: "provider", reason: "not_allowed", allowed: ["elevenlabs"], value: String(provider).slice(0, 100), inputs: ["provider"] }
11104
+ });
10973
11105
  }
10974
11106
  const targetLanguageCode = toISO639_1(toLanguageCode);
10975
11107
  if (numSpeakers !== 0) {
10976
- throw new LegacyMuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", { type: "validation_error" });
11108
+ throw new MuxAiError("The ElevenLabs project API does not support numSpeakers overrides. Omit it or use 0 for auto-detection.", {
11109
+ code: MUX_AI_ERROR_CODES.INVALID_PARAMETER,
11110
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
11111
+ source: MUX_AI_ERROR_SOURCES.REQUEST,
11112
+ facts: { parameter: "numSpeakers", reason: "not_allowed", allowed: [0], value: numSpeakers, inputs: ["numSpeakers"] }
11113
+ });
10977
11114
  }
10978
11115
  const credentials = providedCredentials;
10979
11116
  const effectiveStorageAdapter = storageAdapter;
10980
- const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough) ?? buildMuxAiTrackPassthrough("translate-audio");
11117
+ const trackPassthrough = validateTrackPassthrough(providedTrackPassthrough, { classifiedErrors: true }) ?? buildMuxAiTrackPassthrough("translate-audio");
10981
11118
  const uploadToMux = uploadToMuxOption !== false;
10982
11119
  const uploadToS3 = uploadToS3Option || uploadToMux || uploadCaptionsToMux;
10983
11120
  const muxLangCode = targetLanguageCode;
@@ -10989,22 +11126,40 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
10989
11126
  const s3Bucket = options.s3Bucket ?? env_default.S3_BUCKET;
10990
11127
  const s3AccessKeyId = env_default.S3_ACCESS_KEY_ID;
10991
11128
  const s3SecretAccessKey = env_default.S3_SECRET_ACCESS_KEY;
10992
- if (uploadToS3 && (!s3Endpoint || !s3Bucket || !effectiveStorageAdapter && (!s3AccessKeyId || !s3SecretAccessKey))) {
10993
- throw new LegacyMuxAiError("Storage configuration is required for uploading. Provide s3Endpoint and s3Bucket. If no storageAdapter is supplied, also provide s3AccessKeyId and s3SecretAccessKey in options or set S3_ENDPOINT, S3_BUCKET, S3_ACCESS_KEY_ID, and S3_SECRET_ACCESS_KEY environment variables.", { type: "validation_error" });
11129
+ if (uploadToS3) {
11130
+ const missing = [
11131
+ ...s3Endpoint ? [] : ["s3Endpoint"],
11132
+ ...s3Bucket ? [] : ["s3Bucket"],
11133
+ ...effectiveStorageAdapter || s3AccessKeyId ? [] : ["S3_ACCESS_KEY_ID"],
11134
+ ...effectiveStorageAdapter || s3SecretAccessKey ? [] : ["S3_SECRET_ACCESS_KEY"]
11135
+ ];
11136
+ if (missing.length > 0) {
11137
+ throw storageNotConfiguredError(missing);
11138
+ }
10994
11139
  }
10995
- const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot);
11140
+ const { asset: initialAsset, playbackId, policy } = await getPlaybackIdForAsset(assetId, credentials, options.assetSnapshot, { classifiedErrors: true });
10996
11141
  const assetDurationSeconds = getAssetDurationSecondsFromAsset(initialAsset);
10997
11142
  if (isVideoOnlyAsset(initialAsset)) {
10998
- throw new LegacyMuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, { type: "validation_error" });
11143
+ throw new MuxAiError(`Asset ${assetId} has no audio track, so there is no audio to dub.`, {
11144
+ code: MUX_AI_ERROR_CODES.AUDIO_TRACK_MISSING,
11145
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
11146
+ source: MUX_AI_ERROR_SOURCES.ASSET,
11147
+ facts: { assetId }
11148
+ });
10999
11149
  }
11000
11150
  const audioTrackUnsupported = uploadToMux ? audioTrackUnsupportedReason(initialAsset) : void 0;
11001
11151
  if (audioTrackUnsupported) {
11002
- throw new LegacyMuxAiError(`Asset ${assetId} ${audioTrackUnsupported}`, { type: "validation_error" });
11152
+ throw new MuxAiError(`Asset ${assetId} ${audioTrackUnsupported.message}`, {
11153
+ code: MUX_AI_ERROR_CODES.AUDIO_TRACK_UNSUPPORTED,
11154
+ type: MUX_AI_ERROR_TYPES.VALIDATION_ERROR,
11155
+ source: MUX_AI_ERROR_SOURCES.ASSET,
11156
+ facts: { assetId, reason: audioTrackUnsupported.reason }
11157
+ });
11003
11158
  }
11004
11159
  if (uploadToMux) {
11005
11160
  const plan = planTextTrackReplacement(initialAsset, audioTrackTarget, replaceExistingTracks);
11006
11161
  if (plan.kind === "blocked") {
11007
- throw new LegacyMuxAiError(plan.reason, { type: "validation_error" });
11162
+ throw trackReplacementBlockedError(plan, { facts: { ...trackTargetFacts(audioTrackTarget), assetId, policy: replaceExistingTracks } });
11008
11163
  }
11009
11164
  }
11010
11165
  let currentAsset = initialAsset;
@@ -11044,13 +11199,6 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11044
11199
  credentials
11045
11200
  });
11046
11201
  }
11047
- const audioRendition = getReadyAudioStaticRendition(currentAsset);
11048
- if (!audioRendition) {
11049
- throw new LegacyMuxAiError(
11050
- "Unable to obtain an audio-only static rendition for this asset. Please verify static renditions are enabled in Mux.",
11051
- { type: "validation_error" }
11052
- );
11053
- }
11054
11202
  }
11055
11203
  let audioUrl = `${await getMuxStreamOrigin(credentials)}/${playbackId}/${sourceRenditionName}`;
11056
11204
  if (policy === "signed") {
@@ -11073,7 +11221,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11073
11221
  credentials
11074
11222
  });
11075
11223
  } catch (error) {
11076
- legacyWrapError(error, "Failed to create ElevenLabs dubbing job");
11224
+ wrapError(error, "Failed to create ElevenLabs dubbing job", { provider: "elevenlabs", assetId });
11077
11225
  }
11078
11226
  if (created.kind === "failed") {
11079
11227
  const { failure } = created;
@@ -11081,7 +11229,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11081
11229
  console.warn(
11082
11230
  `Failed to create ElevenLabs dubbing project for asset ${assetId}: ${failure.detail}${mayHaveCreated ? " The project may have been created; check ElevenLabs before retrying." : ""}`
11083
11231
  );
11084
- throw dubbingStartError(failure, { target: elevenLabsLangCode, source: elevenLabsSourceLangCode });
11232
+ throw dubbingStartError(failure, { target: elevenLabsLangCode, source: elevenLabsSourceLangCode }, { assetId, ...mayHaveCreated && { mayHaveCreated } });
11085
11233
  }
11086
11234
  dubbingId = created.projectId;
11087
11235
  languageId = created.languageId;
@@ -11104,14 +11252,17 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11104
11252
  credentials
11105
11253
  });
11106
11254
  } catch (error) {
11107
- legacyWrapError(error, "Failed to check dubbing status");
11255
+ wrapError(error, "Failed to check dubbing status", { provider: "elevenlabs", dubbingId });
11108
11256
  }
11109
11257
  if (statusResult.kind === "failed") {
11110
11258
  const { failure } = statusResult;
11111
11259
  consecutiveStatusCheckFailures++;
11112
11260
  console.warn(`Status check for ElevenLabs dubbing project ${dubbingId} failed: ${failure.detail}`);
11113
11261
  if (!failure.retryable || consecutiveStatusCheckFailures >= MAX_CONSECUTIVE_STATUS_CHECK_FAILURES) {
11114
- throw dubbingProviderError("Could not check audio dubbing progress.", failure);
11262
+ throw dubbingProviderError("Could not check audio dubbing progress.", "elevenlabs_get_dubbing_project", failure, {
11263
+ dubbingId,
11264
+ consecutiveFailures: consecutiveStatusCheckFailures
11265
+ });
11115
11266
  }
11116
11267
  continue;
11117
11268
  }
@@ -11120,17 +11271,51 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11120
11271
  dubbingError = statusResult.error;
11121
11272
  if (dubbingStatus === "failed") {
11122
11273
  console.warn(`\u274C ElevenLabs dubbing project ${dubbingId} (language ${languageId}) failed: ${dubbingError ? `${dubbingError.code}: ${dubbingError.message}` : "no error reported"}`);
11274
+ const facts = { call: "elevenlabs_get_dubbing_project", provider: "elevenlabs", dubbingId, languageId };
11123
11275
  if (!dubbingError) {
11124
- throw new LegacyMuxAiError("Audio dubbing failed.", { type: "processing_error" });
11276
+ throw new MuxAiError("Audio dubbing failed.", {
11277
+ code: MUX_AI_ERROR_CODES.DUBBING_FAILED,
11278
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
11279
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
11280
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
11281
+ facts,
11282
+ // No reason was given, so a resubmit isn't known to help.
11283
+ retryable: false
11284
+ });
11125
11285
  }
11126
- throw new LegacyMuxAiError(
11286
+ throw new MuxAiError(
11127
11287
  `Audio dubbing failed: ${dubbingError.message}${dubbingError.retryable ? " Please try again." : ""}`,
11128
- { type: "processing_error", retryable: dubbingError.retryable }
11288
+ {
11289
+ code: MUX_AI_ERROR_CODES.DUBBING_FAILED,
11290
+ type: MUX_AI_ERROR_TYPES.PROCESSING_ERROR,
11291
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
11292
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
11293
+ // ElevenLabs documents `message` as display text.
11294
+ facts: { ...facts, providerCode: dubbingError.code, providerError: errorDetailFact(dubbingError.message) },
11295
+ // ElevenLabs says whether a new attempt may succeed.
11296
+ retryable: dubbingError.retryable
11297
+ }
11129
11298
  );
11130
11299
  }
11131
11300
  }
11132
11301
  if (dubbingStatus !== "completed") {
11133
- throw new LegacyMuxAiError("Audio translation timed out or failed. Please try again.", { type: "timeout_error", retryable: true });
11302
+ throw new MuxAiError("Audio translation timed out. Please try again.", {
11303
+ code: MUX_AI_ERROR_CODES.DUBBING_TIMEOUT,
11304
+ type: MUX_AI_ERROR_TYPES.TIMEOUT_ERROR,
11305
+ source: MUX_AI_ERROR_SOURCES.UPSTREAM,
11306
+ dependency: MUX_AI_ERROR_DEPENDENCIES.AI_PROVIDER,
11307
+ facts: {
11308
+ call: "elevenlabs_get_dubbing_project",
11309
+ provider: "elevenlabs",
11310
+ dubbingId,
11311
+ languageId,
11312
+ pollAttempts,
11313
+ timeoutSeconds: dubbingPollTimeoutSeconds,
11314
+ lastStatus: dubbingStatus
11315
+ },
11316
+ // Not transient: this already polled for the whole budget.
11317
+ transient: false
11318
+ });
11134
11319
  }
11135
11320
  console.warn("\u2705 Dubbing completed successfully!");
11136
11321
  if (uploadToS3) {
@@ -11151,7 +11336,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11151
11336
  credentials
11152
11337
  });
11153
11338
  } catch (error) {
11154
- legacyWrapError(error, "Failed to download and upload dubbed audio");
11339
+ wrapError(error, "Failed to download and upload dubbed audio", { dubbingId, languageId });
11155
11340
  }
11156
11341
  if (staged.kind === "staged") {
11157
11342
  presignedUrl = staged.presignedUrl;
@@ -11160,7 +11345,7 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11160
11345
  const { failure } = staged;
11161
11346
  console.warn(`Downloading dubbed audio for ElevenLabs dubbing project ${dubbingId} failed (attempt ${attempt}): ${failure.detail}`);
11162
11347
  if (!failure.retryable || attempt >= DUBBED_AUDIO_DOWNLOAD_ATTEMPTS) {
11163
- throw dubbingProviderError("Could not download the dubbed audio.", failure);
11348
+ throw dubbingProviderError("Could not download the dubbed audio.", "elevenlabs_get_dubbed_audio", failure, { dubbingId, languageId, attempts: attempt });
11164
11349
  }
11165
11350
  await sleep2(DUBBED_AUDIO_DOWNLOAD_RETRY_DELAY_MS);
11166
11351
  }
@@ -11175,16 +11360,32 @@ async function translateAudio(assetId, toLanguageCode, options = {}) {
11175
11360
  policy: replaceExistingTracks,
11176
11361
  presignedUrl,
11177
11362
  passthrough: trackPassthrough,
11178
- credentials
11363
+ credentials,
11364
+ classifiedErrors: true
11179
11365
  });
11180
11366
  } catch (error) {
11181
- legacyWrapError(error, `Failed to add dubbed audio track to Mux asset (dubbed audio is staged at: ${presignedUrl})`);
11182
- }
11183
- if (outcome.kind === "blocked") {
11184
- throw new LegacyMuxAiError(`${outcome.reason} Dubbed audio is staged at: ${presignedUrl}`, { type: "validation_error" });
11367
+ wrapError(error, "Failed to fetch the asset before adding the dubbed audio track", {
11368
+ assetId,
11369
+ ...stagedAudioFacts(presignedUrl, s3Bucket)
11370
+ });
11185
11371
  }
11186
- if (outcome.kind === "create_failed") {
11187
- throw new Error(`Failed to add dubbed audio track to Mux asset: ${outcome.reason}. Dubbed audio is staged at: ${presignedUrl}`);
11372
+ if (outcome.kind !== "created") {
11373
+ const facts = {
11374
+ assetId,
11375
+ trackType: "audio",
11376
+ languageCode: muxLangCode,
11377
+ trackName,
11378
+ dubbingId,
11379
+ ...outcome.deleted.length > 0 && { deletedTracks: trackSummaryFacts(outcome.deleted) },
11380
+ ...stagedAudioFacts(presignedUrl, s3Bucket)
11381
+ };
11382
+ if (outcome.kind === "blocked") {
11383
+ throw trackReplacementBlockedError(outcome, { message: `${outcome.reason} The dubbed audio is still staged in storage.`, facts });
11384
+ }
11385
+ const failure = trackWriteFailure(outcome);
11386
+ Object.assign(failure, { facts: { ...facts, ...failure.facts } });
11387
+ failure.message = `Failed to add dubbed audio track to Mux asset: ${failure.message}. The dubbed audio is still staged in storage.`;
11388
+ throw failure;
11188
11389
  }
11189
11390
  uploadedTrackId = outcome.trackId;
11190
11391
  replacedTracks = outcome.deleted;