@meistrari/tela-sdk-js 1.0.2 → 2.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.mjs CHANGED
@@ -1,12 +1,13 @@
1
1
  import * as changeCase from 'change-case';
2
2
  import { minimatch } from 'minimatch';
3
+ import z, { z as z$1, ZodError, string, number, boolean, object, array, any, unknown } from 'zod';
3
4
 
4
- const version = "1.0.2";
5
+ const version = "2.0.0";
5
6
 
6
- var __defProp$5 = Object.defineProperty;
7
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __publicField$5 = (obj, key, value) => {
9
- __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __defProp$7 = Object.defineProperty;
8
+ var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __publicField$7 = (obj, key, value) => {
10
+ __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
10
11
  return value;
11
12
  };
12
13
  class TelaError extends Error {
@@ -32,16 +33,35 @@ class InvalidFileURL extends TelaError {
32
33
  }
33
34
  }
34
35
  class FileUploadError extends TelaError {
36
+ constructor(message, statusCode) {
37
+ super(`Failed to upload file: ${message} (Status code: ${statusCode})`);
38
+ __publicField$7(this, "statusCode");
39
+ this.statusCode = statusCode;
40
+ }
41
+ }
42
+ class ExecutionNotStartedError extends TelaError {
43
+ constructor() {
44
+ super("Execution has not started yet");
45
+ }
46
+ }
47
+ class InvalidExecutionModeError extends TelaError {
35
48
  constructor(message) {
36
- super(`Failed to upload file: ${message}`);
49
+ super(message);
50
+ }
51
+ }
52
+ class ExecutionFailedError extends TelaError {
53
+ constructor(rawOutput) {
54
+ super(`Execution failed: ${JSON.stringify(rawOutput)}`);
55
+ __publicField$7(this, "rawOutput");
56
+ this.rawOutput = rawOutput;
37
57
  }
38
58
  }
39
59
  class APIError extends TelaError {
40
60
  constructor(statusCode, error, _message) {
41
61
  const message = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : _message;
42
62
  super(message);
43
- __publicField$5(this, "statusCode");
44
- __publicField$5(this, "error");
63
+ __publicField$7(this, "statusCode");
64
+ __publicField$7(this, "error");
45
65
  this.statusCode = statusCode;
46
66
  this.error = error;
47
67
  }
@@ -83,7 +103,7 @@ class APIError extends TelaError {
83
103
  class UserAbortError extends APIError {
84
104
  constructor({ message } = {}) {
85
105
  super(void 0, void 0, message || "User aborted.");
86
- __publicField$5(this, "statusCode");
106
+ __publicField$7(this, "statusCode");
87
107
  }
88
108
  }
89
109
  class ConnectionError extends APIError {
@@ -92,7 +112,7 @@ class ConnectionError extends APIError {
92
112
  cause
93
113
  }) {
94
114
  super(void 0, void 0, message || "Connection error.");
95
- __publicField$5(this, "statusCode");
115
+ __publicField$7(this, "statusCode");
96
116
  if (cause)
97
117
  this.cause = cause;
98
118
  }
@@ -102,57 +122,57 @@ class ConnectionTimeout extends APIError {
102
122
  message
103
123
  } = {}) {
104
124
  super(void 0, void 0, message || "Request timed out.");
105
- __publicField$5(this, "statusCode");
125
+ __publicField$7(this, "statusCode");
106
126
  }
107
127
  }
108
128
  class BadRequestError extends APIError {
109
129
  constructor() {
110
130
  super(...arguments);
111
- __publicField$5(this, "statusCode", 400);
131
+ __publicField$7(this, "statusCode", 400);
112
132
  }
113
133
  // todo: handle validation errors from zod/typebox
114
134
  }
115
135
  class AuthenticationError extends APIError {
116
136
  constructor() {
117
137
  super(...arguments);
118
- __publicField$5(this, "statusCode", 401);
138
+ __publicField$7(this, "statusCode", 401);
119
139
  }
120
140
  }
121
141
  class AuthorizationError extends APIError {
122
142
  constructor() {
123
143
  super(...arguments);
124
- __publicField$5(this, "statusCode", 403);
144
+ __publicField$7(this, "statusCode", 403);
125
145
  }
126
146
  }
127
147
  class NotFoundError extends APIError {
128
148
  constructor() {
129
149
  super(...arguments);
130
- __publicField$5(this, "statusCode", 404);
150
+ __publicField$7(this, "statusCode", 404);
131
151
  }
132
152
  }
133
153
  class ConflictError extends APIError {
134
154
  constructor() {
135
155
  super(...arguments);
136
- __publicField$5(this, "statusCode", 409);
156
+ __publicField$7(this, "statusCode", 409);
137
157
  }
138
158
  }
139
159
  class UnprocessableEntityError extends APIError {
140
160
  constructor() {
141
161
  super(...arguments);
142
162
  // todo: check if tela returns 400 or 422 for zod errors
143
- __publicField$5(this, "statusCode", 422);
163
+ __publicField$7(this, "statusCode", 422);
144
164
  }
145
165
  }
146
166
  class RateLimitError extends APIError {
147
167
  constructor() {
148
168
  super(...arguments);
149
- __publicField$5(this, "statusCode", 429);
169
+ __publicField$7(this, "statusCode", 429);
150
170
  }
151
171
  }
152
172
  class InternalServerError extends APIError {
153
173
  constructor() {
154
174
  super(...arguments);
155
- __publicField$5(this, "statusCode", 500);
175
+ __publicField$7(this, "statusCode", 500);
156
176
  }
157
177
  }
158
178
  function toError(err) {
@@ -264,10 +284,10 @@ function transformObjectFromSnakeCaseToCamelCase(obj, exclusions = []) {
264
284
  return result;
265
285
  }
266
286
 
267
- var __defProp$4 = Object.defineProperty;
268
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
269
- var __publicField$4 = (obj, key, value) => {
270
- __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
287
+ var __defProp$6 = Object.defineProperty;
288
+ var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
289
+ var __publicField$6 = (obj, key, value) => {
290
+ __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
271
291
  return value;
272
292
  };
273
293
  class Stream {
@@ -282,7 +302,7 @@ class Stream {
282
302
  /**
283
303
  * The AbortController associated with this stream.
284
304
  */
285
- __publicField$4(this, "controller");
305
+ __publicField$6(this, "controller");
286
306
  this.controller = controller;
287
307
  }
288
308
  /**
@@ -323,6 +343,10 @@ class Stream {
323
343
  if (data && data.error) {
324
344
  throw new APIError(void 0, data.error, void 0);
325
345
  }
346
+ data = data.message.content;
347
+ if (!data) {
348
+ continue;
349
+ }
326
350
  yield data;
327
351
  } else {
328
352
  let data;
@@ -336,6 +360,10 @@ class Stream {
336
360
  if (sse.event === "error") {
337
361
  throw new APIError(void 0, data.error, data.message);
338
362
  }
363
+ data = data.message.content;
364
+ if (!data) {
365
+ continue;
366
+ }
339
367
  yield { event: sse.event, data };
340
368
  }
341
369
  }
@@ -525,9 +553,9 @@ function findDoubleNewlineIndex(buffer) {
525
553
  }
526
554
  class SSEDecoder {
527
555
  constructor() {
528
- __publicField$4(this, "data");
529
- __publicField$4(this, "event");
530
- __publicField$4(this, "chunks");
556
+ __publicField$6(this, "data");
557
+ __publicField$6(this, "event");
558
+ __publicField$6(this, "chunks");
531
559
  this.event = null;
532
560
  this.data = [];
533
561
  this.chunks = [];
@@ -568,9 +596,9 @@ class SSEDecoder {
568
596
  const _LineDecoder = class _LineDecoder {
569
597
  // TextDecoder found in browsers; not typed to avoid pulling in either "dom" or "node" types.
570
598
  constructor() {
571
- __publicField$4(this, "buffer");
572
- __publicField$4(this, "trailingCR");
573
- __publicField$4(this, "textDecoder");
599
+ __publicField$6(this, "buffer");
600
+ __publicField$6(this, "trailingCR");
601
+ __publicField$6(this, "textDecoder");
574
602
  this.buffer = [];
575
603
  this.trailingCR = false;
576
604
  }
@@ -645,8 +673,8 @@ const _LineDecoder = class _LineDecoder {
645
673
  }
646
674
  };
647
675
  // prettier-ignore
648
- __publicField$4(_LineDecoder, "NEWLINE_CHARS", /* @__PURE__ */ new Set(["\n", "\r"]));
649
- __publicField$4(_LineDecoder, "NEWLINE_REGEXP", /\r\n|[\n\r]/g);
676
+ __publicField$6(_LineDecoder, "NEWLINE_CHARS", /* @__PURE__ */ new Set(["\n", "\r"]));
677
+ __publicField$6(_LineDecoder, "NEWLINE_REGEXP", /\r\n|[\n\r]/g);
650
678
  let LineDecoder = _LineDecoder;
651
679
  function partition(str, delimiter) {
652
680
  const index = str.indexOf(delimiter);
@@ -683,10 +711,10 @@ function readableStreamAsyncIterable(stream) {
683
711
  };
684
712
  }
685
713
 
686
- var __defProp$3 = Object.defineProperty;
687
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
688
- var __publicField$3 = (obj, key, value) => {
689
- __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
714
+ var __defProp$5 = Object.defineProperty;
715
+ var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
716
+ var __publicField$5 = (obj, key, value) => {
717
+ __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
690
718
  return value;
691
719
  };
692
720
  async function defaultParseResponse(props) {
@@ -711,10 +739,10 @@ async function defaultParseResponse(props) {
711
739
  }
712
740
  class BaseClient {
713
741
  constructor({ baseURL, maxRetries = 5, timeout = 0 }) {
714
- __publicField$3(this, "baseURL");
715
- __publicField$3(this, "maxRetries");
716
- __publicField$3(this, "timeout");
717
- __publicField$3(this, "fetch");
742
+ __publicField$5(this, "baseURL");
743
+ __publicField$5(this, "maxRetries");
744
+ __publicField$5(this, "timeout");
745
+ __publicField$5(this, "fetch");
718
746
  this.baseURL = baseURL;
719
747
  this.maxRetries = validateMaxRetries(maxRetries);
720
748
  this.timeout = validateTimeout(timeout);
@@ -736,9 +764,6 @@ class BaseClient {
736
764
  getUserAgent() {
737
765
  return `tela-sdk-node/${version}`;
738
766
  }
739
- getAuthHeaders() {
740
- return {};
741
- }
742
767
  get(path, opts) {
743
768
  return this.methodRequest("GET", path, opts);
744
769
  }
@@ -991,12 +1016,15 @@ async function getStreamSize(stream) {
991
1016
  return size;
992
1017
  }
993
1018
 
994
- var __defProp$2 = Object.defineProperty;
995
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
996
- var __publicField$2 = (obj, key, value) => {
997
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1019
+ var __defProp$4 = Object.defineProperty;
1020
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1021
+ var __publicField$4 = (obj, key, value) => {
1022
+ __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
998
1023
  return value;
999
1024
  };
1025
+ function TelaFileSchema() {
1026
+ return z.custom((value) => value instanceof TelaFile, { message: "Value must be an instance of TelaFile" }).meta({ isTelaFile: true });
1027
+ }
1000
1028
  class TelaFile {
1001
1029
  /**
1002
1030
  * Creates an instance of `TelaFile`.
@@ -1006,14 +1034,31 @@ class TelaFile {
1006
1034
  * @throws {InvalidFileURL} If the provided URL is not valid.
1007
1035
  * @throws {EmptyFileError} If the provided file is empty.
1008
1036
  */
1009
- constructor(file, options) {
1010
- __publicField$2(this, "_file");
1011
- __publicField$2(this, "_options");
1012
- __publicField$2(this, "_size", null);
1037
+ constructor(file, options = {}) {
1038
+ __publicField$4(this, "_file");
1039
+ __publicField$4(this, "_options");
1040
+ __publicField$4(this, "_size", null);
1041
+ __publicField$4(this, "_mimeType");
1042
+ __publicField$4(this, "_name");
1013
1043
  this._file = file;
1044
+ if (file instanceof File || file instanceof Blob) {
1045
+ this._size = file.size;
1046
+ }
1047
+ if (file instanceof File || file instanceof Blob) {
1048
+ this._mimeType = file.type;
1049
+ }
1050
+ if ("name" in options) {
1051
+ this._name = options.name;
1052
+ }
1053
+ if ("mimeType" in options) {
1054
+ this._mimeType = options.mimeType;
1055
+ }
1014
1056
  this._options = options;
1015
1057
  this.validateFile();
1016
1058
  }
1059
+ static create(file, options) {
1060
+ return new TelaFile(file, options);
1061
+ }
1017
1062
  /**
1018
1063
  * Retrieves the options provided during instantiation.
1019
1064
  *
@@ -1028,7 +1073,15 @@ class TelaFile {
1028
1073
  * @returns `true` if the file source is a valid URL string, otherwise `false`.
1029
1074
  */
1030
1075
  get isURL() {
1031
- return typeof this._file === "string" && this.isValidURL(this._file);
1076
+ return this.isValidURL(this._file);
1077
+ }
1078
+ /**
1079
+ * Determines whether the file source is a valid Vault reference.
1080
+ *
1081
+ * @returns `true` if the file source is a valid Vault reference, otherwise `false`.
1082
+ */
1083
+ get isVaultReference() {
1084
+ return this.isValidVaultReference(this._file);
1032
1085
  }
1033
1086
  /**
1034
1087
  * Gets the size of the file in bytes.
@@ -1038,6 +1091,22 @@ class TelaFile {
1038
1091
  get size() {
1039
1092
  return this._size;
1040
1093
  }
1094
+ /**
1095
+ * Gets the name of the file.
1096
+ *
1097
+ * @returns The name of the file if available, otherwise `null`.
1098
+ */
1099
+ get name() {
1100
+ return this._name ?? null;
1101
+ }
1102
+ /**
1103
+ * Gets the type of the file.
1104
+ *
1105
+ * @returns The type of the file if available, otherwise `null`.
1106
+ */
1107
+ get type() {
1108
+ return this._mimeType ?? null;
1109
+ }
1041
1110
  /**
1042
1111
  * Retrieves the content of the file in a format suitable for uploading.
1043
1112
  *
@@ -1048,11 +1117,11 @@ class TelaFile {
1048
1117
  * @returns A promise that resolves to the uploadable content.
1049
1118
  */
1050
1119
  async getUploadableContent() {
1051
- if (this.isURL && typeof this._file === "string") {
1120
+ if (this.isValidURL(this._file) || this.isValidVaultReference(this._file)) {
1052
1121
  return this._file;
1053
1122
  }
1054
1123
  if (this._file instanceof Uint8Array) {
1055
- return new File([this._file], "file", {
1124
+ return new File([this._file.buffer], "file", {
1056
1125
  type: "application/octet-stream"
1057
1126
  });
1058
1127
  }
@@ -1093,6 +1162,9 @@ class TelaFile {
1093
1162
  * @returns `true` if the URL is valid, otherwise `false`.
1094
1163
  */
1095
1164
  isValidURL(url) {
1165
+ if (typeof url !== "string") {
1166
+ return false;
1167
+ }
1096
1168
  try {
1097
1169
  new URL(url);
1098
1170
  return true;
@@ -1100,43 +1172,604 @@ class TelaFile {
1100
1172
  return false;
1101
1173
  }
1102
1174
  }
1175
+ /**
1176
+ * Checks if the provided string is a valid Vault reference.
1177
+ *
1178
+ * @param url - The Vault reference string to validate.
1179
+ * @returns `true` if the Vault reference is valid, otherwise `false`.
1180
+ */
1181
+ isValidVaultReference(url) {
1182
+ if (typeof url !== "string") {
1183
+ return false;
1184
+ }
1185
+ return url.startsWith("vault://");
1186
+ }
1103
1187
  }
1104
- function createTelaFile(file, options) {
1105
- return new TelaFile(file, options);
1188
+
1189
+ function compareSchemas(clientSchema, serverSchema, path = "$") {
1190
+ const mismatches = [];
1191
+ if (clientSchema.type !== serverSchema.type) {
1192
+ mismatches.push({
1193
+ path,
1194
+ issue: `Type mismatch: client has "${clientSchema.type}", server has "${serverSchema.type}"`
1195
+ });
1196
+ return mismatches;
1197
+ }
1198
+ if (clientSchema.type === "object") {
1199
+ const clientProps = clientSchema.properties || {};
1200
+ const serverProps = serverSchema.properties || {};
1201
+ const clientRequired = clientSchema.required || [];
1202
+ const serverRequired = serverSchema.required || [];
1203
+ for (const reqProp of serverRequired) {
1204
+ if (!clientProps[reqProp]) {
1205
+ mismatches.push({
1206
+ path: `${path}.${reqProp}`,
1207
+ issue: `Property is required on server but missing on client`
1208
+ });
1209
+ continue;
1210
+ }
1211
+ if (!clientRequired.includes(reqProp)) {
1212
+ mismatches.push({
1213
+ path: `${path}.${reqProp}`,
1214
+ issue: `Property is required on server but optional on client`
1215
+ });
1216
+ }
1217
+ }
1218
+ for (const clientProp of Object.keys(clientProps)) {
1219
+ if (!serverProps[clientProp]) {
1220
+ mismatches.push({
1221
+ path: `${path}.${clientProp}`,
1222
+ issue: `Extra property not expected by server`
1223
+ });
1224
+ }
1225
+ }
1226
+ for (const prop of Object.keys(serverProps)) {
1227
+ if (!clientProps[prop]) {
1228
+ continue;
1229
+ }
1230
+ const nestedMismatches = compareSchemas(
1231
+ clientProps[prop],
1232
+ serverProps[prop],
1233
+ `${path}.${prop}`
1234
+ );
1235
+ mismatches.push(...nestedMismatches);
1236
+ }
1237
+ }
1238
+ if (clientSchema.type === "array") {
1239
+ const clientItems = clientSchema.items;
1240
+ const serverItems = serverSchema.items;
1241
+ if (!clientItems || !serverItems) {
1242
+ if (clientItems !== serverItems) {
1243
+ mismatches.push({
1244
+ path: `${path}[]`,
1245
+ issue: `Array items schema mismatch: one side has items definition, other doesn't`
1246
+ });
1247
+ }
1248
+ return mismatches;
1249
+ }
1250
+ const itemMismatches = compareSchemas(
1251
+ clientItems,
1252
+ serverItems,
1253
+ `${path}[]`
1254
+ );
1255
+ mismatches.push(...itemMismatches);
1256
+ }
1257
+ return mismatches;
1258
+ }
1259
+ function mapServerTypeToJsonSchemaType(serverType) {
1260
+ const typeMap = {
1261
+ text: "string",
1262
+ number: "number",
1263
+ boolean: "boolean",
1264
+ file: "string",
1265
+ // z.file() generates type: "string" with format: "binary", contentEncoding: "binary"
1266
+ array: "array",
1267
+ object: "object"
1268
+ };
1269
+ return typeMap[serverType.toLowerCase()] || null;
1270
+ }
1271
+ function validateInputSchema(clientSchema, serverVariables) {
1272
+ const mismatches = [];
1273
+ const clientProps = clientSchema.properties || {};
1274
+ const clientRequired = clientSchema.required || [];
1275
+ for (const serverVar of serverVariables) {
1276
+ if (serverVar.required) {
1277
+ if (!clientProps[serverVar.name]) {
1278
+ mismatches.push({
1279
+ path: `$.${serverVar.name}`,
1280
+ issue: `Property is required on server but missing on client`
1281
+ });
1282
+ continue;
1283
+ }
1284
+ if (!clientRequired.includes(serverVar.name)) {
1285
+ mismatches.push({
1286
+ path: `$.${serverVar.name}`,
1287
+ issue: `Variable is required on server but optional on client`
1288
+ });
1289
+ }
1290
+ }
1291
+ if (!clientProps[serverVar.name]) {
1292
+ continue;
1293
+ }
1294
+ {
1295
+ const clientProp = clientProps[serverVar.name];
1296
+ const clientType = clientProp.type;
1297
+ const expectedType = mapServerTypeToJsonSchemaType(serverVar.type);
1298
+ if (serverVar.type.toLowerCase() === "file") {
1299
+ const isFileSchema = clientProp.isTelaFile;
1300
+ if (isFileSchema) {
1301
+ continue;
1302
+ }
1303
+ if (clientProp.format === "binary") {
1304
+ mismatches.push({
1305
+ path: `$.${serverVar.name}`,
1306
+ issue: `Type mismatch: file is expected to be a \`telaFile()\` but is a regular file instead.`
1307
+ });
1308
+ continue;
1309
+ }
1310
+ if (clientType === "string" && !clientProp.format && !clientProp.contentEncoding) {
1311
+ mismatches.push({
1312
+ path: `$.${serverVar.name}`,
1313
+ issue: `Type mismatch: server expects file, client has plain string. Did you mean to use \`telaFile()\`?`
1314
+ });
1315
+ continue;
1316
+ }
1317
+ mismatches.push({
1318
+ path: `$.${serverVar.name}`,
1319
+ issue: `Type mismatch: server expects file, client has "${clientType}"`
1320
+ });
1321
+ continue;
1322
+ }
1323
+ if (expectedType && clientType !== expectedType) {
1324
+ mismatches.push({
1325
+ path: `$.${serverVar.name}`,
1326
+ issue: `Type mismatch: server expects "${serverVar.type}", client has "${clientType}"`
1327
+ });
1328
+ }
1329
+ }
1330
+ }
1331
+ const serverVarNames = serverVariables.map((v) => v.name);
1332
+ for (const clientProp of Object.keys(clientProps)) {
1333
+ if (!serverVarNames.includes(clientProp)) {
1334
+ mismatches.push({
1335
+ path: `$.${clientProp}`,
1336
+ issue: `Extra property not expected by server`
1337
+ });
1338
+ }
1339
+ }
1340
+ return mismatches;
1341
+ }
1342
+ function validateOutputSchema(clientSchema, serverSchema) {
1343
+ return compareSchemas(clientSchema, serverSchema);
1106
1344
  }
1107
1345
 
1108
- var __defProp$1 = Object.defineProperty;
1109
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1110
- var __publicField$1 = (obj, key, value) => {
1111
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1346
+ var __defProp$3 = Object.defineProperty;
1347
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1348
+ var __publicField$3 = (obj, key, value) => {
1349
+ __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
1112
1350
  return value;
1113
1351
  };
1114
- class Resource {
1115
- constructor(client) {
1116
- __publicField$1(this, "_client");
1117
- this._client = client;
1352
+ function timeout(ms, signal) {
1353
+ return new Promise((resolve, reject) => {
1354
+ const timer = setTimeout(resolve, ms);
1355
+ if (signal) {
1356
+ signal.addEventListener("abort", () => {
1357
+ clearTimeout(timer);
1358
+ reject(signal.reason);
1359
+ }, { once: true });
1360
+ }
1361
+ });
1362
+ }
1363
+ class Poller {
1364
+ constructor({ interval, timeout: timeout2, abortSignal }) {
1365
+ __publicField$3(this, "_interval");
1366
+ __publicField$3(this, "_timeout");
1367
+ __publicField$3(this, "_abortSignal");
1368
+ __publicField$3(this, "_internalAbortController");
1369
+ if (interval <= 0) {
1370
+ throw new TelaError("Interval must be greater than 0");
1371
+ }
1372
+ if (timeout2 <= 0) {
1373
+ throw new TelaError("Timeout must be greater than 0");
1374
+ }
1375
+ this._interval = interval;
1376
+ this._timeout = timeout2;
1377
+ this._abortSignal = abortSignal ?? new AbortController().signal;
1378
+ this._internalAbortController = new AbortController();
1379
+ }
1380
+ async startTimeout() {
1381
+ await timeout(this._timeout, this._internalAbortController.signal);
1382
+ throw new ConnectionTimeout({
1383
+ message: `Reached timeout of ${this._timeout}ms when polling`
1384
+ });
1385
+ }
1386
+ /**
1387
+ * Starts the polling operation, repeatedly calling the callback until completion.
1388
+ * The callback is invoked at the configured interval and must return a PollerResult
1389
+ * indicating whether polling should continue or if the final value is ready.
1390
+ *
1391
+ * @param callback - Function called on each polling iteration.
1392
+ * @returns A promise resolving to the final result value.
1393
+ * @throws {Error} If the polling operation times out.
1394
+ * @throws {Error} If the operation is aborted via the AbortSignal.
1395
+ * @throws Any error thrown by the callback function.
1396
+ *
1397
+ * @example
1398
+ * ```typescript
1399
+ * const result = await poller.start(async (signal) => {
1400
+ * const response = await fetch('/api/status', { signal });
1401
+ * const data = await response.json();
1402
+ *
1403
+ * if (data.status === 'completed') {
1404
+ * return { done: true, value: data.result };
1405
+ * }
1406
+ * return { done: false };
1407
+ * });
1408
+ * ```
1409
+ */
1410
+ start(callback) {
1411
+ const resultPromise = async () => {
1412
+ try {
1413
+ while (!this._abortSignal.aborted) {
1414
+ const result = await Promise.try(callback, this._abortSignal);
1415
+ if (result.done) {
1416
+ return result.value;
1417
+ }
1418
+ await timeout(this._interval, this._abortSignal);
1419
+ }
1420
+ throw new UserAbortError({ message: "Polling aborted" });
1421
+ } finally {
1422
+ this._internalAbortController.abort();
1423
+ }
1424
+ };
1425
+ return Promise.race([this.startTimeout(), resultPromise()]);
1118
1426
  }
1119
1427
  }
1120
1428
 
1121
- class ChatCompletions extends Resource {
1122
- async create(body, opts) {
1123
- const processedBody = { ...body };
1124
- if (body.variables) {
1125
- const processedVariables = {};
1126
- for await (const [key, value] of Object.entries(body.variables)) {
1127
- if (value instanceof TelaFile) {
1128
- const fileWithUrl = await this.uploadFile(value);
1129
- processedVariables[key] = fileWithUrl;
1130
- } else {
1131
- processedVariables[key] = value;
1429
+ async function calculateSha256sum(content) {
1430
+ const stream = content instanceof File || content instanceof Blob ? content.stream() : content;
1431
+ const reader = stream.getReader();
1432
+ try {
1433
+ const { createHash } = await import('node:crypto');
1434
+ const hash = createHash("sha256");
1435
+ while (true) {
1436
+ const { done, value } = await reader.read();
1437
+ if (done)
1438
+ break;
1439
+ hash.update(value);
1440
+ }
1441
+ return hash.digest("hex");
1442
+ } catch {
1443
+ const chunks = [];
1444
+ while (true) {
1445
+ const { done, value } = await reader.read();
1446
+ if (done)
1447
+ break;
1448
+ chunks.push(value);
1449
+ }
1450
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1451
+ const buffer = new Uint8Array(totalLength);
1452
+ let offset = 0;
1453
+ for (const chunk of chunks) {
1454
+ buffer.set(chunk, offset);
1455
+ offset += chunk.length;
1456
+ }
1457
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
1458
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
1459
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
1460
+ return hashHex;
1461
+ }
1462
+ }
1463
+
1464
+ var __defProp$2 = Object.defineProperty;
1465
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1466
+ var __publicField$2 = (obj, key, value) => {
1467
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1468
+ return value;
1469
+ };
1470
+ function isTelaFile(obj) {
1471
+ return obj instanceof TelaFile;
1472
+ }
1473
+ function isTelaFileArray(obj) {
1474
+ return Array.isArray(obj) && obj.length > 0 && obj.every(isTelaFile);
1475
+ }
1476
+ class CanvasExecution {
1477
+ /**
1478
+ * Creates a new canvas execution instance.
1479
+ *
1480
+ * @param variables - Input variables to be passed to the canvas template.
1481
+ * @param params - Execution parameters controlling sync/async/stream behavior.
1482
+ * @param outputSchema - Zod schema or object schema for validating/parsing output.
1483
+ * @param client - HTTP client instance for making API requests.
1484
+ */
1485
+ constructor(variables, params = { async: false }, outputSchema, client) {
1486
+ __publicField$2(this, "_id");
1487
+ __publicField$2(this, "_variables");
1488
+ __publicField$2(this, "_params");
1489
+ __publicField$2(this, "_client");
1490
+ __publicField$2(this, "_outputSchema");
1491
+ __publicField$2(this, "_skipResultValidation");
1492
+ __publicField$2(this, "_abortController");
1493
+ __publicField$2(this, "_startPropmise");
1494
+ __publicField$2(this, "_resultPromise");
1495
+ __publicField$2(this, "_stream");
1496
+ this._variables = variables;
1497
+ this._params = params;
1498
+ this._outputSchema = outputSchema;
1499
+ this._skipResultValidation = params.skipResultValidation ?? false;
1500
+ this._client = client;
1501
+ this._abortController = new AbortController();
1502
+ }
1503
+ /**
1504
+ * Gets the unique execution ID assigned by the server.
1505
+ *
1506
+ * @throws {Error} If the execution has not been started yet.
1507
+ * @returns The execution ID.
1508
+ */
1509
+ get id() {
1510
+ if (!this._id) {
1511
+ throw new ExecutionNotStartedError();
1512
+ }
1513
+ return this._id;
1514
+ }
1515
+ /**
1516
+ * Gets the input variables provided to this execution.
1517
+ *
1518
+ * @returns The variables object.
1519
+ */
1520
+ get variables() {
1521
+ return this._variables;
1522
+ }
1523
+ /**
1524
+ * Gets the execution parameters configured for this instance.
1525
+ *
1526
+ * @returns The execution parameters or undefined.
1527
+ */
1528
+ get params() {
1529
+ return this._params;
1530
+ }
1531
+ /**
1532
+ * Checks if this execution is configured for asynchronous processing.
1533
+ *
1534
+ * @returns True if async mode is enabled.
1535
+ */
1536
+ get isAsync() {
1537
+ return this._isAsync(this._params);
1538
+ }
1539
+ /**
1540
+ * Checks if this execution is configured for synchronous processing.
1541
+ *
1542
+ * @returns True if sync mode is enabled (not async).
1543
+ */
1544
+ get isSync() {
1545
+ return !this._isAsync(this._params) && !this.isStream;
1546
+ }
1547
+ /**
1548
+ * Checks if this execution is configured for streaming responses.
1549
+ *
1550
+ * @returns True if stream mode is enabled.
1551
+ */
1552
+ get isStream() {
1553
+ return Boolean(this._params.stream);
1554
+ }
1555
+ /**
1556
+ * Type guard to check if params indicate async execution.
1557
+ *
1558
+ * @param params - Execution parameters to check.
1559
+ * @returns True if params indicate async mode.
1560
+ */
1561
+ _isAsync(params) {
1562
+ return Boolean(params.async);
1563
+ }
1564
+ /**
1565
+ * Starts the execution based on configured parameters.
1566
+ * Routes to the appropriate execution method (sync, async, or stream).
1567
+ *
1568
+ * @returns A promise or async generator depending on execution mode.
1569
+ */
1570
+ start() {
1571
+ if (this._resultPromise || this._stream) {
1572
+ return this._resultPromise ?? this._stream;
1573
+ }
1574
+ if (this._params.stream) {
1575
+ return this.startStream();
1576
+ }
1577
+ if (this.isSync) {
1578
+ return this.startSync();
1579
+ }
1580
+ return this.startAsync();
1581
+ }
1582
+ /**
1583
+ * Gets the execution result. For async executions, automatically starts polling.
1584
+ * For sync executions, returns the result promise. For streams, returns the generator.
1585
+ *
1586
+ * @returns The execution result as a promise or async generator.
1587
+ */
1588
+ get result() {
1589
+ if (this.isSync) {
1590
+ if (!this._resultPromise) {
1591
+ throw new ExecutionNotStartedError();
1592
+ }
1593
+ return this._resultPromise;
1594
+ }
1595
+ if (this.isStream) {
1596
+ if (!this._stream) {
1597
+ throw new ExecutionNotStartedError();
1598
+ }
1599
+ return this._stream;
1600
+ }
1601
+ if (this._resultPromise) {
1602
+ return this._resultPromise;
1603
+ }
1604
+ this._resultPromise = this.startPolling();
1605
+ return this._resultPromise;
1606
+ }
1607
+ /**
1608
+ * Cancels the ongoing execution by aborting all active requests and polling operations.
1609
+ */
1610
+ cancel() {
1611
+ this._abortController.abort();
1612
+ }
1613
+ /**
1614
+ * Builds the base request body shared across all execution types.
1615
+ * Includes messages, overrides, and structured output configuration.
1616
+ *
1617
+ * @returns The base request body object.
1618
+ */
1619
+ get baseBody() {
1620
+ const body = {
1621
+ canvasId: this._params.canvasId,
1622
+ applicationId: this._params.applicationId,
1623
+ versionId: this._params.versionId,
1624
+ messages: this._params.messages
1625
+ };
1626
+ if (this._params.override && this._outputSchema instanceof z.ZodType) {
1627
+ return {
1628
+ ...body,
1629
+ override: {
1630
+ ...this._params.override,
1631
+ structured_output: z.toJSONSchema(this._outputSchema)
1132
1632
  }
1633
+ };
1634
+ }
1635
+ return body;
1636
+ }
1637
+ /**
1638
+ * Processes variables and uploads any TelaFile instances to the server.
1639
+ * Replaces TelaFile objects with their uploaded URLs while preserving other values.
1640
+ *
1641
+ * @returns A promise resolving to the processed variables object.
1642
+ */
1643
+ async resolveVariables() {
1644
+ const variables = {};
1645
+ for (const [key, value] of Object.entries(this._variables)) {
1646
+ if (isTelaFileArray(value)) {
1647
+ variables[key] = await this.uploadFiles(value);
1648
+ continue;
1133
1649
  }
1134
- processedBody.variables = processedVariables;
1650
+ if (isTelaFile(value)) {
1651
+ variables[key] = await this.uploadFile(value);
1652
+ continue;
1653
+ }
1654
+ variables[key] = value;
1135
1655
  }
1136
- return this._client.post("/v2/chat/completions", {
1137
- body: processedBody,
1138
- ...opts,
1139
- stream: body.stream ?? false
1656
+ return variables;
1657
+ }
1658
+ /**
1659
+ * Initiates a synchronous execution that waits for the complete result.
1660
+ * The result is validated against the output schema if provided.
1661
+ *
1662
+ * @returns A promise resolving to the parsed execution result.
1663
+ */
1664
+ async startSync() {
1665
+ const resolvedVariables = await this.resolveVariables();
1666
+ const body = {
1667
+ async: this._params.async ?? false,
1668
+ stream: false,
1669
+ ...this.baseBody,
1670
+ variables: resolvedVariables
1671
+ };
1672
+ this._resultPromise = this._client.post("/v2/chat/completions", {
1673
+ body,
1674
+ stream: false,
1675
+ signal: this._abortController.signal
1676
+ }).then((response) => {
1677
+ this._id = response.id;
1678
+ return response.choices?.[0]?.message?.content;
1679
+ }).then((content) => {
1680
+ if (this._skipResultValidation || !(this._outputSchema instanceof z.ZodType)) {
1681
+ return content;
1682
+ }
1683
+ return this._outputSchema.parse(content);
1684
+ });
1685
+ return this._resultPromise;
1686
+ }
1687
+ /**
1688
+ * Initiates an asynchronous execution that returns immediately with an execution ID.
1689
+ * Results must be retrieved separately via polling using the `result` getter.
1690
+ *
1691
+ * @returns A promise that resolves when the execution is queued.
1692
+ */
1693
+ async startAsync() {
1694
+ const resolvedVariables = await this.resolveVariables();
1695
+ const body = {
1696
+ async: true,
1697
+ stream: false,
1698
+ ...this.baseBody,
1699
+ variables: resolvedVariables
1700
+ };
1701
+ return await this._client.post("/v2/chat/completions", {
1702
+ body,
1703
+ stream: false,
1704
+ signal: this._abortController.signal
1705
+ }).then((response) => {
1706
+ this._id = response.id;
1707
+ return response;
1708
+ });
1709
+ }
1710
+ /**
1711
+ * Initiates a streaming execution that returns results incrementally as they're generated.
1712
+ *
1713
+ * @returns A promise resolving to an async generator yielding result chunks.
1714
+ */
1715
+ async startStream() {
1716
+ const resolvedVariables = await this.resolveVariables();
1717
+ const body = {
1718
+ ...this.baseBody,
1719
+ stream: true,
1720
+ variables: resolvedVariables
1721
+ };
1722
+ this._stream = await this._client.post("/v2/chat/completions", {
1723
+ body,
1724
+ stream: true,
1725
+ signal: this._abortController.signal
1726
+ });
1727
+ return this._stream;
1728
+ }
1729
+ /**
1730
+ * Polls the server for async execution results at regular intervals.
1731
+ * Continues polling until the execution completes or the timeout is reached.
1732
+ *
1733
+ * @throws {Error} If called on a non-async execution.
1734
+ * @throws {Error} If the execution fails on the server.
1735
+ * @throws {Error} If the polling operation times out.
1736
+ * @returns A promise resolving to the final execution result.
1737
+ */
1738
+ async startPolling() {
1739
+ if (!this._isAsync(this._params)) {
1740
+ throw new InvalidExecutionModeError("Polling is only supported for async executions");
1741
+ }
1742
+ return new Poller({
1743
+ interval: this._params.pollingInterval ?? 1e3,
1744
+ // 1 second
1745
+ timeout: this._params.pollingTimeout ?? 6e4,
1746
+ // 1 minute
1747
+ abortSignal: this._abortController.signal
1748
+ }).start(async (signal) => {
1749
+ const response = await this._client.get(
1750
+ `/v2/chat/completions/${this.id}`,
1751
+ {
1752
+ signal
1753
+ }
1754
+ );
1755
+ if (response.status === "failed") {
1756
+ throw new ExecutionFailedError(response.rawOutput);
1757
+ }
1758
+ if (response.status !== "succeeded") {
1759
+ return {
1760
+ done: false,
1761
+ value: void 0
1762
+ };
1763
+ }
1764
+ return {
1765
+ done: response.status === "succeeded",
1766
+ value: response.outputContent.content
1767
+ };
1768
+ }).then((value) => {
1769
+ if (this._skipResultValidation || !(this._outputSchema instanceof z.ZodType)) {
1770
+ return value;
1771
+ }
1772
+ return this._outputSchema.parse(value);
1140
1773
  });
1141
1774
  }
1142
1775
  /**
@@ -1152,36 +1785,303 @@ class ChatCompletions extends Resource {
1152
1785
  * ```typescript
1153
1786
  * const file = new TelaFile({ /* file options *\/ });
1154
1787
  * const uploadedFile = await this.uploadFile(file);
1155
- * console.log(uploadedFile.file_url);
1788
+ * console.log(uploadedFile.fileUrl);
1156
1789
  * ```
1157
1790
  */
1158
1791
  async uploadFile(file) {
1159
- const content = await file.getUploadableContent();
1160
- if (file.isURL && typeof content === "string") {
1792
+ let content = await file.getUploadableContent();
1793
+ let sha256sumStream;
1794
+ if (typeof content === "string") {
1161
1795
  return { fileUrl: content, options: file.options };
1162
1796
  }
1163
- const response = await this._client.post(
1164
- "/v2/file"
1165
- );
1166
- const { uploadUrl, downloadUrl } = response;
1167
- let contentType = "application/octet-stream";
1168
- if (content instanceof File || content instanceof Blob) {
1169
- contentType = content.type;
1797
+ const filename = file.name ?? void 0;
1798
+ const fileType = file.type ?? void 0;
1799
+ const contentLength = file.size ?? void 0;
1800
+ if (content instanceof ReadableStream) {
1801
+ const [hashStream, contentStream] = content.tee();
1802
+ content = contentStream;
1803
+ sha256sumStream = hashStream;
1170
1804
  }
1171
- const uploadResponse = await fetch(uploadUrl, {
1805
+ const sha256sum = await calculateSha256sum(sha256sumStream ?? content);
1806
+ const { id, uploadUrl } = await this._client.post("/_services/vault/files", {
1807
+ body: {
1808
+ fileName: filename,
1809
+ mimeType: fileType,
1810
+ size: contentLength ?? void 0,
1811
+ sha256sum
1812
+ }
1813
+ });
1814
+ if (content instanceof ReadableStream && typeof Bun !== "undefined") {
1815
+ console.warn(
1816
+ "[Tela SDK - WARNING] Buffering file upload due to Bun fetch implementation. Large files may cause memory issues. Consider using Node.js for streaming uploads.",
1817
+ { fileName: filename, fileSize: contentLength }
1818
+ );
1819
+ const chunks = [];
1820
+ const reader = content.getReader();
1821
+ while (true) {
1822
+ const { done, value } = await reader.read();
1823
+ if (done)
1824
+ break;
1825
+ chunks.push(value);
1826
+ }
1827
+ content = new Blob(chunks, { type: fileType ?? "application/octet-stream" });
1828
+ }
1829
+ const request = new Request(uploadUrl, {
1172
1830
  method: "PUT",
1173
1831
  body: content,
1174
1832
  headers: {
1175
- "Content-Type": contentType,
1833
+ "Content-Type": fileType ?? "application/octet-stream",
1176
1834
  ...file.size ? { "Content-Length": file.size.toString() } : {}
1177
- },
1178
- // duplex is not supported
1179
- duplex: "half"
1835
+ }
1180
1836
  });
1837
+ const uploadResponse = await fetch(request);
1181
1838
  if (!uploadResponse.ok) {
1182
- throw new FileUploadError(await uploadResponse.text());
1839
+ throw new FileUploadError(await uploadResponse.text(), uploadResponse.status);
1183
1840
  }
1184
- return { fileUrl: downloadUrl, options: file.options };
1841
+ return { fileUrl: `vault://${id}`, options: file.options };
1842
+ }
1843
+ /**
1844
+ * Uploads multiple files and returns their URLs and options.
1845
+ *
1846
+ * This is used internally to handle multiple file uploads associated with chat completions.
1847
+ *
1848
+ * @param files - An array of TelaFile instances to be uploaded.
1849
+ * @returns A Promise that resolves to an array of objects containing file URLs and options.
1850
+ * @throws {FileUploadError} If any file upload fails.
1851
+ */
1852
+ async uploadFiles(files) {
1853
+ const uploadPromises = files.map((file) => this.uploadFile(file));
1854
+ return Promise.all(uploadPromises);
1855
+ }
1856
+ }
1857
+
1858
+ var __defProp$1 = Object.defineProperty;
1859
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1860
+ var __publicField$1 = (obj, key, value) => {
1861
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1862
+ return value;
1863
+ };
1864
+ const zod = {
1865
+ string,
1866
+ number,
1867
+ boolean,
1868
+ object,
1869
+ array,
1870
+ file: TelaFileSchema,
1871
+ any,
1872
+ unknown
1873
+ };
1874
+ function fetchById(id, client) {
1875
+ return client.get(`/prompt/${id}/promoted-version`);
1876
+ }
1877
+ function fetchByVersionId(versionId, client) {
1878
+ return client.get(`/prompt-version/${versionId}`);
1879
+ }
1880
+ function fetchByApplicationId(applicationId, client) {
1881
+ return client.get(`/prompt-application/${applicationId}/targetPromptVersion`);
1882
+ }
1883
+ function fetchByAny({ id, versionId, applicationId, client }) {
1884
+ if (applicationId) {
1885
+ return fetchByApplicationId(applicationId, client);
1886
+ }
1887
+ if (versionId) {
1888
+ return fetchByVersionId(versionId, client);
1889
+ }
1890
+ if (id) {
1891
+ return fetchById(id, client);
1892
+ }
1893
+ throw new Error("Either id, versionId, or applicationId must be provided");
1894
+ }
1895
+ function validateSchemas(input, output, promptVersion) {
1896
+ const canvasIdentifier = `${promptVersion.title} (${promptVersion.promptId})`;
1897
+ if (input instanceof z$1.ZodType) {
1898
+ try {
1899
+ const inputSchema = z$1.toJSONSchema(input, { unrepresentable: "any" });
1900
+ const mismatches = validateInputSchema(inputSchema, promptVersion.variables);
1901
+ if (mismatches.length === 0) {
1902
+ return;
1903
+ }
1904
+ console.warn(
1905
+ `[Tela SDK - Canvas Input Validation] Input schema mismatches for canvas "${canvasIdentifier}":`
1906
+ );
1907
+ for (const mismatch of mismatches) {
1908
+ console.warn(` - ${mismatch.path}: ${mismatch.issue}`);
1909
+ }
1910
+ } catch (error) {
1911
+ console.warn(
1912
+ `[Tela SDK - Canvas Input Validation] Failed to validate input schema for canvas "${canvasIdentifier}":`,
1913
+ error
1914
+ );
1915
+ }
1916
+ }
1917
+ if (output instanceof z$1.ZodType) {
1918
+ try {
1919
+ const outputSchema = z$1.toJSONSchema(output);
1920
+ const serverOutput = promptVersion.configuration.structuredOutput;
1921
+ if (!serverOutput.enabled) {
1922
+ console.warn(
1923
+ `[Tela SDK - Canvas Output Validation] Output schema provided for canvas "${canvasIdentifier}", but structured output is not enabled on the server. The schema may not be enforced.`
1924
+ );
1925
+ return;
1926
+ }
1927
+ const mismatches = validateOutputSchema(outputSchema, serverOutput.schema);
1928
+ if (mismatches.length === 0) {
1929
+ return;
1930
+ }
1931
+ console.warn(
1932
+ `[Tela SDK - Canvas Output Validation] Output schema mismatches for canvas "${canvasIdentifier}":`
1933
+ );
1934
+ for (const mismatch of mismatches) {
1935
+ console.warn(` - ${mismatch.path}: ${mismatch.issue}`);
1936
+ }
1937
+ } catch (error) {
1938
+ console.warn(
1939
+ `[Tela SDK - Canvas Output Validation] Failed to validate output schema for canvas "${canvasIdentifier}":`,
1940
+ error
1941
+ );
1942
+ }
1943
+ }
1944
+ }
1945
+ class Canvas {
1946
+ /**
1947
+ * Creates a new instance of the Canvas class. Usage of this constructor is not recommended.
1948
+ * Use the `tela.getCanvas` method instead.
1949
+ *
1950
+ * @private
1951
+ */
1952
+ constructor({ id, applicationId, name, versionId, input, output, client, variables }) {
1953
+ __publicField$1(this, "_id");
1954
+ __publicField$1(this, "_versionId");
1955
+ __publicField$1(this, "_applicationId");
1956
+ __publicField$1(this, "_name");
1957
+ __publicField$1(this, "_input");
1958
+ __publicField$1(this, "_output");
1959
+ __publicField$1(this, "_client");
1960
+ __publicField$1(this, "_variables");
1961
+ this._id = id;
1962
+ this._applicationId = applicationId;
1963
+ this._name = name;
1964
+ this._versionId = versionId;
1965
+ this._input = input && input(zod);
1966
+ this._output = output && output(zod);
1967
+ this._client = client;
1968
+ this._variables = variables;
1969
+ }
1970
+ /**
1971
+ * Gets a canvas by its ID.
1972
+ *
1973
+ * @param options - The options to use to get the canvas.
1974
+ * @param options.id - The ID of the canvas to get.
1975
+ * @param options.versionId - The version ID of the canvas to get.
1976
+ * @param options.applicationId - The application ID of the canvas to get.
1977
+ * @param options.client - The client to use to make the request.
1978
+ * @param options.input - The input schema of the canvas to get.
1979
+ * @param options.output - The output schema of the canvas to get.
1980
+ * @returns The canvas.
1981
+ */
1982
+ static async get(options) {
1983
+ const { id, versionId, applicationId, client, input, output, skipSchemaValidation = false } = options;
1984
+ const promptVersion = await fetchByAny({ id, versionId, applicationId, client });
1985
+ const inputSchema = input && input(zod);
1986
+ const outputSchema = output && output(zod);
1987
+ if (!skipSchemaValidation) {
1988
+ validateSchemas(inputSchema, outputSchema, promptVersion);
1989
+ }
1990
+ return new Canvas({
1991
+ id: promptVersion.promptId,
1992
+ name: promptVersion.title,
1993
+ versionId: promptVersion.id,
1994
+ input,
1995
+ output,
1996
+ client,
1997
+ variables: promptVersion.variables
1998
+ });
1999
+ }
2000
+ /**
2001
+ * Gets the unique identifier of this canvas.
2002
+ *
2003
+ * @returns The canvas ID.
2004
+ */
2005
+ get id() {
2006
+ if (!this._id) {
2007
+ throw new Error("Canvas ID is not set");
2008
+ }
2009
+ return this._id;
2010
+ }
2011
+ /**
2012
+ * Gets the name of this canvas, if provided.
2013
+ *
2014
+ * @returns The canvas name or undefined.
2015
+ */
2016
+ get name() {
2017
+ if (!this._name) {
2018
+ throw new Error("Canvas name is not set");
2019
+ }
2020
+ return this._name;
2021
+ }
2022
+ /**
2023
+ * Gets the version identifier of this canvas, if specified.
2024
+ * When undefined, the latest promoted version is used.
2025
+ *
2026
+ * @returns The version ID or undefined.
2027
+ */
2028
+ get versionId() {
2029
+ if (!this._versionId) {
2030
+ throw new Error("Canvas version ID is not set");
2031
+ }
2032
+ return this._versionId;
2033
+ }
2034
+ get applicationId() {
2035
+ if (!this._applicationId) {
2036
+ throw new Error("Canvas application ID is not set");
2037
+ }
2038
+ return this._applicationId;
2039
+ }
2040
+ /**
2041
+ * Gets the variables of this canvas.
2042
+ *
2043
+ * @returns The variables of the canvas.
2044
+ */
2045
+ get variables() {
2046
+ return this._variables;
2047
+ }
2048
+ /**
2049
+ * Validates and parses input variables using the canvas input schema.
2050
+ *
2051
+ * @param variables - Raw input variables to validate.
2052
+ * @returns Parsed and validated variables.
2053
+ * @throws {ZodError} If validation fails when a Zod schema is configured.
2054
+ */
2055
+ parseVariables(variables) {
2056
+ try {
2057
+ if (this._input instanceof z$1.ZodType) {
2058
+ return this._input.parse(variables);
2059
+ }
2060
+ return variables;
2061
+ } catch (error) {
2062
+ if (!(error instanceof ZodError)) {
2063
+ throw error;
2064
+ }
2065
+ throw new Error(z$1.prettifyError(error));
2066
+ }
2067
+ }
2068
+ execute(variables, params) {
2069
+ const parsedInput = this.parseVariables(variables);
2070
+ const fullParams = {
2071
+ ...params ?? { async: false },
2072
+ versionId: this._versionId,
2073
+ canvasId: this._id,
2074
+ applicationId: this._applicationId
2075
+ };
2076
+ const execution = new CanvasExecution(parsedInput, fullParams, this._output, this._client);
2077
+ return {
2078
+ then(onfulfilled, onrejected) {
2079
+ return Promise.resolve(execution.start()).then(() => onfulfilled?.(execution) ?? execution).catch(onrejected);
2080
+ },
2081
+ get result() {
2082
+ return Promise.resolve(execution.start()).then(() => execution.result);
2083
+ }
2084
+ };
1185
2085
  }
1186
2086
  }
1187
2087
 
@@ -1202,31 +2102,56 @@ const _TelaSDK = class _TelaSDK extends BaseClient {
1202
2102
  __publicField(this, "apiKey");
1203
2103
  __publicField(this, "jwt");
1204
2104
  /**
1205
- * The ChatCompletions resource for interacting with Tela's chat completion API.
2105
+ * Creates a new `TelaFile` instance from the provided file input.
1206
2106
  *
1207
- * Use this to generate chat completions based on provided messages.
2107
+ * @param file - The file input to create a `TelaFile` instance from.
2108
+ * @returns A new `TelaFile` instance.
2109
+ */
2110
+ __publicField(this, "createFile", TelaFile.create.bind(this));
2111
+ /**
2112
+ * Retrieves a canvas by its ID, version ID, or application ID.
2113
+ * Validates input and output schemas if Zod schemas are provided.
2114
+ *
2115
+ * @param options - Options for retrieving the canvas.
2116
+ * @returns A promise resolving to a Canvas instance.
1208
2117
  *
1209
2118
  * @example
1210
2119
  * ```typescript
1211
- * const completion = await tela.completions.create({
1212
- * canvasId: "your-canvas-id",
1213
- * messages: [{ role: "user", content: "Hello!" }],
2120
+ * import { z } from 'zod';
2121
+ *
2122
+ * // Get canvas by ID with schemas
2123
+ * const canvas = await tela.canvas.get({
2124
+ * id: 'canvas-id',
2125
+ * input: z.object({ query: z.string() }),
2126
+ * output: z.object({ response: z.string() })
1214
2127
  * });
1215
- * ```
1216
- */
1217
- __publicField(this, "completions", new ChatCompletions(this));
1218
- /**
1219
- * Creates a new `TelaFile` instance from the provided file input.
1220
2128
  *
1221
- * @param file - The file input to create a `TelaFile` instance from.
1222
- * @returns A new `TelaFile` instance.
2129
+ * // Get canvas by application ID
2130
+ * const canvas = await tela.canvas.get({
2131
+ * applicationId: 'app-id'
2132
+ * });
2133
+ *
2134
+ * // Execute the canvas
2135
+ * const execution = await canvas.execute({ query: 'Hello' });
2136
+ * const result = await execution.result;
2137
+ * ```
1223
2138
  */
1224
- __publicField(this, "createFile", createTelaFile.bind(this));
2139
+ __publicField(this, "canvas", {
2140
+ get: async (options) => {
2141
+ return Canvas.get({
2142
+ ...options,
2143
+ client: this
2144
+ });
2145
+ }
2146
+ });
1225
2147
  this.opts = { baseURL, ...rest };
1226
2148
  this.apiKey = apiKey;
1227
2149
  this.jwt = jwt;
1228
2150
  this.validateAuth();
1229
2151
  }
2152
+ get authToken() {
2153
+ return this.apiKey || this.jwt;
2154
+ }
1230
2155
  validateAuth() {
1231
2156
  if (!this.apiKey && !this.jwt) {
1232
2157
  throw new MissingApiKeyOrJWTError();
@@ -1283,4 +2208,4 @@ function createTelaClient(opts) {
1283
2208
  return new TelaSDK(opts);
1284
2209
  }
1285
2210
 
1286
- export { TelaFile, TelaSDK, createTelaClient };
2211
+ export { APIError, AuthenticationError, AuthorizationError, BadRequestError, BaseClient, ConflictApiKeyAndJWTError, ConflictError, ConnectionError, ConnectionTimeout, EmptyFileError, ExecutionFailedError, ExecutionNotStartedError, FileUploadError, InternalServerError, InvalidExecutionModeError, InvalidFileURL, MissingApiKeyOrJWTError, NotFoundError, RateLimitError, TelaError, TelaFile, TelaFileSchema, TelaSDK, UnprocessableEntityError, UserAbortError, createTelaClient, toError };