vidnavigator 1.0.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -22,8 +22,8 @@ import {
22
22
  NamespaceRef,
23
23
  NamespaceRefJSON,
24
24
  ExtractionSchema,
25
- ExtractionTokenUsage,
26
- ExtractionTokenUsageJSON,
25
+ UsageBlock,
26
+ UsageBlockJSON,
27
27
  CarouselInfo,
28
28
  CarouselInfoJSON,
29
29
  CarouselVideoResult,
@@ -39,27 +39,24 @@ import {
39
39
  TikTokSearchTask,
40
40
  TikTokSearchTaskJSON,
41
41
  TweetStatement,
42
- TweetStatementJSON,
42
+ AsyncJob,
43
+ AsyncJobJSON,
44
+ AsyncJobAccepted,
45
+ AsyncJobAcceptedJSON,
46
+ TikTokProfilePagination,
43
47
  } from './models';
44
- import {
45
- VidNavigatorError,
46
- AuthenticationError,
47
- BadRequestError,
48
- AccessDeniedError,
49
- NotFoundError,
50
- RateLimitExceededError,
51
- PaymentRequiredError,
52
- ServerError,
53
- StorageQuotaExceededError,
54
- GeoRestrictedError,
55
- SystemOverloadError,
56
- } from './errors';
48
+ import { VidNavigatorError, PaymentRequiredError } from './errors';
49
+ import { buildApiError } from './http';
50
+ import { Job, JobInfo, JobOperation, PollableTask, PollOptions, RunOptions, SubmitOptions } from './jobs';
57
51
 
58
52
  export * from './models';
59
53
  export * from './errors';
54
+ export * from './webhooks';
55
+ export { Job } from './jobs';
56
+ export type { TaskStatus, PollableTask, PollOptions, JobOperation, SubmitOptions, RunOptions, JobInfo } from './jobs';
60
57
 
61
58
  /** SDK version (keep in sync with package.json) */
62
- export const SDK_VERSION = '1.0.4';
59
+ export const SDK_VERSION = '2.0.0';
63
60
 
64
61
  //region --- Interfaces ---
65
62
  export interface SDKConfig {
@@ -71,6 +68,7 @@ export interface SDKConfig {
71
68
  interface ApiSuccessResponse<T> {
72
69
  status: 'success';
73
70
  data: T;
71
+ usage?: UsageBlockJSON;
74
72
  }
75
73
 
76
74
  export type TranscriptRequestPayload = {
@@ -79,26 +77,102 @@ export type TranscriptRequestPayload = {
79
77
  metadata_only?: boolean;
80
78
  fallback_to_metadata?: boolean;
81
79
  transcript_text?: boolean;
80
+ include_usage?: boolean;
82
81
  };
83
82
 
84
83
  export type TranscribeVideoPayload = {
85
84
  video_url: string;
86
85
  transcript_text?: boolean;
87
86
  all_videos?: boolean;
87
+ include_usage?: boolean;
88
+ } & WebhookOption;
89
+
90
+ /**
91
+ * Where to POST a notification when an async job finishes. Overrides the account-level default
92
+ * configured in Studio → API; pass an empty string to opt this job out of that default.
93
+ * Must be a publicly reachable https URL. This is a pass-through: polling always works either way.
94
+ */
95
+ export type WebhookOption = { webhook_url?: string };
96
+
97
+ /** Input for {@link VidNavigatorClient.transcribe}. A plain string is treated as `video_url`. */
98
+ export type TranscribeInput = {
99
+ video_url: string;
100
+ transcript_text?: boolean;
101
+ /** Instagram carousel posts only: transcribe every video in the post. */
102
+ all_videos?: boolean;
103
+ } & WebhookOption;
104
+
105
+ /** Input for {@link VidNavigatorClient.extractVideo}: a JSON `schema`, or a JSON/YAML `schemaFilePath`. */
106
+ export type ExtractVideoInput =
107
+ | ({
108
+ video_url: string;
109
+ schema: ExtractionSchema;
110
+ what_to_extract?: string;
111
+ /** Speech-to-text the audio when no platform transcript exists. Default true. */
112
+ transcribe?: boolean;
113
+ } & WebhookOption)
114
+ | ({
115
+ video_url: string;
116
+ /** Path to a JSON or YAML schema file (sent as multipart form-data). */
117
+ schemaFilePath: string;
118
+ what_to_extract?: string;
119
+ transcribe?: boolean;
120
+ } & WebhookOption);
121
+
122
+ /** Input for {@link VidNavigatorClient.tweetStatement}. A plain string is treated as `tweet_id`. */
123
+ export type TweetStatementInput = { tweet_id: string } & WebhookOption;
124
+
125
+ export type TranscriptResult = {
126
+ video_info: VideoInfo;
127
+ transcript: TranscriptOutput;
128
+ usage?: UsageBlock;
88
129
  };
89
130
 
90
131
  export type TranscribeVideoSingleResult = {
91
132
  video_info: VideoInfo;
92
133
  transcript: TranscriptOutput;
134
+ usage?: UsageBlock;
93
135
  };
94
136
 
95
137
  export type TranscribeVideoCarouselResult = {
96
138
  carousel_info: CarouselInfo;
97
139
  videos: CarouselVideoResult[];
140
+ usage?: UsageBlock;
98
141
  };
99
142
 
100
143
  export type TranscribeVideoResult = TranscribeVideoSingleResult | TranscribeVideoCarouselResult;
101
144
 
145
+ /** Snapshot of a transcription task. `result` has the same shape as {@link VidNavigatorClient.transcribe}'s return value. */
146
+ export type TranscribeAsyncJob = AsyncJob<TranscribeVideoResult>;
147
+
148
+ /** Snapshot of an extraction task. `result` is the extracted object, shaped like your schema. */
149
+ export type ExtractVideoAsyncJob = AsyncJob<Record<string, unknown>>;
150
+
151
+ /** Snapshot of a tweet claim analysis task. `result` is a {@link TweetStatement}. */
152
+ export type TweetStatementAsyncJob = AsyncJob<TweetStatement>;
153
+
154
+ export type TranscribeJob = Job<TranscribeAsyncJob, TranscribeVideoResult>;
155
+
156
+ /** Input that always yields a single-video result (the carousel shape needs `all_videos: true`). */
157
+ type SingleTranscribeInput = string | (TranscribeInput & { all_videos?: false });
158
+
159
+ /**
160
+ * {@link JobOperation} for transcription, typed so that a plain URL (or `all_videos` left off)
161
+ * resolves to {@link TranscribeVideoSingleResult}.
162
+ */
163
+ export interface TranscribeOperation extends JobOperation<string | TranscribeInput, TranscribeAsyncJob, TranscribeVideoResult> {
164
+ (input: SingleTranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoSingleResult>;
165
+ (input: string | TranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoResult>;
166
+ submit(input: SingleTranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoSingleResult>>;
167
+ submit(input: string | TranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoResult>>;
168
+ }
169
+ export type ExtractVideoJob = Job<ExtractVideoAsyncJob, ExtractDataResult>;
170
+ export type TweetStatementJob = Job<TweetStatementAsyncJob, TweetStatement>;
171
+ /** `result()` resolves to the completed task with **all** pages of `videos` collected. */
172
+ export type TikTokProfileJob = Job<TikTokProfileTask, TikTokProfileTask>;
173
+ /** `result()` resolves to the completed task with **all** pages of `results` collected. */
174
+ export type TikTokSearchJob = Job<TikTokSearchTask, TikTokSearchTask>;
175
+
102
176
  export type UploadFileSuccessResult = {
103
177
  status: 'success';
104
178
  file_id: string;
@@ -124,16 +198,83 @@ export interface ExtractDataResult {
124
198
  data: Record<string, unknown>;
125
199
  video_info?: VideoInfo;
126
200
  file_info?: FileInfo;
127
- usage?: ExtractionTokenUsage;
201
+ usage?: UsageBlock;
128
202
  }
129
203
 
204
+ export type YouTubeSearchFocus = 'relevance' | 'popularity' | 'brevity';
205
+
206
+ export type SearchYouTubePayload = {
207
+ query: string;
208
+ use_enhanced_search?: boolean;
209
+ start_year?: number;
210
+ end_year?: number;
211
+ focus?: YouTubeSearchFocus;
212
+ duration?: number;
213
+ max_results?: number;
214
+ include_usage?: boolean;
215
+ };
216
+
217
+ export type SearchYouTubeResult = {
218
+ results: VideoSearchResult[];
219
+ query: string;
220
+ total_found: number;
221
+ explanation?: string;
222
+ usage?: UsageBlock;
223
+ /** Present when a 402 partial-results response is returned. */
224
+ status?: 'success' | 'partial';
225
+ /** Present on partial results (e.g. `insufficient_credits_video_search`). */
226
+ error_code?: string;
227
+ };
228
+
229
+ export type SearchFilesPayload = {
230
+ query: string;
231
+ namespace_ids?: string[];
232
+ include_usage?: boolean;
233
+ };
234
+
235
+ export type SearchFilesResult = {
236
+ results: FileSearchResult[];
237
+ query: string;
238
+ total_found: number;
239
+ explanation?: string;
240
+ usage?: UsageBlock;
241
+ };
242
+
243
+ export type AnalyzeVideoPayload = {
244
+ video_url: string;
245
+ query?: string;
246
+ transcript_text?: boolean;
247
+ include_usage?: boolean;
248
+ };
249
+
250
+ export type AnalyzeFilePayload = {
251
+ file_id: string;
252
+ query?: string;
253
+ transcript_text?: boolean;
254
+ include_usage?: boolean;
255
+ };
256
+
257
+ export type AnalyzeVideoResult = {
258
+ video_info: VideoInfo;
259
+ transcript: TranscriptOutput;
260
+ transcript_analysis: AnalysisResult;
261
+ usage?: UsageBlock;
262
+ };
263
+
264
+ export type AnalyzeFileResult = {
265
+ file_info: FileInfo;
266
+ transcript: TranscriptOutput;
267
+ transcript_analysis: AnalysisResult;
268
+ usage?: UsageBlock;
269
+ };
270
+
130
271
  export type ExtractVideoDataPayload = {
131
272
  video_url: string;
132
273
  schema: ExtractionSchema;
133
274
  what_to_extract?: string;
134
275
  transcribe?: boolean;
135
276
  include_usage?: boolean;
136
- };
277
+ } & WebhookOption;
137
278
 
138
279
  export type ExtractVideoDataMultipartPayload = {
139
280
  video_url: string;
@@ -142,7 +283,9 @@ export type ExtractVideoDataMultipartPayload = {
142
283
  what_to_extract?: string;
143
284
  transcribe?: boolean;
144
285
  include_usage?: boolean;
145
- };
286
+ } & WebhookOption;
287
+
288
+ export type TweetStatementPayload = { tweet_id: string } & WebhookOption;
146
289
 
147
290
  export type ExtractFileDataPayload = {
148
291
  file_id: string;
@@ -160,18 +303,70 @@ export type ExtractFileDataMultipartPayload = {
160
303
  };
161
304
  //endregion
162
305
 
163
- function parseApiErrorPayload(data: any): {
164
- errorCode?: string;
165
- errorMessage?: string;
166
- details?: any;
167
- } {
168
- const errorField = data?.error;
169
- const errorCode =
170
- typeof errorField === 'string' ? errorField : errorField?.code;
171
- const errorMessage =
172
- data?.message ??
173
- (typeof errorField === 'object' ? errorField?.message : undefined);
174
- return { errorCode, errorMessage, details: data };
306
+ function parseTranscribeData(
307
+ inner:
308
+ | { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string }
309
+ | { carousel_info: CarouselInfoJSON; videos: CarouselVideoResultJSON[] },
310
+ usage?: UsageBlock
311
+ ): TranscribeVideoResult {
312
+ if ('videos' in inner && 'carousel_info' in inner) {
313
+ return {
314
+ carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
315
+ videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
316
+ usage,
317
+ };
318
+ }
319
+ const single = inner as { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string };
320
+ return {
321
+ video_info: VideoInfo.fromJSON(single.video_info),
322
+ transcript: transcriptFromJSON(single.transcript)!,
323
+ usage,
324
+ };
325
+ }
326
+
327
+ function buildAsyncJobParams(options?: SubmitOptions): Record<string, string> | undefined {
328
+ // Like the TikTok pollers, the async job pollers take include_usage as a query string value.
329
+ return options?.include_usage ? { include_usage: 'true' } : undefined;
330
+ }
331
+
332
+ function requireResult<T>(task: AsyncJob<T>): T {
333
+ if (task.result === null) {
334
+ const err = new VidNavigatorError(`Task ${task.task_id} completed without a result`);
335
+ err.task_id = task.task_id;
336
+ throw err;
337
+ }
338
+ return task.result;
339
+ }
340
+
341
+ /** TikTok results are paginated; fetch every page of a completed task and merge the items. */
342
+ async function collectAllPages<TTask extends { pagination?: TikTokProfilePagination }, TItem>(
343
+ fetchPage: (query: { cursor?: string; limit: number; include_usage?: boolean }) => Promise<TTask>,
344
+ items: (task: TTask) => TItem[],
345
+ setItems: (task: TTask, all: TItem[]) => void,
346
+ include_usage?: boolean
347
+ ): Promise<TTask> {
348
+ const first = await fetchPage({ limit: TIKTOK_PAGE_SIZE, include_usage });
349
+ const all = [...items(first)];
350
+ let cursor = first.pagination?.next_cursor ?? undefined;
351
+ while (cursor) {
352
+ const page = await fetchPage({ limit: TIKTOK_PAGE_SIZE, cursor });
353
+ all.push(...items(page));
354
+ cursor = page.pagination?.next_cursor ?? undefined;
355
+ }
356
+ setItems(first, all);
357
+ if (first.pagination) {
358
+ first.pagination = { ...first.pagination, limit: all.length, has_next: false, next_cursor: null };
359
+ }
360
+ return first;
361
+ }
362
+
363
+ const TIKTOK_PAGE_SIZE = 500;
364
+
365
+ interface OperationSpec<TInput, TTask extends PollableTask, TResult> {
366
+ jobType: string;
367
+ submit: (input: TInput) => Promise<JobInfo>;
368
+ fetchTask: (task_id: string, options: SubmitOptions) => Promise<TTask>;
369
+ toResult: (task: TTask, options: SubmitOptions) => Promise<TResult>;
175
370
  }
176
371
 
177
372
  function appendOptionalFormField(form: FormData, name: string, value: string | number | boolean | undefined): void {
@@ -180,9 +375,69 @@ function appendOptionalFormField(form: FormData, name: string, value: string | n
180
375
  }
181
376
  }
182
377
 
378
+ function buildTikTokPollParams(query?: {
379
+ cursor?: string;
380
+ limit?: number;
381
+ include_usage?: boolean;
382
+ }): Record<string, string | number> | undefined {
383
+ if (!query) return undefined;
384
+ const params: Record<string, string | number> = {};
385
+ if (query.cursor !== undefined) params.cursor = query.cursor;
386
+ if (query.limit !== undefined) params.limit = query.limit;
387
+ // The TikTok pollers expect include_usage as a query string value.
388
+ if (query.include_usage) params.include_usage = 'true';
389
+ return params;
390
+ }
391
+
392
+ const _deprecationWarned = new Set<string>();
393
+
394
+ function warnDeprecated(oldName: string, newName: string): void {
395
+ if (_deprecationWarned.has(oldName)) return;
396
+ _deprecationWarned.add(oldName);
397
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
398
+ console.warn(
399
+ `[vidnavigator] ${oldName}() is deprecated and will be removed in a future release; use ${newName}() instead.`
400
+ );
401
+ }
402
+ }
403
+
183
404
  export class VidNavigatorClient {
184
405
  private client: AxiosInstance;
185
406
 
407
+ /**
408
+ * Speech-to-text transcription of any length (Instagram, TikTok, X, Facebook, Vimeo, ...),
409
+ * built on `POST /transcribe/async`.
410
+ *
411
+ * - `await vn.transcribe(url)` submits, polls, and returns the result.
412
+ * - `await vn.transcribe.submit(url)` returns a {@link Job} handle right away.
413
+ * - `vn.transcribe.resume(task_id)` reattaches to a job you already submitted.
414
+ */
415
+ readonly transcribe: TranscribeOperation;
416
+
417
+ /**
418
+ * Structured-data extraction from a video of any length, built on `POST /extract/video/async`.
419
+ * The schema is validated when you submit. Same shapes as {@link VidNavigatorClient.transcribe}.
420
+ */
421
+ readonly extractVideo: JobOperation<ExtractVideoInput, ExtractVideoAsyncJob, ExtractDataResult>;
422
+
423
+ /**
424
+ * Structured claim analysis of an X/Twitter tweet (attached media of any length), built on
425
+ * `POST /tweet/statement/async`. Same shapes as {@link VidNavigatorClient.transcribe}.
426
+ */
427
+ readonly tweetStatement: JobOperation<string | TweetStatementInput, TweetStatementAsyncJob, TweetStatement>;
428
+
429
+ /**
430
+ * TikTok profile scrape, built on `POST /tiktok/profile`. The result is the completed task with
431
+ * every page of `videos` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
432
+ */
433
+ readonly tiktokProfile: JobOperation<string | TikTokProfileScrapeRequest, TikTokProfileTask, TikTokProfileTask>;
434
+
435
+ /**
436
+ * TikTok keyword search, built on `POST /tiktok/search`. The result is the completed task with
437
+ * every page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
438
+ */
439
+ readonly tiktokSearch: JobOperation<string | TikTokSearchRequest, TikTokSearchTask, TikTokSearchTask>;
440
+
186
441
  constructor(config: SDKConfig) {
187
442
  if (!config?.apiKey) {
188
443
  throw new Error('An API key is required to use the VidNavigator SDK.');
@@ -196,6 +451,132 @@ export class VidNavigatorClient {
196
451
  },
197
452
  ...config.axiosConfig,
198
453
  });
454
+
455
+ this.transcribe = this.defineOperation({
456
+ jobType: 'transcribe',
457
+ submit: (input: string | TranscribeInput) =>
458
+ this.submitAsyncJob('/transcribe/async', typeof input === 'string' ? { video_url: input } : input),
459
+ fetchTask: (task_id, options) =>
460
+ this.getAsyncJob(`/transcribe/${encodeURIComponent(task_id)}`, options, (raw) => parseTranscribeData(raw)),
461
+ toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
462
+ }) as TranscribeOperation;
463
+
464
+ this.extractVideo = this.defineOperation({
465
+ jobType: 'extract_video',
466
+ submit: (input: ExtractVideoInput) => this.submitExtractVideo(input),
467
+ fetchTask: (task_id, options) =>
468
+ this.getAsyncJob(
469
+ `/extract/video/${encodeURIComponent(task_id)}`,
470
+ options,
471
+ (raw) => raw as Record<string, unknown>
472
+ ),
473
+ toResult: async (task) => ({ data: requireResult(task), usage: task.usage }),
474
+ });
475
+
476
+ this.tweetStatement = this.defineOperation({
477
+ jobType: 'tweet_statement',
478
+ submit: (input: string | TweetStatementInput) =>
479
+ this.submitAsyncJob('/tweet/statement/async', typeof input === 'string' ? { tweet_id: input } : input),
480
+ fetchTask: (task_id, options) =>
481
+ this.getAsyncJob(`/tweet/statement/${encodeURIComponent(task_id)}`, options, (raw) =>
482
+ TweetStatement.fromJSON(raw)
483
+ ),
484
+ toResult: async (task) => {
485
+ const statement = requireResult(task);
486
+ statement.usage = task.usage;
487
+ return statement;
488
+ },
489
+ });
490
+
491
+ this.tiktokProfile = this.defineOperation({
492
+ jobType: 'tiktok_profile',
493
+ submit: async (input: string | TikTokProfileScrapeRequest) => {
494
+ const sub = await this.submitTikTokProfileScrape(typeof input === 'string' ? { profile_url: input } : input);
495
+ return { ...sub, job_type: 'tiktok_profile' };
496
+ },
497
+ // Status polls ask for one video only; the full result is paged in once the task completes.
498
+ fetchTask: (task_id) => this.getTikTokProfileScrape(task_id, { limit: 1 }),
499
+ toResult: (task, options) =>
500
+ collectAllPages(
501
+ (query) => this.getTikTokProfileScrape(task.task_id, query),
502
+ (page) => page.videos,
503
+ (page, all) => { page.videos = all; },
504
+ options.include_usage
505
+ ),
506
+ });
507
+
508
+ this.tiktokSearch = this.defineOperation({
509
+ jobType: 'tiktok_search',
510
+ submit: async (input: string | TikTokSearchRequest) => {
511
+ const sub = await this.submitTikTokSearch(typeof input === 'string' ? { query: input } : input);
512
+ return { ...sub, job_type: 'tiktok_search' };
513
+ },
514
+ fetchTask: (task_id) => this.getTikTokSearch(task_id, { limit: 1 }),
515
+ toResult: (task, options) =>
516
+ collectAllPages(
517
+ (query) => this.getTikTokSearch(task.task_id, query),
518
+ (page) => page.results,
519
+ (page, all) => { page.results = all; },
520
+ options.include_usage
521
+ ),
522
+ });
523
+ }
524
+
525
+ private defineOperation<TInput, TTask extends PollableTask, TResult>(
526
+ spec: OperationSpec<TInput, TTask, TResult>
527
+ ): JobOperation<TInput, TTask, TResult> {
528
+ const makeJob = (info: JobInfo, options: SubmitOptions = {}) =>
529
+ new Job<TTask, TResult>(
530
+ info,
531
+ () => spec.fetchTask(info.task_id, options),
532
+ (task) => spec.toResult(task, options)
533
+ );
534
+ const submit = async (input: TInput, options?: SubmitOptions) => makeJob(await spec.submit(input), options);
535
+ const run = async (input: TInput, options: RunOptions<TTask> = {}) => {
536
+ const { include_usage, ...pollOptions } = options;
537
+ const job = await submit(input, { include_usage });
538
+ return job.result(pollOptions);
539
+ };
540
+ return Object.assign(run, {
541
+ submit,
542
+ resume: (task_id: string, options?: SubmitOptions) =>
543
+ makeJob({ task_id, job_type: spec.jobType }, options),
544
+ });
545
+ }
546
+
547
+ private async submitAsyncJob(url: string, body: unknown, headers?: Record<string, string>): Promise<JobInfo> {
548
+ const response = await this.request<ApiSuccessResponse<AsyncJobAcceptedJSON>>('POST', url, body, undefined, headers);
549
+ const accepted = AsyncJobAccepted.fromJSON(response.data);
550
+ return { ...accepted, job_type: accepted.job_type ?? url.split('/')[1] };
551
+ }
552
+
553
+ private submitExtractVideo(input: ExtractVideoInput): Promise<JobInfo> {
554
+ if ('schemaFilePath' in input) {
555
+ const form = new FormData();
556
+ form.append('video_url', input.video_url);
557
+ form.append('schema', fs.createReadStream(input.schemaFilePath));
558
+ appendOptionalFormField(form, 'what_to_extract', input.what_to_extract);
559
+ appendOptionalFormField(form, 'transcribe', input.transcribe);
560
+ appendOptionalFormField(form, 'webhook_url', input.webhook_url);
561
+ return this.submitAsyncJob('/extract/video/async', form, form.getHeaders());
562
+ }
563
+ return this.submitAsyncJob('/extract/video/async', input);
564
+ }
565
+
566
+ private async getAsyncJob<T>(
567
+ url: string,
568
+ options: SubmitOptions | undefined,
569
+ parseResult: (raw: any) => T
570
+ ): Promise<AsyncJob<T>> {
571
+ const response = await this.request<ApiSuccessResponse<AsyncJobJSON>>(
572
+ 'GET',
573
+ url,
574
+ undefined,
575
+ buildAsyncJobParams(options)
576
+ );
577
+ const job = AsyncJob.fromJSON(response.data, parseResult);
578
+ if (response.usage) job.usage = UsageBlock.fromJSON(response.usage);
579
+ return job;
199
580
  }
200
581
 
201
582
  private async request<T>(
@@ -216,52 +597,19 @@ export class VidNavigatorClient {
216
597
  return response.data;
217
598
  } catch (error: any) {
218
599
  if (axios.isAxiosError(error) && error.response) {
219
- const { status, data } = error.response;
220
- const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
221
- const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
222
-
223
- switch (status) {
224
- case 400:
225
- throw new BadRequestError(message, status, errorCode, errorMessage, details);
226
- case 401:
227
- throw new AuthenticationError(message, status, errorCode, errorMessage, details);
228
- case 402:
229
- throw new PaymentRequiredError(message, status, errorCode, errorMessage, details);
230
- case 403:
231
- throw new AccessDeniedError(message, status, errorCode, errorMessage, details);
232
- case 404:
233
- throw new NotFoundError(message, status, errorCode, errorMessage, details);
234
- case 413:
235
- throw new StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
236
- case 429:
237
- throw new RateLimitExceededError(message, status, errorCode, errorMessage, details);
238
- case 451:
239
- throw new GeoRestrictedError(message, status, errorCode, errorMessage, details);
240
- case 503:
241
- throw new SystemOverloadError(
242
- message,
243
- status,
244
- errorCode,
245
- errorMessage,
246
- details,
247
- data?.retry_after_seconds
248
- );
249
- default:
250
- if (status >= 500) {
251
- throw new ServerError(message, status, errorCode, errorMessage, details);
252
- }
253
- throw new VidNavigatorError(message, status, errorCode, errorMessage, details);
254
- }
600
+ throw buildApiError(error.response.status, error.response.data, error.message);
255
601
  }
256
602
  throw new VidNavigatorError(error.message);
257
603
  }
258
604
  }
259
605
 
260
606
  //region --- Transcripts ---
261
- async getTranscript(payload: TranscriptRequestPayload): Promise<{
262
- video_info: VideoInfo;
263
- transcript: TranscriptOutput;
264
- }> {
607
+ /**
608
+ * Get a transcript for any supported video. The endpoint auto-detects the
609
+ * platform (YouTube, Vimeo, X/Twitter, TikTok, Facebook, Dailymotion, Loom, etc.)
610
+ * from `video_url`. For Instagram, use {@link VidNavigatorClient.transcribeVideo}.
611
+ */
612
+ async getTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
265
613
  const response = await this.request<
266
614
  ApiSuccessResponse<{
267
615
  video_info: VideoInfoJSON;
@@ -272,53 +620,30 @@ export class VidNavigatorClient {
272
620
  return {
273
621
  video_info: VideoInfo.fromJSON(response.data.video_info),
274
622
  transcript: transcriptFromJSON(response.data.transcript)!,
623
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
275
624
  };
276
625
  }
277
626
 
278
- async getYouTubeTranscript(payload: TranscriptRequestPayload): Promise<{
279
- video_info: VideoInfo;
280
- transcript: TranscriptOutput;
281
- }> {
282
- const response = await this.request<
283
- ApiSuccessResponse<{
284
- video_info: VideoInfoJSON;
285
- transcript: TranscriptSegmentJSON[] | string;
286
- }>
287
- >('POST', '/youtube/transcript', payload);
288
-
289
- return {
290
- video_info: VideoInfo.fromJSON(response.data.video_info),
291
- transcript: transcriptFromJSON(response.data.transcript)!,
292
- };
627
+ /**
628
+ * @deprecated There is now a single `/transcript` endpoint that auto-detects the
629
+ * platform. Use {@link VidNavigatorClient.getTranscript} instead. This alias
630
+ * forwards to `getTranscript` and will be removed in a future release.
631
+ */
632
+ async getYouTubeTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
633
+ warnDeprecated('getYouTubeTranscript', 'getTranscript');
634
+ return this.getTranscript(payload);
293
635
  }
294
636
 
295
- async transcribeVideo(payload: TranscribeVideoPayload): Promise<TranscribeVideoResult> {
296
- const response = await this.request<
297
- | ApiSuccessResponse<{
298
- video_info: VideoInfoJSON;
299
- transcript: TranscriptSegmentJSON[] | string;
300
- }>
301
- | ApiSuccessResponse<{
302
- carousel_info: CarouselInfoJSON;
303
- videos: CarouselVideoResultJSON[];
304
- }>
305
- >('POST', '/transcribe', payload);
306
-
307
- const inner = response.data;
308
- if ('videos' in inner && 'carousel_info' in inner) {
309
- return {
310
- carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
311
- videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
312
- };
313
- }
314
- const single = inner as {
315
- video_info: VideoInfoJSON;
316
- transcript: TranscriptSegmentJSON[] | string;
317
- };
318
- return {
319
- video_info: VideoInfo.fromJSON(single.video_info),
320
- transcript: transcriptFromJSON(single.transcript)!,
321
- };
637
+ /**
638
+ * Speech-to-text transcription. Blocking convenience wrapper around {@link VidNavigatorClient.transcribe}:
639
+ * submits to `POST /transcribe/async` and polls until the job finishes, so media of any length works.
640
+ */
641
+ async transcribeVideo(
642
+ payload: TranscribeVideoPayload,
643
+ options?: PollOptions<TranscribeAsyncJob>
644
+ ): Promise<TranscribeVideoResult> {
645
+ const { include_usage, ...input } = payload;
646
+ return this.transcribe(input, { ...options, include_usage });
322
647
  }
323
648
  //endregion
324
649
 
@@ -336,15 +661,17 @@ export class VidNavigatorClient {
336
661
 
337
662
  async getTikTokProfileScrape(
338
663
  task_id: string,
339
- query?: { cursor?: string; limit?: number }
664
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
340
665
  ): Promise<TikTokProfileTask> {
341
666
  const response = await this.request<ApiSuccessResponse<TikTokProfileTaskJSON>>(
342
667
  'GET',
343
668
  `/tiktok/profile/${task_id}`,
344
669
  undefined,
345
- query
670
+ buildTikTokPollParams(query)
346
671
  );
347
- return TikTokProfileTask.fromJSON(response.data);
672
+ const task = TikTokProfileTask.fromJSON(response.data);
673
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
674
+ return task;
348
675
  }
349
676
 
350
677
  async submitTikTokSearch(payload: TikTokSearchRequest): Promise<TikTokSearchSubmission> {
@@ -358,15 +685,17 @@ export class VidNavigatorClient {
358
685
 
359
686
  async getTikTokSearch(
360
687
  task_id: string,
361
- query?: { cursor?: string; limit?: number }
688
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
362
689
  ): Promise<TikTokSearchTask> {
363
690
  const response = await this.request<ApiSuccessResponse<TikTokSearchTaskJSON>>(
364
691
  'GET',
365
692
  `/tiktok/search/${task_id}`,
366
693
  undefined,
367
- query
694
+ buildTikTokPollParams(query)
368
695
  );
369
- return TikTokSearchTask.fromJSON(response.data);
696
+ const task = TikTokSearchTask.fromJSON(response.data);
697
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
698
+ return task;
370
699
  }
371
700
  //endregion
372
701
 
@@ -467,33 +796,7 @@ export class VidNavigatorClient {
467
796
  };
468
797
  } catch (error: any) {
469
798
  if (axios.isAxiosError(error) && error.response) {
470
- const { status, data } = error.response;
471
- const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
472
- const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
473
- switch (status) {
474
- case 400:
475
- throw new BadRequestError(message, status, errorCode, errorMessage, details);
476
- case 401:
477
- throw new AuthenticationError(message, status, errorCode, errorMessage, details);
478
- case 402:
479
- throw new PaymentRequiredError(message, status, errorCode, errorMessage, details);
480
- case 413:
481
- throw new StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
482
- case 503:
483
- throw new SystemOverloadError(
484
- message,
485
- status,
486
- errorCode,
487
- errorMessage,
488
- details,
489
- data?.retry_after_seconds
490
- );
491
- default:
492
- if (status >= 500) {
493
- throw new ServerError(message, status, errorCode, errorMessage, details);
494
- }
495
- throw new VidNavigatorError(message, status, errorCode, errorMessage, details);
496
- }
799
+ throw buildApiError(error.response.status, error.response.data, error.message);
497
800
  }
498
801
  throw new VidNavigatorError(error.message);
499
802
  }
@@ -583,15 +886,7 @@ export class VidNavigatorClient {
583
886
  //endregion
584
887
 
585
888
  //region --- Analysis ---
586
- async analyzeVideo(payload: {
587
- video_url: string;
588
- query?: string;
589
- transcript_text?: boolean;
590
- }): Promise<{
591
- video_info: VideoInfo;
592
- transcript: TranscriptOutput;
593
- transcript_analysis: AnalysisResult;
594
- }> {
889
+ async analyzeVideo(payload: AnalyzeVideoPayload): Promise<AnalyzeVideoResult> {
595
890
  const response = await this.request<
596
891
  ApiSuccessResponse<{
597
892
  video_info: VideoInfoJSON;
@@ -604,18 +899,11 @@ export class VidNavigatorClient {
604
899
  video_info: VideoInfo.fromJSON(response.data.video_info),
605
900
  transcript: transcriptFromJSON(response.data.transcript)!,
606
901
  transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
902
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
607
903
  };
608
904
  }
609
905
 
610
- async analyzeFile(payload: {
611
- file_id: string;
612
- query?: string;
613
- transcript_text?: boolean;
614
- }): Promise<{
615
- file_info: FileInfo;
616
- transcript: TranscriptOutput;
617
- transcript_analysis: AnalysisResult;
618
- }> {
906
+ async analyzeFile(payload: AnalyzeFilePayload): Promise<AnalyzeFileResult> {
619
907
  const response = await this.request<
620
908
  ApiSuccessResponse<{
621
909
  file_info: FileInfoJSON;
@@ -628,55 +916,35 @@ export class VidNavigatorClient {
628
916
  file_info: FileInfo.fromJSON(response.data.file_info),
629
917
  transcript: transcriptFromJSON(response.data.transcript)!,
630
918
  transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
919
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
631
920
  };
632
921
  }
633
922
 
634
- async getTweetStatement(payload: { tweet_id: string }): Promise<TweetStatement> {
635
- const response = await this.request<ApiSuccessResponse<TweetStatementJSON>>(
636
- 'POST',
637
- '/tweet/statement',
638
- payload
639
- );
640
- return TweetStatement.fromJSON(response.data);
923
+ /**
924
+ * Structured claim analysis of an X/Twitter tweet. Blocking convenience wrapper around
925
+ * {@link VidNavigatorClient.tweetStatement}: submits to `POST /tweet/statement/async` and polls.
926
+ */
927
+ async getTweetStatement(
928
+ payload: TweetStatementPayload,
929
+ options?: RunOptions<TweetStatementAsyncJob>
930
+ ): Promise<TweetStatement> {
931
+ return this.tweetStatement(payload, options);
641
932
  }
642
933
  //endregion
643
934
 
644
935
  //region --- Extraction ---
936
+ /**
937
+ * Structured-data extraction from an online video. Blocking convenience wrapper around
938
+ * {@link VidNavigatorClient.extractVideo}: submits to `POST /extract/video/async` and polls, so
939
+ * media of any length works. The async API does not return `video_info`; use
940
+ * {@link VidNavigatorClient.getTranscript} with `metadata_only: true` if you need it.
941
+ */
645
942
  async extractVideoData(
646
- payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload
943
+ payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload,
944
+ options?: PollOptions<ExtractVideoAsyncJob>
647
945
  ): Promise<ExtractDataResult> {
648
- if ('schemaFilePath' in payload) {
649
- const form = new FormData();
650
- form.append('video_url', payload.video_url);
651
- form.append('schema', fs.createReadStream(payload.schemaFilePath));
652
- appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
653
- appendOptionalFormField(form, 'transcribe', payload.transcribe);
654
- appendOptionalFormField(form, 'include_usage', payload.include_usage);
655
-
656
- const body = await this.request<{
657
- status: 'success';
658
- data: Record<string, unknown>;
659
- video_info?: VideoInfoJSON;
660
- usage?: ExtractionTokenUsageJSON;
661
- }>('POST', '/extract/video', form, undefined, form.getHeaders());
662
- return {
663
- data: body.data,
664
- video_info: body.video_info ? VideoInfo.fromJSON(body.video_info) : undefined,
665
- usage: body.usage ? ExtractionTokenUsage.fromJSON(body.usage) : undefined,
666
- };
667
- }
668
-
669
- const body = await this.request<{
670
- status: 'success';
671
- data: Record<string, unknown>;
672
- video_info?: VideoInfoJSON;
673
- usage?: ExtractionTokenUsageJSON;
674
- }>('POST', '/extract/video', payload);
675
- return {
676
- data: body.data,
677
- video_info: body.video_info ? VideoInfo.fromJSON(body.video_info) : undefined,
678
- usage: body.usage ? ExtractionTokenUsage.fromJSON(body.usage) : undefined,
679
- };
946
+ const { include_usage, ...input } = payload;
947
+ return this.extractVideo(input as ExtractVideoInput, { ...options, include_usage });
680
948
  }
681
949
 
682
950
  async extractFileData(
@@ -693,12 +961,12 @@ export class VidNavigatorClient {
693
961
  status: 'success';
694
962
  data: Record<string, unknown>;
695
963
  file_info?: FileInfoJSON;
696
- usage?: ExtractionTokenUsageJSON;
964
+ usage?: UsageBlockJSON;
697
965
  }>('POST', '/extract/file', form, undefined, form.getHeaders());
698
966
  return {
699
967
  data: body.data,
700
968
  file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
701
- usage: body.usage ? ExtractionTokenUsage.fromJSON(body.usage) : undefined,
969
+ usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
702
970
  };
703
971
  }
704
972
 
@@ -706,56 +974,71 @@ export class VidNavigatorClient {
706
974
  status: 'success';
707
975
  data: Record<string, unknown>;
708
976
  file_info?: FileInfoJSON;
709
- usage?: ExtractionTokenUsageJSON;
977
+ usage?: UsageBlockJSON;
710
978
  }>('POST', '/extract/file', payload);
711
979
  return {
712
980
  data: body.data,
713
981
  file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
714
- usage: body.usage ? ExtractionTokenUsage.fromJSON(body.usage) : undefined,
982
+ usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
715
983
  };
716
984
  }
717
985
  //endregion
718
986
 
719
987
  //region --- Search ---
720
- async searchVideos(payload: {
721
- query: string;
722
- use_enhanced_search?: boolean;
723
- start_year?: number;
724
- end_year?: number;
725
- focus?: 'relevance' | 'popularity' | 'brevity';
726
- duration?: number;
727
- }): Promise<{
728
- results: VideoSearchResult[];
729
- query: string;
730
- total_found: number;
731
- explanation?: string;
732
- }> {
733
- const response = await this.request<
734
- ApiSuccessResponse<{
988
+ /**
989
+ * Search YouTube for videos with AI analysis and ranking.
990
+ *
991
+ * If the account runs out of `residential_request` credits mid-search, the API
992
+ * returns HTTP 402 with `status: "partial"` and the videos analysed so far. The
993
+ * SDK surfaces that partial payload (results, `status: "partial"`, `error_code`,
994
+ * and `usage` when requested) instead of throwing.
995
+ */
996
+ async searchYouTube(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
997
+ let response: {
998
+ status?: 'success' | 'partial';
999
+ error_code?: string;
1000
+ data: {
735
1001
  results: VideoSearchResultJSON[];
736
1002
  query: string;
737
1003
  total_found: number;
738
1004
  explanation?: string;
739
- }>
740
- >('POST', '/search/video', payload);
1005
+ };
1006
+ usage?: UsageBlockJSON;
1007
+ };
1008
+
1009
+ try {
1010
+ response = await this.request('POST', '/youtube/search', payload);
1011
+ } catch (error: any) {
1012
+ const body = error?.details;
1013
+ if (error instanceof PaymentRequiredError && body?.status === 'partial' && body?.data) {
1014
+ response = body;
1015
+ } else {
1016
+ throw error;
1017
+ }
1018
+ }
741
1019
 
742
1020
  return {
743
- results: response.data.results.map(VideoSearchResult.fromJSON),
1021
+ results: (response.data.results ?? []).map(VideoSearchResult.fromJSON),
744
1022
  query: response.data.query,
745
1023
  total_found: response.data.total_found,
746
1024
  explanation: response.data.explanation,
1025
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1026
+ status: response.status,
1027
+ error_code: response.error_code,
747
1028
  };
748
1029
  }
749
1030
 
750
- async searchFiles(payload: {
751
- query: string;
752
- namespace_ids?: string[];
753
- }): Promise<{
754
- results: FileSearchResult[];
755
- query: string;
756
- total_found: number;
757
- explanation?: string;
758
- }> {
1031
+ /**
1032
+ * @deprecated `/search/video` moved to `/youtube/search`. Use
1033
+ * {@link VidNavigatorClient.searchYouTube} instead. This alias forwards to
1034
+ * `searchYouTube` and will be removed in a future release.
1035
+ */
1036
+ async searchVideos(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1037
+ warnDeprecated('searchVideos', 'searchYouTube');
1038
+ return this.searchYouTube(payload);
1039
+ }
1040
+
1041
+ async searchFiles(payload: SearchFilesPayload): Promise<SearchFilesResult> {
759
1042
  const response = await this.request<
760
1043
  ApiSuccessResponse<{
761
1044
  results: FileSearchResultJSON[];
@@ -770,6 +1053,7 @@ export class VidNavigatorClient {
770
1053
  query: response.data.query,
771
1054
  total_found: response.data.total_found,
772
1055
  explanation: response.data.explanation,
1056
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
773
1057
  };
774
1058
  }
775
1059
  //endregion