med-scribe-alliance-ts-sdk 2.0.52 → 2.0.53

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 CHANGED
@@ -198,7 +198,7 @@ await client.reset(); // stops recording if active, clears all state and caches
198
198
  - **`cancelSession()` does NOT trigger processing.** It stops the recorder locally, cleans up state, and tells the server the session is cancelled. No `endSession` call is made to the backend.
199
199
  - **All async methods return `SDKResult<T>`, never throw.** Always check `result.success` before accessing `result.data`. Errors are in `result.error`.
200
200
  - **The SDK validates inputs against the discovery document.** If the server doesn't support an upload type, language, or model you requested, you'll get a `ValidationError` before the API call is made.
201
- - **Audio uploads go to a server-selected storage backend.** The create-session response decides it: `storage_provider: "aws"` with an `upload_url` object means a direct S3 presigned POST; an `upload_url` string means the audio is posted to the backend endpoint instead. Discovery's `capabilities.storage_providers` only advertises which backends the deployment can mint URLs for.
201
+ - **Audio uploads go to a server-selected storage backend.** Discovery's `capabilities.storage_provider` (default `aws`) decides the backend; uploads go directly to it (e.g. S3 presigned POST).
202
202
 
203
203
  - **SharedWorker is optional.** If you provide `workerScriptUrl`, the SDK offloads MP3 compression and upload to a SharedWorker. If the worker fails to load, it silently falls back to main-thread processing.
204
204
  - **Microphone permission is requested on `startRecording()`.** The browser will prompt the user for mic access. If denied, you'll get an error via `onError` callback.
