@chatwise/node 0.0.0-stage → 0.1.1

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