@meistrari/tela-sdk-js 0.0.3 → 1.0.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/dist/index.cjs ADDED
@@ -0,0 +1,1303 @@
1
+ 'use strict';
2
+
3
+ const changeCase = require('change-case');
4
+ const micromatch = require('micromatch');
5
+
6
+ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
7
+
8
+ function _interopNamespaceCompat(e) {
9
+ if (e && typeof e === 'object' && 'default' in e) return e;
10
+ const n = Object.create(null);
11
+ if (e) {
12
+ for (const k in e) {
13
+ n[k] = e[k];
14
+ }
15
+ }
16
+ n.default = e;
17
+ return n;
18
+ }
19
+
20
+ const changeCase__namespace = /*#__PURE__*/_interopNamespaceCompat(changeCase);
21
+ const micromatch__default = /*#__PURE__*/_interopDefaultCompat(micromatch);
22
+
23
+ const version = "1.0.0";
24
+
25
+ var __defProp$5 = Object.defineProperty;
26
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
27
+ var __publicField$5 = (obj, key, value) => {
28
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
29
+ return value;
30
+ };
31
+ class TelaError extends Error {
32
+ }
33
+ class ConflictApiKeyAndJWTError extends TelaError {
34
+ constructor() {
35
+ super("You must provide either an API key or a JWT, but not both");
36
+ }
37
+ }
38
+ class MissingApiKeyOrJWTError extends TelaError {
39
+ constructor() {
40
+ super("You must provide an API key or a JWT");
41
+ }
42
+ }
43
+ class EmptyFileError extends TelaError {
44
+ constructor() {
45
+ super("File cannot be empty");
46
+ }
47
+ }
48
+ class InvalidFileURL extends TelaError {
49
+ constructor(url) {
50
+ super(`Invalid file URL: ${url}`);
51
+ }
52
+ }
53
+ class FileUploadError extends TelaError {
54
+ constructor(message) {
55
+ super(`Failed to upload file: ${message}`);
56
+ }
57
+ }
58
+ class APIError extends TelaError {
59
+ constructor(statusCode, error, _message) {
60
+ const message = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : _message;
61
+ super(message);
62
+ __publicField$5(this, "statusCode");
63
+ __publicField$5(this, "error");
64
+ this.statusCode = statusCode;
65
+ this.error = error;
66
+ }
67
+ static from(statusCode, responseError, message) {
68
+ if (!statusCode) {
69
+ return new ConnectionError({
70
+ message,
71
+ cause: toError(responseError)
72
+ });
73
+ }
74
+ const error = responseError;
75
+ if (error.status === 400) {
76
+ return new BadRequestError(statusCode, error, message);
77
+ }
78
+ if (error.status === 401) {
79
+ return new AuthenticationError(statusCode, error, message);
80
+ }
81
+ if (error.status === 403) {
82
+ return new AuthorizationError(statusCode, error, message);
83
+ }
84
+ if (error.status === 404) {
85
+ return new NotFoundError(statusCode, error, message);
86
+ }
87
+ if (error.status === 409) {
88
+ return new ConflictError(statusCode, error, message);
89
+ }
90
+ if (error.status === 422) {
91
+ return new UnprocessableEntityError(statusCode, error, message);
92
+ }
93
+ if (error.status === 429) {
94
+ return new RateLimitError(statusCode, error, message);
95
+ }
96
+ if (error.status >= 500) {
97
+ return new InternalServerError(statusCode, error, message);
98
+ }
99
+ return new APIError(statusCode, error, message);
100
+ }
101
+ }
102
+ class UserAbortError extends APIError {
103
+ constructor({ message } = {}) {
104
+ super(void 0, void 0, message || "User aborted.");
105
+ __publicField$5(this, "statusCode");
106
+ }
107
+ }
108
+ class ConnectionError extends APIError {
109
+ constructor({
110
+ message,
111
+ cause
112
+ }) {
113
+ super(void 0, void 0, message || "Connection error.");
114
+ __publicField$5(this, "statusCode");
115
+ if (cause)
116
+ this.cause = cause;
117
+ }
118
+ }
119
+ class ConnectionTimeout extends APIError {
120
+ constructor({
121
+ message
122
+ } = {}) {
123
+ super(void 0, void 0, message || "Request timed out.");
124
+ __publicField$5(this, "statusCode");
125
+ }
126
+ }
127
+ class BadRequestError extends APIError {
128
+ constructor() {
129
+ super(...arguments);
130
+ __publicField$5(this, "statusCode", 400);
131
+ }
132
+ // todo: handle validation errors from zod/typebox
133
+ }
134
+ class AuthenticationError extends APIError {
135
+ constructor() {
136
+ super(...arguments);
137
+ __publicField$5(this, "statusCode", 401);
138
+ }
139
+ }
140
+ class AuthorizationError extends APIError {
141
+ constructor() {
142
+ super(...arguments);
143
+ __publicField$5(this, "statusCode", 403);
144
+ }
145
+ }
146
+ class NotFoundError extends APIError {
147
+ constructor() {
148
+ super(...arguments);
149
+ __publicField$5(this, "statusCode", 404);
150
+ }
151
+ }
152
+ class ConflictError extends APIError {
153
+ constructor() {
154
+ super(...arguments);
155
+ __publicField$5(this, "statusCode", 409);
156
+ }
157
+ }
158
+ class UnprocessableEntityError extends APIError {
159
+ constructor() {
160
+ super(...arguments);
161
+ // todo: check if tela returns 400 or 422 for zod errors
162
+ __publicField$5(this, "statusCode", 422);
163
+ }
164
+ }
165
+ class RateLimitError extends APIError {
166
+ constructor() {
167
+ super(...arguments);
168
+ __publicField$5(this, "statusCode", 429);
169
+ }
170
+ }
171
+ class InternalServerError extends APIError {
172
+ constructor() {
173
+ super(...arguments);
174
+ __publicField$5(this, "statusCode", 500);
175
+ }
176
+ }
177
+ function toError(err) {
178
+ if (err instanceof Error)
179
+ return err;
180
+ if (typeof err === "object" && err !== null) {
181
+ try {
182
+ return new Error(JSON.stringify(err));
183
+ } catch {
184
+ }
185
+ }
186
+ return new Error(err);
187
+ }
188
+
189
+ const DEFAULT_FIELDS_TRANSFORMATION_EXCLUSIONS = [
190
+ // Inputs
191
+ "variables.*(!(*fileUrl))",
192
+ "override.structuredOutput.schema.properties.*",
193
+ "override.functions.*.parameters.properties.*",
194
+ // Outputs
195
+ "choices.*.message.content.*",
196
+ "choices.*.message.function_call.arguments.*",
197
+ "choices.*.message.tool_calls.*.function.arguments.*",
198
+ "message.content.*",
199
+ "message.function_call.arguments.*",
200
+ "message.tool_calls.*.function.arguments.*",
201
+ "message.structured_content.*",
202
+ "input_content.variables.*",
203
+ "input_content.variables.*(!(*file_url))",
204
+ "input_content.messages.*.function_call.arguments.*",
205
+ "output_content.tool_calls.*.arguments.*",
206
+ "output_content.content.*",
207
+ "raw_input.override.structured_output.schema.properties.*",
208
+ "raw_input.override.functions.*.parameters.properties.*"
209
+ ];
210
+
211
+ function isExcluded(path, exclusions) {
212
+ return exclusions.some((pattern) => {
213
+ const isMatch = micromatch__default.isMatch(path, pattern);
214
+ return isMatch;
215
+ });
216
+ }
217
+ function transformObjectFromCamelCaseToSnakeCase(obj, exclusions = []) {
218
+ const result = Array.isArray(obj) ? [] : {};
219
+ const stack = [
220
+ { source: obj, target: result, path: "" }
221
+ ];
222
+ while (stack.length > 0) {
223
+ const { source, target, path } = stack.pop();
224
+ if (Array.isArray(source)) {
225
+ source.forEach((item, index) => {
226
+ const newPath = path ? `${path}.*` : "*";
227
+ if (Array.isArray(item) || typeof item === "object" && item !== null) {
228
+ target[index] = Array.isArray(item) ? [] : {};
229
+ stack.push({ source: item, target: target[index], path: newPath });
230
+ } else {
231
+ target[index] = item;
232
+ }
233
+ });
234
+ } else if (typeof source === "object" && source !== null) {
235
+ for (const [key, value] of Object.entries(source)) {
236
+ const newPath = path ? `${path}.${key}` : key;
237
+ const snakeKey = isExcluded(newPath, exclusions) ? key : changeCase__namespace.snakeCase(key);
238
+ if (Array.isArray(value) || typeof value === "object" && value !== null) {
239
+ target[snakeKey] = Array.isArray(value) ? [] : {};
240
+ stack.push({ source: value, target: target[snakeKey], path: newPath });
241
+ } else {
242
+ target[snakeKey] = value;
243
+ }
244
+ }
245
+ }
246
+ }
247
+ return result;
248
+ }
249
+ function transformObjectFromSnakeCaseToCamelCase(obj, exclusions = []) {
250
+ const result = Array.isArray(obj) ? [] : {};
251
+ const stack = [
252
+ { source: obj, target: result, path: "" }
253
+ ];
254
+ while (stack.length > 0) {
255
+ const { source, target, path } = stack.pop();
256
+ if (Array.isArray(source)) {
257
+ source.forEach((item, index) => {
258
+ const newPath = path ? `${path}.*` : "*";
259
+ if (Array.isArray(item) || typeof item === "object" && item !== null) {
260
+ target[index] = Array.isArray(item) ? [] : {};
261
+ stack.push({ source: item, target: target[index], path: newPath });
262
+ } else {
263
+ target[index] = item;
264
+ }
265
+ });
266
+ } else if (typeof source === "object" && source !== null) {
267
+ for (const [key, value] of Object.entries(source)) {
268
+ const newPath = path ? `${path}.${key}` : key;
269
+ const camelKey = isExcluded(newPath, exclusions) ? key : changeCase__namespace.camelCase(key);
270
+ if (Array.isArray(value) || typeof value === "object" && value !== null) {
271
+ target[camelKey] = Array.isArray(value) ? [] : {};
272
+ stack.push({ source: value, target: target[camelKey], path: newPath });
273
+ } else {
274
+ target[camelKey] = value;
275
+ }
276
+ }
277
+ }
278
+ }
279
+ return result;
280
+ }
281
+
282
+ var __defProp$4 = Object.defineProperty;
283
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
284
+ var __publicField$4 = (obj, key, value) => {
285
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
286
+ return value;
287
+ };
288
+ class Stream {
289
+ /**
290
+ * Creates a new Stream instance.
291
+ *
292
+ * @param iterator - A function that returns an AsyncIterator<Item>.
293
+ * @param controller - The AbortController for this stream.
294
+ */
295
+ constructor(iterator, controller) {
296
+ this.iterator = iterator;
297
+ /**
298
+ * The AbortController associated with this stream.
299
+ */
300
+ __publicField$4(this, "controller");
301
+ this.controller = controller;
302
+ }
303
+ /**
304
+ * Creates a Stream from a server-sent events (SSE) Response.
305
+ *
306
+ * @param response - The Response object containing the SSE data.
307
+ * @param controller - The AbortController for this stream.
308
+ * @returns A new Stream instance.
309
+ * @throws {Error} If the stream is consumed more than once.
310
+ * @throws {APIError} If the SSE data contains an error.
311
+ */
312
+ static fromSSEResponse(response, controller) {
313
+ let consumed = false;
314
+ async function* iterator() {
315
+ if (consumed) {
316
+ throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
317
+ }
318
+ consumed = true;
319
+ let done = false;
320
+ try {
321
+ for await (const sse of _iterSSEMessages(response, controller)) {
322
+ if (done)
323
+ continue;
324
+ if (sse.data.startsWith("[DONE]")) {
325
+ done = true;
326
+ continue;
327
+ }
328
+ if (sse.event === null) {
329
+ let data;
330
+ try {
331
+ data = JSON.parse(sse.data);
332
+ data = transformObjectFromSnakeCaseToCamelCase(data, DEFAULT_FIELDS_TRANSFORMATION_EXCLUSIONS);
333
+ } catch (e) {
334
+ console.error(`Could not parse message into JSON:`, sse.data);
335
+ console.error(`From chunk:`, sse.raw);
336
+ throw e;
337
+ }
338
+ if (data && data.error) {
339
+ throw new APIError(void 0, data.error, void 0);
340
+ }
341
+ yield data;
342
+ } else {
343
+ let data;
344
+ try {
345
+ data = JSON.parse(sse.data);
346
+ } catch (e) {
347
+ console.error(`Could not parse message into JSON:`, sse.data);
348
+ console.error(`From chunk:`, sse.raw);
349
+ throw e;
350
+ }
351
+ if (sse.event === "error") {
352
+ throw new APIError(void 0, data.error, data.message);
353
+ }
354
+ yield { event: sse.event, data };
355
+ }
356
+ }
357
+ done = true;
358
+ } catch (e) {
359
+ if (e instanceof Error && e.name === "AbortError")
360
+ return;
361
+ throw e;
362
+ } finally {
363
+ if (!done)
364
+ controller.abort();
365
+ }
366
+ }
367
+ return new Stream(iterator, controller);
368
+ }
369
+ /**
370
+ * Creates a Stream from a newline-separated ReadableStream where each item is a JSON value.
371
+ *
372
+ * @param readableStream - The ReadableStream containing newline-separated JSON data.
373
+ * @param controller - The AbortController for this stream.
374
+ * @returns A new Stream instance.
375
+ * @throws {Error} If the stream is consumed more than once.
376
+ */
377
+ static fromReadableStream(readableStream, controller) {
378
+ let consumed = false;
379
+ async function* iterLines() {
380
+ const lineDecoder = new LineDecoder();
381
+ const iter = readableStreamAsyncIterable(readableStream);
382
+ for await (const chunk of iter) {
383
+ for (const line of lineDecoder.decode(chunk)) {
384
+ yield line;
385
+ }
386
+ }
387
+ for (const line of lineDecoder.flush()) {
388
+ yield line;
389
+ }
390
+ }
391
+ async function* iterator() {
392
+ if (consumed) {
393
+ throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
394
+ }
395
+ consumed = true;
396
+ let done = false;
397
+ try {
398
+ for await (const line of iterLines()) {
399
+ if (done)
400
+ continue;
401
+ if (line)
402
+ yield JSON.parse(line);
403
+ }
404
+ done = true;
405
+ } catch (e) {
406
+ if (e instanceof Error && e.name === "AbortError")
407
+ return;
408
+ throw e;
409
+ } finally {
410
+ if (!done)
411
+ controller.abort();
412
+ }
413
+ }
414
+ return new Stream(iterator, controller);
415
+ }
416
+ /**
417
+ * Implements the AsyncIterable interface, allowing the Stream to be used in a for-await-of loop.
418
+ *
419
+ * @returns An AsyncIterator for the stream items.
420
+ */
421
+ [Symbol.asyncIterator]() {
422
+ return this.iterator();
423
+ }
424
+ /**
425
+ * Splits the stream into two streams which can be independently read from at different speeds.
426
+ *
427
+ * @returns A tuple containing two new Stream instances.
428
+ */
429
+ tee() {
430
+ const left = [];
431
+ const right = [];
432
+ const iterator = this.iterator();
433
+ const teeIterator = (queue) => {
434
+ return {
435
+ next: () => {
436
+ if (queue.length === 0) {
437
+ const result = iterator.next();
438
+ left.push(result);
439
+ right.push(result);
440
+ }
441
+ return queue.shift();
442
+ }
443
+ };
444
+ };
445
+ return [
446
+ new Stream(() => teeIterator(left), this.controller),
447
+ new Stream(() => teeIterator(right), this.controller)
448
+ ];
449
+ }
450
+ /**
451
+ * Converts this stream to a newline-separated ReadableStream of JSON stringified values.
452
+ * The resulting stream can be converted back to a Stream using `Stream.fromReadableStream()`.
453
+ *
454
+ * @returns A ReadableStream containing newline-separated JSON data.
455
+ */
456
+ toReadableStream() {
457
+ const self = this;
458
+ let iter;
459
+ const encoder = new TextEncoder();
460
+ return new ReadableStream({
461
+ async start() {
462
+ iter = self[Symbol.asyncIterator]();
463
+ },
464
+ async pull(ctrl) {
465
+ try {
466
+ const { value, done } = await iter.next();
467
+ if (done)
468
+ return ctrl.close();
469
+ const bytes = encoder.encode(`${JSON.stringify(value)}
470
+ `);
471
+ ctrl.enqueue(bytes);
472
+ } catch (err) {
473
+ ctrl.error(err);
474
+ }
475
+ },
476
+ async cancel() {
477
+ await iter.return?.();
478
+ }
479
+ });
480
+ }
481
+ }
482
+ async function* _iterSSEMessages(response, controller) {
483
+ if (!response.body) {
484
+ controller.abort();
485
+ throw new TelaError(`Attempted to iterate over a response with no body`);
486
+ }
487
+ const sseDecoder = new SSEDecoder();
488
+ const lineDecoder = new LineDecoder();
489
+ const iter = readableStreamAsyncIterable(response.body);
490
+ for await (const sseChunk of iterSSEChunks(iter)) {
491
+ for (const line of lineDecoder.decode(sseChunk)) {
492
+ const sse = sseDecoder.decode(line);
493
+ if (sse)
494
+ yield sse;
495
+ }
496
+ }
497
+ for (const line of lineDecoder.flush()) {
498
+ const sse = sseDecoder.decode(line);
499
+ if (sse)
500
+ yield sse;
501
+ }
502
+ }
503
+ async function* iterSSEChunks(iterator) {
504
+ let data = new Uint8Array();
505
+ for await (const chunk of iterator) {
506
+ if (chunk == null) {
507
+ continue;
508
+ }
509
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) : typeof chunk === "string" ? new TextEncoder().encode(chunk) : chunk;
510
+ const newData = new Uint8Array(data.length + binaryChunk.length);
511
+ newData.set(data);
512
+ newData.set(binaryChunk, data.length);
513
+ data = newData;
514
+ let patternIndex = findDoubleNewlineIndex(data);
515
+ while (patternIndex !== -1) {
516
+ yield data.slice(0, patternIndex);
517
+ data = data.slice(patternIndex);
518
+ patternIndex = findDoubleNewlineIndex(data);
519
+ }
520
+ }
521
+ if (data.length > 0) {
522
+ yield data;
523
+ }
524
+ }
525
+ function findDoubleNewlineIndex(buffer) {
526
+ const newline = 10;
527
+ const carriage = 13;
528
+ for (let i = 0; i < buffer.length - 2; i++) {
529
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
530
+ return i + 2;
531
+ }
532
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
533
+ return i + 2;
534
+ }
535
+ if (buffer[i] === carriage && buffer[i + 1] === newline && i + 3 < buffer.length && buffer[i + 2] === carriage && buffer[i + 3] === newline) {
536
+ return i + 4;
537
+ }
538
+ }
539
+ return -1;
540
+ }
541
+ class SSEDecoder {
542
+ constructor() {
543
+ __publicField$4(this, "data");
544
+ __publicField$4(this, "event");
545
+ __publicField$4(this, "chunks");
546
+ this.event = null;
547
+ this.data = [];
548
+ this.chunks = [];
549
+ }
550
+ decode(line) {
551
+ if (line.endsWith("\r")) {
552
+ line = line.substring(0, line.length - 1);
553
+ }
554
+ if (!line) {
555
+ if (!this.event && !this.data.length)
556
+ return null;
557
+ const sse = {
558
+ event: this.event,
559
+ data: this.data.join("\n"),
560
+ raw: this.chunks
561
+ };
562
+ this.event = null;
563
+ this.data = [];
564
+ this.chunks = [];
565
+ return sse;
566
+ }
567
+ this.chunks.push(line);
568
+ if (line.startsWith(":")) {
569
+ return null;
570
+ }
571
+ let [fieldname, _, value] = partition(line, ":");
572
+ if (value.startsWith(" ")) {
573
+ value = value.substring(1);
574
+ }
575
+ if (fieldname === "event") {
576
+ this.event = value;
577
+ } else if (fieldname === "data") {
578
+ this.data.push(value);
579
+ }
580
+ return null;
581
+ }
582
+ }
583
+ const _LineDecoder = class _LineDecoder {
584
+ // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types.
585
+ constructor() {
586
+ __publicField$4(this, "buffer");
587
+ __publicField$4(this, "trailingCR");
588
+ __publicField$4(this, "textDecoder");
589
+ this.buffer = [];
590
+ this.trailingCR = false;
591
+ }
592
+ decode(chunk) {
593
+ let text = this.decodeText(chunk);
594
+ if (this.trailingCR) {
595
+ text = `\r${text}`;
596
+ this.trailingCR = false;
597
+ }
598
+ if (text.endsWith("\r")) {
599
+ this.trailingCR = true;
600
+ text = text.slice(0, -1);
601
+ }
602
+ if (!text) {
603
+ return [];
604
+ }
605
+ const trailingNewline = _LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || "");
606
+ let lines = text.split(_LineDecoder.NEWLINE_REGEXP);
607
+ if (trailingNewline) {
608
+ lines.pop();
609
+ }
610
+ if (lines.length === 1 && !trailingNewline) {
611
+ this.buffer.push(lines[0]);
612
+ return [];
613
+ }
614
+ if (this.buffer.length > 0) {
615
+ lines = [this.buffer.join("") + lines[0], ...lines.slice(1)];
616
+ this.buffer = [];
617
+ }
618
+ if (!trailingNewline) {
619
+ this.buffer = [lines.pop() || ""];
620
+ }
621
+ return lines;
622
+ }
623
+ decodeText(bytes) {
624
+ if (bytes == null)
625
+ return "";
626
+ if (typeof bytes === "string")
627
+ return bytes;
628
+ if (typeof Buffer !== "undefined") {
629
+ if (bytes instanceof Buffer) {
630
+ return bytes.toString();
631
+ }
632
+ if (bytes instanceof Uint8Array) {
633
+ return Buffer.from(bytes).toString();
634
+ }
635
+ throw new TelaError(
636
+ `Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`
637
+ );
638
+ }
639
+ if (typeof TextDecoder !== "undefined") {
640
+ if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {
641
+ this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8"));
642
+ return this.textDecoder.decode(bytes);
643
+ }
644
+ throw new TelaError(
645
+ `Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`
646
+ );
647
+ }
648
+ throw new TelaError(
649
+ `Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`
650
+ );
651
+ }
652
+ flush() {
653
+ if (!this.buffer.length && !this.trailingCR) {
654
+ return [];
655
+ }
656
+ const lines = [this.buffer.join("")];
657
+ this.buffer = [];
658
+ this.trailingCR = false;
659
+ return lines;
660
+ }
661
+ };
662
+ // prettier-ignore
663
+ __publicField$4(_LineDecoder, "NEWLINE_CHARS", /* @__PURE__ */ new Set(["\n", "\r"]));
664
+ __publicField$4(_LineDecoder, "NEWLINE_REGEXP", /\r\n|[\n\r]/g);
665
+ let LineDecoder = _LineDecoder;
666
+ function partition(str, delimiter) {
667
+ const index = str.indexOf(delimiter);
668
+ if (index !== -1) {
669
+ return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
670
+ }
671
+ return [str, "", ""];
672
+ }
673
+ function readableStreamAsyncIterable(stream) {
674
+ if (stream[Symbol.asyncIterator])
675
+ return stream;
676
+ const reader = stream.getReader();
677
+ return {
678
+ async next() {
679
+ try {
680
+ const result = await reader.read();
681
+ if (result?.done)
682
+ reader.releaseLock();
683
+ return result;
684
+ } catch (e) {
685
+ reader.releaseLock();
686
+ throw e;
687
+ }
688
+ },
689
+ async return() {
690
+ const cancelPromise = reader.cancel();
691
+ reader.releaseLock();
692
+ await cancelPromise;
693
+ return { done: true, value: void 0 };
694
+ },
695
+ [Symbol.asyncIterator]() {
696
+ return this;
697
+ }
698
+ };
699
+ }
700
+
701
+ var __defProp$3 = Object.defineProperty;
702
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
703
+ var __publicField$3 = (obj, key, value) => {
704
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
705
+ return value;
706
+ };
707
+ async function defaultParseResponse(props) {
708
+ const { response } = props;
709
+ if (props.options.stream) {
710
+ debug("response", response.status, response.url, response.headers, response.body);
711
+ return Stream.fromSSEResponse(response, props.controller);
712
+ }
713
+ if (response.status === 204) {
714
+ return null;
715
+ }
716
+ const contentType = response.headers.get("content-type");
717
+ const isJSON = contentType?.includes("application/json") || contentType?.includes("application/vnd.api+json");
718
+ if (isJSON) {
719
+ const json = await response.json();
720
+ debug("response", response.status, response.url, response.headers, json);
721
+ return transformObjectFromSnakeCaseToCamelCase(json, DEFAULT_FIELDS_TRANSFORMATION_EXCLUSIONS);
722
+ }
723
+ const text = await response.text();
724
+ debug("response", response.status, response.url, response.headers, text);
725
+ return text;
726
+ }
727
+ class BaseClient {
728
+ constructor({ baseURL, maxRetries = 5, timeout = 0 }) {
729
+ __publicField$3(this, "baseURL");
730
+ __publicField$3(this, "maxRetries");
731
+ __publicField$3(this, "timeout");
732
+ __publicField$3(this, "fetch");
733
+ this.baseURL = baseURL;
734
+ this.maxRetries = validateMaxRetries(maxRetries);
735
+ this.timeout = validateTimeout(timeout);
736
+ this.fetch = fetch;
737
+ }
738
+ createHeaders(opts) {
739
+ const headers = new Headers();
740
+ headers.set("Accept", "application/json");
741
+ headers.set("Content-Type", "application/json");
742
+ headers.set("User-Agent", this.getUserAgent());
743
+ for (const [key, value] of Object.entries(this.getAuthHeaders())) {
744
+ headers.set(key, value);
745
+ }
746
+ for (const [key, value] of Object.entries(opts ?? {})) {
747
+ headers.set(key, value);
748
+ }
749
+ return headers;
750
+ }
751
+ getUserAgent() {
752
+ return `tela-sdk-node/${version}`;
753
+ }
754
+ getAuthHeaders() {
755
+ return {};
756
+ }
757
+ get(path, opts) {
758
+ return this.methodRequest("GET", path, opts);
759
+ }
760
+ post(path, opts) {
761
+ return this.methodRequest("POST", path, opts);
762
+ }
763
+ put(path, opts) {
764
+ return this.methodRequest("PUT", path, opts);
765
+ }
766
+ patch(path, opts) {
767
+ return this.methodRequest("PATCH", path, opts);
768
+ }
769
+ delete(path, opts) {
770
+ return this.methodRequest("DELETE", path, opts);
771
+ }
772
+ async methodRequest(method, path, opts) {
773
+ const headers = this.createHeaders();
774
+ debug("methodRequest", method, path, opts);
775
+ const transformedQuery = opts?.query ? transformObjectFromCamelCaseToSnakeCase(opts.query, DEFAULT_FIELDS_TRANSFORMATION_EXCLUSIONS) : void 0;
776
+ const transformedBody = opts?.body ? transformObjectFromCamelCaseToSnakeCase(opts.body, DEFAULT_FIELDS_TRANSFORMATION_EXCLUSIONS) : void 0;
777
+ const { response, options, controller } = await this.request({
778
+ method,
779
+ path,
780
+ headers,
781
+ ...opts,
782
+ query: transformedQuery,
783
+ body: transformedBody
784
+ });
785
+ return defaultParseResponse({ response, options, controller });
786
+ }
787
+ async request(options, remainingRetries = null) {
788
+ return this.makeRequest(options, remainingRetries);
789
+ }
790
+ async makeRequest(options, remainingRetries = null) {
791
+ if (remainingRetries === null) {
792
+ remainingRetries = options.maxRetries ?? this.maxRetries;
793
+ }
794
+ const { req, url, timeout } = this.buildRequest(options);
795
+ if (options.signal?.aborted) {
796
+ throw new UserAbortError();
797
+ }
798
+ const controller = new AbortController();
799
+ const response = await this.fetchWithTimeout(
800
+ url,
801
+ req,
802
+ timeout,
803
+ controller
804
+ ).catch(toError);
805
+ if (response instanceof Error) {
806
+ debug("fetchWithTimeout error", response);
807
+ if (options.signal?.aborted) {
808
+ throw new UserAbortError();
809
+ }
810
+ if (remainingRetries) {
811
+ return this.retryRequest(options, remainingRetries);
812
+ }
813
+ if (response.name === "AbortError") {
814
+ throw new ConnectionTimeout();
815
+ }
816
+ throw new ConnectionError({ cause: response });
817
+ }
818
+ const responseHeaders = createResponseHeaders(response.headers);
819
+ if (!response.ok) {
820
+ if (remainingRetries && this.shouldRetry(response)) {
821
+ debug("shouldRetry", `Retrying ${remainingRetries} more times`);
822
+ return this.retryRequest(
823
+ options,
824
+ remainingRetries,
825
+ responseHeaders
826
+ );
827
+ }
828
+ const errorText = await response.text().catch((e) => toError(e).message);
829
+ const errorJSON = safeJSONParse(errorText);
830
+ const errorMessage = errorJSON ? void 0 : errorText;
831
+ const error = APIError.from(response.status, errorJSON, errorMessage);
832
+ debug("APIError", error);
833
+ throw error;
834
+ }
835
+ return { response, options, controller };
836
+ }
837
+ shouldRetry(response) {
838
+ const shouldRetryHeader = response.headers.get("x-should-retry");
839
+ if (shouldRetryHeader === "true")
840
+ return true;
841
+ if (shouldRetryHeader === "false")
842
+ return false;
843
+ if (response.status === 408)
844
+ return true;
845
+ if (response.status === 409)
846
+ return true;
847
+ if (response.status === 429)
848
+ return true;
849
+ if (response.status >= 500)
850
+ return true;
851
+ return false;
852
+ }
853
+ async retryRequest(options, retriesRemaining, responseHeaders) {
854
+ let timeoutMillis;
855
+ const retryAfterMillisHeader = responseHeaders?.get("retry-after-ms");
856
+ if (retryAfterMillisHeader) {
857
+ const timeoutMs = Number.parseFloat(retryAfterMillisHeader);
858
+ if (!Number.isNaN(timeoutMs)) {
859
+ timeoutMillis = timeoutMs;
860
+ }
861
+ }
862
+ const retryAfterHeader = responseHeaders?.get("retry-after");
863
+ if (retryAfterHeader && !timeoutMillis) {
864
+ const timeoutSeconds = Number.parseFloat(retryAfterHeader);
865
+ if (!Number.isNaN(timeoutSeconds)) {
866
+ timeoutMillis = timeoutSeconds * 1e3;
867
+ } else {
868
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
869
+ }
870
+ }
871
+ if (!(timeoutMillis && timeoutMillis >= 0 && timeoutMillis < 60 * 1e3)) {
872
+ const maxRetries = options.maxRetries ?? this.maxRetries;
873
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(
874
+ retriesRemaining,
875
+ maxRetries
876
+ );
877
+ }
878
+ await sleep(timeoutMillis);
879
+ return this.makeRequest(options, retriesRemaining - 1);
880
+ }
881
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
882
+ const initialRetryDelay = 0.5;
883
+ const maxRetryDelay = 25;
884
+ const numRetries = maxRetries - retriesRemaining;
885
+ const sleepSeconds = Math.min(
886
+ initialRetryDelay * 2 ** numRetries,
887
+ maxRetryDelay
888
+ );
889
+ const jitter = 1 - Math.random() * 0.25;
890
+ return sleepSeconds * jitter * 1e3;
891
+ }
892
+ async fetchWithTimeout(url, _options, timeout, controller) {
893
+ const { signal, ...options } = _options || {};
894
+ if (signal) {
895
+ signal.addEventListener("abort", () => {
896
+ controller.abort();
897
+ });
898
+ }
899
+ let timeoutId;
900
+ if (timeout > 0) {
901
+ timeoutId = setTimeout(() => {
902
+ debug("fetchWithTimeout timeout");
903
+ controller.abort();
904
+ }, timeout);
905
+ }
906
+ debug("fetchWithTimeout", { url, options });
907
+ return this.fetch.call(void 0, url, {
908
+ signal: controller.signal,
909
+ ...options,
910
+ ...options.body ? { body: JSON.stringify(options.body) } : {}
911
+ }).finally(() => {
912
+ if (timeoutId) {
913
+ clearTimeout(timeoutId);
914
+ }
915
+ });
916
+ }
917
+ buildRequest(options) {
918
+ const { method, path, query, headers = {}, body } = options;
919
+ if ("timeout" in options && options.timeout !== void 0) {
920
+ validateTimeout(options.timeout);
921
+ }
922
+ const url = this.buildURL(path, query);
923
+ const req = {
924
+ method,
925
+ ...body && { body },
926
+ headers,
927
+ signal: options.signal ?? null
928
+ };
929
+ return {
930
+ req,
931
+ url,
932
+ timeout: options.timeout ?? this.timeout
933
+ };
934
+ }
935
+ buildURL(path, query) {
936
+ const startsWithSchemeRegexp = /^(?:[a-z]+:)?\/\//i;
937
+ const isAbsoluteURL = (url2) => {
938
+ return startsWithSchemeRegexp.test(url2);
939
+ };
940
+ const url = isAbsoluteURL(path) ? new URL(path) : new URL(
941
+ this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)
942
+ );
943
+ if (typeof query === "object" && query && !Array.isArray(query)) {
944
+ url.search = this.stringifyQuery(query);
945
+ }
946
+ return url.toString();
947
+ }
948
+ stringifyQuery(query) {
949
+ return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => {
950
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
951
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
952
+ }
953
+ if (value === null) {
954
+ return `${encodeURIComponent(key)}=`;
955
+ }
956
+ throw new TelaError(
957
+ `Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`
958
+ );
959
+ }).join("&");
960
+ }
961
+ }
962
+ function createResponseHeaders(headers) {
963
+ const headersFromResponse = new Headers();
964
+ for (const [key, value] of Object.entries(headers)) {
965
+ headersFromResponse.set(key, value);
966
+ }
967
+ return headersFromResponse;
968
+ }
969
+ function validateMaxRetries(maxRetries) {
970
+ if (maxRetries < 0) {
971
+ throw new TelaError("Max retries must be a non-negative integer");
972
+ }
973
+ return maxRetries;
974
+ }
975
+ function validateTimeout(timeout) {
976
+ if (timeout < 0) {
977
+ throw new TelaError("Timeout must be a non-negative integer");
978
+ }
979
+ return timeout;
980
+ }
981
+ function sleep(ms) {
982
+ return new Promise((resolve) => setTimeout(resolve, ms));
983
+ }
984
+ function safeJSONParse(text) {
985
+ try {
986
+ return JSON.parse(text);
987
+ } catch {
988
+ return text;
989
+ }
990
+ }
991
+ function debug(action, ...args) {
992
+ if (typeof process !== "undefined" && process?.env?.DEBUG === "true") {
993
+ console.log(`TelaSDK:DEBUG:${action}`, ...args);
994
+ }
995
+ }
996
+
997
+ async function getStreamSize(stream) {
998
+ let size = 0;
999
+ const reader = stream.getReader();
1000
+ while (true) {
1001
+ const { done, value } = await reader.read();
1002
+ if (done)
1003
+ break;
1004
+ size += value.length;
1005
+ }
1006
+ return size;
1007
+ }
1008
+
1009
+ var __defProp$2 = Object.defineProperty;
1010
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1011
+ var __publicField$2 = (obj, key, value) => {
1012
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1013
+ return value;
1014
+ };
1015
+ class TelaFile {
1016
+ /**
1017
+ * Creates an instance of `TelaFile`.
1018
+ *
1019
+ * @param file - The source of the file. Can be a URL string, Uint8Array, ReadableStream, ReadStream, Blob, or File.
1020
+ * @param options - Optional configuration options such as byte range.
1021
+ * @throws {InvalidFileURL} If the provided URL is not valid.
1022
+ * @throws {EmptyFileError} If the provided file is empty.
1023
+ */
1024
+ constructor(file, options) {
1025
+ __publicField$2(this, "_file");
1026
+ __publicField$2(this, "_options");
1027
+ __publicField$2(this, "_size", null);
1028
+ this._file = file;
1029
+ this._options = options;
1030
+ this.validateFile();
1031
+ }
1032
+ /**
1033
+ * Retrieves the options provided during instantiation.
1034
+ *
1035
+ * @returns The `TelaFileOptions` or an empty object if none were provided.
1036
+ */
1037
+ get options() {
1038
+ return this._options || {};
1039
+ }
1040
+ /**
1041
+ * Determines whether the file source is a valid URL.
1042
+ *
1043
+ * @returns `true` if the file source is a valid URL string, otherwise `false`.
1044
+ */
1045
+ get isURL() {
1046
+ return typeof this._file === "string" && this.isValidURL(this._file);
1047
+ }
1048
+ /**
1049
+ * Gets the size of the file in bytes.
1050
+ *
1051
+ * @returns The size of the file if available, otherwise `null`.
1052
+ */
1053
+ get size() {
1054
+ return this._size;
1055
+ }
1056
+ /**
1057
+ * Retrieves the content of the file in a format suitable for uploading.
1058
+ *
1059
+ * - If the file is a URL, it returns the URL string.
1060
+ * - If the file is a `Uint8Array`, it converts it to a `File` object.
1061
+ * - If the file is a `ReadStream` or `ReadableStream`, it calculates the size and returns a stream.
1062
+ *
1063
+ * @returns A promise that resolves to the uploadable content.
1064
+ */
1065
+ async getUploadableContent() {
1066
+ if (this.isURL && typeof this._file === "string") {
1067
+ return this._file;
1068
+ }
1069
+ if (this._file instanceof Uint8Array) {
1070
+ return new File([this._file], "file", {
1071
+ type: "application/octet-stream"
1072
+ });
1073
+ }
1074
+ if (this._file instanceof ReadableStream) {
1075
+ const [sizeStream, contentStream] = this._file.tee();
1076
+ this._size = await getStreamSize(sizeStream);
1077
+ return contentStream;
1078
+ }
1079
+ return this._file;
1080
+ }
1081
+ /**
1082
+ * Validates the provided file based on its type.
1083
+ *
1084
+ * @throws {InvalidFileURL} If the file is a string but not a valid URL.
1085
+ * @throws {EmptyFileError} If the file is empty.
1086
+ */
1087
+ validateFile() {
1088
+ if (typeof this._file === "string") {
1089
+ if (!this.isValidURL(this._file)) {
1090
+ throw new InvalidFileURL(this._file);
1091
+ }
1092
+ }
1093
+ if (this._file instanceof Uint8Array) {
1094
+ if (this._file.length === 0) {
1095
+ throw new EmptyFileError();
1096
+ }
1097
+ }
1098
+ if (this._file instanceof Blob || this._file instanceof File) {
1099
+ if (this._file.size === 0) {
1100
+ throw new EmptyFileError();
1101
+ }
1102
+ }
1103
+ }
1104
+ /**
1105
+ * Checks if the provided string is a valid URL.
1106
+ *
1107
+ * @param url - The URL string to validate.
1108
+ * @returns `true` if the URL is valid, otherwise `false`.
1109
+ */
1110
+ isValidURL(url) {
1111
+ try {
1112
+ new URL(url);
1113
+ return true;
1114
+ } catch {
1115
+ return false;
1116
+ }
1117
+ }
1118
+ }
1119
+ function createTelaFile(file, options) {
1120
+ return new TelaFile(file, options);
1121
+ }
1122
+
1123
+ var __defProp$1 = Object.defineProperty;
1124
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1125
+ var __publicField$1 = (obj, key, value) => {
1126
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1127
+ return value;
1128
+ };
1129
+ class Resource {
1130
+ constructor(client) {
1131
+ __publicField$1(this, "_client");
1132
+ this._client = client;
1133
+ }
1134
+ }
1135
+
1136
+ class ChatCompletions extends Resource {
1137
+ async create(body, opts) {
1138
+ const processedBody = { ...body };
1139
+ if (body.variables) {
1140
+ const processedVariables = {};
1141
+ for await (const [key, value] of Object.entries(body.variables)) {
1142
+ if (value instanceof TelaFile) {
1143
+ const fileWithUrl = await this.uploadFile(value);
1144
+ processedVariables[key] = fileWithUrl;
1145
+ } else {
1146
+ processedVariables[key] = value;
1147
+ }
1148
+ }
1149
+ processedBody.variables = processedVariables;
1150
+ }
1151
+ return this._client.post("/v2/chat/completions", {
1152
+ body: processedBody,
1153
+ ...opts,
1154
+ stream: body.stream ?? false
1155
+ });
1156
+ }
1157
+ /**
1158
+ * Uploads a file and returns its URL and options.
1159
+ *
1160
+ * This is used internally to handle file uploads associated with chat completions.
1161
+ *
1162
+ * @param file - The TelaFile to be uploaded.
1163
+ * @returns A Promise that resolves to an object containing the file URL and options.
1164
+ * @throws {FileUploadError} If the file upload fails.
1165
+ *
1166
+ * @example
1167
+ * ```typescript
1168
+ * const file = new TelaFile({ /* file options *\/ });
1169
+ * const uploadedFile = await this.uploadFile(file);
1170
+ * console.log(uploadedFile.file_url);
1171
+ * ```
1172
+ */
1173
+ async uploadFile(file) {
1174
+ const content = await file.getUploadableContent();
1175
+ if (file.isURL && typeof content === "string") {
1176
+ return { fileUrl: content, options: file.options };
1177
+ }
1178
+ const response = await this._client.post(
1179
+ "/v2/file"
1180
+ );
1181
+ const { uploadUrl, downloadUrl } = response;
1182
+ let contentType = "application/octet-stream";
1183
+ if (content instanceof File || content instanceof Blob) {
1184
+ contentType = content.type;
1185
+ }
1186
+ const uploadResponse = await fetch(uploadUrl, {
1187
+ method: "PUT",
1188
+ body: content,
1189
+ headers: {
1190
+ "Content-Type": contentType,
1191
+ ...file.size ? { "Content-Length": file.size.toString() } : {}
1192
+ },
1193
+ // @ts-expect-error: duplex is not supported
1194
+ duplex: "half"
1195
+ });
1196
+ if (!uploadResponse.ok) {
1197
+ throw new FileUploadError(await uploadResponse.text());
1198
+ }
1199
+ return { fileUrl: downloadUrl, options: file.options };
1200
+ }
1201
+ }
1202
+
1203
+ var __defProp = Object.defineProperty;
1204
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1205
+ var __publicField = (obj, key, value) => {
1206
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1207
+ return value;
1208
+ };
1209
+ const baseUrl = "https://api.tela.com";
1210
+ const _TelaSDK = class _TelaSDK extends BaseClient {
1211
+ /**
1212
+ * Creates a new instance of the TelaSDK.
1213
+ */
1214
+ constructor({ baseURL = baseUrl, apiKey, jwt, ...rest }) {
1215
+ super({ baseURL, ...rest });
1216
+ __publicField(this, "opts");
1217
+ __publicField(this, "apiKey");
1218
+ __publicField(this, "jwt");
1219
+ /**
1220
+ * The ChatCompletions resource for interacting with Tela's chat completion API.
1221
+ *
1222
+ * Use this to generate chat completions based on provided messages.
1223
+ *
1224
+ * @example
1225
+ * ```typescript
1226
+ * const completion = await tela.completions.create({
1227
+ * canvasId: "your-canvas-id",
1228
+ * messages: [{ role: "user", content: "Hello!" }],
1229
+ * });
1230
+ * ```
1231
+ */
1232
+ __publicField(this, "completions", new ChatCompletions(this));
1233
+ /**
1234
+ * Creates a new `TelaFile` instance from the provided file input.
1235
+ *
1236
+ * @param file - The file input to create a `TelaFile` instance from.
1237
+ * @returns A new `TelaFile` instance.
1238
+ */
1239
+ __publicField(this, "createFile", createTelaFile.bind(this));
1240
+ this.opts = { baseURL, ...rest };
1241
+ this.apiKey = apiKey;
1242
+ this.jwt = jwt;
1243
+ this.validateAuth();
1244
+ }
1245
+ validateAuth() {
1246
+ if (!this.apiKey && !this.jwt) {
1247
+ throw new MissingApiKeyOrJWTError();
1248
+ }
1249
+ if (this.apiKey && this.jwt) {
1250
+ throw new ConflictApiKeyAndJWTError();
1251
+ }
1252
+ }
1253
+ getAuthHeaders() {
1254
+ return {
1255
+ Authorization: `Bearer ${this.apiKey || this.jwt}`
1256
+ };
1257
+ }
1258
+ };
1259
+ __publicField(_TelaSDK, "TelaSDK", _TelaSDK);
1260
+ __publicField(_TelaSDK, "DEFAULT_TIMEOUT", 0);
1261
+ // Error classes
1262
+ /** Thrown when an API request fails. */
1263
+ __publicField(_TelaSDK, "APIError", APIError);
1264
+ /** Thrown when a request is aborted by the user. */
1265
+ __publicField(_TelaSDK, "UserAbortError", UserAbortError);
1266
+ /** Thrown when there's a network connection error. */
1267
+ __publicField(_TelaSDK, "ConnectionError", ConnectionError);
1268
+ /** Thrown when a request times out. */
1269
+ __publicField(_TelaSDK, "ConnectionTimeout", ConnectionTimeout);
1270
+ /** Thrown when the API returns a 400 Bad Request error. */
1271
+ __publicField(_TelaSDK, "BadRequestError", BadRequestError);
1272
+ /** Thrown when authentication fails (e.g., invalid API key). */
1273
+ __publicField(_TelaSDK, "AuthenticationError", AuthenticationError);
1274
+ /** Thrown when the authenticated user doesn't have permission for the requested operation. */
1275
+ __publicField(_TelaSDK, "AuthorizationError", AuthorizationError);
1276
+ /** Thrown when the requested resource is not found. */
1277
+ __publicField(_TelaSDK, "NotFoundError", NotFoundError);
1278
+ /** Thrown when there's a conflict with the current state of the resource. */
1279
+ __publicField(_TelaSDK, "ConflictError", ConflictError);
1280
+ /** Thrown when the request is well-formed but unable to be processed due to semantic errors. */
1281
+ __publicField(_TelaSDK, "UnprocessableEntityError", UnprocessableEntityError);
1282
+ /** Thrown when the API rate limit is exceeded. */
1283
+ __publicField(_TelaSDK, "RateLimitError", RateLimitError);
1284
+ /** Thrown when an unexpected server error occurs. */
1285
+ __publicField(_TelaSDK, "InternalServerError", InternalServerError);
1286
+ /** Thrown when attempting to upload an empty file. */
1287
+ __publicField(_TelaSDK, "EmptyFileError", EmptyFileError);
1288
+ /** Thrown when an invalid file URL is provided. */
1289
+ __publicField(_TelaSDK, "InvalidFileURL", InvalidFileURL);
1290
+ /** Thrown when there's an error during file upload. */
1291
+ __publicField(_TelaSDK, "FileUploadError", FileUploadError);
1292
+ /** Thrown when neither an API key nor a JWT is provided. */
1293
+ __publicField(_TelaSDK, "MissingApiKeyOrJWTError", MissingApiKeyOrJWTError);
1294
+ /** Thrown when both an API key and a JWT are provided. */
1295
+ __publicField(_TelaSDK, "ConflictApiKeyAndJWTError", ConflictApiKeyAndJWTError);
1296
+ let TelaSDK = _TelaSDK;
1297
+ function createTelaClient(opts) {
1298
+ return new TelaSDK(opts);
1299
+ }
1300
+
1301
+ exports.TelaFile = TelaFile;
1302
+ exports.TelaSDK = TelaSDK;
1303
+ exports.createTelaClient = createTelaClient;