assemblyai 4.35.3 → 4.36.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +98 -0
  3. package/dist/assemblyai.streaming.umd.js +26 -11
  4. package/dist/assemblyai.streaming.umd.min.js +1 -1
  5. package/dist/assemblyai.umd.js +486 -83
  6. package/dist/assemblyai.umd.min.js +1 -1
  7. package/dist/browser.mjs +430 -80
  8. package/dist/bun.mjs +420 -69
  9. package/dist/deno.mjs +420 -69
  10. package/dist/index.cjs +479 -76
  11. package/dist/index.mjs +477 -77
  12. package/dist/node.cjs +418 -64
  13. package/dist/node.mjs +416 -65
  14. package/dist/services/base.d.ts +1 -0
  15. package/dist/services/index.d.ts +7 -1
  16. package/dist/services/sync/index.d.ts +1 -0
  17. package/dist/services/sync/service.d.ts +48 -0
  18. package/dist/streaming.browser.mjs +24 -11
  19. package/dist/streaming.cjs +25 -10
  20. package/dist/streaming.mjs +25 -10
  21. package/dist/types/index.d.ts +1 -0
  22. package/dist/types/services/index.d.ts +1 -0
  23. package/dist/types/streaming/index.d.ts +6 -1
  24. package/dist/types/sync/index.d.ts +133 -0
  25. package/dist/utils/errors/index.d.ts +1 -0
  26. package/dist/utils/errors/sync.d.ts +20 -0
  27. package/dist/workerd.mjs +424 -73
  28. package/package.json +1 -1
  29. package/src/services/base.ts +18 -8
  30. package/src/services/index.ts +19 -0
  31. package/src/services/streaming/service.ts +17 -6
  32. package/src/services/sync/index.ts +1 -0
  33. package/src/services/sync/service.ts +369 -0
  34. package/src/types/index.ts +1 -0
  35. package/src/types/services/index.ts +1 -0
  36. package/src/types/streaming/index.ts +6 -1
  37. package/src/types/sync/index.ts +145 -0
  38. package/src/utils/errors/index.ts +2 -0
  39. package/src/utils/errors/sync.ts +25 -0
package/dist/bun.mjs CHANGED
@@ -1,5 +1,10 @@
1
1
  import ws from 'ws';
2
2
 
