{"version":3,"file":"client.cjs","names":["HttpClient","sleep"],"sources":["../../../src/v2/prerecorded/client.ts"],"sourcesContent":["import { sleep } from '../../helpers.js'\nimport type { InternalGladiaClientOptions } from '../../internal_types.js'\nimport { HttpClient } from '../../network/httpClient.js'\nimport type {\n  PreRecordedV2AudioUploadResponse,\n  PreRecordedV2InitTranscriptionRequest,\n  PreRecordedV2InitTranscriptionResponse,\n  PreRecordedV2Response,\n} from './generated-types.js'\n\nfunction isUrl(s: string): boolean {\n  try {\n    const u = new URL(s)\n    return u.protocol === 'http:' || u.protocol === 'https:'\n  } catch {\n    return false\n  }\n}\n\nfunction resolveFlowDeadlineMs(\n  timeout: number | null | undefined,\n  configuredMs: number\n): number | null {\n  if (timeout === null) return null\n  if (timeout !== undefined) return timeout\n  return configuredMs\n}\n\n/**\n * Client used to interact with Gladia Pre-Recorded Speech-To-Text API.\n */\nexport class PreRecordedV2Client {\n  private httpClient: HttpClient\n  private readonly prerecordedTimeouts: InternalGladiaClientOptions['prerecordedTimeouts']\n\n  constructor(options: InternalGladiaClientOptions) {\n    const httpBaseUrl = new URL(options.apiUrl)\n    httpBaseUrl.protocol = httpBaseUrl.protocol.replace(/^ws/, 'http')\n    this.prerecordedTimeouts = options.prerecordedTimeouts\n    this.httpClient = new HttpClient({\n      baseUrl: httpBaseUrl,\n      headers: options.httpHeaders,\n      ...(options.region ? { queryParams: { region: options.region } } : {}),\n      retry: options.httpRetry,\n      timeout: options.httpTimeout,\n    })\n  }\n\n  /**\n   * Upload a local file and return an audio URL for transcription.\n   *\n   * @param audio_url - A file path (string), `File`, or `Blob`. When a string, it must be a local file path; URLs are not accepted.\n   * @returns The upload response containing `audio_url` and `audio_metadata`.\n   * @throws Error if `audio_url` is a string that is a URL (use a local file path, File, or Blob instead).\n   */\n  async uploadFile(audio_url: string | File | Blob): Promise<PreRecordedV2AudioUploadResponse> {\n    if (typeof audio_url === 'string' && isUrl(audio_url)) {\n      throw new Error(\n        'Expected a file path; URLs are not accepted by uploadFile. Use a local file path, File, or Blob.'\n      )\n    }\n\n    const formData = new FormData()\n\n    if (typeof audio_url === 'string') {\n      if (typeof process === 'undefined' || !process.versions?.node) {\n        throw new Error(\n          'Upload by file path is only supported in Node.js. In the browser, use a File or Blob.'\n        )\n      }\n      const { readFileSync } = await import('fs')\n      const { basename } = await import('path')\n      const fileBuffer = readFileSync(audio_url)\n      const filename = basename(audio_url)\n      const blob = new Blob([fileBuffer], { type: 'application/octet-stream' })\n      formData.append('audio', blob, filename)\n    } else {\n      formData.append('audio', audio_url)\n    }\n\n    return this.httpClient.post<PreRecordedV2AudioUploadResponse>('/v2/upload', {\n      body: formData,\n      requestTimeout: this.prerecordedTimeouts.uploadFile,\n    })\n  }\n\n  /**\n   * Create a new pre-recorded transcription job.\n   *\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/init\n   * @param options - The transcription request parameters including `audio_url`.\n   * @returns A response containing the job `id` and `result_url` to poll.\n   */\n  async create(\n    options: PreRecordedV2InitTranscriptionRequest\n  ): Promise<PreRecordedV2InitTranscriptionResponse> {\n    return this.httpClient.post<PreRecordedV2InitTranscriptionResponse>('/v2/pre-recorded', {\n      body: JSON.stringify(options),\n      headers: { 'content-type': 'application/json' },\n      requestTimeout: this.prerecordedTimeouts.create,\n    })\n  }\n\n  /**\n   * Create a new pre-recorded transcription job with an untyped request (e.g. raw JSON).\n   * Prefer {@link create} for type-safe requests.\n   *\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/init\n   * @param options - Raw request object (must include `audio_url` at runtime).\n   * @returns A response containing the job `id` and `result_url` to poll.\n   */\n  async createUntyped(\n    options: Record<string, unknown>\n  ): Promise<PreRecordedV2InitTranscriptionResponse> {\n    return this.httpClient.post<PreRecordedV2InitTranscriptionResponse>('/v2/pre-recorded', {\n      body: JSON.stringify(options),\n      headers: { 'content-type': 'application/json' },\n      requestTimeout: this.prerecordedTimeouts.create,\n    })\n  }\n\n  /**\n   * Get a pre-recorded transcription job by ID.\n   *\n   * @param jobId - The UUID of the transcription job.\n   * @returns The full job response including status and result if done.\n   */\n  async get(jobId: string): Promise<PreRecordedV2Response> {\n    return this.httpClient.get<PreRecordedV2Response>(`/v2/pre-recorded/${jobId}`, {\n      requestTimeout: this.prerecordedTimeouts.get,\n    })\n  }\n\n  /**\n   * Delete a pre-recorded transcription job.\n   *\n   * @param jobId - The UUID of the transcription job to delete.\n   * @returns `true` if the job was deleted successfully (HTTP 202), `false` if the server responded with another 2xx status.\n   * @throws When the server responds with an error HTTP status (e.g. 404).\n   */\n  async delete(jobId: string): Promise<boolean> {\n    const response = await this.httpClient.delete<Response>(`/v2/pre-recorded/${jobId}`, {\n      rawResponse: true,\n      requestTimeout: this.prerecordedTimeouts.delete,\n    })\n    return response.status === 202\n  }\n\n  /**\n   * Download the audio file for a pre-recorded transcription job.\n   *\n   * @param jobId - The UUID of the transcription job.\n   * @returns The raw audio file as an `ArrayBuffer`.\n   */\n  async getFile(jobId: string): Promise<ArrayBuffer> {\n    const response = await this.httpClient.get<Response>(`/v2/pre-recorded/${jobId}/file`, {\n      requestTimeout: this.prerecordedTimeouts.getFile,\n    })\n    return response.arrayBuffer()\n  }\n\n  /**\n   * Poll a pre-recorded transcription job until it completes.\n   *\n   * Repeatedly fetches the job status until it reaches `\"done\"` or `\"error\"`.\n   *\n   * @param jobId - The UUID of the transcription job.\n   * @param interval - Milliseconds between polling attempts (default: 3000).\n   * @param timeout - Maximum milliseconds to wait before throwing. Omitted uses\n   *   `GladiaClientOptions.prerecordedTimeouts.poll`. `null` means no deadline.\n   * @returns The completed job response.\n   * @throws If the job status is `\"error\"` or the timeout is exceeded.\n   */\n  async poll(\n    jobId: string,\n    { interval = 3_000, timeout }: { interval?: number; timeout?: number | null } = {}\n  ): Promise<PreRecordedV2Response> {\n    const start = Date.now()\n    const deadlineMs = resolveFlowDeadlineMs(timeout, this.prerecordedTimeouts.poll)\n    while (true) {\n      const result = await this.get(jobId)\n      if (result.status === 'done') {\n        return result\n      }\n      if (result.status === 'error') {\n        throw new Error(`Pre-recorded job ${jobId} failed with error code: ${result.error_code}`)\n      }\n      if (deadlineMs !== null && Date.now() - start >= deadlineMs) {\n        throw new Error(`Pre-recorded job ${jobId} did not complete within ${deadlineMs}ms`)\n      }\n      await sleep(interval)\n    }\n  }\n\n  /**\n   * Create a pre-recorded transcription job and poll until completion.\n   *\n   * Convenience method that combines `create` and `poll`.\n   *\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/init\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/get\n   * @param options - The transcription request parameters including `audio_url`.\n   * @param interval - Milliseconds between polling attempts (default: 3000).\n   * @param timeout - Maximum milliseconds to wait before throwing. Omitted uses\n   *   `GladiaClientOptions.prerecordedTimeouts.createAndPoll`. `null` means no deadline.\n   * @returns The completed job response.\n   */\n  async createAndPoll(\n    options: PreRecordedV2InitTranscriptionRequest,\n    { interval = 3_000, timeout }: { interval?: number; timeout?: number | null } = {}\n  ): Promise<PreRecordedV2Response> {\n    const initResponse = await this.create(options)\n    return this.poll(initResponse.id, {\n      interval,\n      timeout: resolveFlowDeadlineMs(timeout, this.prerecordedTimeouts.createAndPoll),\n    })\n  }\n\n  /**\n   * Create a pre-recorded transcription job with an untyped request and poll until completion.\n   * Prefer {@link createAndPoll} for type-safe requests.\n   *\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/init\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/get\n   * @param options - Raw request object (must include `audio_url` at runtime).\n   * @param interval - Milliseconds between polling attempts (default: 3000).\n   * @param timeout - Maximum milliseconds to wait before throwing. Omitted uses\n   *   `GladiaClientOptions.prerecordedTimeouts.createAndPoll`. `null` means no deadline.\n   * @returns The completed job response.\n   */\n  async createAndPollUntyped(\n    options: Record<string, unknown>,\n    { interval = 3_000, timeout }: { interval?: number; timeout?: number | null } = {}\n  ): Promise<PreRecordedV2Response> {\n    const initResponse = await this.createUntyped(options)\n    return this.poll(initResponse.id, {\n      interval,\n      timeout: resolveFlowDeadlineMs(timeout, this.prerecordedTimeouts.createAndPoll),\n    })\n  }\n\n  /**\n   * Upload a local file or use a URL (YouTube, S3, etc.) and transcribe it, polling until completion.\n   *\n   * Convenience method that combines `uploadFile` (when `audio_url` is a path or File/Blob), `create`, and `poll`.\n   * When `audio_url` is a string URL, skips upload and calls create with that URL directly.\n   *\n   * @param audio_url - A file path (string), URL (string), `File`, or `Blob`. When a string, can be either a local file path or an http(s) URL.\n   * @param options - Optional transcription options (typed; `audio_url` is set from the uploaded/URL audio).\n   * @param interval - Milliseconds between polling attempts (default: 3000).\n   * @param timeout - Maximum milliseconds for polling after the job is submitted. Omitted uses\n   *   `GladiaClientOptions.prerecordedTimeouts.transcribe`. `null` means no deadline.\n   * @returns The completed job response.\n   */\n  async transcribe(\n    audio_url: string | File | Blob,\n    options?: Omit<PreRecordedV2InitTranscriptionRequest, 'audio_url'>,\n    { interval = 3_000, timeout }: { interval?: number; timeout?: number | null } = {}\n  ): Promise<PreRecordedV2Response> {\n    const uploadResponse =\n      typeof audio_url === 'string' && isUrl(audio_url)\n        ? audio_url\n        : await this.uploadFile(audio_url)\n    const jobAudioUrl =\n      typeof uploadResponse === 'string' ? uploadResponse : uploadResponse.audio_url\n    return this.createAndPoll(\n      { ...(options ?? {}), audio_url: jobAudioUrl },\n      {\n        interval,\n        timeout: resolveFlowDeadlineMs(timeout, this.prerecordedTimeouts.transcribe),\n      }\n    )\n  }\n\n  /**\n   * Transcribe audio with untyped options (e.g. raw JSON). Prefer {@link transcribe} for type-safe options.\n   *\n   * @see https://docs.gladia.io/api-reference/v2/upload/audio-file\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/init\n   * @see https://docs.gladia.io/api-reference/v2/pre-recorded/get\n   * @param audio_url - A file path (string), URL (string), `File`, or `Blob`.\n   * @param options - Optional raw request options (merged with `audio_url` from upload/URL).\n   * @param interval - Milliseconds between polling attempts (default: 3000).\n   * @param timeout - Maximum milliseconds for polling after the job is submitted. Omitted uses\n   *   `GladiaClientOptions.prerecordedTimeouts.transcribe`. `null` means no deadline.\n   * @returns The completed job response.\n   */\n  async transcribeUntyped(\n    audio_url: string | File | Blob,\n    options?: Record<string, unknown>,\n    { interval = 3_000, timeout }: { interval?: number; timeout?: number | null } = {}\n  ): Promise<PreRecordedV2Response> {\n    const uploadResponse =\n      typeof audio_url === 'string' && isUrl(audio_url)\n        ? audio_url\n        : await this.uploadFile(audio_url)\n    const jobAudioUrl =\n      typeof uploadResponse === 'string' ? uploadResponse : uploadResponse.audio_url\n    return this.createAndPollUntyped(\n      { ...(options ?? {}), audio_url: jobAudioUrl },\n      {\n        interval,\n        timeout: resolveFlowDeadlineMs(timeout, this.prerecordedTimeouts.transcribe),\n      }\n    )\n  }\n}\n"],"mappings":";;;;AAUA,SAAS,MAAM,GAAoB;AACjC,KAAI;EACF,MAAM,IAAI,IAAI,IAAI,EAAE;AACpB,SAAO,EAAE,aAAa,WAAW,EAAE,aAAa;SAC1C;AACN,SAAO;;;AAIX,SAAS,sBACP,SACA,cACe;AACf,KAAI,YAAY,KAAM,QAAO;AAC7B,KAAI,YAAY,OAAW,QAAO;AAClC,QAAO;;;;;AAMT,IAAa,sBAAb,MAAiC;CAC/B,AAAQ;CACR,AAAiB;CAEjB,YAAY,SAAsC;EAChD,MAAM,cAAc,IAAI,IAAI,QAAQ,OAAO;AAC3C,cAAY,WAAW,YAAY,SAAS,QAAQ,OAAO,OAAO;AAClE,OAAK,sBAAsB,QAAQ;AACnC,OAAK,aAAa,IAAIA,8BAAW;GAC/B,SAAS;GACT,SAAS,QAAQ;GACjB,GAAI,QAAQ,SAAS,EAAE,aAAa,EAAE,QAAQ,QAAQ,QAAQ,EAAE,GAAG,EAAE;GACrE,OAAO,QAAQ;GACf,SAAS,QAAQ;GAClB,CAAC;;;;;;;;;CAUJ,MAAM,WAAW,WAA4E;AAC3F,MAAI,OAAO,cAAc,YAAY,MAAM,UAAU,CACnD,OAAM,IAAI,MACR,mGACD;EAGH,MAAM,WAAW,I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