vidnavigator 1.0.5 → 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/README.md CHANGED
@@ -10,7 +10,8 @@ The official JavaScript/TypeScript SDK for the [VidNavigator Developer API](http
10
10
  ## Why VidNavigator?
11
11
 
12
12
  - **Multi-platform transcription** — YouTube, Instagram Reels & carousel posts, TikTok, X/Twitter, Vimeo, Facebook, Dailymotion, Loom, and more.
13
- - **Async TikTok profile scraping and keyword search** — collect public TikTok videos in the background, then read results via cursor pagination or a signed `download_url`.
13
+ - **Any video length** — transcription, extraction, and tweet analysis run as background jobs, so there is no duration limit. Get the result with one `await`, or submit many jobs and collect them as they finish.
14
+ - **Async TikTok profile scraping and keyword search** — collect public TikTok videos in the background, then read results via cursor pagination or a signed `download_url`, optionally notified by webhook.
14
15
  - **Instagram carousel support** — select a specific video by index, or transcribe every video in a carousel post with one call.
15
16
  - **AI-powered analysis** — get summaries, people mentioned, places, key subjects, and direct answers to questions about any video or audio.
16
17
  - **Structured data extraction** — define a JSON schema and receive typed, structured fields extracted from any transcript (powered by LLMs).
@@ -51,7 +52,9 @@ yarn add vidnavigator
51
52
  pnpm add vidnavigator
52
53
  ```
53
54
 
54
- **Requirements:** Node.js 16+ and a [VidNavigator API key](https://vidnavigator.com).
55
+ **Requirements:** Node.js 16+ (18+ for the examples that use the global `fetch`) and a [VidNavigator API key](https://vidnavigator.com).
56
+
57
+ The SDK is for server-side use: it reads local files for uploads and schema files, and your API key should never be shipped to a browser.
55
58
 
56
59
  ## Quick Start
57
60
 
@@ -63,6 +66,37 @@ const vn = new VidNavigatorClient({
63
66
  });
64
67
  ```
65
68
 
69
+ CommonJS works too: `const { VidNavigatorClient } = require('vidnavigator');`
70
+
71
+ ### Configuration
72
+
73
+ | Option | Default | |
74
+ |---|---|---|
75
+ | `apiKey` | (required) | Your VidNavigator API key |
76
+ | `baseURL` | `https://api.vidnavigator.com/v1` | API base URL |
77
+ | `axiosConfig` | | Passed to the underlying [axios](https://axios-http.com/docs/req_config) instance: HTTP timeout, proxy, extra headers, ... |
78
+
79
+ ```ts
80
+ const vn = new VidNavigatorClient({
81
+ apiKey: process.env.VIDNAVIGATOR_API_KEY!,
82
+ axiosConfig: {
83
+ timeout: 120_000, // per HTTP request, in ms (separate from how long background jobs may run)
84
+ proxy: { protocol: 'http', host: 'proxy.internal', port: 3128 },
85
+ },
86
+ });
87
+ ```
88
+
89
+ `axiosConfig.timeout` limits each HTTP request. How long the SDK waits for a background job to finish is set per call with `timeoutMs` (see [Background jobs](#3-background-jobs-one-call-or-many-at-once)).
90
+
91
+ ### Upgrading from 1.x
92
+
93
+ Transcription, structured extraction, and tweet analysis now always run as background jobs, so they work on videos of any length. Your existing calls keep working with the same arguments, with two differences:
94
+
95
+ - `extractVideoData()` no longer returns `video_info`. Use `getTranscript({ video_url, metadata_only: true })` if you need the metadata.
96
+ - `getTweetStatement()` no longer returns `statement_query`, which was never part of the documented API.
97
+
98
+ New in 2.0: `vn.transcribe`, `vn.extractVideo`, `vn.tweetStatement`, `vn.tiktokProfile`, and `vn.tiktokSearch`, each with `.submit()` for running many jobs at once (see [Background jobs](#3-background-jobs-one-call-or-many-at-once)), plus webhook signature helpers.
99
+
66
100
  ---
67
101
 
68
102
  ## Examples
@@ -81,9 +115,11 @@ console.log(video_info.title); // "Rick Astley - Never Gonna Give You Up"
81
115
  console.log(video_info.channel); // "Rick Astley"
82
116
  console.log(video_info.duration); // 212
83
117
 
84
- // Timed segments by default
85
- for (const seg of transcript.slice(0, 3)) {
86
- console.log(`[${seg.start.toFixed(1)}s] ${seg.text}`);
118
+ // Timed segments by default (a single string when transcript_text: true)
119
+ if (Array.isArray(transcript)) {
120
+ for (const seg of transcript.slice(0, 3)) {
121
+ console.log(`[${seg.start.toFixed(1)}s] ${seg.text}`);
122
+ }
87
123
  }
88
124
  // [0.0s] We're no strangers to love
89
125
  // [3.4s] You know the rules and so do I
@@ -96,17 +132,15 @@ Pass `transcript_text: true` to get the full transcript as a single plain-text s
96
132
 
97
133
  ### 2. Instagram Reel / TikTok / X / Vimeo
98
134
 
99
- For most non-Instagram platforms, you can use either `getTranscript` (fast, caption-based) or `transcribeVideo` (speech-to-text). **Note:** Instagram only supports `transcribeVideo`.
135
+ For most non-Instagram platforms, you can use either `getTranscript` (fast, caption-based) or `transcribe` (speech-to-text, any length). **Note:** Instagram only supports `transcribe`.
100
136
 
101
137
  ```ts
102
138
  // Instagram Reel (speech-to-text only)
103
- const { video_info, transcript } = await vn.transcribeVideo({
104
- video_url: 'https://www.instagram.com/reel/C86ZvEaqRmo/',
105
- });
139
+ const { video_info, transcript } = await vn.transcribe('https://www.instagram.com/reel/C86ZvEaqRmo/');
106
140
  console.log(video_info.title);
107
- console.log(transcript[0].text);
141
+ console.log(transcript);
108
142
 
109
- // TikTok (can use getTranscript or transcribeVideo)
143
+ // TikTok (can use getTranscript or transcribe)
110
144
  const tiktok = await vn.getTranscript({
111
145
  video_url: 'https://www.tiktok.com/@user/video/1234567890',
112
146
  });
@@ -117,64 +151,255 @@ const tweet = await vn.getTranscript({
117
151
  });
118
152
  ```
119
153
 
120
- ### 3. TikTok profile scraping (async)
154
+ ### 3. Background jobs: one call, or many at once
155
+
156
+ Transcription, structured extraction, tweet analysis, and TikTok scraping run as background jobs on VidNavigator. The SDK always uses the async API endpoints, so **video length is never a problem**. You never deal with the request-response limits of long transcriptions.
157
+
158
+ Each of these operations comes in two shapes:
159
+
160
+ | Operation | Wait for the result | Start it and come back later |
161
+ |---|---|---|
162
+ | Transcription | `await vn.transcribe(url)` | `await vn.transcribe.submit(url)` |
163
+ | Structured extraction | `await vn.extractVideo({ video_url, schema })` | `await vn.extractVideo.submit({ ... })` |
164
+ | Tweet claim analysis | `await vn.tweetStatement(tweetId)` | `await vn.tweetStatement.submit(tweetId)` |
165
+ | TikTok profile scrape | `await vn.tiktokProfile(profileUrl)` | `await vn.tiktokProfile.submit(profileUrl)` |
166
+ | TikTok keyword search | `await vn.tiktokSearch(query)` | `await vn.tiktokSearch.submit(query)` |
121
167
 
122
- TikTok profile scraping is asynchronous. First submit the profile URL, then poll the task until `task_status` is no longer `processing`. Once complete, you can either page through results with `getTikTokProfileScrape()` or fetch the full JSON from `download_url`.
168
+ **Wait for the result.** The one-liner submits the job, checks on it until it finishes, and returns the result:
123
169
 
124
170
  ```ts
125
- const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
171
+ const { video_info, transcript, usage } = await vn.transcribe(
172
+ 'https://www.tiktok.com/@user/video/1234567890',
173
+ { include_usage: true }
174
+ );
175
+ console.log(video_info.title, transcript, usage?.total_credits);
176
+ ```
126
177
 
127
- const submitted = await vn.submitTikTokProfileScrape({
128
- profile_url: 'https://www.tiktok.com/@tiktok',
129
- max_posts: 250,
130
- after_datetime: '2024-01-01',
178
+ Pass an object instead of a URL for more options, e.g. `vn.transcribe({ video_url, transcript_text: true, all_videos: true })`.
179
+
180
+ **Start many at once.** `.submit()` returns a `Job` right away. Each job has a `task_id`, `status()` (checks once), `result()` (waits, then returns the result), and `wait()` (waits, then returns the final task without throwing on failure):
181
+
182
+ ```ts
183
+ const urls = ['https://www.instagram.com/reel/A/', 'https://www.instagram.com/reel/B/', 'https://vimeo.com/123'];
184
+
185
+ const jobs = await Promise.all(urls.map((url) => vn.transcribe.submit(url)));
186
+ console.log(jobs.map((job) => job.task_id)); // store these if you may need to come back later
187
+
188
+ const results = await Promise.allSettled(jobs.map((job) => job.result()));
189
+ results.forEach((r, i) => console.log(urls[i], r.status === 'fulfilled' ? r.value : r.reason.message));
190
+ ```
191
+
192
+ ```ts
193
+ const job = await vn.extractVideo.submit({
194
+ video_url: 'https://www.facebook.com/watch/?v=1234567890',
195
+ schema: {
196
+ speakers: { type: 'Array', description: 'Names of everyone who speaks', items: { type: 'String', description: 'A speaker name' } },
197
+ verdict: { type: 'String', description: 'The final conclusion of the video' },
198
+ },
131
199
  });
132
200
 
133
- let task = await vn.getTikTokProfileScrape(submitted.task_id, { limit: 50 });
201
+ console.log(await job.status()); // 'processing' | 'completed' | 'failed'
202
+ const { data } = await job.result();
203
+ console.log(data); // { speakers: [...], verdict: "..." }, shaped like your schema
204
+ ```
134
205
 
135
- while (task.task_status === 'processing') {
136
- await sleep(5000);
137
- task = await vn.getTikTokProfileScrape(submitted.task_id, { limit: 50 });
206
+ **Come back later.** A job keeps running on VidNavigator even if your process stops waiting, and its result stays available for **1 hour after it finishes**. Keep the `task_id` and reattach with `.resume()`:
207
+
208
+ ```ts
209
+ const job = vn.transcribe.resume(savedTaskId);
210
+ const result = await job.result();
211
+ ```
212
+
213
+ **Timeouts.** The one-liners and `result()` wait up to 30 minutes by default. If that runs out, they throw a `TaskTimeoutError` that **carries the `task_id`**. The job is not lost, so resume it:
214
+
215
+ ```ts
216
+ import { TaskTimeoutError } from 'vidnavigator';
217
+
218
+ try {
219
+ const result = await vn.transcribe(url, { timeoutMs: 5 * 60 * 1000 });
220
+ } catch (err) {
221
+ if (err instanceof TaskTimeoutError) {
222
+ saveForLater(err.task_id); // later: await vn.transcribe.resume(err.task_id).result()
223
+ } else {
224
+ throw err;
225
+ }
138
226
  }
227
+ ```
228
+
229
+ **Waiting options.** Pass these to the one-liner or to `result()` / `wait()`:
230
+
231
+ | Option | Default | |
232
+ |---|---|---|
233
+ | `timeoutMs` | 30 minutes | Stop waiting and throw `TaskTimeoutError` (with `task_id`). `0` waits forever |
234
+ | `intervalMs` | `3000` | Time between checks. Checking costs no credits and is not rate-limited |
235
+ | `fastStart` | `true` | Check every second for the first 10 seconds, so short clips return quickly |
236
+ | `signal` | | An `AbortSignal` to stop waiting early (the job keeps running) |
237
+ | `onPoll` | | Called with each task snapshot, e.g. for progress logs |
238
+ | `include_usage` | `false` | Attach a `usage` block to the result (one-liner, `.submit()` and `.resume()` options) |
239
+
240
+ **When a job fails**, `result()` and the one-liners throw an error built from the job's `error` details (`error`, `message`, `http_status`), using the same error class as any other API error, for example `NotFoundError` for a missing video. The error also carries the `task_id`. `wait()` returns the failed task instead, with `task.error` set.
241
+
242
+ **When a job can't start**, submitting throws right away and no job is created:
243
+ - `InsufficientCreditsError` (402): not enough credits (for transcription, less than 60 seconds left). A job can also be accepted and then run out of credits while it runs; `result()` then throws the same `InsufficientCreditsError`, so handle it in both places.
244
+ - `TooManyActiveJobsError` (429): too many of your jobs are already running. Wait for some to finish and retry.
139
245
 
140
- if (task.task_status === 'failed') {
141
- throw new Error(task.error_message || 'TikTok profile scrape failed');
246
+ **Large batches.** Your account can only have a limited number of jobs running at once, so `Promise.all` over hundreds of URLs will hit `TooManyActiveJobsError`. Keep a fixed number in flight and retry when the limit is reached:
247
+
248
+ ```ts
249
+ import { TooManyActiveJobsError } from 'vidnavigator';
250
+
251
+ async function transcribeAll(urls: string[], concurrency = 10) {
252
+ const results = new Map<string, unknown>();
253
+ const queue = [...urls];
254
+
255
+ async function worker() {
256
+ for (let url = queue.shift(); url; url = queue.shift()) {
257
+ for (;;) {
258
+ try {
259
+ results.set(url, await vn.transcribe(url));
260
+ break;
261
+ } catch (err) {
262
+ if (err instanceof TooManyActiveJobsError) {
263
+ await new Promise((r) => setTimeout(r, 10_000)); // wait for running jobs to finish
264
+ continue;
265
+ }
266
+ results.set(url, err); // record the failure and move on
267
+ break;
268
+ }
269
+ }
270
+ }
271
+ }
272
+
273
+ await Promise.all(Array.from({ length: concurrency }, worker));
274
+ return results;
142
275
  }
276
+ ```
143
277
 
144
- console.log(`Matched ${task.stats?.videos_matched ?? task.pagination?.total_items ?? 0} videos`);
278
+ **Progress.** `onPoll` receives every task snapshot while you wait:
279
+
280
+ ```ts
281
+ const started = Date.now();
282
+ const result = await vn.transcribe(url, {
283
+ onPoll: (task) => console.log(`${task.task_id}: ${task.task_status} after ${Math.round((Date.now() - started) / 1000)}s`),
284
+ });
145
285
  ```
146
286
 
147
- Use cursor pagination when you want to process videos page by page:
287
+ **Surviving restarts.** Save each `task_id` as soon as you submit, so a crash or deploy doesn't lose the work. Results stay available for 1 hour after a job finishes:
148
288
 
149
289
  ```ts
150
- const videos = [];
151
- let cursor: string | undefined;
290
+ import { writeFileSync, readFileSync, existsSync } from 'fs';
152
291
 
153
- do {
154
- const page = await vn.getTikTokProfileScrape(submitted.task_id, {
155
- limit: 100,
156
- cursor,
157
- });
292
+ // Submit and persist
293
+ const job = await vn.transcribe.submit(url);
294
+ writeFileSync('pending-jobs.json', JSON.stringify([...pending(), job.task_id]));
158
295
 
159
- videos.push(...page.videos);
160
- cursor = page.pagination?.next_cursor ?? undefined;
161
- } while (cursor);
296
+ // After a restart: pick every job back up
297
+ for (const taskId of pending()) {
298
+ const result = await vn.transcribe.resume(taskId).result();
299
+ // ... store the result, then drop taskId from pending-jobs.json
300
+ }
162
301
 
163
- console.log(`Loaded ${videos.length} TikTok videos`);
302
+ function pending(): string[] {
303
+ return existsSync('pending-jobs.json') ? JSON.parse(readFileSync('pending-jobs.json', 'utf8')) : [];
304
+ }
164
305
  ```
165
306
 
166
- Use `download_url` when you want the entire profile result in one request. The URL is short-lived and points directly to the generated JSON file, so it can be fetched with any HTTP client.
307
+ > The older methods `transcribeVideo()`, `extractVideoData()`, and `getTweetStatement()` still work with the same arguments. They now run as background jobs too, so they handle videos of any length. `extractVideoData()` no longer returns `video_info`; call `getTranscript({ video_url, metadata_only: true })` if you need it.
308
+
309
+ ### 4. Webhooks
310
+
311
+ You can also have VidNavigator call your server when a job finishes. Pass `webhook_url` to any of the operations above (transcription, extraction, tweet analysis, TikTok profile and search), or set an account-wide default in **Studio → API**. A per-job `webhook_url` overrides the default, and `webhook_url: ''` turns the default off for that one job. The URL must be a public `https` endpoint; private and loopback hosts are rejected with a `BadRequestError`.
312
+
313
+ Webhooks are optional. Waiting with `result()` or the one-liners works exactly the same whether or not a webhook is set, and it remains the source of truth.
167
314
 
168
315
  ```ts
169
- if (!task.download_url) {
170
- throw new Error('No download URL is available for this scrape');
171
- }
316
+ const job = await vn.transcribe.submit({
317
+ video_url: 'https://www.instagram.com/reel/C86ZvEaqRmo/',
318
+ webhook_url: 'https://example.com/hooks/vidnavigator',
319
+ });
320
+ console.log(job.webhook_url); // where the notification will be sent, or null
321
+ ```
322
+
323
+ Each delivery is signed with your signing secret (from Studio → API). Verify it with `constructWebhookEvent()`, passing the **raw** request body:
324
+
325
+ ```ts
326
+ import express from 'express';
327
+ import { VidNavigatorClient, constructWebhookEvent, WebhookSignatureError, WEBHOOK_HEADERS } from 'vidnavigator';
328
+
329
+ const vn = new VidNavigatorClient({ apiKey: process.env.VIDNAVIGATOR_API_KEY! });
330
+ const app = express();
331
+
332
+ app.post('/hooks/vidnavigator', express.raw({ type: 'application/json' }), async (req, res) => {
333
+ let event;
334
+ try {
335
+ event = constructWebhookEvent(
336
+ req.body, // raw Buffer, not parsed JSON
337
+ req.headers[WEBHOOK_HEADERS.signature], // "t=<unix_ts>,v1=<hex>"
338
+ process.env.VIDNAVIGATOR_WEBHOOK_SECRET!
339
+ );
340
+ } catch (err) {
341
+ if (err instanceof WebhookSignatureError) return res.status(400).send('Invalid signature');
342
+ throw err;
343
+ }
344
+ res.sendStatus(200); // acknowledge quickly; any 2xx counts
345
+
346
+ // Deliveries can repeat: dedupe on req.headers[WEBHOOK_HEADERS.delivery].
347
+ // The simplest handler reattaches to the job and reads the parsed result:
348
+ if (event.type === 'transcribe.completed') {
349
+ const result = await vn.transcribe.resume(event.data.task_id).result();
350
+ console.log(result);
351
+ } else if (event.type === 'tiktok_profile.completed') {
352
+ const task = await vn.tiktokProfile.resume(event.data.task_id).result(); // every video, all pages
353
+ console.log(task.videos.length);
354
+ } else if (event.type.endsWith('.failed')) {
355
+ console.error(event.data.task_id, event.data.error); // { error, message, http_status }
356
+ }
357
+ });
358
+ ```
359
+
360
+ - `event.data.result` holds the raw result for transcription, extraction, and tweet events, unless it was over 256 KB (`result_truncated: true`). For TikTok events it is only a summary, `{ stats, download_url_available }`, since a scrape can hold thousands of videos. In every case, `resume(task_id).result()` gets the full parsed result.
361
+ - `verifyWebhookSignature(rawBody, signatureHeader, secret)` returns `true` or `false` instead of throwing.
362
+ - Deliveries older than 5 minutes are rejected by default. Change this with `{ toleranceSeconds }`; `0` turns the check off.
363
+ - Failed deliveries (5xx, 429, network errors) are retried 5 times over about 13 minutes. Other 4xx responses are not retried.
364
+ - To see a job's delivery status, check it: `(await job.refresh()).webhook` → `{ status: 'pending' | 'delivered' | 'failed', attempts, response_status, last_error, delivered_at }`.
365
+
366
+ ### 5. TikTok profile scraping (async)
367
+
368
+ `vn.tiktokProfile()` scrapes a public profile in the background and returns the finished task with **every** matching video (the SDK fetches all result pages for you):
172
369
 
173
- const response = await fetch(task.download_url);
174
- const fullProfile = await response.json();
175
- const videos = fullProfile.videos ?? [];
370
+ ```ts
371
+ const task = await vn.tiktokProfile({
372
+ profile_url: 'https://www.tiktok.com/@tiktok',
373
+ max_posts: 250,
374
+ after_datetime: '2024-01-01',
375
+ });
376
+
377
+ console.log(`Matched ${task.videos.length} videos`, task.stats);
378
+ const videos = task.videos; // TikTokVideo[], published_at parsed as Date
379
+ ```
380
+
381
+ Pass just the URL for the defaults: `await vn.tiktokProfile('https://www.tiktok.com/@tiktok')`. As with every operation, `vn.tiktokProfile.submit(...)` returns a `Job` instead, and `webhook_url` is accepted.
382
+
383
+ If you'd rather read the results one page at a time, or grab them as a single JSON file, submit the job and use the page-level method with its `task_id`:
384
+
385
+ ```ts
386
+ const job = await vn.tiktokProfile.submit('https://www.tiktok.com/@tiktok');
387
+ await job.wait();
388
+
389
+ // Page by page
390
+ let cursor: string | undefined;
391
+ do {
392
+ const page = await vn.getTikTokProfileScrape(job.task_id, { limit: 100, cursor });
393
+ handle(page.videos);
394
+ cursor = page.pagination?.next_cursor ?? undefined;
395
+ } while (cursor);
176
396
 
177
- console.log(`Downloaded ${videos.length} videos for`, fullProfile.profile_url);
397
+ // Or the whole result as one JSON file (short-lived signed URL, any HTTP client works)
398
+ const { download_url } = await vn.getTikTokProfileScrape(job.task_id, { limit: 1 });
399
+ if (download_url) {
400
+ const fullProfile = await (await fetch(download_url)).json();
401
+ console.log(fullProfile.videos.length);
402
+ }
178
403
  ```
179
404
 
180
405
  After you have the final video list, loop through each TikTok video URL and use the normal transcript or extraction APIs:
@@ -203,7 +428,7 @@ for (const video of videos) {
203
428
  video_url: video.url,
204
429
  schema: {
205
430
  hook: { type: 'String', description: 'The opening hook or premise' },
206
- products: { type: 'Array', description: 'Products or brands mentioned' },
431
+ products: { type: 'Array', description: 'Products or brands mentioned', items: { type: 'String', description: 'A product or brand' } },
207
432
  sentiment: {
208
433
  type: 'Enum',
209
434
  description: 'Overall sentiment',
@@ -220,47 +445,41 @@ for (const video of videos) {
220
445
 
221
446
  For large profiles, process videos sequentially or with a small concurrency limit so you do not exhaust credits or hit rate limits.
222
447
 
223
- ### 4. TikTok keyword search (async)
448
+ ### 6. TikTok keyword search (async)
224
449
 
225
- TikTok keyword search follows the same async pattern as profile scraping: submit a search, then poll by `task_id` until results are ready.
450
+ `vn.tiktokSearch()` works the same way and returns the finished task with every result:
226
451
 
227
452
  ```ts
228
- const submitted = await vn.submitTikTokSearch({
453
+ const task = await vn.tiktokSearch({
229
454
  query: 'ai tools',
230
455
  max_results: 100,
231
- parallel_search_slices: 2,
232
- after_datetime: '2024-01-01',
456
+ sort_by: 'most_liked', // 'relevance' | 'most_liked' | 'newest'
457
+ published_within: 'this_month', // 'all' | 'past_24_hours' | 'this_week' | 'this_month' | 'last_3_months' | 'last_6_months'
458
+ min_views: 10000,
233
459
  });
234
460
 
235
- let task = await vn.getTikTokSearch(submitted.task_id, { limit: 50 });
236
-
237
- while (task.task_status === 'processing') {
238
- await sleep(5000);
239
- task = await vn.getTikTokSearch(submitted.task_id, { limit: 50 });
240
- }
241
-
461
+ console.log(task.stats?.sort_by, task.stats?.published_within); // what the search actually ran with
242
462
  for (const result of task.results) {
243
463
  console.log(result.published_at?.toISOString(), result.url, result.stats?.views);
244
464
  }
245
465
  ```
246
466
 
247
- Use `parallel_search_slices` from `2` to `4` when you need broader collection than TikTok's natural single-chain cap. Billing scales with the number of slices, so keep it at `1` unless you need the wider result set.
467
+ - `sort_by` and `published_within` are applied by TikTok itself. If you leave out `sort_by`, results come back newest first. If you leave out `published_within` and set an `after_datetime` more than 24 hours ago, the smallest window that covers it is picked for you.
468
+ - `parallel_search_slices` (`2` to `4`) runs several search chains in parallel to collect more results than TikTok's single-chain limit (about 115 to 140 items). Billing grows with the number of slices, so keep it at `1` unless you need the extra results, and especially when `published_within` is set, since every slice searches the same window.
248
469
 
249
- ### 5. Instagram carousel posts (multiple videos)
470
+ ### 7. Instagram carousel posts (multiple videos)
250
471
 
251
472
  Instagram carousel posts can contain multiple videos. You can select a specific video by index, or transcribe them all at once:
252
473
 
253
474
  ```ts
254
475
  // Transcribe the 2nd video in a carousel
255
- const single = await vn.transcribeVideo({
256
- video_url: 'https://www.instagram.com/p/ABC123/?img_index=2',
257
- });
476
+ const single = await vn.transcribe('https://www.instagram.com/p/ABC123/?img_index=2');
258
477
  console.log(single.video_info.title);
259
478
  console.log(single.video_info.carousel_info);
260
479
  // { total_items: 5, video_count: 3, image_count: 2, selected_index: 2 }
261
480
 
262
481
  // Transcribe ALL videos in a carousel at once
263
- const all = await vn.transcribeVideo({
482
+ const all = await vn.transcribe({
264
483
  video_url: 'https://www.instagram.com/p/ABC123/',
265
484
  all_videos: true,
266
485
  });
@@ -270,8 +489,8 @@ if ('carousel_info' in all) {
270
489
 
271
490
  for (const video of all.videos) {
272
491
  if (video.status === 'success') {
273
- console.log(`Video #${video.index}: ${video.video_info.title}`);
274
- console.log(` Transcript: ${video.transcript[0]?.text}...`);
492
+ console.log(`Video #${video.index}: ${video.video_info?.title}`);
493
+ console.log(' Transcript:', video.transcript);
275
494
  } else {
276
495
  console.log(`Video #${video.index}: failed — ${video.message}`);
277
496
  }
@@ -279,7 +498,7 @@ if ('carousel_info' in all) {
279
498
  }
280
499
  ```
281
500
 
282
- ### 6. Upload and analyze a local file
501
+ ### 8. Upload and analyze a local file
283
502
 
284
503
  Upload audio or video files for transcription, analysis, and search. Supported formats: mp4, webm, mov, avi, wmv, flv, mkv, m4a, mp3, mpeg, mpga, wav.
285
504
 
@@ -292,11 +511,11 @@ const upload = await vn.uploadFile({
292
511
 
293
512
  console.log(upload.file_id); // "64a1b2c3d4e5f6789..."
294
513
  console.log(upload.file_name); // "meeting-recording.mp4"
295
- console.log(upload.file_info.namespace_ids); // ["ns_meetings"]
514
+ console.log(upload.file_info?.namespace_ids); // ["ns_meetings"]
296
515
 
297
516
  // Analyze with a question
298
517
  const { transcript_analysis } = await vn.analyzeFile({
299
- file_id: upload.file_info.id,
518
+ file_id: upload.file_id,
300
519
  query: 'What action items were discussed?',
301
520
  });
302
521
 
@@ -313,7 +532,42 @@ console.log(transcript_analysis.query_answer?.answer);
313
532
  // "Three action items were discussed: 1) Finalize the hiring..."
314
533
  ```
315
534
 
316
- ### 7. Extract structured data
535
+ Without `wait_for_completion`, the upload returns right away (`status: 'accepted'`) while the file is processed. Check on it with `getFile()`, then work with it:
536
+
537
+ ```ts
538
+ const { file_id } = await vn.uploadFile({ filePath: './interview.mp3' });
539
+
540
+ let { file_info } = await vn.getFile(file_id);
541
+ while (file_info.status === 'processing') {
542
+ await new Promise((r) => setTimeout(r, 5000));
543
+ ({ file_info } = await vn.getFile(file_id));
544
+ }
545
+
546
+ if (file_info.status === 'failed') {
547
+ await vn.retryFileProcessing(file_id); // or: await vn.cancelFileUpload(file_id) while it is still processing
548
+ }
549
+
550
+ const { transcript } = await vn.getFile(file_id, { transcript_text: true }); // full text
551
+ const { file_url } = await vn.getFileUrl(file_id); // signed download URL
552
+ const { files, has_more } = await vn.getFiles({ status: 'completed', limit: 20, offset: 0 });
553
+ await vn.deleteFile(file_id);
554
+ ```
555
+
556
+ ### Analyze an online video
557
+
558
+ ```ts
559
+ const { video_info, transcript_analysis } = await vn.analyzeVideo({
560
+ video_url: 'https://www.youtube.com/watch?v=4czjS9h4Fpg',
561
+ query: 'Where did the rover land?',
562
+ include_usage: true,
563
+ });
564
+
565
+ console.log(transcript_analysis.summary);
566
+ console.log(transcript_analysis.query_answer?.answer); // direct answer to your question
567
+ console.log(transcript_analysis.query_answer?.relevant_segments); // supporting transcript excerpts
568
+ ```
569
+
570
+ ### 9. Extract structured data
317
571
 
318
572
  Define a schema and get back clean, structured data extracted from any video or file transcript. Powered by LLMs with per-call usage tracking (see [Per-call usage](#per-call-usage)).
319
573
 
@@ -325,7 +579,7 @@ const { data, usage } = await vn.extractVideoData({
325
579
  language: { type: 'String', description: 'Primary spoken language (ISO 639-1)' },
326
580
  tone: { type: 'Enum', description: 'Overall tone',
327
581
  enum: ['positive', 'negative', 'neutral', 'mixed'] },
328
- key_quotes: { type: 'Array', description: 'Top 3 memorable quotes' },
582
+ key_quotes: { type: 'Array', description: 'Top 3 memorable quotes', items: { type: 'String', description: 'A quote' } },
329
583
  },
330
584
  what_to_extract: 'Determine the topic, language, tone, and notable quotes.',
331
585
  include_usage: true,
@@ -350,7 +604,7 @@ Also works on uploaded files:
350
604
  const { data } = await vn.extractFileData({
351
605
  file_id: 'your-file-id',
352
606
  schema: {
353
- action_items: { type: 'Array', description: 'List of action items from the meeting' },
607
+ action_items: { type: 'Array', description: 'List of action items from the meeting', items: { type: 'String', description: 'An action item' } },
354
608
  next_meeting: { type: 'String', description: 'When is the next meeting scheduled?' },
355
609
  sentiment: { type: 'Enum', description: 'Overall meeting mood',
356
610
  enum: ['productive', 'tense', 'casual', 'urgent'] },
@@ -370,7 +624,11 @@ const { data } = await vn.extractVideoData({
370
624
 
371
625
  **Supported schema types:** `String`, `Number`, `Boolean`, `Integer`, `Object`, `Array`, `Enum`
372
626
 
373
- ### 8. Semantic search
627
+ **Schema rules:** every field needs `type` and `description`. `Array` fields also need `items` (the schema of one element). `Object` fields list their sub-fields in `properties` (up to 10), and `Enum` fields list the allowed values in `enum`. At most 10 top-level fields and 3 levels of nesting. An invalid schema is rejected with a `BadRequestError` before anything runs.
628
+
629
+ > `extractVideoData()` runs as a background job, so videos of any length work. For many extractions at once, use `vn.extractVideo.submit()` (see [Background jobs](#3-background-jobs-one-call-or-many-at-once)). The result has `data` and `usage`, but no `video_info`.
630
+
631
+ ### 10. Semantic search
374
632
 
375
633
  Search YouTube videos and uploaded files with AI-powered ranking/reranking.
376
634
 
@@ -409,7 +667,7 @@ for (const r of fileResults.results) {
409
667
 
410
668
  > **Deprecated:** `searchVideos()` still works but is deprecated — it now forwards to `searchYouTube()` (the `/search/video` endpoint moved to `/youtube/search`) and emits a deprecation warning. Use `searchYouTube()` instead.
411
669
 
412
- ### 9. Organize files with namespaces
670
+ ### 11. Organize files with namespaces
413
671
 
414
672
  ```ts
415
673
  // Create a namespace
@@ -417,33 +675,33 @@ const ns = await vn.createNamespace({ name: 'Client Calls' });
417
675
 
418
676
  // Assign a file to namespaces
419
677
  const updated = await vn.updateFileNamespaces(fileId, {
420
- namespace_ids: [ns.id],
678
+ namespace_ids: [ns.id!],
421
679
  });
422
680
  console.log(updated.namespaces);
423
681
  // [{ id: "...", name: "Client Calls" }]
424
682
 
425
683
  // List files filtered by namespace
426
- const files = await vn.getFiles({ namespace_id: ns.id });
684
+ const files = await vn.getFiles({ namespace_id: ns.id! });
427
685
 
428
686
  // List all namespaces
429
687
  const all = await vn.getNamespaces();
430
688
  ```
431
689
 
432
- ### 10. Usage and credits
690
+ ### 12. Usage and credits
433
691
 
434
692
  ```ts
435
693
  const usage = await vn.getUsage();
436
694
 
437
695
  console.log(`Credits remaining: ${usage.credits.monthly_remaining}`);
438
- console.log(`Video transcripts used: ${usage.usage.videoTranscripts.used}`);
439
- console.log(`YouTube transcripts used: ${usage.usage.youtubeTranscripts.used}`);
440
- console.log(`Storage: ${usage.storage.used_formatted} / ${usage.storage.limit_formatted}`);
696
+ console.log(`Transcription hours used: ${usage.usage.transcriptionHour?.used}`);
697
+ console.log(`Standard requests used: ${usage.usage.standardRequest?.used}`);
698
+ console.log(`Storage: ${usage.storage.usedFormatted} / ${usage.storage.limitFormatted}`);
441
699
  console.log(`Channels indexed: ${usage.channelsIndexed.used} / ${usage.channelsIndexed.limit}`);
442
700
  ```
443
701
 
444
702
  ### Per-call usage
445
703
 
446
- Pass `include_usage: true` to most endpoints (`getTranscript`, `transcribeVideo`, `analyzeVideo`, `analyzeFile`, `extractVideoData`, `extractFileData`, `searchYouTube`, `searchFiles`) to receive a `usage` block describing exactly what the request cost. For the TikTok pollers (`getTikTokProfileScrape`, `getTikTokSearch`), pass `include_usage: true` in the options object — usage is populated once `task_status === 'completed'`.
704
+ Pass `include_usage: true` to most endpoints (`getTranscript`, `transcribeVideo`, `analyzeVideo`, `analyzeFile`, `extractVideoData`, `extractFileData`, `searchYouTube`, `searchFiles`) to receive a `usage` block describing exactly what the request cost. For background jobs, pass it in the options: `vn.transcribe(url, { include_usage: true })`, `vn.transcribe.submit(url, { include_usage: true })`, or `vn.transcribe.resume(taskId, { include_usage: true })`. The result's `usage` is filled in once the job completes. A failed job has all its charges reverted, so it has no usage.
447
705
 
448
706
  The `usage` field is a `UsageBlock`:
449
707
 
@@ -483,20 +741,48 @@ All methods return a `Promise`. Responses are automatically parsed into typed mo
483
741
  |--------|-------------|
484
742
  | `getTranscript(payload)` | Get a transcript for any supported video; auto-detects the platform from the URL (note: Instagram uses `transcribeVideo`) |
485
743
  | `getYouTubeTranscript(payload)` | **Deprecated** — forwards to `getTranscript()` |
486
- | `transcribeVideo(payload)` | Speech-to-text transcription via AI models; supports Instagram carousel with `all_videos` |
744
+ | `transcribe(urlOrInput, options?)` | Speech-to-text of any length. Input: `video_url`, `transcript_text`, `all_videos` (Instagram carousels), `webhook_url`. See [Background jobs](#background-jobs) |
745
+ | `transcribeVideo(payload, options?)` | Same as `transcribe()`, with the original payload shape (`include_usage` in the payload) |
487
746
 
488
747
  **Common options:** `video_url`, `language`, `metadata_only`, `fallback_to_metadata`, `transcript_text`, `include_usage`
489
748
 
749
+ ### Background jobs
750
+
751
+ | Member | Description |
752
+ |--------|-------------|
753
+ | `vn.transcribe`, `vn.extractVideo`, `vn.tweetStatement`, `vn.tiktokProfile`, `vn.tiktokSearch` | Call directly to submit and wait for the result. Options: `include_usage`, `timeoutMs`, `intervalMs`, `fastStart`, `signal`, `onPoll` |
754
+ | `.submit(input, { include_usage? })` | Start the job and return a `Job` immediately |
755
+ | `.resume(task_id, { include_usage? })` | Get a `Job` for a job you already started (no request is made) |
756
+ | `job.task_id`, `job.job_type`, `job.check_status_url`, `job.webhook_url` | Job details from the submit response |
757
+ | `job.status()` | Check once; returns `'processing'`, `'completed'` or `'failed'` |
758
+ | `job.refresh()` | Check once; returns the full task (`error`, `webhook`, timestamps, ...) |
759
+ | `job.result(options?)` | Wait until finished and return the result. Throws on failure or timeout; every error carries `task_id` |
760
+ | `job.wait(options?)` | Wait until finished and return the final task, without throwing on failure |
761
+
762
+ Results: `transcribe` → same shape as `transcribeVideo()`; `extractVideo` → `{ data, usage? }`; `tweetStatement` → `TweetStatement`; `tiktokProfile` / `tiktokSearch` → the completed task with every page of `videos` / `results`.
763
+
764
+ ### Webhooks
765
+
766
+ | Function | Description |
767
+ |----------|-------------|
768
+ | `constructWebhookEvent(rawBody, signatureHeader, secret, options?)` | Verify a delivery and return the parsed `WebhookEvent`. Throws `WebhookSignatureError` if the signature is invalid |
769
+ | `verifyWebhookSignature(rawBody, signatureHeader, secret, options?)` | Same check, returning `true` / `false` |
770
+ | `WEBHOOK_HEADERS` | Header names: `signature`, `delivery`, `event`, `taskId` |
771
+
772
+ `options`: `toleranceSeconds` (default `300`, `0` turns the check off). Event types: `transcribe.*`, `extract_video.*`, `tweet_statement.*`, `tiktok_profile.*`, `tiktok_search.*`, each with `.completed` or `.failed`.
773
+
490
774
  ### TikTok
491
775
 
492
776
  | Method | Description |
493
777
  |--------|-------------|
494
- | `submitTikTokProfileScrape(payload)` | Start an async public TikTok profile scrape. Returns a `task_id` immediately |
778
+ | `tiktokProfile(urlOrInput, options?)` | Scrape a public profile and return the completed task with every video. See [Background jobs](#background-jobs) |
779
+ | `tiktokSearch(queryOrInput, options?)` | Keyword search returning the completed task with every result |
780
+ | `submitTikTokProfileScrape(payload)` | Lower-level: start a public TikTok profile scrape. Returns a `task_id` immediately. Options: `max_posts`, `after_datetime`, `before_datetime`, `min_likes`, `max_likes`, `webhook_url` |
495
781
  | `getTikTokProfileScrape(task_id, query?)` | Poll task status and retrieve a page of videos. Options: `cursor`, `limit`, `include_usage` |
496
- | `submitTikTokSearch(payload)` | Start an async TikTok keyword search. Returns a `task_id` immediately |
782
+ | `submitTikTokSearch(payload)` | Start an async TikTok keyword search. Returns a `task_id` immediately. Options: `max_results`, `parallel_search_slices`, `sort_by`, `published_within`, `after_datetime`, `before_datetime`, `min_likes`, `max_likes`, `min_views`, `max_views`, `webhook_url` |
497
783
  | `getTikTokSearch(task_id, query?)` | Poll search status and retrieve a page of results. Options: `cursor`, `limit`, `include_usage` |
498
784
 
499
- Completed profile tasks include `videos`; completed search tasks include `results`. Both include `pagination`, optional `stats`, and an optional short-lived `download_url` for retrieving the whole result as JSON. Datetime filters use `after_datetime` and `before_datetime`, each accepting either `YYYY-MM-DD` or full ISO datetime strings with timezone; TikTok `published_at` values are parsed into JavaScript `Date` objects, and numeric counters such as `views` and `likes` are normalized to integers.
785
+ Completed profile tasks include `videos`; completed search tasks include `results`. Both include `pagination`, optional `stats`, and an optional short-lived `download_url` for retrieving the whole result as JSON. Failed tasks include `error` (`{ error, message, http_status }`); the older `error_message` string still works but is deprecated. Datetime filters use `after_datetime` and `before_datetime`, each accepting either `YYYY-MM-DD` or full ISO datetime strings with timezone; TikTok `published_at` values are parsed into JavaScript `Date` objects, and numeric counters such as `views` and `likes` are normalized to integers.
500
786
 
501
787
  ### Files
502
788
 
@@ -528,7 +814,8 @@ Completed profile tasks include `videos`; completed search tasks include `result
528
814
  |--------|-------------|
529
815
  | `analyzeVideo(payload)` | Analyze an online video with an optional natural language query |
530
816
  | `analyzeFile(payload)` | Analyze an uploaded file with an optional natural language query |
531
- | `getTweetStatement(payload)` | Extract a structured claim analysis from an X/Twitter tweet ID |
817
+ | `tweetStatement(tweetIdOrInput, options?)` | Structured claim analysis of an X/Twitter tweet, including attached media of any length. Input: `tweet_id`, `webhook_url`. Returns a `TweetStatement` |
818
+ | `getTweetStatement(payload, options?)` | Same as `tweetStatement()`, with the original payload shape |
532
819
 
533
820
  Returns `transcript_analysis` containing:
534
821
  - `summary` — content overview
@@ -541,7 +828,8 @@ Returns `transcript_analysis` containing:
541
828
 
542
829
  | Method | Description |
543
830
  |--------|-------------|
544
- | `extractVideoData(payload)` | Extract structured data from an online video transcript |
831
+ | `extractVideo(input, options?)` | Structured data from an online video of any length. Input: `video_url`, `schema` or `schemaFilePath`, `what_to_extract`, `transcribe`, `webhook_url`. Returns `{ data, usage? }` |
832
+ | `extractVideoData(payload, options?)` | Same as `extractVideo()`, with the original payload shape (`include_usage` in the payload) |
545
833
  | `extractFileData(payload)` | Extract structured data from an uploaded file transcript |
546
834
 
547
835
  **Options:** `schema` (required for JSON requests), `schemaFilePath` (JSON/YAML schema file via multipart form-data), `what_to_extract` (optional guidance), `include_usage` (attach a per-call `UsageBlock`; read LLM tokens via `usage.analysis_tokens`)
@@ -596,13 +884,19 @@ try {
596
884
  | `BadRequestError` | 400 | Invalid parameters |
597
885
  | `AuthenticationError` | 401 | Invalid or missing API key |
598
886
  | `PaymentRequiredError` | 402 | Credit limit reached |
887
+ | `InsufficientCreditsError` | 402 | A job could not start: not enough credits (`limit_exceeded`). Extends `PaymentRequiredError` |
599
888
  | `AccessDeniedError` | 403 | Insufficient permissions |
600
- | `NotFoundError` | 404 | Resource does not exist |
889
+ | `NotFoundError` | 404 | Resource does not exist, or a job's `task_id` is unknown or expired (`task_not_found`) |
601
890
  | `StorageQuotaExceededError` | 413 | Storage quota exceeded |
602
891
  | `RateLimitExceededError` | 429 | Too many requests |
892
+ | `TooManyActiveJobsError` | 429 | A job could not start: too many of your jobs are already running (`too_many_active_jobs`). Extends `RateLimitExceededError` |
603
893
  | `GeoRestrictedError` | 451 | Content unavailable in your region |
604
894
  | `ServerError` | 5xx | Unexpected server error |
605
895
  | `SystemOverloadError` | 503 | Temporary overload (has `retry_after_seconds`) |
896
+ | `TaskTimeoutError` | - | Waiting for a job took longer than `timeoutMs`. Has `task_id`; the job keeps running, so `resume(task_id)` it |
897
+ | `WebhookSignatureError` | - | `constructWebhookEvent()` got a missing, invalid, or expired signature |
898
+
899
+ A failed job throws the class matching its `error.http_status`, with `error_code` and `error_message` taken from its `error` details. Every error raised while waiting for a job has a `task_id` property.
606
900
 
607
901
  ## TypeScript Models
608
902
 
@@ -624,11 +918,13 @@ All API responses are parsed into typed classes with static `fromJSON()` constru
624
918
  | `ExtractionTokenUsage` | Legacy flat token usage (`prompt_tokens`, `completion_tokens`, `total_tokens`) — extraction now returns a `UsageBlock`; prefer `usage.analysis_tokens` |
625
919
  | `CarouselInfo` | Carousel summary: total items, video/image count, transcribed count, total duration |
626
920
  | `CarouselVideoResult` | Per-video result in a carousel: index, status, video info, transcript |
627
- | `TikTokProfileScrapeSubmission` | Async scrape submission: `task_id`, status, profile URL, expiry |
628
- | `TikTokProfileTask` | TikTok profile scrape task with status, profile metadata, videos, pagination, `download_url` |
921
+ | `Job` | Handle returned by `.submit()` / `.resume()`: `task_id`, `status()`, `refresh()`, `result()`, `wait()` |
922
+ | `AsyncJob<T>` | Task snapshot of a transcription, extraction, or tweet job (from `job.refresh()` / `job.wait()`): `task_status`, `result`, `error`, `webhook`, `request`, timestamps |
923
+ | `TikTokProfileScrapeSubmission` | Async scrape submission: `task_id`, status, profile URL, expiry, `webhook_url` |
924
+ | `TikTokProfileTask` | TikTok profile scrape task with status, profile metadata, videos, pagination, `download_url`, `error`, `webhook` |
629
925
  | `TikTokVideo` | Public TikTok video metadata returned by profile scraping, including `published_at` as a `Date` and integer counters |
630
- | `TikTokSearchSubmission` | Async TikTok keyword search submission: `task_id`, query, slice count, expiry |
631
- | `TikTokSearchTask` | TikTok keyword search task with status, results, pagination, `download_url` |
926
+ | `TikTokSearchSubmission` | Async TikTok keyword search submission: `task_id`, query, slice count, expiry, `webhook_url` |
927
+ | `TikTokSearchTask` | TikTok keyword search task with status, results, pagination, `download_url`, `error`, `webhook`; `stats` shows the `sort_by` / `published_within` the search ran with |
632
928
  | `TikTokSearchResult` | Normalized TikTok keyword result, including `published_at` as a `Date` and integer counters |
633
929
  | `TweetStatement` | Structured X/Twitter claim analysis, topics, entities, tone, intent, and source text |
634
930