@tungoai/sdk 0.0.0-stage → 0.2.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 +40 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +151 -0
- package/dist/cjs/client.d.ts +116 -0
- package/dist/cjs/client.js +223 -0
- package/dist/cjs/core.d.ts +210 -0
- package/dist/cjs/core.js +605 -0
- package/dist/cjs/errors.d.ts +212 -0
- package/dist/cjs/errors.js +410 -0
- package/dist/cjs/generated/resources.d.ts +1059 -0
- package/dist/cjs/generated/resources.js +1064 -0
- package/dist/cjs/generated/types.d.ts +4927 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +80 -0
- package/dist/cjs/json.d.ts +10 -0
- package/dist/cjs/json.js +120 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +113 -0
- package/dist/cjs/streaming.d.ts +74 -0
- package/dist/cjs/streaming.js +253 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +248 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +143 -0
- package/dist/esm/client.d.ts +116 -0
- package/dist/esm/client.js +219 -0
- package/dist/esm/core.d.ts +210 -0
- package/dist/esm/core.js +589 -0
- package/dist/esm/errors.d.ts +212 -0
- package/dist/esm/errors.js +381 -0
- package/dist/esm/generated/resources.d.ts +1059 -0
- package/dist/esm/generated/resources.js +1048 -0
- package/dist/esm/generated/types.d.ts +4927 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +10 -0
- package/dist/esm/json.js +116 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +107 -0
- package/dist/esm/streaming.d.ts +74 -0
- package/dist/esm/streaming.js +247 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +239 -0
- package/package.json +67 -4
package/dist/cjs/core.js
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.APIClient = exports.StreamPromise = exports.APIPromise = exports.MAX_TIMER_MS = exports.MAX_RETRY_AFTER_SECONDS = exports.DEFAULT_STREAM_IDLE_TIMEOUT = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_LONG_RUNNING_TIMEOUT = exports.DEFAULT_TIMEOUT = exports.DEFAULT_BASE_URL = void 0;
|
|
4
|
+
exports.readEnv = readEnv;
|
|
5
|
+
exports.uuid4 = uuid4;
|
|
6
|
+
exports.encodePathSegment = encodePathSegment;
|
|
7
|
+
exports.buildPath = buildPath;
|
|
8
|
+
exports.buildQuery = buildQuery;
|
|
9
|
+
exports.backoffDelay = backoffDelay;
|
|
10
|
+
exports.isRetryableStatus = isRetryableStatus;
|
|
11
|
+
exports.shouldRetry = shouldRetry;
|
|
12
|
+
exports.startTimer = startTimer;
|
|
13
|
+
exports.sleep = sleep;
|
|
14
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
15
|
+
const errors_js_1 = require("./errors.js");
|
|
16
|
+
const json_js_1 = require("./json.js");
|
|
17
|
+
const version_js_1 = require("./version.js");
|
|
18
|
+
/** The production API host. */
|
|
19
|
+
exports.DEFAULT_BASE_URL = 'https://api.tungo.kz';
|
|
20
|
+
/** Default timeout of an ordinary request, in milliseconds. */
|
|
21
|
+
exports.DEFAULT_TIMEOUT = 60_000;
|
|
22
|
+
/** Default timeout of a non-streaming chat turn, in milliseconds. */
|
|
23
|
+
exports.DEFAULT_LONG_RUNNING_TIMEOUT = 600_000;
|
|
24
|
+
/** Default number of retries (so 3 attempts in total). */
|
|
25
|
+
exports.DEFAULT_MAX_RETRIES = 2;
|
|
26
|
+
/** Default idle timeout of a stream, in milliseconds. */
|
|
27
|
+
exports.DEFAULT_STREAM_IDLE_TIMEOUT = 120_000;
|
|
28
|
+
/** A server-requested delay above this many seconds is not slept: the error is raised instead. */
|
|
29
|
+
exports.MAX_RETRY_AFTER_SECONDS = 60;
|
|
30
|
+
/**
|
|
31
|
+
* The longest delay a platform timer supports, in milliseconds (2^31 - 1, about 24.8 days).
|
|
32
|
+
* A timeout above it, `Infinity` included, means "no time limit": no timer is started.
|
|
33
|
+
*/
|
|
34
|
+
exports.MAX_TIMER_MS = 2_147_483_647;
|
|
35
|
+
const USER_AGENT = 'tungo-sdk-typescript/' + version_js_1.VERSION;
|
|
36
|
+
/** Reads an environment variable on Node.js, Bun and Deno; undefined elsewhere or when empty. */
|
|
37
|
+
function readEnv(name) {
|
|
38
|
+
try {
|
|
39
|
+
const scope = globalThis;
|
|
40
|
+
const fromProcess = scope.process?.env?.[name];
|
|
41
|
+
if (typeof fromProcess === 'string' && fromProcess !== '')
|
|
42
|
+
return fromProcess;
|
|
43
|
+
const fromDeno = scope.Deno?.env?.get?.(name);
|
|
44
|
+
if (typeof fromDeno === 'string' && fromDeno !== '')
|
|
45
|
+
return fromDeno;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// No permission to read the environment.
|
|
49
|
+
}
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
/** A random RFC 4122 version 4 UUID from the platform CSPRNG. */
|
|
53
|
+
function uuid4() {
|
|
54
|
+
const bytes = new Uint8Array(16);
|
|
55
|
+
crypto.getRandomValues(bytes);
|
|
56
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
|
57
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
58
|
+
let hex = '';
|
|
59
|
+
for (const b of bytes)
|
|
60
|
+
hex += b.toString(16).padStart(2, '0');
|
|
61
|
+
return hex.slice(0, 8) + '-' + hex.slice(8, 12) + '-' + hex.slice(12, 16) + '-' + hex.slice(16, 20) + '-' + hex.slice(20);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Percent-encodes a value as ONE path segment (`/`, `?`, `#`, spaces, CR/LF and non-ASCII are all
|
|
65
|
+
* encoded). An empty value, `.` and `..` are rejected because they would change the path.
|
|
66
|
+
*/
|
|
67
|
+
function encodePathSegment(value, name = 'value') {
|
|
68
|
+
if (typeof value !== 'string') {
|
|
69
|
+
throw new errors_js_1.ValidationError('The path parameter "' + name + '" must be a string');
|
|
70
|
+
}
|
|
71
|
+
if (value === '' || value === '.' || value === '..') {
|
|
72
|
+
throw new errors_js_1.ValidationError('The path parameter "' + name + '" must not be empty, "." or ".."');
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
|
|
76
|
+
}
|
|
77
|
+
catch (cause) {
|
|
78
|
+
throw new errors_js_1.ValidationError('The path parameter "' + name + '" is not valid Unicode text', { cause });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Fills a path template (`/v1/companies/{co}`) with encoded parameter values. */
|
|
82
|
+
function buildPath(template, params) {
|
|
83
|
+
return template.replace(/\{([^{}]+)\}/g, (_match, name) => {
|
|
84
|
+
const value = params === undefined ? undefined : params[name];
|
|
85
|
+
return encodePathSegment(value, name);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
function queryText(name, value) {
|
|
89
|
+
switch (typeof value) {
|
|
90
|
+
case 'string':
|
|
91
|
+
return value;
|
|
92
|
+
case 'boolean':
|
|
93
|
+
return value ? 'true' : 'false';
|
|
94
|
+
case 'bigint':
|
|
95
|
+
return value.toString();
|
|
96
|
+
case 'number':
|
|
97
|
+
if (!Number.isFinite(value))
|
|
98
|
+
break;
|
|
99
|
+
return String(value);
|
|
100
|
+
case 'object':
|
|
101
|
+
if (value instanceof Date && !Number.isNaN(value.getTime()))
|
|
102
|
+
return value.toISOString();
|
|
103
|
+
break;
|
|
104
|
+
default:
|
|
105
|
+
break;
|
|
106
|
+
}
|
|
107
|
+
throw new errors_js_1.ValidationError('The query parameter "' + name + '" has a value that cannot be sent');
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Builds a query string (without the leading `?`): booleans as `true`/`false`, dates as RFC 3339,
|
|
111
|
+
* arrays as repeated keys, null and undefined omitted, `+` encoded as `%2B`.
|
|
112
|
+
*/
|
|
113
|
+
function buildQuery(query) {
|
|
114
|
+
if (query === undefined)
|
|
115
|
+
return '';
|
|
116
|
+
const parts = [];
|
|
117
|
+
const add = (name, value) => {
|
|
118
|
+
try {
|
|
119
|
+
parts.push(encodeURIComponent(name) + '=' + encodeURIComponent(queryText(name, value)));
|
|
120
|
+
}
|
|
121
|
+
catch (cause) {
|
|
122
|
+
if (cause instanceof errors_js_1.TungoError)
|
|
123
|
+
throw cause;
|
|
124
|
+
throw new errors_js_1.ValidationError('The query parameter "' + name + '" is not valid Unicode text', { cause });
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
for (const [name, value] of Object.entries(query)) {
|
|
128
|
+
if (value === undefined || value === null)
|
|
129
|
+
continue;
|
|
130
|
+
if (Array.isArray(value)) {
|
|
131
|
+
for (const item of value) {
|
|
132
|
+
if (item !== undefined && item !== null)
|
|
133
|
+
add(name, item);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
add(name, value);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return parts.join('&');
|
|
141
|
+
}
|
|
142
|
+
/** Delay before retry number `attempt` (0-based), in milliseconds: min(0.5 s * 2^attempt, 8 s) * [0.75, 1]. */
|
|
143
|
+
function backoffDelay(attempt, random = Math.random) {
|
|
144
|
+
const base = Math.min(500 * 2 ** attempt, 8000);
|
|
145
|
+
return base * (0.75 + 0.25 * random());
|
|
146
|
+
}
|
|
147
|
+
/** Statuses after which a request may be repeated. */
|
|
148
|
+
function isRetryableStatus(status) {
|
|
149
|
+
return status === 408 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* The retry rule: the failure must be transient (a retryable status, a connection error or a
|
|
153
|
+
* timeout) AND repeating the request must be safe (GET, HEAD, PUT, DELETE, or any request that
|
|
154
|
+
* carries an idempotency key).
|
|
155
|
+
*/
|
|
156
|
+
function shouldRetry(method, hasIdempotencyKey, cause) {
|
|
157
|
+
const transient = typeof cause === 'number' ? isRetryableStatus(cause) : true;
|
|
158
|
+
const m = method.toUpperCase();
|
|
159
|
+
const repeatable = m === 'GET' || m === 'HEAD' || m === 'PUT' || m === 'DELETE' || hasIdempotencyKey;
|
|
160
|
+
return transient && repeatable;
|
|
161
|
+
}
|
|
162
|
+
function abortError(signal, what) {
|
|
163
|
+
return new errors_js_1.AbortError(what + ' was aborted', { cause: signal.reason });
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Starts a timer, or none (undefined) when the delay is infinite or longer than the platform can
|
|
167
|
+
* count: `setTimeout` would fire such a timer at once instead of never.
|
|
168
|
+
*/
|
|
169
|
+
function startTimer(callback, ms) {
|
|
170
|
+
return ms > exports.MAX_TIMER_MS ? undefined : setTimeout(callback, ms);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Waits `ms` milliseconds; rejects with an AbortError as soon as the signal aborts. A delay above
|
|
174
|
+
* {@link MAX_TIMER_MS} waits until the signal aborts.
|
|
175
|
+
*/
|
|
176
|
+
function sleep(ms, signal) {
|
|
177
|
+
return new Promise((resolve, reject) => {
|
|
178
|
+
if (signal !== undefined && signal.aborted) {
|
|
179
|
+
reject(abortError(signal, 'The wait'));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const onAbort = () => {
|
|
183
|
+
clearTimeout(timer);
|
|
184
|
+
reject(abortError(signal, 'The wait'));
|
|
185
|
+
};
|
|
186
|
+
const timer = startTimer(() => {
|
|
187
|
+
if (signal !== undefined)
|
|
188
|
+
signal.removeEventListener('abort', onAbort);
|
|
189
|
+
resolve();
|
|
190
|
+
}, ms);
|
|
191
|
+
if (signal !== undefined)
|
|
192
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
function causeText(cause) {
|
|
196
|
+
if (!(cause instanceof Error))
|
|
197
|
+
return String(cause);
|
|
198
|
+
const inner = cause.cause;
|
|
199
|
+
if (inner instanceof Error && inner.message !== '' && inner.message !== cause.message) {
|
|
200
|
+
return cause.message + ': ' + inner.message;
|
|
201
|
+
}
|
|
202
|
+
return cause.message;
|
|
203
|
+
}
|
|
204
|
+
function positive(value, fallback, name, zeroAllowed) {
|
|
205
|
+
if (value === undefined)
|
|
206
|
+
return fallback;
|
|
207
|
+
if (typeof value !== 'number' || Number.isNaN(value) || value < 0 || (value === 0 && !zeroAllowed)) {
|
|
208
|
+
throw new errors_js_1.ConfigError('The option "' + name + '" must be a ' + (zeroAllowed ? 'non-negative' : 'positive') + ' number');
|
|
209
|
+
}
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
function retries(value, fallback) {
|
|
213
|
+
if (value === undefined)
|
|
214
|
+
return fallback;
|
|
215
|
+
if (!Number.isInteger(value) || value < 0) {
|
|
216
|
+
throw new errors_js_1.ConfigError('The option "maxRetries" must be a non-negative integer');
|
|
217
|
+
}
|
|
218
|
+
return value;
|
|
219
|
+
}
|
|
220
|
+
class HeaderBag {
|
|
221
|
+
#map = new Map();
|
|
222
|
+
set(name, value) {
|
|
223
|
+
if (value.includes('\r') || value.includes('\n') || value.includes('\0') || !/^[!#$%&'*+.^_|~0-9A-Za-z-]+$/.test(name)) {
|
|
224
|
+
throw new errors_js_1.ValidationError('The header "' + name.replace(/[^ -~]/g, '?') + '" has an invalid name or value');
|
|
225
|
+
}
|
|
226
|
+
this.#map.set(name.toLowerCase(), [name, value]);
|
|
227
|
+
}
|
|
228
|
+
delete(name) {
|
|
229
|
+
this.#map.delete(name.toLowerCase());
|
|
230
|
+
}
|
|
231
|
+
has(name) {
|
|
232
|
+
return this.#map.has(name.toLowerCase());
|
|
233
|
+
}
|
|
234
|
+
toRecord() {
|
|
235
|
+
const out = {};
|
|
236
|
+
for (const [name, value] of this.#map.values())
|
|
237
|
+
out[name] = value;
|
|
238
|
+
return out;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* A promise of a decoded response that also gives access to the raw response:
|
|
243
|
+
* `await client.companies.get(id)` yields the data, `.withResponse()` adds status, headers,
|
|
244
|
+
* request id and rate-limit information of that very response.
|
|
245
|
+
*/
|
|
246
|
+
class APIPromise extends Promise {
|
|
247
|
+
#result;
|
|
248
|
+
constructor(result) {
|
|
249
|
+
super((resolve) => {
|
|
250
|
+
resolve(undefined);
|
|
251
|
+
});
|
|
252
|
+
this.#result = result;
|
|
253
|
+
}
|
|
254
|
+
/** The decoded data together with the status, headers, request id and rate limit of the response. */
|
|
255
|
+
withResponse() {
|
|
256
|
+
return this.#result;
|
|
257
|
+
}
|
|
258
|
+
/** Only the status, headers, request id and rate limit of the response. */
|
|
259
|
+
asResponse() {
|
|
260
|
+
return this.#result.then((r) => r.response);
|
|
261
|
+
}
|
|
262
|
+
then(onfulfilled, onrejected) {
|
|
263
|
+
return this.#result.then((r) => r.data).then(onfulfilled, onrejected);
|
|
264
|
+
}
|
|
265
|
+
catch(onrejected) {
|
|
266
|
+
return this.#result.then((r) => r.data).catch(onrejected);
|
|
267
|
+
}
|
|
268
|
+
finally(onfinally) {
|
|
269
|
+
return this.#result.then((r) => r.data).finally(onfinally);
|
|
270
|
+
}
|
|
271
|
+
static get [Symbol.species]() {
|
|
272
|
+
return Promise;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
exports.APIPromise = APIPromise;
|
|
276
|
+
/**
|
|
277
|
+
* A promise of an open stream that can also be iterated directly:
|
|
278
|
+
* `for await (const event of client.feed.listEvents(co))`. Awaiting it gives the stream object
|
|
279
|
+
* (with `response`, `close()` and, for chat streams, `dialogId` and `turnNo`).
|
|
280
|
+
*/
|
|
281
|
+
class StreamPromise extends Promise {
|
|
282
|
+
#stream;
|
|
283
|
+
constructor(stream) {
|
|
284
|
+
super((resolve) => {
|
|
285
|
+
resolve(undefined);
|
|
286
|
+
});
|
|
287
|
+
this.#stream = stream;
|
|
288
|
+
}
|
|
289
|
+
then(onfulfilled, onrejected) {
|
|
290
|
+
return this.#stream.then(onfulfilled, onrejected);
|
|
291
|
+
}
|
|
292
|
+
catch(onrejected) {
|
|
293
|
+
return this.#stream.catch(onrejected);
|
|
294
|
+
}
|
|
295
|
+
finally(onfinally) {
|
|
296
|
+
return this.#stream.finally(onfinally);
|
|
297
|
+
}
|
|
298
|
+
async *[Symbol.asyncIterator]() {
|
|
299
|
+
const stream = await this.#stream;
|
|
300
|
+
yield* stream;
|
|
301
|
+
}
|
|
302
|
+
static get [Symbol.species]() {
|
|
303
|
+
return Promise;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
exports.StreamPromise = StreamPromise;
|
|
307
|
+
/**
|
|
308
|
+
* The HTTP engine shared by all resources: configuration, authentication, retries, timeouts,
|
|
309
|
+
* cancellation and decoding. It is immutable after construction and safe to share.
|
|
310
|
+
*/
|
|
311
|
+
class APIClient {
|
|
312
|
+
/** Base URL without a trailing slash. */
|
|
313
|
+
baseUrl;
|
|
314
|
+
/** Default request timeout in milliseconds. */
|
|
315
|
+
timeout;
|
|
316
|
+
/** Default timeout of non-streaming chat turns in milliseconds. */
|
|
317
|
+
longRunningTimeout;
|
|
318
|
+
/** Default number of retries. */
|
|
319
|
+
maxRetries;
|
|
320
|
+
/** Default idle timeout of streams in milliseconds. */
|
|
321
|
+
streamIdleTimeout;
|
|
322
|
+
#apiKey;
|
|
323
|
+
#webhookSecret;
|
|
324
|
+
#fetch;
|
|
325
|
+
#defaultHeaders;
|
|
326
|
+
#bearer;
|
|
327
|
+
#logger;
|
|
328
|
+
constructor(options = {}) {
|
|
329
|
+
const baseUrl = (options.baseUrl ?? readEnv('TUNGO_BASE_URL') ?? exports.DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
330
|
+
let parsed;
|
|
331
|
+
try {
|
|
332
|
+
parsed = new URL(baseUrl);
|
|
333
|
+
}
|
|
334
|
+
catch (cause) {
|
|
335
|
+
throw new errors_js_1.ConfigError('The base URL is not a valid absolute URL', { cause });
|
|
336
|
+
}
|
|
337
|
+
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
|
338
|
+
throw new errors_js_1.ConfigError('The base URL must start with https:// or http://');
|
|
339
|
+
}
|
|
340
|
+
if (parsed.search !== '' || parsed.hash !== '' || parsed.username !== '' || parsed.password !== '') {
|
|
341
|
+
throw new errors_js_1.ConfigError('The base URL must not contain credentials, a query string or a fragment');
|
|
342
|
+
}
|
|
343
|
+
this.baseUrl = baseUrl;
|
|
344
|
+
this.timeout = positive(options.timeout, exports.DEFAULT_TIMEOUT, 'timeout', false);
|
|
345
|
+
this.longRunningTimeout = positive(options.longRunningTimeout, exports.DEFAULT_LONG_RUNNING_TIMEOUT, 'longRunningTimeout', false);
|
|
346
|
+
this.streamIdleTimeout = positive(options.streamIdleTimeout, exports.DEFAULT_STREAM_IDLE_TIMEOUT, 'streamIdleTimeout', true);
|
|
347
|
+
this.maxRetries = retries(options.maxRetries, exports.DEFAULT_MAX_RETRIES);
|
|
348
|
+
const apiKey = options.apiKey ?? readEnv('TUNGO_API_KEY');
|
|
349
|
+
this.#apiKey = apiKey === '' ? undefined : apiKey;
|
|
350
|
+
const webhookSecret = options.webhookSecret ?? readEnv('TUNGO_WEBHOOK_SECRET');
|
|
351
|
+
this.#webhookSecret = webhookSecret === '' ? undefined : webhookSecret;
|
|
352
|
+
this.#bearer = options.authScheme === 'bearer';
|
|
353
|
+
this.#defaultHeaders = { ...(options.defaultHeaders ?? {}) };
|
|
354
|
+
this.#logger = options.logger;
|
|
355
|
+
if (options.fetch !== undefined) {
|
|
356
|
+
this.#fetch = options.fetch;
|
|
357
|
+
}
|
|
358
|
+
else if (typeof globalThis.fetch === 'function') {
|
|
359
|
+
this.#fetch = (input, init) => globalThis.fetch(input, init);
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
throw new errors_js_1.ConfigError('This runtime has no global fetch: pass a fetch implementation in the "fetch" option');
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/** The webhook secret to use: the explicit one, else the client's; a ConfigError when there is none. */
|
|
366
|
+
webhookSecret(explicit) {
|
|
367
|
+
const secret = explicit ?? this.#webhookSecret;
|
|
368
|
+
if (secret === undefined || secret === '') {
|
|
369
|
+
throw new errors_js_1.ConfigError('No webhook secret: pass one or set the TUNGO_WEBHOOK_SECRET environment variable');
|
|
370
|
+
}
|
|
371
|
+
return secret;
|
|
372
|
+
}
|
|
373
|
+
/** Performs a request and decodes the JSON response. */
|
|
374
|
+
request(spec) {
|
|
375
|
+
return new APIPromise(this.#requestJSON(spec));
|
|
376
|
+
}
|
|
377
|
+
/** Opens a server-sent event stream; `make` wraps the connection into the stream object. */
|
|
378
|
+
openStream(spec, make) {
|
|
379
|
+
return this.#exchange(spec, true).then((x) => make({
|
|
380
|
+
response: x.info,
|
|
381
|
+
body: x.response.body,
|
|
382
|
+
controller: x.controller,
|
|
383
|
+
signal: spec.options?.signal ?? undefined,
|
|
384
|
+
detach: x.detach,
|
|
385
|
+
idleTimeout: positive(spec.options?.streamIdleTimeout, this.streamIdleTimeout, 'streamIdleTimeout', true),
|
|
386
|
+
route: spec.method.toUpperCase() + ' ' + spec.path,
|
|
387
|
+
}));
|
|
388
|
+
}
|
|
389
|
+
async #requestJSON(spec) {
|
|
390
|
+
const x = await this.#exchange(spec, false);
|
|
391
|
+
const status = x.info.status;
|
|
392
|
+
if (spec.emptyResult === true || status === 204 || status === 205) {
|
|
393
|
+
return { data: undefined, response: x.info };
|
|
394
|
+
}
|
|
395
|
+
const route = spec.method.toUpperCase() + ' ' + spec.path;
|
|
396
|
+
if (x.text.trim() === '') {
|
|
397
|
+
throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + status + ') has an empty body where JSON was expected', {
|
|
398
|
+
status,
|
|
399
|
+
requestId: x.info.requestId,
|
|
400
|
+
body: x.text,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
try {
|
|
404
|
+
return { data: (0, json_js_1.parseJSON)(x.text), response: x.info };
|
|
405
|
+
}
|
|
406
|
+
catch (cause) {
|
|
407
|
+
throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + status + ') is not valid JSON', {
|
|
408
|
+
status,
|
|
409
|
+
requestId: x.info.requestId,
|
|
410
|
+
body: x.text,
|
|
411
|
+
cause,
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
#headers(spec, stream) {
|
|
416
|
+
const options = spec.options ?? {};
|
|
417
|
+
const bag = new HeaderBag();
|
|
418
|
+
bag.set('Accept', stream ? 'text/event-stream' : 'application/json');
|
|
419
|
+
bag.set('User-Agent', USER_AGENT);
|
|
420
|
+
if (spec.rawBody !== undefined) {
|
|
421
|
+
bag.set('Content-Type', spec.contentType ?? 'application/octet-stream');
|
|
422
|
+
}
|
|
423
|
+
else if (spec.body !== undefined) {
|
|
424
|
+
bag.set('Content-Type', 'application/json');
|
|
425
|
+
}
|
|
426
|
+
for (const [name, value] of Object.entries(this.#defaultHeaders))
|
|
427
|
+
bag.set(name, value);
|
|
428
|
+
for (const [name, value] of Object.entries(spec.headers ?? {})) {
|
|
429
|
+
if (value !== undefined)
|
|
430
|
+
bag.set(name, value);
|
|
431
|
+
}
|
|
432
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) {
|
|
433
|
+
if (value === null)
|
|
434
|
+
bag.delete(name);
|
|
435
|
+
else if (value !== undefined)
|
|
436
|
+
bag.set(name, value);
|
|
437
|
+
}
|
|
438
|
+
// Credentials go only to operations that require the API key.
|
|
439
|
+
bag.delete('x-api-key');
|
|
440
|
+
bag.delete('authorization');
|
|
441
|
+
if ((spec.auth ?? 'key') === 'key') {
|
|
442
|
+
const key = this.#apiKey;
|
|
443
|
+
if (key === undefined) {
|
|
444
|
+
throw new errors_js_1.ConfigError('No API key: pass "apiKey" to the client or set the TUNGO_API_KEY environment variable');
|
|
445
|
+
}
|
|
446
|
+
if (this.#bearer)
|
|
447
|
+
bag.set('Authorization', 'Bearer ' + key);
|
|
448
|
+
else
|
|
449
|
+
bag.set('x-api-key', key);
|
|
450
|
+
}
|
|
451
|
+
const headerName = spec.idempotencyHeader ?? 'Idempotency-Key';
|
|
452
|
+
if (options.idempotencyKey !== undefined) {
|
|
453
|
+
if (options.idempotencyKey === '')
|
|
454
|
+
throw new errors_js_1.ValidationError('The idempotency key must not be empty');
|
|
455
|
+
bag.set(headerName, options.idempotencyKey);
|
|
456
|
+
}
|
|
457
|
+
else if (spec.idempotencyHeader !== undefined && !bag.has(headerName)) {
|
|
458
|
+
bag.set(headerName, uuid4());
|
|
459
|
+
}
|
|
460
|
+
return { headers: bag.toRecord(), hasIdempotencyKey: bag.has(headerName) };
|
|
461
|
+
}
|
|
462
|
+
#log(event) {
|
|
463
|
+
const logger = this.#logger;
|
|
464
|
+
if (logger === undefined)
|
|
465
|
+
return;
|
|
466
|
+
try {
|
|
467
|
+
logger(event);
|
|
468
|
+
}
|
|
469
|
+
catch {
|
|
470
|
+
// A failing logger must not break the request.
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Fetches without ever following a redirect: the request carries the API key in a custom
|
|
475
|
+
* header, which no HTTP client strips when a redirect leads to another host. A 3xx answer is
|
|
476
|
+
* returned as it is and becomes an APIError with that status.
|
|
477
|
+
*/
|
|
478
|
+
async #fetchNoRedirect(url, init) {
|
|
479
|
+
const res = await this.#fetch(url, init);
|
|
480
|
+
if (res.type === 'opaqueredirect') {
|
|
481
|
+
// Browsers hide the status and the headers of a redirect fetched with redirect: 'manual'.
|
|
482
|
+
throw new errors_js_1.ConnectionError('The API answered with a redirect, which is never followed');
|
|
483
|
+
}
|
|
484
|
+
return res;
|
|
485
|
+
}
|
|
486
|
+
async #exchange(spec, stream) {
|
|
487
|
+
const options = spec.options ?? {};
|
|
488
|
+
const signal = options.signal ?? undefined;
|
|
489
|
+
const method = spec.method.toUpperCase();
|
|
490
|
+
const route = method + ' ' + spec.path;
|
|
491
|
+
if (signal !== undefined && signal.aborted)
|
|
492
|
+
throw abortError(signal, 'The request ' + route);
|
|
493
|
+
const query = buildQuery(spec.query);
|
|
494
|
+
const url = this.baseUrl + buildPath(spec.path, spec.pathParams) + (query === '' ? '' : '?' + query);
|
|
495
|
+
const { headers, hasIdempotencyKey } = this.#headers(spec, stream);
|
|
496
|
+
let body;
|
|
497
|
+
if (spec.rawBody !== undefined)
|
|
498
|
+
body = spec.rawBody;
|
|
499
|
+
else if (spec.body !== undefined)
|
|
500
|
+
body = (0, json_js_1.stringifyJSON)(spec.body);
|
|
501
|
+
const maxRetries = retries(options.maxRetries, this.maxRetries);
|
|
502
|
+
const timeout = positive(options.timeout, spec.longRunning === true ? this.longRunningTimeout : this.timeout, 'timeout', false);
|
|
503
|
+
for (let attempt = 0;; attempt++) {
|
|
504
|
+
const controller = new AbortController();
|
|
505
|
+
let timedOut = false;
|
|
506
|
+
// No timer at all for an unlimited timeout (see MAX_TIMER_MS).
|
|
507
|
+
const timer = startTimer(() => {
|
|
508
|
+
timedOut = true;
|
|
509
|
+
controller.abort();
|
|
510
|
+
}, timeout);
|
|
511
|
+
const onAbort = () => {
|
|
512
|
+
controller.abort();
|
|
513
|
+
};
|
|
514
|
+
const detach = () => {
|
|
515
|
+
if (signal !== undefined)
|
|
516
|
+
signal.removeEventListener('abort', onAbort);
|
|
517
|
+
};
|
|
518
|
+
if (signal !== undefined)
|
|
519
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
520
|
+
const started = Date.now();
|
|
521
|
+
let keepOpen = false;
|
|
522
|
+
let failure;
|
|
523
|
+
let cause;
|
|
524
|
+
let retryAfter = null;
|
|
525
|
+
this.#log({ kind: 'request', method, route: spec.path, attempt: attempt + 1 });
|
|
526
|
+
try {
|
|
527
|
+
const init = { method, headers, signal: controller.signal, redirect: 'manual' };
|
|
528
|
+
if (body !== undefined)
|
|
529
|
+
init.body = body;
|
|
530
|
+
const response = await this.#fetchNoRedirect(url, init);
|
|
531
|
+
const requestId = response.headers.get('x-request-id');
|
|
532
|
+
const info = {
|
|
533
|
+
status: response.status,
|
|
534
|
+
headers: response.headers,
|
|
535
|
+
requestId: requestId === '' ? null : requestId,
|
|
536
|
+
rateLimit: (0, errors_js_1.parseRateLimit)(response.headers),
|
|
537
|
+
attempts: attempt + 1,
|
|
538
|
+
};
|
|
539
|
+
if (response.status >= 200 && response.status < 300) {
|
|
540
|
+
if (stream) {
|
|
541
|
+
const contentType = (response.headers.get('content-type') ?? '').trim().toLowerCase();
|
|
542
|
+
if (!contentType.startsWith('text/event-stream')) {
|
|
543
|
+
// Not an event stream (a proxy page, a JSON body): reading it as one would yield
|
|
544
|
+
// zero events and look like a turn that produced nothing.
|
|
545
|
+
const unexpected = await response.text();
|
|
546
|
+
const shown = contentType === '' ? 'missing' : '"' + contentType.replace(/[^ -~]/g, '?').slice(0, 100) + '"';
|
|
547
|
+
throw new errors_js_1.DecodeError('The response of ' + route + ' (status ' + response.status + ') is not an event stream: its content type is ' + shown, {
|
|
548
|
+
status: response.status,
|
|
549
|
+
requestId: info.requestId,
|
|
550
|
+
body: unexpected,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
keepOpen = true;
|
|
554
|
+
clearTimeout(timer);
|
|
555
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
556
|
+
return { info, text: '', response, controller, detach };
|
|
557
|
+
}
|
|
558
|
+
const text = await response.text();
|
|
559
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
560
|
+
return { info, text, response, controller, detach };
|
|
561
|
+
}
|
|
562
|
+
const text = await response.text();
|
|
563
|
+
this.#log({ kind: 'response', method, route: spec.path, attempt: attempt + 1, status: info.status, durationMs: Date.now() - started, requestId: info.requestId });
|
|
564
|
+
const apiError = (0, errors_js_1.apiErrorFromResponse)(response.status, response.headers, text);
|
|
565
|
+
failure = apiError;
|
|
566
|
+
cause = response.status;
|
|
567
|
+
retryAfter = apiError.retryAfter;
|
|
568
|
+
}
|
|
569
|
+
catch (reason) {
|
|
570
|
+
if (signal !== undefined && signal.aborted)
|
|
571
|
+
throw abortError(signal, 'The request ' + route);
|
|
572
|
+
if (reason instanceof errors_js_1.TungoError)
|
|
573
|
+
throw reason;
|
|
574
|
+
if (timedOut) {
|
|
575
|
+
failure = new errors_js_1.TimeoutError('The request ' + route + ' timed out after ' + timeout + ' ms', timeout, { cause: reason });
|
|
576
|
+
cause = 'timeout';
|
|
577
|
+
}
|
|
578
|
+
else {
|
|
579
|
+
failure = new errors_js_1.ConnectionError('Could not reach the API for ' + route + ': ' + causeText(reason), { cause: reason });
|
|
580
|
+
cause = 'connection_error';
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
finally {
|
|
584
|
+
if (!keepOpen) {
|
|
585
|
+
clearTimeout(timer);
|
|
586
|
+
detach();
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
const retry = attempt < maxRetries && shouldRetry(method, hasIdempotencyKey, cause) && (retryAfter === null || retryAfter <= exports.MAX_RETRY_AFTER_SECONDS);
|
|
590
|
+
if (!retry) {
|
|
591
|
+
this.#log({ kind: 'error', method, route: spec.path, attempt: attempt + 1, error: failure });
|
|
592
|
+
throw failure;
|
|
593
|
+
}
|
|
594
|
+
// A delay of zero (also an HTTP-date that has already passed) is not an order to hammer the
|
|
595
|
+
// server at once: the computed backoff applies.
|
|
596
|
+
const delayMs = retryAfter !== null && retryAfter > 0 ? Math.ceil(retryAfter * 1000) : Math.round(backoffDelay(attempt));
|
|
597
|
+
const event = { kind: 'retry', method, route: spec.path, attempt: attempt + 1, delayMs, error: failure };
|
|
598
|
+
if (failure instanceof errors_js_1.APIError && failure.status !== undefined)
|
|
599
|
+
event.status = failure.status;
|
|
600
|
+
this.#log(event);
|
|
601
|
+
await sleep(delayMs, signal);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
exports.APIClient = APIClient;
|