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 +388 -92
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +53 -1
- package/dist/http.d.ts +11 -0
- package/dist/http.js +51 -0
- package/dist/index.d.ts +121 -9
- package/dist/index.js +152 -97
- package/dist/jobs.d.ts +92 -0
- package/dist/jobs.js +132 -0
- package/dist/models/AsyncJob.d.ts +92 -0
- package/dist/models/AsyncJob.js +45 -0
- package/dist/models/TikTok.d.ts +49 -0
- package/dist/models/TikTok.js +10 -0
- package/dist/models/TweetStatement.d.ts +4 -0
- package/dist/models/index.d.ts +1 -0
- package/dist/models/index.js +1 -0
- package/dist/webhooks.d.ts +63 -0
- package/dist/webhooks.js +98 -0
- package/package.json +1 -1
- package/src/errors.ts +59 -1
- package/src/http.ts +77 -0
- package/src/index.ts +338 -163
- package/src/jobs.ts +215 -0
- package/src/models/AsyncJob.ts +130 -0
- package/src/models/TikTok.ts +521 -454
- package/src/models/TweetStatement.ts +89 -84
- package/src/models/index.ts +2 -1
- package/src/webhooks.ts +156 -0
package/dist/index.js
CHANGED
|
@@ -17,24 +17,66 @@ 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 = '
|
|
34
|
+
exports.SDK_VERSION = '2.0.0';
|
|
30
35
|
//endregion
|
|
31
|
-
function
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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;
|
|
37
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;
|
|
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));
|
|
@@ -75,6 +117,84 @@ class VidNavigatorClient {
|
|
|
75
117
|
},
|
|
76
118
|
...config.axiosConfig,
|
|
77
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;
|
|
78
198
|
}
|
|
79
199
|
async request(method, url, data, params, extraHeaders) {
|
|
80
200
|
try {
|
|
@@ -89,34 +209,7 @@ class VidNavigatorClient {
|
|
|
89
209
|
}
|
|
90
210
|
catch (error) {
|
|
91
211
|
if (axios_1.default.isAxiosError(error) && error.response) {
|
|
92
|
-
|
|
93
|
-
const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
|
|
94
|
-
const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
|
|
95
|
-
switch (status) {
|
|
96
|
-
case 400:
|
|
97
|
-
throw new errors_1.BadRequestError(message, status, errorCode, errorMessage, details);
|
|
98
|
-
case 401:
|
|
99
|
-
throw new errors_1.AuthenticationError(message, status, errorCode, errorMessage, details);
|
|
100
|
-
case 402:
|
|
101
|
-
throw new errors_1.PaymentRequiredError(message, status, errorCode, errorMessage, details);
|
|
102
|
-
case 403:
|
|
103
|
-
throw new errors_1.AccessDeniedError(message, status, errorCode, errorMessage, details);
|
|
104
|
-
case 404:
|
|
105
|
-
throw new errors_1.NotFoundError(message, status, errorCode, errorMessage, details);
|
|
106
|
-
case 413:
|
|
107
|
-
throw new errors_1.StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
|
|
108
|
-
case 429:
|
|
109
|
-
throw new errors_1.RateLimitExceededError(message, status, errorCode, errorMessage, details);
|
|
110
|
-
case 451:
|
|
111
|
-
throw new errors_1.GeoRestrictedError(message, status, errorCode, errorMessage, details);
|
|
112
|
-
case 503:
|
|
113
|
-
throw new errors_1.SystemOverloadError(message, status, errorCode, errorMessage, details, data?.retry_after_seconds);
|
|
114
|
-
default:
|
|
115
|
-
if (status >= 500) {
|
|
116
|
-
throw new errors_1.ServerError(message, status, errorCode, errorMessage, details);
|
|
117
|
-
}
|
|
118
|
-
throw new errors_1.VidNavigatorError(message, status, errorCode, errorMessage, details);
|
|
119
|
-
}
|
|
212
|
+
throw (0, http_1.buildApiError)(error.response.status, error.response.data, error.message);
|
|
120
213
|
}
|
|
121
214
|
throw new errors_1.VidNavigatorError(error.message);
|
|
122
215
|
}
|
|
@@ -144,23 +237,13 @@ class VidNavigatorClient {
|
|
|
144
237
|
warnDeprecated('getYouTubeTranscript', 'getTranscript');
|
|
145
238
|
return this.getTranscript(payload);
|
|
146
239
|
}
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
videos: inner.videos.map((v) => models_1.CarouselVideoResult.fromJSON(v)),
|
|
155
|
-
usage,
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
const single = inner;
|
|
159
|
-
return {
|
|
160
|
-
video_info: models_1.VideoInfo.fromJSON(single.video_info),
|
|
161
|
-
transcript: (0, models_1.transcriptFromJSON)(single.transcript),
|
|
162
|
-
usage,
|
|
163
|
-
};
|
|
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 });
|
|
164
247
|
}
|
|
165
248
|
//endregion
|
|
166
249
|
//region --- TikTok ---
|
|
@@ -240,26 +323,7 @@ class VidNavigatorClient {
|
|
|
240
323
|
}
|
|
241
324
|
catch (error) {
|
|
242
325
|
if (axios_1.default.isAxiosError(error) && error.response) {
|
|
243
|
-
|
|
244
|
-
const { errorCode, errorMessage, details } = parseApiErrorPayload(data);
|
|
245
|
-
const message = `API request failed with status ${status}: ${errorMessage || error.message}`;
|
|
246
|
-
switch (status) {
|
|
247
|
-
case 400:
|
|
248
|
-
throw new errors_1.BadRequestError(message, status, errorCode, errorMessage, details);
|
|
249
|
-
case 401:
|
|
250
|
-
throw new errors_1.AuthenticationError(message, status, errorCode, errorMessage, details);
|
|
251
|
-
case 402:
|
|
252
|
-
throw new errors_1.PaymentRequiredError(message, status, errorCode, errorMessage, details);
|
|
253
|
-
case 413:
|
|
254
|
-
throw new errors_1.StorageQuotaExceededError(message, status, errorCode, errorMessage, details);
|
|
255
|
-
case 503:
|
|
256
|
-
throw new errors_1.SystemOverloadError(message, status, errorCode, errorMessage, details, data?.retry_after_seconds);
|
|
257
|
-
default:
|
|
258
|
-
if (status >= 500) {
|
|
259
|
-
throw new errors_1.ServerError(message, status, errorCode, errorMessage, details);
|
|
260
|
-
}
|
|
261
|
-
throw new errors_1.VidNavigatorError(message, status, errorCode, errorMessage, details);
|
|
262
|
-
}
|
|
326
|
+
throw (0, http_1.buildApiError)(error.response.status, error.response.data, error.message);
|
|
263
327
|
}
|
|
264
328
|
throw new errors_1.VidNavigatorError(error.message);
|
|
265
329
|
}
|
|
@@ -326,33 +390,24 @@ class VidNavigatorClient {
|
|
|
326
390
|
usage: response.usage ? models_1.UsageBlock.fromJSON(response.usage) : undefined,
|
|
327
391
|
};
|
|
328
392
|
}
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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);
|
|
332
399
|
}
|
|
333
400
|
//endregion
|
|
334
401
|
//region --- Extraction ---
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
return {
|
|
345
|
-
data: body.data,
|
|
346
|
-
video_info: body.video_info ? models_1.VideoInfo.fromJSON(body.video_info) : undefined,
|
|
347
|
-
usage: body.usage ? models_1.UsageBlock.fromJSON(body.usage) : undefined,
|
|
348
|
-
};
|
|
349
|
-
}
|
|
350
|
-
const body = await this.request('POST', '/extract/video', payload);
|
|
351
|
-
return {
|
|
352
|
-
data: body.data,
|
|
353
|
-
video_info: body.video_info ? models_1.VideoInfo.fromJSON(body.video_info) : undefined,
|
|
354
|
-
usage: body.usage ? models_1.UsageBlock.fromJSON(body.usage) : undefined,
|
|
355
|
-
};
|
|
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 });
|
|
356
411
|
}
|
|
357
412
|
async extractFileData(payload) {
|
|
358
413
|
if ('schemaFilePath' in payload) {
|
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>;
|
package/dist/jobs.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Job = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_POLL_INTERVAL_MS = void 0;
|
|
4
|
+
exports.isTerminal = isTerminal;
|
|
5
|
+
exports.pollUntilDone = pollUntilDone;
|
|
6
|
+
exports.errorFromFailedTask = errorFromFailedTask;
|
|
7
|
+
const errors_1 = require("./errors");
|
|
8
|
+
const http_1 = require("./http");
|
|
9
|
+
exports.DEFAULT_POLL_INTERVAL_MS = 3000;
|
|
10
|
+
exports.DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
|
|
11
|
+
const FAST_START_WINDOW_MS = 10000;
|
|
12
|
+
const FAST_START_INTERVAL_MS = 1000;
|
|
13
|
+
function isTerminal(status) {
|
|
14
|
+
return status === 'completed' || status === 'failed';
|
|
15
|
+
}
|
|
16
|
+
function abortError(task_id) {
|
|
17
|
+
const err = new errors_1.VidNavigatorError(`Stopped waiting for task ${task_id} (aborted); the job keeps running server-side`);
|
|
18
|
+
err.task_id = task_id;
|
|
19
|
+
return err;
|
|
20
|
+
}
|
|
21
|
+
function sleep(ms, task_id, signal) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
if (signal?.aborted)
|
|
24
|
+
return reject(abortError(task_id));
|
|
25
|
+
const onAbort = () => {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
reject(abortError(task_id));
|
|
28
|
+
};
|
|
29
|
+
const timer = setTimeout(() => {
|
|
30
|
+
signal?.removeEventListener('abort', onAbort);
|
|
31
|
+
resolve();
|
|
32
|
+
}, ms);
|
|
33
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/** Poll `fetchTask` until `task_status` is `completed` or `failed`, and return that final snapshot. */
|
|
37
|
+
async function pollUntilDone(task_id, fetchTask, options = {}) {
|
|
38
|
+
const intervalMs = options.intervalMs ?? exports.DEFAULT_POLL_INTERVAL_MS;
|
|
39
|
+
const fastStart = options.fastStart ?? true;
|
|
40
|
+
const timeoutMs = options.timeoutMs ?? exports.DEFAULT_TIMEOUT_MS;
|
|
41
|
+
const started = Date.now();
|
|
42
|
+
let task = await withTaskId(task_id, fetchTask);
|
|
43
|
+
options.onPoll?.(task);
|
|
44
|
+
while (!isTerminal(task.task_status)) {
|
|
45
|
+
const elapsed = Date.now() - started;
|
|
46
|
+
const delay = fastStart && elapsed < FAST_START_WINDOW_MS ? Math.min(FAST_START_INTERVAL_MS, intervalMs) : intervalMs;
|
|
47
|
+
if (timeoutMs > 0 && elapsed + delay > timeoutMs) {
|
|
48
|
+
throw new errors_1.TaskTimeoutError(`Task ${task_id} still ${task.task_status} after ${Math.round(elapsed / 1000)}s. ` +
|
|
49
|
+
`It keeps running server-side; resume it with this task_id (results are kept 1 hour after it finishes).`, task_id);
|
|
50
|
+
}
|
|
51
|
+
await sleep(delay, task_id, options.signal);
|
|
52
|
+
task = await withTaskId(task_id, fetchTask);
|
|
53
|
+
options.onPoll?.(task);
|
|
54
|
+
}
|
|
55
|
+
return task;
|
|
56
|
+
}
|
|
57
|
+
/** Run `fn`, tagging any SDK error it throws with `task_id` so the job can always be resumed. */
|
|
58
|
+
async function withTaskId(task_id, fn) {
|
|
59
|
+
try {
|
|
60
|
+
return await fn();
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (error instanceof errors_1.VidNavigatorError && !error.task_id)
|
|
64
|
+
error.task_id = task_id;
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Build the error for a `failed` task from its `error` object (`error`, `message`, `http_status`),
|
|
70
|
+
* using the same class the API would have used for that status. Carries `task_id`.
|
|
71
|
+
*/
|
|
72
|
+
function errorFromFailedTask(task) {
|
|
73
|
+
const info = task.error;
|
|
74
|
+
let err;
|
|
75
|
+
if (info?.http_status) {
|
|
76
|
+
err = (0, http_1.buildApiError)(info.http_status, {
|
|
77
|
+
error: info.error,
|
|
78
|
+
message: info.message ?? `Task ${task.task_id} failed`,
|
|
79
|
+
task_id: task.task_id,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
const message = info?.message ?? 'no error details returned';
|
|
84
|
+
err = new errors_1.VidNavigatorError(`Task ${task.task_id} failed: ${message}`, undefined, info?.error, info?.message, task);
|
|
85
|
+
}
|
|
86
|
+
err.task_id = task.task_id;
|
|
87
|
+
return err;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Handle to a submitted async job. Use it to run many jobs at once: submit them all, then
|
|
91
|
+
* `await job.result()` on each (or check `await job.status()` yourself).
|
|
92
|
+
*
|
|
93
|
+
* Polling always works, whether or not a webhook is configured.
|
|
94
|
+
*/
|
|
95
|
+
class Job {
|
|
96
|
+
constructor(info, fetchTask, toResult) {
|
|
97
|
+
this.task_id = info.task_id;
|
|
98
|
+
this.job_type = info.job_type;
|
|
99
|
+
this.check_status_url = info.check_status_url;
|
|
100
|
+
this.webhook_url = info.webhook_url;
|
|
101
|
+
this.expires_at = info.expires_at;
|
|
102
|
+
this.fetchTask = async () => {
|
|
103
|
+
const task = await fetchTask();
|
|
104
|
+
this.task = task;
|
|
105
|
+
return task;
|
|
106
|
+
};
|
|
107
|
+
this.toResult = toResult;
|
|
108
|
+
}
|
|
109
|
+
/** Poll once and return the full task snapshot. */
|
|
110
|
+
async refresh() {
|
|
111
|
+
return withTaskId(this.task_id, this.fetchTask);
|
|
112
|
+
}
|
|
113
|
+
/** Poll once and return the current `task_status`. */
|
|
114
|
+
async status() {
|
|
115
|
+
return (await this.refresh()).task_status;
|
|
116
|
+
}
|
|
117
|
+
/** Poll until the task is `completed` or `failed` and return the final snapshot. Does not throw on `failed`. */
|
|
118
|
+
async wait(options) {
|
|
119
|
+
return pollUntilDone(this.task_id, this.fetchTask, options);
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Wait for the job and return its result. Throws the error from the task's `error` object when it
|
|
123
|
+
* failed, or {@link TaskTimeoutError} on timeout. Every error carries `task_id`.
|
|
124
|
+
*/
|
|
125
|
+
async result(options) {
|
|
126
|
+
const task = await this.wait(options);
|
|
127
|
+
if (task.task_status === 'failed')
|
|
128
|
+
throw errorFromFailedTask(task);
|
|
129
|
+
return withTaskId(this.task_id, () => this.toResult(task));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
exports.Job = Job;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { UsageBlock } from './Usage';
|
|
2
|
+
/** Async job kinds returned by the `/transcribe/async`, `/extract/video/async` and `/tweet/statement/async` endpoints. */
|
|
3
|
+
export type AsyncJobType = 'transcribe' | 'extract_video' | 'tweet_statement';
|
|
4
|
+
/** `processing` = accepted and being worked on. `completed` and `failed` are terminal. */
|
|
5
|
+
export type AsyncTaskStatus = 'processing' | 'completed' | 'failed';
|
|
6
|
+
/**
|
|
7
|
+
* Present when `task_status === 'failed'`. Carries the same `error` code and HTTP status
|
|
8
|
+
* the synchronous endpoint would have returned (e.g. `video_too_long` / 400).
|
|
9
|
+
*/
|
|
10
|
+
export interface AsyncJobError {
|
|
11
|
+
error?: string;
|
|
12
|
+
message?: string;
|
|
13
|
+
http_status?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Delivery state of a job's webhook. `null` when no webhook was configured.
|
|
17
|
+
* The webhook URL itself is never echoed back.
|
|
18
|
+
*/
|
|
19
|
+
export interface AsyncJobWebhookStatus {
|
|
20
|
+
status?: 'pending' | 'delivered' | 'failed';
|
|
21
|
+
/** Delivery attempts made (max 5). */
|
|
22
|
+
attempts?: number;
|
|
23
|
+
/** HTTP status your endpoint returned on the last attempt. */
|
|
24
|
+
response_status?: number | null;
|
|
25
|
+
last_error?: string | null;
|
|
26
|
+
delivered_at?: string | null;
|
|
27
|
+
}
|
|
28
|
+
export interface AsyncJobAcceptedJSON {
|
|
29
|
+
task_id: string;
|
|
30
|
+
task_status: 'processing';
|
|
31
|
+
job_type?: AsyncJobType;
|
|
32
|
+
expires_at?: string;
|
|
33
|
+
check_status_url?: string;
|
|
34
|
+
webhook_url?: string | null;
|
|
35
|
+
message?: string;
|
|
36
|
+
docs_url?: string;
|
|
37
|
+
}
|
|
38
|
+
/** 202 response from an async submit endpoint. Poll with the matching `get...AsyncJob(task_id)` method. */
|
|
39
|
+
export declare class AsyncJobAccepted {
|
|
40
|
+
task_id: string;
|
|
41
|
+
task_status: 'processing';
|
|
42
|
+
job_type?: AsyncJobType;
|
|
43
|
+
/** Provisional submit-time bound; pushed out to finish time + 1 hour once the job completes. */
|
|
44
|
+
expires_at?: string;
|
|
45
|
+
/** Relative URL to poll for status and the result. */
|
|
46
|
+
check_status_url?: string;
|
|
47
|
+
/** The URL this job's result will be POSTed to, or `null` if no webhook applies. */
|
|
48
|
+
webhook_url?: string | null;
|
|
49
|
+
message?: string;
|
|
50
|
+
docs_url?: string;
|
|
51
|
+
constructor(data: AsyncJobAcceptedJSON);
|
|
52
|
+
static fromJSON(json: AsyncJobAcceptedJSON): AsyncJobAccepted;
|
|
53
|
+
}
|
|
54
|
+
export interface AsyncJobJSON {
|
|
55
|
+
task_id: string;
|
|
56
|
+
task_status: AsyncTaskStatus;
|
|
57
|
+
job_type?: string;
|
|
58
|
+
request?: Record<string, unknown>;
|
|
59
|
+
created_at?: string;
|
|
60
|
+
started_at?: string | null;
|
|
61
|
+
completed_at?: string | null;
|
|
62
|
+
expires_at?: string;
|
|
63
|
+
check_status_url?: string;
|
|
64
|
+
webhook?: AsyncJobWebhookStatus | null;
|
|
65
|
+
result?: any;
|
|
66
|
+
error?: AsyncJobError | null;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* State of an async job, returned by the `get...AsyncJob(task_id)` pollers.
|
|
70
|
+
* `result` is populated only when `task_status === 'completed'` and is parsed into the same
|
|
71
|
+
* shape the synchronous endpoint returns; `error` is populated only when `task_status === 'failed'`.
|
|
72
|
+
*/
|
|
73
|
+
export declare class AsyncJob<TResult> {
|
|
74
|
+
task_id: string;
|
|
75
|
+
task_status: AsyncTaskStatus;
|
|
76
|
+
job_type?: string;
|
|
77
|
+
/** Echo of the submitted parameters (`webhook_url` is never echoed). */
|
|
78
|
+
request?: Record<string, unknown>;
|
|
79
|
+
created_at?: string;
|
|
80
|
+
started_at?: string | null;
|
|
81
|
+
completed_at?: string | null;
|
|
82
|
+
/** Results are deleted after this time (1 hour after the job finishes). */
|
|
83
|
+
expires_at?: string;
|
|
84
|
+
check_status_url?: string;
|
|
85
|
+
webhook?: AsyncJobWebhookStatus | null;
|
|
86
|
+
result: TResult | null;
|
|
87
|
+
error: AsyncJobError | null;
|
|
88
|
+
/** Per-call usage, populated only when polled with `include_usage: true` and `task_status === 'completed'`. */
|
|
89
|
+
usage?: UsageBlock;
|
|
90
|
+
constructor(data: AsyncJobJSON, parseResult: (raw: any) => TResult);
|
|
91
|
+
static fromJSON<T>(json: AsyncJobJSON, parseResult: (raw: any) => T): AsyncJob<T>;
|
|
92
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AsyncJob = exports.AsyncJobAccepted = void 0;
|
|
4
|
+
/** 202 response from an async submit endpoint. Poll with the matching `get...AsyncJob(task_id)` method. */
|
|
5
|
+
class AsyncJobAccepted {
|
|
6
|
+
constructor(data) {
|
|
7
|
+
this.task_id = data.task_id;
|
|
8
|
+
this.task_status = data.task_status;
|
|
9
|
+
this.job_type = data.job_type;
|
|
10
|
+
this.expires_at = data.expires_at;
|
|
11
|
+
this.check_status_url = data.check_status_url;
|
|
12
|
+
this.webhook_url = data.webhook_url;
|
|
13
|
+
this.message = data.message;
|
|
14
|
+
this.docs_url = data.docs_url;
|
|
15
|
+
}
|
|
16
|
+
static fromJSON(json) {
|
|
17
|
+
return new AsyncJobAccepted(json);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
exports.AsyncJobAccepted = AsyncJobAccepted;
|
|
21
|
+
/**
|
|
22
|
+
* State of an async job, returned by the `get...AsyncJob(task_id)` pollers.
|
|
23
|
+
* `result` is populated only when `task_status === 'completed'` and is parsed into the same
|
|
24
|
+
* shape the synchronous endpoint returns; `error` is populated only when `task_status === 'failed'`.
|
|
25
|
+
*/
|
|
26
|
+
class AsyncJob {
|
|
27
|
+
constructor(data, parseResult) {
|
|
28
|
+
this.task_id = data.task_id;
|
|
29
|
+
this.task_status = data.task_status;
|
|
30
|
+
this.job_type = data.job_type;
|
|
31
|
+
this.request = data.request;
|
|
32
|
+
this.created_at = data.created_at;
|
|
33
|
+
this.started_at = data.started_at;
|
|
34
|
+
this.completed_at = data.completed_at;
|
|
35
|
+
this.expires_at = data.expires_at;
|
|
36
|
+
this.check_status_url = data.check_status_url;
|
|
37
|
+
this.webhook = data.webhook;
|
|
38
|
+
this.result = data.result !== undefined && data.result !== null ? parseResult(data.result) : null;
|
|
39
|
+
this.error = data.error ?? null;
|
|
40
|
+
}
|
|
41
|
+
static fromJSON(json, parseResult) {
|
|
42
|
+
return new AsyncJob(json, parseResult);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
exports.AsyncJob = AsyncJob;
|