vidnavigator 1.0.4 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -17,29 +17,93 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.VidNavigatorClient = exports.SDK_VERSION = void 0;
20
+ exports.VidNavigatorClient = exports.SDK_VERSION = exports.Job = void 0;
21
21
  const axios_1 = __importDefault(require("axios"));
22
22
  const form_data_1 = __importDefault(require("form-data"));
23
23
  const fs_1 = __importDefault(require("fs"));
24
24
  const models_1 = require("./models");
25
25
  const errors_1 = require("./errors");
26
+ const http_1 = require("./http");
27
+ const jobs_1 = require("./jobs");
26
28
  __exportStar(require("./models"), exports);
27
29
  __exportStar(require("./errors"), exports);
30
+ __exportStar(require("./webhooks"), exports);
31
+ var jobs_2 = require("./jobs");
32
+ Object.defineProperty(exports, "Job", { enumerable: true, get: function () { return jobs_2.Job; } });
28
33
  /** SDK version (keep in sync with package.json) */
29
- exports.SDK_VERSION = '1.0.4';
34
+ exports.SDK_VERSION = '2.0.0';
30
35
  //endregion
31
- function parseApiErrorPayload(data) {
32
- const errorField = data?.error;
33
- const errorCode = typeof errorField === 'string' ? errorField : errorField?.code;
34
- const errorMessage = data?.message ??
35
- (typeof errorField === 'object' ? errorField?.message : undefined);
36
- return { errorCode, errorMessage, details: data };
36
+ function parseTranscribeData(inner, usage) {
37
+ if ('videos' in inner && 'carousel_info' in inner) {
38
+ return {
39
+ carousel_info: models_1.CarouselInfo.fromJSON(inner.carousel_info),
40
+ videos: inner.videos.map((v) => models_1.CarouselVideoResult.fromJSON(v)),
41
+ usage,
42
+ };
43
+ }
44
+ const single = inner;
45
+ return {
46
+ video_info: models_1.VideoInfo.fromJSON(single.video_info),
47
+ transcript: (0, models_1.transcriptFromJSON)(single.transcript),
48
+ usage,
49
+ };
50
+ }
51
+ function buildAsyncJobParams(options) {
52
+ // Like the TikTok pollers, the async job pollers take include_usage as a query string value.
53
+ return options?.include_usage ? { include_usage: 'true' } : undefined;
54
+ }
55
+ function requireResult(task) {
56
+ if (task.result === null) {
57
+ const err = new errors_1.VidNavigatorError(`Task ${task.task_id} completed without a result`);
58
+ err.task_id = task.task_id;
59
+ throw err;
60
+ }
61
+ return task.result;
62
+ }
63
+ /** TikTok results are paginated; fetch every page of a completed task and merge the items. */
64
+ async function collectAllPages(fetchPage, items, setItems, include_usage) {
65
+ const first = await fetchPage({ limit: TIKTOK_PAGE_SIZE, include_usage });
66
+ const all = [...items(first)];
67
+ let cursor = first.pagination?.next_cursor ?? undefined;
68
+ while (cursor) {
69
+ const page = await fetchPage({ limit: TIKTOK_PAGE_SIZE, cursor });
70
+ all.push(...items(page));
71
+ cursor = page.pagination?.next_cursor ?? undefined;
72
+ }
73
+ setItems(first, all);
74
+ if (first.pagination) {
75
+ first.pagination = { ...first.pagination, limit: all.length, has_next: false, next_cursor: null };
76
+ }
77
+ return first;
37
78
  }
79
+ const TIKTOK_PAGE_SIZE = 500;
38
80
  function appendOptionalFormField(form, name, value) {
39
81
  if (value !== undefined) {
40
82
  form.append(name, String(value));
41
83
  }
42
84
  }
85
+ function buildTikTokPollParams(query) {
86
+ if (!query)
87
+ return undefined;
88
+ const params = {};
89
+ if (query.cursor !== undefined)
90
+ params.cursor = query.cursor;
91
+ if (query.limit !== undefined)
92
+ params.limit = query.limit;
93
+ // The TikTok pollers expect include_usage as a query string value.
94
+ if (query.include_usage)
95
+ params.include_usage = 'true';
96
+ return params;
97
+ }
98
+ const _deprecationWarned = new Set();
99
+ function warnDeprecated(oldName, newName) {
100
+ if (_deprecationWarned.has(oldName))
101
+ return;
102
+ _deprecationWarned.add(oldName);
103
+ if (typeof console !== 'undefined' && typeof console.warn === 'function') {
104
+ console.warn(`[vidnavigator] ${oldName}() is deprecated and will be removed in a future release; use ${newName}() instead.`);
105
+ }
106
+ }
43
107
  class VidNavigatorClient {
44
108
  constructor(config) {
45
109
  if (!config?.apiKey) {
@@ -53,6 +117,84 @@ class VidNavigatorClient {
53
117
  },
54
118
  ...config.axiosConfig,
55
119
  });
120
+ this.transcribe = this.defineOperation({
121
+ jobType: 'transcribe',
122
+ submit: (input) => this.submitAsyncJob('/transcribe/async', typeof input === 'string' ? { video_url: input } : input),
123
+ fetchTask: (task_id, options) => this.getAsyncJob(`/transcribe/${encodeURIComponent(task_id)}`, options, (raw) => parseTranscribeData(raw)),
124
+ toResult: async (task) => ({ ...requireResult(task), usage: task.usage }),
125
+ });
126
+ this.extractVideo = this.defineOperation({
127
+ jobType: 'extract_video',
128
+ submit: (input) => this.submitExtractVideo(input),
129
+ fetchTask: (task_id, options) => this.getAsyncJob(`/extract/video/${encodeURIComponent(task_id)}`, options, (raw) => raw),
130
+ toResult: async (task) => ({ data: requireResult(task), usage: task.usage }),
131
+ });
132
+ this.tweetStatement = this.defineOperation({
133
+ jobType: 'tweet_statement',
134
+ submit: (input) => this.submitAsyncJob('/tweet/statement/async', typeof input === 'string' ? { tweet_id: input } : input),
135
+ fetchTask: (task_id, options) => this.getAsyncJob(`/tweet/statement/${encodeURIComponent(task_id)}`, options, (raw) => models_1.TweetStatement.fromJSON(raw)),
136
+ toResult: async (task) => {
137
+ const statement = requireResult(task);
138
+ statement.usage = task.usage;
139
+ return statement;
140
+ },
141
+ });
142
+ this.tiktokProfile = this.defineOperation({
143
+ jobType: 'tiktok_profile',
144
+ submit: async (input) => {
145
+ const sub = await this.submitTikTokProfileScrape(typeof input === 'string' ? { profile_url: input } : input);
146
+ return { ...sub, job_type: 'tiktok_profile' };
147
+ },
148
+ // Status polls ask for one video only; the full result is paged in once the task completes.
149
+ fetchTask: (task_id) => this.getTikTokProfileScrape(task_id, { limit: 1 }),
150
+ toResult: (task, options) => collectAllPages((query) => this.getTikTokProfileScrape(task.task_id, query), (page) => page.videos, (page, all) => { page.videos = all; }, options.include_usage),
151
+ });
152
+ this.tiktokSearch = this.defineOperation({
153
+ jobType: 'tiktok_search',
154
+ submit: async (input) => {
155
+ const sub = await this.submitTikTokSearch(typeof input === 'string' ? { query: input } : input);
156
+ return { ...sub, job_type: 'tiktok_search' };
157
+ },
158
+ fetchTask: (task_id) => this.getTikTokSearch(task_id, { limit: 1 }),
159
+ toResult: (task, options) => collectAllPages((query) => this.getTikTokSearch(task.task_id, query), (page) => page.results, (page, all) => { page.results = all; }, options.include_usage),
160
+ });
161
+ }
162
+ defineOperation(spec) {
163
+ const makeJob = (info, options = {}) => new jobs_1.Job(info, () => spec.fetchTask(info.task_id, options), (task) => spec.toResult(task, options));
164
+ const submit = async (input, options) => makeJob(await spec.submit(input), options);
165
+ const run = async (input, options = {}) => {
166
+ const { include_usage, ...pollOptions } = options;
167
+ const job = await submit(input, { include_usage });
168
+ return job.result(pollOptions);
169
+ };
170
+ return Object.assign(run, {
171
+ submit,
172
+ resume: (task_id, options) => makeJob({ task_id, job_type: spec.jobType }, options),
173
+ });
174
+ }
175
+ async submitAsyncJob(url, body, headers) {
176
+ const response = await this.request('POST', url, body, undefined, headers);
177
+ const accepted = models_1.AsyncJobAccepted.fromJSON(response.data);
178
+ return { ...accepted, job_type: accepted.job_type ?? url.split('/')[1] };
179
+ }
180
+ submitExtractVideo(input) {
181
+ if ('schemaFilePath' in input) {
182
+ const form = new form_data_1.default();
183
+ form.append('video_url', input.video_url);
184
+ form.append('schema', fs_1.default.createReadStream(input.schemaFilePath));
185
+ appendOptionalFormField(form, 'what_to_extract', input.what_to_extract);
186
+ appendOptionalFormField(form, 'transcribe', input.transcribe);
187
+ appendOptionalFormField(form, 'webhook_url', input.webhook_url);
188
+ return this.submitAsyncJob('/extract/video/async', form, form.getHeaders());
189
+ }
190
+ return this.submitAsyncJob('/extract/video/async', input);
191
+ }
192
+ async getAsyncJob(url, options, parseResult) {
193
+ const response = await this.request('GET', url, undefined, buildAsyncJobParams(options));
194
+ const job = models_1.AsyncJob.fromJSON(response.data, parseResult);
195
+ if (response.usage)
196
+ job.usage = models_1.UsageBlock.fromJSON(response.usage);
197
+ return job;
56
198
  }
57
199
  async request(method, url, data, params, extraHeaders) {
58
200
  try {
@@ -67,67 +209,41 @@ class VidNavigatorClient {
67
209
  }
68
210
  catch (error) {
69
211
  if (axios_1.default.isAxiosError(error) && error.response) {
70
- const { status, data } = error.response;
71
- const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
72
- const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
73
- switch (status) {
74
- case 400:
75
- throw new errors_1.BadRequestError(message, status, errorCode, errorMessage, details);
76
- case 401:
77
- throw new errors_1.AuthenticationError(message, status, errorCode, errorMessage, details);
78
- case 402:
79
- throw new errors_1.PaymentRequiredError(message, status, errorCode, errorMessage, details);
80
- case 403:
81
- throw new errors_1.AccessDeniedError(message, status, errorCode, errorMessage, details);
82
- case 404:
83
- throw new errors_1.NotFoundError(message, status, errorCode, errorMessage, details);
84
- case 413:
85
- throw new errors_1.StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
86
- case 429:
87
- throw new errors_1.RateLimitExceededError(message, status, errorCode, errorMessage, details);
88
- case 451:
89
- throw new errors_1.GeoRestrictedError(message, status, errorCode, errorMessage, details);
90
- case 503:
91
- throw new errors_1.SystemOverloadError(message, status, errorCode, errorMessage, details, data?.retry_after_seconds);
92
- default:
93
- if (status >= 500) {
94
- throw new errors_1.ServerError(message, status, errorCode, errorMessage, details);
95
- }
96
- throw new errors_1.VidNavigatorError(message, status, errorCode, errorMessage, details);
97
- }
212
+ throw (0, http_1.buildApiError)(error.response.status, error.response.data, error.message);
98
213
  }
99
214
  throw new errors_1.VidNavigatorError(error.message);
100
215
  }
101
216
  }
102
217
  //region --- Transcripts ---
218
+ /**
219
+ * Get a transcript for any supported video. The endpoint auto-detects the
220
+ * platform (YouTube, Vimeo, X/Twitter, TikTok, Facebook, Dailymotion, Loom, etc.)
221
+ * from `video_url`. For Instagram, use {@link VidNavigatorClient.transcribeVideo}.
222
+ */
103
223
  async getTranscript(payload) {
104
224
  const response = await this.request('POST', '/transcript', payload);
105
225
  return {
106
226
  video_info: models_1.VideoInfo.fromJSON(response.data.video_info),
107
227
  transcript: (0, models_1.transcriptFromJSON)(response.data.transcript),
228
+ usage: response.usage ? models_1.UsageBlock.fromJSON(response.usage) : undefined,
108
229
  };
109
230
  }
231
+ /**
232
+ * @deprecated There is now a single `/transcript` endpoint that auto-detects the
233
+ * platform. Use {@link VidNavigatorClient.getTranscript} instead. This alias
234
+ * forwards to `getTranscript` and will be removed in a future release.
235
+ */
110
236
  async getYouTubeTranscript(payload) {
111
- const response = await this.request('POST', '/youtube/transcript', payload);
112
- return {
113
- video_info: models_1.VideoInfo.fromJSON(response.data.video_info),
114
- transcript: (0, models_1.transcriptFromJSON)(response.data.transcript),
115
- };
237
+ warnDeprecated('getYouTubeTranscript', 'getTranscript');
238
+ return this.getTranscript(payload);
116
239
  }
117
- async transcribeVideo(payload) {
118
- const response = await this.request('POST', '/transcribe', payload);
119
- const inner = response.data;
120
- if ('videos' in inner && 'carousel_info' in inner) {
121
- return {
122
- carousel_info: models_1.CarouselInfo.fromJSON(inner.carousel_info),
123
- videos: inner.videos.map((v) => models_1.CarouselVideoResult.fromJSON(v)),
124
- };
125
- }
126
- const single = inner;
127
- return {
128
- video_info: models_1.VideoInfo.fromJSON(single.video_info),
129
- transcript: (0, models_1.transcriptFromJSON)(single.transcript),
130
- };
240
+ /**
241
+ * Speech-to-text transcription. Blocking convenience wrapper around {@link VidNavigatorClient.transcribe}:
242
+ * submits to `POST /transcribe/async` and polls until the job finishes, so media of any length works.
243
+ */
244
+ async transcribeVideo(payload, options) {
245
+ const { include_usage, ...input } = payload;
246
+ return this.transcribe(input, { ...options, include_usage });
131
247
  }
132
248
  //endregion
133
249
  //region --- TikTok ---
@@ -136,16 +252,22 @@ class VidNavigatorClient {
136
252
  return models_1.TikTokProfileScrapeSubmission.fromJSON(response.data);
137
253
  }
138
254
  async getTikTokProfileScrape(task_id, query) {
139
- const response = await this.request('GET', `/tiktok/profile/${task_id}`, undefined, query);
140
- return models_1.TikTokProfileTask.fromJSON(response.data);
255
+ const response = await this.request('GET', `/tiktok/profile/${task_id}`, undefined, buildTikTokPollParams(query));
256
+ const task = models_1.TikTokProfileTask.fromJSON(response.data);
257
+ if (response.usage)
258
+ task.usage = models_1.UsageBlock.fromJSON(response.usage);
259
+ return task;
141
260
  }
142
261
  async submitTikTokSearch(payload) {
143
262
  const response = await this.request('POST', '/tiktok/search', payload);
144
263
  return models_1.TikTokSearchSubmission.fromJSON(response.data);
145
264
  }
146
265
  async getTikTokSearch(task_id, query) {
147
- const response = await this.request('GET', `/tiktok/search/${task_id}`, undefined, query);
148
- return models_1.TikTokSearchTask.fromJSON(response.data);
266
+ const response = await this.request('GET', `/tiktok/search/${task_id}`, undefined, buildTikTokPollParams(query));
267
+ const task = models_1.TikTokSearchTask.fromJSON(response.data);
268
+ if (response.usage)
269
+ task.usage = models_1.UsageBlock.fromJSON(response.usage);
270
+ return task;
149
271
  }
150
272
  //endregion
151
273
  //region --- Files ---
@@ -201,26 +323,7 @@ class VidNavigatorClient {
201
323
  }
202
324
  catch (error) {
203
325
  if (axios_1.default.isAxiosError(error) && error.response) {
204
- const { status, data } = error.response;
205
- const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
206
- const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
207
- switch (status) {
208
- case 400:
209
- throw new errors_1.BadRequestError(message, status, errorCode, errorMessage, details);
210
- case 401:
211
- throw new errors_1.AuthenticationError(message, status, errorCode, errorMessage, details);
212
- case 402:
213
- throw new errors_1.PaymentRequiredError(message, status, errorCode, errorMessage, details);
214
- case 413:
215
- throw new errors_1.StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
216
- case 503:
217
- throw new errors_1.SystemOverloadError(message, status, errorCode, errorMessage, details, data?.retry_after_seconds);
218
- default:
219
- if (status >= 500) {
220
- throw new errors_1.ServerError(message, status, errorCode, errorMessage, details);
221
- }
222
- throw new errors_1.VidNavigatorError(message, status, errorCode, errorMessage, details);
223
- }
326
+ throw (0, http_1.buildApiError)(error.response.status, error.response.data, error.message);
224
327
  }
225
328
  throw new errors_1.VidNavigatorError(error.message);
226
329
  }
@@ -275,6 +378,7 @@ class VidNavigatorClient {
275
378
  video_info: models_1.VideoInfo.fromJSON(response.data.video_info),
276
379
  transcript: (0, models_1.transcriptFromJSON)(response.data.transcript),
277
380
  transcript_analysis: models_1.AnalysisResult.fromJSON(response.data.transcript_analysis),
381
+ usage: response.usage ? models_1.UsageBlock.fromJSON(response.usage) : undefined,
278
382
  };
279
383
  }
280
384
  async analyzeFile(payload) {
@@ -283,35 +387,27 @@ class VidNavigatorClient {
283
387
  file_info: models_1.FileInfo.fromJSON(response.data.file_info),
284
388
  transcript: (0, models_1.transcriptFromJSON)(response.data.transcript),
285
389
  transcript_analysis: models_1.AnalysisResult.fromJSON(response.data.transcript_analysis),
390
+ usage: response.usage ? models_1.UsageBlock.fromJSON(response.usage) : undefined,
286
391
  };
287
392
  }
288
- async getTweetStatement(payload) {
289
- const response = await this.request('POST', '/tweet/statement', payload);
290
- return models_1.TweetStatement.fromJSON(response.data);
393
+ /**
394
+ * Structured claim analysis of an X/Twitter tweet. Blocking convenience wrapper around
395
+ * {@link VidNavigatorClient.tweetStatement}: submits to `POST /tweet/statement/async` and polls.
396
+ */
397
+ async getTweetStatement(payload, options) {
398
+ return this.tweetStatement(payload, options);
291
399
  }
292
400
  //endregion
293
401
  //region --- Extraction ---
294
- async extractVideoData(payload) {
295
- if ('schemaFilePath' in payload) {
296
- const form = new form_data_1.default();
297
- form.append('video_url', payload.video_url);
298
- form.append('schema', fs_1.default.createReadStream(payload.schemaFilePath));
299
- appendOptionalFormField(form, 'what_to_extract', payload.what_to_extract);
300
- appendOptionalFormField(form, 'transcribe', payload.transcribe);
301
- appendOptionalFormField(form, 'include_usage', payload.include_usage);
302
- const body = await this.request('POST', '/extract/video', form, undefined, form.getHeaders());
303
- return {
304
- data: body.data,
305
- video_info: body.video_info ? models_1.VideoInfo.fromJSON(body.video_info) : undefined,
306
- usage: body.usage ? models_1.ExtractionTokenUsage.fromJSON(body.usage) : undefined,
307
- };
308
- }
309
- const body = await this.request('POST', '/extract/video', payload);
310
- return {
311
- data: body.data,
312
- video_info: body.video_info ? models_1.VideoInfo.fromJSON(body.video_info) : undefined,
313
- usage: body.usage ? models_1.ExtractionTokenUsage.fromJSON(body.usage) : undefined,
314
- };
402
+ /**
403
+ * Structured-data extraction from an online video. Blocking convenience wrapper around
404
+ * {@link VidNavigatorClient.extractVideo}: submits to `POST /extract/video/async` and polls, so
405
+ * media of any length works. The async API does not return `video_info`; use
406
+ * {@link VidNavigatorClient.getTranscript} with `metadata_only: true` if you need it.
407
+ */
408
+ async extractVideoData(payload, options) {
409
+ const { include_usage, ...input } = payload;
410
+ return this.extractVideo(input, { ...options, include_usage });
315
411
  }
316
412
  async extractFileData(payload) {
317
413
  if ('schemaFilePath' in payload) {
@@ -324,27 +420,59 @@ class VidNavigatorClient {
324
420
  return {
325
421
  data: body.data,
326
422
  file_info: body.file_info ? models_1.FileInfo.fromJSON(body.file_info) : undefined,
327
- usage: body.usage ? models_1.ExtractionTokenUsage.fromJSON(body.usage) : undefined,
423
+ usage: body.usage ? models_1.UsageBlock.fromJSON(body.usage) : undefined,
328
424
  };
329
425
  }
330
426
  const body = await this.request('POST', '/extract/file', payload);
331
427
  return {
332
428
  data: body.data,
333
429
  file_info: body.file_info ? models_1.FileInfo.fromJSON(body.file_info) : undefined,
334
- usage: body.usage ? models_1.ExtractionTokenUsage.fromJSON(body.usage) : undefined,
430
+ usage: body.usage ? models_1.UsageBlock.fromJSON(body.usage) : undefined,
335
431
  };
336
432
  }
337
433
  //endregion
338
434
  //region --- Search ---
339
- async searchVideos(payload) {
340
- const response = await this.request('POST', '/search/video', payload);
435
+ /**
436
+ * Search YouTube for videos with AI analysis and ranking.
437
+ *
438
+ * If the account runs out of `residential_request` credits mid-search, the API
439
+ * returns HTTP 402 with `status: "partial"` and the videos analysed so far. The
440
+ * SDK surfaces that partial payload (results, `status: "partial"`, `error_code`,
441
+ * and `usage` when requested) instead of throwing.
442
+ */
443
+ async searchYouTube(payload) {
444
+ let response;
445
+ try {
446
+ response = await this.request('POST', '/youtube/search', payload);
447
+ }
448
+ catch (error) {
449
+ const body = error?.details;
450
+ if (error instanceof errors_1.PaymentRequiredError && body?.status === 'partial' && body?.data) {
451
+ response = body;
452
+ }
453
+ else {
454
+ throw error;
455
+ }
456
+ }
341
457
  return {
342
- results: response.data.results.map(models_1.VideoSearchResult.fromJSON),
458
+ results: (response.data.results ?? []).map(models_1.VideoSearchResult.fromJSON),
343
459
  query: response.data.query,
344
460
  total_found: response.data.total_found,
345
461
  explanation: response.data.explanation,
462
+ usage: response.usage ? models_1.UsageBlock.fromJSON(response.usage) : undefined,
463
+ status: response.status,
464
+ error_code: response.error_code,
346
465
  };
347
466
  }
467
+ /**
468
+ * @deprecated `/search/video` moved to `/youtube/search`. Use
469
+ * {@link VidNavigatorClient.searchYouTube} instead. This alias forwards to
470
+ * `searchYouTube` and will be removed in a future release.
471
+ */
472
+ async searchVideos(payload) {
473
+ warnDeprecated('searchVideos', 'searchYouTube');
474
+ return this.searchYouTube(payload);
475
+ }
348
476
  async searchFiles(payload) {
349
477
  const response = await this.request('POST', '/search/file', payload);
350
478
  return {
@@ -352,6 +480,7 @@ class VidNavigatorClient {
352
480
  query: response.data.query,
353
481
  total_found: response.data.total_found,
354
482
  explanation: response.data.explanation,
483
+ usage: response.usage ? models_1.UsageBlock.fromJSON(response.usage) : undefined,
355
484
  };
356
485
  }
357
486
  //endregion
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { AsyncJobError } from './models';
2
+ import { VidNavigatorError } from './errors';
3
+ /**
4
+ * Status of an async task. `completed` and `failed` are terminal; anything else (today only
5
+ * `processing`) means the task is still running.
6
+ */
7
+ export type TaskStatus = 'processing' | 'completed' | 'failed' | (string & {});
8
+ /** Minimal shape of every polled task (async jobs and TikTok tasks). */
9
+ export interface PollableTask {
10
+ task_id: string;
11
+ task_status: TaskStatus;
12
+ error?: AsyncJobError | null;
13
+ }
14
+ export interface PollOptions<TTask = PollableTask> {
15
+ /** Delay between polls once the task has run for 10 seconds, in ms. Default 3000. Polling is free and not rate-limited. */
16
+ intervalMs?: number;
17
+ /** Poll every second during the first 10 seconds so short clips return fast. Default true. */
18
+ fastStart?: boolean;
19
+ /**
20
+ * Stop waiting after this many ms and throw {@link TaskTimeoutError} (which carries `task_id`).
21
+ * The job keeps running server-side. Default 30 minutes; `0` waits forever.
22
+ */
23
+ timeoutMs?: number;
24
+ /** Stop waiting early. The job keeps running server-side. */
25
+ signal?: AbortSignal;
26
+ /** Called with every polled task snapshot, including the final one. */
27
+ onPoll?: (task: TTask) => void;
28
+ }
29
+ export declare const DEFAULT_POLL_INTERVAL_MS = 3000;
30
+ export declare const DEFAULT_TIMEOUT_MS: number;
31
+ export declare function isTerminal(status: TaskStatus): boolean;
32
+ /** Poll `fetchTask` until `task_status` is `completed` or `failed`, and return that final snapshot. */
33
+ export declare function pollUntilDone<TTask extends PollableTask>(task_id: string, fetchTask: () => Promise<TTask>, options?: PollOptions<TTask>): Promise<TTask>;
34
+ /**
35
+ * Build the error for a `failed` task from its `error` object (`error`, `message`, `http_status`),
36
+ * using the same class the API would have used for that status. Carries `task_id`.
37
+ */
38
+ export declare function errorFromFailedTask(task: PollableTask): VidNavigatorError;
39
+ export interface JobInfo {
40
+ task_id: string;
41
+ job_type: string;
42
+ check_status_url?: string;
43
+ /** Where the result notification will be POSTed, or `null` when no webhook applies. */
44
+ webhook_url?: string | null;
45
+ expires_at?: string;
46
+ }
47
+ /**
48
+ * Handle to a submitted async job. Use it to run many jobs at once: submit them all, then
49
+ * `await job.result()` on each (or check `await job.status()` yourself).
50
+ *
51
+ * Polling always works, whether or not a webhook is configured.
52
+ */
53
+ export declare class Job<TTask extends PollableTask, TResult> {
54
+ readonly task_id: string;
55
+ readonly job_type: string;
56
+ readonly check_status_url?: string;
57
+ readonly webhook_url?: string | null;
58
+ readonly expires_at?: string;
59
+ /** Most recent task snapshot fetched by `status()`, `refresh()`, `wait()` or `result()`. */
60
+ task?: TTask;
61
+ private readonly fetchTask;
62
+ private readonly toResult;
63
+ constructor(info: JobInfo, fetchTask: () => Promise<TTask>, toResult: (task: TTask) => Promise<TResult>);
64
+ /** Poll once and return the full task snapshot. */
65
+ refresh(): Promise<TTask>;
66
+ /** Poll once and return the current `task_status`. */
67
+ status(): Promise<TaskStatus>;
68
+ /** Poll until the task is `completed` or `failed` and return the final snapshot. Does not throw on `failed`. */
69
+ wait(options?: PollOptions<TTask>): Promise<TTask>;
70
+ /**
71
+ * Wait for the job and return its result. Throws the error from the task's `error` object when it
72
+ * failed, or {@link TaskTimeoutError} on timeout. Every error carries `task_id`.
73
+ */
74
+ result(options?: PollOptions<TTask>): Promise<TResult>;
75
+ }
76
+ /**
77
+ * An async operation, callable as a blocking one-liner, with `.submit()` for a non-blocking
78
+ * {@link Job} handle and `.resume(task_id)` to reattach to a job you already submitted.
79
+ */
80
+ export interface JobOperation<TInput, TTask extends PollableTask, TResult> {
81
+ /** Submit, poll until finished, and return the result. */
82
+ (input: TInput, options?: RunOptions<TTask>): Promise<TResult>;
83
+ /** Submit and return a {@link Job} handle immediately. */
84
+ submit(input: TInput, options?: SubmitOptions): Promise<Job<TTask, TResult>>;
85
+ /** Reattach to a submitted job by `task_id` (e.g. from a {@link TaskTimeoutError}). Makes no request. */
86
+ resume(task_id: string, options?: SubmitOptions): Job<TTask, TResult>;
87
+ }
88
+ export interface SubmitOptions {
89
+ /** Attach a `usage` block to the result. Billing happens in the background, so usage is read when polling. */
90
+ include_usage?: boolean;
91
+ }
92
+ export type RunOptions<TTask = PollableTask> = SubmitOptions & PollOptions<TTask>;