@@ -390,7 +390,7 @@ interface RecordingOptions {
390
390
  | `isRecordingPaused()` | `boolean` | Whether the active recording is paused. |
391
391
  | `retryFailedUploads()` | `SDKResult<RetryUploadResult>` | Retry uploads that failed during the last recording. |
392
392
  | `hasFailedUploads()` | `boolean` | Whether there are retryable failed uploads. |
393
- | `uploadAudioFile(file, fileName, upload, options?)` | `SDKResult<UploadAudioFileResult>` | Upload one pre-recorded audio file using a session's `upload_url` (string or presigned object). No mic/recorder. The provider is taken from the session's `storage_provider`, or inferred from the payload shape; `options.storageProvider` overrides both. |
393
+ | `uploadAudioFile(file, fileName, upload)` | `SDKResult<UploadAudioFileResult>` | Upload one pre-recorded audio file to storage using a session's `upload_url`. No mic/recorder. |
394
394
 
395
395
  ### Session
396
396
 
@@ -628,7 +628,7 @@ console.log(result.data.session_id);
628
628
  | `TransportError` | — | Network / IPC failure |
629
629
  | `WorkerError` | — | SharedWorker failure |
630
630
  | `UploadError` | — | Audio upload failure (failed transfer, or malformed `upload_url` payload). Has `failedFiles: string[]`. |
631
- | `UnsupportedStorageProviderError` | — | The session's `storage_provider` names a backend this SDK build has no wrapper for. Thrown at `startRecording`. Has `provider: string`. |
631
+ | `UnsupportedStorageProviderError` | — | Discovery advertised a `storage_provider` this SDK build has no wrapper for. Thrown at `startRecording`. Has `provider: string`. |
632
632
 
633
633
  ## SharedWorker Support
634
634
 
package/dist/index.d.ts CHANGED
@@ -208,8 +208,6 @@ export interface TransportRequest {
208
208
  isUpload?: boolean;
209
209
  uploadBlob?: Blob;
210
210
  uploadFileName?: string;
211
- /** Body shape for an upload, from PreparedUpload.bodyMode. Falls back to the form-fields check. */
212
- uploadBodyMode?: "multipart" | "binary";
213
211
  /** Multipart form fields; when set, the request is multipart/form-data with uploadBlob as the file. */
214
212
  uploadFormFields?: Record<string, string>;
215
213
  /** Multipart field name for the file part. Defaults to 'file'. */
@@ -355,6 +353,7 @@ export interface ResolvedConfig {
355
353
  supportedAudioFormats: string[];
356
354
  supportedUploadMethods: string[];
357
355
  storageProviders: string[];
356
+ storageProvider: string;
358
357
  maxChunkDurationSeconds: number;
359
358
  /** modelId -> max session duration in seconds */
360
359
  maxSessionDurationSeconds: Map<string, number>;
@@ -1255,7 +1254,9 @@ export declare class RecordingManager {
1255
1254
  * Create the appropriate recorder based on upload type.
1256
1255
  */
1257
1256
  private createRecorder;
1257
+ /** Storage provider name from discovery; defaults to 'aws'. */
1258
1258
  private getStorageProviderName;
1259
+ /** Validate the provider has a wrapper (throws UnsupportedStorageProviderError) and return its name. */
1259
1260
  private resolveStorageProviderName;
1260
1261
  /**
1261
1262
  * Build upload headers from the current auth state.
package/dist/index.mjs CHANGED
@@ -383,13 +383,8 @@ function M() {
383
383
  }
384
384
  }
385
385
  //#endregion
386
- //#region src/transport/upload-body.ts
387
- function N(e) {
388
- return e.uploadBodyMode ? e.uploadBodyMode === "multipart" : !!e.uploadFormFields;
389
- }
390
- //#endregion
391
386
  //#region src/transport/http-transport.ts
392
- var P = class {
387
+ var N = class {
393
388
  constructor(e) {
394
389
  this.tokenRefreshPromise = null, this.accessToken = e.accessToken, this.flavour = e.flavour, this.debug = e.debug ?? !1, this.onUnauthorized = e.onUnauthorized;
395
390
  }
@@ -448,7 +443,7 @@ var P = class {
448
443
  }
449
444
  buildHeaders(e) {
450
445
  let t = {}, n = e.isUpload === !0 && e.attachAuth === !1;
451
- if (e.isUpload ? N(e) || (t["Content-Type"] = "audio/mp3") : (t["Content-Type"] = "application/json", t.Accept = "application/json"), !n) {
446
+ if (e.isUpload ? e.uploadFormFields || (t["Content-Type"] = "audio/mp3") : (t["Content-Type"] = "application/json", t.Accept = "application/json"), !n) {
452
447
  this.accessToken && (t.Authorization = `Bearer ${this.accessToken}`), this.flavour && (t.flavour = this.flavour);
453
448
  let e = M();
454
449
  e && (t[j] = e);
@@ -461,9 +456,9 @@ var P = class {
461
456
  headers: t,
462
457
  credentials: n ? "omit" : "include"
463
458
  };
464
- if (e.isUpload && N(e)) {
459
+ if (e.isUpload && e.uploadFormFields) {
465
460
  let t = new FormData();
466
- for (let [n, r] of Object.entries(e.uploadFormFields ?? {})) t.append(n, r);
461
+ for (let [n, r] of Object.entries(e.uploadFormFields)) t.append(n, r);
467
462
  e.uploadBlob && t.append(e.uploadFileFieldName ?? "file", e.uploadBlob, e.uploadFileName), r.body = t;
468
463
  } else e.isUpload && e.uploadBlob ? r.body = e.uploadBlob : e.body !== void 0 && (r.body = JSON.stringify(e.body));
469
464
  return r;
@@ -516,7 +511,7 @@ var P = class {
516
511
  }
517
512
  };
518
513
  }
519
- }, F = class {
514
+ }, P = class {
520
515
  constructor(e) {
521
516
  this.pendingRequests = /* @__PURE__ */ new Map(), this.correlationCounter = 0, this.tokenRefreshPromise = null, this.bridge = e.bridge, this.accessToken = e.accessToken, this.flavour = e.flavour, this.debug = e.debug ?? !1, this.onUnauthorized = e.onUnauthorized, this.bridge.onResponse((e) => {
522
517
  this.handleResponse(e);
@@ -583,7 +578,7 @@ var P = class {
583
578
  }
584
579
  buildHeaders(e) {
585
580
  let t = {}, n = e.isUpload === !0 && e.attachAuth === !1;
586
- if (e.isUpload ? N(e) || (t["Content-Type"] = "audio/mp3") : (t["Content-Type"] = "application/json", t.Accept = "application/json"), !n) {
581
+ if (e.isUpload ? e.uploadFormFields || (t["Content-Type"] = "audio/mp3") : (t["Content-Type"] = "application/json", t.Accept = "application/json"), !n) {
587
582
  this.accessToken && (t.Authorization = `Bearer ${this.accessToken}`), this.flavour && (t.flavour = this.flavour);
588
583
  let e = M();
589
584
  e && (t[j] = e);
@@ -599,7 +594,7 @@ var P = class {
599
594
  };
600
595
  if (t.isUpload && t.uploadBlob) {
601
596
  let e = await t.uploadBlob.arrayBuffer(), n = new Uint8Array(e);
602
- r.blobData = this.uint8ArrayToBase64(n), N(t) && (r.uploadFormFields = t.uploadFormFields ?? {}, r.uploadFileFieldName = t.uploadFileFieldName ?? "file", r.uploadFileName = t.uploadFileName);
597
+ r.blobData = this.uint8ArrayToBase64(n), t.uploadFormFields && (r.uploadFormFields = t.uploadFormFields, r.uploadFileFieldName = t.uploadFileFieldName ?? "file", r.uploadFileName = t.uploadFileName);
603
598
  } else t.body !== void 0 && (r.body = t.body);
604
599
  return r;
605
600
  }
@@ -673,25 +668,15 @@ var P = class {
673
668
  destroy() {
674
669
  for (let [e, t] of this.pendingRequests) t.reject(new T("IPC transport destroyed")), this.pendingRequests.delete(e);
675
670
  }
676
- }, ve = "aws", I = "backend";
677
- function L(e) {
678
- return typeof e == "string" ? e.trim().length > 0 : typeof e == "object" && !!e;
679
- }
680
- function R(e, t) {
681
- return (typeof e == "string" ? e.trim().toLowerCase() : "") || (typeof t == "string" ? I : "aws");
682
- }
683
- //#endregion
684
- //#region src/discovery/resolved-config.ts
685
- var ye = ["aws"];
686
- function be(e) {
671
+ }, F = "aws";
672
+ function ve(e) {
687
673
  let t = (e.storage_providers ?? []).filter((e) => typeof e == "string").map((e) => e.trim().toLowerCase()).filter((e) => e.length > 0);
688
- return t.length > 0 ? Array.from(new Set(t)) : [...ye];
674
+ return t.length > 0 ? Array.from(new Set(t)) : [F];
689
675
  }
690
- function xe(e) {
676
+ function ye(e) {
691
677
  try {
692
678
  let t = /* @__PURE__ */ new Map(), n = e.models ?? [];
693
679
  for (let e of n) e.id && typeof e.max_session_duration_seconds == "number" && t.set(e.id, e.max_session_duration_seconds);
694
- let r = be(e.capabilities);
695
680
  return {
696
681
  baseUrl: e.endpoints.base_url,
697
682
  webhooksUrl: e.endpoints.webhooks_url,
@@ -699,7 +684,8 @@ function xe(e) {
699
684
  autoDetectLanguage: e.languages?.auto_detection ?? !1,
700
685
  supportedAudioFormats: e.capabilities.audio_formats,
701
686
  supportedUploadMethods: e.capabilities.upload_methods ?? [],
702
- storageProviders: r,
687
+ storageProviders: ve(e.capabilities),
688
+ storageProvider: F,
703
689
  maxChunkDurationSeconds: e.capabilities.max_chunk_duration_seconds,
704
690
  maxSessionDurationSeconds: t,
705
691
  supportedAuthMethods: e.authentication.supported_methods,
@@ -713,7 +699,7 @@ function xe(e) {
713
699
  }
714
700
  //#endregion
715
701
  //#region src/discovery/discovery-manager.ts
716
- var z = class {
702
+ var I = class {
717
703
  constructor(e, t, n = !1) {
718
704
  this.cachedDocument = null, this.resolvedConfig = null, this.cacheTimestamp = 0, this.cacheTtlMs = i, this.transport = e, this.validator = t, this.debug = n;
719
705
  }
@@ -730,7 +716,7 @@ var z = class {
730
716
  url: n
731
717
  });
732
718
  this.validator.validateDiscoveryResponse(i.data);
733
- let a = i.data, o = xe(a);
719
+ let a = i.data, o = ye(a);
734
720
  return this.cachedDocument = a, this.resolvedConfig = o, this.cacheTimestamp = Date.now(), this.debug && console.log("[ScribeSDK] Discovery complete:", a.service?.name ?? a.protocol), {
735
721
  data: o,
736
722
  httpStatus: i.status
@@ -783,7 +769,7 @@ var z = class {
783
769
  isCacheValid() {
784
770
  return Date.now() - this.cacheTimestamp < this.cacheTtlMs;
785
771
  }
786
- }, B = class {
772
+ }, L = class {
787
773
  constructor(e, t, n = !1) {
788
774
  this.currentSession = null, this.transport = e, this.validator = t, this.debug = n;
789
775
  }
@@ -951,13 +937,13 @@ var z = class {
951
937
  }, { once: !0 });
952
938
  }) : this.sleep(e);
953
939
  }
954
- }, V = 1024, H = 16e3;
955
- V / H, H / V;
956
- var Se = {
940
+ }, R = 1024, z = 16e3;
941
+ R / z, z / R;
942
+ var be = {
957
943
  m4a: "audio/m4a",
958
944
  wav: "audio/wav",
959
945
  mp3: "audio/mpeg"
960
- }, Ce = class {
946
+ }, xe = class {
961
947
  constructor(e, t) {
962
948
  this.vadPast = [], this.lastClipIndex = 0, this.silDurationAcc = 0, this.micVad = null, this.micStream = null, this.isLoading = !0, this.isRecording = !1, this.noSpeechStartTime = null, this.lastWarningTime = null;
963
949
  let n = e.samplingRate;
@@ -1089,7 +1075,7 @@ var Se = {
1089
1075
  } catch {}
1090
1076
  this.micStream = null;
1091
1077
  }
1092
- }, we = class {
1078
+ }, Se = class {
1093
1079
  constructor(e, t) {
1094
1080
  this.currentSampleLength = 0, this.currentFrameLength = 0, this.samplingRate = e, this.incrementalAllocationSize = Math.floor(e * t), this.buffer = new Float32Array(this.incrementalAllocationSize);
1095
1081
  }
@@ -1139,7 +1125,7 @@ var Se = {
1139
1125
  formatTimestamp(e) {
1140
1126
  return `${Math.floor(e / 60).toString().padStart(2, "0")}:${(e % 60).toFixed(6).padStart(9, "0")}`;
1141
1127
  }
1142
- }, Te = class {
1128
+ }, Ce = class {
1143
1129
  constructor() {
1144
1130
  this.chunks = [], this.successfulUploads = [], this.totalRawSamples = 0, this.totalRawFrames = 0, this.totalInsertedSamples = 0, this.totalInsertedFrames = 0;
1145
1131
  }
@@ -1238,7 +1224,7 @@ var Se = {
1238
1224
  };
1239
1225
  //#endregion
1240
1226
  //#region src/audio/mp3-encoder.ts
1241
- function Ee(e, t = H, r = 128) {
1227
+ function we(e, t = z, r = 128) {
1242
1228
  try {
1243
1229
  let i = new n.Mp3Encoder(1, t, r), a = new Int16Array(e.length);
1244
1230
  for (let t = 0; t < e.length; t++) {
@@ -1249,7 +1235,7 @@ function Ee(e, t = H, r = 128) {
1249
1235
  s && s.length > 0 && o.push(s);
1250
1236
  let c = i.flush();
1251
1237
  return c && c.length > 0 && o.push(c), o.length === 0 ? null : {
1252
- blob: new Blob(o, { type: Se.mp3 }),
1238
+ blob: new Blob(o, { type: be.mp3 }),
1253
1239
  chunks: o
1254
1240
  };
1255
1241
  } catch (e) {
@@ -1258,25 +1244,25 @@ function Ee(e, t = H, r = 128) {
1258
1244
  }
1259
1245
  //#endregion
1260
1246
  //#region src/storage/aws-s3-provider.ts
1261
- var De = e.object({
1247
+ var Te = e.object({
1262
1248
  uploadData: e.object({
1263
1249
  url: e.string().min(1, "uploadData.url is required"),
1264
1250
  fields: e.record(e.string(), e.string())
1265
1251
  }),
1266
1252
  folderPath: e.string().optional(),
1267
1253
  txn_id: e.string().optional()
1268
- }), Oe = "key", ke = "${filename}", U = "Content-Type", Ae = "audio/mp3", W = class {
1254
+ }), Ee = "key", De = "${filename}", B = "Content-Type", Oe = "audio/mp3", V = class {
1269
1255
  constructor() {
1270
1256
  this.name = "aws";
1271
1257
  }
1272
1258
  prepareUpload({ fileName: e, blob: t, upload: n }) {
1273
- let r = De.safeParse(n);
1259
+ let r = Te.safeParse(n);
1274
1260
  if (!r.success) throw new E(`Invalid AWS upload payload in session response: ${r.error.message}`, [e]);
1275
1261
  let { uploadData: i } = r.data, a = {};
1276
- for (let [t, n] of Object.entries(i.fields)) a[t] = t === Oe ? n.split(ke).join(e) : n;
1277
- if (!(U in a)) {
1262
+ for (let [t, n] of Object.entries(i.fields)) a[t] = t === Ee ? n.split(De).join(e) : n;
1263
+ if (!(B in a)) {
1278
1264
  let e = t?.type;
1279
- a[U] = e && e.startsWith("audio/") ? e : Ae;
1265
+ a[B] = e && e.startsWith("audio/") ? e : Oe;
1280
1266
  }
1281
1267
  return {
1282
1268
  url: i.url,
@@ -1288,7 +1274,7 @@ var De = e.object({
1288
1274
  attachAuth: !1
1289
1275
  };
1290
1276
  }
1291
- }, je = e.string().trim().min(1, "upload_url is required"), Me = "Content-Type", Ne = "audio/mp3", Pe = new Set([
1277
+ }, ke = e.string().trim().min(1, "upload_url is required"), Ae = "Content-Type", je = "audio/mp3", Me = new Set([
1292
1278
  "audio/webm;codecs=opus",
1293
1279
  "audio/wav",
1294
1280
  "audio/ogg",
@@ -1296,7 +1282,7 @@ var De = e.object({
1296
1282
  "audio/mp4",
1297
1283
  "audio/m4a",
1298
1284
  "audio/mp3"
1299
- ]), Fe = {
1285
+ ]), Ne = {
1300
1286
  mp3: "audio/mp3",
1301
1287
  webm: "audio/webm;codecs=opus",
1302
1288
  wav: "audio/wav",
@@ -1304,46 +1290,46 @@ var De = e.object({
1304
1290
  m4a: "audio/m4a",
1305
1291
  mp4: "audio/mp4"
1306
1292
  };
1307
- function Ie(e, t) {
1308
- let n = Fe[e.split(".").pop()?.toLowerCase() ?? ""];
1293
+ function Pe(e, t) {
1294
+ let n = Ne[e.split(".").pop()?.toLowerCase() ?? ""];
1309
1295
  if (n) return n;
1310
1296
  let r = t?.type;
1311
- return r && Pe.has(r) ? r : Ne;
1297
+ return r && Me.has(r) ? r : je;
1312
1298
  }
1313
- var G = class {
1299
+ var H = class {
1314
1300
  constructor() {
1315
1301
  this.name = "backend";
1316
1302
  }
1317
1303
  prepareUpload({ fileName: e, blob: t, upload: n }) {
1318
- let r = je.safeParse(n);
1304
+ let r = ke.safeParse(n);
1319
1305
  if (!r.success) throw new E(`Invalid backend upload payload: expected an upload_url string, got ${typeof n}`, [e]);
1320
1306
  return {
1321
1307
  url: `${r.data.replace(/\/+$/, "")}/${encodeURIComponent(e)}`,
1322
1308
  method: "POST",
1323
1309
  bodyMode: "binary",
1324
- headers: { [Me]: Ie(e, t) },
1310
+ headers: { [Ae]: Pe(e, t) },
1325
1311
  attachAuth: !0
1326
1312
  };
1327
1313
  }
1328
- }, K = {
1329
- aws: () => new W(),
1330
- backend: () => new G()
1314
+ }, U = {
1315
+ aws: () => new V(),
1316
+ backend: () => new H()
1331
1317
  };
1332
- function q(e) {
1318
+ function W(e) {
1333
1319
  return typeof e == "string" ? e.trim().toLowerCase() : "";
1334
1320
  }
1335
- function Le(e) {
1336
- return q(e) in K;
1321
+ function Fe(e) {
1322
+ return W(e) in U;
1337
1323
  }
1338
- function J(e) {
1339
- let t = K[q(e)];
1324
+ function G(e) {
1325
+ let t = U[W(e)];
1340
1326
  if (!t) throw new D(e);
1341
1327
  return t();
1342
1328
  }
1343
1329
  //#endregion
1344
1330
  //#region src/storage/upload-file.ts
1345
- async function Y(e, t) {
1346
- let n = J(t.storageProvider).prepareUpload({
1331
+ async function K(e, t) {
1332
+ let n = G(t.storageProvider).prepareUpload({
1347
1333
  fileName: t.fileName,
1348
1334
  blob: t.blob,
1349
1335
  upload: t.upload
@@ -1353,7 +1339,6 @@ async function Y(e, t) {
1353
1339
  url: n.url,
1354
1340
  headers: n.headers,
1355
1341
  isUpload: !0,
1356
- uploadBodyMode: n.bodyMode,
1357
1342
  uploadBlob: t.blob,
1358
1343
  uploadFormFields: n.formFields,
1359
1344
  uploadFileFieldName: n.fileFieldName,
@@ -1364,7 +1349,7 @@ async function Y(e, t) {
1364
1349
  }
1365
1350
  //#endregion
1366
1351
  //#region src/worker/worker-manager.ts
1367
- var Re = class {
1352
+ var Ie = class {
1368
1353
  constructor(e, t, n, r) {
1369
1354
  if (this.worker = null, this.port = null, this.useWorker = !1, this.uploadPayload = {}, this.storageProviderName = "", this.uploadHeaders = {}, this.refreshUploadUrl = null, this.inFlightRefresh = null, this.pendingUploads = /* @__PURE__ */ new Set(), this.allUploadsResolver = null, this.callbackRegistry = e, this.fileManager = t, this.transport = n, !r?.forceMainThread && typeof SharedWorker < "u" && r?.workerScriptUrl) try {
1370
1355
  this.worker = new SharedWorker(r.workerScriptUrl, { name: "scribe-sdk-worker" }), this.port = this.worker.port, this.port.onmessage = (e) => {
@@ -1375,10 +1360,10 @@ var Re = class {
1375
1360
  }
1376
1361
  }
1377
1362
  setUploadConfig(e, t, n, r) {
1378
- this.uploadPayload = e, this.storageProviderName = t, this.uploadHeaders = n, this.refreshUploadUrl = r ?? null, J(t);
1363
+ this.uploadPayload = e, this.storageProviderName = t, this.uploadHeaders = n, this.refreshUploadUrl = r ?? null, G(t);
1379
1364
  }
1380
1365
  compressAndUpload(e, t, n) {
1381
- let r = e.length / H;
1366
+ let r = e.length / z;
1382
1367
  if (r > 27) {
1383
1368
  this.fileManager.markFailure(n, new Blob(), `Chunk exceeds maximum length: ${r.toFixed(1)}s > 25s`), this.callbackRegistry.dispatch("onError", {
1384
1369
  type: m.VALIDATION_ERROR,
@@ -1516,7 +1501,7 @@ var Re = class {
1516
1501
  async doMainThreadUpload(e, t, n) {
1517
1502
  let r = null;
1518
1503
  try {
1519
- let i = Ee(e);
1504
+ let i = we(e);
1520
1505
  if (!i) {
1521
1506
  this.fileManager.markFailure(n, new Blob(), "MP3 encoding failed"), this.callbackRegistry.dispatch("onUploadEvent", {
1522
1507
  type: f.FAILED,
@@ -1538,7 +1523,7 @@ var Re = class {
1538
1523
  }
1539
1524
  });
1540
1525
  try {
1541
- await Y(this.transport, {
1526
+ await K(this.transport, {
1542
1527
  fileName: t,
1543
1528
  blob: r,
1544
1529
  upload: this.uploadPayload,
@@ -1547,7 +1532,7 @@ var Re = class {
1547
1532
  } catch (e) {
1548
1533
  let n = await this.refreshUploadPayload();
1549
1534
  if (!n) throw e;
1550
- await Y(this.transport, {
1535
+ await K(this.transport, {
1551
1536
  fileName: t,
1552
1537
  blob: r,
1553
1538
  upload: n,
@@ -1580,9 +1565,9 @@ var Re = class {
1580
1565
  }
1581
1566
  });
1582
1567
  }
1583
- }, X = class {
1568
+ }, q = class {
1584
1569
  constructor(e, t, n, r) {
1585
- this._isPaused = !1, this.initialized = !1, this.chunkLimitReached = !1, this.chunkLimitOverridden = !1, this.callbackRegistry = e, this.bufferManager = new we(H, 25), this.fileManager = new Te();
1570
+ this._isPaused = !1, this.initialized = !1, this.chunkLimitReached = !1, this.chunkLimitOverridden = !1, this.callbackRegistry = e, this.bufferManager = new Se(z, 25), this.fileManager = new Ce();
1586
1571
  let i = {
1587
1572
  prefChunkLength: n?.prefChunkLength ?? 10,
1588
1573
  despChunkLength: n?.despChunkLength ?? 20,
@@ -1593,10 +1578,10 @@ var Re = class {
1593
1578
  shortSilenceThreshold: n?.shortSilenceThreshold,
1594
1579
  longSilenceThreshold: n?.longSilenceThreshold
1595
1580
  };
1596
- this.vadClient = new Ce(i, e), this.workerManager = new Re(e, this.fileManager, t, r), this.wireVadCallbacks();
1581
+ this.vadClient = new xe(i, e), this.workerManager = new Ie(e, this.fileManager, t, r), this.wireVadCallbacks();
1597
1582
  }
1598
1583
  initialize(e, t) {
1599
- if (!t.upload || typeof t.upload != "object") throw Error("Chunked recording requires a presigned upload payload object, not a URL string.");
1584
+ if (!t.upload || typeof t.upload != "object") throw Error("Upload payload is required for chunked recording");
1600
1585
  if (!t.storageProvider) throw Error("Storage provider is required for chunked recording");
1601
1586
  this.workerManager.setUploadConfig(t.upload, t.storageProvider, t.uploadHeaders, t.refreshUploadUrl), this.initialized = !0;
1602
1587
  }
@@ -1696,14 +1681,14 @@ var Re = class {
1696
1681
  flushRemainingAudio() {
1697
1682
  this.bufferManager.getCurrentSampleLength() > 0 && this.handleClipPoint();
1698
1683
  }
1699
- }, Z = class {
1684
+ }, J = class {
1700
1685
  constructor(e, t) {
1701
1686
  this.mediaRecorder = null, this.audioChunks = [], this.micStream = null, this._isPaused = !1, this.uploadPayload = {}, this.storageProviderName = "", this.failedUploadData = null, this.callbackRegistry = e, this.transport = t;
1702
1687
  }
1703
1688
  initialize(e, t) {
1704
- if (!L(t.upload)) throw Error("Upload payload is required for single recording");
1689
+ if (!t.upload || typeof t.upload != "object") throw Error("Upload payload is required for single recording");
1705
1690
  if (!t.storageProvider) throw Error("Storage provider is required for single recording");
1706
- this.uploadPayload = t.upload, this.storageProviderName = t.storageProvider, J(t.storageProvider), this.failedUploadData = null;
1691
+ this.uploadPayload = t.upload, this.storageProviderName = t.storageProvider, G(t.storageProvider), this.failedUploadData = null;
1707
1692
  }
1708
1693
  async start(e) {
1709
1694
  try {
@@ -1749,7 +1734,7 @@ var Re = class {
1749
1734
  }
1750
1735
  let t = `1.${this.getFileExtension()}`;
1751
1736
  try {
1752
- return await Y(this.transport, {
1737
+ return await K(this.transport, {
1753
1738
  fileName: t,
1754
1739
  blob: e,
1755
1740
  upload: this.uploadPayload,
@@ -1831,7 +1816,7 @@ var Re = class {
1831
1816
  let e = this.mediaRecorder?.mimeType || "";
1832
1817
  return e.includes("mp4") ? "mp4" : e.includes("ogg") ? "ogg" : "webm";
1833
1818
  }
1834
- }, Q = class {
1819
+ }, Y = class {
1835
1820
  constructor(e, t, n, r, i) {
1836
1821
  this.recorder = null, this.activeSession = null, this.activeBaseUrl = "", this.activeUploadUrlRefresher = null, this._isRecording = !1, this._isStarting = !1, this._startGeneration = 0, this.retryContext = null, this.callbackRegistry = e, this.sessionManager = t, this.discoveryManager = n, this.transport = r, this.config = i ?? {};
1837
1822
  }
@@ -1864,7 +1849,7 @@ var Re = class {
1864
1849
  this.activeSession = a;
1865
1850
  let c;
1866
1851
  try {
1867
- c = this.resolveStorageProviderName(a);
1852
+ c = this.resolveStorageProviderName();
1868
1853
  } catch (e) {
1869
1854
  throw r === this._startGeneration && (this.cleanupRecordingState(), this.dispatchStartError(m.VALIDATION_ERROR, g.UNSUPPORTED_STORAGE_PROVIDER, e)), e;
1870
1855
  }
@@ -1891,7 +1876,7 @@ var Re = class {
1891
1876
  } catch {}
1892
1877
  throw r === this._startGeneration && (this.cleanupRecordingState(), this.dispatchStartError(m.VALIDATION_ERROR, g.RECORDER_INIT_FAILED, e)), e;
1893
1878
  }
1894
- l instanceof X && this.applyDiscoveryOverrides(l);
1879
+ l instanceof q && this.applyDiscoveryOverrides(l);
1895
1880
  try {
1896
1881
  await l.start(t.deviceId);
1897
1882
  } catch (e) {
@@ -1927,7 +1912,7 @@ var Re = class {
1927
1912
  try {
1928
1913
  let o;
1929
1914
  try {
1930
- o = this.resolveStorageProviderName(t);
1915
+ o = this.resolveStorageProviderName();
1931
1916
  } catch (e) {
1932
1917
  throw i === this._startGeneration && (this.cleanupRecordingState(), this.dispatchStartError(m.VALIDATION_ERROR, g.UNSUPPORTED_STORAGE_PROVIDER, e)), e;
1933
1918
  }
@@ -1949,7 +1934,7 @@ var Re = class {
1949
1934
  } catch {}
1950
1935
  throw i === this._startGeneration && (this.cleanupRecordingState(), this.dispatchStartError(m.VALIDATION_ERROR, g.RECORDER_INIT_FAILED, e)), e;
1951
1936
  }
1952
- s instanceof X && this.applyDiscoveryOverrides(s);
1937
+ s instanceof q && this.applyDiscoveryOverrides(s);
1953
1938
  try {
1954
1939
  await s.start(n?.deviceId);
1955
1940
  } catch (e) {
@@ -2080,10 +2065,10 @@ var Re = class {
2080
2065
  }
2081
2066
  }
2082
2067
  forceAllowMoreChunks() {
2083
- this.recorder && this.recorder instanceof X && this.recorder.forceAllowMoreChunks();
2068
+ this.recorder && this.recorder instanceof q && this.recorder.forceAllowMoreChunks();
2084
2069
  }
2085
2070
  updateAuthToken(e) {
2086
- this.recorder && this.recorder instanceof X && this.recorder.updateAuthToken(e), this.transport.setAuthToken(e);
2071
+ this.recorder && this.recorder instanceof q && this.recorder.updateAuthToken(e), this.transport.setAuthToken(e);
2087
2072
  }
2088
2073
  reset() {
2089
2074
  ++this._startGeneration, this.recorder && this.recorder.reset(), this.retryContext = null, this.cleanupRecordingState();
@@ -2122,7 +2107,7 @@ var Re = class {
2122
2107
  }
2123
2108
  this.config.debug && console.log(`[ScribeSDK] Retrying ${n} failed uploads`);
2124
2109
  for (let o of t) try {
2125
- await Y(this.transport, {
2110
+ await K(this.transport, {
2126
2111
  fileName: o.fileName,
2127
2112
  blob: o.blob,
2128
2113
  upload: a,
@@ -2157,15 +2142,18 @@ var Re = class {
2157
2142
  };
2158
2143
  }
2159
2144
  createRecorder(e) {
2160
- return e === "single" ? new Z(this.callbackRegistry, this.transport) : new X(this.callbackRegistry, this.transport, void 0, this.config.workerConfig);
2145
+ return e === "single" ? new J(this.callbackRegistry, this.transport) : new q(this.callbackRegistry, this.transport, void 0, this.config.workerConfig);
2161
2146
  }
2162
- getStorageProviderName(e) {
2163
- let t = e ?? this.activeSession;
2164
- return R(t?.storage_provider, t?.upload_url);
2147
+ getStorageProviderName() {
2148
+ try {
2149
+ return this.discoveryManager.getResolvedConfig().storageProvider || "aws";
2150
+ } catch {
2151
+ return "aws";
2152
+ }
2165
2153
  }
2166
- resolveStorageProviderName(e) {
2167
- let t = this.getStorageProviderName(e);
2168
- return J(t), t;
2154
+ resolveStorageProviderName() {
2155
+ let e = this.getStorageProviderName();
2156
+ return G(e), e;
2169
2157
  }
2170
2158
  buildUploadHeaders(e) {
2171
2159
  let t = {};
@@ -2201,16 +2189,16 @@ var Re = class {
2201
2189
  return;
2202
2190
  }
2203
2191
  let e = [];
2204
- if (this.recorder instanceof X ? e = this.recorder.getFileManager().getFailedChunksWithBlobs().map((e) => ({
2192
+ if (this.recorder instanceof q ? e = this.recorder.getFileManager().getFailedChunksWithBlobs().map((e) => ({
2205
2193
  fileName: e.fileName,
2206
2194
  blob: e.fileBlob
2207
- })) : this.recorder instanceof Z && (e = this.recorder.getFailedBlobData()), e.length === 0) {
2195
+ })) : this.recorder instanceof J && (e = this.recorder.getFailedBlobData()), e.length === 0) {
2208
2196
  this.retryContext = null;
2209
2197
  return;
2210
2198
  }
2211
2199
  this.retryContext = {
2212
2200
  upload: this.activeSession.upload_url,
2213
- storageProvider: this.getStorageProviderName(this.activeSession),
2201
+ storageProvider: this.getStorageProviderName(),
2214
2202
  failedChunks: e
2215
2203
  }, this.config.debug && console.log(`[ScribeSDK] Preserved ${e.length} failed uploads for retry`);
2216
2204
  }
@@ -2220,14 +2208,23 @@ var Re = class {
2220
2208
  partialCleanupAfterFailedFinalize() {
2221
2209
  this.recorder = null, this._isRecording = !1, this._isStarting = !1;
2222
2210
  }
2223
- }, ze = class {
2211
+ }, Le = "aws", X = "backend";
2212
+ function Z(e) {
2213
+ return typeof e == "string" ? e.trim().length > 0 : typeof e == "object" && !!e;
2214
+ }
2215
+ function Q(e, t) {
2216
+ return (typeof e == "string" ? e.trim().toLowerCase() : "") || (typeof t == "string" ? X : "aws");
2217
+ }
2218
+ //#endregion
2219
+ //#region src/client.ts
2220
+ var Re = class {
2224
2221
  constructor(e) {
2225
2222
  this.isInitialized = !1, this.validateConfig(e), this.config = {
2226
2223
  debug: !1,
2227
2224
  autoDiscovery: !0,
2228
2225
  mode: l.DIRECT,
2229
2226
  ...e
2230
- }, this.callbackRegistry = new O(), this.validator = new k(), this.transport = this.createTransport(), this.discoveryManager = new z(this.transport, this.validator, this.config.debug), this.sessionManager = new B(this.transport, this.validator, this.config.debug), this.recordingManager = new Q(this.callbackRegistry, this.sessionManager, this.discoveryManager, this.transport, {
2227
+ }, this.callbackRegistry = new O(), this.validator = new k(), this.transport = this.createTransport(), this.discoveryManager = new I(this.transport, this.validator, this.config.debug), this.sessionManager = new L(this.transport, this.validator, this.config.debug), this.recordingManager = new Y(this.callbackRegistry, this.sessionManager, this.discoveryManager, this.transport, {
2231
2228
  debug: this.config.debug,
2232
2229
  flavour: this.config.flavour,
2233
2230
  workerConfig: this.resolveWorkerConfig()
@@ -2296,12 +2293,12 @@ var Re = class {
2296
2293
  return this.wrapResult(async () => {
2297
2294
  if (!e || e.size === 0) throw new y("A non-empty audio file is required");
2298
2295
  if (!t || !t.trim()) throw new y("fileName is required");
2299
- if (!L(n)) throw new y("upload (upload_url payload) is required");
2300
- let i = await Y(this.transport, {
2296
+ if (!Z(n)) throw new y("upload (upload_url payload) is required");
2297
+ let i = await K(this.transport, {
2301
2298
  fileName: t,
2302
2299
  blob: e,
2303
2300
  upload: n,
2304
- storageProvider: R(r?.storageProvider ?? this.providerForUpload(n), n)
2301
+ storageProvider: Q(r?.storageProvider ?? this.providerForUpload(n), n)
2305
2302
  });
2306
2303
  return {
2307
2304
  data: {
@@ -2424,7 +2421,7 @@ var Re = class {
2424
2421
  }) : Promise.resolve(void 0);
2425
2422
  if (this.config.mode === l.IPC) {
2426
2423
  if (!this.config.ipcTransport) throw new y("ipcTransport (IpcBridge) is required when mode is \"ipc\"");
2427
- return new F({
2424
+ return new P({
2428
2425
  bridge: this.config.ipcTransport,
2429
2426
  accessToken: this.config.accessToken,
2430
2427
  flavour: this.config.flavour,
@@ -2432,7 +2429,7 @@ var Re = class {
2432
2429
  onUnauthorized: e
2433
2430
  });
2434
2431
  }
2435
- return new P({
2432
+ return new N({
2436
2433
  accessToken: this.config.accessToken,
2437
2434
  flavour: this.config.flavour,
2438
2435
  debug: this.config.debug,
@@ -2461,7 +2458,7 @@ var Re = class {
2461
2458
  if (!e.baseUrl) throw new y("baseUrl is required");
2462
2459
  }
2463
2460
  }, $ = "worker.bundle.js";
2464
- function Be() {
2461
+ function ze() {
2465
2462
  if (typeof window < "u" && window.__MEDSCRIBE_WORKER_URL__) return window.__MEDSCRIBE_WORKER_URL__;
2466
2463
  if (typeof document < "u" && document.currentScript) {
2467
2464
  let e = document.currentScript.src;
@@ -2469,11 +2466,11 @@ function Be() {
2469
2466
  }
2470
2467
  return `/${$}`;
2471
2468
  }
2472
- async function Ve(e) {
2469
+ async function Be(e) {
2473
2470
  let t = e ?? `https://cdn.jsdelivr.net/npm/med-scribe-alliance-ts-sdk/dist/${$}`, n = await fetch(t);
2474
2471
  if (!n.ok) throw Error(`Failed to fetch worker script: ${n.status} ${n.statusText}`);
2475
2472
  let r = await n.text(), i = new Blob([r], { type: "application/javascript" });
2476
2473
  return URL.createObjectURL(i);
2477
2474
  }
2478
2475
  //#endregion
2479
- export { ve as AWS_STORAGE_PROVIDER, d as AudioEventType, x as AuthenticationError, W as AwsS3StorageProvider, I as BACKEND_STORAGE_PROVIDER, G as BackendStorageProvider, O as CallbackRegistry, c as CommunicationProtocol, h as DiscardReason, b as DiscoveryError, z as DiscoveryManager, g as ErrorCode, m as ErrorEventType, S as ForbiddenError, _ as HttpStatus, P as HttpTransport, F as IpcTransport, w as RateLimitError, Q as RecordingManager, u as RecordingState, ze as ScribeClient, v as ScribeError, p as SessionEventType, te as SessionExpiredError, B as SessionManager, C as SessionNotFoundError, a as SessionStatus, o as TemplateStatus, T as TransportError, l as TransportMode, D as UnsupportedStorageProviderError, E as UploadError, f as UploadEventType, s as UploadType, y as ValidationError, k as Validator, ne as WorkerError, Ve as createWorkerBlobUrl, J as getStorageProvider, Be as getWorkerUrl, L as hasUploadPayload, Le as isStorageProviderSupported, R as resolveStorageProvider };
2476
+ export { Le as AWS_STORAGE_PROVIDER, d as AudioEventType, x as AuthenticationError, V as AwsS3StorageProvider, X as BACKEND_STORAGE_PROVIDER, H as BackendStorageProvider, O as CallbackRegistry, c as CommunicationProtocol, h as DiscardReason, b as DiscoveryError, I as DiscoveryManager, g as ErrorCode, m as ErrorEventType, S as ForbiddenError, _ as HttpStatus, N as HttpTransport, P as IpcTransport, w as RateLimitError, Y as RecordingManager, u as RecordingState, Re as ScribeClient, v as ScribeError, p as SessionEventType, te as SessionExpiredError, L as SessionManager, C as SessionNotFoundError, a as SessionStatus, o as TemplateStatus, T as TransportError, l as TransportMode, D as UnsupportedStorageProviderError, E as UploadError, f as UploadEventType, s as UploadType, y as ValidationError, k as Validator, ne as WorkerError, Be as createWorkerBlobUrl, G as getStorageProvider, ze as getWorkerUrl, Z as hasUploadPayload, Fe as isStorageProviderSupported, Q as resolveStorageProvider };
@@ -74,4 +74,4 @@ bitsperframe: %d
74
74
 
75
75
  `)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},a,o=pr,s=!er.jitless,c=s&&mr.value,l=t.catchall,u;e._zod.parse=(d,f)=>{u??=r.value;let p=d.value;return o(p)?s&&c&&f?.async===!1&&f.jitless!==!0?(a||=i(t.shape),d=a(d,f),l?Ca([],p,d,f,u,e):d):n(d,f):(d.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),d)}});function Ea(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Or(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Mr(e,r,tr())))}),t)}var Da=Y(`$ZodUnion`,(e,t)=>{Ui.init(e,t),X(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),X(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),X(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),X(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>or(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Ea(t,r,e,i)):Ea(o,r,e,i)}}),Oa=Y(`$ZodIntersection`,(e,t)=>{Ui.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Aa(e,t,n)):Aa(e,i,a)}});function ka(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(hr(e)&&hr(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=ka(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=ka(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Aa(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),Or(e))return e;let o=ka(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var ja=Y(`$ZodRecord`,(e,t)=>{Ui.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!hr(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[],o=t.keyType._zod.values;if(o){n.value={};let s=new Set;for(let c of o)if(typeof c==`string`||typeof c==`number`||typeof c==`symbol`){s.add(typeof c==`number`?c.toString():c);let o=t.keyType._zod.run({value:c,issues:[]},r);if(o instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(o.issues.length){n.issues.push({code:`invalid_key`,origin:`record`,issues:o.issues.map(e=>Mr(e,r,tr())),input:c,path:[c],inst:e});continue}let l=o.value,u=t.valueType._zod.run({value:i[c],issues:[]},r);u instanceof Promise?a.push(u.then(e=>{e.issues.length&&n.issues.push(...Ar(c,e.issues)),n.value[l]=e.value})):(u.issues.length&&n.issues.push(...Ar(c,u.issues)),n.value[l]=u.value)}let c;for(let e in i)s.has(e)||(c??=[],c.push(e));c&&c.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:c})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof o==`string`&&Ei.test(o)&&s.issues.length){let e=t.keyType._zod.run({value:Number(o),issues:[]},r);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(s=e)}if(s.issues.length){t.mode===`loose`?n.value[o]=i[o]:n.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Mr(e,r,tr())),input:o,path:[o],inst:e});continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...Ar(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...Ar(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),Ma=Y(`$ZodEnum`,(e,t)=>{Ui.init(e,t);let n=nr(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=RegExp(`^(${n.filter(e=>_r.has(typeof e)).map(e=>typeof e==`string`?vr(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Na=Y(`$ZodTransform`,(e,t)=>{Ui.init(e,t),e._zod.optin=`optional`,e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $n(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n.fallback=!0,n));if(i instanceof Promise)throw new Qn;return n.value=i,n.fallback=!0,n}});function Pa(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}var Fa=Y(`$ZodOptional`,(e,t)=>{Ui.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,X(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),X(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${or(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(t.innerType._zod.optin===`optional`){let r=e.value,i=t.innerType._zod.run(e,n);return i instanceof Promise?i.then(e=>Pa(e,r)):Pa(i,r)}return e.value===void 0?e:t.innerType._zod.run(e,n)}}),Ia=Y(`$ZodExactOptional`,(e,t)=>{Fa.init(e,t),X(e._zod,`values`,()=>t.innerType._zod.values),X(e._zod,`pattern`,()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),La=Y(`$ZodNullable`,(e,t)=>{Ui.init(e,t),X(e._zod,`optin`,()=>t.innerType._zod.optin),X(e._zod,`optout`,()=>t.innerType._zod.optout),X(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${or(e.source)}|null)$`):void 0}),X(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ra=Y(`$ZodDefault`,(e,t)=>{Ui.init(e,t),e._zod.optin=`optional`,X(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>za(e,t)):za(r,t)}});function za(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Ba=Y(`$ZodPrefault`,(e,t)=>{Ui.init(e,t),e._zod.optin=`optional`,X(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Va=Y(`$ZodNonOptional`,(e,t)=>{Ui.init(e,t),X(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Ha(t,e)):Ha(i,e)}});function Ha(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var Ua=Y(`$ZodCatch`,(e,t)=>{Ui.init(e,t),e._zod.optin=`optional`,X(e._zod,`optout`,()=>t.innerType._zod.optout),X(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Mr(e,n,tr()))},input:e.value}),e.issues=[],e.fallback=!0),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>Mr(e,n,tr()))},input:e.value}),e.issues=[],e.fallback=!0),e)}}),Wa=Y(`$ZodPipe`,(e,t)=>{Ui.init(e,t),X(e._zod,`values`,()=>t.in._zod.values),X(e._zod,`optin`,()=>t.in._zod.optin),X(e._zod,`optout`,()=>t.out._zod.optout),X(e._zod,`propValues`,()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ga(e,t.in,n)):Ga(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ga(e,t.out,n)):Ga(r,t.out,n)}});function Ga(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}var Ka=Y(`$ZodReadonly`,(e,t)=>{Ui.init(e,t),X(e._zod,`propValues`,()=>t.innerType._zod.propValues),X(e._zod,`values`,()=>t.innerType._zod.values),X(e._zod,`optin`,()=>t.innerType?._zod?.optin),X(e._zod,`optout`,()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(qa):qa(r)}});function qa(e){return e.value=Object.freeze(e.value),e}var Ja=Y(`$ZodCustom`,(e,t)=>{ki.init(e,t),Ui.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ya(t,n,r,e));Ya(i,n,r,e)}});function Ya(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Pr(e))}}var Xa,Za=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Qa(){return new Za}(Xa=globalThis).__zod_globalRegistry??(Xa.__zod_globalRegistry=Qa());var $a=globalThis.__zod_globalRegistry;function eo(e,t){return new e({type:`string`,...Z(t)})}function to(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...Z(t)})}function no(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...Z(t)})}function ro(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...Z(t)})}function io(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...Z(t)})}function ao(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...Z(t)})}function oo(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...Z(t)})}function so(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...Z(t)})}function co(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...Z(t)})}function lo(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...Z(t)})}function uo(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...Z(t)})}function fo(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...Z(t)})}function po(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...Z(t)})}function mo(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...Z(t)})}function ho(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...Z(t)})}function go(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...Z(t)})}function _o(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...Z(t)})}function vo(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...Z(t)})}function yo(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...Z(t)})}function bo(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...Z(t)})}function xo(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...Z(t)})}function So(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...Z(t)})}function Co(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...Z(t)})}function wo(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...Z(t)})}function To(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...Z(t)})}function Eo(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...Z(t)})}function Do(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...Z(t)})}function Oo(e){return new e({type:`unknown`})}function ko(e,t){return new e({type:`never`,...Z(t)})}function Ao(e,t){return new Ai({check:`max_length`,...Z(t),maximum:e})}function jo(e,t){return new ji({check:`min_length`,...Z(t),minimum:e})}function Mo(e,t){return new Mi({check:`length_equals`,...Z(t),length:e})}function No(e,t){return new Pi({check:`string_format`,format:`regex`,...Z(t),pattern:e})}function Po(e){return new Fi({check:`string_format`,format:`lowercase`,...Z(e)})}function Fo(e){return new Ii({check:`string_format`,format:`uppercase`,...Z(e)})}function Io(e,t){return new Li({check:`string_format`,format:`includes`,...Z(t),includes:e})}function Lo(e,t){return new Ri({check:`string_format`,format:`starts_with`,...Z(t),prefix:e})}function Ro(e,t){return new zi({check:`string_format`,format:`ends_with`,...Z(t),suffix:e})}function zo(e){return new Bi({check:`overwrite`,tx:e})}function Bo(e){return zo(t=>t.normalize(e))}function Vo(){return zo(e=>e.trim())}function Ho(){return zo(e=>e.toLowerCase())}function Uo(){return zo(e=>e.toUpperCase())}function Wo(){return zo(e=>dr(e))}function Go(e,t,n){return new e({type:`array`,element:t,...Z(n)})}function Ko(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...Z(n)})}function qo(e,t){let n=Jo(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Pr(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=t.value,r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Pr(r))}},e(t.value,t)),t);return n}function Jo(e,t){let n=new ki({check:`custom`,...Z(t)});return n._zod.check=e,n}function Yo(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??$a,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,external:e?.external??void 0}}function Xo(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Xo(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io===`input`&&$o(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Zo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${a}`}}if(t[1]===n)return{ref:`#`};let i=`#/${r}/`,a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+a}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
76
76
 
77
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Qo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:ts(t,`input`,e.processors),output:ts(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function $o(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return $o(r.element,n);if(r.type===`set`)return $o(r.valueType,n);if(r.type===`lazy`)return $o(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return $o(r.innerType,n);if(r.type===`intersection`)return $o(r.left,n)||$o(r.right,n);if(r.type===`record`||r.type===`map`)return $o(r.keyType,n)||$o(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:$o(r.in,n)||$o(r.out,n);if(r.type===`object`){for(let e in r.shape)if($o(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if($o(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if($o(e,n))return!0;return!!(r.rest&&$o(r.rest,n))}return!1}var es=(e,t={})=>n=>{let r=Yo({...n,processors:t});return Xo(e,r),Zo(r,e),Qo(r,e)},ts=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Yo({...i??{},target:a,io:t,processors:n});return Xo(e,o),Zo(o,e),Qo(o,e)},ns={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},rs=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ns[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},is=(e,t,n,r)=>{n.not={}},as=(e,t,n,r)=>{let i=e._zod.def,a=nr(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},os=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ss=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},cs=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Xo(a.element,t,{...r,path:[...r.path,`items`]})},ls=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Xo(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Xo(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},us=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Xo(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ds=(e,t,n,r)=>{let i=e._zod.def,a=Xo(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Xo(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},fs=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Xo(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Xo(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Xo(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},ps=(e,t,n,r)=>{let i=e._zod.def,a=Xo(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ms=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},hs=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},gs=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},_s=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},vs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Xo(o,t,r);let s=t.seen.get(e);s.ref=o},ys=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},bs=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xs=Y(`ZodISODateTime`,(e,t)=>{na.init(e,t),$.init(e,t)});function Ss(e){return wo(xs,e)}var Cs=Y(`ZodISODate`,(e,t)=>{ra.init(e,t),$.init(e,t)});function ws(e){return To(Cs,e)}var Ts=Y(`ZodISOTime`,(e,t)=>{ia.init(e,t),$.init(e,t)});function Es(e){return Eo(Ts,e)}var Ds=Y(`ZodISODuration`,(e,t)=>{aa.init(e,t),$.init(e,t)});function Os(e){return Do(Ds,e)}var ks=Y(`ZodError`,(e,t)=>{Ir.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>zr(e,t)},flatten:{value:t=>Rr(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,rr,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,rr,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),As=Br(ks),js=Vr(ks),Ms=Hr(ks),Ns=Wr(ks),Ps=Kr(ks),Fs=qr(ks),Is=Jr(ks),Ls=Yr(ks),Rs=Xr(ks),zs=Zr(ks),Bs=Qr(ks),Vs=$r(ks),Hs=new WeakMap;function Us(e,t,n){let r=Object.getPrototypeOf(e),i=Hs.get(r);if(i||(i=new Set,Hs.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ws=Y(`ZodType`,(e,t)=>(Ui.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ts(e,`input`),output:ts(e,`output`)}}),e.toJSONSchema=es(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>As(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ms(e,t,n),e.parseAsync=async(t,n)=>js(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ns(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ps(e,t,n),e.decode=(t,n)=>Fs(e,t,n),e.encodeAsync=async(t,n)=>Is(e,t,n),e.decodeAsync=async(t,n)=>Ls(e,t,n),e.safeEncode=(t,n)=>Rs(e,t,n),e.safeDecode=(t,n)=>zs(e,t,n),e.safeEncodeAsync=async(t,n)=>Bs(e,t,n),e.safeDecodeAsync=async(t,n)=>Vs(e,t,n),Us(e,`ZodType`,{check(...e){let t=this.def;return this.clone(lr(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return yr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Xc(e,t))},superRefine(e,t){return this.check(Zc(e,t))},overwrite(e){return this.check(zo(e))},optional(){return Mc(this)},exactOptional(){return Pc(this)},nullable(){return Ic(this)},nullish(){return Mc(Ic(this))},nonoptional(e){return Hc(this,e)},array(){return vc(this)},or(e){return Sc([this,e])},and(e){return wc(this,e)},transform(e){return Kc(this,Ac(e))},default(e){return Rc(this,e)},prefault(e){return Bc(this,e)},catch(e){return Wc(this,e)},pipe(e){return Kc(this,e)},readonly(){return Jc(this)},describe(e){let t=this.clone();return $a.add(t,{description:e}),t},meta(...e){if(e.length===0)return $a.get(this);let t=this.clone();return $a.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return $a.get(e)?.description},configurable:!0}),e)),Gs=Y(`_ZodString`,(e,t)=>{Wi.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Us(e,`_ZodString`,{regex(...e){return this.check(No(...e))},includes(...e){return this.check(Io(...e))},startsWith(...e){return this.check(Lo(...e))},endsWith(...e){return this.check(Ro(...e))},min(...e){return this.check(jo(...e))},max(...e){return this.check(Ao(...e))},length(...e){return this.check(Mo(...e))},nonempty(...e){return this.check(jo(1,...e))},lowercase(e){return this.check(Po(e))},uppercase(e){return this.check(Fo(e))},trim(){return this.check(Vo())},normalize(...e){return this.check(Bo(...e))},toLowerCase(){return this.check(Ho())},toUpperCase(){return this.check(Uo())},slugify(){return this.check(Wo())}})}),Ks=Y(`ZodString`,(e,t)=>{Wi.init(e,t),Gs.init(e,t),e.email=t=>e.check(to(Js,t)),e.url=t=>e.check(so(Zs,t)),e.jwt=t=>e.check(Co(fc,t)),e.emoji=t=>e.check(co(Qs,t)),e.guid=t=>e.check(no(Ys,t)),e.uuid=t=>e.check(ro(Xs,t)),e.uuidv4=t=>e.check(io(Xs,t)),e.uuidv6=t=>e.check(ao(Xs,t)),e.uuidv7=t=>e.check(oo(Xs,t)),e.nanoid=t=>e.check(lo($s,t)),e.guid=t=>e.check(no(Ys,t)),e.cuid=t=>e.check(uo(ec,t)),e.cuid2=t=>e.check(fo(tc,t)),e.ulid=t=>e.check(po(nc,t)),e.base64=t=>e.check(bo(lc,t)),e.base64url=t=>e.check(xo(uc,t)),e.xid=t=>e.check(mo(rc,t)),e.ksuid=t=>e.check(ho(ic,t)),e.ipv4=t=>e.check(go(ac,t)),e.ipv6=t=>e.check(_o(oc,t)),e.cidrv4=t=>e.check(vo(sc,t)),e.cidrv6=t=>e.check(yo(cc,t)),e.e164=t=>e.check(So(dc,t)),e.datetime=t=>e.check(Ss(t)),e.date=t=>e.check(ws(t)),e.time=t=>e.check(Es(t)),e.duration=t=>e.check(Os(t))});function qs(e){return eo(Ks,e)}var $=Y(`ZodStringFormat`,(e,t)=>{Q.init(e,t),Gs.init(e,t)}),Js=Y(`ZodEmail`,(e,t)=>{qi.init(e,t),$.init(e,t)}),Ys=Y(`ZodGUID`,(e,t)=>{Gi.init(e,t),$.init(e,t)}),Xs=Y(`ZodUUID`,(e,t)=>{Ki.init(e,t),$.init(e,t)}),Zs=Y(`ZodURL`,(e,t)=>{Ji.init(e,t),$.init(e,t)}),Qs=Y(`ZodEmoji`,(e,t)=>{Yi.init(e,t),$.init(e,t)}),$s=Y(`ZodNanoID`,(e,t)=>{Xi.init(e,t),$.init(e,t)}),ec=Y(`ZodCUID`,(e,t)=>{Zi.init(e,t),$.init(e,t)}),tc=Y(`ZodCUID2`,(e,t)=>{Qi.init(e,t),$.init(e,t)}),nc=Y(`ZodULID`,(e,t)=>{$i.init(e,t),$.init(e,t)}),rc=Y(`ZodXID`,(e,t)=>{ea.init(e,t),$.init(e,t)}),ic=Y(`ZodKSUID`,(e,t)=>{ta.init(e,t),$.init(e,t)}),ac=Y(`ZodIPv4`,(e,t)=>{oa.init(e,t),$.init(e,t)}),oc=Y(`ZodIPv6`,(e,t)=>{sa.init(e,t),$.init(e,t)}),sc=Y(`ZodCIDRv4`,(e,t)=>{ca.init(e,t),$.init(e,t)}),cc=Y(`ZodCIDRv6`,(e,t)=>{la.init(e,t),$.init(e,t)}),lc=Y(`ZodBase64`,(e,t)=>{da.init(e,t),$.init(e,t)}),uc=Y(`ZodBase64URL`,(e,t)=>{pa.init(e,t),$.init(e,t)}),dc=Y(`ZodE164`,(e,t)=>{ma.init(e,t),$.init(e,t)}),fc=Y(`ZodJWT`,(e,t)=>{ga.init(e,t),$.init(e,t)}),pc=Y(`ZodUnknown`,(e,t)=>{_a.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function mc(){return Oo(pc)}var hc=Y(`ZodNever`,(e,t)=>{va.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r)});function gc(e){return ko(hc,e)}var _c=Y(`ZodArray`,(e,t)=>{ba.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cs(e,t,n,r),e.element=t.element,Us(e,`ZodArray`,{min(e,t){return this.check(jo(e,t))},nonempty(e){return this.check(jo(1,e))},max(e,t){return this.check(Ao(e,t))},length(e,t){return this.check(Mo(e,t))},unwrap(){return this.element}})});function vc(e,t){return Go(_c,e,t)}var yc=Y(`ZodObject`,(e,t)=>{Ta.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ls(e,t,n,r),X(e,`shape`,()=>t.shape),Us(e,`ZodObject`,{keyof(){return Oc(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:mc()})},loose(){return this.clone({...this._zod.def,catchall:mc()})},strict(){return this.clone({...this._zod.def,catchall:gc()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Cr(this,e)},safeExtend(e){return wr(this,e)},merge(e){return Tr(this,e)},pick(e){return xr(this,e)},omit(e){return Sr(this,e)},partial(...e){return Er(jc,this,e[0])},required(...e){return Dr(Vc,this,e[0])}})});function bc(e,t){return new yc({type:`object`,shape:e??{},...Z(t)})}var xc=Y(`ZodUnion`,(e,t)=>{Da.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),e.options=t.options});function Sc(e,t){return new xc({type:`union`,options:e,...Z(t)})}var Cc=Y(`ZodIntersection`,(e,t)=>{Oa.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r)});function wc(e,t){return new Cc({type:`intersection`,left:e,right:t})}var Tc=Y(`ZodRecord`,(e,t)=>{ja.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ec(e,t,n){return!t||!t._zod?new Tc({type:`record`,keyType:qs(),valueType:e,...Z(t)}):new Tc({type:`record`,keyType:e,valueType:t,...Z(n)})}var Dc=Y(`ZodEnum`,(e,t)=>{Ma.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Dc({...t,checks:[],...Z(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Dc({...t,checks:[],...Z(r),entries:i})}});function Oc(e,t){return new Dc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...Z(t)})}var kc=Y(`ZodTransform`,(e,t)=>{Na.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $n(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Pr(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Pr(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Ac(e){return new kc({type:`transform`,transform:e})}var jc=Y(`ZodOptional`,(e,t)=>{Fa.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Mc(e){return new jc({type:`optional`,innerType:e})}var Nc=Y(`ZodExactOptional`,(e,t)=>{Ia.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new Nc({type:`optional`,innerType:e})}var Fc=Y(`ZodNullable`,(e,t)=>{La.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e){return new Fc({type:`nullable`,innerType:e})}var Lc=Y(`ZodDefault`,(e,t)=>{Ra.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Rc(e,t){return new Lc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():gr(t)}})}var zc=Y(`ZodPrefault`,(e,t)=>{Ba.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bc(e,t){return new zc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():gr(t)}})}var Vc=Y(`ZodNonOptional`,(e,t)=>{Va.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ms(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e,t){return new Vc({type:`nonoptional`,innerType:e,...Z(t)})}var Uc=Y(`ZodCatch`,(e,t)=>{Ua.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wc(e,t){return new Uc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Gc=Y(`ZodPipe`,(e,t)=>{Wa.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.in=t.in,e.out=t.out});function Kc(e,t){return new Gc({type:`pipe`,in:e,out:t})}var qc=Y(`ZodReadonly`,(e,t)=>{Ka.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jc(e){return new qc({type:`readonly`,innerType:e})}var Yc=Y(`ZodCustom`,(e,t)=>{Ja.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function Xc(e,t={}){return Ko(Yc,e,t)}function Zc(e,t){return qo(e,t)}var Qc=function(e){return e.AUTHENTICATION_FAILED=`authentication_failed`,e.TOKEN_EXPIRED=`token_expired`,e.INVALID_API_KEY=`invalid_api_key`,e.FORBIDDEN=`forbidden`,e.RATE_LIMIT_EXCEEDED=`rate_limit_exceeded`,e.SESSION_NOT_FOUND=`session_not_found`,e.TEMPLATE_NOT_FOUND=`template_not_found`,e.SESSION_EXPIRED=`session_expired`,e.INVALID_REQUEST=`invalid_request`,e.INVALID_AUDIO_FORMAT=`invalid_audio_format`,e.CHUNK_TOO_LARGE=`chunk_too_large`,e.INVALID_TEMPLATE=`invalid_template`,e.MISSING_REQUIRED_FIELD=`missing_required_field`,e.PROCESSING_FAILED=`processing_failed`,e.AUDIO_QUALITY_POOR=`audio_quality_poor`,e.AUDIO_TOO_SHORT=`audio_too_short`,e.LANGUAGE_UNSUPPORTED=`language_unsupported`,e.INTERNAL_ERROR=`internal_error`,e.SERVICE_UNAVAILABLE=`service_unavailable`,e.DISCOVERY_FAILED=`discovery_failed`,e.TRANSPORT_ERROR=`transport_error`,e.WORKER_ERROR=`worker_error`,e.UPLOAD_FAILED=`upload_failed`,e.VAD_ERROR=`vad_error`,e.CHUNK_LENGTH_EXCEEDED=`chunk_length_exceeded`,e.CHUNK_LIMIT_REACHED=`chunk_limit_reached`,e.CHUNK_CREATION_FAILED=`chunk_creation_failed`,e.WORKER_POST_FAILED=`worker_post_failed`,e.SESSION_CREATION_FAILED=`session_creation_failed`,e.RECORDER_INIT_FAILED=`recorder_init_failed`,e.RECORDER_START_FAILED=`recorder_start_failed`,e.VAD_START_FAILED=`vad_start_failed`,e.STOP_FAILED=`stop_failed`,e.INTERNAL_RETRY_FAILED=`internal_retry_failed`,e.SESSION_END_FAILED=`session_end_failed`,e.UNSUPPORTED_STORAGE_PROVIDER=`unsupported_storage_provider`,e}({}),$c=class e extends Error{constructor(t,n=Qc.INTERNAL_ERROR,r,i){super(t),this.name=`ScribeError`,this.code=n,this.httpStatus=r,this.details=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}static fromApiError(t,n){return new e(t.message,t.code,n,t.details)}toJSON(){return{name:this.name,message:this.message,code:this.code,httpStatus:this.httpStatus,details:this.details}}},el=class extends $c{constructor(e,t,n){super(e,Qc.UPLOAD_FAILED,void 0,n),this.name=`UploadError`,this.failedFiles=t}toJSON(){return{...super.toJSON(),failedFiles:this.failedFiles}}},tl=class extends $c{constructor(e){super(`Storage provider '${e||`(none)`}' is not supported by this SDK build.`,Qc.UNSUPPORTED_STORAGE_PROVIDER,void 0,{provider:e}),this.name=`UnsupportedStorageProviderError`,this.provider=e}},nl=bc({uploadData:bc({url:qs().min(1,`uploadData.url is required`),fields:Ec(qs(),qs())}),folderPath:qs().optional(),txn_id:qs().optional()}),rl=`key`,il="${filename}",al=`Content-Type`,ol=`audio/mp3`,sl=class{constructor(){this.name=`aws`}prepareUpload({fileName:e,blob:t,upload:n}){let r=nl.safeParse(n);if(!r.success)throw new el(`Invalid AWS upload payload in session response: ${r.error.message}`,[e]);let{uploadData:i}=r.data,a={};for(let[t,n]of Object.entries(i.fields))a[t]=t===rl?n.split(il).join(e):n;if(!(al in a)){let e=t?.type;a[al]=e&&e.startsWith(`audio/`)?e:ol}return{url:i.url,method:`POST`,bodyMode:`multipart`,formFields:a,fileFieldName:`file`,headers:{},attachAuth:!1}}},cl=qs().trim().min(1,`upload_url is required`),ll=`Content-Type`,ul=`audio/mp3`,dl=new Set([`audio/webm;codecs=opus`,`audio/wav`,`audio/ogg`,`audio/ogg;codecs=opus`,`audio/mp4`,`audio/m4a`,`audio/mp3`]),fl={mp3:`audio/mp3`,webm:`audio/webm;codecs=opus`,wav:`audio/wav`,ogg:`audio/ogg`,m4a:`audio/m4a`,mp4:`audio/mp4`};function pl(e,t){let n=fl[e.split(`.`).pop()?.toLowerCase()??``];if(n)return n;let r=t?.type;return r&&dl.has(r)?r:ul}var ml=class{constructor(){this.name=`backend`}prepareUpload({fileName:e,blob:t,upload:n}){let r=cl.safeParse(n);if(!r.success)throw new el(`Invalid backend upload payload: expected an upload_url string, got ${typeof n}`,[e]);return{url:`${r.data.replace(/\/+$/,``)}/${encodeURIComponent(e)}`,method:`POST`,bodyMode:`binary`,headers:{[ll]:pl(e,t)},attachAuth:!0}}},hl={aws:()=>new sl,backend:()=>new ml};function gl(e){return typeof e==`string`?e.trim().toLowerCase():``}function _l(e){let t=hl[gl(e)];if(!t)throw new tl(e);return t()}var vl=2,yl=2e3,bl=1e4,xl,Sl=[],Cl=new Map,wl=null,Tl=new Map;function El(e,t){let n=Tl.get(e);if(n){Tl.delete(e);for(let e of n)e(t)}}function Dl(e,t){try{e.postMessage(t)}catch{}}function Ol(e){for(let t of Sl)Dl(t,e)}function kl(){return new Promise(e=>{let t=wl;wl=()=>{t?.(),e()},setTimeout(()=>{e()},bl)})}function Al(e){return new Promise(t=>{let n=Tl.get(e);n||(n=new Set,Tl.set(e,n)),n.add(t),setTimeout(()=>{let n=Tl.get(e);n?.has(t)&&(n.delete(t),n.size===0&&Tl.delete(e),t(null))},bl)})}function jl(e,t,n,r){let i={...e.headers};e.attachAuth&&(Object.assign(i,r),xl&&(i.Authorization=`Bearer ${xl}`));let a;if(e.bodyMode===`multipart`){let r=new FormData;for(let[t,n]of Object.entries(e.formFields??{}))r.append(t,n);r.append(e.fileFieldName??`file`,n,t),a=r}else a=n,i[`Content-Type`]||=`audio/mp3`;return{method:e.method,body:a,headers:i,credentials:e.attachAuth?`include`:`omit`}}async function Ml(e,t,n,r,i){Dl(e,{type:`upload_url_required`,fileName:n});let a=await Al(e);if(!a)return i;try{return _l(t).prepareUpload({fileName:n,blob:r,upload:a})}catch{return i}}async function Nl(e,t,n,r,i,a){let o=`Upload failed after retries`,s;for(let c=0;c<=vl;c++)try{let l=await fetch(e.url,jl(e,t,n,r));if(l.ok)return{success:!0};if(s=l.status,o=await Pl(l),l.status===401&&e.attachAuth){Ol({type:`token_required`}),await kl();continue}if(c<vl){e=await Ml(a,i,t,n,e),await Fl(yl);continue}return{success:!1,error:o,statusCode:s}}catch(r){o=r?.message??`Network error`,c<vl&&(e=await Ml(a,i,t,n,e),await Fl(yl))}return{success:!1,error:o,statusCode:s}}async function Pl(e){try{let t=await e.json();return t?.error?.message??t?.message??e.statusText??`Request failed`}catch{return e.statusText??`HTTP ${e.status}`}}function Fl(e){return new Promise(t=>setTimeout(t,e))}async function Il(e,t,n,r,i,a){try{let o=Xn(e);if(!o){Dl(a,{type:`upload_failed`,fileName:t,error:`MP3 encoding failed`});return}Dl(a,{type:`chunk_encoded`,fileName:t,chunkData:o.chunks});let s;try{s=_l(n).prepareUpload({fileName:t,blob:o.blob,upload:r})}catch(e){Dl(a,{type:`upload_failed`,fileName:t,error:e?.message??`Failed to prepare upload`,chunkData:o.chunks});return}let c=await Nl(s,t,o.blob,i,n,a);c.success?Dl(a,{type:`upload_success`,fileName:t}):Dl(a,{type:`upload_failed`,fileName:t,error:c.error??`Upload failed after retries`,chunkData:o.chunks})}catch(e){Dl(a,{type:`upload_failed`,fileName:t,error:e?.message??`Unknown error`})}}function Ll(e,t){switch(e.type){case`compress_and_upload`:{Cl.has(t)||Cl.set(t,new Set);let n=Cl.get(t),r=Il(e.audioFrames,e.fileName,e.storageProvider,e.upload,e.headers,t);n.add(r),r.finally(()=>n.delete(r));break}case`wait_for_all_uploads`:{let e=Cl.get(t)??new Set;Promise.all(e).then(()=>{Dl(t,{type:`all_uploads_complete`})});break}case`update_auth_token`:xl=e.token,wl&&=(wl(),null);break;case`update_upload_url`:El(t,e.upload);break;case`terminate`:{let e=Sl.indexOf(t);e>=0&&Sl.splice(e,1),Cl.delete(t),El(t,null);try{t.close()}catch{}Sl.length===0&&self.close();break}}}var Rl=self;Rl.onconnect=e=>{let t=e.ports[0];Sl.push(t),t.onmessage=e=>{Ll(e.data,t)},t.start()}})();
77
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}}function Qo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Object.assign(i,s),Object.assign(i,a),t._zod.parent===o)for(let e in i)e===`$ref`||e===`allOf`||e in a||delete i[e];if(s.$ref&&n.def)for(let e in i)e===`$ref`||e===`allOf`||e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e===`$ref`||e===`allOf`||e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(let t of[...e.seen.entries()].reverse())r(t[0]);let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,`~standard`,{value:{...t[`~standard`],jsonSchema:{input:ts(t,`input`,e.processors),output:ts(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function $o(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return $o(r.element,n);if(r.type===`set`)return $o(r.valueType,n);if(r.type===`lazy`)return $o(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type===`default`||r.type===`prefault`)return $o(r.innerType,n);if(r.type===`intersection`)return $o(r.left,n)||$o(r.right,n);if(r.type===`record`||r.type===`map`)return $o(r.keyType,n)||$o(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:$o(r.in,n)||$o(r.out,n);if(r.type===`object`){for(let e in r.shape)if($o(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if($o(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if($o(e,n))return!0;return!!(r.rest&&$o(r.rest,n))}return!1}var es=(e,t={})=>n=>{let r=Yo({...n,processors:t});return Xo(e,r),Zo(r,e),Qo(r,e)},ts=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Yo({...i??{},target:a,io:t,processors:n});return Xo(e,o),Zo(o,e),Qo(o,e)},ns={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},rs=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ns[s]??s,i.format===``&&delete i.format,s===`time`&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},is=(e,t,n,r)=>{n.not={}},as=(e,t,n,r)=>{let i=e._zod.def,a=nr(i.entries);a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},os=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Custom types cannot be represented in JSON Schema`)},ss=(e,t,n,r)=>{if(t.unrepresentable===`throw`)throw Error(`Transforms cannot be represented in JSON Schema`)},cs=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Xo(a.element,t,{...r,path:[...r.path,`items`]})},ls=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`,i.properties={};let o=a.shape;for(let e in o)i.properties[e]=Xo(o[e],t,{...r,path:[...r.path,`properties`,e]});let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e]._zod;return t.io===`input`?n.optin===void 0:n.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Xo(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},us=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Xo(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ds=(e,t,n,r)=>{let i=e._zod.def,a=Xo(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Xo(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1;n.allOf=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]]},fs=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Xo(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)i.patternProperties[t.source]=e}else (t.target===`draft-07`||t.target===`draft-2020-12`)&&(i.propertyNames=Xo(a.keyType,t,{...r,path:[...r.path,`propertyNames`]})),i.additionalProperties=Xo(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]});let c=o._zod.values;if(c){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e)}},ps=(e,t,n,r)=>{let i=e._zod.def,a=Xo(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},ms=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},hs=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},gs=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,t.io===`input`&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},_s=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw Error(`Dynamic catch values are not supported in JSON Schema`)}n.default=o},vs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Xo(o,t,r);let s=t.seen.get(e);s.ref=o},ys=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},bs=(e,t,n,r)=>{let i=e._zod.def;Xo(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xs=Y(`ZodISODateTime`,(e,t)=>{na.init(e,t),$.init(e,t)});function Ss(e){return wo(xs,e)}var Cs=Y(`ZodISODate`,(e,t)=>{ra.init(e,t),$.init(e,t)});function ws(e){return To(Cs,e)}var Ts=Y(`ZodISOTime`,(e,t)=>{ia.init(e,t),$.init(e,t)});function Es(e){return Eo(Ts,e)}var Ds=Y(`ZodISODuration`,(e,t)=>{aa.init(e,t),$.init(e,t)});function Os(e){return Do(Ds,e)}var ks=Y(`ZodError`,(e,t)=>{Ir.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>zr(e,t)},flatten:{value:t=>Rr(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,rr,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,rr,2)}},isEmpty:{get(){return e.issues.length===0}}})},{Parent:Error}),As=Br(ks),js=Vr(ks),Ms=Hr(ks),Ns=Wr(ks),Ps=Kr(ks),Fs=qr(ks),Is=Jr(ks),Ls=Yr(ks),Rs=Xr(ks),zs=Zr(ks),Bs=Qr(ks),Vs=$r(ks),Hs=new WeakMap;function Us(e,t,n){let r=Object.getPrototypeOf(e),i=Hs.get(r);if(i||(i=new Set,Hs.set(r,i)),!i.has(t)){i.add(t);for(let e in n){let t=n[e];Object.defineProperty(r,e,{configurable:!0,enumerable:!1,get(){let n=t.bind(this);return Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:n}),n},set(t){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:!0,value:t})}})}}}var Ws=Y(`ZodType`,(e,t)=>(Ui.init(e,t),Object.assign(e[`~standard`],{jsonSchema:{input:ts(e,`input`),output:ts(e,`output`)}}),e.toJSONSchema=es(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,`_def`,{value:t}),e.parse=(t,n)=>As(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>Ms(e,t,n),e.parseAsync=async(t,n)=>js(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Ns(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>Ps(e,t,n),e.decode=(t,n)=>Fs(e,t,n),e.encodeAsync=async(t,n)=>Is(e,t,n),e.decodeAsync=async(t,n)=>Ls(e,t,n),e.safeEncode=(t,n)=>Rs(e,t,n),e.safeDecode=(t,n)=>zs(e,t,n),e.safeEncodeAsync=async(t,n)=>Bs(e,t,n),e.safeDecodeAsync=async(t,n)=>Vs(e,t,n),Us(e,`ZodType`,{check(...e){let t=this.def;return this.clone(lr(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return yr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Xc(e,t))},superRefine(e,t){return this.check(Zc(e,t))},overwrite(e){return this.check(zo(e))},optional(){return Mc(this)},exactOptional(){return Pc(this)},nullable(){return Ic(this)},nullish(){return Mc(Ic(this))},nonoptional(e){return Hc(this,e)},array(){return vc(this)},or(e){return Sc([this,e])},and(e){return wc(this,e)},transform(e){return Kc(this,Ac(e))},default(e){return Rc(this,e)},prefault(e){return Bc(this,e)},catch(e){return Wc(this,e)},pipe(e){return Kc(this,e)},readonly(){return Jc(this)},describe(e){let t=this.clone();return $a.add(t,{description:e}),t},meta(...e){if(e.length===0)return $a.get(this);let t=this.clone();return $a.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e){return e(this)}}),Object.defineProperty(e,`description`,{get(){return $a.get(e)?.description},configurable:!0}),e)),Gs=Y(`_ZodString`,(e,t)=>{Wi.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,Us(e,`_ZodString`,{regex(...e){return this.check(No(...e))},includes(...e){return this.check(Io(...e))},startsWith(...e){return this.check(Lo(...e))},endsWith(...e){return this.check(Ro(...e))},min(...e){return this.check(jo(...e))},max(...e){return this.check(Ao(...e))},length(...e){return this.check(Mo(...e))},nonempty(...e){return this.check(jo(1,...e))},lowercase(e){return this.check(Po(e))},uppercase(e){return this.check(Fo(e))},trim(){return this.check(Vo())},normalize(...e){return this.check(Bo(...e))},toLowerCase(){return this.check(Ho())},toUpperCase(){return this.check(Uo())},slugify(){return this.check(Wo())}})}),Ks=Y(`ZodString`,(e,t)=>{Wi.init(e,t),Gs.init(e,t),e.email=t=>e.check(to(Js,t)),e.url=t=>e.check(so(Zs,t)),e.jwt=t=>e.check(Co(fc,t)),e.emoji=t=>e.check(co(Qs,t)),e.guid=t=>e.check(no(Ys,t)),e.uuid=t=>e.check(ro(Xs,t)),e.uuidv4=t=>e.check(io(Xs,t)),e.uuidv6=t=>e.check(ao(Xs,t)),e.uuidv7=t=>e.check(oo(Xs,t)),e.nanoid=t=>e.check(lo($s,t)),e.guid=t=>e.check(no(Ys,t)),e.cuid=t=>e.check(uo(ec,t)),e.cuid2=t=>e.check(fo(tc,t)),e.ulid=t=>e.check(po(nc,t)),e.base64=t=>e.check(bo(lc,t)),e.base64url=t=>e.check(xo(uc,t)),e.xid=t=>e.check(mo(rc,t)),e.ksuid=t=>e.check(ho(ic,t)),e.ipv4=t=>e.check(go(ac,t)),e.ipv6=t=>e.check(_o(oc,t)),e.cidrv4=t=>e.check(vo(sc,t)),e.cidrv6=t=>e.check(yo(cc,t)),e.e164=t=>e.check(So(dc,t)),e.datetime=t=>e.check(Ss(t)),e.date=t=>e.check(ws(t)),e.time=t=>e.check(Es(t)),e.duration=t=>e.check(Os(t))});function qs(e){return eo(Ks,e)}var $=Y(`ZodStringFormat`,(e,t)=>{Q.init(e,t),Gs.init(e,t)}),Js=Y(`ZodEmail`,(e,t)=>{qi.init(e,t),$.init(e,t)}),Ys=Y(`ZodGUID`,(e,t)=>{Gi.init(e,t),$.init(e,t)}),Xs=Y(`ZodUUID`,(e,t)=>{Ki.init(e,t),$.init(e,t)}),Zs=Y(`ZodURL`,(e,t)=>{Ji.init(e,t),$.init(e,t)}),Qs=Y(`ZodEmoji`,(e,t)=>{Yi.init(e,t),$.init(e,t)}),$s=Y(`ZodNanoID`,(e,t)=>{Xi.init(e,t),$.init(e,t)}),ec=Y(`ZodCUID`,(e,t)=>{Zi.init(e,t),$.init(e,t)}),tc=Y(`ZodCUID2`,(e,t)=>{Qi.init(e,t),$.init(e,t)}),nc=Y(`ZodULID`,(e,t)=>{$i.init(e,t),$.init(e,t)}),rc=Y(`ZodXID`,(e,t)=>{ea.init(e,t),$.init(e,t)}),ic=Y(`ZodKSUID`,(e,t)=>{ta.init(e,t),$.init(e,t)}),ac=Y(`ZodIPv4`,(e,t)=>{oa.init(e,t),$.init(e,t)}),oc=Y(`ZodIPv6`,(e,t)=>{sa.init(e,t),$.init(e,t)}),sc=Y(`ZodCIDRv4`,(e,t)=>{ca.init(e,t),$.init(e,t)}),cc=Y(`ZodCIDRv6`,(e,t)=>{la.init(e,t),$.init(e,t)}),lc=Y(`ZodBase64`,(e,t)=>{da.init(e,t),$.init(e,t)}),uc=Y(`ZodBase64URL`,(e,t)=>{pa.init(e,t),$.init(e,t)}),dc=Y(`ZodE164`,(e,t)=>{ma.init(e,t),$.init(e,t)}),fc=Y(`ZodJWT`,(e,t)=>{ga.init(e,t),$.init(e,t)}),pc=Y(`ZodUnknown`,(e,t)=>{_a.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function mc(){return Oo(pc)}var hc=Y(`ZodNever`,(e,t)=>{va.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r)});function gc(e){return ko(hc,e)}var _c=Y(`ZodArray`,(e,t)=>{ba.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cs(e,t,n,r),e.element=t.element,Us(e,`ZodArray`,{min(e,t){return this.check(jo(e,t))},nonempty(e){return this.check(jo(1,e))},max(e,t){return this.check(Ao(e,t))},length(e,t){return this.check(Mo(e,t))},unwrap(){return this.element}})});function vc(e,t){return Go(_c,e,t)}var yc=Y(`ZodObject`,(e,t)=>{Ta.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ls(e,t,n,r),X(e,`shape`,()=>t.shape),Us(e,`ZodObject`,{keyof(){return Oc(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:mc()})},loose(){return this.clone({...this._zod.def,catchall:mc()})},strict(){return this.clone({...this._zod.def,catchall:gc()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return Cr(this,e)},safeExtend(e){return wr(this,e)},merge(e){return Tr(this,e)},pick(e){return xr(this,e)},omit(e){return Sr(this,e)},partial(...e){return Er(jc,this,e[0])},required(...e){return Dr(Vc,this,e[0])}})});function bc(e,t){return new yc({type:`object`,shape:e??{},...Z(t)})}var xc=Y(`ZodUnion`,(e,t)=>{Da.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>us(e,t,n,r),e.options=t.options});function Sc(e,t){return new xc({type:`union`,options:e,...Z(t)})}var Cc=Y(`ZodIntersection`,(e,t)=>{Oa.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ds(e,t,n,r)});function wc(e,t){return new Cc({type:`intersection`,left:e,right:t})}var Tc=Y(`ZodRecord`,(e,t)=>{ja.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fs(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ec(e,t,n){return!t||!t._zod?new Tc({type:`record`,keyType:qs(),valueType:e,...Z(t)}):new Tc({type:`record`,keyType:e,valueType:t,...Z(n)})}var Dc=Y(`ZodEnum`,(e,t)=>{Ma.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Dc({...t,checks:[],...Z(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Dc({...t,checks:[],...Z(r),entries:i})}});function Oc(e,t){return new Dc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...Z(t)})}var kc=Y(`ZodTransform`,(e,t)=>{Na.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ss(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $n(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Pr(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,n.issues.push(Pr(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function Ac(e){return new kc({type:`transform`,transform:e})}var jc=Y(`ZodOptional`,(e,t)=>{Fa.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Mc(e){return new jc({type:`optional`,innerType:e})}var Nc=Y(`ZodExactOptional`,(e,t)=>{Ia.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e){return new Nc({type:`optional`,innerType:e})}var Fc=Y(`ZodNullable`,(e,t)=>{La.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ps(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e){return new Fc({type:`nullable`,innerType:e})}var Lc=Y(`ZodDefault`,(e,t)=>{Ra.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Rc(e,t){return new Lc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():gr(t)}})}var zc=Y(`ZodPrefault`,(e,t)=>{Ba.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gs(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bc(e,t){return new zc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():gr(t)}})}var Vc=Y(`ZodNonOptional`,(e,t)=>{Va.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ms(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e,t){return new Vc({type:`nonoptional`,innerType:e,...Z(t)})}var Uc=Y(`ZodCatch`,(e,t)=>{Ua.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_s(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Wc(e,t){return new Uc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var Gc=Y(`ZodPipe`,(e,t)=>{Wa.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vs(e,t,n,r),e.in=t.in,e.out=t.out});function Kc(e,t){return new Gc({type:`pipe`,in:e,out:t})}var qc=Y(`ZodReadonly`,(e,t)=>{Ka.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ys(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Jc(e){return new qc({type:`readonly`,innerType:e})}var Yc=Y(`ZodCustom`,(e,t)=>{Ja.init(e,t),Ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r)});function Xc(e,t={}){return Ko(Yc,e,t)}function Zc(e,t){return qo(e,t)}var Qc=function(e){return e.AUTHENTICATION_FAILED=`authentication_failed`,e.TOKEN_EXPIRED=`token_expired`,e.INVALID_API_KEY=`invalid_api_key`,e.FORBIDDEN=`forbidden`,e.RATE_LIMIT_EXCEEDED=`rate_limit_exceeded`,e.SESSION_NOT_FOUND=`session_not_found`,e.TEMPLATE_NOT_FOUND=`template_not_found`,e.SESSION_EXPIRED=`session_expired`,e.INVALID_REQUEST=`invalid_request`,e.INVALID_AUDIO_FORMAT=`invalid_audio_format`,e.CHUNK_TOO_LARGE=`chunk_too_large`,e.INVALID_TEMPLATE=`invalid_template`,e.MISSING_REQUIRED_FIELD=`missing_required_field`,e.PROCESSING_FAILED=`processing_failed`,e.AUDIO_QUALITY_POOR=`audio_quality_poor`,e.AUDIO_TOO_SHORT=`audio_too_short`,e.LANGUAGE_UNSUPPORTED=`language_unsupported`,e.INTERNAL_ERROR=`internal_error`,e.SERVICE_UNAVAILABLE=`service_unavailable`,e.DISCOVERY_FAILED=`discovery_failed`,e.TRANSPORT_ERROR=`transport_error`,e.WORKER_ERROR=`worker_error`,e.UPLOAD_FAILED=`upload_failed`,e.VAD_ERROR=`vad_error`,e.CHUNK_LENGTH_EXCEEDED=`chunk_length_exceeded`,e.CHUNK_LIMIT_REACHED=`chunk_limit_reached`,e.CHUNK_CREATION_FAILED=`chunk_creation_failed`,e.WORKER_POST_FAILED=`worker_post_failed`,e.SESSION_CREATION_FAILED=`session_creation_failed`,e.RECORDER_INIT_FAILED=`recorder_init_failed`,e.RECORDER_START_FAILED=`recorder_start_failed`,e.VAD_START_FAILED=`vad_start_failed`,e.STOP_FAILED=`stop_failed`,e.INTERNAL_RETRY_FAILED=`internal_retry_failed`,e.SESSION_END_FAILED=`session_end_failed`,e.UNSUPPORTED_STORAGE_PROVIDER=`unsupported_storage_provider`,e}({}),$c=class e extends Error{constructor(t,n=Qc.INTERNAL_ERROR,r,i){super(t),this.name=`ScribeError`,this.code=n,this.httpStatus=r,this.details=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}static fromApiError(t,n){return new e(t.message,t.code,n,t.details)}toJSON(){return{name:this.name,message:this.message,code:this.code,httpStatus:this.httpStatus,details:this.details}}},el=class extends $c{constructor(e,t,n){super(e,Qc.UPLOAD_FAILED,void 0,n),this.name=`UploadError`,this.failedFiles=t}toJSON(){return{...super.toJSON(),failedFiles:this.failedFiles}}},tl=class extends $c{constructor(e){super(`Storage provider '${e||`(none)`}' is not supported by this SDK build.`,Qc.UNSUPPORTED_STORAGE_PROVIDER,void 0,{provider:e}),this.name=`UnsupportedStorageProviderError`,this.provider=e}},nl=bc({uploadData:bc({url:qs().min(1,`uploadData.url is required`),fields:Ec(qs(),qs())}),folderPath:qs().optional(),txn_id:qs().optional()}),rl=`key`,il="${filename}",al=`Content-Type`,ol=`audio/mp3`,sl=class{constructor(){this.name=`aws`}prepareUpload({fileName:e,blob:t,upload:n}){let r=nl.safeParse(n);if(!r.success)throw new el(`Invalid AWS upload payload in session response: ${r.error.message}`,[e]);let{uploadData:i}=r.data,a={};for(let[t,n]of Object.entries(i.fields))a[t]=t===rl?n.split(il).join(e):n;if(!(al in a)){let e=t?.type;a[al]=e&&e.startsWith(`audio/`)?e:ol}return{url:i.url,method:`POST`,bodyMode:`multipart`,formFields:a,fileFieldName:`file`,headers:{},attachAuth:!1}}},cl=qs().trim().min(1,`upload_url is required`),ll=`Content-Type`,ul=`audio/mp3`,dl=new Set([`audio/webm;codecs=opus`,`audio/wav`,`audio/ogg`,`audio/ogg;codecs=opus`,`audio/mp4`,`audio/m4a`,`audio/mp3`]),fl={mp3:`audio/mp3`,webm:`audio/webm;codecs=opus`,wav:`audio/wav`,ogg:`audio/ogg`,m4a:`audio/m4a`,mp4:`audio/mp4`};function pl(e,t){let n=fl[e.split(`.`).pop()?.toLowerCase()??``];if(n)return n;let r=t?.type;return r&&dl.has(r)?r:ul}var ml=class{constructor(){this.name=`backend`}prepareUpload({fileName:e,blob:t,upload:n}){let r=cl.safeParse(n);if(!r.success)throw new el(`Invalid backend upload payload: expected an upload_url string, got ${typeof n}`,[e]);return{url:`${r.data.replace(/\/+$/,``)}/${encodeURIComponent(e)}`,method:`POST`,bodyMode:`binary`,headers:{[ll]:pl(e,t)},attachAuth:!0}}},hl={aws:()=>new sl,backend:()=>new ml};function gl(e){return typeof e==`string`?e.trim().toLowerCase():``}function _l(e){let t=hl[gl(e)];if(!t)throw new tl(e);return t()}var vl=2,yl=2e3,bl=1e4,xl,Sl=[],Cl=new Map,wl=null,Tl=new Map;function El(e,t){let n=Tl.get(e);if(n){Tl.delete(e);for(let e of n)e(t)}}function Dl(e,t){try{e.postMessage(t)}catch{}}function Ol(e){for(let t of Sl)Dl(t,e)}function kl(){return new Promise(e=>{let t=wl;wl=()=>{t?.(),e()},setTimeout(()=>{e()},bl)})}function Al(e){return new Promise(t=>{let n=Tl.get(e);n||(n=new Set,Tl.set(e,n)),n.add(t),setTimeout(()=>{let n=Tl.get(e);n?.has(t)&&(n.delete(t),n.size===0&&Tl.delete(e),t(null))},bl)})}function jl(e,t,n,r){let i={...e.headers};e.attachAuth&&(Object.assign(i,r),xl&&(i.Authorization=`Bearer ${xl}`));let a;if(e.bodyMode===`multipart`&&e.formFields){let r=new FormData;for(let[t,n]of Object.entries(e.formFields))r.append(t,n);r.append(e.fileFieldName??`file`,n,t),a=r}else a=n,i[`Content-Type`]||=`audio/mp3`;return{method:e.method,body:a,headers:i,credentials:e.attachAuth?`include`:`omit`}}async function Ml(e,t,n,r,i){Dl(e,{type:`upload_url_required`,fileName:n});let a=await Al(e);if(!a)return i;try{return _l(t).prepareUpload({fileName:n,blob:r,upload:a})}catch{return i}}async function Nl(e,t,n,r,i,a){let o=`Upload failed after retries`,s;for(let c=0;c<=vl;c++)try{let l=await fetch(e.url,jl(e,t,n,r));if(l.ok)return{success:!0};if(s=l.status,o=await Pl(l),l.status===401&&e.attachAuth){Ol({type:`token_required`}),await kl();continue}if(c<vl){e=await Ml(a,i,t,n,e),await Fl(yl);continue}return{success:!1,error:o,statusCode:s}}catch(r){o=r?.message??`Network error`,c<vl&&(e=await Ml(a,i,t,n,e),await Fl(yl))}return{success:!1,error:o,statusCode:s}}async function Pl(e){try{let t=await e.json();return t?.error?.message??t?.message??e.statusText??`Request failed`}catch{return e.statusText??`HTTP ${e.status}`}}function Fl(e){return new Promise(t=>setTimeout(t,e))}async function Il(e,t,n,r,i,a){try{let o=Xn(e);if(!o){Dl(a,{type:`upload_failed`,fileName:t,error:`MP3 encoding failed`});return}Dl(a,{type:`chunk_encoded`,fileName:t,chunkData:o.chunks});let s;try{s=_l(n).prepareUpload({fileName:t,blob:o.blob,upload:r})}catch(e){Dl(a,{type:`upload_failed`,fileName:t,error:e?.message??`Failed to prepare upload`,chunkData:o.chunks});return}let c=await Nl(s,t,o.blob,i,n,a);c.success?Dl(a,{type:`upload_success`,fileName:t}):Dl(a,{type:`upload_failed`,fileName:t,error:c.error??`Upload failed after retries`,chunkData:o.chunks})}catch(e){Dl(a,{type:`upload_failed`,fileName:t,error:e?.message??`Unknown error`})}}function Ll(e,t){switch(e.type){case`compress_and_upload`:{Cl.has(t)||Cl.set(t,new Set);let n=Cl.get(t),r=Il(e.audioFrames,e.fileName,e.storageProvider,e.upload,e.headers,t);n.add(r),r.finally(()=>n.delete(r));break}case`wait_for_all_uploads`:{let e=Cl.get(t)??new Set;Promise.all(e).then(()=>{Dl(t,{type:`all_uploads_complete`})});break}case`update_auth_token`:xl=e.token,wl&&=(wl(),null);break;case`update_upload_url`:El(t,e.upload);break;case`terminate`:{let e=Sl.indexOf(t);e>=0&&Sl.splice(e,1),Cl.delete(t),El(t,null);try{t.close()}catch{}Sl.length===0&&self.close();break}}}var Rl=self;Rl.onconnect=e=>{let t=e.ports[0];Sl.push(t),t.onmessage=e=>{Ll(e.data,t)},t.start()}})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "med-scribe-alliance-ts-sdk",
3
- "version": "2.0.52",
3
+ "version": "2.0.53",
4
4
  "description": "TypeScript SDK for the MedScribe Alliance Protocol",
5
5
  "main": "dist/index.mjs",
6
6
  "module": "dist/index.mjs",