twitterviewer 0.0.0-stage → 0.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 +21 -0
- package/README.md +257 -2
- package/dist/cli/bin.d.ts +2 -0
- package/dist/cli/bin.js +33 -0
- package/dist/cli/cli.d.ts +21 -0
- package/dist/cli/cli.js +242 -0
- package/dist/cli/credentials.d.ts +16 -0
- package/dist/cli/credentials.js +44 -0
- package/dist/cli/errors.d.ts +21 -0
- package/dist/cli/errors.js +38 -0
- package/dist/cli/login.d.ts +24 -0
- package/dist/cli/login.js +78 -0
- package/dist/client.d.ts +62 -0
- package/dist/client.js +109 -0
- package/dist/errors.d.ts +27 -0
- package/dist/errors.js +39 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +3 -0
- package/dist/transport.d.ts +26 -0
- package/dist/transport.js +122 -0
- package/dist/types.d.ts +211 -0
- package/dist/types.js +5 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/package.json +44 -4
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export const EXIT = { ok: 0, error: 1, usage: 2, auth: 3 };
|
|
2
|
+
export class CliError extends Error {
|
|
3
|
+
exitCode;
|
|
4
|
+
info;
|
|
5
|
+
constructor(message, exitCode = EXIT.error, info = {}) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.exitCode = exitCode;
|
|
8
|
+
this.info = info;
|
|
9
|
+
this.name = 'CliError';
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function normalizeBaseUrl(raw) {
|
|
13
|
+
const url = raw.trim().replace(/\/+$/, '');
|
|
14
|
+
if (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol))
|
|
15
|
+
throw new CliError(`Invalid base URL: ${raw}`, EXIT.usage);
|
|
16
|
+
return url;
|
|
17
|
+
}
|
|
18
|
+
export const pricingUrl = (baseUrl) => `${baseUrl}/pricing`;
|
|
19
|
+
export const keysUrl = (baseUrl) => `${baseUrl}/account/api`;
|
|
20
|
+
/** SDK error to exit code and hint: 401 and 402 exit with 3 (sign-in, Plus or credits needed), everything else with 1. */
|
|
21
|
+
export function fromApiError(err, baseUrl) {
|
|
22
|
+
const { message, status, retryAfterSec } = err;
|
|
23
|
+
if (status === 401) {
|
|
24
|
+
return new CliError(message, EXIT.auth, { hint: `Run "twitterviewer login", or set TWITTERVIEWER_API_KEY. Keys: ${keysUrl(baseUrl)}` });
|
|
25
|
+
}
|
|
26
|
+
if (status === 402) {
|
|
27
|
+
const reason = err.details?.reason;
|
|
28
|
+
const hint = reason === 'PLUS_REQUIRED'
|
|
29
|
+
? `The CLI needs Plus. Subscribe: ${pricingUrl(baseUrl)}`
|
|
30
|
+
: reason === 'API_KEY_LIMIT'
|
|
31
|
+
? `Manage keys: ${keysUrl(baseUrl)}`
|
|
32
|
+
: `Get more credits: ${pricingUrl(baseUrl)}`;
|
|
33
|
+
return new CliError(message, EXIT.auth, { hint });
|
|
34
|
+
}
|
|
35
|
+
if (status === 429 && retryAfterSec)
|
|
36
|
+
return new CliError(`${message}. Try again in ${retryAfterSec}s.`, EXIT.error);
|
|
37
|
+
return new CliError(message, EXIT.error);
|
|
38
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const cliHeaders: (version: string) => Record<string, string>;
|
|
2
|
+
export interface LoginDeps {
|
|
3
|
+
fetch: typeof fetch;
|
|
4
|
+
stderr: {
|
|
5
|
+
write(chunk: string): unknown;
|
|
6
|
+
};
|
|
7
|
+
stdout: {
|
|
8
|
+
write(chunk: string | Uint8Array): unknown;
|
|
9
|
+
};
|
|
10
|
+
readStdin: () => Promise<string>;
|
|
11
|
+
sleep: (ms: number) => Promise<void>;
|
|
12
|
+
openBrowser: (url: string) => void;
|
|
13
|
+
hostname: () => string;
|
|
14
|
+
}
|
|
15
|
+
export interface LoginOptions {
|
|
16
|
+
baseUrl: string;
|
|
17
|
+
version: string;
|
|
18
|
+
noOpen: boolean;
|
|
19
|
+
key?: string;
|
|
20
|
+
keyStdin: boolean;
|
|
21
|
+
dir: string;
|
|
22
|
+
}
|
|
23
|
+
/** Sign in: --key / --key-stdin save an existing key; otherwise the device flow (approve in the browser, receive a key). The key is checked, then saved. */
|
|
24
|
+
export declare function login(opts: LoginOptions, deps: LoginDeps): Promise<void>;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { DEFAULT_TIMEOUT_MS, TwitterViewer } from '../client.js';
|
|
2
|
+
import { TwitterViewerError } from '../errors.js';
|
|
3
|
+
import { send } from '../transport.js';
|
|
4
|
+
import { KEY_PATTERN, writeCredentials } from './credentials.js';
|
|
5
|
+
import { CliError, EXIT } from './errors.js';
|
|
6
|
+
export const cliHeaders = (version) => ({
|
|
7
|
+
'x-twitterviewer-client': `cli/${version}`,
|
|
8
|
+
'user-agent': `twitterviewer-cli/${version}`,
|
|
9
|
+
});
|
|
10
|
+
/** Sign in: --key / --key-stdin save an existing key; otherwise the device flow (approve in the browser, receive a key). The key is checked, then saved. */
|
|
11
|
+
export async function login(opts, deps) {
|
|
12
|
+
let apiKey;
|
|
13
|
+
if (opts.key !== undefined || opts.keyStdin) {
|
|
14
|
+
apiKey = (opts.key ?? (await deps.readStdin())).trim();
|
|
15
|
+
if (!KEY_PATTERN.test(apiKey))
|
|
16
|
+
throw new CliError('That does not look like a TwitterViewer API key (tv_live_ followed by 32 letters or digits).', EXIT.usage);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
apiKey = await deviceFlow(opts, deps);
|
|
20
|
+
}
|
|
21
|
+
// Check before saving: an invalid key never reaches the disk
|
|
22
|
+
const client = new TwitterViewer({ apiKey, baseUrl: opts.baseUrl, fetch: deps.fetch, headers: cliHeaders(opts.version) });
|
|
23
|
+
const { total } = await client.credits();
|
|
24
|
+
writeCredentials(opts.dir, { apiKey, baseUrl: opts.baseUrl });
|
|
25
|
+
deps.stderr.write(`Logged in${total === undefined ? '' : `. ${total.toLocaleString('en-US')} credits available`}.\n`);
|
|
26
|
+
}
|
|
27
|
+
/** The device operations need no key and are not public SDK methods, so they use the transport directly. */
|
|
28
|
+
function devicePost(opts, deps, path, json) {
|
|
29
|
+
const config = { baseUrl: opts.baseUrl, apiKey: undefined, timeout: DEFAULT_TIMEOUT_MS, maxRetries: 0, headers: cliHeaders(opts.version), fetch: deps.fetch };
|
|
30
|
+
const request = { method: 'POST', path, json, accept: 'application/json', auth: false };
|
|
31
|
+
return send(config, request, async (res) => (await res.json()));
|
|
32
|
+
}
|
|
33
|
+
async function deviceFlow(opts, deps) {
|
|
34
|
+
const start = await devicePost(opts, deps, '/api/v1/cli/device', { client: deps.hostname(), version: opts.version });
|
|
35
|
+
deps.stderr.write(`\nOpen this link and confirm the code:\n\n ${start.verificationUriComplete}\n\n Code: ${start.userCode}\n\n`);
|
|
36
|
+
if (!opts.noOpen) {
|
|
37
|
+
try {
|
|
38
|
+
deps.openBrowser(start.verificationUriComplete);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// If the browser cannot be opened, the user opens the link by hand
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
deps.stderr.write('Waiting for approval...\n');
|
|
45
|
+
let waitMs = start.interval * 1000;
|
|
46
|
+
const deadline = Date.now() + start.expiresIn * 1000;
|
|
47
|
+
let networkFailures = 0;
|
|
48
|
+
while (Date.now() < deadline) {
|
|
49
|
+
await deps.sleep(waitMs);
|
|
50
|
+
try {
|
|
51
|
+
return (await devicePost(opts, deps, '/api/v1/cli/device/token', { deviceCode: start.deviceCode })).apiKey;
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
if (!(err instanceof TwitterViewerError))
|
|
55
|
+
throw err;
|
|
56
|
+
const { status, code, retryAfterSec } = err;
|
|
57
|
+
const reason = err.details?.reason;
|
|
58
|
+
if (reason === 'PENDING') {
|
|
59
|
+
waitMs = start.interval * 1000;
|
|
60
|
+
networkFailures = 0;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (reason === 'DENIED')
|
|
64
|
+
throw new CliError('The login request was denied in the browser.', EXIT.error);
|
|
65
|
+
if (reason === 'EXPIRED')
|
|
66
|
+
throw new CliError('The code expired before it was approved. Run "twitterviewer login" again.', EXIT.error);
|
|
67
|
+
if (status === 429) {
|
|
68
|
+
waitMs = Math.max(waitMs, (retryAfterSec ?? start.interval) * 1000);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
// Network trouble or 5xx: give up after 5 failures in a row
|
|
72
|
+
if ((code === 'NETWORK' || code === 'TIMEOUT' || (status ?? 0) >= 500) && ++networkFailures < 5)
|
|
73
|
+
continue;
|
|
74
|
+
throw err;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
throw new CliError('Timed out waiting for approval. Run "twitterviewer login" again.', EXIT.error);
|
|
78
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type CallOptions } from './transport.js';
|
|
2
|
+
import type { ConvertParams, ConvertPdfParams, ConvertResult, ConvertTextParams, CreditBalance, PdfDocument, RepliesParams, RepliesResult, SwapParams, TextDocument } from './types.js';
|
|
3
|
+
export declare const DEFAULT_BASE_URL = "https://twitterviewer.ai";
|
|
4
|
+
export declare const DEFAULT_MAX_RETRIES = 2;
|
|
5
|
+
/**
|
|
6
|
+
* Longer than the 60 seconds the server waits for an identical request that is still running (so its 503 `IN_PROGRESS` arrives),
|
|
7
|
+
* shorter than the 100 seconds after which the edge answers 524.
|
|
8
|
+
*/
|
|
9
|
+
export declare const DEFAULT_TIMEOUT_MS = 90000;
|
|
10
|
+
export interface TwitterViewerOptions {
|
|
11
|
+
/** Default: the `TWITTERVIEWER_API_KEY` environment variable */
|
|
12
|
+
apiKey?: string;
|
|
13
|
+
/** Default: `TWITTERVIEWER_BASE_URL`, then https://twitterviewer.ai */
|
|
14
|
+
baseUrl?: string;
|
|
15
|
+
/** Milliseconds per attempt. Default 90000 */
|
|
16
|
+
timeout?: number;
|
|
17
|
+
/** Retries after the first attempt. Default 2; 0 turns retries off */
|
|
18
|
+
maxRetries?: number;
|
|
19
|
+
/** Extra request headers */
|
|
20
|
+
headers?: Record<string, string>;
|
|
21
|
+
/** Custom fetch implementation */
|
|
22
|
+
fetch?: typeof fetch;
|
|
23
|
+
}
|
|
24
|
+
export declare class TwitterViewer {
|
|
25
|
+
#private;
|
|
26
|
+
readonly baseUrl: string;
|
|
27
|
+
constructor(options?: TwitterViewerOptions);
|
|
28
|
+
/** Convert a post, thread, Article or profile and get structured JSON (`POST /api/v1/convert`). */
|
|
29
|
+
convert(params: ConvertParams, options?: CallOptions): Promise<ConvertResult>;
|
|
30
|
+
/** Same as {@link convert}, sent as query parameters (`GET /api/v1/convert`). */
|
|
31
|
+
convertByQuery(params: ConvertParams, options?: CallOptions): Promise<ConvertResult>;
|
|
32
|
+
/** Convert and get the Markdown, Obsidian or plain text document itself. */
|
|
33
|
+
convertText(params: ConvertTextParams, options?: CallOptions): Promise<TextDocument>;
|
|
34
|
+
/** Convert to a PDF rendered on the server. */
|
|
35
|
+
convertPdf(params: ConvertPdfParams, options?: CallOptions): Promise<PdfDocument>;
|
|
36
|
+
/** Read the replies under a post (`GET /api/v1/replies`). */
|
|
37
|
+
replies(params: RepliesParams, options?: CallOptions): Promise<RepliesResult>;
|
|
38
|
+
/** Credit balance; costs no credits (`GET /api/v1/credits`). */
|
|
39
|
+
credits(options?: CallOptions): Promise<CreditBalance>;
|
|
40
|
+
/** A post or thread by handle and id (`GET /api/v1/swap/{handle}/status/{id}`). Markdown unless `format` says otherwise. */
|
|
41
|
+
swapPost(handle: string, id: string, params: SwapParams & {
|
|
42
|
+
format: 'json';
|
|
43
|
+
}, options?: CallOptions): Promise<ConvertResult>;
|
|
44
|
+
swapPost(handle: string, id: string, params: SwapParams & {
|
|
45
|
+
format: 'pdf';
|
|
46
|
+
}, options?: CallOptions): Promise<PdfDocument>;
|
|
47
|
+
swapPost(handle: string, id: string, params?: SwapParams & {
|
|
48
|
+
format?: 'markdown' | 'obsidian' | 'text';
|
|
49
|
+
}, options?: CallOptions): Promise<TextDocument>;
|
|
50
|
+
swapPost(handle: string, id: string, params?: SwapParams, options?: CallOptions): Promise<ConvertResult | PdfDocument | TextDocument>;
|
|
51
|
+
/** Recent posts of a profile by handle (`GET /api/v1/swap/{handle}`). Markdown unless `format` says otherwise. */
|
|
52
|
+
swapProfile(handle: string, params: SwapParams & {
|
|
53
|
+
format: 'json';
|
|
54
|
+
}, options?: CallOptions): Promise<ConvertResult>;
|
|
55
|
+
swapProfile(handle: string, params: SwapParams & {
|
|
56
|
+
format: 'pdf';
|
|
57
|
+
}, options?: CallOptions): Promise<PdfDocument>;
|
|
58
|
+
swapProfile(handle: string, params?: SwapParams & {
|
|
59
|
+
format?: 'markdown' | 'obsidian' | 'text';
|
|
60
|
+
}, options?: CallOptions): Promise<TextDocument>;
|
|
61
|
+
swapProfile(handle: string, params?: SwapParams, options?: CallOptions): Promise<ConvertResult | PdfDocument | TextDocument>;
|
|
62
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { TwitterViewerError } from './errors.js';
|
|
2
|
+
import { send } from './transport.js';
|
|
3
|
+
import { VERSION } from './version.js';
|
|
4
|
+
export const DEFAULT_BASE_URL = 'https://twitterviewer.ai';
|
|
5
|
+
export const DEFAULT_MAX_RETRIES = 2;
|
|
6
|
+
/**
|
|
7
|
+
* Longer than the 60 seconds the server waits for an identical request that is still running (so its 503 `IN_PROGRESS` arrives),
|
|
8
|
+
* shorter than the 100 seconds after which the edge answers 524.
|
|
9
|
+
*/
|
|
10
|
+
export const DEFAULT_TIMEOUT_MS = 90_000;
|
|
11
|
+
const env = (name) => (typeof process === 'undefined' ? undefined : process.env[name]?.trim() || undefined);
|
|
12
|
+
export class TwitterViewer {
|
|
13
|
+
baseUrl;
|
|
14
|
+
#config;
|
|
15
|
+
constructor(options = {}) {
|
|
16
|
+
this.baseUrl = (options.baseUrl ?? env('TWITTERVIEWER_BASE_URL') ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
17
|
+
this.#config = {
|
|
18
|
+
baseUrl: this.baseUrl,
|
|
19
|
+
apiKey: options.apiKey ?? env('TWITTERVIEWER_API_KEY'),
|
|
20
|
+
timeout: options.timeout ?? DEFAULT_TIMEOUT_MS,
|
|
21
|
+
maxRetries: options.maxRetries ?? DEFAULT_MAX_RETRIES,
|
|
22
|
+
headers: { 'user-agent': `twitterviewer-node/${VERSION}`, 'x-twitterviewer-client': `node/${VERSION}`, ...options.headers },
|
|
23
|
+
fetch: options.fetch ?? ((input, init) => fetch(input, init)),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
/** Convert a post, thread, Article or profile and get structured JSON (`POST /api/v1/convert`). */
|
|
27
|
+
convert(params, options) {
|
|
28
|
+
return this.#send({ method: 'POST', path: '/api/v1/convert', json: params, accept: 'application/json' }, (readJson), options);
|
|
29
|
+
}
|
|
30
|
+
/** Same as {@link convert}, sent as query parameters (`GET /api/v1/convert`). */
|
|
31
|
+
convertByQuery(params, options) {
|
|
32
|
+
return this.#send({ method: 'GET', path: '/api/v1/convert', query: params, accept: 'application/json' }, (readJson), options);
|
|
33
|
+
}
|
|
34
|
+
/** Convert and get the Markdown, Obsidian or plain text document itself. */
|
|
35
|
+
convertText(params, options) {
|
|
36
|
+
const json = { ...params, format: params.format ?? 'markdown' };
|
|
37
|
+
return this.#send({ method: 'POST', path: '/api/v1/convert', json, accept: 'text/markdown' }, readText, options);
|
|
38
|
+
}
|
|
39
|
+
/** Convert to a PDF rendered on the server. */
|
|
40
|
+
convertPdf(params, options) {
|
|
41
|
+
const json = { ...params, format: 'pdf' };
|
|
42
|
+
return this.#send({ method: 'POST', path: '/api/v1/convert', json, accept: 'application/pdf' }, readPdf, options);
|
|
43
|
+
}
|
|
44
|
+
/** Read the replies under a post (`GET /api/v1/replies`). */
|
|
45
|
+
replies(params, options) {
|
|
46
|
+
return this.#send({ method: 'GET', path: '/api/v1/replies', query: params, accept: 'application/json' }, (readJson), options);
|
|
47
|
+
}
|
|
48
|
+
/** Credit balance; costs no credits (`GET /api/v1/credits`). */
|
|
49
|
+
credits(options) {
|
|
50
|
+
return this.#send({ method: 'GET', path: '/api/v1/credits', accept: 'application/json' }, (readJson), options);
|
|
51
|
+
}
|
|
52
|
+
async swapPost(handle, id, params = {}, options) {
|
|
53
|
+
if (!/^\d{1,25}$/.test(id))
|
|
54
|
+
throw new TwitterViewerError('INVALID_INPUT', `Invalid post id "${id}"`);
|
|
55
|
+
return this.#swap(`${handlePath(handle)}/status/${id}`, params, options);
|
|
56
|
+
}
|
|
57
|
+
async swapProfile(handle, params = {}, options) {
|
|
58
|
+
return this.#swap(handlePath(handle), params, options);
|
|
59
|
+
}
|
|
60
|
+
#swap(path, params, options) {
|
|
61
|
+
const format = params.format ?? 'markdown';
|
|
62
|
+
const accept = format === 'pdf' ? 'application/pdf' : format === 'json' ? 'application/json' : 'text/markdown';
|
|
63
|
+
const read = format === 'pdf' ? readPdf : format === 'json' ? readJson : readText;
|
|
64
|
+
return this.#send({ method: 'GET', path: `/api/v1/swap/${path}`, query: params, accept }, read, options);
|
|
65
|
+
}
|
|
66
|
+
#send(request, read, options) {
|
|
67
|
+
return send(this.#config, { ...request, auth: true }, read, options);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** The handle is part of the path, so it is validated before it is used. */
|
|
71
|
+
function handlePath(handle) {
|
|
72
|
+
const name = handle.replace(/^@/, '');
|
|
73
|
+
if (!/^[A-Za-z0-9_]{1,15}$/.test(name))
|
|
74
|
+
throw new TwitterViewerError('INVALID_INPUT', `Invalid X handle "${handle}"`);
|
|
75
|
+
return name;
|
|
76
|
+
}
|
|
77
|
+
async function readJson(res) {
|
|
78
|
+
return (await res.json());
|
|
79
|
+
}
|
|
80
|
+
function headerNumber(res, name) {
|
|
81
|
+
const value = res.headers.get(name);
|
|
82
|
+
return value === null || Number.isNaN(Number(value)) ? null : Number(value);
|
|
83
|
+
}
|
|
84
|
+
function meta(res) {
|
|
85
|
+
return {
|
|
86
|
+
creditsCharged: headerNumber(res, 'x-credits-charged'),
|
|
87
|
+
creditsRemaining: headerNumber(res, 'x-credits-remaining'),
|
|
88
|
+
rateLimitRemaining: headerNumber(res, 'x-ratelimit-remaining'),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
async function readText(res) {
|
|
92
|
+
return { ...meta(res), content: await res.text(), postsReturned: headerNumber(res, 'x-posts-returned') };
|
|
93
|
+
}
|
|
94
|
+
async function readPdf(res) {
|
|
95
|
+
return { ...meta(res), data: new Uint8Array(await res.arrayBuffer()), filename: dispositionFilename(res.headers.get('content-disposition')) };
|
|
96
|
+
}
|
|
97
|
+
/** `filename*=UTF-8''…` (RFC 5987) carries the title in its own script; `filename="…"` is the ASCII fallback. */
|
|
98
|
+
function dispositionFilename(header) {
|
|
99
|
+
const encoded = /filename\*\s*=\s*UTF-8''([^;\s]+)/i.exec(header ?? '')?.[1];
|
|
100
|
+
if (encoded) {
|
|
101
|
+
try {
|
|
102
|
+
return decodeURIComponent(encoded);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Malformed percent-encoding: use the fallback name
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return /filename\s*=\s*"([^"]+)"/i.exec(header ?? '')?.[1] ?? null;
|
|
109
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Error codes defined by the API (the ErrorCode schema of openapi.json). */
|
|
2
|
+
export declare const API_ERROR_CODES: readonly ["INVALID_INPUT", "UNAUTHORIZED", "FORBIDDEN", "NOT_FOUND", "PROTECTED", "SUSPENDED", "CONFLICT", "LIMIT_REACHED", "RATE_LIMITED", "UPSTREAM", "UNSUPPORTED", "INTERNAL", "TURNSTILE_FAILED", "HUMAN_CHECK_REQUIRED", "INVALID_OR_EXPIRED_TOKEN", "EMAIL_SEND_FAILED", "EMAIL_NOT_CONFIGURED", "EMAIL_BLOCKED", "SERVICE_UNAVAILABLE"];
|
|
3
|
+
export type ApiErrorCode = (typeof API_ERROR_CODES)[number];
|
|
4
|
+
/**
|
|
5
|
+
* Codes produced by this library:
|
|
6
|
+
* `NETWORK` the request or response failed in transit, `TIMEOUT` no complete response in time,
|
|
7
|
+
* `HTTP_ERROR` an error status without an API error body (for example from a gateway),
|
|
8
|
+
* `INVALID_RESPONSE` a successful status with a body that could not be read.
|
|
9
|
+
*/
|
|
10
|
+
export type ClientErrorCode = 'NETWORK' | 'TIMEOUT' | 'HTTP_ERROR' | 'INVALID_RESPONSE';
|
|
11
|
+
export type ErrorCode = ApiErrorCode | ClientErrorCode;
|
|
12
|
+
export interface TwitterViewerErrorOptions {
|
|
13
|
+
status?: number;
|
|
14
|
+
retryAfterSec?: number;
|
|
15
|
+
details?: Record<string, unknown>;
|
|
16
|
+
cause?: unknown;
|
|
17
|
+
}
|
|
18
|
+
export declare class TwitterViewerError extends Error {
|
|
19
|
+
readonly code: ErrorCode;
|
|
20
|
+
/** HTTP status; undefined when no response was received */
|
|
21
|
+
readonly status: number | undefined;
|
|
22
|
+
/** Seconds the server asks to wait */
|
|
23
|
+
readonly retryAfterSec: number | undefined;
|
|
24
|
+
/** Extra data, for example `details.reason` on `LIMIT_REACHED` */
|
|
25
|
+
readonly details: Record<string, unknown> | undefined;
|
|
26
|
+
constructor(code: ErrorCode, message: string, options?: TwitterViewerErrorOptions);
|
|
27
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Error codes defined by the API (the ErrorCode schema of openapi.json). */
|
|
2
|
+
export const API_ERROR_CODES = [
|
|
3
|
+
'INVALID_INPUT',
|
|
4
|
+
'UNAUTHORIZED',
|
|
5
|
+
'FORBIDDEN',
|
|
6
|
+
'NOT_FOUND',
|
|
7
|
+
'PROTECTED',
|
|
8
|
+
'SUSPENDED',
|
|
9
|
+
'CONFLICT',
|
|
10
|
+
'LIMIT_REACHED',
|
|
11
|
+
'RATE_LIMITED',
|
|
12
|
+
'UPSTREAM',
|
|
13
|
+
'UNSUPPORTED',
|
|
14
|
+
'INTERNAL',
|
|
15
|
+
'TURNSTILE_FAILED',
|
|
16
|
+
'HUMAN_CHECK_REQUIRED',
|
|
17
|
+
'INVALID_OR_EXPIRED_TOKEN',
|
|
18
|
+
'EMAIL_SEND_FAILED',
|
|
19
|
+
'EMAIL_NOT_CONFIGURED',
|
|
20
|
+
'EMAIL_BLOCKED',
|
|
21
|
+
'SERVICE_UNAVAILABLE',
|
|
22
|
+
];
|
|
23
|
+
export class TwitterViewerError extends Error {
|
|
24
|
+
code;
|
|
25
|
+
/** HTTP status; undefined when no response was received */
|
|
26
|
+
status;
|
|
27
|
+
/** Seconds the server asks to wait */
|
|
28
|
+
retryAfterSec;
|
|
29
|
+
/** Extra data, for example `details.reason` on `LIMIT_REACHED` */
|
|
30
|
+
details;
|
|
31
|
+
constructor(code, message, options = {}) {
|
|
32
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
33
|
+
this.name = 'TwitterViewerError';
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.status = options.status;
|
|
36
|
+
this.retryAfterSec = options.retryAfterSec;
|
|
37
|
+
this.details = options.details;
|
|
38
|
+
}
|
|
39
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, TwitterViewer, type TwitterViewerOptions } from './client.js';
|
|
2
|
+
export { API_ERROR_CODES, TwitterViewerError, type ApiErrorCode, type ClientErrorCode, type ErrorCode, type TwitterViewerErrorOptions } from './errors.js';
|
|
3
|
+
export type { CallOptions } from './transport.js';
|
|
4
|
+
export type * from './types.js';
|
|
5
|
+
export { VERSION } from './version.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** HTTP layer shared by the SDK and the CLI: headers, timeout, retries and error parsing. */
|
|
2
|
+
/** A longer wait than this is reported to the caller instead of slept through. */
|
|
3
|
+
export declare const MAX_RETRY_AFTER_SEC = 120;
|
|
4
|
+
export interface TransportConfig {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
apiKey: string | undefined;
|
|
7
|
+
/** Milliseconds per attempt */
|
|
8
|
+
timeout: number;
|
|
9
|
+
maxRetries: number;
|
|
10
|
+
headers: Record<string, string>;
|
|
11
|
+
fetch: typeof fetch;
|
|
12
|
+
}
|
|
13
|
+
export interface TransportRequest {
|
|
14
|
+
method: 'GET' | 'POST';
|
|
15
|
+
path: string;
|
|
16
|
+
query?: object;
|
|
17
|
+
json?: unknown;
|
|
18
|
+
accept: string;
|
|
19
|
+
auth: boolean;
|
|
20
|
+
}
|
|
21
|
+
export interface CallOptions {
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
/** Milliseconds, for this call only */
|
|
24
|
+
timeout?: number;
|
|
25
|
+
}
|
|
26
|
+
export declare function send<T>(config: TransportConfig, request: TransportRequest, read: (res: Response) => Promise<T>, options?: CallOptions): Promise<T>;
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { TwitterViewerError } from './errors.js';
|
|
2
|
+
/** HTTP layer shared by the SDK and the CLI: headers, timeout, retries and error parsing. */
|
|
3
|
+
/** A longer wait than this is reported to the caller instead of slept through. */
|
|
4
|
+
export const MAX_RETRY_AFTER_SEC = 120;
|
|
5
|
+
const BACKOFF_BASE_MS = 500;
|
|
6
|
+
const BACKOFF_MAX_MS = 8_000;
|
|
7
|
+
export async function send(config, request, read, options = {}) {
|
|
8
|
+
if (request.auth && !config.apiKey) {
|
|
9
|
+
throw new TwitterViewerError('UNAUTHORIZED', 'No API key. Pass apiKey or set TWITTERVIEWER_API_KEY.');
|
|
10
|
+
}
|
|
11
|
+
for (let attempt = 0;; attempt++) {
|
|
12
|
+
options.signal?.throwIfAborted();
|
|
13
|
+
try {
|
|
14
|
+
return await once(config, request, read, options);
|
|
15
|
+
}
|
|
16
|
+
catch (err) {
|
|
17
|
+
if (!(err instanceof TwitterViewerError) || attempt >= config.maxRetries)
|
|
18
|
+
throw err;
|
|
19
|
+
const delay = retryDelay(err, attempt);
|
|
20
|
+
if (delay === null)
|
|
21
|
+
throw err;
|
|
22
|
+
await sleep(delay, options.signal);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
async function once(config, request, read, options) {
|
|
27
|
+
const headers = { ...config.headers, accept: request.accept };
|
|
28
|
+
if (request.auth)
|
|
29
|
+
headers.authorization = `Bearer ${config.apiKey}`;
|
|
30
|
+
if (request.json !== undefined)
|
|
31
|
+
headers['content-type'] = 'application/json';
|
|
32
|
+
const controller = new AbortController();
|
|
33
|
+
let timedOut = false;
|
|
34
|
+
const timer = setTimeout(() => {
|
|
35
|
+
timedOut = true;
|
|
36
|
+
controller.abort();
|
|
37
|
+
}, options.timeout ?? config.timeout);
|
|
38
|
+
const onAbort = () => controller.abort(options.signal?.reason);
|
|
39
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
40
|
+
let status;
|
|
41
|
+
try {
|
|
42
|
+
const res = await config.fetch(`${config.baseUrl}${request.path}${queryString(request.query)}`, {
|
|
43
|
+
method: request.method,
|
|
44
|
+
headers,
|
|
45
|
+
body: request.json === undefined ? undefined : JSON.stringify(request.json),
|
|
46
|
+
signal: controller.signal,
|
|
47
|
+
});
|
|
48
|
+
status = res.status;
|
|
49
|
+
if (!res.ok)
|
|
50
|
+
throw await errorFrom(res);
|
|
51
|
+
return await read(res);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
if (options.signal?.aborted)
|
|
55
|
+
throw options.signal.reason;
|
|
56
|
+
if (timedOut)
|
|
57
|
+
throw new TwitterViewerError('TIMEOUT', `Request to ${config.baseUrl} timed out`, { status, cause: err });
|
|
58
|
+
if (err instanceof TwitterViewerError)
|
|
59
|
+
throw err;
|
|
60
|
+
if (err instanceof SyntaxError)
|
|
61
|
+
throw new TwitterViewerError('INVALID_RESPONSE', `Invalid response from ${config.baseUrl}`, { status, cause: err });
|
|
62
|
+
throw new TwitterViewerError('NETWORK', `Could not reach ${config.baseUrl}: ${describe(err)}`, { status, cause: err });
|
|
63
|
+
}
|
|
64
|
+
finally {
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function queryString(query) {
|
|
70
|
+
const params = new URLSearchParams();
|
|
71
|
+
for (const [key, value] of Object.entries(query ?? {})) {
|
|
72
|
+
if (value !== undefined)
|
|
73
|
+
params.set(key, String(value));
|
|
74
|
+
}
|
|
75
|
+
const text = params.toString();
|
|
76
|
+
return text ? `?${text}` : '';
|
|
77
|
+
}
|
|
78
|
+
async function errorFrom(res) {
|
|
79
|
+
const body = (await res.json().catch(() => null));
|
|
80
|
+
const error = body?.error;
|
|
81
|
+
const retryAfterSec = typeof error?.retryAfterSec === 'number' ? error.retryAfterSec : Number(res.headers.get('retry-after')) || undefined;
|
|
82
|
+
const code = typeof error?.code === 'string' ? error.code : 'HTTP_ERROR';
|
|
83
|
+
const message = typeof error?.message === 'string' ? error.message : `HTTP ${res.status}`;
|
|
84
|
+
return new TwitterViewerError(code, message, { status: res.status, retryAfterSec, details: error?.details });
|
|
85
|
+
}
|
|
86
|
+
function causeOf(err) {
|
|
87
|
+
return err instanceof Error ? err.cause : undefined;
|
|
88
|
+
}
|
|
89
|
+
function describe(err) {
|
|
90
|
+
const cause = causeOf(err);
|
|
91
|
+
return cause?.message || cause?.code || (err instanceof Error ? err.message : String(err));
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Milliseconds to wait before the next attempt, or null when the request is not repeated.
|
|
95
|
+
* Repeating is safe: within 10 minutes the server answers an identical request with the first result and does not charge again.
|
|
96
|
+
*/
|
|
97
|
+
function retryDelay({ code, status = 0, retryAfterSec }, attempt) {
|
|
98
|
+
// 501 UNSUPPORTED: the server caches that answer for 300 seconds
|
|
99
|
+
if (status === 501 || (status >= 400 && status < 500 && status !== 429))
|
|
100
|
+
return null;
|
|
101
|
+
if (code !== 'NETWORK' && code !== 'TIMEOUT' && status !== 429 && status < 500)
|
|
102
|
+
return null;
|
|
103
|
+
if (retryAfterSec !== undefined)
|
|
104
|
+
return retryAfterSec <= MAX_RETRY_AFTER_SEC ? retryAfterSec * 1000 : null;
|
|
105
|
+
const ceiling = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
106
|
+
return ceiling / 2 + Math.random() * (ceiling / 2);
|
|
107
|
+
}
|
|
108
|
+
function sleep(ms, signal) {
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
if (signal?.aborted)
|
|
111
|
+
return reject(signal.reason);
|
|
112
|
+
const onAbort = () => {
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
reject(signal?.reason);
|
|
115
|
+
};
|
|
116
|
+
const timer = setTimeout(() => {
|
|
117
|
+
signal?.removeEventListener('abort', onAbort);
|
|
118
|
+
resolve();
|
|
119
|
+
}, ms);
|
|
120
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
121
|
+
});
|
|
122
|
+
}
|