3
+ /**
4
+ * The default speech model for synchronous transcription.
5
+ */
6
+ const defaultSyncSpeechModel = "universal-3-5-pro";
7
+
3
8
  /**
4
9
  * Thrown when `DualChannelCapture` is constructed in a non-browser environment
5
10
  * (no `globalThis.AudioContext`). The helper is intentionally surfaced from the
@@ -13,6 +18,8 @@ class BrowserOnlyError extends Error {
13
18
  }
14
19
  }
15
20
 
21
+ const readFile = async (path) => Bun.file(path).stream();
22
+
16
23
  const DEFAULT_FETCH_INIT = {
17
24
  cache: "no-store",
18
25
  };
@@ -30,7 +37,7 @@ if (typeof navigator !== "undefined" && navigator.userAgent) {
30
37
  defaultUserAgentString += navigator.userAgent;
31
38
  }
32
39
  const defaultUserAgent = {
33
- sdk: { name: "JavaScript", version: "4.35.3" },
40
+ sdk: { name: "JavaScript", version: "4.36.3" },
34
41
  };
35
42
  if (typeof process !== "undefined") {
36
43
  if (process.versions.node && defaultUserAgentString.indexOf("Node") === -1) {
@@ -69,12 +76,15 @@ class BaseService {
69
76
  this.userAgent = buildUserAgent(params.userAgent || {});
70
77
  }
71
78
  }
72
- async fetch(input, init) {
79
+ async fetchResponse(input, init) {
73
80
  init = { ...DEFAULT_FETCH_INIT, ...init };
74
81
  let headers = {
75
82
  Authorization: this.params.apiKey,
76
- "Content-Type": "application/json",
77
83
  };
84
+ // FormData bodies must let fetch set the multipart boundary itself.
85
+ if (!(init.body instanceof FormData)) {
86
+ headers["Content-Type"] = "application/json";
87
+ }
78
88
  if (DEFAULT_FETCH_INIT?.headers)
79
89
  headers = { ...headers, ...DEFAULT_FETCH_INIT.headers };
80
90
  if (init?.headers)
@@ -85,7 +95,10 @@ class BaseService {
85
95
  init.headers = headers;
86
96
  if (!input.startsWith("http"))
87
97
  input = this.params.baseUrl + input;
88
- const response = await fetch(input, init);
98
+ return await fetch(input, init);
99
+ }
100
+ async fetch(input, init) {
101
+ const response = await this.fetchResponse(input, init);
89
102
  if (response.status >= 400) {
90
103
  let json;
91
104
  const text = await response.text();
@@ -110,58 +123,342 @@ class BaseService {
110
123
  }
111
124
  }
112
125
 
113
- class LemurService extends BaseService {
114
- summary(params, signal) {
115
- return this.fetchJson("/lemur/v3/generate/summary", {
116
- method: "POST",
117
- body: JSON.stringify(params),
118
- signal,
119
- });
120
- }
121
- questionAnswer(params, signal) {
122
- return this.fetchJson("/lemur/v3/generate/question-answer", {
123
- method: "POST",
124
- body: JSON.stringify(params),
125
- signal,
126
- });
126
+ /**
127
+ * Error thrown when a synchronous transcription request fails.
128
+ */
129
+ class SyncTranscriptError extends Error {
130
+ /**
131
+ * Create a new SyncTranscriptError.
132
+ * @param message - The human-readable error message.
133
+ * @param status - The HTTP status code of the failed request.
134
+ * @param errorCode - Machine-readable code — the snake_cased
135
+ * problem-details `title` from the server (e.g. `bad_audio`,
136
+ * `audio_too_large`, `capacity_exceeded`, `inference_timeout`).
137
+ * @param retryAfter - Seconds to wait before retrying, from the
138
+ * `Retry-After` header on 429/503 responses.
139
+ */
140
+ constructor(message, status, errorCode, retryAfter) {
141
+ super(message);
142
+ this.status = status;
143
+ this.errorCode = errorCode;
144
+ this.retryAfter = retryAfter;
145
+ this.name = "SyncTranscriptError";
127
146
  }
128
- actionItems(params, signal) {
129
- return this.fetchJson("/lemur/v3/generate/action-items", {
130
- method: "POST",
131
- body: JSON.stringify(params),
132
- signal,
133
- });
147
+ }
148
+
149
+ function getPath(path) {
150
+ if (path.startsWith("http"))
151
+ return null;
152
+ if (path.startsWith("https"))
153
+ return null;
154
+ if (path.startsWith("data:"))
155
+ return null;
156
+ if (path.startsWith("file://"))
157
+ return path.substring(7);
158
+ if (path.startsWith("file:"))
159
+ return path.substring(5);
160
+ return path;
161
+ }
162
+
163
+ // Canonical paths since the sync API gained a /v1 prefix (#18103); the
164
+ // unprefixed routes remain served for SDK versions that predate it.
165
+ const transcribeEndpoint = "/v1/transcribe";
166
+ const warmEndpoint = "/v1/warm";
167
+ const modelHeader = "X-AAI-Model";
168
+ // Kept above the server's 30 s deadline so the client doesn't race it.
169
+ const defaultTimeoutMs = 60_000;
170
+ const warmTimeoutMs = 10_000;
171
+ const maxPromptLength = 4096;
172
+ const maxKeytermsPromptLength = 2048;
173
+ const maxContextTurns = 100;
174
+ const maxContextLength = 4096;
175
+ // Extensions that signal raw S16LE PCM rather than a WAV container.
176
+ const pcmSuffixes = [".pcm", ".raw"];
177
+ /**
178
+ * The synchronous transcription service: audio in, transcript out,
179
+ * one request.
180
+ *
181
+ * Unlike `client.transcripts` (which submits a job to the async API and
182
+ * polls for completion), `SyncTranscriber` posts the audio to the sync
183
+ * API and returns the finished transcript in the HTTP response. There is no
184
+ * job id or status to poll. Accepts a local file path, raw audio bytes, a
185
+ * Blob, or a readable stream — but not a URL.
186
+ */
187
+ class SyncTranscriber extends BaseService {
188
+ /**
189
+ * Create a new synchronous transcription service.
190
+ * @param params - The parameters to use for the service.
191
+ */
192
+ constructor(params) {
193
+ super(params);
134
194
  }
135
- task(params, signal) {
136
- return this.fetchJson("/lemur/v3/generate/task", {
195
+ /**
196
+ * Transcribe audio and return the finished transcript in one request.
197
+ * @param audio - A local file path, raw audio bytes, a Blob, or a readable
198
+ * stream. Raw PCM also requires `sample_rate` and `channels` on the config.
199
+ * @param config - Options for this transcription request.
200
+ * @param options - Client-side options, such as the request timeout.
201
+ * @returns A promise that resolves to the finished transcript.
202
+ * @throws SyncTranscriptError when the request fails.
203
+ */
204
+ async transcribe(audio, config = {}, options = {}) {
205
+ const { bytes, filename, contentType } = await resolveAudio(audio, config);
206
+ const body = new FormData();
207
+ body.append("audio", new Blob([bytes], { type: contentType }), filename);
208
+ const configJson = buildConfigJson(config);
209
+ if (configJson) {
210
+ body.append("config", new Blob([JSON.stringify(configJson)], { type: "application/json" }));
211
+ }
212
+ const response = await this.fetchResponse(transcribeEndpoint, {
137
213
  method: "POST",
138
- body: JSON.stringify(params),
139
- signal,
214
+ body,
215
+ headers: { [modelHeader]: config.model ?? defaultSyncSpeechModel },
216
+ signal: AbortSignal.timeout(options.timeout ?? defaultTimeoutMs),
140
217
  });
141
- }
142
- getResponse(id, signal) {
143
- return this.fetchJson(`/lemur/v3/${id}`, { signal });
218
+ if (response.status !== 200)
219
+ throw await errorFromResponse(response);
220
+ return (await response.json());
144
221
  }
145
222
  /**
146
- * Delete the data for a previously submitted LeMUR request.
147
- * @param id - ID of the LeMUR request
148
- * @param signal - Optional AbortSignal to cancel the request
223
+ * Open the connection to the sync API ahead of time.
224
+ *
225
+ * The sync API is a single request/response, so a `transcribe()` that
226
+ * opens its connection on demand pays the full DNS + TCP + TLS handshake
227
+ * on the critical path. Call `warm()` as soon as you know audio is coming —
228
+ * typically while the clip is still being recorded — so the next
229
+ * `transcribe()` reuses the already-open connection. `warm()` is idempotent
230
+ * and cheap; call it shortly before `transcribe()` so the pooled connection
231
+ * hasn't idled out.
232
+ * @param params - Optionally the model to route the probe to, so the warmed
233
+ * connection lands on the same backend as the eventual transcription.
234
+ * @returns A promise that resolves to `true` once the connection is open
235
+ * (any HTTP response — even a non-200 — means the socket is
236
+ * established), or `false` if the connection could not be opened.
149
237
  */
150
- purgeRequestData(id, signal) {
151
- return this.fetchJson(`/lemur/v3/${id}`, {
152
- method: "DELETE",
153
- signal,
154
- });
238
+ async warm(params) {
239
+ try {
240
+ await this.fetchResponse(warmEndpoint, {
241
+ method: "GET",
242
+ headers: { [modelHeader]: params?.model ?? defaultSyncSpeechModel },
243
+ signal: AbortSignal.timeout(warmTimeoutMs),
244
+ });
245
+ return true;
246
+ }
247
+ catch {
248
+ return false;
249
+ }
155
250
  }
156
251
  }
157
-
158
- const { WritableStream } = typeof window !== "undefined"
159
- ? window
160
- : typeof global !== "undefined"
161
- ? global
162
- : globalThis;
163
-
164
- const factory = (url, params) => new ws(url, params);
252
+ /**
253
+ * Read the audio input into bytes and decide its multipart content type.
254
+ *
255
+ * PCM is selected when the source has a `.pcm`/`.raw` extension or when
256
+ * `sample_rate`/`channels` are set on the config (the fields the sync API
257
+ * requires only for raw PCM) — and both must then be present. Everything
258
+ * else is treated as a WAV container. URLs are rejected — the sync API has
259
+ * no URL ingestion.
260
+ */
261
+ async function resolveAudio(input, config) {
262
+ let bytes;
263
+ let filename;
264
+ let suffix = "";
265
+ if (typeof input === "string") {
266
+ if (/^https?:\/\//i.test(input)) {
267
+ throw new Error("SyncTranscriber does not accept URLs. Pass a local file path or " +
268
+ "audio bytes, or use client.transcripts for URL/async transcription.");
269
+ }
270
+ if (input.startsWith("data:")) {
271
+ bytes = dataUrlToBytes(input);
272
+ }
273
+ else {
274
+ const path = getPath(input) ?? input;
275
+ bytes = await readStream(await readFile(path));
276
+ filename = basename(path);
277
+ suffix = extname(filename);
278
+ }
279
+ }
280
+ else if (input instanceof Uint8Array) {
281
+ bytes = input;
282
+ }
283
+ else if (input instanceof ArrayBuffer) {
284
+ bytes = new Uint8Array(input);
285
+ }
286
+ else if (input instanceof Blob) {
287
+ bytes = new Uint8Array(await input.arrayBuffer());
288
+ // File instances carry a name; the File global itself needs Node >= 20.
289
+ const name = input.name;
290
+ if (name) {
291
+ filename = basename(name);
292
+ suffix = extname(filename);
293
+ }
294
+ }
295
+ else if (isWebReadableStream(input)) {
296
+ bytes = await readStream(input);
297
+ }
298
+ else if (isAsyncIterable(input)) {
299
+ bytes = await readAsyncIterable(input);
300
+ // fs.ReadStream carries the path it was opened from.
301
+ const path = input.path;
302
+ if (typeof path === "string") {
303
+ filename = basename(path);
304
+ suffix = extname(filename);
305
+ }
306
+ }
307
+ else {
308
+ throw new TypeError("unsupported audio input type");
309
+ }
310
+ const wantsPcm = config.sample_rate !== undefined || config.channels !== undefined;
311
+ const isPcm = pcmSuffixes.includes(suffix) || wantsPcm;
312
+ if (isPcm &&
313
+ (config.sample_rate === undefined || config.channels === undefined)) {
314
+ throw new Error("raw PCM audio requires both sample_rate and channels in the config");
315
+ }
316
+ const contentType = isPcm ? "audio/pcm" : "audio/wav";
317
+ if (!filename)
318
+ filename = isPcm ? "audio.pcm" : "audio.wav";
319
+ return { bytes, filename, contentType };
320
+ }
321
+ /**
322
+ * Serialize the config to the JSON `config` part, validating and normalizing
323
+ * field values to match the server's caps. The routing `model` is never
324
+ * included — it travels in the `X-AAI-Model` header. Returns `undefined`
325
+ * when there is nothing to send, so the part can be omitted entirely.
326
+ */
327
+ function buildConfigJson(config) {
328
+ if (config.prompt !== undefined && config.prompt.length > maxPromptLength) {
329
+ throw new Error(`prompt exceeds ${maxPromptLength} characters (got ${config.prompt.length})`);
330
+ }
331
+ const json = {};
332
+ if (config.prompt !== undefined)
333
+ json["prompt"] = config.prompt;
334
+ const keytermsPrompt = normalizeKeytermsPrompt(config.keyterms_prompt);
335
+ if (keytermsPrompt)
336
+ json["keyterms_prompt"] = keytermsPrompt;
337
+ const context = normalizeConversationContext(config.conversation_context);
338
+ if (context)
339
+ json["conversation_context"] = context;
340
+ if (config.language_codes !== undefined)
341
+ json["language_codes"] = config.language_codes;
342
+ if (config.sample_rate !== undefined)
343
+ json["sample_rate"] = config.sample_rate;
344
+ if (config.channels !== undefined)
345
+ json["channels"] = config.channels;
346
+ if (config.timestamps !== undefined)
347
+ json["timestamps"] = config.timestamps;
348
+ return Object.keys(json).length > 0 ? json : undefined;
349
+ }
350
+ function normalizeKeytermsPrompt(keytermsPrompt) {
351
+ if (!keytermsPrompt)
352
+ return undefined;
353
+ const terms = keytermsPrompt
354
+ .map((term) => term.trim())
355
+ .filter((term) => term.length > 0);
356
+ const total = terms.reduce((sum, term) => sum + term.length, 0);
357
+ if (total > maxKeytermsPromptLength) {
358
+ throw new Error(`keyterms_prompt exceeds ${maxKeytermsPromptLength} characters (got ${total})`);
359
+ }
360
+ return terms.length > 0 ? terms : undefined;
361
+ }
362
+ function normalizeConversationContext(context) {
363
+ if (context === undefined)
364
+ return undefined;
365
+ let turns = (typeof context === "string" ? [context] : context)
366
+ .map((turn) => turn.trim())
367
+ .filter((turn) => turn.length > 0);
368
+ let total = turns.reduce((sum, turn) => sum + turn.length, 0);
369
+ // Over-cap context is trimmed oldest-first, never rejected.
370
+ while (turns.length > 0 &&
371
+ (turns.length > maxContextTurns || total > maxContextLength)) {
372
+ total -= turns[0].length;
373
+ turns = turns.slice(1);
374
+ }
375
+ return turns.length > 0 ? turns : undefined;
376
+ }
377
+ /**
378
+ * Build a SyncTranscriptError from a non-200 response. The primary format
379
+ * is an RFC 9457 problem-details body (`status`/`title`/`detail`); legacy
380
+ * `{error_code, message}` and `{detail}`-only bodies are also accepted.
381
+ */
382
+ async function errorFromResponse(response) {
383
+ let errorCode;
384
+ let message;
385
+ const text = await response.text();
386
+ try {
387
+ const body = JSON.parse(text);
388
+ if (body && typeof body === "object" && !Array.isArray(body)) {
389
+ if (typeof body.error_code === "string")
390
+ errorCode = body.error_code;
391
+ if (errorCode === undefined && typeof body.title === "string") {
392
+ errorCode = body.title.toLowerCase().replace(/ /g, "_");
393
+ }
394
+ if (typeof body.detail === "string")
395
+ message = body.detail;
396
+ else if (typeof body.message === "string")
397
+ message = body.message;
398
+ }
399
+ }
400
+ catch {
401
+ if (text)
402
+ message = text;
403
+ }
404
+ if (!message) {
405
+ message = `sync transcription failed with status ${response.status}`;
406
+ }
407
+ const retryHeader = response.headers.get("retry-after");
408
+ const retryAfter = retryHeader && /^\d+$/.test(retryHeader)
409
+ ? parseInt(retryHeader, 10)
410
+ : undefined;
411
+ return new SyncTranscriptError(message, response.status, errorCode, retryAfter);
412
+ }
413
+ function basename(path) {
414
+ return path.split(/[\\/]/).pop() ?? path;
415
+ }
416
+ function extname(filename) {
417
+ const dotIndex = filename.lastIndexOf(".");
418
+ return dotIndex > 0 ? filename.slice(dotIndex).toLowerCase() : "";
419
+ }
420
+ function dataUrlToBytes(dataUrl) {
421
+ const base64 = dataUrl.split(",")[1];
422
+ const binary = atob(base64);
423
+ const bytes = new Uint8Array(binary.length);
424
+ for (let i = 0; i < binary.length; i++)
425
+ bytes[i] = binary.charCodeAt(i);
426
+ return bytes;
427
+ }
428
+ function isWebReadableStream(input) {
429
+ return typeof input?.getReader === "function";
430
+ }
431
+ function isAsyncIterable(input) {
432
+ return (typeof input?.[Symbol.asyncIterator] ===
433
+ "function");
434
+ }
435
+ async function readStream(stream) {
436
+ const chunks = [];
437
+ const reader = stream.getReader();
438
+ for (;;) {
439
+ const { done, value } = await reader.read();
440
+ if (done)
441
+ break;
442
+ chunks.push(value);
443
+ }
444
+ return concatChunks(chunks);
445
+ }
446
+ async function readAsyncIterable(iterable) {
447
+ const chunks = [];
448
+ for await (const chunk of iterable)
449
+ chunks.push(chunk);
450
+ return concatChunks(chunks);
451
+ }
452
+ function concatChunks(chunks) {
453
+ const total = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
454
+ const bytes = new Uint8Array(total);
455
+ let offset = 0;
456
+ for (const chunk of chunks) {
457
+ bytes.set(chunk, offset);
458
+ offset += chunk.length;
459
+ }
460
+ return bytes;
461
+ }
165
462
 
166
463
  const RealtimeErrorType = {
167
464
  BadSampleRate: 4000,
@@ -267,6 +564,59 @@ const StreamingErrorMessages = {
267
564
  class StreamingError extends Error {
268
565
  }
269
566
 
567
+ class LemurService extends BaseService {
568
+ summary(params, signal) {
569
+ return this.fetchJson("/lemur/v3/generate/summary", {
570
+ method: "POST",
571
+ body: JSON.stringify(params),
572
+ signal,
573
+ });
574
+ }
575
+ questionAnswer(params, signal) {
576
+ return this.fetchJson("/lemur/v3/generate/question-answer", {
577
+ method: "POST",
578
+ body: JSON.stringify(params),
579
+ signal,
580
+ });
581
+ }
582
+ actionItems(params, signal) {
583
+ return this.fetchJson("/lemur/v3/generate/action-items", {
584
+ method: "POST",
585
+ body: JSON.stringify(params),
586
+ signal,
587
+ });
588
+ }
589
+ task(params, signal) {
590
+ return this.fetchJson("/lemur/v3/generate/task", {
591
+ method: "POST",
592
+ body: JSON.stringify(params),
593
+ signal,
594
+ });
595
+ }
596
+ getResponse(id, signal) {
597
+ return this.fetchJson(`/lemur/v3/${id}`, { signal });
598
+ }
599
+ /**
600
+ * Delete the data for a previously submitted LeMUR request.
601
+ * @param id - ID of the LeMUR request
602
+ * @param signal - Optional AbortSignal to cancel the request
603
+ */
604
+ purgeRequestData(id, signal) {
605
+ return this.fetchJson(`/lemur/v3/${id}`, {
606
+ method: "DELETE",
607
+ signal,
608
+ });
609
+ }
610
+ }
611
+
612
+ const { WritableStream } = typeof window !== "undefined"
613
+ ? window
614
+ : typeof global !== "undefined"
615
+ ? global
616
+ : globalThis;
617
+
618
+ const factory = (url, params) => new ws(url, params);
619
+
270
620
  const defaultRealtimeUrl = "wss://api.assemblyai.com/v2/realtime/ws";
271
621
  const forceEndOfUtteranceMessage = `{"force_end_utterance":true}`;
272
622
  const terminateSessionMessage$1 = `{"terminate_session":true}`;
@@ -511,20 +861,6 @@ class RealtimeTranscriberFactory extends BaseService {
511
861
  class RealtimeServiceFactory extends RealtimeTranscriberFactory {
512
862
  }
513
863
 
514
- function getPath(path) {
515
- if (path.startsWith("http"))
516
- return null;
517
- if (path.startsWith("https"))
518
- return null;
519
- if (path.startsWith("data:"))
520
- return null;
521
- if (path.startsWith("file://"))
522
- return path.substring(7);
523
- if (path.startsWith("file:"))
524
- return path.substring(5);
525
- return path;
526
- }
527
-
528
864
  class TranscriptService extends BaseService {
529
865
  constructor(params, files) {
530
866
  super(params);
@@ -752,8 +1088,6 @@ class TranscriptService extends BaseService {
752
1088
  }
753
1089
  }
754
1090
 
755
- const readFile = async (path) => Bun.file(path).stream();
756
-
757
1091
  class FileService extends BaseService {
758
1092
  /**
759
1093
  * Upload a local file to AssemblyAI.
@@ -1034,6 +1368,10 @@ class StreamingTranscriber {
1034
1368
  if (!(this.token || this.apiKey)) {
1035
1369
  throw new Error("API key or temporary token is required.");
1036
1370
  }
1371
+ const isOpus = params.encoding === "opus" || params.encoding === "ogg_opus";
1372
+ if (params.sampleRate === undefined && (!isOpus || params.channels)) {
1373
+ throw new Error('`sampleRate` is required; it may only be omitted when `encoding` is "opus" or "ogg_opus" (the Opus stream is self-describing) and dual-channel mode is not used.');
1374
+ }
1037
1375
  if (params.channels) {
1038
1376
  if (params.channels.length !== 2) {
1039
1377
  throw new Error("StreamingTranscriber.channels must have exactly 2 entries.");
@@ -1059,10 +1397,12 @@ class StreamingTranscriber {
1059
1397
  "speaker-history") {
1060
1398
  this.speakerHistory = new Map();
1061
1399
  }
1062
- // 20 ms VAD frames at the transcriber's target sample rate.
1063
- this.vadFrameSamples = Math.max(1, Math.round(params.sampleRate * 0.02));
1064
- this.minChunkSamples = Math.max(1, Math.round(params.sampleRate * (MIN_CHUNK_MS / 1000)));
1065
- this.maxChunkSamples = Math.max(this.minChunkSamples, Math.round(params.sampleRate * (MAX_CHUNK_MS / 1000)));
1400
+ // 20 ms VAD frames at the transcriber's target sample rate. The
1401
+ // constructor check above guarantees sampleRate in dual-channel mode.
1402
+ const sampleRate = params.sampleRate;
1403
+ this.vadFrameSamples = Math.max(1, Math.round(sampleRate * 0.02));
1404
+ this.minChunkSamples = Math.max(1, Math.round(sampleRate * (MIN_CHUNK_MS / 1000)));
1405
+ this.maxChunkSamples = Math.max(this.minChunkSamples, Math.round(sampleRate * (MAX_CHUNK_MS / 1000)));
1066
1406
  this.channelBuffers = new Map(names.map((n) => [n, []]));
1067
1407
  this.channelSamplesReceived = new Map(names.map((n) => [n, 0]));
1068
1408
  this.channelVadFloatBuffers = new Map(names.map((n) => [n, new Float32Array(this.vadFrameSamples)]));
@@ -1080,7 +1420,9 @@ class StreamingTranscriber {
1080
1420
  if (this.token) {
1081
1421
  searchParams.set("token", this.token);
1082
1422
  }
1083
- searchParams.set("sample_rate", this.params.sampleRate.toString());
1423
+ if (this.params.sampleRate !== undefined) {
1424
+ searchParams.set("sample_rate", this.params.sampleRate.toString());
1425
+ }
1084
1426
  if (this.params.endOfTurnConfidenceThreshold) {
1085
1427
  searchParams.set("end_of_turn_confidence_threshold", this.params.endOfTurnConfidenceThreshold.toString());
1086
1428
  }
@@ -2007,6 +2349,7 @@ function float32ToPcm16(input) {
2007
2349
 
2008
2350
  const defaultBaseUrl = "https://api.assemblyai.com";
2009
2351
  const defaultStreamingUrl = "https://streaming.assemblyai.com";
2352
+ const defaultSyncUrl = "https://sync.assemblyai.com";
2010
2353
  class AssemblyAI {
2011
2354
  /**
2012
2355
  * Create a new AssemblyAI client.
@@ -2025,7 +2368,15 @@ class AssemblyAI {
2025
2368
  ...params,
2026
2369
  baseUrl: params.streamingBaseUrl || defaultStreamingUrl,
2027
2370
  });
2371
+ let syncBaseUrl = params.syncBaseUrl || defaultSyncUrl;
2372
+ if (syncBaseUrl.endsWith("/")) {
2373
+ syncBaseUrl = syncBaseUrl.slice(0, -1);
2374
+ }
2375
+ this.sync = new SyncTranscriber({
2376
+ ...params,
2377
+ baseUrl: syncBaseUrl,
2378
+ });
2028
2379
  }
2029
2380
  }
2030
2381
 
2031
- export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, TranscriptService, VadTimeline, attributeTurn, attributeWord, float32ToPcm16, rollUpTurnChannel };
2382
+ export { AssemblyAI, BrowserOnlyError, DualChannelCapture, EnergyVad, FileService, LemurService, LinearResampler, RealtimeService, RealtimeServiceFactory, RealtimeTranscriber, RealtimeTranscriberFactory, StreamingTranscriber, SyncTranscriber, SyncTranscriptError, TranscriptService, VadTimeline, attributeTurn, attributeWord, defaultSyncSpeechModel, float32ToPcm16, rollUpTurnChannel };