vidnavigator 2.3.1 → 2.5.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
@@ -1,1198 +1,1477 @@
1
- import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- import FormData from 'form-data';
3
- import fs from 'fs';
4
- import {
5
- VideoInfo,
6
- VideoInfoJSON,
7
- TranscriptSegmentJSON,
8
- TranscriptOutput,
9
- transcriptFromJSON,
10
- FileInfo,
11
- FileInfoJSON,
12
- AnalysisResult,
13
- AnalysisResultJSON,
14
- VideoSearchResult,
15
- VideoSearchResultJSON,
16
- FileSearchResult,
17
- FileSearchResultJSON,
18
- UsageData,
19
- UsageDataJSON,
20
- Namespace,
21
- NamespaceJSON,
22
- NamespaceRef,
23
- NamespaceRefJSON,
24
- ExtractionSchema,
25
- UsageBlock,
26
- UsageBlockJSON,
27
- CarouselInfo,
28
- CarouselInfoJSON,
29
- CarouselVideoResult,
30
- CarouselVideoResultJSON,
31
- TikTokProfileScrapeRequest,
32
- TikTokProfileScrapeSubmission,
33
- TikTokProfileScrapeSubmissionJSON,
34
- TikTokProfileTask,
35
- TikTokProfileTaskJSON,
36
- TikTokSearchRequest,
37
- TikTokSearchSubmission,
38
- TikTokSearchSubmissionJSON,
39
- TikTokSearchTask,
40
- TikTokSearchTaskJSON,
41
- TikTokLiveSearchRequest,
42
- TikTokLiveSearchSubmission,
43
- TikTokLiveSearchSubmissionJSON,
44
- TikTokLiveSearchTask,
45
- TikTokLiveSearchTaskJSON,
46
- TikTokLiveRoomRequest,
47
- TikTokLiveRoomResult,
48
- TikTokLiveRoomResultJSON,
49
- tiktokLiveRoomResultFromJSON,
50
- TweetStatement,
51
- AsyncJob,
52
- AsyncJobJSON,
53
- AsyncJobAccepted,
54
- AsyncJobAcceptedJSON,
55
- TikTokProfilePagination,
56
- } from './models';
57
- import { VidNavigatorError, PaymentRequiredError } from './errors';
58
- import { buildApiError } from './http';
59
- import { Job, JobInfo, JobOperation, PollableTask, PollOptions, RunOptions, SubmitOptions } from './jobs';
60
-
61
- export * from './models';
62
- export * from './errors';
63
- export * from './webhooks';
64
- export { Job } from './jobs';
65
- export type { TaskStatus, PollableTask, PollOptions, JobOperation, SubmitOptions, RunOptions, JobInfo } from './jobs';
66
-
67
- /** SDK version (keep in sync with package.json) */
68
- export const SDK_VERSION = '2.3.1';
69
-
70
- /**
71
- * A LIVE room usually answers in 1-5 s, up to ~30 s when the API has to open a TikTok page, and two
72
- * minutes at worst. A shorter configured axios timeout is raised to this for that call only.
73
- */
74
- const LIVE_ROOM_TIMEOUT_MS = 120_000;
75
-
76
- //region --- Interfaces ---
77
- export interface SDKConfig {
78
- apiKey: string;
79
- baseURL?: string;
80
- axiosConfig?: AxiosRequestConfig;
81
- }
82
-
83
- interface ApiSuccessResponse<T> {
84
- status: 'success';
85
- data: T;
86
- usage?: UsageBlockJSON;
87
- }
88
-
89
- export type TranscriptRequestPayload = {
90
- video_url: string;
91
- language?: string;
92
- metadata_only?: boolean;
93
- fallback_to_metadata?: boolean;
94
- transcript_text?: boolean;
95
- include_usage?: boolean;
96
- };
97
-
98
- export type TranscribeVideoPayload = {
99
- video_url: string;
100
- transcript_text?: boolean;
101
- all_videos?: boolean;
102
- include_usage?: boolean;
103
- } & WebhookOption;
104
-
105
- /**
106
- * Where to POST a notification when an async job finishes. Overrides the account-level default
107
- * configured in Studio → API; pass an empty string to opt this job out of that default.
108
- * Must be a publicly reachable https URL. This is a pass-through: polling always works either way.
109
- */
110
- export type WebhookOption = { webhook_url?: string };
111
-
112
- /** Input for {@link VidNavigatorClient.transcribe}. A plain string is treated as `video_url`. */
113
- export type TranscribeInput = {
114
- video_url: string;
115
- transcript_text?: boolean;
116
- /** Instagram carousel posts only: transcribe every video in the post. */
117
- all_videos?: boolean;
118
- } & WebhookOption;
119
-
120
- /** Input for {@link VidNavigatorClient.extractVideo}: a JSON `schema`, or a JSON/YAML `schemaFilePath`. */
121
- export type ExtractVideoInput =
122
- | ({
123
- video_url: string;
124
- schema: ExtractionSchema;
125
- what_to_extract?: string;
126
- /** Speech-to-text the audio when no platform transcript exists. Default true. */
127
- transcribe?: boolean;
128
- } & WebhookOption)
129
- | ({
130
- video_url: string;
131
- /** Path to a JSON or YAML schema file (sent as multipart form-data). */
132
- schemaFilePath: string;
133
- what_to_extract?: string;
134
- transcribe?: boolean;
135
- } & WebhookOption);
136
-
137
- /** Input for {@link VidNavigatorClient.tweetStatement}. A plain string is treated as `tweet_id`. */
138
- export type TweetStatementInput = { tweet_id: string } & WebhookOption;
139
-
140
- export type TranscriptResult = {
141
- video_info: VideoInfo;
142
- transcript: TranscriptOutput;
143
- usage?: UsageBlock;
144
- };
145
-
146
- export type TranscribeVideoSingleResult = {
147
- video_info: VideoInfo;
148
- transcript: TranscriptOutput;
149
- usage?: UsageBlock;
150
- };
151
-
152
- export type TranscribeVideoCarouselResult = {
153
- carousel_info: CarouselInfo;
154
- videos: CarouselVideoResult[];
155
- usage?: UsageBlock;
156
- };
157
-
158
- export type TranscribeVideoResult = TranscribeVideoSingleResult | TranscribeVideoCarouselResult;
159
-
160
- /** Snapshot of a transcription task. `result` has the same shape as {@link VidNavigatorClient.transcribe}'s return value. */
161
- export type TranscribeAsyncJob = AsyncJob<TranscribeVideoResult>;
162
-
163
- /** Snapshot of an extraction task. `result` is the extracted object, shaped like your schema. */
164
- export type ExtractVideoAsyncJob = AsyncJob<Record<string, unknown>>;
165
-
166
- /** Snapshot of a tweet claim analysis task. `result` is a {@link TweetStatement}. */
167
- export type TweetStatementAsyncJob = AsyncJob<TweetStatement>;
168
-
169
- export type TranscribeJob = Job<TranscribeAsyncJob, TranscribeVideoResult>;
170
-
171
- /** Input that always yields a single-video result (the carousel shape needs `all_videos: true`). */
172
- type SingleTranscribeInput = string | (TranscribeInput & { all_videos?: false });
173
-
174
- /**
175
- * {@link JobOperation} for transcription, typed so that a plain URL (or `all_videos` left off)
176
- * resolves to {@link TranscribeVideoSingleResult}.
177
- */
178
- export interface TranscribeOperation extends JobOperation<string | TranscribeInput, TranscribeAsyncJob, TranscribeVideoResult> {
179
- (input: SingleTranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoSingleResult>;
180
- (input: string | TranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoResult>;
181
- submit(input: SingleTranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoSingleResult>>;
182
- submit(input: string | TranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoResult>>;
183
- }
184
- export type ExtractVideoJob = Job<ExtractVideoAsyncJob, ExtractDataResult>;
185
- export type TweetStatementJob = Job<TweetStatementAsyncJob, TweetStatement>;
186
- /** `result()` resolves to the completed task with **all** pages of `videos` collected. */
187
- export type TikTokProfileJob = Job<TikTokProfileTask, TikTokProfileTask>;
188
- /** `result()` resolves to the completed task with **all** pages of `results` collected. */
189
- export type TikTokSearchJob = Job<TikTokSearchTask, TikTokSearchTask>;
190
- /** `result()` resolves to the completed task with **all** pages of rooms collected. */
191
- export type TikTokLiveSearchJob = Job<TikTokLiveSearchTask, TikTokLiveSearchTask>;
192
-
193
- export type UploadFileSuccessResult = {
194
- status: 'success';
195
- file_id: string;
196
- file_name: string;
197
- file_status: 'processing' | 'completed';
198
- message: string;
199
- file_info: FileInfo;
200
- };
201
-
202
- export type UploadFileAcceptedResult = {
203
- status: 'accepted';
204
- file_id: string;
205
- file_name: string;
206
- file_status: 'processing';
207
- message: string;
208
- note?: string;
209
- file_info?: FileInfo;
210
- };
211
-
212
- export type UploadFileResult = UploadFileSuccessResult | UploadFileAcceptedResult;
213
-
214
- export interface ExtractDataResult {
215
- data: Record<string, unknown>;
216
- video_info?: VideoInfo;
217
- file_info?: FileInfo;
218
- usage?: UsageBlock;
219
- }
220
-
221
- /**
222
- * What comes first among the videos that match the query: the best matches
223
- * (`relevance`), the most recent (`recency`), the most viewed (`popularity`)
224
- * or the shortest (`brevity`).
225
- */
226
- export type YouTubeSearchFocus = 'relevance' | 'recency' | 'popularity' | 'brevity';
227
-
228
- export type SearchYouTubePayload = {
229
- query: string;
230
- use_enhanced_search?: boolean;
231
- /** Only videos published in or after this year. */
232
- start_year?: number;
233
- /** Only videos published in or before this year. */
234
- end_year?: number;
235
- /** Defaults to `relevance`. With another value, `explanation` is empty. */
236
- focus?: YouTubeSearchFocus;
237
- /** Maximum duration in seconds: longer videos are left out. */
238
- duration?: number;
239
- max_results?: number;
240
- include_usage?: boolean;
241
- };
242
-
243
- export type SearchYouTubeResult = {
244
- results: VideoSearchResult[];
245
- query: string;
246
- total_found: number;
247
- explanation?: string;
248
- usage?: UsageBlock;
249
- /** Present when a 402 partial-results response is returned. */
250
- status?: 'success' | 'partial';
251
- /** Present on partial results (e.g. `insufficient_credits_video_search`). */
252
- error_code?: string;
253
- };
254
-
255
- export type SearchFilesPayload = {
256
- query: string;
257
- namespace_ids?: string[];
258
- include_usage?: boolean;
259
- };
260
-
261
- export type SearchFilesResult = {
262
- results: FileSearchResult[];
263
- query: string;
264
- total_found: number;
265
- explanation?: string;
266
- usage?: UsageBlock;
267
- };
268
-
269
- export type AnalyzeVideoPayload = {
270
- video_url: string;
271
- query?: string;
272
- transcript_text?: boolean;
273
- include_usage?: boolean;
274
- };
275
-
276
- export type AnalyzeFilePayload = {
277
- file_id: string;
278
- query?: string;
279
- transcript_text?: boolean;
280
- include_usage?: boolean;
281
- };
282
-
283
- export type AnalyzeVideoResult = {
284
- video_info: VideoInfo;
285
- transcript: TranscriptOutput;
286
- transcript_analysis: AnalysisResult;
287
- usage?: UsageBlock;
288
- };
289
-
290
- export type AnalyzeFileResult = {
291
- file_info: FileInfo;
292
- transcript: TranscriptOutput;
293
- transcript_analysis: AnalysisResult;
294
- usage?: UsageBlock;
295
- };
296
-
297
- export type ExtractVideoDataPayload = {
298
- video_url: string;
299
- schema: ExtractionSchema;
300
- what_to_extract?: string;
301
- transcribe?: boolean;
302
- include_usage?: boolean;
303
- } & WebhookOption;
304
-
305
- export type ExtractVideoDataMultipartPayload = {
306
- video_url: string;
307
- /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
308
- schemaFilePath: string;
309
- what_to_extract?: string;
310
- transcribe?: boolean;
311
- include_usage?: boolean;
312
- } & WebhookOption;
313
-
314
- export type TweetStatementPayload = { tweet_id: string } & WebhookOption;
315
-
316
- export type ExtractFileDataPayload = {
317
- file_id: string;
318
- schema: ExtractionSchema;
319
- what_to_extract?: string;
320
- include_usage?: boolean;
321
- };
322
-
323
- export type ExtractFileDataMultipartPayload = {
324
- file_id: string;
325
- /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
326
- schemaFilePath: string;
327
- what_to_extract?: string;
328
- include_usage?: boolean;
329
- };
330
- //endregion
331
-
332
- function parseTranscribeData(
333
- inner:
334
- | { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string }
335
- | { carousel_info: CarouselInfoJSON; videos: CarouselVideoResultJSON[] },
336
- usage?: UsageBlock
337
- ): TranscribeVideoResult {
338
- if ('videos' in inner && 'carousel_info' in inner) {
339
- return {
340
- carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
341
- videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
342
- usage,
343
- };
344
- }
345
- const single = inner as { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string };
346
- return {
347
- video_info: VideoInfo.fromJSON(single.video_info),
348
- transcript: transcriptFromJSON(single.transcript)!,
349
- usage,
350
- };
351
- }
352
-
353
- function buildAsyncJobParams(options?: SubmitOptions): Record<string, string> | undefined {
354
- // Like the TikTok pollers, the async job pollers take include_usage as a query string value.
355
- return options?.include_usage ? { include_usage: 'true' } : undefined;
356
- }
357
-
358
- function requireResult<T>(task: AsyncJob<T>): T {
359
- if (task.result === null) {
360
- const err = new VidNavigatorError(`Task ${task.task_id} completed without a result`);
361
- err.task_id = task.task_id;
362
- throw err;
363
- }
364
- return task.result;
365
- }
366
-
367
- /** TikTok results are paginated; fetch every page of a completed task and merge the items. */
368
- async function collectAllPages<TTask extends { pagination?: TikTokProfilePagination }, TItem>(
369
- fetchPage: (query: { cursor?: string; limit: number; include_usage?: boolean }) => Promise<TTask>,
370
- items: (task: TTask) => TItem[],
371
- setItems: (task: TTask, all: TItem[]) => void,
372
- include_usage?: boolean
373
- ): Promise<TTask> {
374
- const first = await fetchPage({ limit: TIKTOK_PAGE_SIZE, include_usage });
375
- const all = [...items(first)];
376
- let cursor = first.pagination?.next_cursor ?? undefined;
377
- while (cursor) {
378
- const page = await fetchPage({ limit: TIKTOK_PAGE_SIZE, cursor });
379
- all.push(...items(page));
380
- cursor = page.pagination?.next_cursor ?? undefined;
381
- }
382
- setItems(first, all);
383
- if (first.pagination) {
384
- first.pagination = { ...first.pagination, limit: all.length, has_next: false, next_cursor: null };
385
- }
386
- return first;
387
- }
388
-
389
- const TIKTOK_PAGE_SIZE = 500;
390
-
391
- interface OperationSpec<TInput, TTask extends PollableTask, TResult> {
392
- jobType: string;
393
- submit: (input: TInput) => Promise<JobInfo>;
394
- fetchTask: (task_id: string, options: SubmitOptions) => Promise<TTask>;
395
- toResult: (task: TTask, options: SubmitOptions) => Promise<TResult>;
396
- }
397
-
398
- function appendOptionalFormField(form: FormData, name: string, value: string | number | boolean | undefined): void {
399
- if (value !== undefined) {
400
- form.append(name, String(value));
401
- }
402
- }
403
-
404
- function buildTikTokPollParams(query?: {
405
- cursor?: string;
406
- limit?: number;
407
- include_usage?: boolean;
408
- }): Record<string, string | number> | undefined {
409
- if (!query) return undefined;
410
- const params: Record<string, string | number> = {};
411
- if (query.cursor !== undefined) params.cursor = query.cursor;
412
- if (query.limit !== undefined) params.limit = query.limit;
413
- // The TikTok pollers expect include_usage as a query string value.
414
- if (query.include_usage) params.include_usage = 'true';
415
- return params;
416
- }
417
-
418
- const _deprecationWarned = new Set<string>();
419
-
420
- function warnDeprecated(oldName: string, newName: string): void {
421
- if (_deprecationWarned.has(oldName)) return;
422
- _deprecationWarned.add(oldName);
423
- if (typeof console !== 'undefined' && typeof console.warn === 'function') {
424
- console.warn(
425
- `[vidnavigator] ${oldName}() is deprecated and will be removed in a future release; use ${newName}() instead.`
426
- );
427
- }
428
- }
429
-
430
- export class VidNavigatorClient {
431
- private client: AxiosInstance;
432
-
433
- /**
434
- * Speech-to-text transcription of any length (Instagram, TikTok, X, Facebook, Vimeo, ...),
435
- * built on `POST /transcribe/async`.
436
- *
437
- * - `await vn.transcribe(url)` submits, polls, and returns the result.
438
- * - `await vn.transcribe.submit(url)` returns a {@link Job} handle right away.
439
- * - `vn.transcribe.resume(task_id)` reattaches to a job you already submitted.
440
- */
441
- readonly transcribe: TranscribeOperation;
442
-
443
- /**
444
- * Structured-data extraction from a video of any length, built on `POST /extract/video/async`.
445
- * The schema is validated when you submit. Same shapes as {@link VidNavigatorClient.transcribe}.
446
- */
447
- readonly extractVideo: JobOperation<ExtractVideoInput, ExtractVideoAsyncJob, ExtractDataResult>;
448
-
449
- /**
450
- * Structured claim analysis of an X/Twitter tweet (attached media of any length), built on
451
- * `POST /tweet/statement/async`. Same shapes as {@link VidNavigatorClient.transcribe}.
452
- */
453
- readonly tweetStatement: JobOperation<string | TweetStatementInput, TweetStatementAsyncJob, TweetStatement>;
454
-
455
- /**
456
- * TikTok profile scrape, built on `POST /tiktok/profile`. The result is the completed task with
457
- * every page of `videos` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
458
- */
459
- readonly tiktokProfile: JobOperation<string | TikTokProfileScrapeRequest, TikTokProfileTask, TikTokProfileTask>;
460
-
461
- /**
462
- * TikTok keyword search, built on `POST /tiktok/search`. The result is the completed task with
463
- * every page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
464
- */
465
- readonly tiktokSearch: JobOperation<string | TikTokSearchRequest, TikTokSearchTask, TikTokSearchTask>;
466
-
467
- /**
468
- * TikTok LIVE search, built on `POST /tiktok/live/search`: rooms broadcasting now for a keyword,
469
- * with their FLV / HLS / audio-only stream URLs. The result is the completed task with every
470
- * page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
471
- */
472
- readonly tiktokLiveSearch: JobOperation<string | TikTokLiveSearchRequest, TikTokLiveSearchTask, TikTokLiveSearchTask>;
473
-
474
- constructor(config: SDKConfig) {
475
- if (!config?.apiKey) {
476
- throw new Error('An API key is required to use the VidNavigator SDK.');
477
- }
478
-
479
- this.client = axios.create({
480
- baseURL: config.baseURL ?? 'https://api.vidnavigator.com/v1',
481
- headers: {
482
- 'X-API-Key': config.apiKey,
483
- 'User-Agent': `vidnavigator-js/${SDK_VERSION}`,
484
- },
485
- ...config.axiosConfig,
486
- });
487
-
488
- this.transcribe = this.defineOperation({
489
- jobType: 'transcribe',
490
- submit: (input: string | TranscribeInput) =>
491
- this.submitAsyncJob('/transcribe/async', typeof input === 'string' ? { video_url: input } : input),
492
- fetchTask: (task_id, options) =>
493
- this.getAsyncJob(`/transcribe/${encodeURIComponent(task_id)}`, options, (raw) => parseTranscribeData(raw)),
494
- toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
495
- }) as TranscribeOperation;
496
-
497
- this.extractVideo = this.defineOperation({
498
- jobType: 'extract_video',
499
- submit: (input: ExtractVideoInput) => this.submitExtractVideo(input),
500
- fetchTask: (task_id, options) =>
501
- this.getAsyncJob(
502
- `/extract/video/${encodeURIComponent(task_id)}`,
503
- options,
504
- (raw) => raw as Record<string, unknown>
505
- ),
506
- toResult: async (task) => ({ data: requireResult(task), video_info: task.video_info, usage: task.usage }),
507
- });
508
-
509
- this.tweetStatement = this.defineOperation({
510
- jobType: 'tweet_statement',
511
- submit: (input: string | TweetStatementInput) =>
512
- this.submitAsyncJob('/tweet/statement/async', typeof input === 'string' ? { tweet_id: input } : input),
513
- fetchTask: (task_id, options) =>
514
- this.getAsyncJob(`/tweet/statement/${encodeURIComponent(task_id)}`, options, (raw) =>
515
- TweetStatement.fromJSON(raw)
516
- ),
517
- toResult: async (task) => {
518
- const statement = requireResult(task);
519
- statement.usage = task.usage;
520
- return statement;
521
- },
522
- });
523
-
524
- this.tiktokProfile = this.defineOperation({
525
- jobType: 'tiktok_profile',
526
- submit: async (input: string | TikTokProfileScrapeRequest) => {
527
- const sub = await this.submitTikTokProfileScrape(typeof input === 'string' ? { profile_url: input } : input);
528
- return { ...sub, job_type: 'tiktok_profile' };
529
- },
530
- // Status polls ask for one video only; the full result is paged in once the task completes.
531
- fetchTask: (task_id) => this.getTikTokProfileScrape(task_id, { limit: 1 }),
532
- toResult: (task, options) =>
533
- collectAllPages(
534
- (query) => this.getTikTokProfileScrape(task.task_id, query),
535
- (page) => page.videos,
536
- (page, all) => { page.videos = all; },
537
- options.include_usage
538
- ),
539
- });
540
-
541
- this.tiktokSearch = this.defineOperation({
542
- jobType: 'tiktok_search',
543
- submit: async (input: string | TikTokSearchRequest) => {
544
- const sub = await this.submitTikTokSearch(typeof input === 'string' ? { query: input } : input);
545
- return { ...sub, job_type: 'tiktok_search' };
546
- },
547
- fetchTask: (task_id) => this.getTikTokSearch(task_id, { limit: 1 }),
548
- toResult: (task, options) =>
549
- collectAllPages(
550
- (query) => this.getTikTokSearch(task.task_id, query),
551
- (page) => page.results,
552
- (page, all) => { page.results = all; },
553
- options.include_usage
554
- ),
555
- });
556
-
557
- this.tiktokLiveSearch = this.defineOperation({
558
- jobType: 'tiktok_live_search',
559
- submit: async (input: string | TikTokLiveSearchRequest) => {
560
- const sub = await this.submitTikTokLiveSearch(typeof input === 'string' ? { query: input } : input);
561
- return { ...sub, job_type: 'tiktok_live_search' };
562
- },
563
- fetchTask: (task_id) => this.getTikTokLiveSearch(task_id, { limit: 1 }),
564
- toResult: (task, options) =>
565
- collectAllPages(
566
- (query) => this.getTikTokLiveSearch(task.task_id, query),
567
- (page) => page.results,
568
- (page, all) => { page.results = all; },
569
- options.include_usage
570
- ),
571
- });
572
- }
573
-
574
- private defineOperation<TInput, TTask extends PollableTask, TResult>(
575
- spec: OperationSpec<TInput, TTask, TResult>
576
- ): JobOperation<TInput, TTask, TResult> {
577
- const makeJob = (info: JobInfo, options: SubmitOptions = {}) =>
578
- new Job<TTask, TResult>(
579
- info,
580
- () => spec.fetchTask(info.task_id, options),
581
- (task) => spec.toResult(task, options)
582
- );
583
- const submit = async (input: TInput, options?: SubmitOptions) => makeJob(await spec.submit(input), options);
584
- const run = async (input: TInput, options: RunOptions<TTask> = {}) => {
585
- const { include_usage, ...pollOptions } = options;
586
- const job = await submit(input, { include_usage });
587
- return job.result(pollOptions);
588
- };
589
- return Object.assign(run, {
590
- submit,
591
- resume: (task_id: string, options?: SubmitOptions) =>
592
- makeJob({ task_id, job_type: spec.jobType }, options),
593
- });
594
- }
595
-
596
- private async submitAsyncJob(url: string, body: unknown, headers?: Record<string, string>): Promise<JobInfo> {
597
- const response = await this.request<ApiSuccessResponse<AsyncJobAcceptedJSON>>('POST', url, body, undefined, headers);
598
- const accepted = AsyncJobAccepted.fromJSON(response.data);
599
- return { ...accepted, job_type: accepted.job_type ?? url.split('/')[1] };
600
- }
601
-
602
- private submitExtractVideo(input: ExtractVideoInput): Promise<JobInfo> {
603
- if ('schemaFilePath' in input) {
604
- const form = new FormData();
605
- form.append('video_url', input.video_url);
606
- form.append('schema', fs.createReadStream(input.schemaFilePath));
607
- appendOptionalFormField(form, 'what_to_extract', input.what_to_extract);
608
- appendOptionalFormField(form, 'transcribe', input.transcribe);
609
- appendOptionalFormField(form, 'webhook_url', input.webhook_url);
610
- return this.submitAsyncJob('/extract/video/async', form, form.getHeaders());
611
- }
612
- return this.submitAsyncJob('/extract/video/async', input);
613
- }
614
-
615
- private async getAsyncJob<T>(
616
- url: string,
617
- options: SubmitOptions | undefined,
618
- parseResult: (raw: any) => T
619
- ): Promise<AsyncJob<T>> {
620
- const response = await this.request<ApiSuccessResponse<AsyncJobJSON>>(
621
- 'GET',
622
- url,
623
- undefined,
624
- buildAsyncJobParams(options)
625
- );
626
- const job = AsyncJob.fromJSON(response.data, parseResult);
627
- if (response.usage) job.usage = UsageBlock.fromJSON(response.usage);
628
- return job;
629
- }
630
-
631
- private async request<T>(
632
- method: 'GET' | 'POST' | 'DELETE' | 'PUT',
633
- url: string,
634
- data?: any,
635
- params?: any,
636
- extraHeaders?: any,
637
- minTimeoutMs?: number
638
- ): Promise<T> {
639
- // A call known to run long raises a configured timeout, never lowers it
640
- // (0 / unset means no timeout at all).
641
- const configured = this.client.defaults.timeout;
642
- const timeout = minTimeoutMs && configured ? Math.max(configured, minTimeoutMs) : undefined;
643
- try {
644
- const response = await this.client.request<T>({
645
- method,
646
- url,
647
- data,
648
- params,
649
- headers: extraHeaders,
650
- ...(timeout !== undefined ? { timeout } : {}),
651
- });
652
- return response.data;
653
- } catch (error: any) {
654
- if (axios.isAxiosError(error) && error.response) {
655
- throw buildApiError(error.response.status, error.response.data, error.message);
656
- }
657
- throw new VidNavigatorError(error.message);
658
- }
659
- }
660
-
661
- //region --- Transcripts ---
662
- /**
663
- * Get a transcript for any supported video. The endpoint auto-detects the
664
- * platform (YouTube, Vimeo, X/Twitter, TikTok, Facebook, Dailymotion, Loom, Snapchat, etc.)
665
- * from `video_url`. For Instagram, use {@link VidNavigatorClient.transcribeVideo}.
666
- */
667
- async getTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
668
- const response = await this.request<
669
- ApiSuccessResponse<{
670
- video_info: VideoInfoJSON;
671
- transcript: TranscriptSegmentJSON[] | string;
672
- }>
673
- >('POST', '/transcript', payload);
674
-
675
- return {
676
- video_info: VideoInfo.fromJSON(response.data.video_info),
677
- transcript: transcriptFromJSON(response.data.transcript)!,
678
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
679
- };
680
- }
681
-
682
- /**
683
- * @deprecated There is now a single `/transcript` endpoint that auto-detects the
684
- * platform. Use {@link VidNavigatorClient.getTranscript} instead. This alias
685
- * forwards to `getTranscript` and will be removed in a future release.
686
- */
687
- async getYouTubeTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
688
- warnDeprecated('getYouTubeTranscript', 'getTranscript');
689
- return this.getTranscript(payload);
690
- }
691
-
692
- /**
693
- * Speech-to-text transcription. Blocking convenience wrapper around {@link VidNavigatorClient.transcribe}:
694
- * submits to `POST /transcribe/async` and polls until the job finishes, so media of any length works.
695
- */
696
- async transcribeVideo(
697
- payload: TranscribeVideoPayload,
698
- options?: PollOptions<TranscribeAsyncJob>
699
- ): Promise<TranscribeVideoResult> {
700
- const { include_usage, ...input } = payload;
701
- return this.transcribe(input, { ...options, include_usage });
702
- }
703
- //endregion
704
-
705
- //region --- TikTok ---
706
- async submitTikTokProfileScrape(
707
- payload: TikTokProfileScrapeRequest
708
- ): Promise<TikTokProfileScrapeSubmission> {
709
- const response = await this.request<ApiSuccessResponse<TikTokProfileScrapeSubmissionJSON>>(
710
- 'POST',
711
- '/tiktok/profile',
712
- payload
713
- );
714
- return TikTokProfileScrapeSubmission.fromJSON(response.data);
715
- }
716
-
717
- async getTikTokProfileScrape(
718
- task_id: string,
719
- query?: { cursor?: string; limit?: number; include_usage?: boolean }
720
- ): Promise<TikTokProfileTask> {
721
- const response = await this.request<ApiSuccessResponse<TikTokProfileTaskJSON>>(
722
- 'GET',
723
- `/tiktok/profile/${task_id}`,
724
- undefined,
725
- buildTikTokPollParams(query)
726
- );
727
- const task = TikTokProfileTask.fromJSON(response.data);
728
- if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
729
- return task;
730
- }
731
-
732
- async submitTikTokSearch(payload: TikTokSearchRequest): Promise<TikTokSearchSubmission> {
733
- const response = await this.request<ApiSuccessResponse<TikTokSearchSubmissionJSON>>(
734
- 'POST',
735
- '/tiktok/search',
736
- payload
737
- );
738
- return TikTokSearchSubmission.fromJSON(response.data);
739
- }
740
-
741
- async getTikTokSearch(
742
- task_id: string,
743
- query?: { cursor?: string; limit?: number; include_usage?: boolean }
744
- ): Promise<TikTokSearchTask> {
745
- const response = await this.request<ApiSuccessResponse<TikTokSearchTaskJSON>>(
746
- 'GET',
747
- `/tiktok/search/${task_id}`,
748
- undefined,
749
- buildTikTokPollParams(query)
750
- );
751
- const task = TikTokSearchTask.fromJSON(response.data);
752
- if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
753
- return task;
754
- }
755
-
756
- async submitTikTokLiveSearch(payload: TikTokLiveSearchRequest): Promise<TikTokLiveSearchSubmission> {
757
- const response = await this.request<ApiSuccessResponse<TikTokLiveSearchSubmissionJSON>>(
758
- 'POST',
759
- '/tiktok/live/search',
760
- payload
761
- );
762
- return TikTokLiveSearchSubmission.fromJSON(response.data);
763
- }
764
-
765
- async getTikTokLiveSearch(
766
- task_id: string,
767
- query?: { cursor?: string; limit?: number; include_usage?: boolean }
768
- ): Promise<TikTokLiveSearchTask> {
769
- const response = await this.request<ApiSuccessResponse<TikTokLiveSearchTaskJSON>>(
770
- 'GET',
771
- `/tiktok/live/search/${task_id}`,
772
- undefined,
773
- buildTikTokPollParams(query)
774
- );
775
- const task = TikTokLiveSearchTask.fromJSON(response.data);
776
- if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
777
- return task;
778
- }
779
-
780
- /**
781
- * One TikTok LIVE room, right away (`POST /tiktok/live/room`, no job): by `room_id`, `username`
782
- * or `url`, exactly one. The room says whether it is live or ended (and when), its viewers and new
783
- * followers, the streamer's bio, and more. With `include_comments: true` the result also has the
784
- * latest comments (up to 50), the pinned comment, the intro and the top viewers.
785
- *
786
- * The room has no likes, comment count or share count: TikTok gives those to LIVE search only.
787
- * A room or account that does not exist throws `NotFoundError` (`error_code` `live_not_found`)
788
- * and is not billed. Billing: 1 `residential_request`, 2 with `include_comments`.
789
- */
790
- async getTikTokLiveRoom(payload: TikTokLiveRoomRequest): Promise<TikTokLiveRoomResult> {
791
- const targets = (['room_id', 'username', 'url'] as const).filter((key) => payload?.[key]);
792
- if (targets.length !== 1) {
793
- throw new VidNavigatorError('Pass exactly one of room_id, username or url');
794
- }
795
- let body: TikTokLiveRoomRequest = payload;
796
- const roomId: unknown = payload.room_id;
797
- if (typeof roomId === 'number') {
798
- if (!Number.isSafeInteger(roomId)) {
799
- throw new VidNavigatorError(
800
- 'room_id has more digits than a JavaScript number holds: pass it as a string'
801
- );
802
- }
803
- body = { ...payload, room_id: String(roomId) };
804
- }
805
- const response = await this.request<ApiSuccessResponse<TikTokLiveRoomResultJSON>>(
806
- 'POST',
807
- '/tiktok/live/room',
808
- body,
809
- undefined,
810
- undefined,
811
- LIVE_ROOM_TIMEOUT_MS
812
- );
813
- const result = tiktokLiveRoomResultFromJSON(response.data);
814
- if (response.usage) result.usage = UsageBlock.fromJSON(response.usage);
815
- return result;
816
- }
817
- //endregion
818
-
819
- //region --- Files ---
820
- async getFiles(query?: {
821
- limit?: number;
822
- offset?: number;
823
- status?: 'processing' | 'completed' | 'failed' | 'cancelled';
824
- namespace_id?: string;
825
- }): Promise<{
826
- files: FileInfo[];
827
- total_count: number;
828
- limit: number;
829
- offset: number;
830
- has_more: boolean;
831
- }> {
832
- const response = await this.request<
833
- ApiSuccessResponse<{
834
- files: FileInfoJSON[];
835
- total_count: number;
836
- limit: number;
837
- offset: number;
838
- has_more: boolean;
839
- }>
840
- >('GET', '/files', undefined, query);
841
-
842
- return {
843
- files: response.data.files.map(FileInfo.fromJSON),
844
- total_count: response.data.total_count,
845
- limit: response.data.limit,
846
- offset: response.data.offset,
847
- has_more: response.data.has_more,
848
- };
849
- }
850
-
851
- async getFile(
852
- file_id: string,
853
- query?: { transcript_text?: boolean }
854
- ): Promise<{ file_info: FileInfo; transcript?: TranscriptOutput }> {
855
- const response = await this.request<
856
- ApiSuccessResponse<{
857
- file_info: FileInfoJSON;
858
- transcript?: TranscriptSegmentJSON[] | string;
859
- }>
860
- >('GET', `/file/${file_id}`, undefined, query);
861
-
862
- return {
863
- file_info: FileInfo.fromJSON(response.data.file_info),
864
- transcript: transcriptFromJSON(response.data.transcript),
865
- };
866
- }
867
-
868
- async uploadFile(options: {
869
- filePath: string;
870
- wait_for_completion?: boolean;
871
- namespace_ids?: string[];
872
- }): Promise<UploadFileResult> {
873
- const form = new FormData();
874
- form.append('file', fs.createReadStream(options.filePath));
875
- if (options.wait_for_completion) {
876
- form.append('wait_for_completion', 'true');
877
- }
878
- if (options.namespace_ids?.length) {
879
- form.append('namespace_ids', JSON.stringify(options.namespace_ids));
880
- }
881
-
882
- try {
883
- const response = await this.client.post<{
884
- status: 'success' | 'accepted';
885
- file_id: string;
886
- file_name: string;
887
- file_status: 'processing' | 'completed';
888
- message: string;
889
- note?: string;
890
- data?: { file_info: FileInfoJSON };
891
- }>('/upload/file', form, { headers: form.getHeaders() });
892
-
893
- const body = response.data;
894
- const fileInfo = body.data?.file_info ? FileInfo.fromJSON(body.data.file_info) : undefined;
895
- if (body.status === 'accepted') {
896
- return {
897
- status: 'accepted',
898
- file_id: body.file_id,
899
- file_name: body.file_name,
900
- file_status: body.file_status as 'processing',
901
- message: body.message,
902
- note: body.note,
903
- file_info: fileInfo,
904
- };
905
- }
906
- return {
907
- status: 'success',
908
- file_id: body.file_id,
909
- file_name: body.file_name,
910
- file_status: body.file_status,
911
- message: body.message,
912
- file_info: fileInfo!,
913
- };
914
- } catch (error: any) {
915
- if (axios.isAxiosError(error) && error.response) {
916
- throw buildApiError(error.response.status, error.response.data, error.message);
917
- }
918
- throw new VidNavigatorError(error.message);
919
- }
920
- }
921
-
922
- async deleteFile(file_id: string): Promise<{ file_id: string; file_name: string; message: string }> {
923
- const response = await this.request<
924
- ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
925
- >('DELETE', `/file/${file_id}/delete`);
926
- return response.data;
927
- }
928
-
929
- async getFileUrl(file_id: string): Promise<{ file_id: string; file_url: string }> {
930
- const response = await this.request<
931
- ApiSuccessResponse<{ file_id: string; file_url: string }>
932
- >('GET', `/file/${file_id}/url`);
933
- return response.data;
934
- }
935
-
936
- async retryFileProcessing(
937
- file_id: string
938
- ): Promise<{ file_id: string; file_name: string; file_status: string; message: string }> {
939
- const response = await this.request<
940
- ApiSuccessResponse<{
941
- file_id: string;
942
- file_name: string;
943
- file_status: string;
944
- message: string;
945
- }>
946
- >('POST', `/file/${file_id}/retry`);
947
- return response.data;
948
- }
949
-
950
- async cancelFileUpload(
951
- file_id: string
952
- ): Promise<{ file_id: string; file_name: string; message: string }> {
953
- const response = await this.request<
954
- ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
955
- >('POST', `/file/${file_id}/cancel`);
956
- return response.data;
957
- }
958
- //endregion
959
-
960
- //region --- Namespaces ---
961
- async getNamespaces(): Promise<Namespace[]> {
962
- const response = await this.request<ApiSuccessResponse<NamespaceJSON[]>>('GET', '/namespaces');
963
- return response.data.map((n) => Namespace.fromJSON(n));
964
- }
965
-
966
- async createNamespace(payload: { name: string }): Promise<Namespace> {
967
- const response = await this.request<ApiSuccessResponse<NamespaceJSON>>('POST', '/namespaces', payload);
968
- return Namespace.fromJSON(response.data);
969
- }
970
-
971
- async updateNamespace(namespace_id: string, payload: { name: string }): Promise<{ message: string }> {
972
- const body = await this.request<{ status: string; message: string }>(
973
- 'PUT',
974
- `/namespaces/${namespace_id}`,
975
- payload
976
- );
977
- return { message: body.message };
978
- }
979
-
980
- async deleteNamespace(namespace_id: string): Promise<{ message: string }> {
981
- const body = await this.request<{ status: string; message: string }>(
982
- 'DELETE',
983
- `/namespaces/${namespace_id}`
984
- );
985
- return { message: body.message };
986
- }
987
-
988
- async updateFileNamespaces(
989
- file_id: string,
990
- payload: { namespace_ids: string[] }
991
- ): Promise<{ message: string; namespace_ids: string[]; namespaces: NamespaceRef[] }> {
992
- const body = await this.request<{
993
- status: string;
994
- message: string;
995
- data: { namespace_ids: string[]; namespaces: NamespaceRefJSON[] };
996
- }>('PUT', `/file/${file_id}/namespaces`, payload);
997
- return {
998
- message: body.message,
999
- namespace_ids: body.data.namespace_ids,
1000
- namespaces: body.data.namespaces.map(NamespaceRef.fromJSON),
1001
- };
1002
- }
1003
- //endregion
1004
-
1005
- //region --- Analysis ---
1006
- async analyzeVideo(payload: AnalyzeVideoPayload): Promise<AnalyzeVideoResult> {
1007
- const response = await this.request<
1008
- ApiSuccessResponse<{
1009
- video_info: VideoInfoJSON;
1010
- transcript: TranscriptSegmentJSON[] | string;
1011
- transcript_analysis: AnalysisResultJSON;
1012
- }>
1013
- >('POST', '/analyze/video', payload);
1014
-
1015
- return {
1016
- video_info: VideoInfo.fromJSON(response.data.video_info),
1017
- transcript: transcriptFromJSON(response.data.transcript)!,
1018
- transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
1019
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1020
- };
1021
- }
1022
-
1023
- async analyzeFile(payload: AnalyzeFilePayload): Promise<AnalyzeFileResult> {
1024
- const response = await this.request<
1025
- ApiSuccessResponse<{
1026
- file_info: FileInfoJSON;
1027
- transcript: TranscriptSegmentJSON[] | string;
1028
- transcript_analysis: AnalysisResultJSON;
1029
- }>
1030
- >('POST', '/analyze/file', payload);
1031
-
1032
- return {
1033
- file_info: FileInfo.fromJSON(response.data.file_info),
1034
- transcript: transcriptFromJSON(response.data.transcript)!,
1035
- transcript_analysis: AnalysisResult.fromJSON(response.data.transcript_analysis),
1036
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1037
- };
1038
- }
1039
-
1040
- /**
1041
- * Structured claim analysis of an X/Twitter tweet. Blocking convenience wrapper around
1042
- * {@link VidNavigatorClient.tweetStatement}: submits to `POST /tweet/statement/async` and polls.
1043
- */
1044
- async getTweetStatement(
1045
- payload: TweetStatementPayload,
1046
- options?: RunOptions<TweetStatementAsyncJob>
1047
- ): Promise<TweetStatement> {
1048
- return this.tweetStatement(payload, options);
1049
- }
1050
- //endregion
1051
-
1052
- //region --- Extraction ---
1053
- /**
1054
- * Structured-data extraction from an online video. Blocking convenience wrapper around
1055
- * {@link VidNavigatorClient.extractVideo}: submits to `POST /extract/video/async` and polls, so
1056
- * media of any length works. The result carries the extracted `data` and the video's `video_info`.
1057
- */
1058
- async extractVideoData(
1059
- payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload,
1060
- options?: PollOptions<ExtractVideoAsyncJob>
1061
- ): Promise<ExtractDataResult> {
1062
- const { include_usage, ...input } = payload;
1063
- return this.extractVideo(input as ExtractVideoInput, { ...options, include_usage });
1064
- }
1065
-
1066
- async extractFileData(
1067
- payload: ExtractFileDataPayload | ExtractFileDataMultipartPayload
1068
- ): Promise<ExtractDataResult> {
1069
- if ('schemaFilePath' in payload) {
1070
- const form = new FormData();
1071
- form.append('file_id', payload.file_id);
1072
- form.append('schema', fs.createReadStream(payload.schemaFilePath));
1073
- appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
1074
- appendOptionalFormField(form, 'include_usage', payload.include_usage);
1075
-
1076
- const body = await this.request<{
1077
- status: 'success';
1078
- data: Record<string, unknown>;
1079
- file_info?: FileInfoJSON;
1080
- usage?: UsageBlockJSON;
1081
- }>('POST', '/extract/file', form, undefined, form.getHeaders());
1082
- return {
1083
- data: body.data,
1084
- file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
1085
- usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
1086
- };
1087
- }
1088
-
1089
- const body = await this.request<{
1090
- status: 'success';
1091
- data: Record<string, unknown>;
1092
- file_info?: FileInfoJSON;
1093
- usage?: UsageBlockJSON;
1094
- }>('POST', '/extract/file', payload);
1095
- return {
1096
- data: body.data,
1097
- file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
1098
- usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
1099
- };
1100
- }
1101
- //endregion
1102
-
1103
- //region --- Search ---
1104
- /**
1105
- * Search YouTube for videos with AI analysis and ranking.
1106
- *
1107
- * If the account runs out of `residential_request` credits mid-search, the API
1108
- * returns HTTP 402 with `status: "partial"` and the videos analysed so far. The
1109
- * SDK surfaces that partial payload (results, `status: "partial"`, `error_code`,
1110
- * and `usage` when requested) instead of throwing.
1111
- */
1112
- async searchYouTube(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1113
- let response: {
1114
- status?: 'success' | 'partial';
1115
- error_code?: string;
1116
- data: {
1117
- results: VideoSearchResultJSON[];
1118
- query: string;
1119
- total_found: number;
1120
- explanation?: string;
1121
- };
1122
- usage?: UsageBlockJSON;
1123
- };
1124
-
1125
- try {
1126
- response = await this.request('POST', '/youtube/search', payload);
1127
- } catch (error: any) {
1128
- const body = error?.details;
1129
- if (error instanceof PaymentRequiredError && body?.status === 'partial' && body?.data) {
1130
- response = body;
1131
- } else {
1132
- throw error;
1133
- }
1134
- }
1135
-
1136
- return {
1137
- results: (response.data.results ?? []).map(VideoSearchResult.fromJSON),
1138
- query: response.data.query,
1139
- total_found: response.data.total_found,
1140
- explanation: response.data.explanation,
1141
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1142
- status: response.status,
1143
- error_code: response.error_code,
1144
- };
1145
- }
1146
-
1147
- /**
1148
- * @deprecated `/search/video` moved to `/youtube/search`. Use
1149
- * {@link VidNavigatorClient.searchYouTube} instead. This alias forwards to
1150
- * `searchYouTube` and will be removed in a future release.
1151
- */
1152
- async searchVideos(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1153
- warnDeprecated('searchVideos', 'searchYouTube');
1154
- return this.searchYouTube(payload);
1155
- }
1156
-
1157
- async searchFiles(payload: SearchFilesPayload): Promise<SearchFilesResult> {
1158
- const response = await this.request<
1159
- ApiSuccessResponse<{
1160
- results: FileSearchResultJSON[];
1161
- query: string;
1162
- total_found: number;
1163
- explanation?: string;
1164
- }>
1165
- >('POST', '/search/file', payload);
1166
-
1167
- return {
1168
- results: response.data.results.map(FileSearchResult.fromJSON),
1169
- query: response.data.query,
1170
- total_found: response.data.total_found,
1171
- explanation: response.data.explanation,
1172
- usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1173
- };
1174
- }
1175
- //endregion
1176
-
1177
- //region --- System ---
1178
- async getUsage(): Promise<UsageData> {
1179
- const response = await this.request<ApiSuccessResponse<UsageDataJSON>>('GET', '/usage');
1180
- return UsageData.fromJSON(response.data);
1181
- }
1182
-
1183
- async healthCheck(): Promise<{
1184
- status?: string;
1185
- message?: string;
1186
- version?: string;
1187
- endpoints?: Array<{
1188
- path?: string;
1189
- method?: string;
1190
- description?: string;
1191
- auth_required?: boolean;
1192
- }>;
1193
- }> {
1194
- const response = await this.client.get('/health');
1195
- return response.data;
1196
- }
1197
- //endregion
1198
- }
1
+ import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+ import FormData from 'form-data';
3
+ import fs from 'fs';
4
+ import {
5
+ VideoInfo,
6
+ VideoInfoJSON,
7
+ TranscriptSegmentJSON,
8
+ TranscriptOutput,
9
+ transcriptFromJSON,
10
+ FileInfo,
11
+ FileInfoJSON,
12
+ AnalysisResult,
13
+ AnalysisResultJSON,
14
+ VideoSearchResult,
15
+ VideoSearchResultJSON,
16
+ FileSearchResult,
17
+ FileSearchResultJSON,
18
+ UsageData,
19
+ UsageDataJSON,
20
+ Namespace,
21
+ NamespaceJSON,
22
+ NamespaceRef,
23
+ NamespaceRefJSON,
24
+ ExtractionSchema,
25
+ UsageBlock,
26
+ UsageBlockJSON,
27
+ CarouselInfo,
28
+ CarouselInfoJSON,
29
+ CarouselVideoResult,
30
+ CarouselVideoResultJSON,
31
+ TikTokProfileScrapeRequest,
32
+ TikTokProfileScrapeSubmission,
33
+ TikTokProfileScrapeSubmissionJSON,
34
+ TikTokProfileTask,
35
+ TikTokProfileTaskJSON,
36
+ TikTokSearchRequest,
37
+ TikTokSearchSubmission,
38
+ TikTokSearchSubmissionJSON,
39
+ TikTokSearchTask,
40
+ TikTokSearchTaskJSON,
41
+ TikTokLiveSearchRequest,
42
+ TikTokLiveSearchSubmission,
43
+ TikTokLiveSearchSubmissionJSON,
44
+ TikTokLiveSearchTask,
45
+ TikTokLiveSearchTaskJSON,
46
+ TikTokLiveRoomRequest,
47
+ TikTokLiveRoomResult,
48
+ TikTokLiveRoomResultJSON,
49
+ tiktokLiveRoomResultFromJSON,
50
+ TweetStatement,
51
+ WatchResult,
52
+ WatchResultJSON,
53
+ WatchTranscriptError,
54
+ VideoScene,
55
+ VideoSceneJSON,
56
+ ScenesError,
57
+ FileScenesStatus,
58
+ AsyncJob,
59
+ AsyncJobJSON,
60
+ AsyncJobAccepted,
61
+ AsyncJobAcceptedJSON,
62
+ TikTokProfilePagination,
63
+ } from './models';
64
+ import { VidNavigatorError, PaymentRequiredError } from './errors';
65
+ import { buildApiError } from './http';
66
+ import { Job, JobInfo, JobOperation, PollableTask, PollOptions, RunOptions, SubmitOptions } from './jobs';
67
+
68
+ export * from './models';
69
+ export * from './errors';
70
+ export * from './webhooks';
71
+ export { Job } from './jobs';
72
+ export type { TaskStatus, PollableTask, PollOptions, JobOperation, SubmitOptions, RunOptions, JobInfo } from './jobs';
73
+
74
+ /** SDK version (keep in sync with package.json) */
75
+ export const SDK_VERSION = '2.5.0';
76
+
77
+ /**
78
+ * A LIVE room usually answers in 1-5 s, up to ~30 s when the API has to open a TikTok page, and two
79
+ * minutes at worst. A shorter configured axios timeout is raised to this for that call only.
80
+ */
81
+ const LIVE_ROOM_TIMEOUT_MS = 120_000;
82
+
83
+ //region --- Interfaces ---
84
+ export interface SDKConfig {
85
+ apiKey: string;
86
+ baseURL?: string;
87
+ axiosConfig?: AxiosRequestConfig;
88
+ }
89
+
90
+ interface ApiSuccessResponse<T> {
91
+ status: 'success';
92
+ data: T;
93
+ usage?: UsageBlockJSON;
94
+ }
95
+
96
+ export type TranscriptRequestPayload = {
97
+ video_url: string;
98
+ language?: string;
99
+ metadata_only?: boolean;
100
+ fallback_to_metadata?: boolean;
101
+ transcript_text?: boolean;
102
+ include_usage?: boolean;
103
+ };
104
+
105
+ export type TranscribeVideoPayload = {
106
+ video_url: string;
107
+ transcript_text?: boolean;
108
+ all_videos?: boolean;
109
+ include_usage?: boolean;
110
+ } & WebhookOption;
111
+
112
+ /**
113
+ * Where to POST a notification when an async job finishes. Overrides the account-level default
114
+ * configured in Studio → API; pass an empty string to opt this job out of that default.
115
+ * Must be a publicly reachable https URL. This is a pass-through: polling always works either way.
116
+ */
117
+ export type WebhookOption = { webhook_url?: string };
118
+
119
+ /** Input for {@link VidNavigatorClient.transcribe}. A plain string is treated as `video_url`. */
120
+ export type TranscribeInput = {
121
+ video_url: string;
122
+ transcript_text?: boolean;
123
+ /** Instagram carousel posts only: transcribe every video in the post. */
124
+ all_videos?: boolean;
125
+ } & WebhookOption;
126
+
127
+ /** How closely {@link VidNavigatorClient.watch} follows the picture. */
128
+ export type WatchDetail = 'low' | 'auto' | 'high';
129
+
130
+ /** Input for {@link VidNavigatorClient.watch}. A plain string is treated as `video_url`. */
131
+ export type WatchInput = {
132
+ /** `?img_index=N` selects one video of an Instagram carousel or a Snapchat highlight. */
133
+ video_url: string;
134
+ /**
135
+ * How closely the picture is followed. Default `auto`. The number of frames depends on the
136
+ * video at every level; a higher level analyzes more frames when the picture changes often.
137
+ */
138
+ detail?: WatchDetail;
139
+ /** Default true. `false` returns the scenes only: the result has no `transcript`. */
140
+ include_transcript?: boolean;
141
+ /** Return the transcript as a single string instead of segments. */
142
+ transcript_text?: boolean;
143
+ } & WebhookOption;
144
+
145
+ /** Payload of {@link VidNavigatorClient.watchVideo}: a {@link WatchInput} with `include_usage`. */
146
+ export type WatchVideoPayload = WatchInput & { include_usage?: boolean };
147
+
148
+ /** Input for {@link VidNavigatorClient.analyze}. A plain string is treated as `video_url`. */
149
+ export type AnalyzeVideoInput = {
150
+ video_url: string;
151
+ /** Optional question about the video. */
152
+ query?: string;
153
+ /**
154
+ * Default false. `true` also reads what the video shows: the analysis is made from the
155
+ * transcript and the scenes together, and the result has `scenes` and `frames_analyzed`.
156
+ */
157
+ include_scenes?: boolean;
158
+ /** Return the transcript as a single string instead of segments. */
159
+ transcript_text?: boolean;
160
+ } & WebhookOption;
161
+
162
+ /** Input for {@link VidNavigatorClient.extractVideo}: a JSON `schema`, or a JSON/YAML `schemaFilePath`. */
163
+ export type ExtractVideoInput =
164
+ | ({
165
+ video_url: string;
166
+ schema: ExtractionSchema;
167
+ what_to_extract?: string;
168
+ /** Speech-to-text the audio when no platform transcript exists. Default true. */
169
+ transcribe?: boolean;
170
+ /**
171
+ * Default false. `true` also reads what the video shows: the fields are extracted from the
172
+ * transcript and the scenes together, and the result has `frames_analyzed`.
173
+ */
174
+ include_scenes?: boolean;
175
+ } & WebhookOption)
176
+ | ({
177
+ video_url: string;
178
+ /** Path to a JSON or YAML schema file (sent as multipart form-data). */
179
+ schemaFilePath: string;
180
+ what_to_extract?: string;
181
+ transcribe?: boolean;
182
+ include_scenes?: boolean;
183
+ } & WebhookOption);
184
+
185
+ /** Input for {@link VidNavigatorClient.tweetStatement}. A plain string is treated as `tweet_id`. */
186
+ export type TweetStatementInput = { tweet_id: string } & WebhookOption;
187
+
188
+ export type TranscriptResult = {
189
+ video_info: VideoInfo;
190
+ transcript: TranscriptOutput;
191
+ usage?: UsageBlock;
192
+ };
193
+
194
+ export type TranscribeVideoSingleResult = {
195
+ video_info: VideoInfo;
196
+ transcript: TranscriptOutput;
197
+ usage?: UsageBlock;
198
+ };
199
+
200
+ export type TranscribeVideoCarouselResult = {
201
+ carousel_info: CarouselInfo;
202
+ videos: CarouselVideoResult[];
203
+ usage?: UsageBlock;
204
+ };
205
+
206
+ export type TranscribeVideoResult = TranscribeVideoSingleResult | TranscribeVideoCarouselResult;
207
+
208
+ /** Snapshot of a transcription task. `result` has the same shape as {@link VidNavigatorClient.transcribe}'s return value. */
209
+ export type TranscribeAsyncJob = AsyncJob<TranscribeVideoResult>;
210
+
211
+ /** Snapshot of a watch task. `result` is a {@link WatchResult}. */
212
+ export type WatchAsyncJob = AsyncJob<WatchResult>;
213
+
214
+ /** Snapshot of a video analysis task. `result` has the same shape as {@link VidNavigatorClient.analyzeVideo}'s return value. */
215
+ export type AnalyzeVideoAsyncJob = AsyncJob<AnalyzeVideoResult>;
216
+
217
+ /** Snapshot of an extraction task. `result` is the extracted object, shaped like your schema. */
218
+ export type ExtractVideoAsyncJob = AsyncJob<Record<string, unknown>>;
219
+
220
+ /** Snapshot of a tweet claim analysis task. `result` is a {@link TweetStatement}. */
221
+ export type TweetStatementAsyncJob = AsyncJob<TweetStatement>;
222
+
223
+ export type TranscribeJob = Job<TranscribeAsyncJob, TranscribeVideoResult>;
224
+
225
+ /** Input that always yields a single-video result (the carousel shape needs `all_videos: true`). */
226
+ type SingleTranscribeInput = string | (TranscribeInput & { all_videos?: false });
227
+
228
+ /**
229
+ * {@link JobOperation} for transcription, typed so that a plain URL (or `all_videos` left off)
230
+ * resolves to {@link TranscribeVideoSingleResult}.
231
+ */
232
+ export interface TranscribeOperation extends JobOperation<string | TranscribeInput, TranscribeAsyncJob, TranscribeVideoResult> {
233
+ (input: SingleTranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoSingleResult>;
234
+ (input: string | TranscribeInput, options?: RunOptions<TranscribeAsyncJob>): Promise<TranscribeVideoResult>;
235
+ submit(input: SingleTranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoSingleResult>>;
236
+ submit(input: string | TranscribeInput, options?: SubmitOptions): Promise<Job<TranscribeAsyncJob, TranscribeVideoResult>>;
237
+ }
238
+ export type WatchJob = Job<WatchAsyncJob, WatchResult>;
239
+ export type AnalyzeVideoJob = Job<AnalyzeVideoAsyncJob, AnalyzeVideoResult>;
240
+ export type ExtractVideoJob = Job<ExtractVideoAsyncJob, ExtractDataResult>;
241
+ export type TweetStatementJob = Job<TweetStatementAsyncJob, TweetStatement>;
242
+ /** `result()` resolves to the completed task with **all** pages of `videos` collected. */
243
+ export type TikTokProfileJob = Job<TikTokProfileTask, TikTokProfileTask>;
244
+ /** `result()` resolves to the completed task with **all** pages of `results` collected. */
245
+ export type TikTokSearchJob = Job<TikTokSearchTask, TikTokSearchTask>;
246
+ /** `result()` resolves to the completed task with **all** pages of rooms collected. */
247
+ export type TikTokLiveSearchJob = Job<TikTokLiveSearchTask, TikTokLiveSearchTask>;
248
+
249
+ export type UploadFileSuccessResult = {
250
+ status: 'success';
251
+ file_id: string;
252
+ file_name: string;
253
+ file_status: 'processing' | 'completed';
254
+ message: string;
255
+ file_info: FileInfo;
256
+ };
257
+
258
+ export type UploadFileAcceptedResult = {
259
+ status: 'accepted';
260
+ file_id: string;
261
+ file_name: string;
262
+ file_status: 'processing';
263
+ message: string;
264
+ note?: string;
265
+ file_info?: FileInfo;
266
+ };
267
+
268
+ export type UploadFileResult = UploadFileSuccessResult | UploadFileAcceptedResult;
269
+
270
+ /** Answer of {@link VidNavigatorClient.analyzeFileScenes}. */
271
+ export type AnalyzeFileScenesResult = {
272
+ file_id: string;
273
+ /** `processing`: the analysis was started, or is already running. `completed`: the scenes are already there. */
274
+ scenes_status: Extract<FileScenesStatus, 'processing' | 'completed'>;
275
+ message: string;
276
+ };
277
+
278
+ /** Answer of {@link VidNavigatorClient.getFile}. */
279
+ export type GetFileResult = {
280
+ file_info: FileInfo;
281
+ /** Present once the file has a transcript. */
282
+ transcript?: TranscriptOutput;
283
+ /** What the file shows, in chronological order. Present once `file_info.scenes_status` is `completed`. */
284
+ scenes?: VideoScene[];
285
+ };
286
+
287
+ export interface ExtractDataResult {
288
+ data: Record<string, unknown>;
289
+ video_info?: VideoInfo;
290
+ file_info?: FileInfo;
291
+ /** With `include_scenes: true`: number of frames that were analyzed to produce the scenes. */
292
+ frames_analyzed?: number;
293
+ /** With `include_scenes: true`, when the picture could not be read: the fields were extracted from the transcript alone. */
294
+ scenes_error?: ScenesError;
295
+ /** With `include_scenes: true`, when there is no transcript: the fields were extracted from the scenes alone. */
296
+ transcript_error?: WatchTranscriptError;
297
+ usage?: UsageBlock;
298
+ }
299
+
300
+ /**
301
+ * What comes first among the videos that match the query: the best matches
302
+ * (`relevance`), the most recent (`recency`), the most viewed (`popularity`)
303
+ * or the shortest (`brevity`).
304
+ */
305
+ export type YouTubeSearchFocus = 'relevance' | 'recency' | 'popularity' | 'brevity';
306
+
307
+ export type SearchYouTubePayload = {
308
+ query: string;
309
+ use_enhanced_search?: boolean;
310
+ /** Only videos published in or after this year. */
311
+ start_year?: number;
312
+ /** Only videos published in or before this year. */
313
+ end_year?: number;
314
+ /** Defaults to `relevance`. With another value, `explanation` is empty. */
315
+ focus?: YouTubeSearchFocus;
316
+ /** Maximum duration in seconds: longer videos are left out. */
317
+ duration?: number;
318
+ max_results?: number;
319
+ include_usage?: boolean;
320
+ };
321
+
322
+ export type SearchYouTubeResult = {
323
+ results: VideoSearchResult[];
324
+ query: string;
325
+ total_found: number;
326
+ explanation?: string;
327
+ usage?: UsageBlock;
328
+ /** Present when a 402 partial-results response is returned. */
329
+ status?: 'success' | 'partial';
330
+ /** Present on partial results (e.g. `insufficient_credits_video_search`). */
331
+ error_code?: string;
332
+ };
333
+
334
+ export type SearchFilesPayload = {
335
+ query: string;
336
+ namespace_ids?: string[];
337
+ include_usage?: boolean;
338
+ };
339
+
340
+ export type SearchFilesResult = {
341
+ results: FileSearchResult[];
342
+ query: string;
343
+ total_found: number;
344
+ explanation?: string;
345
+ usage?: UsageBlock;
346
+ };
347
+
348
+ export type AnalyzeVideoPayload = {
349
+ video_url: string;
350
+ query?: string;
351
+ /**
352
+ * Default false. `true` also reads what the video shows: the analysis is made from the
353
+ * transcript and the scenes together, and the result has `scenes` and `frames_analyzed`.
354
+ */
355
+ include_scenes?: boolean;
356
+ transcript_text?: boolean;
357
+ include_usage?: boolean;
358
+ };
359
+
360
+ export type AnalyzeFilePayload = {
361
+ file_id: string;
362
+ query?: string;
363
+ /**
364
+ * Default false. `true` analyzes the file from its transcript and its scenes together. The
365
+ * scenes are the ones kept with the file: ask for them at the upload (`include_scenes`) or with
366
+ * {@link VidNavigatorClient.analyzeFileScenes}. A file that has none is refused with
367
+ * `ScenesNotAvailableError`.
368
+ */
369
+ include_scenes?: boolean;
370
+ transcript_text?: boolean;
371
+ include_usage?: boolean;
372
+ };
373
+
374
+ export type AnalyzeVideoResult = {
375
+ video_info: VideoInfo;
376
+ transcript: TranscriptOutput;
377
+ transcript_analysis: AnalysisResult;
378
+ /**
379
+ * With `include_scenes: true`: what the video shows, in chronological order. Empty when the
380
+ * picture could not be read (see `scenes_error`).
381
+ */
382
+ scenes?: VideoScene[];
383
+ /** With `include_scenes: true`: number of frames that were analyzed to produce the scenes. */
384
+ frames_analyzed?: number;
385
+ /** With `include_scenes: true`, when the picture could not be read: the analysis was made from the transcript alone. */
386
+ scenes_error?: ScenesError;
387
+ /** With `include_scenes: true`, when there is no transcript: the analysis was made from the scenes alone. */
388
+ transcript_error?: WatchTranscriptError;
389
+ usage?: UsageBlock;
390
+ };
391
+
392
+ export type AnalyzeFileResult = {
393
+ file_info: FileInfo;
394
+ transcript: TranscriptOutput;
395
+ transcript_analysis: AnalysisResult;
396
+ /** With `include_scenes: true`: what the file shows, in chronological order. */
397
+ scenes?: VideoScene[];
398
+ /** With `include_scenes: true`: number of frames that were analyzed to produce the scenes. */
399
+ frames_analyzed?: number;
400
+ /** Why the scenes could not be read, when the answer carries it. A file that has no scenes at all is refused with `ScenesNotAvailableError` instead. */
401
+ scenes_error?: ScenesError;
402
+ /** With `include_scenes: true`, when the file has no speech: the analysis was made from the scenes alone. */
403
+ transcript_error?: WatchTranscriptError;
404
+ usage?: UsageBlock;
405
+ };
406
+
407
+ export type ExtractVideoDataPayload = {
408
+ video_url: string;
409
+ schema: ExtractionSchema;
410
+ what_to_extract?: string;
411
+ transcribe?: boolean;
412
+ /**
413
+ * Default false. `true` also reads what the video shows: the fields are extracted from the
414
+ * transcript and the scenes together, and the result has `frames_analyzed`.
415
+ */
416
+ include_scenes?: boolean;
417
+ include_usage?: boolean;
418
+ } & WebhookOption;
419
+
420
+ export type ExtractVideoDataMultipartPayload = {
421
+ video_url: string;
422
+ /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
423
+ schemaFilePath: string;
424
+ what_to_extract?: string;
425
+ transcribe?: boolean;
426
+ include_scenes?: boolean;
427
+ include_usage?: boolean;
428
+ } & WebhookOption;
429
+
430
+ export type TweetStatementPayload = { tweet_id: string } & WebhookOption;
431
+
432
+ export type ExtractFileDataPayload = {
433
+ file_id: string;
434
+ schema: ExtractionSchema;
435
+ what_to_extract?: string;
436
+ /**
437
+ * Default false. `true` extracts from the transcript of the file and its scenes together. The
438
+ * scenes are the ones kept with the file: ask for them at the upload (`include_scenes`) or with
439
+ * {@link VidNavigatorClient.analyzeFileScenes}. A file that has none is refused with
440
+ * `ScenesNotAvailableError`.
441
+ */
442
+ include_scenes?: boolean;
443
+ include_usage?: boolean;
444
+ };
445
+
446
+ export type ExtractFileDataMultipartPayload = {
447
+ file_id: string;
448
+ /** Path to a JSON or YAML schema file. The API accepts either a raw schema or a full extraction request object. */
449
+ schemaFilePath: string;
450
+ what_to_extract?: string;
451
+ include_scenes?: boolean;
452
+ include_usage?: boolean;
453
+ };
454
+ //endregion
455
+
456
+ function parseTranscribeData(
457
+ inner:
458
+ | { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string }
459
+ | { carousel_info: CarouselInfoJSON; videos: CarouselVideoResultJSON[] },
460
+ usage?: UsageBlock
461
+ ): TranscribeVideoResult {
462
+ if ('videos' in inner && 'carousel_info' in inner) {
463
+ return {
464
+ carousel_info: CarouselInfo.fromJSON(inner.carousel_info),
465
+ videos: inner.videos.map((v) => CarouselVideoResult.fromJSON(v)),
466
+ usage,
467
+ };
468
+ }
469
+ const single = inner as { video_info: VideoInfoJSON; transcript: TranscriptSegmentJSON[] | string };
470
+ return {
471
+ video_info: VideoInfo.fromJSON(single.video_info),
472
+ transcript: transcriptFromJSON(single.transcript)!,
473
+ usage,
474
+ };
475
+ }
476
+
477
+ /** What `include_scenes` adds beside the scenes themselves. */
478
+ interface SceneNotes {
479
+ frames_analyzed?: number;
480
+ scenes_error?: ScenesError;
481
+ transcript_error?: WatchTranscriptError;
482
+ }
483
+
484
+ /** The `data` block of an analysis: the same for a video, its background job and an uploaded file. */
485
+ interface AnalysisDataJSON extends SceneNotes {
486
+ transcript: TranscriptSegmentJSON[] | string;
487
+ transcript_analysis: AnalysisResultJSON;
488
+ scenes?: VideoSceneJSON[];
489
+ }
490
+
491
+ // The scene fields are set only when the response carries them, so a result asked without
492
+ // `include_scenes` keeps the shape it always had.
493
+ function pickSceneNotes(raw: SceneNotes): SceneNotes {
494
+ const notes: SceneNotes = {};
495
+ if (raw.frames_analyzed != null) notes.frames_analyzed = raw.frames_analyzed;
496
+ if (raw.scenes_error) notes.scenes_error = raw.scenes_error;
497
+ if (raw.transcript_error) notes.transcript_error = raw.transcript_error;
498
+ return notes;
499
+ }
500
+
501
+ function parseScenes(raw: VideoSceneJSON[] | undefined): { scenes?: VideoScene[] } {
502
+ return raw ? { scenes: raw.map((scene) => VideoScene.fromJSON(scene)) } : {};
503
+ }
504
+
505
+ function parseAnalysisData(raw: AnalysisDataJSON) {
506
+ return {
507
+ transcript: transcriptFromJSON(raw.transcript)!,
508
+ transcript_analysis: AnalysisResult.fromJSON(raw.transcript_analysis),
509
+ ...parseScenes(raw.scenes),
510
+ ...pickSceneNotes(raw),
511
+ };
512
+ }
513
+
514
+ function parseAnalyzeVideoData(
515
+ raw: AnalysisDataJSON & { video_info: VideoInfoJSON },
516
+ usage?: UsageBlock
517
+ ): AnalyzeVideoResult {
518
+ return { video_info: VideoInfo.fromJSON(raw.video_info), ...parseAnalysisData(raw), usage };
519
+ }
520
+
521
+ function buildAsyncJobParams(options?: SubmitOptions): Record<string, string> | undefined {
522
+ // Like the TikTok pollers, the async job pollers take include_usage as a query string value.
523
+ return options?.include_usage ? { include_usage: 'true' } : undefined;
524
+ }
525
+
526
+ function requireResult<T>(task: AsyncJob<T>): T {
527
+ if (task.result === null) {
528
+ const err = new VidNavigatorError(`Task ${task.task_id} completed without a result`);
529
+ err.task_id = task.task_id;
530
+ throw err;
531
+ }
532
+ return task.result;
533
+ }
534
+
535
+ /** TikTok results are paginated; fetch every page of a completed task and merge the items. */
536
+ async function collectAllPages<TTask extends { pagination?: TikTokProfilePagination }, TItem>(
537
+ fetchPage: (query: { cursor?: string; limit: number; include_usage?: boolean }) => Promise<TTask>,
538
+ items: (task: TTask) => TItem[],
539
+ setItems: (task: TTask, all: TItem[]) => void,
540
+ include_usage?: boolean
541
+ ): Promise<TTask> {
542
+ const first = await fetchPage({ limit: TIKTOK_PAGE_SIZE, include_usage });
543
+ const all = [...items(first)];
544
+ let cursor = first.pagination?.next_cursor ?? undefined;
545
+ while (cursor) {
546
+ const page = await fetchPage({ limit: TIKTOK_PAGE_SIZE, cursor });
547
+ all.push(...items(page));
548
+ cursor = page.pagination?.next_cursor ?? undefined;
549
+ }
550
+ setItems(first, all);
551
+ if (first.pagination) {
552
+ first.pagination = { ...first.pagination, limit: all.length, has_next: false, next_cursor: null };
553
+ }
554
+ return first;
555
+ }
556
+
557
+ const TIKTOK_PAGE_SIZE = 500;
558
+
559
+ interface OperationSpec<TInput, TTask extends PollableTask, TResult> {
560
+ jobType: string;
561
+ submit: (input: TInput) => Promise<JobInfo>;
562
+ fetchTask: (task_id: string, options: SubmitOptions) => Promise<TTask>;
563
+ toResult: (task: TTask, options: SubmitOptions) => Promise<TResult>;
564
+ }
565
+
566
+ function appendOptionalFormField(form: FormData, name: string, value: string | number | boolean | undefined): void {
567
+ if (value !== undefined) {
568
+ form.append(name, String(value));
569
+ }
570
+ }
571
+
572
+ function buildTikTokPollParams(query?: {
573
+ cursor?: string;
574
+ limit?: number;
575
+ include_usage?: boolean;
576
+ }): Record<string, string | number> | undefined {
577
+ if (!query) return undefined;
578
+ const params: Record<string, string | number> = {};
579
+ if (query.cursor !== undefined) params.cursor = query.cursor;
580
+ if (query.limit !== undefined) params.limit = query.limit;
581
+ // The TikTok pollers expect include_usage as a query string value.
582
+ if (query.include_usage) params.include_usage = 'true';
583
+ return params;
584
+ }
585
+
586
+ const _deprecationWarned = new Set<string>();
587
+
588
+ function warnDeprecated(oldName: string, newName: string): void {
589
+ if (_deprecationWarned.has(oldName)) return;
590
+ _deprecationWarned.add(oldName);
591
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
592
+ console.warn(
593
+ `[vidnavigator] ${oldName}() is deprecated and will be removed in a future release; use ${newName}() instead.`
594
+ );
595
+ }
596
+ }
597
+
598
+ export class VidNavigatorClient {
599
+ private client: AxiosInstance;
600
+
601
+ /**
602
+ * Speech-to-text transcription of any length (Instagram, TikTok, X, Facebook, Vimeo, ...),
603
+ * built on `POST /transcribe/async`.
604
+ *
605
+ * - `await vn.transcribe(url)` submits, polls, and returns the result.
606
+ * - `await vn.transcribe.submit(url)` returns a {@link Job} handle right away.
607
+ * - `vn.transcribe.resume(task_id)` reattaches to a job you already submitted.
608
+ */
609
+ readonly transcribe: TranscribeOperation;
610
+
611
+ /**
612
+ * What a video shows, scene by scene, next to what it says, built on `POST /watch/async`. The
613
+ * result is a {@link WatchResult}: `scenes` (for each one its `start` and `end` in seconds, a
614
+ * `description` of the picture and the `on_screen_text`), the `transcript` and `frames_analyzed`.
615
+ * Works with every platform `getTranscript` and `transcribe` support.
616
+ *
617
+ * A video without a transcript is not an error: `transcript` is empty and `transcript_error`
618
+ * says why. Same shapes as {@link VidNavigatorClient.transcribe}.
619
+ */
620
+ readonly watch: JobOperation<string | WatchInput, WatchAsyncJob, WatchResult>;
621
+
622
+ /**
623
+ * Analysis of an online video as a background job, built on `POST /analyze/video/async`: the
624
+ * same analysis and the same result as {@link VidNavigatorClient.analyzeVideo}, without holding
625
+ * a connection open while it runs. Use it with `include_scenes: true` on a video longer than
626
+ * about 10 minutes. Same shapes as {@link VidNavigatorClient.transcribe}.
627
+ */
628
+ readonly analyze: JobOperation<string | AnalyzeVideoInput, AnalyzeVideoAsyncJob, AnalyzeVideoResult>;
629
+
630
+ /**
631
+ * Structured-data extraction from a video of any length, built on `POST /extract/video/async`.
632
+ * The schema is validated when you submit. With `include_scenes: true` the fields are extracted
633
+ * from the transcript and from what the video shows. Same shapes as
634
+ * {@link VidNavigatorClient.transcribe}.
635
+ */
636
+ readonly extractVideo: JobOperation<ExtractVideoInput, ExtractVideoAsyncJob, ExtractDataResult>;
637
+
638
+ /**
639
+ * Structured claim analysis of an X/Twitter tweet (attached media of any length), built on
640
+ * `POST /tweet/statement/async`. Same shapes as {@link VidNavigatorClient.transcribe}.
641
+ */
642
+ readonly tweetStatement: JobOperation<string | TweetStatementInput, TweetStatementAsyncJob, TweetStatement>;
643
+
644
+ /**
645
+ * TikTok profile scrape, built on `POST /tiktok/profile`. The result is the completed task with
646
+ * every page of `videos` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
647
+ */
648
+ readonly tiktokProfile: JobOperation<string | TikTokProfileScrapeRequest, TikTokProfileTask, TikTokProfileTask>;
649
+
650
+ /**
651
+ * TikTok keyword search, built on `POST /tiktok/search`. The result is the completed task with
652
+ * every page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
653
+ */
654
+ readonly tiktokSearch: JobOperation<string | TikTokSearchRequest, TikTokSearchTask, TikTokSearchTask>;
655
+
656
+ /**
657
+ * TikTok LIVE search, built on `POST /tiktok/live/search`: rooms broadcasting now for a keyword,
658
+ * with their FLV / HLS / audio-only stream URLs. The result is the completed task with every
659
+ * page of `results` collected. Same shapes as {@link VidNavigatorClient.transcribe}.
660
+ */
661
+ readonly tiktokLiveSearch: JobOperation<string | TikTokLiveSearchRequest, TikTokLiveSearchTask, TikTokLiveSearchTask>;
662
+
663
+ constructor(config: SDKConfig) {
664
+ if (!config?.apiKey) {
665
+ throw new Error('An API key is required to use the VidNavigator SDK.');
666
+ }
667
+
668
+ this.client = axios.create({
669
+ baseURL: config.baseURL ?? 'https://api.vidnavigator.com/v1',
670
+ headers: {
671
+ 'X-API-Key': config.apiKey,
672
+ 'User-Agent': `vidnavigator-js/${SDK_VERSION}`,
673
+ },
674
+ ...config.axiosConfig,
675
+ });
676
+
677
+ this.transcribe = this.defineOperation({
678
+ jobType: 'transcribe',
679
+ submit: (input: string | TranscribeInput) =>
680
+ this.submitAsyncJob('/transcribe/async', typeof input === 'string' ? { video_url: input } : input),
681
+ fetchTask: (task_id, options) =>
682
+ this.getAsyncJob(`/transcribe/${encodeURIComponent(task_id)}`, options, (raw) => parseTranscribeData(raw)),
683
+ toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
684
+ }) as TranscribeOperation;
685
+
686
+ this.watch = this.defineOperation({
687
+ jobType: 'watch',
688
+ submit: (input: string | WatchInput) =>
689
+ this.submitAsyncJob('/watch/async', typeof input === 'string' ? { video_url: input } : input),
690
+ fetchTask: (task_id, options) =>
691
+ this.getAsyncJob(`/watch/${encodeURIComponent(task_id)}`, options, (raw: WatchResultJSON) =>
692
+ WatchResult.fromJSON(raw)
693
+ ),
694
+ toResult: async (task) => {
695
+ const watched = requireResult(task);
696
+ watched.usage = task.usage;
697
+ return watched;
698
+ },
699
+ });
700
+
701
+ this.analyze = this.defineOperation({
702
+ jobType: 'analyze_video',
703
+ submit: (input: string | AnalyzeVideoInput) =>
704
+ this.submitAsyncJob('/analyze/video/async', typeof input === 'string' ? { video_url: input } : input),
705
+ fetchTask: (task_id, options) =>
706
+ this.getAsyncJob(`/analyze/video/${encodeURIComponent(task_id)}`, options, (raw) =>
707
+ parseAnalyzeVideoData(raw)
708
+ ),
709
+ toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
710
+ });
711
+
712
+ this.extractVideo = this.defineOperation({
713
+ jobType: 'extract_video',
714
+ submit: (input: ExtractVideoInput) => this.submitExtractVideo(input),
715
+ fetchTask: (task_id, options) =>
716
+ this.getAsyncJob(
717
+ `/extract/video/${encodeURIComponent(task_id)}`,
718
+ options,
719
+ (raw) => raw as Record<string, unknown>
720
+ ),
721
+ toResult: async (task) => ({
722
+ data: requireResult(task),
723
+ video_info: task.video_info,
724
+ ...pickSceneNotes(task),
725
+ usage: task.usage,
726
+ }),
727
+ });
728
+
729
+ this.tweetStatement = this.defineOperation({
730
+ jobType: 'tweet_statement',
731
+ submit: (input: string | TweetStatementInput) =>
732
+ this.submitAsyncJob('/tweet/statement/async', typeof input === 'string' ? { tweet_id: input } : input),
733
+ fetchTask: (task_id, options) =>
734
+ this.getAsyncJob(`/tweet/statement/${encodeURIComponent(task_id)}`, options, (raw) =>
735
+ TweetStatement.fromJSON(raw)
736
+ ),
737
+ toResult: async (task) => {
738
+ const statement = requireResult(task);
739
+ statement.usage = task.usage;
740
+ return statement;
741
+ },
742
+ });
743
+
744
+ this.tiktokProfile = this.defineOperation({
745
+ jobType: 'tiktok_profile',
746
+ submit: async (input: string | TikTokProfileScrapeRequest) => {
747
+ const sub = await this.submitTikTokProfileScrape(typeof input === 'string' ? { profile_url: input } : input);
748
+ return { ...sub, job_type: 'tiktok_profile' };
749
+ },
750
+ // Status polls ask for one video only; the full result is paged in once the task completes.
751
+ fetchTask: (task_id) => this.getTikTokProfileScrape(task_id, { limit: 1 }),
752
+ toResult: (task, options) =>
753
+ collectAllPages(
754
+ (query) => this.getTikTokProfileScrape(task.task_id, query),
755
+ (page) => page.videos,
756
+ (page, all) => { page.videos = all; },
757
+ options.include_usage
758
+ ),
759
+ });
760
+
761
+ this.tiktokSearch = this.defineOperation({
762
+ jobType: 'tiktok_search',
763
+ submit: async (input: string | TikTokSearchRequest) => {
764
+ const sub = await this.submitTikTokSearch(typeof input === 'string' ? { query: input } : input);
765
+ return { ...sub, job_type: 'tiktok_search' };
766
+ },
767
+ fetchTask: (task_id) => this.getTikTokSearch(task_id, { limit: 1 }),
768
+ toResult: (task, options) =>
769
+ collectAllPages(
770
+ (query) => this.getTikTokSearch(task.task_id, query),
771
+ (page) => page.results,
772
+ (page, all) => { page.results = all; },
773
+ options.include_usage
774
+ ),
775
+ });
776
+
777
+ this.tiktokLiveSearch = this.defineOperation({
778
+ jobType: 'tiktok_live_search',
779
+ submit: async (input: string | TikTokLiveSearchRequest) => {
780
+ const sub = await this.submitTikTokLiveSearch(typeof input === 'string' ? { query: input } : input);
781
+ return { ...sub, job_type: 'tiktok_live_search' };
782
+ },
783
+ fetchTask: (task_id) => this.getTikTokLiveSearch(task_id, { limit: 1 }),
784
+ toResult: (task, options) =>
785
+ collectAllPages(
786
+ (query) => this.getTikTokLiveSearch(task.task_id, query),
787
+ (page) => page.results,
788
+ (page, all) => { page.results = all; },
789
+ options.include_usage
790
+ ),
791
+ });
792
+ }
793
+
794
+ private defineOperation<TInput, TTask extends PollableTask, TResult>(
795
+ spec: OperationSpec<TInput, TTask, TResult>
796
+ ): JobOperation<TInput, TTask, TResult> {
797
+ const makeJob = (info: JobInfo, options: SubmitOptions = {}) =>
798
+ new Job<TTask, TResult>(
799
+ info,
800
+ () => spec.fetchTask(info.task_id, options),
801
+ (task) => spec.toResult(task, options)
802
+ );
803
+ const submit = async (input: TInput, options?: SubmitOptions) => makeJob(await spec.submit(input), options);
804
+ const run = async (input: TInput, options: RunOptions<TTask> = {}) => {
805
+ const { include_usage, ...pollOptions } = options;
806
+ const job = await submit(input, { include_usage });
807
+ return job.result(pollOptions);
808
+ };
809
+ return Object.assign(run, {
810
+ submit,
811
+ resume: (task_id: string, options?: SubmitOptions) =>
812
+ makeJob({ task_id, job_type: spec.jobType }, options),
813
+ });
814
+ }
815
+
816
+ private async submitAsyncJob(url: string, body: unknown, headers?: Record<string, string>): Promise<JobInfo> {
817
+ const response = await this.request<ApiSuccessResponse<AsyncJobAcceptedJSON>>('POST', url, body, undefined, headers);
818
+ const accepted = AsyncJobAccepted.fromJSON(response.data);
819
+ return { ...accepted, job_type: accepted.job_type ?? url.split('/')[1] };
820
+ }
821
+
822
+ private submitExtractVideo(input: ExtractVideoInput): Promise<JobInfo> {
823
+ if ('schemaFilePath' in input) {
824
+ const form = new FormData();
825
+ form.append('video_url', input.video_url);
826
+ form.append('schema', fs.createReadStream(input.schemaFilePath));
827
+ appendOptionalFormField(form, 'what_to_extract', input.what_to_extract);
828
+ appendOptionalFormField(form, 'transcribe', input.transcribe);
829
+ appendOptionalFormField(form, 'include_scenes', input.include_scenes);
830
+ appendOptionalFormField(form, 'webhook_url', input.webhook_url);
831
+ return this.submitAsyncJob('/extract/video/async', form, form.getHeaders());
832
+ }
833
+ return this.submitAsyncJob('/extract/video/async', input);
834
+ }
835
+
836
+ private async getAsyncJob<T>(
837
+ url: string,
838
+ options: SubmitOptions | undefined,
839
+ parseResult: (raw: any) => T
840
+ ): Promise<AsyncJob<T>> {
841
+ const response = await this.request<ApiSuccessResponse<AsyncJobJSON>>(
842
+ 'GET',
843
+ url,
844
+ undefined,
845
+ buildAsyncJobParams(options)
846
+ );
847
+ const job = AsyncJob.fromJSON(response.data, parseResult);
848
+ if (response.usage) job.usage = UsageBlock.fromJSON(response.usage);
849
+ return job;
850
+ }
851
+
852
+ private async request<T>(
853
+ method: 'GET' | 'POST' | 'DELETE' | 'PUT',
854
+ url: string,
855
+ data?: any,
856
+ params?: any,
857
+ extraHeaders?: any,
858
+ minTimeoutMs?: number
859
+ ): Promise<T> {
860
+ // A call known to run long raises a configured timeout, never lowers it
861
+ // (0 / unset means no timeout at all).
862
+ const configured = this.client.defaults.timeout;
863
+ const timeout = minTimeoutMs && configured ? Math.max(configured, minTimeoutMs) : undefined;
864
+ try {
865
+ const response = await this.client.request<T>({
866
+ method,
867
+ url,
868
+ data,
869
+ params,
870
+ headers: extraHeaders,
871
+ ...(timeout !== undefined ? { timeout } : {}),
872
+ });
873
+ return response.data;
874
+ } catch (error: any) {
875
+ if (axios.isAxiosError(error) && error.response) {
876
+ throw buildApiError(error.response.status, error.response.data, error.message);
877
+ }
878
+ throw new VidNavigatorError(error.message);
879
+ }
880
+ }
881
+
882
+ //region --- Transcripts ---
883
+ /**
884
+ * Get a transcript for any supported video. The endpoint auto-detects the
885
+ * platform (YouTube, Vimeo, X/Twitter, TikTok, Facebook, Dailymotion, Loom, Snapchat, etc.)
886
+ * from `video_url`. For Instagram, use {@link VidNavigatorClient.transcribeVideo}.
887
+ */
888
+ async getTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
889
+ const response = await this.request<
890
+ ApiSuccessResponse<{
891
+ video_info: VideoInfoJSON;
892
+ transcript: TranscriptSegmentJSON[] | string;
893
+ }>
894
+ >('POST', '/transcript', payload);
895
+
896
+ return {
897
+ video_info: VideoInfo.fromJSON(response.data.video_info),
898
+ transcript: transcriptFromJSON(response.data.transcript)!,
899
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
900
+ };
901
+ }
902
+
903
+ /**
904
+ * @deprecated There is now a single `/transcript` endpoint that auto-detects the
905
+ * platform. Use {@link VidNavigatorClient.getTranscript} instead. This alias
906
+ * forwards to `getTranscript` and will be removed in a future release.
907
+ */
908
+ async getYouTubeTranscript(payload: TranscriptRequestPayload): Promise<TranscriptResult> {
909
+ warnDeprecated('getYouTubeTranscript', 'getTranscript');
910
+ return this.getTranscript(payload);
911
+ }
912
+
913
+ /**
914
+ * Speech-to-text transcription. Blocking convenience wrapper around {@link VidNavigatorClient.transcribe}:
915
+ * submits to `POST /transcribe/async` and polls until the job finishes, so media of any length works.
916
+ */
917
+ async transcribeVideo(
918
+ payload: TranscribeVideoPayload,
919
+ options?: PollOptions<TranscribeAsyncJob>
920
+ ): Promise<TranscribeVideoResult> {
921
+ const { include_usage, ...input } = payload;
922
+ return this.transcribe(input, { ...options, include_usage });
923
+ }
924
+ //endregion
925
+
926
+ //region --- Watch ---
927
+ /**
928
+ * What a video shows, scene by scene, next to what it says. Blocking convenience wrapper around
929
+ * {@link VidNavigatorClient.watch}: submits to `POST /watch/async` and polls until the job
930
+ * finishes, so media of any length works.
931
+ */
932
+ async watchVideo(payload: WatchVideoPayload, options?: PollOptions<WatchAsyncJob>): Promise<WatchResult> {
933
+ const { include_usage, ...input } = payload;
934
+ return this.watch(input, { ...options, include_usage });
935
+ }
936
+ //endregion
937
+
938
+ //region --- TikTok ---
939
+ async submitTikTokProfileScrape(
940
+ payload: TikTokProfileScrapeRequest
941
+ ): Promise<TikTokProfileScrapeSubmission> {
942
+ const response = await this.request<ApiSuccessResponse<TikTokProfileScrapeSubmissionJSON>>(
943
+ 'POST',
944
+ '/tiktok/profile',
945
+ payload
946
+ );
947
+ return TikTokProfileScrapeSubmission.fromJSON(response.data);
948
+ }
949
+
950
+ async getTikTokProfileScrape(
951
+ task_id: string,
952
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
953
+ ): Promise<TikTokProfileTask> {
954
+ const response = await this.request<ApiSuccessResponse<TikTokProfileTaskJSON>>(
955
+ 'GET',
956
+ `/tiktok/profile/${task_id}`,
957
+ undefined,
958
+ buildTikTokPollParams(query)
959
+ );
960
+ const task = TikTokProfileTask.fromJSON(response.data);
961
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
962
+ return task;
963
+ }
964
+
965
+ async submitTikTokSearch(payload: TikTokSearchRequest): Promise<TikTokSearchSubmission> {
966
+ const response = await this.request<ApiSuccessResponse<TikTokSearchSubmissionJSON>>(
967
+ 'POST',
968
+ '/tiktok/search',
969
+ payload
970
+ );
971
+ return TikTokSearchSubmission.fromJSON(response.data);
972
+ }
973
+
974
+ async getTikTokSearch(
975
+ task_id: string,
976
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
977
+ ): Promise<TikTokSearchTask> {
978
+ const response = await this.request<ApiSuccessResponse<TikTokSearchTaskJSON>>(
979
+ 'GET',
980
+ `/tiktok/search/${task_id}`,
981
+ undefined,
982
+ buildTikTokPollParams(query)
983
+ );
984
+ const task = TikTokSearchTask.fromJSON(response.data);
985
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
986
+ return task;
987
+ }
988
+
989
+ async submitTikTokLiveSearch(payload: TikTokLiveSearchRequest): Promise<TikTokLiveSearchSubmission> {
990
+ const response = await this.request<ApiSuccessResponse<TikTokLiveSearchSubmissionJSON>>(
991
+ 'POST',
992
+ '/tiktok/live/search',
993
+ payload
994
+ );
995
+ return TikTokLiveSearchSubmission.fromJSON(response.data);
996
+ }
997
+
998
+ async getTikTokLiveSearch(
999
+ task_id: string,
1000
+ query?: { cursor?: string; limit?: number; include_usage?: boolean }
1001
+ ): Promise<TikTokLiveSearchTask> {
1002
+ const response = await this.request<ApiSuccessResponse<TikTokLiveSearchTaskJSON>>(
1003
+ 'GET',
1004
+ `/tiktok/live/search/${task_id}`,
1005
+ undefined,
1006
+ buildTikTokPollParams(query)
1007
+ );
1008
+ const task = TikTokLiveSearchTask.fromJSON(response.data);
1009
+ if (response.usage) task.usage = UsageBlock.fromJSON(response.usage);
1010
+ return task;
1011
+ }
1012
+
1013
+ /**
1014
+ * One TikTok LIVE room, right away (`POST /tiktok/live/room`, no job): by `room_id`, `username`
1015
+ * or `url`, exactly one. The room says whether it is live or ended (and when), its viewers and new
1016
+ * followers, the streamer's bio, and more. With `include_comments: true` the result also has the
1017
+ * latest comments (up to 50), the pinned comment, the intro and the top viewers.
1018
+ *
1019
+ * The room has no likes, comment count or share count: TikTok gives those to LIVE search only.
1020
+ * A room or account that does not exist throws `NotFoundError` (`error_code` `live_not_found`)
1021
+ * and is not billed. Billing: 1 `residential_request`, 2 with `include_comments`.
1022
+ */
1023
+ async getTikTokLiveRoom(payload: TikTokLiveRoomRequest): Promise<TikTokLiveRoomResult> {
1024
+ const targets = (['room_id', 'username', 'url'] as const).filter((key) => payload?.[key]);
1025
+ if (targets.length !== 1) {
1026
+ throw new VidNavigatorError('Pass exactly one of room_id, username or url');
1027
+ }
1028
+ let body: TikTokLiveRoomRequest = payload;
1029
+ const roomId: unknown = payload.room_id;
1030
+ if (typeof roomId === 'number') {
1031
+ if (!Number.isSafeInteger(roomId)) {
1032
+ throw new VidNavigatorError(
1033
+ 'room_id has more digits than a JavaScript number holds: pass it as a string'
1034
+ );
1035
+ }
1036
+ body = { ...payload, room_id: String(roomId) };
1037
+ }
1038
+ const response = await this.request<ApiSuccessResponse<TikTokLiveRoomResultJSON>>(
1039
+ 'POST',
1040
+ '/tiktok/live/room',
1041
+ body,
1042
+ undefined,
1043
+ undefined,
1044
+ LIVE_ROOM_TIMEOUT_MS
1045
+ );
1046
+ const result = tiktokLiveRoomResultFromJSON(response.data);
1047
+ if (response.usage) result.usage = UsageBlock.fromJSON(response.usage);
1048
+ return result;
1049
+ }
1050
+ //endregion
1051
+
1052
+ //region --- Files ---
1053
+ async getFiles(query?: {
1054
+ limit?: number;
1055
+ offset?: number;
1056
+ status?: 'processing' | 'completed' | 'failed' | 'cancelled';
1057
+ namespace_id?: string;
1058
+ }): Promise<{
1059
+ files: FileInfo[];
1060
+ total_count: number;
1061
+ limit: number;
1062
+ offset: number;
1063
+ has_more: boolean;
1064
+ }> {
1065
+ const response = await this.request<
1066
+ ApiSuccessResponse<{
1067
+ files: FileInfoJSON[];
1068
+ total_count: number;
1069
+ limit: number;
1070
+ offset: number;
1071
+ has_more: boolean;
1072
+ }>
1073
+ >('GET', '/files', undefined, query);
1074
+
1075
+ return {
1076
+ files: response.data.files.map(FileInfo.fromJSON),
1077
+ total_count: response.data.total_count,
1078
+ limit: response.data.limit,
1079
+ offset: response.data.offset,
1080
+ has_more: response.data.has_more,
1081
+ };
1082
+ }
1083
+
1084
+ /**
1085
+ * A file's metadata, its transcript once it has one, and its scenes once they are analyzed.
1086
+ * `file_info.scenes_status` says where the scene analysis stands; when it is `completed`, the
1087
+ * result has `scenes`, as {@link VidNavigatorClient.watch} returns them for an online video.
1088
+ */
1089
+ async getFile(file_id: string, query?: { transcript_text?: boolean }): Promise<GetFileResult> {
1090
+ const response = await this.request<
1091
+ ApiSuccessResponse<{
1092
+ file_info: FileInfoJSON;
1093
+ transcript?: TranscriptSegmentJSON[] | string;
1094
+ scenes?: VideoSceneJSON[];
1095
+ }>
1096
+ >('GET', `/file/${file_id}`, undefined, query);
1097
+
1098
+ return {
1099
+ file_info: FileInfo.fromJSON(response.data.file_info),
1100
+ transcript: transcriptFromJSON(response.data.transcript),
1101
+ ...parseScenes(response.data.scenes),
1102
+ };
1103
+ }
1104
+
1105
+ /**
1106
+ * Upload an audio or video file. With `include_scenes: true` the picture of a video file is
1107
+ * analyzed as well, next to its transcription: follow `file_info.scenes_status` with
1108
+ * {@link VidNavigatorClient.getFile}, which returns the scenes once it is `completed`. An audio
1109
+ * file has no picture: its `scenes_status` is `failed`, with `frames_not_available`.
1110
+ */
1111
+ async uploadFile(options: {
1112
+ filePath: string;
1113
+ wait_for_completion?: boolean;
1114
+ namespace_ids?: string[];
1115
+ /** Default false. `true` also analyzes the scenes of the file (video files only). */
1116
+ include_scenes?: boolean;
1117
+ }): Promise<UploadFileResult> {
1118
+ const form = new FormData();
1119
+ form.append('file', fs.createReadStream(options.filePath));
1120
+ if (options.wait_for_completion) {
1121
+ form.append('wait_for_completion', 'true');
1122
+ }
1123
+ if (options.namespace_ids?.length) {
1124
+ form.append('namespace_ids', JSON.stringify(options.namespace_ids));
1125
+ }
1126
+ appendOptionalFormField(form, 'include_scenes', options.include_scenes);
1127
+
1128
+ try {
1129
+ const response = await this.client.post<{
1130
+ status: 'success' | 'accepted';
1131
+ file_id: string;
1132
+ file_name: string;
1133
+ file_status: 'processing' | 'completed';
1134
+ message: string;
1135
+ note?: string;
1136
+ data?: { file_info: FileInfoJSON };
1137
+ }>('/upload/file', form, { headers: form.getHeaders() });
1138
+
1139
+ const body = response.data;
1140
+ const fileInfo = body.data?.file_info ? FileInfo.fromJSON(body.data.file_info) : undefined;
1141
+ if (body.status === 'accepted') {
1142
+ return {
1143
+ status: 'accepted',
1144
+ file_id: body.file_id,
1145
+ file_name: body.file_name,
1146
+ file_status: body.file_status as 'processing',
1147
+ message: body.message,
1148
+ note: body.note,
1149
+ file_info: fileInfo,
1150
+ };
1151
+ }
1152
+ return {
1153
+ status: 'success',
1154
+ file_id: body.file_id,
1155
+ file_name: body.file_name,
1156
+ file_status: body.file_status,
1157
+ message: body.message,
1158
+ file_info: fileInfo!,
1159
+ };
1160
+ } catch (error: any) {
1161
+ if (axios.isAxiosError(error) && error.response) {
1162
+ throw buildApiError(error.response.status, error.response.data, error.message);
1163
+ }
1164
+ throw new VidNavigatorError(error.message);
1165
+ }
1166
+ }
1167
+
1168
+ async deleteFile(file_id: string): Promise<{ file_id: string; file_name: string; message: string }> {
1169
+ const response = await this.request<
1170
+ ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
1171
+ >('DELETE', `/file/${file_id}/delete`);
1172
+ return response.data;
1173
+ }
1174
+
1175
+ async getFileUrl(file_id: string): Promise<{ file_id: string; file_url: string }> {
1176
+ const response = await this.request<
1177
+ ApiSuccessResponse<{ file_id: string; file_url: string }>
1178
+ >('GET', `/file/${file_id}/url`);
1179
+ return response.data;
1180
+ }
1181
+
1182
+ async retryFileProcessing(
1183
+ file_id: string
1184
+ ): Promise<{ file_id: string; file_name: string; file_status: string; message: string }> {
1185
+ const response = await this.request<
1186
+ ApiSuccessResponse<{
1187
+ file_id: string;
1188
+ file_name: string;
1189
+ file_status: string;
1190
+ message: string;
1191
+ }>
1192
+ >('POST', `/file/${file_id}/retry`);
1193
+ return response.data;
1194
+ }
1195
+
1196
+ /**
1197
+ * Start the scene analysis of a file already uploaded: what its picture shows, scene by scene,
1198
+ * with the text readable on screen. The scenes of a file are analyzed once and kept with it.
1199
+ *
1200
+ * The answer has `scenes_status` `processing` when the analysis was started or is already
1201
+ * running, and `completed` when the scenes are already there (nothing new is started). Follow
1202
+ * `file_info.scenes_status` with {@link VidNavigatorClient.getFile}, which returns the scenes
1203
+ * once it is `completed`; `analyzeFile` and `extractFileData` read them with `include_scenes: true`.
1204
+ *
1205
+ * An audio file has no picture: the call throws `BadRequestError` with `error_code`
1206
+ * `frames_not_available`.
1207
+ */
1208
+ async analyzeFileScenes(file_id: string): Promise<AnalyzeFileScenesResult> {
1209
+ const response = await this.request<ApiSuccessResponse<AnalyzeFileScenesResult>>(
1210
+ 'POST',
1211
+ `/file/${file_id}/scenes`
1212
+ );
1213
+ return response.data;
1214
+ }
1215
+
1216
+ async cancelFileUpload(
1217
+ file_id: string
1218
+ ): Promise<{ file_id: string; file_name: string; message: string }> {
1219
+ const response = await this.request<
1220
+ ApiSuccessResponse<{ file_id: string; file_name: string; message: string }>
1221
+ >('POST', `/file/${file_id}/cancel`);
1222
+ return response.data;
1223
+ }
1224
+ //endregion
1225
+
1226
+ //region --- Namespaces ---
1227
+ async getNamespaces(): Promise<Namespace[]> {
1228
+ const response = await this.request<ApiSuccessResponse<NamespaceJSON[]>>('GET', '/namespaces');
1229
+ return response.data.map((n) => Namespace.fromJSON(n));
1230
+ }
1231
+
1232
+ async createNamespace(payload: { name: string }): Promise<Namespace> {
1233
+ const response = await this.request<ApiSuccessResponse<NamespaceJSON>>('POST', '/namespaces', payload);
1234
+ return Namespace.fromJSON(response.data);
1235
+ }
1236
+
1237
+ async updateNamespace(namespace_id: string, payload: { name: string }): Promise<{ message: string }> {
1238
+ const body = await this.request<{ status: string; message: string }>(
1239
+ 'PUT',
1240
+ `/namespaces/${namespace_id}`,
1241
+ payload
1242
+ );
1243
+ return { message: body.message };
1244
+ }
1245
+
1246
+ async deleteNamespace(namespace_id: string): Promise<{ message: string }> {
1247
+ const body = await this.request<{ status: string; message: string }>(
1248
+ 'DELETE',
1249
+ `/namespaces/${namespace_id}`
1250
+ );
1251
+ return { message: body.message };
1252
+ }
1253
+
1254
+ async updateFileNamespaces(
1255
+ file_id: string,
1256
+ payload: { namespace_ids: string[] }
1257
+ ): Promise<{ message: string; namespace_ids: string[]; namespaces: NamespaceRef[] }> {
1258
+ const body = await this.request<{
1259
+ status: string;
1260
+ message: string;
1261
+ data: { namespace_ids: string[]; namespaces: NamespaceRefJSON[] };
1262
+ }>('PUT', `/file/${file_id}/namespaces`, payload);
1263
+ return {
1264
+ message: body.message,
1265
+ namespace_ids: body.data.namespace_ids,
1266
+ namespaces: body.data.namespaces.map(NamespaceRef.fromJSON),
1267
+ };
1268
+ }
1269
+ //endregion
1270
+
1271
+ //region --- Analysis ---
1272
+ /**
1273
+ * Analyze an online video: a summary, the people, places and key subjects, and the answer to
1274
+ * an optional `query`. With `include_scenes: true` the analysis is made from the transcript and
1275
+ * from what the video shows, and the result also has `scenes` and `frames_analyzed`, as
1276
+ * {@link VidNavigatorClient.watch} returns them. When the picture cannot be read, the analysis
1277
+ * is made from the transcript alone and `scenes_error` says why; a video without a transcript
1278
+ * is analyzed from its scenes, and `transcript_error` says why the transcript is missing.
1279
+ *
1280
+ * This call waits on one HTTP request. With `include_scenes` on a video longer than about
1281
+ * 10 minutes, use {@link VidNavigatorClient.analyze}, which runs the same analysis as a
1282
+ * background job.
1283
+ */
1284
+ async analyzeVideo(payload: AnalyzeVideoPayload): Promise<AnalyzeVideoResult> {
1285
+ const response = await this.request<ApiSuccessResponse<AnalysisDataJSON & { video_info: VideoInfoJSON }>>(
1286
+ 'POST',
1287
+ '/analyze/video',
1288
+ payload
1289
+ );
1290
+
1291
+ return parseAnalyzeVideoData(response.data, response.usage ? UsageBlock.fromJSON(response.usage) : undefined);
1292
+ }
1293
+
1294
+ /**
1295
+ * Analyze an uploaded file. With `include_scenes: true` the analysis is made from the transcript
1296
+ * of the file and its scenes together, and the result also has `scenes` and `frames_analyzed`.
1297
+ * The scenes are the ones kept with the file: ask for them at the upload (`include_scenes`) or
1298
+ * with {@link VidNavigatorClient.analyzeFileScenes}. A file that has none is refused with
1299
+ * `ScenesNotAvailableError` (HTTP 409), whose `scenes_status` says where their analysis stands.
1300
+ */
1301
+ async analyzeFile(payload: AnalyzeFilePayload): Promise<AnalyzeFileResult> {
1302
+ const response = await this.request<ApiSuccessResponse<AnalysisDataJSON & { file_info: FileInfoJSON }>>(
1303
+ 'POST',
1304
+ '/analyze/file',
1305
+ payload
1306
+ );
1307
+
1308
+ return {
1309
+ file_info: FileInfo.fromJSON(response.data.file_info),
1310
+ ...parseAnalysisData(response.data),
1311
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1312
+ };
1313
+ }
1314
+
1315
+ /**
1316
+ * Structured claim analysis of an X/Twitter tweet. Blocking convenience wrapper around
1317
+ * {@link VidNavigatorClient.tweetStatement}: submits to `POST /tweet/statement/async` and polls.
1318
+ */
1319
+ async getTweetStatement(
1320
+ payload: TweetStatementPayload,
1321
+ options?: RunOptions<TweetStatementAsyncJob>
1322
+ ): Promise<TweetStatement> {
1323
+ return this.tweetStatement(payload, options);
1324
+ }
1325
+ //endregion
1326
+
1327
+ //region --- Extraction ---
1328
+ /**
1329
+ * Structured-data extraction from an online video. Blocking convenience wrapper around
1330
+ * {@link VidNavigatorClient.extractVideo}: submits to `POST /extract/video/async` and polls, so
1331
+ * media of any length works. The result carries the extracted `data` and the video's `video_info`.
1332
+ * With `include_scenes: true` the fields are extracted from the transcript and from what the video
1333
+ * shows, and the result also has `frames_analyzed`.
1334
+ */
1335
+ async extractVideoData(
1336
+ payload: ExtractVideoDataPayload | ExtractVideoDataMultipartPayload,
1337
+ options?: PollOptions<ExtractVideoAsyncJob>
1338
+ ): Promise<ExtractDataResult> {
1339
+ const { include_usage, ...input } = payload;
1340
+ return this.extractVideo(input as ExtractVideoInput, { ...options, include_usage });
1341
+ }
1342
+
1343
+ /**
1344
+ * Structured-data extraction from an uploaded file. With `include_scenes: true` the fields are
1345
+ * extracted from the transcript of the file and its scenes together, and the result has
1346
+ * `frames_analyzed`. The scenes are the ones kept with the file: ask for them at the upload
1347
+ * (`include_scenes`) or with {@link VidNavigatorClient.analyzeFileScenes}. A file that has none
1348
+ * is refused with `ScenesNotAvailableError` (HTTP 409).
1349
+ */
1350
+ async extractFileData(
1351
+ payload: ExtractFileDataPayload | ExtractFileDataMultipartPayload
1352
+ ): Promise<ExtractDataResult> {
1353
+ type ExtractFileBody = {
1354
+ status: 'success';
1355
+ data: Record<string, unknown>;
1356
+ file_info?: FileInfoJSON;
1357
+ usage?: UsageBlockJSON;
1358
+ } & SceneNotes;
1359
+ let body: ExtractFileBody;
1360
+
1361
+ if ('schemaFilePath' in payload) {
1362
+ const form = new FormData();
1363
+ form.append('file_id', payload.file_id);
1364
+ form.append('schema', fs.createReadStream(payload.schemaFilePath));
1365
+ appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
1366
+ appendOptionalFormField(form, 'include_scenes', payload.include_scenes);
1367
+ appendOptionalFormField(form, 'include_usage', payload.include_usage);
1368
+ body = await this.request<ExtractFileBody>('POST', '/extract/file', form, undefined, form.getHeaders());
1369
+ } else {
1370
+ body = await this.request<ExtractFileBody>('POST', '/extract/file', payload);
1371
+ }
1372
+
1373
+ return {
1374
+ data: body.data,
1375
+ file_info: body.file_info ? FileInfo.fromJSON(body.file_info) : undefined,
1376
+ ...pickSceneNotes(body),
1377
+ usage: body.usage ? UsageBlock.fromJSON(body.usage) : undefined,
1378
+ };
1379
+ }
1380
+ //endregion
1381
+
1382
+ //region --- Search ---
1383
+ /**
1384
+ * Search YouTube for videos with AI analysis and ranking.
1385
+ *
1386
+ * If the account runs out of `residential_request` credits mid-search, the API
1387
+ * returns HTTP 402 with `status: "partial"` and the videos analysed so far. The
1388
+ * SDK surfaces that partial payload (results, `status: "partial"`, `error_code`,
1389
+ * and `usage` when requested) instead of throwing.
1390
+ */
1391
+ async searchYouTube(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1392
+ let response: {
1393
+ status?: 'success' | 'partial';
1394
+ error_code?: string;
1395
+ data: {
1396
+ results: VideoSearchResultJSON[];
1397
+ query: string;
1398
+ total_found: number;
1399
+ explanation?: string;
1400
+ };
1401
+ usage?: UsageBlockJSON;
1402
+ };
1403
+
1404
+ try {
1405
+ response = await this.request('POST', '/youtube/search', payload);
1406
+ } catch (error: any) {
1407
+ const body = error?.details;
1408
+ if (error instanceof PaymentRequiredError && body?.status === 'partial' && body?.data) {
1409
+ response = body;
1410
+ } else {
1411
+ throw error;
1412
+ }
1413
+ }
1414
+
1415
+ return {
1416
+ results: (response.data.results ?? []).map(VideoSearchResult.fromJSON),
1417
+ query: response.data.query,
1418
+ total_found: response.data.total_found,
1419
+ explanation: response.data.explanation,
1420
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1421
+ status: response.status,
1422
+ error_code: response.error_code,
1423
+ };
1424
+ }
1425
+
1426
+ /**
1427
+ * @deprecated `/search/video` moved to `/youtube/search`. Use
1428
+ * {@link VidNavigatorClient.searchYouTube} instead. This alias forwards to
1429
+ * `searchYouTube` and will be removed in a future release.
1430
+ */
1431
+ async searchVideos(payload: SearchYouTubePayload): Promise<SearchYouTubeResult> {
1432
+ warnDeprecated('searchVideos', 'searchYouTube');
1433
+ return this.searchYouTube(payload);
1434
+ }
1435
+
1436
+ async searchFiles(payload: SearchFilesPayload): Promise<SearchFilesResult> {
1437
+ const response = await this.request<
1438
+ ApiSuccessResponse<{
1439
+ results: FileSearchResultJSON[];
1440
+ query: string;
1441
+ total_found: number;
1442
+ explanation?: string;
1443
+ }>
1444
+ >('POST', '/search/file', payload);
1445
+
1446
+ return {
1447
+ results: response.data.results.map(FileSearchResult.fromJSON),
1448
+ query: response.data.query,
1449
+ total_found: response.data.total_found,
1450
+ explanation: response.data.explanation,
1451
+ usage: response.usage ? UsageBlock.fromJSON(response.usage) : undefined,
1452
+ };
1453
+ }
1454
+ //endregion
1455
+
1456
+ //region --- System ---
1457
+ async getUsage(): Promise<UsageData> {
1458
+ const response = await this.request<ApiSuccessResponse<UsageDataJSON>>('GET', '/usage');
1459
+ return UsageData.fromJSON(response.data);
1460
+ }
1461
+
1462
+ async healthCheck(): Promise<{
1463
+ status?: string;
1464
+ message?: string;
1465
+ version?: string;
1466
+ endpoints?: Array<{
1467
+ path?: string;
1468
+ method?: string;
1469
+ description?: string;
1470
+ auth_required?: boolean;
1471
+ }>;
1472
+ }> {
1473
+ const response = await this.client.get('/health');
1474
+ return response.data;
1475
+ }
1476
+ //endregion
1477
+ }