@tube2vid/sdk 0.0.0-stage → 1.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tube2Vid
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,118 @@
1
- # Temporary Holding Version
1
+ # Tube2Vid TypeScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/Tube2Vid/sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/Tube2Vid/sdk/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@tube2vid/sdk.svg)](https://www.npmjs.com/package/@tube2vid/sdk)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ The official YouTube, TikTok and Instagram video downloader API client for TypeScript and JavaScript. `@tube2vid/sdk` is a typed, zero-dependency wrapper around the [Tube2Vid media download API](https://tube2vid.com): submit a URL from YouTube, TikTok, Instagram, X, Reddit or any of 1,800+ other sites, and get back an MP4, MP3 or image file. It runs in Node, Deno, Bun and the browser.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install @tube2vid/sdk
13
+ ```
14
+
15
+ Needs Node 18.17+ (or any runtime with `fetch`). [Get an API key](https://tube2vid.com/pricing) and export it as `TUBE2VID_API_KEY`; the client reads it automatically.
16
+
17
+ ## Quickstart
18
+
19
+ ```ts
20
+ import { writeFile } from "node:fs/promises";
21
+ import { Tube2VidClient } from "@tube2vid/sdk";
22
+
23
+ const client = new Tube2VidClient({ apiKey: process.env.TUBE2VID_API_KEY });
24
+
25
+ const queued = await client.submitJob({
26
+ url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
27
+ mode: "auto", // "auto" | "video" | "audio" | "gallery"
28
+ format: "mp4",
29
+ quality: "best"
30
+ });
31
+
32
+ const job = await client.waitForJob(queued.jobId);
33
+ if (job.status === "failed") throw new Error(job.errorMessage);
34
+
35
+ const file = await client.downloadJob(job.id);
36
+ await writeFile(`${job.id}.${job.format}`, Buffer.from(await file.arrayBuffer()));
37
+
38
+ // Or hand someone a short-lived direct link instead:
39
+ console.log(await client.getDownloadLink(job.id));
40
+ ```
41
+
42
+ ## Configuration
43
+
44
+ | Option | Default | |
45
+ | --- | --- | --- |
46
+ | `apiKey` | `$TUBE2VID_API_KEY` | Your `tv_live_...` key, sent as `Authorization: Bearer` |
47
+ | `baseUrl` | `https://tube2vid.com` (the page origin in a browser) | API origin |
48
+ | `fetch` | global `fetch` | Custom fetch, e.g. for proxies or tests |
49
+ | `headers` | none | Extra headers on every request |
50
+
51
+ ## Methods
52
+
53
+ Public, no key needed:
54
+
55
+ | Method | Endpoint |
56
+ | --- | --- |
57
+ | `getHealth()` | `GET /healthz` |
58
+ | `listPlatforms()` | `GET /v1/platforms` |
59
+ | `getPlatformHealth()` | `GET /v1/platforms/health` |
60
+ | `getStatusHistory(limit?, platform?)` | `GET /v1/status/history` |
61
+ | `getOperationalMetrics()` | `GET /v1/ops/metrics` |
62
+ | `getPowChallenge()` | `GET /v1/challenges/pow` |
63
+ | `submitPublicJob(input)` | `POST /v1/public/jobs` (browser flow: needs a solved `pow`) |
64
+ | `getPublicJobStatus(jobId)` | `GET /v1/public/jobs/{jobId}` |
65
+ | `getPublicDownloadUrl(jobId)`, `getPublicThumbnailUrl(jobId)` | URL builders |
66
+
67
+ With an API key:
68
+
69
+ | Method | Endpoint | Scope |
70
+ | --- | --- | --- |
71
+ | `submitJob(input)` / `submitAuthenticatedJob(input)` | `POST /v1/jobs` | `jobs:write` |
72
+ | `getJobStatus(jobId)`, `waitForJob(jobId, options?)` | `GET /v1/jobs/{jobId}` | `jobs:read` |
73
+ | `getJobEvents(jobId)` | `GET /v1/jobs/{jobId}/events` | `jobs:read` |
74
+ | `downloadJob(jobId)`, `getDownloadLink(jobId)` | `GET /v1/jobs/{jobId}/download` | `jobs:read` |
75
+ | `getUsage()` | `GET /v1/usage` | `usage:read` |
76
+ | `listApiKeys()` | `GET /v1/api-keys` | `keys:read` |
77
+ | `createApiKey(input)` | `POST /v1/api-keys` | `keys:write` |
78
+ | `createCheckout({ credits })` | `POST /v1/billing/checkout` | `billing:write` |
79
+
80
+ `getDownloadLink` and `downloadJob` read the API's redirect to the signed file URL, so they work in server runtimes (Node, Deno, Bun), not in browsers.
81
+
82
+ ## Errors
83
+
84
+ Any non-2xx response throws a `Tube2VidApiError` with `status`, `message`, `code` (when the API sends one, e.g. `turnstile_failed`), the raw `body`, and the parsed `data`. A `402` means the account is out of credits; `data.requiredCredits` says how many the job needs.
85
+
86
+ ```ts
87
+ import { Tube2VidApiError } from "@tube2vid/sdk";
88
+
89
+ try {
90
+ await client.getUsage();
91
+ } catch (error) {
92
+ if (error instanceof Tube2VidApiError && error.status === 401) console.error("Check your API key");
93
+ else throw error;
94
+ }
95
+ ```
96
+
97
+
98
+ ## Links
99
+
100
+ - [Tube2Vid](https://tube2vid.com): the online video downloader this SDK talks to
101
+ - [API documentation](https://tube2vid.com/docs) and the [OpenAPI spec](https://github.com/Tube2Vid/api)
102
+ - [Pricing and API keys](https://tube2vid.com/pricing)
103
+ - [Live platform status](https://tube2vid.com/status) for YouTube, TikTok, Instagram and the rest
104
+ - Tools built on this SDK: the [`tube2vid` CLI](https://github.com/Tube2Vid/cli) and the [Tube2Vid MCP server](https://github.com/Tube2Vid/mcp) for Claude and Cursor
105
+
106
+ Other languages: [TypeScript](https://github.com/Tube2Vid/sdk), [Python](https://github.com/Tube2Vid/sdk-python), [Go](https://github.com/Tube2Vid/sdk-go), [Java](https://github.com/Tube2Vid/sdk-java), [C#](https://github.com/Tube2Vid/sdk-dotnet), [PHP](https://github.com/Tube2Vid/sdk-php), [Ruby](https://github.com/Tube2Vid/sdk-ruby), [Rust](https://github.com/Tube2Vid/sdk-rust), [Swift](https://github.com/Tube2Vid/sdk-swift).
107
+
108
+ ## Develop
109
+
110
+ ```bash
111
+ npm install
112
+ npm test
113
+ npm run build
114
+ ```
115
+
116
+ ## License
117
+
118
+ [MIT](LICENSE), Copyright (c) 2026 Tube2Vid.
@@ -0,0 +1,74 @@
1
+ import type { ApiKeyCreateInput, ApiKeySummary, CheckoutInput, CheckoutSession, CreatedApiKey, JobEvent, JobStatus, JobSubmitInput, OperationalMetrics, PlatformHealthRow, PlatformSummary, PowChallenge, PublicJobStatus, QueuedJobResponse, ServiceHealth, StatusHistoryItem, UsageSummary } from "./types.js";
2
+ export declare const DEFAULT_BASE_URL = "https://tube2vid.com";
3
+ export type Tube2VidClientOptions = {
4
+ /** API origin. Defaults to the page origin in a browser, otherwise https://tube2vid.com. */
5
+ baseUrl?: string;
6
+ /** A `tv_live_...` API key. Defaults to `$TUBE2VID_API_KEY` in Node, Deno and Bun. Required for /v1/jobs, /v1/usage, /v1/api-keys and billing. */
7
+ apiKey?: string;
8
+ fetch?: typeof fetch;
9
+ headers?: Record<string, string>;
10
+ };
11
+ export type WaitForJobOptions = {
12
+ /** Poll interval, default 2000 ms. */
13
+ intervalMs?: number;
14
+ /** Give up after this long, default 15 minutes. */
15
+ timeoutMs?: number;
16
+ onUpdate?: (job: JobStatus) => void;
17
+ signal?: AbortSignal;
18
+ };
19
+ /** Thrown for any non-2xx API response. */
20
+ export declare class Tube2VidApiError extends Error {
21
+ readonly status: number;
22
+ /** Raw response body, if any. */
23
+ readonly body?: string;
24
+ /** Machine-readable error code when the API sent one (e.g. "turnstile_failed"). */
25
+ readonly code?: string;
26
+ /** Parsed JSON body, if the body was JSON. */
27
+ readonly data?: unknown;
28
+ constructor(status: number, body?: string);
29
+ }
30
+ export declare class Tube2VidClient {
31
+ readonly baseUrl: string;
32
+ readonly apiKey?: string;
33
+ readonly fetchImpl: typeof fetch;
34
+ readonly headers: Record<string, string>;
35
+ constructor(options?: Tube2VidClientOptions);
36
+ getHealth(): Promise<ServiceHealth>;
37
+ listPlatforms(): Promise<PlatformSummary[]>;
38
+ getPlatformHealth(): Promise<PlatformHealthRow[]>;
39
+ getStatusHistory(limit?: number, platform?: string): Promise<StatusHistoryItem[]>;
40
+ getOperationalMetrics(): Promise<OperationalMetrics>;
41
+ getPowChallenge(): Promise<PowChallenge>;
42
+ /** Anonymous submission, as the website does it. Requires `pow` (and `turnstileToken` where the human check is on). */
43
+ submitPublicJob(input: JobSubmitInput): Promise<QueuedJobResponse>;
44
+ getPublicJobStatus(jobId: string): Promise<PublicJobStatus>;
45
+ /** Direct link to an anonymous job's file; it redirects to a short-lived signed URL. */
46
+ getPublicDownloadUrl(jobId: string): string;
47
+ getPublicThumbnailUrl(jobId: string): string;
48
+ submitAuthenticatedJob(input: JobSubmitInput): Promise<QueuedJobResponse>;
49
+ /** Uses /v1/jobs with an API key, /v1/public/jobs without one. */
50
+ submitJob(input: JobSubmitInput): Promise<QueuedJobResponse>;
51
+ getJobStatus(jobId: string): Promise<JobStatus>;
52
+ getJobEvents(jobId: string): Promise<JobEvent[]>;
53
+ /** Polls getJobStatus until the job is completed or failed. Resolves with the final job either way. */
54
+ waitForJob(jobId: string, options?: WaitForJobOptions): Promise<JobStatus>;
55
+ /** The authenticated download endpoint. It needs the bearer header, so prefer getDownloadLink or downloadJob. */
56
+ getDownloadUrl(jobId: string): string;
57
+ /**
58
+ * Resolves a completed job to its short-lived signed file URL, which needs no auth.
59
+ * shortcut: relies on reading the redirect, which only server runtimes (Node, Deno, Bun) allow; browsers get an error.
60
+ */
61
+ getDownloadLink(jobId: string): Promise<string>;
62
+ /** Fetches a completed job's file. Read the body as a stream or with arrayBuffer(). */
63
+ downloadJob(jobId: string): Promise<Response>;
64
+ getUsage(): Promise<UsageSummary>;
65
+ /** Needs the keys:read scope. */
66
+ listApiKeys(): Promise<ApiKeySummary[]>;
67
+ /** Needs the keys:write scope. The returned `key` is shown only once. */
68
+ createApiKey(input: ApiKeyCreateInput): Promise<CreatedApiKey>;
69
+ /** Needs the billing:write scope. Open `checkoutUrl` to pay. */
70
+ createCheckout(input: CheckoutInput): Promise<CheckoutSession>;
71
+ private getJson;
72
+ private postJson;
73
+ private send;
74
+ }
package/dist/client.js ADDED
@@ -0,0 +1,195 @@
1
+ export const DEFAULT_BASE_URL = "https://tube2vid.com";
2
+ /** Thrown for any non-2xx API response. */
3
+ export class Tube2VidApiError extends Error {
4
+ status;
5
+ /** Raw response body, if any. */
6
+ body;
7
+ /** Machine-readable error code when the API sent one (e.g. "turnstile_failed"). */
8
+ code;
9
+ /** Parsed JSON body, if the body was JSON. */
10
+ data;
11
+ constructor(status, body) {
12
+ let data;
13
+ try {
14
+ data = body ? JSON.parse(body) : undefined;
15
+ }
16
+ catch {
17
+ data = undefined;
18
+ }
19
+ const fields = (data && typeof data === "object" ? data : {});
20
+ super(typeof fields.error === "string" ? fields.error : body || `Tube2Vid API request failed with ${status}`);
21
+ this.name = "Tube2VidApiError";
22
+ this.status = status;
23
+ this.body = body || undefined;
24
+ this.code = typeof fields.code === "string" ? fields.code : undefined;
25
+ this.data = data;
26
+ }
27
+ }
28
+ export class Tube2VidClient {
29
+ baseUrl;
30
+ apiKey;
31
+ fetchImpl;
32
+ headers;
33
+ constructor(options = {}) {
34
+ this.baseUrl = normalizeBaseUrl(options.baseUrl ?? defaultBaseUrl());
35
+ this.apiKey = (options.apiKey ?? envApiKey())?.trim() || undefined;
36
+ this.fetchImpl = options.fetch ?? ((...args) => fetch(...args));
37
+ this.headers = { ...(options.headers ?? {}) };
38
+ }
39
+ // Public, no API key needed.
40
+ async getHealth() {
41
+ return this.getJson("/healthz");
42
+ }
43
+ async listPlatforms() {
44
+ return this.getJson("/v1/platforms");
45
+ }
46
+ async getPlatformHealth() {
47
+ return this.getJson("/v1/platforms/health");
48
+ }
49
+ async getStatusHistory(limit = 50, platform) {
50
+ const query = new URLSearchParams({ limit: String(limit) });
51
+ if (platform)
52
+ query.set("platform", platform);
53
+ return this.getJson(`/v1/status/history?${query}`);
54
+ }
55
+ async getOperationalMetrics() {
56
+ return this.getJson("/v1/ops/metrics");
57
+ }
58
+ async getPowChallenge() {
59
+ return this.getJson("/v1/challenges/pow");
60
+ }
61
+ /** Anonymous submission, as the website does it. Requires `pow` (and `turnstileToken` where the human check is on). */
62
+ async submitPublicJob(input) {
63
+ return this.postJson("/v1/public/jobs", input);
64
+ }
65
+ async getPublicJobStatus(jobId) {
66
+ return this.getJson(`/v1/public/jobs/${encodeURIComponent(jobId)}`);
67
+ }
68
+ /** Direct link to an anonymous job's file; it redirects to a short-lived signed URL. */
69
+ getPublicDownloadUrl(jobId) {
70
+ return `${this.baseUrl}/v1/public/jobs/${encodeURIComponent(jobId)}/download`;
71
+ }
72
+ getPublicThumbnailUrl(jobId) {
73
+ return `${this.baseUrl}/v1/public/jobs/${encodeURIComponent(jobId)}/thumbnail`;
74
+ }
75
+ // Authenticated, needs an API key (or a browser session token).
76
+ async submitAuthenticatedJob(input) {
77
+ return this.postJson("/v1/jobs", input);
78
+ }
79
+ /** Uses /v1/jobs with an API key, /v1/public/jobs without one. */
80
+ async submitJob(input) {
81
+ return this.apiKey ? this.submitAuthenticatedJob(input) : this.submitPublicJob(input);
82
+ }
83
+ async getJobStatus(jobId) {
84
+ return this.getJson(`/v1/jobs/${encodeURIComponent(jobId)}`);
85
+ }
86
+ async getJobEvents(jobId) {
87
+ return this.getJson(`/v1/jobs/${encodeURIComponent(jobId)}/events`);
88
+ }
89
+ /** Polls getJobStatus until the job is completed or failed. Resolves with the final job either way. */
90
+ async waitForJob(jobId, options = {}) {
91
+ const intervalMs = options.intervalMs ?? 2000;
92
+ const deadline = Date.now() + (options.timeoutMs ?? 15 * 60 * 1000);
93
+ for (;;) {
94
+ options.signal?.throwIfAborted();
95
+ const job = await this.getJobStatus(jobId);
96
+ options.onUpdate?.(job);
97
+ if (job.status === "completed" || job.status === "failed")
98
+ return job;
99
+ if (Date.now() + intervalMs > deadline)
100
+ throw new Error(`Timed out waiting for job ${jobId}`);
101
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
102
+ }
103
+ }
104
+ /** The authenticated download endpoint. It needs the bearer header, so prefer getDownloadLink or downloadJob. */
105
+ getDownloadUrl(jobId) {
106
+ return `${this.baseUrl}/v1/jobs/${encodeURIComponent(jobId)}/download`;
107
+ }
108
+ /**
109
+ * Resolves a completed job to its short-lived signed file URL, which needs no auth.
110
+ * shortcut: relies on reading the redirect, which only server runtimes (Node, Deno, Bun) allow; browsers get an error.
111
+ */
112
+ async getDownloadLink(jobId) {
113
+ const response = await this.send(this.getDownloadUrl(jobId), { redirect: "manual" });
114
+ const location = response.headers.get("location");
115
+ if (response.status >= 300 && response.status < 400 && location)
116
+ return new URL(location, this.baseUrl).toString();
117
+ await response.body?.cancel();
118
+ if (!response.ok)
119
+ throw await toApiError(response);
120
+ throw new Tube2VidApiError(response.status, "This API serves the file directly; use downloadJob instead.");
121
+ }
122
+ /** Fetches a completed job's file. Read the body as a stream or with arrayBuffer(). */
123
+ async downloadJob(jobId) {
124
+ const response = await this.send(this.getDownloadUrl(jobId), { redirect: "manual" });
125
+ const location = response.headers.get("location");
126
+ if (response.status >= 300 && response.status < 400 && location) {
127
+ // The signed URL carries its own auth; the API key must not be sent to the storage host.
128
+ const file = await this.fetchImpl(new URL(location, this.baseUrl).toString());
129
+ if (!file.ok)
130
+ throw await toApiError(file);
131
+ return file;
132
+ }
133
+ if (!response.ok)
134
+ throw await toApiError(response);
135
+ return response;
136
+ }
137
+ async getUsage() {
138
+ return this.getJson("/v1/usage");
139
+ }
140
+ /** Needs the keys:read scope. */
141
+ async listApiKeys() {
142
+ return this.getJson("/v1/api-keys");
143
+ }
144
+ /** Needs the keys:write scope. The returned `key` is shown only once. */
145
+ async createApiKey(input) {
146
+ return this.postJson("/v1/api-keys", input);
147
+ }
148
+ /** Needs the billing:write scope. Open `checkoutUrl` to pay. */
149
+ async createCheckout(input) {
150
+ return this.postJson("/v1/billing/checkout", input);
151
+ }
152
+ async getJson(path) {
153
+ const response = await this.send(`${this.baseUrl}${path}`, {});
154
+ if (!response.ok)
155
+ throw await toApiError(response);
156
+ return (await response.json());
157
+ }
158
+ async postJson(path, body) {
159
+ const response = await this.send(`${this.baseUrl}${path}`, {
160
+ method: "POST",
161
+ headers: { "content-type": "application/json" },
162
+ body: JSON.stringify(body)
163
+ });
164
+ if (!response.ok)
165
+ throw await toApiError(response);
166
+ return (await response.json());
167
+ }
168
+ send(url, init) {
169
+ return this.fetchImpl(url, {
170
+ ...init,
171
+ headers: {
172
+ ...(this.apiKey ? { authorization: `Bearer ${this.apiKey}` } : {}),
173
+ ...this.headers,
174
+ ...init.headers
175
+ }
176
+ });
177
+ }
178
+ }
179
+ async function toApiError(response) {
180
+ return new Tube2VidApiError(response.status, await response.text().catch(() => ""));
181
+ }
182
+ function normalizeBaseUrl(baseUrl) {
183
+ return baseUrl.replace(/\/+$/, "");
184
+ }
185
+ function defaultBaseUrl() {
186
+ if (typeof window !== "undefined" && window.location?.origin) {
187
+ return window.location.origin;
188
+ }
189
+ return DEFAULT_BASE_URL;
190
+ }
191
+ // No @types/node here: the SDK also runs in browsers, where `process` does not exist.
192
+ function envApiKey() {
193
+ return globalThis.process?.env?.TUBE2VID_API_KEY;
194
+ }
195
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAoBA,MAAM,CAAC,MAAM,gBAAgB,GAAG,sBAAsB,CAAC;AAoBvD,2CAA2C;AAC3C,MAAM,OAAO,gBAAiB,SAAQ,KAAK;IAChC,MAAM,CAAS;IACxB,iCAAiC;IACxB,IAAI,CAAU;IACvB,mFAAmF;IAC1E,IAAI,CAAU;IACvB,8CAA8C;IACrC,IAAI,CAAW;IAExB,YAAY,MAAc,EAAE,IAAa;QACvC,IAAI,IAAa,CAAC;QAClB,IAAI,CAAC;YACH,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAC7C,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,GAAG,SAAS,CAAC;QACnB,CAAC;QACD,MAAM,MAAM,GAAG,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAwC,CAAC;QACrG,KAAK,CAAC,OAAO,MAAM,CAAC,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,oCAAoC,MAAM,EAAE,CAAC,CAAC;QAC9G,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,SAAS,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,OAAO,MAAM,CAAC,IAAI,KAAK,QAAQ,CA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client.js";
2
+ export * from "./types.js";
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC"}
@@ -0,0 +1,203 @@
1
+ export type JobMode = "auto" | "video" | "audio" | "gallery";
2
+ export type JobState = "queued" | "running" | "completed" | "failed";
3
+ export type PlatformStatusValue = "operational" | "degraded" | "partial_outage" | "down" | "beta";
4
+ export type ProofOfWork = {
5
+ nonce: string;
6
+ expiresAt: string;
7
+ difficulty: number;
8
+ signature: string;
9
+ /** Any string such that sha256(`${nonce}.${expiresAt}.${difficulty}.${solution}`) starts with `difficulty` hex zeros. */
10
+ solution: string;
11
+ };
12
+ export type JobSubmitInput = {
13
+ url: string;
14
+ /** Force a platform slug instead of detecting it from the URL. */
15
+ platform?: string;
16
+ mode?: JobMode;
17
+ format?: string;
18
+ quality?: string;
19
+ /** Browser-only human check; not needed with an API key. */
20
+ turnstileToken?: string;
21
+ /** Browser-only work challenge; not needed with an API key. */
22
+ pow?: ProofOfWork;
23
+ };
24
+ export type QueuedJobResponse = {
25
+ jobId: string;
26
+ /** "queued" for a new job; a deduplicated public submission returns the existing job's state. */
27
+ status: JobState;
28
+ platform: string;
29
+ estimatedCredits: number;
30
+ /** True when a public submission was folded into an identical job from the last minute. */
31
+ deduped?: boolean;
32
+ };
33
+ export type PlatformSummary = {
34
+ slug: string;
35
+ name: string;
36
+ category: string;
37
+ supportLevel: string;
38
+ publicClaim: boolean;
39
+ capabilities: string[];
40
+ providers: Array<{
41
+ id: string;
42
+ kind: string;
43
+ priority: number;
44
+ }>;
45
+ };
46
+ export type PlatformHealthRow = {
47
+ platform: string;
48
+ name: string;
49
+ category: string;
50
+ supportLevel: string;
51
+ status: PlatformStatusValue;
52
+ auditCategory: string;
53
+ provider?: string;
54
+ providerKind?: string;
55
+ successRate?: number;
56
+ medianExtractMs?: number;
57
+ lastCheckedAt?: string;
58
+ note?: string;
59
+ reason?: string;
60
+ authNeeded?: boolean;
61
+ repaired?: boolean;
62
+ };
63
+ export type JobEvent = {
64
+ id: string;
65
+ jobId: string;
66
+ stage: string;
67
+ message: string;
68
+ details?: Record<string, unknown> | null;
69
+ createdAt: string;
70
+ };
71
+ export type PublicJobStatus = {
72
+ jobId: string;
73
+ platform: string;
74
+ status: JobState;
75
+ progress: number;
76
+ provider?: string;
77
+ /** True when the file came from a reduced-quality last-resort provider. */
78
+ fallback?: boolean;
79
+ title?: string;
80
+ errorCode?: string;
81
+ errorMessage?: string;
82
+ completedAt?: string;
83
+ createdAt: string;
84
+ updatedAt: string;
85
+ latestEvent?: {
86
+ stage: string;
87
+ message?: string;
88
+ details?: Record<string, unknown> | null;
89
+ createdAt: string;
90
+ };
91
+ };
92
+ export type JobStatus = {
93
+ id: string;
94
+ jobId?: string;
95
+ userId?: string;
96
+ apiKeyId?: string;
97
+ url: string;
98
+ platform: string;
99
+ mode: JobMode;
100
+ format: string;
101
+ quality: string;
102
+ creditsReserved: number;
103
+ status: JobState;
104
+ progress: number;
105
+ creditsCharged: number;
106
+ provider?: string;
107
+ title?: string;
108
+ outputPath?: string;
109
+ outputStorageKey?: string;
110
+ outputSize?: number;
111
+ thumbnailUrl?: string;
112
+ errorCode?: string;
113
+ errorMessage?: string;
114
+ completedAt?: string;
115
+ createdAt: string;
116
+ updatedAt: string;
117
+ };
118
+ export type UsageSummary = {
119
+ creditBalance: number;
120
+ jobsTotal: number;
121
+ jobsCompleted: number;
122
+ jobsFailed: number;
123
+ };
124
+ export type StatusHistoryItem = {
125
+ id: string;
126
+ platform: string;
127
+ provider: string;
128
+ status: string;
129
+ durationMs?: number;
130
+ errorCode?: string;
131
+ errorMessage?: string;
132
+ createdAt: string;
133
+ };
134
+ export type OperationalMetrics = {
135
+ generatedAt: string;
136
+ queueDepth: number;
137
+ queuedJobs: number;
138
+ runningJobs: number;
139
+ completedJobs24h: number;
140
+ failedJobs24h: number;
141
+ p95JobDurationMs?: number;
142
+ providerFailureRates: Array<{
143
+ provider: string;
144
+ total: number;
145
+ failed: number;
146
+ failureRate: number;
147
+ }>;
148
+ alerts: Array<{
149
+ level: "info" | "warn" | "critical";
150
+ code: string;
151
+ message: string;
152
+ }>;
153
+ };
154
+ export type ServiceHealth = {
155
+ ok: boolean;
156
+ service: string;
157
+ time: string;
158
+ };
159
+ export type PowChallenge = {
160
+ nonce: string;
161
+ expiresAt: string;
162
+ difficulty: number;
163
+ signature: string;
164
+ };
165
+ export type ApiKeyScope = "jobs:write" | "jobs:read" | "usage:read" | "keys:read" | "keys:write" | "billing:write";
166
+ export type ApiKeyCreateInput = {
167
+ name: string;
168
+ /** Defaults to ["jobs:write", "jobs:read", "usage:read"]. */
169
+ scopes?: ApiKeyScope[];
170
+ /** 1-1000, defaults to 60. */
171
+ rateLimitPerMinute?: number;
172
+ };
173
+ export type CreatedApiKey = {
174
+ id: string;
175
+ name: string;
176
+ /** The plaintext key. It is only ever returned once. */
177
+ key: string;
178
+ prefix: string;
179
+ scopes: string[];
180
+ };
181
+ export type ApiKeySummary = {
182
+ id: string;
183
+ name: string;
184
+ prefix: string;
185
+ scopes: string[];
186
+ rateLimitPerMinute: number;
187
+ revokedAt?: string;
188
+ createdAt: string;
189
+ };
190
+ export type CheckoutInput = {
191
+ /** 1,000-250,000 credits. */
192
+ credits?: number;
193
+ /** Legacy fixed packs. */
194
+ pack?: "starter" | "builder" | "scale";
195
+ };
196
+ export type CheckoutSession = {
197
+ checkoutUrl: string | null;
198
+ mode: "stripe" | "placeholder";
199
+ sessionId?: string;
200
+ credits: number;
201
+ amountCents: number;
202
+ message?: string;
203
+ };
package/dist/types.js ADDED
@@ -0,0 +1,3 @@
1
+ // Response and request shapes of the public Tube2Vid API (/v1/*). Kept in sync with openapi/openapi.yaml.
2
+ export {};
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,0GAA0G"}
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@tube2vid/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.0",
4
+ "description": "Typed, zero-dependency TypeScript/JavaScript client for the Tube2Vid video downloader API: YouTube, TikTok, Instagram and 1,800+ sites.",
5
+ "license": "MIT",
6
+ "homepage": "https://tube2vid.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/Tube2Vid/sdk.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/Tube2Vid/sdk/issues"
13
+ },
14
+ "keywords": [
15
+ "tube2vid",
16
+ "youtube downloader",
17
+ "tiktok downloader",
18
+ "instagram downloader",
19
+ "video downloader api",
20
+ "youtube api",
21
+ "media download",
22
+ "yt-dlp alternative",
23
+ "api client",
24
+ "sdk",
25
+ "typescript",
26
+ "javascript"
27
+ ],
28
+ "type": "module",
29
+ "main": "dist/index.js",
30
+ "types": "dist/index.d.ts",
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "README.md",
40
+ "LICENSE"
41
+ ],
42
+ "engines": {
43
+ "node": ">=18.17"
44
+ },
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.json",
47
+ "typecheck": "tsc -p tsconfig.json --noEmit",
48
+ "test": "node --import tsx --test src/*.test.ts",
49
+ "prepublishOnly": "npm run build"
50
+ },
51
+ "devDependencies": {
52
+ "tsx": "^4.19.4",
53
+ "typescript": "^5.8.3"
54
+ },
55
+ "author": "Tube2Vid (https://tube2vid.com)",
56
+ "publishConfig": {
57
+ "access": "public",
58
+ "provenance": true
59
+ }
60
+ }