diff --git a/README.md b/README.md index caaa819..093914c 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ filters into two: | `full_content` | `content` | | `removeduplicate`, `excludefield` | `remove_duplicate`, `exclude_field` | -`coin` and `market_id` keep their names. v2 also accepts `raw_query` on every +`coin` and `market_id` keep their names. v2 also accepts `rawQuery` on every endpoint, `sources` included. v2 responses carry `total_results` and `next_page` where v1 carries @@ -153,7 +153,8 @@ await client.latestApi({ rawQuery: 'q=bitcoin&country=us&language=en' }); ``` `rawQuery` is mutually exclusive with all other parameters and is validated -against the endpoint's allowed keys. +against the endpoint's allowed keys; for the v1 count endpoints it must also +carry `from_date` and `to_date`. ## Real-time news (WebSocket) @@ -200,7 +201,8 @@ for await (const response of ws.stream(registrationId)) { ``` Break out of the loop to stop; the connection closes either way. `ws.close()` -ends an in-flight stream from outside the loop. +ends an in-flight stream from outside the loop — at once, even while it is +waiting to reconnect. Transient drops (network errors, server restarts, abnormal closes) are reconnected automatically with a capped exponential backoff. Pass @@ -209,12 +211,17 @@ rejection — bad API key or unknown `registration_id`, exhausted API credits, or too many simultaneous devices — throws `NewsdataWebSocketAuthError` and is **not** retried. -The server always accepts the handshake and then closes with code **1008** when -the connection is refused, carrying one of three reasons: `invalid credentials -or registration not found`, `api limit reached`, or `device limit reached` (more -than 5 devices on one `registration_id`). Every other close code — including -`1013` (`send timeout`, meaning the client read too slowly) — is transient and -reconnects. +When it refuses a connection, the server accepts the handshake, sends one error +response — `{"status":"error","results":{"message":"…","code":"…"}}` — and +closes. The stream never yields that response: it becomes the thrown error, +whose `message` is the server's explanation, `code` its error code and +`responseBody` the whole response. Close code **1008** is permanent; its reason +is the bare code: `Unauthorized` or `InvalidRequest` (bad key or unknown +`registration_id`), `ApiLimitExceeded` or `ApiKeyLimitExceeded` (credits used +up), `DeviceLimitExceeded` (more than 5 devices on one `registration_id`). +Every other close code — `1011` (server error) and `1013` (the client read too +slowly) included — is transient and reconnects; with `reconnect: false` it +throws `NewsdataWebSocketError` carrying the server's message. **Each delivered article consumes 1 API credit per connected device.** @@ -231,7 +238,7 @@ try { // ... } } catch (err) { - if (err instanceof NewsdataWebSocketAuthError) console.error('rejected:', err.message); + if (err instanceof NewsdataWebSocketAuthError) console.error(`rejected (${err.code}):`, err.message); else if (err instanceof NewsdataWebSocketError) console.error('stream error:', err.message); else throw err; } @@ -254,16 +261,18 @@ const ws = new NewsDataApiWebSocket(client, { > v22. On older runtimes pass your own implementation, e.g. > `new NewsDataApiWebSocket(client, { WebSocket: require('ws') })`. > -> Node's global `WebSocket` does not expose the handshake HTTP status. When a -> connection fails before it opens, the client probes the same URL over HTTP to -> tell a permanent rejection (401 / 403) from a transient failure. +> Node's global `WebSocket` does not expose the handshake HTTP status, so a +> handshake that fails before the connection opens — a proxy answering 401 or +> 403, say — shows up as close code 1006 and is retried as a transient failure. Runnable example: [`examples/websocket.js`](examples/websocket.js). ## Client-side validation -Before any request is sent, parameters are validated and normalized. A -`NewsdataValidationError` is thrown (without spending API quota) when: +Before any request is sent, parameters are validated and normalized. The +returned promise rejects with a `NewsdataValidationError` (without spending API +quota; with `paginate: true` the first iteration throws it — a client method +never throws synchronously) when: - a parameter is not accepted by that endpoint; - mutually-exclusive parameters are set together — `q`/`qInTitle`/`qInMeta`, @@ -339,9 +348,12 @@ const client = new NewsDataApiClient(apiKey, { 0.3.0 it included the version (`https://newsdata.io/api/1/`), so drop the trailing `/1/` if you override it. -Retries cover network errors, HTTP 429, and 5xx. 429 honors the `Retry-After` -header (integer seconds or HTTP-date); otherwise backoff is exponential. Auth -and other 4xx errors are never retried. +Retries cover network errors, HTTP 429, and 5xx. `timeout` covers the whole +request, reading the response body included. A 429 waits for its `Retry-After` +(integer seconds or HTTP-date) plus one second; without the header, backoff is +exponential. When `Retry-After` is longer than `retryBackoffMax`, the call +rejects at once with `NewsdataRateLimitError` and `retryAfter` set (seconds), +leaving the wait to you. Auth and other 4xx errors are never retried. A 429 that waiting cannot fix is never retried. `NewsdataApiLimitExceededError` means the account's whole credit pool is diff --git a/examples/websocket.js b/examples/websocket.js index a34dc9d..cb8da5d 100644 --- a/examples/websocket.js +++ b/examples/websocket.js @@ -64,8 +64,10 @@ try { } } } catch (err) { + // A refusal is never yielded as news: the server's explanation arrives + // here, with its code (Unauthorized, ApiLimitExceeded, DeviceLimitExceeded, …). if (err instanceof NewsdataWebSocketAuthError) { - console.error(`rejected: ${err.message}`); + console.error(`rejected (${err.code}): ${err.message}`); process.exit(1); } throw err; diff --git a/package.json b/package.json index f5aff4b..24a4f55 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "newsdata-nodejs-client", - "version": "0.3.0", + "version": "0.4.0", "description": "Official Node.js client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, pagination, and typed errors.", "type": "module", "main": "src/index.js", diff --git a/src/client.js b/src/client.js index 1fdf0fe..fb39cae 100644 --- a/src/client.js +++ b/src/client.js @@ -91,10 +91,12 @@ export class NewsDataApiClient { * @param {string} apiKey * @param {object} [options] * @param {string} [options.baseUrl] - * @param {number} [options.timeout] Per-request timeout (ms). + * @param {number} [options.timeout] Per-request timeout (ms), body read included. * @param {number} [options.maxRetries] Total attempts (1 = no retry). * @param {number} [options.retryBackoff] Base backoff (ms). - * @param {number} [options.retryBackoffMax] Cap on a single backoff (ms). + * @param {number} [options.retryBackoffMax] Cap on a single backoff (ms). A 429 whose + * Retry-After is longer rejects at once with NewsdataRateLimitError (retryAfter set); + * a shorter one is waited out, plus one second. * @param {number} [options.paginationDelay] Delay between pages (ms). * @param {number} [options.maxResult] Default cap for scroll mode. * @param {number} [options.maxPages] Default cap for paginate mode. @@ -153,7 +155,7 @@ export class NewsDataApiClient { * Single-page endpoint; scroll / paginate are not supported. * @returns {Promise} */ - sourcesApi(params = {}) { + async sourcesApi(params = {}) { const { rawQuery = null, ...rest } = params; const validated = validateParams('sources', rest, rawQuery); return this.#request('sources', validated); @@ -190,7 +192,7 @@ export class NewsDataApiClient { * Single-page endpoint; scroll / paginate are not supported. * @returns {Promise} */ - sources(params = {}) { + async sources(params = {}) { const { rawQuery = null, ...rest } = params; const validated = validateParams('sources_v2', rest, rawQuery); return this.#request('sources_v2', validated); @@ -213,7 +215,7 @@ export class NewsDataApiClient { * `err.responseBody.results.registration_id`. * @returns {Promise} */ - websocketRegister(params = {}) { + async websocketRegister(params = {}) { const { rawQuery = null, ...rest } = params; const validated = validateParams('websocket_register', rest, rawQuery); validated.news_type = WS_NEWS_TYPE; @@ -237,7 +239,7 @@ export class NewsDataApiClient { * @param {string} registrationId * @returns {Promise} */ - websocketDelete(registrationId) { + async websocketDelete(registrationId) { if (typeof registrationId !== 'string' || registrationId === '') { throw new NewsdataValidationError( 'registrationId must be a non-empty string', @@ -252,11 +254,6 @@ export class NewsDataApiClient { return this.#apiKey; } - /** The configured fetch, reused by the WebSocket handshake probe. @internal */ - get fetchForWebSocket() { - return this.#fetch; - } - /** Forward a log line from the WebSocket layer. @internal */ logForWebSocket(level, message) { this.#log(level, message); @@ -269,6 +266,10 @@ export class NewsDataApiClient { * Returns a Promise for single & scroll modes, or an async generator when * `paginate: true`. `v2` selects the v2 response keys (`total_results` / * `next_page`) for the multi-page modes. + * + * Validation errors are reported the way the call's result is consumed: a + * rejected promise, or (paginate) the generator's first `next()` — never a + * synchronous throw before the caller holds anything to attach a handler to. */ #dispatch(endpoint, params, isCount = false, v2 = false) { const { @@ -280,10 +281,15 @@ export class NewsDataApiClient { ...rest } = params; - if (scroll && paginate) { - throw new NewsdataValidationError('scroll and paginate are mutually exclusive'); + let validated; + try { + if (scroll && paginate) { + throw new NewsdataValidationError('scroll and paginate are mutually exclusive'); + } + validated = validateParams(endpoint, rest, rawQuery); + } catch (err) { + return paginate ? failOnFirstNext(err) : Promise.reject(err); } - const validated = validateParams(endpoint, rest, rawQuery); if (paginate) { return this.#paginate(endpoint, validated, maxPages ?? this.#maxPages, isCount, v2); @@ -324,14 +330,28 @@ export class NewsDataApiClient { this.#log('info', `${method} ${logUrl} (attempt ${attempt}/${this.#maxRetries})`); let res; + let text; const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), this.#timeout); + // The timeout covers the whole exchange, body included. Racing it (on + // top of aborting) bounds the body read even when a fetch + // implementation ignores the abort signal while the body streams in. + let timer; + const timedOut = new Promise((_, reject) => { + timer = setTimeout(() => { + reject(new Error(`request timed out after ${this.#timeout}ms`)); + controller.abort(); + }, this.#timeout); + }); try { - res = await this.#fetch(fullUrl, { - method, - headers: { Accept: 'application/json' }, - signal: controller.signal, - }); + res = await Promise.race([ + this.#fetch(fullUrl, { + method, + headers: { Accept: 'application/json' }, + signal: controller.signal, + }), + timedOut, + ]); + text = await Promise.race([res.text(), timedOut]); } catch (err) { if (attempt >= this.#maxRetries) { throw new NewsdataNetworkError( @@ -347,7 +367,6 @@ export class NewsDataApiClient { } const status = res.status; - const text = await res.text(); let body; try { body = text === '' ? null : JSON.parse(text); @@ -376,15 +395,19 @@ export class NewsDataApiClient { // A 429 covers a burst limit, a rate limit, and exhausted API // credits. Only the first two are worth retrying. const QuotaError = quotaExhaustedError(body); - if (QuotaError !== null || attempt >= this.#maxRetries) { + // A wait longer than retryBackoffMax is left to the caller. + const waitTooLong = retryAfter !== null && retryAfter > this.#retryBackoffMax; + if (QuotaError !== null || attempt >= this.#maxRetries || waitTooLong) { const ErrorClass = QuotaError ?? NewsdataRateLimitError; throw new ErrorClass( this.#errorMessage(body, status), 429, asObject(body), retryAfter === null ? null : Math.round(retryAfter / 1000), ); } - const wait = retryAfter ?? this.#backoff(attempt); - this.#log('warn', `429 rate limit; sleeping ${wait}ms`); + // Retry-After is in whole seconds: one second more keeps the retry + // from arriving just before the limit resets. + const wait = retryAfter !== null ? retryAfter + 1000 : this.#backoff(attempt); + this.#log('warn', `429 rate limit (attempt ${attempt}/${this.#maxRetries}); sleeping ${wait}ms`); await sleep(wait); continue; } @@ -499,3 +522,9 @@ export class NewsDataApiClient { function asObject(body) { return body && typeof body === 'object' && !Array.isArray(body) ? body : null; } + +/** An async generator whose first `next()` rejects with `err` (paginate mode). */ +// eslint-disable-next-line require-yield +async function* failOnFirstNext(err) { + throw err; +} diff --git a/src/constants.js b/src/constants.js index 5a3f308..8a20fd2 100644 --- a/src/constants.js +++ b/src/constants.js @@ -3,8 +3,7 @@ // // Parameter names are lowercase here; user-supplied keys are lowercased before // validation (the API is case-insensitive, so `qInTitle` and `qintitle` are -// equivalent). The sets mirror the server-side filter mapping and the official -// Python/PHP clients. +// equivalent). The sets mirror the server-side filter mapping. export const BASE_URL = 'https://newsdata.io/api'; @@ -222,15 +221,14 @@ export const FILTERS = Object.freeze({ ], // Real-time query registration. The real-time service is v2 only, so these // are the v2 filter names. No date or paging filters apply -- a registered - // query matches news as it is published. `news_type` is set by - // websocketRegister, not by the caller. + // query matches news as it is published. `news_type` is not accepted from + // the caller: websocketRegister sets it after validation. websocket_register: [ 'q', 'q_in_title', 'q_in_meta', 'country', 'exclude_country', 'category', 'exclude_category', 'language', 'exclude_language', 'source_url', 'exclude_source_url', 'source_priority', 'timezone', 'content', 'image', 'video', 'remove_duplicate', 'tag', 'sentiment', 'sentiment_score', 'region', 'organization', 'creator', 'datatype', 'exclude_field', - 'news_type', ], websocket_fetch: [], websocket_delete: ['registration_id'], diff --git a/src/errors.js b/src/errors.js index e553632..bc9489b 100644 --- a/src/errors.js +++ b/src/errors.js @@ -100,11 +100,18 @@ export class NewsdataWebSocketError extends NewsdataError { /** * @param {string} message * @param {Error|null} [cause] The underlying error. + * @param {object} [details] + * @param {object|null} [details.responseBody] The error response the server + * sent before closing ({status:"error", results:{message, code}}), if any. + * @param {string|null} [details.code] The server's error code, e.g. + * "Unauthorized" or "ServerError". */ - constructor(message, cause = null) { + constructor(message, cause = null, { responseBody = null, code = null } = {}) { super(message); this.name = 'NewsdataWebSocketError'; if (cause) this.cause = cause; + this.responseBody = responseBody; + this.code = code; } } @@ -114,8 +121,8 @@ export class NewsdataWebSocketError extends NewsdataError { * exhausted quota. Never retried, regardless of the `reconnect` setting. */ export class NewsdataWebSocketAuthError extends NewsdataWebSocketError { - constructor(message, cause = null) { - super(message, cause); + constructor(message, cause = null, details = {}) { + super(message, cause, details); this.name = 'NewsdataWebSocketAuthError'; } } diff --git a/src/validator.js b/src/validator.js index d542f46..7c1c86a 100644 --- a/src/validator.js +++ b/src/validator.js @@ -1,5 +1,4 @@ -// Client-side parameter validation and normalization, mirroring the official -// Python/PHP clients: +// Client-side parameter validation and normalization, before a request is sent: // - keys are lowercased (the API is case-insensitive); // - null/undefined values are dropped; // - arrays are comma-joined; booleans become '1' / '0'; @@ -52,21 +51,13 @@ export function validateParams(endpoint, params = {}, rawQuery = null) { 'rawQuery', ); } - return parseRawQuery(rawQuery, allowed); - } - - // Count endpoints require an explicit date range. - if (REQUIRES_DATE_RANGE.includes(endpoint)) { - for (const required of ['from_date', 'to_date']) { - if (lowered[required] === undefined || lowered[required] === '') { - throw new NewsdataValidationError( - `${required} is required for the ${endpoint} endpoint`, - required, - ); - } - } + const values = parseRawQuery(rawQuery, allowed); + requireDateRange(endpoint, values); + return values; } + requireDateRange(endpoint, lowered); + checkMutex(lowered); if (lowered.sentiment_score !== undefined && lowered.sentiment === undefined) { @@ -89,6 +80,22 @@ export function validateParams(endpoint, params = {}, rawQuery = null) { return validated; } +/** + * Count endpoints require an explicit date range, whether the dates are + * passed as parameters or inside rawQuery. + */ +function requireDateRange(endpoint, values) { + if (!REQUIRES_DATE_RANGE.includes(endpoint)) return; + for (const required of ['from_date', 'to_date']) { + if (values[required] === undefined || values[required] === '') { + throw new NewsdataValidationError( + `${required} is required for the ${endpoint} endpoint`, + required, + ); + } + } +} + function checkMutex(params) { for (const group of MUTEX_GROUPS) { const set = group.filter((name) => params[name] !== undefined); diff --git a/src/websocket.js b/src/websocket.js index 483a2f7..7490b66 100644 --- a/src/websocket.js +++ b/src/websocket.js @@ -19,8 +19,6 @@ import { } from './errors.js'; import { redactApiKey } from './client.js'; -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - /** * NewsData.io real-time WebSocket service. * @@ -41,10 +39,11 @@ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); * Transient drops are reconnected automatically with a capped exponential * backoff; pass `reconnect: false` to stop on the first disconnect. A * permanent rejection throws `NewsdataWebSocketAuthError` and is never - * retried. + * retried. The error response the server sends with a refusal is never + * yielded: it becomes the thrown error's message, `code` and `responseBody`. * * Break out of the loop (or call `close()`) to stop; the connection is closed - * either way. + * either way, and `close()` also cuts short a pending reconnect wait. */ export class NewsDataApiWebSocket { #client; @@ -65,6 +64,9 @@ export class NewsDataApiWebSocket { #closed = false; + /** Ends the pending reconnect wait early; set while one is running. */ + #wake = null; + /** * @param {import('./client.js').NewsDataApiClient} client * Supplies the API key and performs the management HTTP calls. Not closed @@ -150,26 +152,41 @@ export class NewsDataApiWebSocket { try { while (!this.#closed) { - const session = this.#connect(url, logUrl); + // The error response the server sends right before it closes a + // refused connection. Never yielded: raised with that close instead. + let errorResponse = null; + let refusedDelay = delay; + const session = this.#connect(url, logUrl, () => { + // reset after a successful connect, unless the server refuses it + refusedDelay = delay; + delay = this.#reconnectDelay; + }); try { for await (const message of session) { - delay = this.#reconnectDelay; // reset after a successful connect let response; try { response = JSON.parse(message); } catch { continue; // skip malformed frames } - if (response && typeof response === 'object' && !Array.isArray(response)) { - yield response; + if (!response || typeof response !== 'object' || Array.isArray(response)) { + continue; } + if (response.status === 'error') { + // sent right before the server closes the connection: raise it + // with that close, and keep backing off + errorResponse = response; + delay = refusedDelay; + continue; + } + yield response; } } catch (err) { if (this.#closed) return; - const permanent = this.#permanentAuthError(err); + const permanent = this.#permanentAuthError(err, errorResponse); if (permanent) throw permanent; - if (!this.#reconnect) throw toTransientError(err); + if (!this.#reconnect) throw toTransientError(err, errorResponse); this.#client.logForWebSocket( 'warn', `connection to ${logUrl} failed (${err.message}); reconnecting in ${delay}ms`, @@ -179,7 +196,7 @@ export class NewsDataApiWebSocket { if (this.#closed) return; // A clean close with reconnect disabled ends the stream. if (!this.#reconnect) return; - await sleep(delay); + await this.#wait(delay); delay = this.#nextDelay(delay); } } finally { @@ -187,11 +204,25 @@ export class NewsDataApiWebSocket { } } + /** Sleep `ms` before a reconnect; `close()` ends the wait at once. */ + #wait(ms) { + return new Promise((resolve) => { + const wake = () => { + clearTimeout(timer); + if (this.#wake === wake) this.#wake = null; + resolve(); + }; + const timer = setTimeout(wake, ms); + this.#wake = wake; + }); + } + /** * Bridge one WebSocket connection's events into an async iterable of raw - * message payloads. Throws a `WsClosed` when the socket drops. + * message payloads. Throws a `WsClosed` when the socket drops. `onOpen` + * runs when the handshake completes. */ - #connect(url, logUrl) { + #connect(url, logUrl, onOpen) { const socket = new this.#WebSocketImpl(url); this.#socket = socket; @@ -227,6 +258,7 @@ export class NewsDataApiWebSocket { socket.addEventListener('open', () => { if (openTimer) clearTimeout(openTimer); this.#client.logForWebSocket('info', `connected to ${logUrl}`); + onOpen(); }); socket.addEventListener('message', (event) => { @@ -247,7 +279,7 @@ export class NewsDataApiWebSocket { if (code === 1000) { done = true; // normal closure } else { - failure = new WsClosed(reason || `connection closed (${code})`, code, true); + failure = new WsClosed(reason || `connection closed (${code})`, code, true, reason); } settle(); }); @@ -277,26 +309,39 @@ export class NewsDataApiWebSocket { /** * Decide whether a failure is a permanent rejection. * - * The server always accepts the handshake and then closes with code 1008 - * on a permanent failure — bad apikey or unknown registration_id - * ("invalid credentials or registration not found"), exhausted credits - * ("api limit reached"), or too many simultaneous devices for the same - * registration_id ("device limit reached"). Every other close code, - * including 1013 ("send timeout", the client read too slowly), is - * transient and reconnects. + * On a refusal the server accepts the handshake, sends one error response + * ({"status":"error","results":{"message":...,"code":...}}) and closes. + * Close 1008 is permanent: bad apikey or unknown registration_id + * (Unauthorized, InvalidRequest), exhausted credits (ApiLimitExceeded, + * ApiKeyLimitExceeded), or too many devices on one registration_id + * (DeviceLimitExceeded); the close reason is that bare code. Every other + * close code — 1011 (server error), 1013 (the client read too slowly) — is + * transient and reconnects. A handshake that fails before the socket opens + * (e.g. a proxy answering 401 / 403) surfaces as close 1006: Node's global + * WebSocket does not expose the HTTP status, so it is retried as transient. * + * @param {Error} err + * @param {object|null} errorResponse The error response received before the close. * @returns {NewsdataWebSocketAuthError|null} */ - #permanentAuthError(err) { + #permanentAuthError(err, errorResponse) { if (err instanceof WsClosed && err.code === WS_POLICY_VIOLATION) { - return new NewsdataWebSocketAuthError(err.message || 'connection rejected', err); + return new NewsdataWebSocketAuthError( + frameMessage(errorResponse) ?? (err.reason || 'connection rejected'), + err, + { responseBody: errorResponse, code: frameCode(errorResponse) ?? (err.reason || null) }, + ); } return null; } - /** Close the active connection, ending any in-flight `stream()`. */ + /** + * Close the active connection, ending any in-flight `stream()` — at once, + * even while it waits to reconnect. + */ close() { this.#closed = true; + if (this.#wake) this.#wake(); if (this.#socket) { try { this.#socket.close(); } catch { /* already closing */ } this.#socket = null; @@ -304,18 +349,44 @@ export class NewsDataApiWebSocket { } } -/** Internal marker for a dropped connection, carrying the close code. */ +/** Internal marker for a dropped connection, carrying the close code and reason. */ class WsClosed extends Error { - constructor(message, code, wasOpen) { + constructor(message, code, wasOpen, reason = '') { super(message); this.name = 'WsClosed'; this.code = code; this.wasOpen = wasOpen; + this.reason = reason; } } -/** Wrap a transient failure, used only when reconnect is disabled. */ -function toTransientError(err) { +/** The human-readable message in a server error response, if any. */ +function frameMessage(errorResponse) { + const results = errorResponse?.results; + if (typeof results === 'string' && results !== '') return results; + const message = results && typeof results === 'object' ? results.message : undefined; + return typeof message === 'string' && message !== '' ? message : null; +} + +/** The error code in a server error response (e.g. "Unauthorized"), if any. */ +function frameCode(errorResponse) { + const results = errorResponse?.results; + const code = results && typeof results === 'object' ? results.code : undefined; + return typeof code === 'string' && code !== '' ? code : null; +} + +/** + * Wrap a transient failure, used only when reconnect is disabled. An error + * response received before the close supplies the message. + */ +function toTransientError(err, errorResponse = null) { + if (errorResponse !== null) { + return new NewsdataWebSocketError( + frameMessage(errorResponse) ?? 'connection closed', + err, + { responseBody: errorResponse, code: frameCode(errorResponse) }, + ); + } if (err instanceof WsClosed) { return new NewsdataWebSocketError(err.code === null ? err.message : 'connection closed', err); } diff --git a/test/client.test.js b/test/client.test.js index 69c1e53..ab7b49b 100644 --- a/test/client.test.js +++ b/test/client.test.js @@ -1,7 +1,12 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { NewsDataApiClient, redactApiKey } from '../src/client.js'; -import { NewsdataAuthError, NewsdataRateLimitError } from '../src/errors.js'; +import { + NewsdataAuthError, + NewsdataNetworkError, + NewsdataRateLimitError, + NewsdataValidationError, +} from '../src/errors.js'; function mockResponse(status, body, headers = {}) { return { @@ -168,3 +173,114 @@ test('429 without a quota code still retries', async () => { assert.equal(res.results[0].title, 'recovered'); assert.equal(fetchStub.calls.length, 2); }); + +/** Settle `promise`, or reject after `ms` so a hang fails the test instead of stalling it. */ +function within(ms, promise) { + let timer; + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`still pending after ${ms}ms`)), ms); + }); + return Promise.race([promise, deadline]).finally(() => clearTimeout(timer)); +} + +// ---- 429 Retry-After -------------------------------------------------------- + +test('429 with a Retry-After longer than retryBackoffMax rejects at once', async () => { + const fetchStub = stubFetch([ + mockResponse( + 429, + { status: 'error', results: { message: 'slow down', code: 'RateLimitExceeded' } }, + { 'retry-after': '615' }, + ), + mockResponse(200, ok([{ title: 'too late' }])), + ]); + // Default retryBackoffMax: 60 s. + const client = new NewsDataApiClient('key', { fetch: fetchStub }); + + const started = Date.now(); + await assert.rejects(within(2_000, client.latestApi({ q: 'x' })), (err) => { + assert.ok(err instanceof NewsdataRateLimitError, `got ${err.name}: ${err.message}`); + assert.equal(err.retryAfter, 615); + return true; + }); + assert.equal(fetchStub.calls.length, 1, 'the 615 s wait is left to the caller'); + assert.ok(Date.now() - started < 1_000); +}); + +test('429 with Retry-After 0 waits one second before retrying', async () => { + const fetchStub = stubFetch([ + mockResponse(429, { status: 'error' }, { 'retry-after': '0' }), + mockResponse(200, ok([{ title: 'recovered' }])), + ]); + const client = new NewsDataApiClient('key', { fetch: fetchStub }); + + const started = Date.now(); + const res = await client.latestApi({ q: 'x' }); + const waited = Date.now() - started; + assert.equal(res.results[0].title, 'recovered'); + assert.equal(fetchStub.calls.length, 2); + assert.ok(waited >= 990, `retried after ${waited}ms; Retry-After + 1 s expected`); +}); + +// ---- the timeout covers the response body --------------------------------- + +test('a response body that never arrives times out as a network error', async () => { + const fetchStub = stubFetch([ + { status: 200, headers: new Headers(), text: () => new Promise(() => {}) }, + ]); + const client = new NewsDataApiClient('key', { fetch: fetchStub, timeout: 50, maxRetries: 1 }); + + await assert.rejects(within(2_000, client.latestApi({ q: 'x' })), (err) => { + assert.ok(err instanceof NewsdataNetworkError, `got ${err.name}: ${err.message}`); + return true; + }); +}); + +test('a failed body read is retried, then reported as a network error', async () => { + const broken = () => ({ + status: 200, + headers: new Headers(), + text: async () => { throw new TypeError('terminated'); }, + }); + const fetchStub = stubFetch([broken, broken]); + const client = new NewsDataApiClient('key', { fetch: fetchStub, maxRetries: 2, retryBackoff: 1 }); + + await assert.rejects(client.latestApi({ q: 'x' }), (err) => { + assert.ok(err instanceof NewsdataNetworkError, `got ${err.name}: ${err.message}`); + assert.match(err.message, /terminated/); + return true; + }); + assert.equal(fetchStub.calls.length, 2, 'the failed body read should be retried'); +}); + +// ---- validation errors reject; they are never thrown synchronously -------- + +test('validation errors reject the returned promise instead of throwing', async () => { + const fetchStub = stubFetch([]); + const client = new NewsDataApiClient('key', { fetch: fetchStub }); + const calls = { + 'news size=abc': () => client.news({ size: 'abc' }), + 'latestApi mutex': () => client.latestApi({ q: 'a', qInTitle: 'b' }), + 'countApi without dates': () => client.countApi({ q: 'x' }), + 'scroll mode': () => client.news({ size: 'abc', scroll: true }), + 'sources unknown param': () => client.sources({ bogus: 'x' }), + 'sourcesApi unknown param': () => client.sourcesApi({ bogus: 'x' }), + 'websocketRegister date filter': () => client.websocketRegister({ from_date: '2026-01-01' }), + 'websocketDelete empty id': () => client.websocketDelete(''), + }; + for (const [name, call] of Object.entries(calls)) { + let promise; + assert.doesNotThrow(() => { promise = call(); }, `${name} threw synchronously`); + await assert.rejects(promise, NewsdataValidationError, name); + } + assert.equal(fetchStub.calls.length, 0, 'nothing may be sent'); +}); + +test('in paginate mode a validation error is thrown by the first next()', async () => { + const client = new NewsDataApiClient('key', { fetch: stubFetch([]) }); + for (const params of [{ size: 'abc', paginate: true }, { scroll: true, paginate: true }]) { + let pages; + assert.doesNotThrow(() => { pages = client.news(params); }); + await assert.rejects(pages.next(), NewsdataValidationError); + } +}); diff --git a/test/v2.test.js b/test/v2.test.js index 79295fa..6bb1085 100644 --- a/test/v2.test.js +++ b/test/v2.test.js @@ -92,7 +92,7 @@ test('v2 accepts the snake_case vocabulary', async () => { assert.match(url, /exclude_field=description/); }); -test('v2 rejects the v1 spellings it replaced', () => { +test('v2 rejects the v1 spellings it replaced', async () => { const client = new NewsDataApiClient('key', { fetch: stubFetch([]) }); for (const params of [ { qInTitle: 'x' }, @@ -102,8 +102,8 @@ test('v2 rejects the v1 spellings it replaced', () => { { full_content: true }, { removeduplicate: true }, ]) { - assert.throws( - () => client.news(params), + await assert.rejects( + client.news(params), NewsdataValidationError, `${Object.keys(params)[0]} should not be a v2 filter`, ); @@ -117,18 +117,18 @@ test('v1 still accepts the v1 spellings', async () => { assert.match(fetchStub.calls[0], /qintitle=x/); }); -test('source_url and exclude_source_url are mutually exclusive', () => { +test('source_url and exclude_source_url are mutually exclusive', async () => { const client = new NewsDataApiClient('key', { fetch: stubFetch([]) }); - assert.throws( - () => client.news({ source_url: 'a.com', exclude_source_url: 'b.com' }), + await assert.rejects( + client.news({ source_url: 'a.com', exclude_source_url: 'b.com' }), NewsdataValidationError, ); }); -test('v2 q / q_in_title / q_in_meta are mutually exclusive', () => { +test('v2 q / q_in_title / q_in_meta are mutually exclusive', async () => { const client = new NewsDataApiClient('key', { fetch: stubFetch([]) }); - assert.throws( - () => client.news({ q: 'a', q_in_title: 'b' }), + await assert.rejects( + client.news({ q: 'a', q_in_title: 'b' }), NewsdataValidationError, ); }); @@ -190,8 +190,8 @@ test('rawQuery on a v2 method is checked against the v2 keyset', async () => { await client.news({ rawQuery: 'q_in_title=tesla&source_url=bbc.com' }); assert.match(fetchStub.calls[0], /q_in_title=tesla/); - assert.throws( - () => client.news({ rawQuery: 'qInTitle=tesla' }), + await assert.rejects( + client.news({ rawQuery: 'qInTitle=tesla' }), NewsdataValidationError, ); }); @@ -274,18 +274,18 @@ test('excludedomainurl is accepted on the v1 endpoints that take it', async () = } }); -test('excludedomainurl joins the v1 domain mutex group', () => { +test('excludedomainurl joins the v1 domain mutex group', async () => { const client = new NewsDataApiClient('key', { fetch: stubFetch([]) }); - assert.throws( - () => client.latestApi({ domain: 'a.com', excludedomainurl: 'b.com' }), + await assert.rejects( + client.latestApi({ domain: 'a.com', excludedomainurl: 'b.com' }), NewsdataValidationError, ); }); -test('excludedomainurl is not a sources filter', () => { +test('excludedomainurl is not a sources filter', async () => { const client = new NewsDataApiClient('key', { fetch: stubFetch([]) }); - assert.throws( - () => client.sourcesApi({ excludedomainurl: 'bbc.com' }), + await assert.rejects( + client.sourcesApi({ excludedomainurl: 'bbc.com' }), NewsdataValidationError, ); }); diff --git a/test/validator.test.js b/test/validator.test.js index d40da0f..e5d3c6c 100644 --- a/test/validator.test.js +++ b/test/validator.test.js @@ -65,6 +65,24 @@ test('count with dates is accepted', () => { ); }); +test('a count rawQuery must carry both dates', () => { + assert.throws( + () => validateParams('count', {}, 'q=x&from_date=2024-01-01'), + (err) => err instanceof NewsdataValidationError && err.param === 'to_date', + ); + assert.throws( + () => validateParams('crypto_count', {}, 'coin=btc'), + (err) => err instanceof NewsdataValidationError && err.param === 'from_date', + ); +}); + +test('a count rawQuery with both dates is accepted', () => { + assert.deepEqual( + validateParams('market_count', {}, 'q=x&from_date=2024-01-01&to_date=2024-01-02'), + { q: 'x', from_date: '2024-01-01', to_date: '2024-01-02' }, + ); +}); + test('rawQuery is parsed and validated', () => { assert.deepEqual( validateParams('latest', {}, 'q=foo&country=us'), diff --git a/test/websocket.test.js b/test/websocket.test.js index 1efef8d..36fb450 100644 --- a/test/websocket.test.js +++ b/test/websocket.test.js @@ -150,13 +150,9 @@ test('close code 1008 raises a permanent auth error and does not reconnect', asy assert.equal(connections, 1, 'a permanent rejection must not retry'); }); -// The server always accepts the handshake, then closes with 1008 carrying the -// reason. These are the three documented permanent rejections. -for (const reason of [ - 'invalid credentials or registration not found', - 'api limit reached', - 'device limit reached', -]) { +// The server always accepts the handshake, then closes with 1008 on a +// permanent rejection; the close reason is the bare error code. +for (const reason of ['Unauthorized', 'ApiLimitExceeded', 'DeviceLimitExceeded']) { test(`close 1008 "${reason}" is permanent`, async () => { const FakeWebSocket = fakeWebSocketFactory((socket) => { socket.open(); @@ -172,12 +168,166 @@ for (const reason of [ (err) => { assert.ok(err instanceof NewsdataWebSocketAuthError, `got ${err.name}`); assert.match(err.message, new RegExp(reason)); + assert.equal(err.code, reason, 'without an error frame the code is the close reason'); return true; }, ); }); } +// ---- refusals: the server's error frame ------------------------------------ +// On a refusal the server accepts the handshake, sends ONE error frame and +// closes. The frame is never yielded; it is raised with the close. + +const refusal = (code, message) => ({ status: 'error', results: { message, code } }); + +test('a refused stream yields nothing and raises the server message on close 1008', async () => { + const frame = refusal('Unauthorized', 'Your API key is invalid or the registration was not found.'); + let connections = 0; + const FakeWebSocket = fakeWebSocketFactory((socket, n) => { + connections = n; + socket.open(); + socket.message(frame); + socket.drop(1008, 'Unauthorized'); + }); + const ws = new NewsDataApiWebSocket(wsClient(), { WebSocket: FakeWebSocket }); + + const yielded = []; + await assert.rejects( + async () => { + for await (const response of ws.stream('reg-1')) yielded.push(response); + }, + (err) => { + assert.ok(err instanceof NewsdataWebSocketAuthError, `got ${err.name}`); + assert.equal(err.message, frame.results.message); + assert.equal(err.code, 'Unauthorized'); + assert.deepEqual(err.responseBody, frame); + return true; + }, + ); + assert.deepEqual(yielded, [], 'the error frame must not be handed over as news'); + assert.equal(connections, 1, 'a permanent rejection must not retry'); +}); + +test('an error frame then close 1011 with reconnect off raises a stream error carrying the frame', async () => { + const frame = refusal('ServerError', 'Something went wrong on our side.'); + const FakeWebSocket = fakeWebSocketFactory((socket) => { + socket.open(); + socket.message(frame); + socket.drop(1011, 'ServerError'); + }); + const ws = new NewsDataApiWebSocket(wsClient(), { WebSocket: FakeWebSocket, reconnect: false }); + + const yielded = []; + await assert.rejects( + async () => { + for await (const response of ws.stream('reg-1')) yielded.push(response); + }, + (err) => { + assert.ok(err instanceof NewsdataWebSocketError, `got ${err.name}`); + assert.ok(!(err instanceof NewsdataWebSocketAuthError), '1011 is transient, not an auth error'); + assert.equal(err.message, frame.results.message); + assert.equal(err.code, 'ServerError'); + assert.deepEqual(err.responseBody, frame); + return true; + }, + ); + assert.deepEqual(yielded, []); +}); + +test('an error frame then a normal close ends the stream quietly when reconnect is off', async () => { + // A clean close is not an error, even after an error frame. + const FakeWebSocket = fakeWebSocketFactory((socket) => { + socket.open(); + socket.message(refusal('ServerError', 'closing')); + socket.close(); + }); + const ws = new NewsDataApiWebSocket(wsClient(), { WebSocket: FakeWebSocket, reconnect: false }); + + const yielded = []; + for await (const response of ws.stream('reg-1')) yielded.push(response); + assert.deepEqual(yielded, []); +}); + +test('the reconnect delay resets on connect but keeps growing while the server refuses', async () => { + const delays = []; + const client = new NewsDataApiClient('key', { + fetch: stubFetch([]), + logger: { + warn: (message) => { + const match = /reconnecting in (\d+)ms/.exec(message); + if (match) delays.push(Number(match[1])); + }, + }, + }); + const serverError = refusal('ServerError', 'temporarily unavailable'); + const FakeWebSocket = fakeWebSocketFactory((socket, n) => { + if (n <= 2) { // the handshake fails: never opens + socket.drop(1006); + return; + } + if (n === 3) { // a healthy connection that later drops + socket.open(); + socket.drop(1006); + return; + } + if (n <= 6) { // accept, refuse, close 1011 + socket.open(); + socket.message(serverError); + socket.drop(1011, 'ServerError'); + return; + } + socket.open(); + socket.message(article('a1', 'finally')); + }); + const ws = new NewsDataApiWebSocket(client, { + WebSocket: FakeWebSocket, + reconnectDelay: 10, + reconnectDelayMax: 1_000, + }); + + for await (const response of ws.stream('reg-1')) { + if (response.status === 'success') break; + } + // 10, 20: handshake failures double. 10: a connect resets it. 20, 40, 80: + // connections the server refuses restore the pre-connect delay and double. + assert.deepEqual(delays, [10, 20, 10, 20, 40, 80]); +}); + +const activeTimers = () => process.getActiveResourcesInfo().filter((t) => t === 'Timeout').length; + +/** Settle `promise`, or reject after `ms` so a hang fails the test instead of stalling it. */ +function within(ms, promise) { + let timer; + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`still pending after ${ms}ms`)), ms); + }); + return Promise.race([promise, deadline]).finally(() => clearTimeout(timer)); +} + +test('close() ends a stream that is waiting to reconnect, and clears its timer', async () => { + const FakeWebSocket = fakeWebSocketFactory((socket) => { + socket.open(); + socket.drop(1011, 'ServerError'); + }); + const ws = new NewsDataApiWebSocket(wsClient(), { + WebSocket: FakeWebSocket, + reconnectDelay: 5_000, + }); + const timersBefore = activeTimers(); + + const stream = ws.stream('reg-1'); + const pending = stream.next(); + await new Promise((resolve) => { setTimeout(resolve, 20); }); // dropped; now waiting 5 s + + const started = Date.now(); + ws.close(); + const result = await within(1_000, pending); + assert.equal(result.done, true); + assert.ok(Date.now() - started < 200, `took ${Date.now() - started}ms to stop`); + assert.ok(activeTimers() <= timersBefore, 'the reconnect timer must not be left running'); +}); + // 1013 ("send timeout" — the client read too slowly) is transient. test('close 1013 is transient and reconnects', async () => { const FakeWebSocket = fakeWebSocketFactory((socket, n) => { @@ -326,8 +476,8 @@ test('websocketDelete uses DELETE and carries registration_id', async () => { assert.match(fetchStub.calls[0].url, /registration_id=reg-9/); }); -test('websocketDelete rejects an empty id', () => { - assert.throws(() => wsClient().websocketDelete(''), NewsdataValidationError); +test('websocketDelete rejects an empty id', async () => { + await assert.rejects(wsClient().websocketDelete(''), NewsdataValidationError); }); test('a resultless success envelope still succeeds on the websocket endpoints', async () => { @@ -387,7 +537,7 @@ test('websocketRegister accepts the v2 filter names', async () => { assert.match(url, /exclude_field=description/); }); -test('websocketRegister rejects the v1 filter names', () => { +test('websocketRegister rejects the v1 filter names', async () => { const retired = [ { qInTitle: 'x' }, { qInMeta: 'x' }, { excludecountry: 'us' }, { excludecategory: 'tech' }, { excludelanguage: 'en' }, { domain: 'bbc' }, @@ -398,36 +548,61 @@ test('websocketRegister rejects the v1 filter names', () => { ]; for (const params of retired) { const name = Object.keys(params)[0]; - assert.throws( - () => wsClient().websocketRegister(params), + await assert.rejects( + wsClient().websocketRegister(params), NewsdataValidationError, `${name} is no longer a register filter`, ); } }); -test('websocketRegister rejects a v1 name passed through rawQuery', () => { - assert.throws( - () => wsClient().websocketRegister({ rawQuery: 'qInTitle=pizza' }), +test('websocketRegister rejects a v1 name passed through rawQuery', async () => { + await assert.rejects( + wsClient().websocketRegister({ rawQuery: 'qInTitle=pizza' }), NewsdataValidationError, ); }); -test('websocketRegister keeps the v2 source_url mutex group', () => { - assert.throws( - () => wsClient().websocketRegister({ +test('websocketRegister keeps the v2 source_url mutex group', async () => { + await assert.rejects( + wsClient().websocketRegister({ source_url: 'a.com', exclude_source_url: 'b.com', }), NewsdataValidationError, ); }); -test('websocketRegister rejects the date and paging filters', () => { +test('websocketRegister rejects the date and paging filters', async () => { for (const params of [{ from_date: '2026-01-01' }, { page: 'p2' }, { sort: 'relevance' }]) { - assert.throws( - () => wsClient().websocketRegister(params), + await assert.rejects( + wsClient().websocketRegister(params), NewsdataValidationError, `${Object.keys(params)[0]} does not apply to a standing query`, ); } }); + +test('websocketRegister rejects news_type: the client sets it', async () => { + const fetchStub = stubFetch([]); + await assert.rejects( + wsClient(fetchStub).websocketRegister({ q: 'x', news_type: 'market' }), + NewsdataValidationError, + ); + await assert.rejects( + wsClient(fetchStub).websocketRegister({ rawQuery: 'q=x&news_type=market' }), + NewsdataValidationError, + ); + assert.equal(fetchStub.calls.length, 0, 'nothing may be sent'); +}); + +test('websocketRegister with rawQuery sends its parameters plus news_type=news', async () => { + const fetchStub = stubFetch([ + mockResponse(200, { status: 'success', results: { registration_id: 'reg-1' } }), + ]); + await wsClient(fetchStub).websocketRegister({ rawQuery: 'q=bitcoin&language=en' }); + const { url, method } = fetchStub.calls[0]; + assert.equal(method, 'POST'); + assert.match(url, /q=bitcoin/); + assert.match(url, /language=en/); + assert.match(url, /news_type=news/); +}); diff --git a/types/index.d.ts b/types/index.d.ts index df50908..a5d7217 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -36,9 +36,15 @@ export interface NewsdataResponse { export interface ClientOptions { /** API root without a version segment; default https://newsdata.io/api */ baseUrl?: string; + /** Per-request timeout in ms, reading the response body included. */ timeout?: number; maxRetries?: number; retryBackoff?: number; + /** + * Cap on a single backoff, in ms (default 60 000). A 429 whose Retry-After + * is longer rejects at once with `NewsdataRateLimitError` (`retryAfter` + * set); a shorter one is waited out, plus one second. + */ retryBackoffMax?: number; paginationDelay?: number; maxResult?: number; @@ -52,23 +58,42 @@ export interface ClientOptions { }; } +/** `paginate: true`: the call returns an async generator, one response per page. */ +type PaginateParams = EndpointParams & { paginate: true }; +/** A single request or `scroll: true`: the call returns a promise. */ +type SingleParams = EndpointParams & { paginate?: false }; +type PageGenerator = AsyncGenerator; +/** When `paginate` is only known at runtime. */ +type EndpointResult = Promise | PageGenerator; + /** * Endpoint methods return a `Promise` for single and * `scroll: true` calls, and an `AsyncGenerator` when - * `paginate: true`. + * `paginate: true`. Validation errors reject the promise (or are thrown by + * the generator's first `next()`); they are never thrown synchronously. */ -type EndpointResult = - | Promise - | AsyncGenerator; - export class NewsDataApiClient { constructor(apiKey: string, options?: ClientOptions); + latestApi(params: PaginateParams): PageGenerator; + latestApi(params?: SingleParams): Promise; latestApi(params?: EndpointParams): EndpointResult; + archiveApi(params: PaginateParams): PageGenerator; + archiveApi(params?: SingleParams): Promise; archiveApi(params?: EndpointParams): EndpointResult; + cryptoApi(params: PaginateParams): PageGenerator; + cryptoApi(params?: SingleParams): Promise; cryptoApi(params?: EndpointParams): EndpointResult; + marketApi(params: PaginateParams): PageGenerator; + marketApi(params?: SingleParams): Promise; marketApi(params?: EndpointParams): EndpointResult; + countApi(params: PaginateParams): PageGenerator; + countApi(params?: SingleParams): Promise; countApi(params?: EndpointParams): EndpointResult; + cryptoCountApi(params: PaginateParams): PageGenerator; + cryptoCountApi(params?: SingleParams): Promise; cryptoCountApi(params?: EndpointParams): EndpointResult; + marketCountApi(params: PaginateParams): PageGenerator; + marketCountApi(params?: SingleParams): Promise; marketCountApi(params?: EndpointParams): EndpointResult; sourcesApi(params?: EndpointParams): Promise; @@ -77,11 +102,23 @@ export class NewsDataApiClient { * `exclude_country`, `source_priority`, `content`, `remove_duplicate`, …) * and `source_url` / `exclude_source_url` replace the four domain filters. */ + news(params: PaginateParams): PageGenerator; + news(params?: SingleParams): Promise; news(params?: EndpointParams): EndpointResult; + market(params: PaginateParams): PageGenerator; + market(params?: SingleParams): Promise; market(params?: EndpointParams): EndpointResult; + crypto(params: PaginateParams): PageGenerator; + crypto(params?: SingleParams): Promise; crypto(params?: EndpointParams): EndpointResult; + countNews(params: PaginateParams): PageGenerator; + countNews(params?: SingleParams): Promise; countNews(params?: EndpointParams): EndpointResult; + countMarket(params: PaginateParams): PageGenerator; + countMarket(params?: SingleParams): Promise; countMarket(params?: EndpointParams): EndpointResult; + countCrypto(params: PaginateParams): PageGenerator; + countCrypto(params?: SingleParams): Promise; countCrypto(params?: EndpointParams): EndpointResult; sources(params?: EndpointParams): Promise; @@ -161,7 +198,30 @@ export class NewsdataNetworkError extends NewsdataError { } export class NewsdataWebSocketError extends NewsdataError { cause?: Error; + /** + * The error response the server sent before closing + * (`{ status: 'error', results: { message, code } }`), or null. + */ + responseBody: object | null; + /** The server's error code, e.g. 'Unauthorized' or 'ServerError', or null. */ + code: string | null; } +/** A permanent rejection (close 1008); `message` is the server's explanation. */ export class NewsdataWebSocketAuthError extends NewsdataWebSocketError {} +/** Static configuration: base URLs, endpoint paths, defaults and filter sets. */ +export const constants: { + BASE_URL: string; + ENDPOINTS: Record; + FILTERS: Record; + BOOL_PARAMS: readonly string[]; + INT_PARAMS: readonly string[]; + FLOAT_PARAMS: readonly string[]; + MUTEX_GROUPS: readonly (readonly string[])[]; + REQUIRES_DATE_RANGE: readonly string[]; + SIZE_MIN: number; + SIZE_MAX: number; + [key: string]: unknown; +}; + export as namespace newsdata;