@chatwise/node 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/CHANGELOG.md +12 -0
- package/LICENSE +202 -0
- package/README.md +506 -2
- package/dist/cjs/client.d.ts +20 -0
- package/dist/cjs/client.js +32 -0
- package/dist/cjs/core/errors.d.ts +91 -0
- package/dist/cjs/core/errors.js +131 -0
- package/dist/cjs/core/http.d.ts +74 -0
- package/dist/cjs/core/http.js +336 -0
- package/dist/cjs/core/pagination.d.ts +35 -0
- package/dist/cjs/core/pagination.js +101 -0
- package/dist/cjs/generated/types.d.ts +969 -0
- package/dist/cjs/generated/types.js +3 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +25 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources/conversations.d.ts +20 -0
- package/dist/cjs/resources/conversations.js +32 -0
- package/dist/cjs/resources/messages.d.ts +46 -0
- package/dist/cjs/resources/messages.js +60 -0
- package/dist/cjs/resources/webhook-deliveries.d.ts +27 -0
- package/dist/cjs/resources/webhook-deliveries.js +42 -0
- package/dist/cjs/resources/webhook-endpoints.d.ts +54 -0
- package/dist/cjs/resources/webhook-endpoints.js +82 -0
- package/dist/cjs/resources/webhook-event-types.d.ts +13 -0
- package/dist/cjs/resources/webhook-event-types.js +22 -0
- package/dist/cjs/resources/whatsapp-templates.d.ts +48 -0
- package/dist/cjs/resources/whatsapp-templates.js +69 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +123 -0
- package/dist/esm/client.d.ts +20 -0
- package/dist/esm/client.js +28 -0
- package/dist/esm/core/errors.d.ts +91 -0
- package/dist/esm/core/errors.js +113 -0
- package/dist/esm/core/http.d.ts +74 -0
- package/dist/esm/core/http.js +332 -0
- package/dist/esm/core/pagination.d.ts +35 -0
- package/dist/esm/core/pagination.js +95 -0
- package/dist/esm/generated/types.d.ts +969 -0
- package/dist/esm/generated/types.js +2 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/resources/conversations.d.ts +20 -0
- package/dist/esm/resources/conversations.js +28 -0
- package/dist/esm/resources/messages.d.ts +46 -0
- package/dist/esm/resources/messages.js +56 -0
- package/dist/esm/resources/webhook-deliveries.d.ts +27 -0
- package/dist/esm/resources/webhook-deliveries.js +38 -0
- package/dist/esm/resources/webhook-endpoints.d.ts +54 -0
- package/dist/esm/resources/webhook-endpoints.js +78 -0
- package/dist/esm/resources/webhook-event-types.d.ts +13 -0
- package/dist/esm/resources/webhook-event-types.js +18 -0
- package/dist/esm/resources/whatsapp-templates.d.ts +48 -0
- package/dist/esm/resources/whatsapp-templates.js +65 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +118 -0
- package/package.json +79 -4
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { VERSION } from '../version.js';
|
|
2
|
+
import { apiError, APIError, ChatwiseError, ConnectionError, RequestAbortedError, RequestTimeoutError } from './errors.js';
|
|
3
|
+
const DEFAULT_BASE_URL = 'https://api.chatwise.so';
|
|
4
|
+
const DEFAULT_TIMEOUT_MS = 60_000;
|
|
5
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
6
|
+
/** The longest wait setTimeout can hold. A longer one would end at once. */
|
|
7
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
8
|
+
/** Chatwise asks for 60 seconds. A call doesn't wait for much longer than that: it fails instead. */
|
|
9
|
+
const MAX_RETRY_AFTER_MS = 90_000;
|
|
10
|
+
/** The most that is read of an answer. The API's are far smaller: compressed, a few hundred KB can hold 300 MB. */
|
|
11
|
+
const MAX_BODY_BYTES = 33_554_432; // 32 MB. Not a multiplication, which bundlers keep when nothing uses it.
|
|
12
|
+
const MAX_ERROR_BODY_BYTES = 1_048_576;
|
|
13
|
+
const REDACTED = '[redacted]';
|
|
14
|
+
function checkTimeout(value) {
|
|
15
|
+
if (!Number.isInteger(value) || value < 1 || value > MAX_TIMEOUT_MS) {
|
|
16
|
+
throw new ChatwiseError(`timeoutMs must be a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}.`);
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
function checkRetries(value) {
|
|
21
|
+
if (!Number.isInteger(value) || value < 0 || value > 10) {
|
|
22
|
+
throw new ChatwiseError('maxRetries must be a whole number from 0 to 10.');
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
function checkSignal(signal) {
|
|
27
|
+
if (signal !== undefined && (typeof signal !== 'object' || signal === null || typeof signal.addEventListener !== 'function')) {
|
|
28
|
+
throw new ChatwiseError('signal must be an AbortSignal. Of an AbortController, pass its `signal`.');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function environmentKey() {
|
|
32
|
+
// Not every runtime has `process`.
|
|
33
|
+
return typeof process === 'undefined' ? undefined : process.env?.CHATWISE_API_KEY;
|
|
34
|
+
}
|
|
35
|
+
function checkKey(value) {
|
|
36
|
+
if (typeof value !== 'string' || !value.trim()) {
|
|
37
|
+
throw new ChatwiseError('No API key. Pass `apiKey`, or set the CHATWISE_API_KEY environment variable.');
|
|
38
|
+
}
|
|
39
|
+
const key = value.trim();
|
|
40
|
+
// fetch refuses other characters with an error that quotes the header, and so the key.
|
|
41
|
+
if (!/^[\x21-\x7e]+$/.test(key)) {
|
|
42
|
+
throw new ChatwiseError('The API key has spaces, line breaks or other characters a key can\'t have.');
|
|
43
|
+
}
|
|
44
|
+
return key;
|
|
45
|
+
}
|
|
46
|
+
function checkBaseUrl(value) {
|
|
47
|
+
let url;
|
|
48
|
+
try {
|
|
49
|
+
url = new URL(value);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new ChatwiseError('baseUrl is not a valid URL.');
|
|
53
|
+
}
|
|
54
|
+
const local = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || url.hostname.endsWith('.localhost');
|
|
55
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) {
|
|
56
|
+
throw new ChatwiseError('baseUrl must be https, or the API key would be sent unencrypted. Only this machine may use http.');
|
|
57
|
+
}
|
|
58
|
+
if (url.username || url.password || url.search || url.hash) {
|
|
59
|
+
throw new ChatwiseError('baseUrl can\'t have a username, password, query or fragment.');
|
|
60
|
+
}
|
|
61
|
+
return (url.origin + url.pathname).replace(/\/+$/, '');
|
|
62
|
+
}
|
|
63
|
+
/** A path with its ids. An id that would change the path, such as `..`, is refused. */
|
|
64
|
+
export function path(strings, ...ids) {
|
|
65
|
+
return strings.reduce((result, part, index) => {
|
|
66
|
+
const id = ids[index - 1];
|
|
67
|
+
if (typeof id !== 'string') {
|
|
68
|
+
throw new ChatwiseError('An id must be a string. Ids can be larger than a JavaScript number can hold, so keep them as strings.');
|
|
69
|
+
}
|
|
70
|
+
if (!id || id === '.' || id === '..')
|
|
71
|
+
throw new ChatwiseError('An id can\'t be empty, "." or "..".');
|
|
72
|
+
let encoded;
|
|
73
|
+
try {
|
|
74
|
+
encoded = encodeURIComponent(id);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
throw new ChatwiseError('An id can\'t have half of a character in it.');
|
|
78
|
+
}
|
|
79
|
+
return result + encoded + part;
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
function queryString(query = {}) {
|
|
83
|
+
const search = new URLSearchParams();
|
|
84
|
+
for (const [name, value] of Object.entries(query)) {
|
|
85
|
+
if (value === undefined)
|
|
86
|
+
continue;
|
|
87
|
+
// Leaving it out would answer with everything, when one conversation's messages were wanted.
|
|
88
|
+
if (value === null)
|
|
89
|
+
throw new ChatwiseError(`${name} is null. Leave it out, or pass undefined, not to filter by it.`);
|
|
90
|
+
if (value instanceof Date) {
|
|
91
|
+
if (Number.isNaN(value.getTime()))
|
|
92
|
+
throw new ChatwiseError(`${name} is not a valid date.`);
|
|
93
|
+
search.set(name, value.toISOString());
|
|
94
|
+
}
|
|
95
|
+
else if (typeof value === 'number' && !Number.isSafeInteger(value)) {
|
|
96
|
+
throw new ChatwiseError(`${name} is not a whole number JavaScript can hold exactly. Pass ids as strings.`);
|
|
97
|
+
}
|
|
98
|
+
else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
99
|
+
search.set(name, String(value));
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
throw new ChatwiseError(`${name} must be a string, number, boolean or Date.`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const text = search.toString();
|
|
106
|
+
return text && `?${text}`;
|
|
107
|
+
}
|
|
108
|
+
function serialize(body) {
|
|
109
|
+
try {
|
|
110
|
+
return JSON.stringify(body);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
throw new ChatwiseError('The request can\'t be written as JSON. Pass ids as strings, not as BigInt.');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** `Retry-After` in milliseconds: it is a number of seconds or a date. */
|
|
117
|
+
function parseRetryAfter(value) {
|
|
118
|
+
const text = value?.trim();
|
|
119
|
+
if (!text)
|
|
120
|
+
return undefined;
|
|
121
|
+
// However long: one that isn't read would be a retry right away.
|
|
122
|
+
if (/^\d+(?:\.\d+)?$/.test(text))
|
|
123
|
+
return Math.min(Math.ceil(Number(text) * 1000), Number.MAX_SAFE_INTEGER);
|
|
124
|
+
// Date.parse reads some numbers as dates too.
|
|
125
|
+
const date = /\bGMT$/.test(text) ? Date.parse(text) : NaN;
|
|
126
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
127
|
+
}
|
|
128
|
+
/** How long to wait before retrying after `error`, or undefined not to retry. `attempt` counts from 0. */
|
|
129
|
+
function retryDelay(error, attempt, { method, idempotent = false }) {
|
|
130
|
+
const limited = error instanceof APIError && error.status === 429;
|
|
131
|
+
const failed = error instanceof ConnectionError || (error instanceof APIError && error.status >= 500);
|
|
132
|
+
// An answer with a code says what to do about a template that was submitted, such as to wait for
|
|
133
|
+
// Meta. Asking again right away would only replace it with "already in progress".
|
|
134
|
+
const safe = method === 'GET' || (idempotent && !(error instanceof APIError && error.code !== undefined));
|
|
135
|
+
if (!limited && !(safe && failed))
|
|
136
|
+
return undefined;
|
|
137
|
+
const retryAfter = error instanceof APIError ? error.retryAfterMs : undefined;
|
|
138
|
+
if (retryAfter !== undefined) {
|
|
139
|
+
if (retryAfter > MAX_RETRY_AFTER_MS)
|
|
140
|
+
return undefined;
|
|
141
|
+
// Up to a second more, so that callers limited together don't come back together.
|
|
142
|
+
return Math.ceil(retryAfter + Math.random() * 1000);
|
|
143
|
+
}
|
|
144
|
+
const backoff = Math.min(8000, 500 * 2 ** attempt);
|
|
145
|
+
return Math.ceil(backoff * (0.75 + Math.random() * 0.25));
|
|
146
|
+
}
|
|
147
|
+
/** An answer's text, or undefined if it has more than `maxBytes`. The rest isn't read then. */
|
|
148
|
+
async function readText(response, maxBytes, signal) {
|
|
149
|
+
const stream = response.body;
|
|
150
|
+
// Locked: a custom fetch read it, to log it for example, and answers with a text() of its own.
|
|
151
|
+
if (typeof stream?.getReader !== 'function' || stream.locked) {
|
|
152
|
+
const text = await response.text();
|
|
153
|
+
return text.length > maxBytes ? undefined : text;
|
|
154
|
+
}
|
|
155
|
+
const reader = stream.getReader();
|
|
156
|
+
// Not awaited: a stream that doesn't end its cancellation can't hold the call up.
|
|
157
|
+
const cancel = () => void Promise.resolve().then(() => reader.cancel()).catch(() => undefined);
|
|
158
|
+
signal.addEventListener('abort', cancel);
|
|
159
|
+
try {
|
|
160
|
+
const decoder = new TextDecoder();
|
|
161
|
+
let text = '';
|
|
162
|
+
let bytes = 0;
|
|
163
|
+
for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
|
|
164
|
+
bytes += chunk.value.byteLength;
|
|
165
|
+
if (bytes > maxBytes) {
|
|
166
|
+
cancel();
|
|
167
|
+
return undefined;
|
|
168
|
+
}
|
|
169
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
170
|
+
}
|
|
171
|
+
return text + decoder.decode();
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
signal.removeEventListener('abort', cancel);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function aborted(signal) {
|
|
178
|
+
return new RequestAbortedError('The request was aborted.', { cause: signal.reason });
|
|
179
|
+
}
|
|
180
|
+
function sleep(ms, signal) {
|
|
181
|
+
return new Promise((resolve, reject) => {
|
|
182
|
+
const finish = (settle) => {
|
|
183
|
+
clearTimeout(timer);
|
|
184
|
+
signal?.removeEventListener('abort', onAbort);
|
|
185
|
+
settle();
|
|
186
|
+
};
|
|
187
|
+
const onAbort = () => finish(() => reject(aborted(signal)));
|
|
188
|
+
const timer = setTimeout(() => finish(resolve), ms);
|
|
189
|
+
signal?.addEventListener('abort', onAbort);
|
|
190
|
+
if (signal?.aborted)
|
|
191
|
+
onAbort();
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The function every resource makes its requests with. The key stays in this closure: it is on no
|
|
196
|
+
* object, so printing a client can't show it.
|
|
197
|
+
*/
|
|
198
|
+
export function createRequester(options) {
|
|
199
|
+
// A key that is passed by itself would be ignored, for the environment's.
|
|
200
|
+
if (typeof options !== 'object' || options === null)
|
|
201
|
+
throw new ChatwiseError('Pass the options as an object, such as `{ apiKey }`.');
|
|
202
|
+
const apiKey = checkKey(options.apiKey ?? environmentKey());
|
|
203
|
+
const baseUrl = checkBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);
|
|
204
|
+
const defaultTimeoutMs = checkTimeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
205
|
+
const defaultMaxRetries = checkRetries(options.maxRetries ?? DEFAULT_MAX_RETRIES);
|
|
206
|
+
const customFetch = options.fetch;
|
|
207
|
+
if (customFetch !== undefined && typeof customFetch !== 'function')
|
|
208
|
+
throw new ChatwiseError('fetch must be a function.');
|
|
209
|
+
const encodedKey = encodeURIComponent(apiKey);
|
|
210
|
+
const redact = (value) => value.replaceAll(apiKey, REDACTED).replaceAll(encodedKey, REDACTED);
|
|
211
|
+
/** A parsed body without the key, which the JSON may have written with escapes. */
|
|
212
|
+
function redactBody(value) {
|
|
213
|
+
if (typeof value === 'string')
|
|
214
|
+
return redact(value);
|
|
215
|
+
if (Array.isArray(value))
|
|
216
|
+
return value.map(redactBody);
|
|
217
|
+
if (typeof value !== 'object' || value === null)
|
|
218
|
+
return value;
|
|
219
|
+
return Object.fromEntries(Object.entries(value).map(([name, inner]) => [redact(name), redactBody(inner)]));
|
|
220
|
+
}
|
|
221
|
+
/** An error from fetch, as a new one with only its message and code. The original can hold the request's headers. */
|
|
222
|
+
function redactedCause(error, depth = 0) {
|
|
223
|
+
if (typeof error !== 'object' || error === null)
|
|
224
|
+
return undefined;
|
|
225
|
+
const { name, message, code, cause } = error;
|
|
226
|
+
const inner = depth < 3 ? redactedCause(cause, depth + 1) : undefined;
|
|
227
|
+
const copy = new Error(typeof message === 'string' ? redact(message) : '', inner && { cause: inner });
|
|
228
|
+
if (typeof name === 'string')
|
|
229
|
+
copy.name = redact(name);
|
|
230
|
+
return typeof code === 'string' ? Object.assign(copy, { code: redact(code) }) : copy;
|
|
231
|
+
}
|
|
232
|
+
function connectionError(error, method, requestPath) {
|
|
233
|
+
const cause = redactedCause(error);
|
|
234
|
+
const detail = cause?.cause?.message || cause?.message;
|
|
235
|
+
return new ConnectionError(`No complete answer from Chatwise to ${method} ${requestPath}${detail ? `: ${detail}` : ''}`, cause && { cause });
|
|
236
|
+
}
|
|
237
|
+
function parse(text) {
|
|
238
|
+
try {
|
|
239
|
+
return { body: JSON.parse(text), isJson: true };
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
return { body: text.slice(0, 1000), isJson: false };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async function attempt({ method, headers }, requestPath, url, body, timeoutMs, signal) {
|
|
246
|
+
if (signal?.aborted)
|
|
247
|
+
throw aborted(signal);
|
|
248
|
+
const controller = new AbortController();
|
|
249
|
+
let interruption;
|
|
250
|
+
let interrupt;
|
|
251
|
+
// Raced against fetch, so that a fetch that ignores its signal can't outlast the timeout.
|
|
252
|
+
const interrupted = new Promise((_, reject) => {
|
|
253
|
+
interrupt = (error) => {
|
|
254
|
+
interruption ??= error;
|
|
255
|
+
reject(error);
|
|
256
|
+
controller.abort();
|
|
257
|
+
};
|
|
258
|
+
});
|
|
259
|
+
interrupted.catch(() => undefined);
|
|
260
|
+
const onAbort = () => interrupt(aborted(signal));
|
|
261
|
+
const timer = setTimeout(() => interrupt(new RequestTimeoutError(`Chatwise didn't answer ${method} ${requestPath} within ${timeoutMs} ms.`)), timeoutMs);
|
|
262
|
+
try {
|
|
263
|
+
signal?.addEventListener('abort', onAbort);
|
|
264
|
+
const send = async () => {
|
|
265
|
+
const response = await (customFetch ?? globalThis.fetch)(url, {
|
|
266
|
+
method,
|
|
267
|
+
headers: {
|
|
268
|
+
Accept: 'application/json',
|
|
269
|
+
Authorization: `Bearer ${apiKey}`,
|
|
270
|
+
'User-Agent': `chatwise-node/${VERSION}`,
|
|
271
|
+
...(body !== undefined && { 'Content-Type': 'application/json' }),
|
|
272
|
+
...headers,
|
|
273
|
+
},
|
|
274
|
+
...(body !== undefined && { body }),
|
|
275
|
+
// Following a redirect could send the key elsewhere, or a POST twice. The API has none. (Node's
|
|
276
|
+
// fetch itself repeats a request after a 421, which says that it wasn't processed.)
|
|
277
|
+
redirect: 'manual',
|
|
278
|
+
signal: controller.signal,
|
|
279
|
+
});
|
|
280
|
+
const { status } = response;
|
|
281
|
+
const maxBytes = status >= 200 && status < 300 ? MAX_BODY_BYTES : MAX_ERROR_BODY_BYTES;
|
|
282
|
+
return { status, retryAfter: response.headers.get('retry-after'), text: await readText(response, maxBytes, controller.signal) };
|
|
283
|
+
};
|
|
284
|
+
return await Promise.race([send(), interrupted]);
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
// By identity: fetch can throw one of this package's errors, with the key in it or a status that
|
|
288
|
+
// would be retried.
|
|
289
|
+
if (interruption !== undefined && error === interruption)
|
|
290
|
+
throw error;
|
|
291
|
+
throw connectionError(error, method, requestPath);
|
|
292
|
+
}
|
|
293
|
+
finally {
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
signal?.removeEventListener('abort', onAbort);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return async function request(operation, options) {
|
|
299
|
+
const { signal, timeoutMs, maxRetries } = options ?? {};
|
|
300
|
+
checkSignal(signal);
|
|
301
|
+
const { method } = operation;
|
|
302
|
+
// For errors, which can show it.
|
|
303
|
+
const requestPath = redact(operation.path);
|
|
304
|
+
const timeout = timeoutMs === undefined ? defaultTimeoutMs : checkTimeout(timeoutMs);
|
|
305
|
+
const retries = maxRetries === undefined ? defaultMaxRetries : checkRetries(maxRetries);
|
|
306
|
+
const url = baseUrl + operation.path + queryString(operation.query);
|
|
307
|
+
const requestBody = operation.body && serialize(operation.body);
|
|
308
|
+
for (let count = 0;; count++) {
|
|
309
|
+
try {
|
|
310
|
+
const { status, retryAfter, text } = await attempt(operation, requestPath, url, requestBody, timeout, signal);
|
|
311
|
+
if (status >= 200 && status < 300) {
|
|
312
|
+
if (text === undefined) {
|
|
313
|
+
throw new ConnectionError(`Chatwise answered ${status} to ${method} ${requestPath}, but with more than the API answers.`);
|
|
314
|
+
}
|
|
315
|
+
const { body, isJson } = parse(text);
|
|
316
|
+
if (isJson && typeof body === 'object' && body !== null && 'data' in body)
|
|
317
|
+
return body;
|
|
318
|
+
// It was carried out, or it seems so. The answer is cut off, or not from the API.
|
|
319
|
+
throw new ConnectionError(`Chatwise answered ${status} to ${method} ${requestPath}, but the answer is incomplete or not the API's.`);
|
|
320
|
+
}
|
|
321
|
+
const { body } = parse(redact(text ?? ''));
|
|
322
|
+
throw apiError({ status, method, path: requestPath, body: redactBody(body), retryAfterMs: parseRetryAfter(retryAfter) });
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
const delay = count < retries ? retryDelay(error, count, operation) : undefined;
|
|
326
|
+
if (delay === undefined)
|
|
327
|
+
throw error;
|
|
328
|
+
await sleep(delay, signal);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { RequestOptions, Requester } from './http.js';
|
|
2
|
+
/** One page of a list. Iterating over it goes through this page's items and those of the pages after it. */
|
|
3
|
+
export declare class Page<Item> implements AsyncIterable<Item> {
|
|
4
|
+
#private;
|
|
5
|
+
/** The items of this page. */
|
|
6
|
+
readonly data: Item[];
|
|
7
|
+
/** Where the next page starts, or null on the last page. Pass it as `cursor`, with the same filters and order. */
|
|
8
|
+
readonly nextCursor: string | null;
|
|
9
|
+
hasNextPage(): boolean;
|
|
10
|
+
/** The next page, or null after the last one. */
|
|
11
|
+
getNextPage(): Promise<Page<Item> | null>;
|
|
12
|
+
/** This page and the ones after it. */
|
|
13
|
+
pages(): AsyncGenerator<Page<Item>, void, undefined>;
|
|
14
|
+
/** The items of this page and of the pages after it. */
|
|
15
|
+
[Symbol.asyncIterator](): AsyncGenerator<Item, void, undefined>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A list that isn't read yet. `await` it for its first page, or iterate over it with `for await` for
|
|
19
|
+
* every item. Nothing is requested before that.
|
|
20
|
+
*/
|
|
21
|
+
export declare class PagePromise<Item> implements Promise<Page<Item>>, AsyncIterable<Item> {
|
|
22
|
+
#private;
|
|
23
|
+
get [Symbol.toStringTag](): string;
|
|
24
|
+
then<Result1 = Page<Item>, Result2 = never>(onFulfilled?: ((page: Page<Item>) => Result1 | PromiseLike<Result1>) | null, onRejected?: ((reason: any) => Result2 | PromiseLike<Result2>) | null): Promise<Result1 | Result2>;
|
|
25
|
+
catch<Result = never>(onRejected?: ((reason: any) => Result | PromiseLike<Result>) | null): Promise<Page<Item> | Result>;
|
|
26
|
+
finally(onFinally?: (() => void) | null): Promise<Page<Item>>;
|
|
27
|
+
/** The pages, from the first. */
|
|
28
|
+
pages(): AsyncGenerator<Page<Item>, void, undefined>;
|
|
29
|
+
/** The items of every page. */
|
|
30
|
+
[Symbol.asyncIterator](): AsyncGenerator<Item, void, undefined>;
|
|
31
|
+
}
|
|
32
|
+
/** A list with pages. `path` is a function so that a bad id rejects like every other error. */
|
|
33
|
+
export declare function list<Item>(request: Requester, path: () => string, params: {
|
|
34
|
+
cursor?: string | undefined;
|
|
35
|
+
}, options: RequestOptions | undefined): PagePromise<Item>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { ChatwiseError } from './errors.js';
|
|
2
|
+
/** One page of a list. Iterating over it goes through this page's items and those of the pages after it. */
|
|
3
|
+
export class Page {
|
|
4
|
+
/** The items of this page. */
|
|
5
|
+
data;
|
|
6
|
+
/** Where the next page starts, or null on the last page. Pass it as `cursor`, with the same filters and order. */
|
|
7
|
+
nextCursor;
|
|
8
|
+
#next;
|
|
9
|
+
/** @internal */
|
|
10
|
+
constructor(data, nextCursor, next) {
|
|
11
|
+
this.data = data;
|
|
12
|
+
this.nextCursor = nextCursor;
|
|
13
|
+
this.#next = next;
|
|
14
|
+
}
|
|
15
|
+
hasNextPage() {
|
|
16
|
+
return this.nextCursor !== null;
|
|
17
|
+
}
|
|
18
|
+
/** The next page, or null after the last one. */
|
|
19
|
+
async getNextPage() {
|
|
20
|
+
return this.nextCursor === null ? null : this.#next(this.nextCursor);
|
|
21
|
+
}
|
|
22
|
+
/** This page and the ones after it. */
|
|
23
|
+
async *pages() {
|
|
24
|
+
yield this;
|
|
25
|
+
const seen = new Set([this.nextCursor]);
|
|
26
|
+
for (let page = await this.getNextPage(); page; page = await page.getNextPage()) {
|
|
27
|
+
yield page;
|
|
28
|
+
if (page.nextCursor !== null && seen.has(page.nextCursor))
|
|
29
|
+
throw new ChatwiseError('Chatwise answered with the same pages again.');
|
|
30
|
+
seen.add(page.nextCursor);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** The items of this page and of the pages after it. */
|
|
34
|
+
async *[Symbol.asyncIterator]() {
|
|
35
|
+
for await (const page of this.pages())
|
|
36
|
+
yield* page.data;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A list that isn't read yet. `await` it for its first page, or iterate over it with `for await` for
|
|
41
|
+
* every item. Nothing is requested before that.
|
|
42
|
+
*/
|
|
43
|
+
export class PagePromise {
|
|
44
|
+
#load;
|
|
45
|
+
#first;
|
|
46
|
+
/** @internal */
|
|
47
|
+
constructor(load) {
|
|
48
|
+
this.#load = load;
|
|
49
|
+
}
|
|
50
|
+
get [Symbol.toStringTag]() {
|
|
51
|
+
return 'PagePromise';
|
|
52
|
+
}
|
|
53
|
+
#page() {
|
|
54
|
+
return (this.#first ??= this.#load());
|
|
55
|
+
}
|
|
56
|
+
then(onFulfilled,
|
|
57
|
+
// `any`, as in Promise itself.
|
|
58
|
+
onRejected) {
|
|
59
|
+
return this.#page().then(onFulfilled, onRejected);
|
|
60
|
+
}
|
|
61
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
62
|
+
catch(onRejected) {
|
|
63
|
+
return this.#page().catch(onRejected);
|
|
64
|
+
}
|
|
65
|
+
finally(onFinally) {
|
|
66
|
+
return this.#page().finally(onFinally);
|
|
67
|
+
}
|
|
68
|
+
/** The pages, from the first. */
|
|
69
|
+
async *pages() {
|
|
70
|
+
yield* (await this.#page()).pages();
|
|
71
|
+
}
|
|
72
|
+
/** The items of every page. */
|
|
73
|
+
async *[Symbol.asyncIterator]() {
|
|
74
|
+
yield* await this.#page();
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** A list with pages. `path` is a function so that a bad id rejects like every other error. */
|
|
78
|
+
export function list(request, path, params, options) {
|
|
79
|
+
// A copy, so that changing the filters afterwards, or one of their dates, doesn't change what the next
|
|
80
|
+
// page is of.
|
|
81
|
+
const query = Object.fromEntries(Object.entries({ ...params }).map(([name, value]) => [name, value instanceof Date ? new Date(value) : value]));
|
|
82
|
+
const load = async (cursor) => {
|
|
83
|
+
const operation = { method: 'GET', path: path(), query: { ...query, cursor } };
|
|
84
|
+
const { data, pagination } = await request(operation, options);
|
|
85
|
+
const nextCursor = pagination?.nextCursor;
|
|
86
|
+
if (!Array.isArray(data) || (nextCursor !== null && typeof nextCursor !== 'string')) {
|
|
87
|
+
throw new ChatwiseError(`Chatwise answered ${operation.path} with a list this version doesn't understand.`);
|
|
88
|
+
}
|
|
89
|
+
if (nextCursor !== null && nextCursor === cursor) {
|
|
90
|
+
throw new ChatwiseError(`Chatwise answered ${operation.path} with the same page again.`);
|
|
91
|
+
}
|
|
92
|
+
return new Page(data, nextCursor, load);
|
|
93
|
+
};
|
|
94
|
+
return new PagePromise(() => load(query.cursor));
|
|
95
|
+
}
|