@mitralab.io/sdk-core 0.1.0 → 0.2.0-beta.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.js CHANGED
@@ -24,6 +24,23 @@ function invalidResponse(message, errors = defaultSdkCoreErrorFactory) {
24
24
  throw errors.invalidResponse(message);
25
25
  }
26
26
 
27
+ // src/batch.ts
28
+ function requireBatchSize(items, name, maxSize, errors = defaultSdkCoreErrorFactory) {
29
+ if (items.length < 1 || items.length > maxSize) {
30
+ configurationError(`${name} must contain between 1 and ${maxSize} items`, errors);
31
+ }
32
+ }
33
+
34
+ // src/path.ts
35
+ function encodePathSegment(value, name, errors = defaultSdkCoreErrorFactory) {
36
+ const segment = String(value);
37
+ if (!segment.trim()) configurationError(`${name} must not be empty`, errors);
38
+ if (segment === "." || segment === "..") {
39
+ configurationError(`${name} must not be a dot segment`, errors);
40
+ }
41
+ return encodeURIComponent(segment);
42
+ }
43
+
27
44
  // src/response.ts
28
45
  function isObject(value) {
29
46
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -31,6 +48,9 @@ function isObject(value) {
31
48
  function isNullableString(value) {
32
49
  return value === null || typeof value === "string";
33
50
  }
51
+ function isNullableBoolean(value) {
52
+ return value === null || typeof value === "boolean";
53
+ }
34
54
  function isInteger(value) {
35
55
  return typeof value === "number" && Number.isInteger(value);
36
56
  }
@@ -40,8 +60,23 @@ function isNullableInteger(value) {
40
60
  function isStringRecord(value) {
41
61
  return isObject(value) && Object.values(value).every((item) => typeof item === "string");
42
62
  }
63
+ function isStringArray(value) {
64
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
65
+ }
66
+ function isJsonValue(value) {
67
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
68
+ if (typeof value === "number") return Number.isFinite(value);
69
+ if (Array.isArray(value)) return value.every(isJsonValue);
70
+ return isObject(value) && Object.values(value).every(isJsonValue);
71
+ }
72
+ function isJsonRecord(value) {
73
+ return isObject(value) && Object.values(value).every(isJsonValue);
74
+ }
75
+ function isOneOf(value, allowed) {
76
+ return typeof value === "string" && allowed.includes(value);
77
+ }
43
78
  function hasOwn(value, property) {
44
- return Object.prototype.hasOwnProperty.call(value, property);
79
+ return Object.hasOwn(value, property);
45
80
  }
46
81
  function invalidField(context, field, errors) {
47
82
  return invalidResponse(`${context} has an invalid ${field} field`, errors);
@@ -52,21 +87,67 @@ function expectObject(value, context, errors = defaultSdkCoreErrorFactory) {
52
87
  }
53
88
  return value;
54
89
  }
55
- function expectObjectArray(value, context, errors = defaultSdkCoreErrorFactory) {
90
+ function expectObjectArray(value, context, errors = defaultSdkCoreErrorFactory, validateItem) {
56
91
  if (!Array.isArray(value) || value.some((item) => !isObject(item))) {
57
92
  return invalidResponse(`${context} must be a JSON array of objects`, errors);
58
93
  }
94
+ if (validateItem) {
95
+ value.forEach((item, position) => validateItem(item, `${context} item ${position}`, errors));
96
+ }
97
+ return value;
98
+ }
99
+ function expectNullableObject(value, context, errors = defaultSdkCoreErrorFactory) {
100
+ return value === null ? null : expectObject(value, context, errors);
101
+ }
102
+ function expectStringArray(value, context, errors = defaultSdkCoreErrorFactory) {
103
+ if (!isStringArray(value)) {
104
+ return invalidResponse(`${context} must be a JSON array of strings`, errors);
105
+ }
59
106
  return value;
60
107
  }
108
+ function expectPage(value, context, errors = defaultSdkCoreErrorFactory, validateItem) {
109
+ const page = expectObject(value, context, errors);
110
+ if (!Array.isArray(page.content) || page.content.some((item) => !isObject(item))) {
111
+ invalidField(context, "content", errors);
112
+ }
113
+ const metadata = expectObject(page.page, `${context} page`, errors);
114
+ for (const field of ["size", "totalElements", "totalPages", "number"]) {
115
+ if (!isInteger(metadata[field])) invalidField(`${context} page`, field, errors);
116
+ }
117
+ if (metadata.totalElements < page.content.length) {
118
+ invalidField(`${context} page`, "totalElements", errors);
119
+ }
120
+ if (validateItem) {
121
+ page.content.forEach(
122
+ (item, position) => validateItem(item, `${context} item ${position}`, errors)
123
+ );
124
+ }
125
+ return page;
126
+ }
127
+ function expectLegacyPage(value, context, errors = defaultSdkCoreErrorFactory, validateItem) {
128
+ const page = expectObject(value, context, errors);
129
+ if (!Array.isArray(page.content) || page.content.some((item) => !isObject(item))) {
130
+ invalidField(context, "content", errors);
131
+ }
132
+ if (!isInteger(page.totalElements) || page.totalElements < page.content.length) {
133
+ invalidField(context, "totalElements", errors);
134
+ }
135
+ if (validateItem) {
136
+ page.content.forEach(
137
+ (item, position) => validateItem(item, `${context} item ${position}`, errors)
138
+ );
139
+ }
140
+ return page;
141
+ }
61
142
  function expectTenant(value, context, errors = defaultSdkCoreErrorFactory) {
62
143
  const tenant = expectObject(value, context, errors);
63
144
  if (typeof tenant.id !== "string") invalidField(context, "id", errors);
64
145
  if (typeof tenant.shortId !== "string") invalidField(context, "shortId", errors);
65
146
  if (!isNullableInteger(tenant.legacyId)) invalidField(context, "legacyId", errors);
66
147
  if (typeof tenant.slug !== "string") invalidField(context, "slug", errors);
67
- if (!isObject(tenant.plan)) invalidField(context, "plan", errors);
68
- if (typeof tenant.plan.id !== "string") invalidField(`${context} plan`, "id", errors);
69
- if (typeof tenant.plan.name !== "string") invalidField(`${context} plan`, "name", errors);
148
+ if (!isOneOf(tenant.clusterType, ["SHARED", "DEDICATED"])) {
149
+ invalidField(context, "clusterType", errors);
150
+ }
70
151
  if (typeof tenant.name !== "string") invalidField(context, "name", errors);
71
152
  if (!isNullableString(tenant.description)) invalidField(context, "description", errors);
72
153
  if (!isNullableString(tenant.hexColor)) invalidField(context, "hexColor", errors);
@@ -82,11 +163,29 @@ function expectUser(value, context, errors = defaultSdkCoreErrorFactory) {
82
163
  if (typeof user.name !== "string") invalidField(context, "name", errors);
83
164
  if (typeof user.email !== "string") invalidField(context, "email", errors);
84
165
  if (!isNullableString(user.imageUrl)) invalidField(context, "imageUrl", errors);
166
+ if (typeof user.planId !== "string") invalidField(context, "planId", errors);
85
167
  if (typeof user.onboardingCompleted !== "boolean") {
86
168
  invalidField(context, "onboardingCompleted", errors);
87
169
  }
170
+ if (typeof user.language !== "string") invalidField(context, "language", errors);
88
171
  return user;
89
172
  }
173
+ function expectUserPlan(value, context, errors = defaultSdkCoreErrorFactory) {
174
+ const plan = expectObject(value, context, errors);
175
+ if (typeof plan.id !== "string") invalidField(context, "id", errors);
176
+ if (typeof plan.code !== "string") invalidField(context, "code", errors);
177
+ if (typeof plan.name !== "string") invalidField(context, "name", errors);
178
+ if (!isInteger(plan.maxUsers)) invalidField(context, "maxUsers", errors);
179
+ expectObjectArray(plan.prices, `${context} prices`, errors).forEach(
180
+ (price, position) => {
181
+ const priceContext = `${context} price ${position}`;
182
+ if (typeof price.currency !== "string") invalidField(priceContext, "currency", errors);
183
+ if (!isInteger(price.amountMinorUnits)) invalidField(priceContext, "amountMinorUnits", errors);
184
+ if (typeof price.interval !== "string") invalidField(priceContext, "interval", errors);
185
+ }
186
+ );
187
+ return plan;
188
+ }
90
189
  function expectQueryResult(value, context, errors = defaultSdkCoreErrorFactory) {
91
190
  const result = expectObject(value, context, errors);
92
191
  if (!Array.isArray(result.rows) || result.rows.some((row) => !isObject(row))) {
@@ -121,7 +220,7 @@ function expectFunctionExecution(value, context, errors = defaultSdkCoreErrorFac
121
220
  if (!isNullableInteger(execution.durationMs)) invalidField(context, "durationMs", errors);
122
221
  if (!isNullableString(execution.startedAt)) invalidField(context, "startedAt", errors);
123
222
  if (!isNullableString(execution.finishedAt)) invalidField(context, "finishedAt", errors);
124
- if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
223
+ if (!isNullableString(execution.createdAt)) invalidField(context, "createdAt", errors);
125
224
  return execution;
126
225
  }
127
226
  function expectProxyResult(value, context, errors = defaultSdkCoreErrorFactory) {
@@ -137,194 +236,2062 @@ function expectProxyResult(value, context, errors = defaultSdkCoreErrorFactory)
137
236
  if (typeof result.executionId !== "string") invalidField(context, "executionId", errors);
138
237
  return result;
139
238
  }
140
- function expectEmpty(value, context, errors = defaultSdkCoreErrorFactory) {
141
- if (value !== void 0) invalidResponse(`${context} must be empty`, errors);
239
+ function expectBatchExecution(value, context, errors = defaultSdkCoreErrorFactory) {
240
+ const execution = expectObject(value, context, errors);
241
+ expectObjectArray(execution.results, `${context} results`, errors).forEach(
242
+ (item, position) => {
243
+ const itemContext = `${context} result ${position}`;
244
+ if (!isInteger(item.index)) invalidField(itemContext, "index", errors);
245
+ if (hasOwn(item, "affectedRows") && !isInteger(item.affectedRows)) {
246
+ invalidField(itemContext, "affectedRows", errors);
247
+ }
248
+ if (!isInteger(item.durationMs)) invalidField(itemContext, "durationMs", errors);
249
+ }
250
+ );
251
+ if (!isInteger(execution.executedCount)) invalidField(context, "executedCount", errors);
252
+ if (!isInteger(execution.totalDurationMs)) invalidField(context, "totalDurationMs", errors);
253
+ return execution;
142
254
  }
143
-
144
- // src/modules/auth.ts
145
- function createAuthModule(transport, errors = defaultSdkCoreErrorFactory) {
146
- return {
147
- async me() {
148
- return expectUser(
149
- await transport.request("/api/v1/auth/me", { method: "GET" }),
150
- "Current user response",
151
- errors
152
- );
255
+ function expectSchemaTables(value, context, errors = defaultSdkCoreErrorFactory) {
256
+ const groups = expectObjectArray(value, context, errors);
257
+ groups.forEach((group, position) => {
258
+ const groupContext = `${context} group ${position}`;
259
+ if (typeof group.schema !== "string") invalidField(groupContext, "schema", errors);
260
+ expectObjectArray(group.tables, `${groupContext} tables`, errors).forEach(
261
+ (table, tablePosition) => {
262
+ const tableContext = `${groupContext} table ${tablePosition}`;
263
+ if (typeof table.tableName !== "string") invalidField(tableContext, "tableName", errors);
264
+ expectObjectArray(table.columns, `${tableContext} columns`, errors).forEach(
265
+ (column, columnPosition) => {
266
+ const columnContext = `${tableContext} column ${columnPosition}`;
267
+ if (typeof column.name !== "string") invalidField(columnContext, "name", errors);
268
+ if (typeof column.type !== "string") invalidField(columnContext, "type", errors);
269
+ if (typeof column.primaryKey !== "boolean") {
270
+ invalidField(columnContext, "primaryKey", errors);
271
+ }
272
+ if (typeof column.nullable !== "boolean") {
273
+ invalidField(columnContext, "nullable", errors);
274
+ }
275
+ if (!isNullableString(column.defaultValue)) {
276
+ invalidField(columnContext, "defaultValue", errors);
277
+ }
278
+ }
279
+ );
280
+ expectObjectArray(
281
+ table.foreignKeys,
282
+ `${tableContext} foreignKeys`,
283
+ errors
284
+ ).forEach((foreignKey, foreignKeyPosition) => {
285
+ const foreignKeyContext = `${tableContext} foreign key ${foreignKeyPosition}`;
286
+ if (!isStringArray(foreignKey.columns)) {
287
+ invalidField(foreignKeyContext, "columns", errors);
288
+ }
289
+ if (typeof foreignKey.referencedTable !== "string") {
290
+ invalidField(foreignKeyContext, "referencedTable", errors);
291
+ }
292
+ if (!isStringArray(foreignKey.referencedColumns)) {
293
+ invalidField(foreignKeyContext, "referencedColumns", errors);
294
+ }
295
+ });
296
+ }
297
+ );
298
+ });
299
+ return groups;
300
+ }
301
+ function expectBulkResult(value, context, idField, errors) {
302
+ const result = expectObject(value, context, errors);
303
+ expectObjectArray(result.results, `${context} results`, errors).forEach(
304
+ (item, position) => {
305
+ const itemContext = `${context} result ${position}`;
306
+ if (!isInteger(item.index)) invalidField(itemContext, "index", errors);
307
+ if (typeof item.success !== "boolean") invalidField(itemContext, "success", errors);
308
+ if (hasOwn(item, idField) && !isNullableString(item[idField])) {
309
+ invalidField(itemContext, idField, errors);
310
+ }
311
+ if (hasOwn(item, "errorCode") && !isNullableString(item.errorCode)) {
312
+ invalidField(itemContext, "errorCode", errors);
313
+ }
314
+ if (hasOwn(item, "message") && !isNullableString(item.message)) {
315
+ invalidField(itemContext, "message", errors);
316
+ }
153
317
  }
154
- };
318
+ );
319
+ if (!isInteger(result.processedCount)) invalidField(context, "processedCount", errors);
320
+ if (!isInteger(result.succeededCount)) invalidField(context, "succeededCount", errors);
321
+ if (!isInteger(result.failedCount)) invalidField(context, "failedCount", errors);
322
+ return result;
155
323
  }
156
-
157
- // src/path.ts
158
- function encodePathSegment(value, name, errors = defaultSdkCoreErrorFactory) {
159
- const segment = String(value);
160
- if (!segment.trim()) configurationError(`${name} must not be empty`, errors);
161
- if (segment === "." || segment === "..") {
162
- configurationError(`${name} must not be a dot segment`, errors);
324
+ function expectTemplateConfigBulkResult(value, context, errors = defaultSdkCoreErrorFactory) {
325
+ return expectBulkResult(value, context, "configId", errors);
326
+ }
327
+ function expectFunctionVersion(value, context, errors) {
328
+ const version = expectObject(value, context, errors);
329
+ if (typeof version.id !== "string") invalidField(context, "id", errors);
330
+ if (typeof version.functionId !== "string") invalidField(context, "functionId", errors);
331
+ if (typeof version.status !== "string") invalidField(context, "status", errors);
332
+ if (typeof version.code !== "string") invalidField(context, "code", errors);
333
+ if (version.inputSchema !== null && !isObject(version.inputSchema)) {
334
+ invalidField(context, "inputSchema", errors);
163
335
  }
164
- return encodeURIComponent(segment);
336
+ if (version.outputSchema !== null && !isObject(version.outputSchema)) {
337
+ invalidField(context, "outputSchema", errors);
338
+ }
339
+ if (version.secrets !== null && !isStringArray(version.secrets)) {
340
+ invalidField(context, "secrets", errors);
341
+ }
342
+ if (typeof version.createdAt !== "string") invalidField(context, "createdAt", errors);
165
343
  }
166
-
167
- // src/modules/entities.ts
168
- var DefaultEntitiesModule = class {
169
- constructor(transport, errors) {
170
- this.transport = transport;
171
- this.errors = errors;
344
+ function expectFunctionDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
345
+ const definition = expectObject(value, context, errors);
346
+ if (typeof definition.id !== "string") invalidField(context, "id", errors);
347
+ if (typeof definition.tenantId !== "string") invalidField(context, "tenantId", errors);
348
+ if (!isNullableString(definition.appId)) invalidField(context, "appId", errors);
349
+ if (!isNullableInteger(definition.legacyId)) invalidField(context, "legacyId", errors);
350
+ if (typeof definition.name !== "string") invalidField(context, "name", errors);
351
+ if (!isNullableString(definition.description)) invalidField(context, "description", errors);
352
+ if (typeof definition.runtime !== "string") invalidField(context, "runtime", errors);
353
+ if (!isNullableString(definition.dataSourceId)) invalidField(context, "dataSourceId", errors);
354
+ if (typeof definition.visibility !== "string") invalidField(context, "visibility", errors);
355
+ if (definition.currentVersion !== null) {
356
+ expectFunctionVersion(definition.currentVersion, `${context} current version`, errors);
172
357
  }
173
- tables = /* @__PURE__ */ new Map();
174
- getTable(tableName) {
175
- if (!this.tables.has(tableName)) {
176
- this.tables.set(tableName, this.createTable(tableName));
358
+ if (!isNullableString(definition.cronExpression)) {
359
+ invalidField(context, "cronExpression", errors);
360
+ }
361
+ if (definition.cronInputJson !== null && !isJsonRecord(definition.cronInputJson)) {
362
+ invalidField(context, "cronInputJson", errors);
363
+ }
364
+ if (!isNullableBoolean(definition.cronEnabled)) invalidField(context, "cronEnabled", errors);
365
+ if (!isNullableString(definition.createdAt)) invalidField(context, "createdAt", errors);
366
+ if (typeof definition.updatedAt !== "string") invalidField(context, "updatedAt", errors);
367
+ return definition;
368
+ }
369
+ function expectFunctionDefinitions(value, context, errors = defaultSdkCoreErrorFactory) {
370
+ return expectObjectArray(value, context, errors).map(
371
+ (item, position) => expectFunctionDefinition(item, `${context} item ${position}`, errors)
372
+ );
373
+ }
374
+ function expectFunctionBulkDeleteResult(value, context, errors = defaultSdkCoreErrorFactory) {
375
+ const result = expectObject(value, context, errors);
376
+ if (!isStringArray(result.deleted)) invalidField(context, "deleted", errors);
377
+ if (!isStringArray(result.notFound)) invalidField(context, "notFound", errors);
378
+ if (!isInteger(result.deletedCount)) invalidField(context, "deletedCount", errors);
379
+ return result;
380
+ }
381
+ function expectTemplateConfigPage(value, context, errors = defaultSdkCoreErrorFactory) {
382
+ return expectLegacyPage(value, context, errors, expectTemplateConfigSummary);
383
+ }
384
+ function expectConnectionTestResult(value, context, errors = defaultSdkCoreErrorFactory) {
385
+ const result = expectObject(value, context, errors);
386
+ if (!isOneOf(result.status, ["unchecked", "connected", "error"])) {
387
+ invalidField(context, "status", errors);
388
+ }
389
+ if (!isInteger(result.durationMs)) invalidField(context, "durationMs", errors);
390
+ if (typeof result.checkedAt !== "string") invalidField(context, "checkedAt", errors);
391
+ if (!isNullableString(result.message)) invalidField(context, "message", errors);
392
+ return result;
393
+ }
394
+ function expectAppMembers(value, context, errors = defaultSdkCoreErrorFactory) {
395
+ const members = expectObjectArray(value, context, errors);
396
+ members.forEach((member, position) => {
397
+ const memberContext = `${context} member ${position}`;
398
+ if (typeof member.userId !== "string") invalidField(memberContext, "userId", errors);
399
+ if (typeof member.name !== "string") invalidField(memberContext, "name", errors);
400
+ if (typeof member.email !== "string") invalidField(memberContext, "email", errors);
401
+ if (typeof member.accessLevel !== "string") invalidField(memberContext, "accessLevel", errors);
402
+ if (typeof member.accessSource !== "string") {
403
+ invalidField(memberContext, "accessSource", errors);
177
404
  }
178
- return this.tables.get(tableName);
405
+ });
406
+ return members;
407
+ }
408
+ function expectBulkUnsubscribeResult(value, context, errors = defaultSdkCoreErrorFactory) {
409
+ const result = expectObject(value, context, errors);
410
+ if (!isStringArray(result.revoked)) invalidField(context, "revoked", errors);
411
+ if (!isStringArray(result.notFound)) invalidField(context, "notFound", errors);
412
+ if (!isInteger(result.revokedCount)) invalidField(context, "revokedCount", errors);
413
+ return result;
414
+ }
415
+ function expectAppDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
416
+ const app = expectObject(value, context, errors);
417
+ expectAppFields(app, context, errors);
418
+ if (!isNullableString(app.dataSourceId)) invalidField(context, "dataSourceId", errors);
419
+ return app;
420
+ }
421
+ function expectAppSummary(value, context, errors = defaultSdkCoreErrorFactory) {
422
+ const app = expectObject(value, context, errors);
423
+ expectAppFields(app, context, errors);
424
+ if (typeof app.tenantId !== "string") invalidField(context, "tenantId", errors);
425
+ return app;
426
+ }
427
+ function expectAppFields(app, context, errors) {
428
+ for (const field of ["id", "shortId", "subdomain", "brand", "name", "planId"]) {
429
+ if (typeof app[field] !== "string") invalidField(context, field, errors);
179
430
  }
180
- createTable(tableName) {
181
- const basePath = `/api/v1/tables/${encodePathSegment(tableName, "tableName", this.errors)}/records`;
182
- return {
183
- list: async (sortOrOptions, limit, skip, fields) => {
184
- const options = typeof sortOrOptions === "object" ? sortOrOptions : void 0;
185
- const params = {
186
- sort: options?.sort ?? (typeof sortOrOptions === "string" ? sortOrOptions : void 0),
187
- limit: options?.limit ?? limit,
188
- skip: options?.skip ?? skip,
189
- fields: (options?.fields ?? fields)?.join(",")
190
- };
191
- const response = expectObject(
192
- await this.transport.request(basePath, { method: "GET", params }),
193
- "Entity list response",
194
- this.errors
195
- );
196
- return expectObjectArray(response.data, "Entity list data", this.errors);
197
- },
198
- filter: async (query, sort, limit, skip, fields) => {
199
- const response = expectObject(
200
- await this.transport.request(basePath, {
201
- method: "GET",
202
- params: {
203
- q: JSON.stringify(query),
204
- sort,
205
- limit,
206
- skip,
207
- fields: fields?.join(",")
208
- }
209
- }),
210
- "Entity list response",
211
- this.errors
212
- );
213
- return expectObjectArray(response.data, "Entity list data", this.errors);
214
- },
215
- get: async (id) => expectObject(
216
- await this.transport.request(
217
- `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
218
- { method: "GET" }
219
- ),
220
- "Entity response",
221
- this.errors
222
- ),
223
- create: async (data) => expectObject(
224
- await this.transport.request(basePath, { method: "POST", body: data }),
225
- "Created entity response",
226
- this.errors
227
- ),
228
- bulkCreate: async (data) => expectObjectArray(
229
- await this.transport.request(`${basePath}/bulk`, {
230
- method: "POST",
231
- body: data
232
- }),
233
- "Bulk create response",
234
- this.errors
235
- ),
236
- update: async (id, data) => expectObject(
237
- await this.transport.request(
238
- `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
239
- { method: "PUT", body: data }
240
- ),
241
- "Updated entity response",
242
- this.errors
243
- ),
244
- delete: (id) => this.transport.request(`${basePath}/${encodePathSegment(id, "id", this.errors)}`, {
245
- method: "DELETE"
246
- }).then((response) => expectEmpty(response, "Delete entity response", this.errors)),
247
- deleteMany: async (query) => {
248
- if (Object.keys(query).length === 0) {
249
- configurationError("query must not be empty for deleteMany", this.errors);
250
- }
251
- const response = expectObject(
252
- await this.transport.request(basePath, {
253
- method: "DELETE",
254
- params: { q: JSON.stringify(query) }
255
- }),
256
- "Delete many response",
257
- this.errors
258
- );
259
- if (!Number.isInteger(response.deleted)) {
260
- return invalidResponse(
261
- "Delete many response must include an integer deleted count",
262
- this.errors
263
- );
264
- }
265
- return { deleted: response.deleted };
266
- }
267
- };
431
+ if (!isNullableInteger(app.legacyId)) invalidField(context, "legacyId", errors);
432
+ if (!isNullableString(app.description)) invalidField(context, "description", errors);
433
+ if (!isNullableString(app.icon)) invalidField(context, "icon", errors);
434
+ if (!isNullableString(app.template)) invalidField(context, "template", errors);
435
+ if (typeof app.allowSignup !== "boolean") invalidField(context, "allowSignup", errors);
436
+ if (typeof app.externalAccessEnabled !== "boolean") {
437
+ invalidField(context, "externalAccessEnabled", errors);
268
438
  }
269
- };
270
- function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
271
- const instance = new DefaultEntitiesModule(transport, errors);
272
- return new Proxy(instance, {
273
- get(target, property, receiver) {
274
- if (typeof property !== "string" || property in target) {
275
- return Reflect.get(target, property, receiver);
439
+ expectAppColor(app.color, `${context} color`, errors);
440
+ expectObjectArray(app.domains, `${context} domains`, errors).forEach(
441
+ (domain, position) => {
442
+ const domainContext = `${context} domain ${position}`;
443
+ if (typeof domain.hostname !== "string") invalidField(domainContext, "hostname", errors);
444
+ if (!isOneOf(domain.kind, ["PLATFORM", "CUSTOM"])) {
445
+ invalidField(domainContext, "kind", errors);
446
+ }
447
+ if (!isOneOf(domain.status, ["ACTIVE", "PENDING", "INACTIVE"])) {
448
+ invalidField(domainContext, "status", errors);
276
449
  }
277
- return target.getTable(property);
278
450
  }
279
- });
451
+ );
452
+ if (app.currentVersion !== null) {
453
+ expectAppVersion(app.currentVersion, `${context} currentVersion`, errors);
454
+ }
455
+ if (typeof app.createdAt !== "string") invalidField(context, "createdAt", errors);
456
+ if (typeof app.updatedAt !== "string") invalidField(context, "updatedAt", errors);
280
457
  }
281
-
282
- // src/modules/functions.ts
283
- var DefaultFunctionsModule = class {
284
- constructor(transport, errors, options) {
285
- this.transport = transport;
286
- this.errors = errors;
287
- this.options = options;
458
+ function expectAppColor(value, context, errors) {
459
+ const color = expectObject(value, context, errors);
460
+ if (color.type === "SOLID") {
461
+ if (typeof color.hex !== "string") invalidField(context, "hex", errors);
462
+ return;
288
463
  }
289
- execute(id, input) {
290
- return this.executeWithType(id, this.options.executeInvocationType, input);
464
+ if (color.type === "GRADIENT") {
465
+ if (typeof color.startHex !== "string") invalidField(context, "startHex", errors);
466
+ if (typeof color.endHex !== "string") invalidField(context, "endHex", errors);
467
+ return;
291
468
  }
292
- executeAsync(id, input) {
293
- return this.executeWithType(id, "async", input);
469
+ invalidField(context, "type", errors);
470
+ }
471
+ function expectAppDeploy(value, context, errors = defaultSdkCoreErrorFactory) {
472
+ const deploy = expectObject(value, context, errors);
473
+ if (typeof deploy.id !== "string") invalidField(context, "id", errors);
474
+ if (typeof deploy.appId !== "string") invalidField(context, "appId", errors);
475
+ if (typeof deploy.appVersionId !== "string") invalidField(context, "appVersionId", errors);
476
+ if (!isOneOf(deploy.status, ["PENDING", "BUILDING", "DEPLOYED", "FAILED", "CANCELLED"])) {
477
+ invalidField(context, "status", errors);
294
478
  }
295
- getExecution(id) {
296
- return this.transport.request(
297
- `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}`,
298
- { method: "GET" }
299
- ).then(
300
- (response) => expectFunctionExecution(response, "Function execution response", this.errors)
301
- );
479
+ for (const field of ["deployUrl", "errorMessage", "logs", "startedAt", "finishedAt"]) {
480
+ if (!isNullableString(deploy[field])) invalidField(context, field, errors);
302
481
  }
303
- cancelExecution(id) {
304
- return this.transport.request(
305
- `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}/cancel`,
306
- { method: "POST" }
307
- ).then((response) => expectEmpty(response, "Cancel execution response", this.errors));
482
+ if (!isNullableInteger(deploy.durationMs)) invalidField(context, "durationMs", errors);
483
+ if (typeof deploy.createdAt !== "string") invalidField(context, "createdAt", errors);
484
+ return deploy;
485
+ }
486
+ function expectAppVersion(value, context, errors = defaultSdkCoreErrorFactory) {
487
+ const version = expectObject(value, context, errors);
488
+ if (typeof version.id !== "string") invalidField(context, "id", errors);
489
+ if (typeof version.appId !== "string") invalidField(context, "appId", errors);
490
+ if (!isOneOf(version.status, ["DRAFT", "PUBLISHED"])) {
491
+ invalidField(context, "status", errors);
308
492
  }
309
- executeWithType(id, invocationType, input) {
310
- const request = {
311
- method: "POST",
312
- ...input !== void 0 || this.options.emptyInput !== "omit-body" ? { body: { input: input ?? {} } } : {},
313
- ...invocationType === void 0 ? {} : { headers: { "X-Invocation-Type": invocationType } }
314
- };
315
- return this.transport.request(
316
- `/api/v1/functions/${encodePathSegment(id, "function id", this.errors)}/execute`,
317
- request
318
- ).then(
319
- (response) => expectFunctionExecution(response, "Function execution response", this.errors)
320
- );
493
+ if (version.currentDeploy !== null) {
494
+ expectAppDeploy(version.currentDeploy, `${context} currentDeploy`, errors);
321
495
  }
322
- };
323
- function createFunctionsModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
324
- return new DefaultFunctionsModule(transport, errors, options);
496
+ if (typeof version.createdAt !== "string") invalidField(context, "createdAt", errors);
497
+ return version;
325
498
  }
326
-
327
- // src/modules/integration.ts
499
+ function expectCustomQueryDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
500
+ const query = expectCustomQuerySummary(value, context, errors);
501
+ if (typeof query.sql !== "string") invalidField(context, "sql", errors);
502
+ return query;
503
+ }
504
+ function expectCustomQuerySummary(value, context, errors = defaultSdkCoreErrorFactory) {
505
+ const query = expectObject(value, context, errors);
506
+ if (typeof query.id !== "string") invalidField(context, "id", errors);
507
+ if (typeof query.name !== "string") invalidField(context, "name", errors);
508
+ if (typeof query.isVirtualTable !== "boolean") invalidField(context, "isVirtualTable", errors);
509
+ if (!isNullableString(query.connectionId)) invalidField(context, "connectionId", errors);
510
+ if (!isNullableString(query.createdAt)) invalidField(context, "createdAt", errors);
511
+ if (typeof query.updatedAt !== "string") invalidField(context, "updatedAt", errors);
512
+ return query;
513
+ }
514
+ function expectConnectionConfig(value, context, errors) {
515
+ const config = expectObject(value, context, errors);
516
+ for (const field of ["host", "schema", "databaseName", "username"]) {
517
+ if (!isNullableString(config[field])) invalidField(context, field, errors);
518
+ }
519
+ if (!isNullableInteger(config.port)) invalidField(context, "port", errors);
520
+ for (const field of [
521
+ "maxPoolSize",
522
+ "connectionTimeoutMs",
523
+ "idleTimeoutMs",
524
+ "minimumIdle",
525
+ "maxLifetimeMs"
526
+ ]) {
527
+ if (!isNullableInteger(config[field])) invalidField(context, field, errors);
528
+ }
529
+ if (config.additionalParams !== null && !isStringRecord(config.additionalParams)) {
530
+ invalidField(context, "additionalParams", errors);
531
+ }
532
+ if (config.credential !== null) invalidField(context, "credential", errors);
533
+ }
534
+ function expectDataSourceDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
535
+ const dataSource = expectObject(value, context, errors);
536
+ if (typeof dataSource.id !== "string") invalidField(context, "id", errors);
537
+ if (!isNullableInteger(dataSource.legacyId)) invalidField(context, "legacyId", errors);
538
+ if (!isNullableString(dataSource.appId)) invalidField(context, "appId", errors);
539
+ if (typeof dataSource.name !== "string") invalidField(context, "name", errors);
540
+ if (!isOneOf(dataSource.instanceType, ["MITRA_SHARED", "MITRA_DEDICATED", "EXTERNAL"])) {
541
+ invalidField(context, "instanceType", errors);
542
+ }
543
+ if (!isOneOf(dataSource.dbType, ["POSTGRES", "MYSQL", "SQLSERVER", "ORACLE"])) {
544
+ invalidField(context, "dbType", errors);
545
+ }
546
+ expectConnectionConfig(
547
+ dataSource.writeConnectionConfig,
548
+ `${context} writeConnectionConfig`,
549
+ errors
550
+ );
551
+ if (dataSource.readConnectionConfig !== null) {
552
+ expectConnectionConfig(
553
+ dataSource.readConnectionConfig,
554
+ `${context} readConnectionConfig`,
555
+ errors
556
+ );
557
+ }
558
+ if (dataSource.connectionStatus !== null && !isOneOf(dataSource.connectionStatus, ["CONNECTED", "ERROR"])) {
559
+ invalidField(context, "connectionStatus", errors);
560
+ }
561
+ if (!isNullableString(dataSource.lastCheckedAt)) invalidField(context, "lastCheckedAt", errors);
562
+ if (dataSource.storageQuota !== null) {
563
+ const quota = expectObject(
564
+ dataSource.storageQuota,
565
+ `${context} storageQuota`,
566
+ errors
567
+ );
568
+ if (quota.status !== null && !isOneOf(quota.status, ["NORMAL", "WATCH", "BLOCKED"])) {
569
+ invalidField(`${context} storageQuota`, "status", errors);
570
+ }
571
+ for (const field of ["usedBytes", "limitBytes", "measurementVersion"]) {
572
+ if (!isNullableInteger(quota[field])) invalidField(`${context} storageQuota`, field, errors);
573
+ }
574
+ if (!isNullableString(quota.measuredAt)) {
575
+ invalidField(`${context} storageQuota`, "measuredAt", errors);
576
+ }
577
+ }
578
+ return dataSource;
579
+ }
580
+ function expectImportSource(value, context, errors) {
581
+ const source = expectObject(value, context, errors);
582
+ if (source.type === "SQL") {
583
+ if (typeof source.query !== "string") invalidField(context, "query", errors);
584
+ return;
585
+ }
586
+ if (source.type === "CSV") {
587
+ if (typeof source.fileKey !== "string") invalidField(context, "fileKey", errors);
588
+ if (typeof source.separator !== "string") invalidField(context, "separator", errors);
589
+ return;
590
+ }
591
+ invalidField(context, "type", errors);
592
+ }
593
+ function expectImportDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
594
+ const definition = expectObject(value, context, errors);
595
+ if (typeof definition.id !== "string") invalidField(context, "id", errors);
596
+ if (!isNullableInteger(definition.legacyId)) invalidField(context, "legacyId", errors);
597
+ if (typeof definition.name !== "string") invalidField(context, "name", errors);
598
+ expectImportSource(definition.source, `${context} source`, errors);
599
+ const target = expectObject(definition.target, `${context} target`, errors);
600
+ if (typeof target.tableName !== "string") invalidField(`${context} target`, "tableName", errors);
601
+ if (!isOneOf(target.mode, ["REPLACE", "APPEND", "UPSERT"])) {
602
+ invalidField(`${context} target`, "mode", errors);
603
+ }
604
+ if (target.upsertKeyColumns !== null && !isStringArray(target.upsertKeyColumns)) {
605
+ invalidField(`${context} target`, "upsertKeyColumns", errors);
606
+ }
607
+ const processing = expectObject(
608
+ definition.processing,
609
+ `${context} processing`,
610
+ errors
611
+ );
612
+ if (!isOneOf(processing.mode, ["CHUNKED", "STREAMING"])) {
613
+ invalidField(`${context} processing`, "mode", errors);
614
+ }
615
+ if (!isNullableString(processing.orderColumn)) {
616
+ invalidField(`${context} processing`, "orderColumn", errors);
617
+ }
618
+ if (!isInteger(processing.chunkSize)) invalidField(`${context} processing`, "chunkSize", errors);
619
+ const schedule = expectObject(definition.schedule, `${context} schedule`, errors);
620
+ if (!isNullableString(schedule.cron)) invalidField(`${context} schedule`, "cron", errors);
621
+ if (typeof schedule.enabled !== "boolean") invalidField(`${context} schedule`, "enabled", errors);
622
+ if (definition.columnMappings !== null) {
623
+ expectObjectArray(
624
+ definition.columnMappings,
625
+ `${context} columnMappings`,
626
+ errors
627
+ ).forEach((mapping, position) => {
628
+ const mappingContext = `${context} columnMapping ${position}`;
629
+ if (typeof mapping.source !== "string") invalidField(mappingContext, "source", errors);
630
+ if (typeof mapping.target !== "string") invalidField(mappingContext, "target", errors);
631
+ if (hasOwn(mapping, "type") && !isNullableString(mapping.type)) {
632
+ invalidField(mappingContext, "type", errors);
633
+ }
634
+ });
635
+ }
636
+ if (typeof definition.createdAt !== "string") invalidField(context, "createdAt", errors);
637
+ if (typeof definition.updatedAt !== "string") invalidField(context, "updatedAt", errors);
638
+ return definition;
639
+ }
640
+ function expectImportExecution(value, context, errors = defaultSdkCoreErrorFactory) {
641
+ const execution = expectObject(value, context, errors);
642
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
643
+ if (typeof execution.importDefinitionId !== "string") {
644
+ invalidField(context, "importDefinitionId", errors);
645
+ }
646
+ if (!isNullableString(execution.importName)) invalidField(context, "importName", errors);
647
+ if (!isOneOf(execution.status, [
648
+ "PENDING",
649
+ "PREPARING",
650
+ "RUNNING",
651
+ "COMPLETED",
652
+ "PARTIALLY_COMPLETED",
653
+ "FAILED",
654
+ "CANCELLED"
655
+ ])) {
656
+ invalidField(context, "status", errors);
657
+ }
658
+ if (!isOneOf(execution.triggerType, ["MANUAL", "SCHEDULED", "API"])) {
659
+ invalidField(context, "triggerType", errors);
660
+ }
661
+ for (const field of ["totalChunks", "progressPercent", "rowsTotal", "durationSeconds"]) {
662
+ if (!isNullableInteger(execution[field])) invalidField(context, field, errors);
663
+ }
664
+ for (const field of ["completedChunks", "failedChunks", "rowsProcessed"]) {
665
+ if (!isInteger(execution[field])) invalidField(context, field, errors);
666
+ }
667
+ if (typeof execution.queuedAt !== "string") invalidField(context, "queuedAt", errors);
668
+ if (!isNullableString(execution.startedAt)) invalidField(context, "startedAt", errors);
669
+ if (!isNullableString(execution.completedAt)) invalidField(context, "completedAt", errors);
670
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
671
+ return execution;
672
+ }
673
+ function expectMessageAccepted(value, context, errors = defaultSdkCoreErrorFactory) {
674
+ const response = expectObject(value, context, errors);
675
+ if (typeof response.messageId !== "string") invalidField(context, "messageId", errors);
676
+ return response;
677
+ }
678
+ function expectAgentDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
679
+ const agent = expectObject(value, context, errors);
680
+ if (typeof agent.id !== "string") invalidField(context, "id", errors);
681
+ if (typeof agent.name !== "string") invalidField(context, "name", errors);
682
+ if (!isStringArray(agent.functionIds)) invalidField(context, "functionIds", errors);
683
+ if (typeof agent.autonomous !== "boolean") invalidField(context, "autonomous", errors);
684
+ if (typeof agent.createdAt !== "string") invalidField(context, "createdAt", errors);
685
+ if (typeof agent.updatedAt !== "string") invalidField(context, "updatedAt", errors);
686
+ return agent;
687
+ }
688
+ function expectAgentBulkDeleteResult(value, context, errors = defaultSdkCoreErrorFactory) {
689
+ const result = expectObject(value, context, errors);
690
+ if (!isStringArray(result.deleted)) invalidField(context, "deleted", errors);
691
+ if (!isStringArray(result.notFound)) invalidField(context, "notFound", errors);
692
+ if (!isInteger(result.deletedCount)) invalidField(context, "deletedCount", errors);
693
+ return result;
694
+ }
695
+ function expectWorkflowDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
696
+ const workflow = expectWorkflowSummary(value, context, errors);
697
+ if (!isObject(workflow.definition)) invalidField(context, "definition", errors);
698
+ return workflow;
699
+ }
700
+ function expectWorkflowSummary(value, context, errors = defaultSdkCoreErrorFactory) {
701
+ const workflow = expectObject(value, context, errors);
702
+ if (typeof workflow.id !== "string") invalidField(context, "id", errors);
703
+ if (typeof workflow.tenantId !== "string") invalidField(context, "tenantId", errors);
704
+ if (!isNullableString(workflow.appId)) invalidField(context, "appId", errors);
705
+ if (typeof workflow.name !== "string") invalidField(context, "name", errors);
706
+ if (typeof workflow.createdAt !== "string") invalidField(context, "createdAt", errors);
707
+ if (typeof workflow.updatedAt !== "string") invalidField(context, "updatedAt", errors);
708
+ return workflow;
709
+ }
710
+ function expectWorkflowExecution(value, context, errors = defaultSdkCoreErrorFactory) {
711
+ const execution = expectObject(value, context, errors);
712
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
713
+ if (typeof execution.tenantId !== "string") invalidField(context, "tenantId", errors);
714
+ if (!isNullableString(execution.appId)) invalidField(context, "appId", errors);
715
+ if (typeof execution.workflowId !== "string") invalidField(context, "workflowId", errors);
716
+ if (!isOneOf(execution.triggerType, ["MANUAL", "SCHEDULED"])) {
717
+ invalidField(context, "triggerType", errors);
718
+ }
719
+ if (!isNullableString(execution.triggeredBy)) invalidField(context, "triggeredBy", errors);
720
+ if (!isOneOf(execution.status, ["PENDING", "RUNNING", "SUCCESS", "FAILED", "CANCELLED"])) {
721
+ invalidField(context, "status", errors);
722
+ }
723
+ if (!isNullableString(execution.currentStepId)) invalidField(context, "currentStepId", errors);
724
+ if (execution.context !== null && !isJsonRecord(execution.context)) {
725
+ invalidField(context, "context", errors);
726
+ }
727
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
728
+ if (!isNullableString(execution.startedAt)) invalidField(context, "startedAt", errors);
729
+ if (!isNullableString(execution.finishedAt)) invalidField(context, "finishedAt", errors);
730
+ if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
731
+ return execution;
732
+ }
733
+ function expectIntegrationResource(value, context, errors = defaultSdkCoreErrorFactory) {
734
+ const resource = expectObject(value, context, errors);
735
+ if (typeof resource.id !== "string") invalidField(context, "id", errors);
736
+ if (typeof resource.tenantId !== "string") invalidField(context, "tenantId", errors);
737
+ if (typeof resource.templateConfigId !== "string")
738
+ invalidField(context, "templateConfigId", errors);
739
+ if (typeof resource.name !== "string") invalidField(context, "name", errors);
740
+ if (typeof resource.method !== "string") invalidField(context, "method", errors);
741
+ if (typeof resource.endpoint !== "string") invalidField(context, "endpoint", errors);
742
+ if (resource.body !== null && !isJsonRecord(resource.body)) {
743
+ invalidField(context, "body", errors);
744
+ }
745
+ const params = expectObject(resource.params, `${context} params`, errors);
746
+ Object.entries(params).forEach(([name, value2]) => {
747
+ const paramContext = `${context} param ${name}`;
748
+ const param = expectObject(value2, paramContext, errors);
749
+ if (typeof param.type !== "string") invalidField(paramContext, "type", errors);
750
+ if (typeof param.required !== "boolean") invalidField(paramContext, "required", errors);
751
+ if (!isJsonValue(param.defaultValue)) invalidField(paramContext, "defaultValue", errors);
752
+ if (!isNullableString(param.description)) invalidField(paramContext, "description", errors);
753
+ });
754
+ if (typeof resource.createdAt !== "string") invalidField(context, "createdAt", errors);
755
+ if (typeof resource.updatedAt !== "string") invalidField(context, "updatedAt", errors);
756
+ return resource;
757
+ }
758
+ function expectIntegrationResourceSummary(value, context, errors = defaultSdkCoreErrorFactory) {
759
+ const resource = expectObject(value, context, errors);
760
+ if (typeof resource.id !== "string") invalidField(context, "id", errors);
761
+ if (typeof resource.name !== "string") invalidField(context, "name", errors);
762
+ if (typeof resource.method !== "string") invalidField(context, "method", errors);
763
+ if (typeof resource.endpoint !== "string") invalidField(context, "endpoint", errors);
764
+ return resource;
765
+ }
766
+ function expectIntegrationTemplateSummary(value, context, errors = defaultSdkCoreErrorFactory) {
767
+ const template = expectObject(value, context, errors);
768
+ if (typeof template.id !== "string") invalidField(context, "id", errors);
769
+ if (typeof template.name !== "string") invalidField(context, "name", errors);
770
+ if (!isNullableString(template.baseUrl)) invalidField(context, "baseUrl", errors);
771
+ if (!isOneOf(template.proxyMode, ["OPEN", "RESOURCE_ONLY"])) {
772
+ invalidField(context, "proxyMode", errors);
773
+ }
774
+ if (!isNullableString(template.logoUrl)) invalidField(context, "logoUrl", errors);
775
+ if (!isOneOf(template.templateType, ["GENERIC_AUTH", "PROVIDER"])) {
776
+ invalidField(context, "templateType", errors);
777
+ }
778
+ return template;
779
+ }
780
+ function expectIntegrationTemplate(value, context, errors = defaultSdkCoreErrorFactory) {
781
+ const template = expectIntegrationTemplateSummary(value, context, errors);
782
+ if (template.loginConfig !== null) {
783
+ expectIntegrationLoginConfig(template.loginConfig, `${context} loginConfig`, errors);
784
+ }
785
+ expectIntegrationRequestConfig(template.requestConfig, `${context} requestConfig`, errors);
786
+ expectObjectArray(template.fieldsSchema, `${context} fieldsSchema`, errors).forEach(
787
+ (field, position) => {
788
+ const fieldContext = `${context} field ${position}`;
789
+ if (typeof field.key !== "string") invalidField(fieldContext, "key", errors);
790
+ if (typeof field.label !== "string") invalidField(fieldContext, "label", errors);
791
+ if (!isOneOf(field.type, ["url", "text", "secret"])) {
792
+ invalidField(fieldContext, "type", errors);
793
+ }
794
+ if (typeof field.required !== "boolean") invalidField(fieldContext, "required", errors);
795
+ if (!isNullableString(field.placeholder)) invalidField(fieldContext, "placeholder", errors);
796
+ if (!isNullableString(field.default)) invalidField(fieldContext, "default", errors);
797
+ }
798
+ );
799
+ if (!isNullableString(template.documentationUrl)) {
800
+ invalidField(context, "documentationUrl", errors);
801
+ }
802
+ return template;
803
+ }
804
+ function expectIntegrationLoginConfig(value, context, errors) {
805
+ const config = expectObject(value, context, errors);
806
+ if (!isNullableString(config.url)) invalidField(context, "url", errors);
807
+ if (!isNullableString(config.method)) invalidField(context, "method", errors);
808
+ for (const field of ["headers", "query_params", "body_form", "body"]) {
809
+ if (config[field] !== null && !isJsonRecord(config[field])) {
810
+ invalidField(context, field, errors);
811
+ }
812
+ }
813
+ if (config.token_extraction !== null) {
814
+ const extraction = expectObject(
815
+ config.token_extraction,
816
+ `${context} token_extraction`,
817
+ errors
818
+ );
819
+ for (const field of ["source", "path", "name"]) {
820
+ if (!isNullableString(extraction[field])) {
821
+ invalidField(`${context} token_extraction`, field, errors);
822
+ }
823
+ }
824
+ }
825
+ if (!isNullableInteger(config.token_ttl_seconds)) {
826
+ invalidField(context, "token_ttl_seconds", errors);
827
+ }
828
+ }
829
+ function expectIntegrationRequestConfig(value, context, errors) {
830
+ const config = expectObject(value, context, errors);
831
+ if (config.headers !== null && !isJsonRecord(config.headers)) {
832
+ invalidField(context, "headers", errors);
833
+ }
834
+ if (config.credential_rules !== null) {
835
+ expectObjectArray(
836
+ config.credential_rules,
837
+ `${context} credential_rules`,
838
+ errors
839
+ ).forEach((rule, position) => {
840
+ const ruleContext = `${context} credential rule ${position}`;
841
+ if (rule.placement !== null && !isOneOf(rule.placement, ["HEADER", "QUERY", "COOKIE", "BODY", "BASIC"])) {
842
+ invalidField(ruleContext, "placement", errors);
843
+ }
844
+ for (const field of ["name", "path", "value"]) {
845
+ if (!isNullableString(rule[field])) invalidField(ruleContext, field, errors);
846
+ }
847
+ });
848
+ }
849
+ }
850
+ function expectTemplateConfigSummary(value, context, errors = defaultSdkCoreErrorFactory) {
851
+ const config = expectObject(value, context, errors);
852
+ if (typeof config.id !== "string") invalidField(context, "id", errors);
853
+ if (!isNullableString(config.appId)) invalidField(context, "appId", errors);
854
+ if (!isNullableInteger(config.legacyId)) invalidField(context, "legacyId", errors);
855
+ if (typeof config.templateId !== "string") invalidField(context, "templateId", errors);
856
+ if (typeof config.alias !== "string") invalidField(context, "alias", errors);
857
+ if (config.status !== null && !isOneOf(config.status, ["unchecked", "connected", "error"])) {
858
+ invalidField(context, "status", errors);
859
+ }
860
+ if (!isNullableString(config.lastCheckedAt)) invalidField(context, "lastCheckedAt", errors);
861
+ return config;
862
+ }
863
+ function expectTemplateConfig(value, context, errors = defaultSdkCoreErrorFactory) {
864
+ const config = expectTemplateConfigSummary(value, context, errors);
865
+ if (typeof config.tenantId !== "string") invalidField(context, "tenantId", errors);
866
+ if (!isJsonRecord(config.config)) invalidField(context, "config", errors);
867
+ if (!isNullableString(config.lastCheckMessage)) {
868
+ invalidField(context, "lastCheckMessage", errors);
869
+ }
870
+ if (typeof config.createdAt !== "string") invalidField(context, "createdAt", errors);
871
+ if (typeof config.updatedAt !== "string") invalidField(context, "updatedAt", errors);
872
+ return config;
873
+ }
874
+ function expectIntegrationExecution(value, context, errors = defaultSdkCoreErrorFactory) {
875
+ const execution = expectObject(value, context, errors);
876
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
877
+ if (typeof execution.templateConfigId !== "string") {
878
+ invalidField(context, "templateConfigId", errors);
879
+ }
880
+ if (!isNullableString(execution.appId)) invalidField(context, "appId", errors);
881
+ if (typeof execution.method !== "string") invalidField(context, "method", errors);
882
+ if (typeof execution.endpoint !== "string") invalidField(context, "endpoint", errors);
883
+ if (!hasOwn(execution, "requestBody") || !isJsonValue(execution.requestBody)) {
884
+ invalidField(context, "requestBody", errors);
885
+ }
886
+ if (!isNullableInteger(execution.responseStatus)) {
887
+ invalidField(context, "responseStatus", errors);
888
+ }
889
+ if (!hasOwn(execution, "responseBody") || !isJsonValue(execution.responseBody)) {
890
+ invalidField(context, "responseBody", errors);
891
+ }
892
+ if (!isNullableInteger(execution.durationMs)) invalidField(context, "durationMs", errors);
893
+ if (typeof execution.success !== "boolean") invalidField(context, "success", errors);
894
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
895
+ if (!isNullableString(execution.source)) invalidField(context, "source", errors);
896
+ if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
897
+ return execution;
898
+ }
899
+ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
900
+ const task = expectObject(value, context, errors);
901
+ if (typeof task.id !== "string") invalidField(context, "id", errors);
902
+ for (const field of ["appId", "agentId", "userId", "title", "reasoningEffort"]) {
903
+ if (!isNullableString(task[field])) invalidField(context, field, errors);
904
+ }
905
+ if (typeof task.agentType !== "string") invalidField(context, "agentType", errors);
906
+ if (typeof task.archived !== "boolean") invalidField(context, "archived", errors);
907
+ if (!isNullableString(task.createdAt)) invalidField(context, "createdAt", errors);
908
+ if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
909
+ return task;
910
+ }
911
+ function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
912
+ const message = expectObject(value, context, errors);
913
+ for (const field of ["id", "sender", "type", "content", "createdAt"]) {
914
+ if (typeof message[field] !== "string") invalidField(context, field, errors);
915
+ }
916
+ return message;
917
+ }
918
+ function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
919
+ const model = expectObject(value, context, errors);
920
+ for (const field of ["model", "name", "provider", "agentType"]) {
921
+ if (typeof model[field] !== "string") invalidField(context, field, errors);
922
+ }
923
+ if (!isStringArray(model.reasoningOptions)) invalidField(context, "reasoningOptions", errors);
924
+ return model;
925
+ }
926
+ function expectCredentialStatus(value, context, errors = defaultSdkCoreErrorFactory) {
927
+ const status = expectObject(value, context, errors);
928
+ if (typeof status.provider !== "string") invalidField(context, "provider", errors);
929
+ if (typeof status.connected !== "boolean") invalidField(context, "connected", errors);
930
+ for (const field of ["credentialType", "accountEmail", "maskedApiKey"]) {
931
+ if (!isNullableString(status[field])) invalidField(context, field, errors);
932
+ }
933
+ return status;
934
+ }
935
+ function expectOAuthStartResult(value, context, errors = defaultSdkCoreErrorFactory) {
936
+ const result = expectObject(value, context, errors);
937
+ if (typeof result.authUrl !== "string") invalidField(context, "authUrl", errors);
938
+ if (typeof result.state !== "string") invalidField(context, "state", errors);
939
+ return result;
940
+ }
941
+ function expectAuthenticationResult(value, context, errors = defaultSdkCoreErrorFactory) {
942
+ const result = expectObject(value, context, errors);
943
+ if (typeof result.connected !== "boolean") invalidField(context, "connected", errors);
944
+ if (!isNullableString(result.email)) invalidField(context, "email", errors);
945
+ return result;
946
+ }
947
+ function expectDeviceAuthorization(value, context, errors = defaultSdkCoreErrorFactory) {
948
+ const result = expectObject(value, context, errors);
949
+ for (const field of ["deviceAuthId", "userCode", "verificationUri"]) {
950
+ if (typeof result[field] !== "string") invalidField(context, field, errors);
951
+ }
952
+ if (!isInteger(result.intervalSeconds)) invalidField(context, "intervalSeconds", errors);
953
+ return result;
954
+ }
955
+ function expectProviderCredentialStatus(value, context, errors) {
956
+ const status = expectObject(value, context, errors);
957
+ if (typeof status.provider !== "string") invalidField(context, "provider", errors);
958
+ if (typeof status.connected !== "boolean") invalidField(context, "connected", errors);
959
+ if (!isNullableString(status.credentialType)) invalidField(context, "credentialType", errors);
960
+ if (!isNullableString(status.accountEmail)) invalidField(context, "accountEmail", errors);
961
+ return status;
962
+ }
963
+ function expectAgentConnection(value, context, errors = defaultSdkCoreErrorFactory) {
964
+ const connection = expectObject(value, context, errors);
965
+ if (typeof connection.id !== "string") invalidField(context, "id", errors);
966
+ if (typeof connection.name !== "string") invalidField(context, "name", errors);
967
+ if (typeof connection.createdAt !== "string") invalidField(context, "createdAt", errors);
968
+ if (typeof connection.updatedAt !== "string") invalidField(context, "updatedAt", errors);
969
+ expectObjectArray(
970
+ connection.credentials,
971
+ `${context} credentials`,
972
+ errors,
973
+ expectProviderCredentialStatus
974
+ );
975
+ return connection;
976
+ }
977
+ function expectTableDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
978
+ const wrapped = expectSchemaTables([{ schema: "validation", tables: [value] }], context, errors);
979
+ return wrapped[0].tables[0];
980
+ }
981
+ function expectFunctionSummary(value, context, errors = defaultSdkCoreErrorFactory) {
982
+ const summary = expectObject(value, context, errors);
983
+ if (typeof summary.id !== "string") invalidField(context, "id", errors);
984
+ if (typeof summary.tenantId !== "string") invalidField(context, "tenantId", errors);
985
+ if (!isNullableString(summary.appId)) invalidField(context, "appId", errors);
986
+ if (!isNullableInteger(summary.legacyId)) invalidField(context, "legacyId", errors);
987
+ if (typeof summary.name !== "string") invalidField(context, "name", errors);
988
+ if (!isNullableString(summary.description)) invalidField(context, "description", errors);
989
+ if (typeof summary.runtime !== "string") invalidField(context, "runtime", errors);
990
+ if (!isNullableString(summary.dataSourceId)) invalidField(context, "dataSourceId", errors);
991
+ if (typeof summary.visibility !== "string") invalidField(context, "visibility", errors);
992
+ if (!isNullableString(summary.cronExpression)) invalidField(context, "cronExpression", errors);
993
+ if (summary.cronInputJson !== null && !isJsonRecord(summary.cronInputJson)) {
994
+ invalidField(context, "cronInputJson", errors);
995
+ }
996
+ if (!isNullableBoolean(summary.cronEnabled)) invalidField(context, "cronEnabled", errors);
997
+ if (typeof summary.createdAt !== "string") invalidField(context, "createdAt", errors);
998
+ if (typeof summary.updatedAt !== "string") invalidField(context, "updatedAt", errors);
999
+ return summary;
1000
+ }
1001
+ function expectFunctionVersionResponse(value, context, errors = defaultSdkCoreErrorFactory) {
1002
+ expectFunctionVersion(value, context, errors);
1003
+ return value;
1004
+ }
1005
+ function expectFunctionSecrets(value, context, errors = defaultSdkCoreErrorFactory) {
1006
+ const result = expectObject(value, context, errors);
1007
+ if (!isStringArray(result.secrets)) invalidField(context, "secrets", errors);
1008
+ return result;
1009
+ }
1010
+ function expectPublicFunctionResult(value, context, errors = defaultSdkCoreErrorFactory) {
1011
+ const result = expectObject(value, context, errors);
1012
+ if (typeof result.success !== "boolean") invalidField(context, "success", errors);
1013
+ if (result.output !== null && !isObject(result.output)) invalidField(context, "output", errors);
1014
+ if (!isNullableString(result.error)) invalidField(context, "error", errors);
1015
+ return result;
1016
+ }
1017
+ function expectPublicFunctionAsyncResult(value, context, errors = defaultSdkCoreErrorFactory) {
1018
+ const result = expectObject(value, context, errors);
1019
+ if (typeof result.id !== "string") invalidField(context, "id", errors);
1020
+ if (typeof result.status !== "string") invalidField(context, "status", errors);
1021
+ return result;
1022
+ }
1023
+ function expectEmpty(value, context, errors = defaultSdkCoreErrorFactory) {
1024
+ if (value !== void 0) invalidResponse(`${context} must be empty`, errors);
1025
+ }
1026
+
1027
+ // src/modules/agentConnections.ts
1028
+ var MAX_CONNECTIONS = 100;
1029
+ function createAgentConnectionsModule(transport, errors = defaultSdkCoreErrorFactory) {
1030
+ const path = (id) => `/api/v1/connections/${encodePathSegment(id, "connection id", errors)}`;
1031
+ const providerPath = (id, provider) => `${path(id)}/providers/${encodePathSegment(provider, "provider", errors)}`;
1032
+ return {
1033
+ async list() {
1034
+ return expectObjectArray(
1035
+ await transport.request("/api/v1/connections", { method: "GET" }),
1036
+ "Connection response",
1037
+ errors,
1038
+ expectAgentConnection
1039
+ );
1040
+ },
1041
+ async get(id) {
1042
+ return expectAgentConnection(
1043
+ await transport.request(path(id), { method: "GET" }),
1044
+ "Connection response",
1045
+ errors
1046
+ );
1047
+ },
1048
+ async create(name) {
1049
+ return expectAgentConnection(
1050
+ await transport.request("/api/v1/connections", {
1051
+ method: "POST",
1052
+ body: { name }
1053
+ }),
1054
+ "Create connection response",
1055
+ errors
1056
+ );
1057
+ },
1058
+ async bulkCreate(inputs) {
1059
+ requireBatchSize(inputs, "connections", MAX_CONNECTIONS, errors);
1060
+ return expectObjectArray(
1061
+ await transport.request("/api/v1/connections/bulk", {
1062
+ method: "POST",
1063
+ body: { connections: inputs }
1064
+ }),
1065
+ "Bulk create connections response",
1066
+ errors,
1067
+ expectAgentConnection
1068
+ );
1069
+ },
1070
+ async delete(id) {
1071
+ expectEmpty(
1072
+ await transport.request(path(id), { method: "DELETE" }),
1073
+ "Delete connection response",
1074
+ errors
1075
+ );
1076
+ },
1077
+ async saveApiKey(id, provider, apiKey) {
1078
+ expectEmpty(
1079
+ await transport.request(`${providerPath(id, provider)}/api-key`, {
1080
+ method: "PUT",
1081
+ body: { apiKey }
1082
+ }),
1083
+ "Save connection API key response",
1084
+ errors
1085
+ );
1086
+ },
1087
+ async disconnectProvider(id, provider) {
1088
+ expectEmpty(
1089
+ await transport.request(providerPath(id, provider), { method: "DELETE" }),
1090
+ "Disconnect connection provider response",
1091
+ errors
1092
+ );
1093
+ },
1094
+ async startOAuth(id, provider) {
1095
+ return expectOAuthStartResult(
1096
+ await transport.request(`${providerPath(id, provider)}/oauth/start`, {
1097
+ method: "POST"
1098
+ }),
1099
+ "Connection OAuth start response",
1100
+ errors
1101
+ );
1102
+ },
1103
+ async exchangeOAuth(id, provider, input) {
1104
+ return expectAuthenticationResult(
1105
+ await transport.request(`${providerPath(id, provider)}/oauth/exchange`, {
1106
+ method: "POST",
1107
+ body: input
1108
+ }),
1109
+ "Connection OAuth exchange response",
1110
+ errors
1111
+ );
1112
+ },
1113
+ async startDeviceAuthorization(id, provider) {
1114
+ return expectDeviceAuthorization(
1115
+ await transport.request(`${providerPath(id, provider)}/device-authorizations`, {
1116
+ method: "POST"
1117
+ }),
1118
+ "Connection device authorization response",
1119
+ errors
1120
+ );
1121
+ },
1122
+ async pollDeviceAuthorization(id, provider, deviceAuthId) {
1123
+ return expectAuthenticationResult(
1124
+ await transport.request(
1125
+ `${providerPath(id, provider)}/device-authorizations/${encodePathSegment(
1126
+ deviceAuthId,
1127
+ "device authorization id",
1128
+ errors
1129
+ )}/poll`,
1130
+ { method: "POST" }
1131
+ ),
1132
+ "Connection device authorization poll response",
1133
+ errors
1134
+ );
1135
+ }
1136
+ };
1137
+ }
1138
+
1139
+ // src/modules/agentCredentials.ts
1140
+ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFactory) {
1141
+ const providerSegment = (provider) => encodePathSegment(provider, "provider", errors);
1142
+ return {
1143
+ async list() {
1144
+ return expectObjectArray(
1145
+ await transport.request("/api/v1/credentials", { method: "GET" }),
1146
+ "Credential status response",
1147
+ errors,
1148
+ expectCredentialStatus
1149
+ );
1150
+ },
1151
+ async listModels(agentId) {
1152
+ return expectObjectArray(
1153
+ await transport.request("/api/v1/models", {
1154
+ method: "GET",
1155
+ params: { agentId }
1156
+ }),
1157
+ "Agent model response",
1158
+ errors,
1159
+ expectAgentModel
1160
+ );
1161
+ },
1162
+ async saveApiKey(provider, apiKey) {
1163
+ expectEmpty(
1164
+ await transport.request(
1165
+ `/api/v1/credentials/${providerSegment(provider)}/api-key`,
1166
+ { method: "PUT", body: { apiKey } }
1167
+ ),
1168
+ "Save API key response",
1169
+ errors
1170
+ );
1171
+ },
1172
+ async remove(provider) {
1173
+ expectEmpty(
1174
+ await transport.request(`/api/v1/credentials/${providerSegment(provider)}`, {
1175
+ method: "DELETE"
1176
+ }),
1177
+ "Remove credential response",
1178
+ errors
1179
+ );
1180
+ },
1181
+ async startOAuth(provider) {
1182
+ return expectOAuthStartResult(
1183
+ await transport.request("/api/v1/oauth/start", {
1184
+ method: "POST",
1185
+ body: { provider }
1186
+ }),
1187
+ "OAuth start response",
1188
+ errors
1189
+ );
1190
+ },
1191
+ async exchangeOAuth(provider, input) {
1192
+ return expectAuthenticationResult(
1193
+ await transport.request("/api/v1/oauth/exchange", {
1194
+ method: "POST",
1195
+ body: { provider, ...input }
1196
+ }),
1197
+ "OAuth exchange response",
1198
+ errors
1199
+ );
1200
+ },
1201
+ async startDeviceAuthorization(provider) {
1202
+ return expectDeviceAuthorization(
1203
+ await transport.request(
1204
+ `/api/v1/credentials/${providerSegment(provider)}/device-authorizations`,
1205
+ { method: "POST" }
1206
+ ),
1207
+ "Device authorization response",
1208
+ errors
1209
+ );
1210
+ },
1211
+ async pollDeviceAuthorization(provider, deviceAuthId) {
1212
+ return expectAuthenticationResult(
1213
+ await transport.request(
1214
+ `/api/v1/credentials/${providerSegment(provider)}/device-authorizations/${encodePathSegment(
1215
+ deviceAuthId,
1216
+ "device authorization id",
1217
+ errors
1218
+ )}/poll`,
1219
+ { method: "POST" }
1220
+ ),
1221
+ "Device authorization poll response",
1222
+ errors
1223
+ );
1224
+ }
1225
+ };
1226
+ }
1227
+
1228
+ // src/modules/agents.ts
1229
+ var MAX_AGENTS = 100;
1230
+ function createAgentsModule(functionsTransport, copilotTransport, errors = defaultSdkCoreErrorFactory) {
1231
+ const path = (id) => `/api/v1/agents/${encodePathSegment(id, "agent id", errors)}`;
1232
+ return {
1233
+ async list(options = {}) {
1234
+ const params = {
1235
+ page: options.page,
1236
+ size: options.size,
1237
+ sort: options.sort
1238
+ };
1239
+ return expectPage(
1240
+ await functionsTransport.request("/api/v1/agents", { method: "GET", params }),
1241
+ "Agent page response",
1242
+ errors,
1243
+ expectAgentDefinition
1244
+ );
1245
+ },
1246
+ async get(id) {
1247
+ return expectAgentDefinition(
1248
+ await functionsTransport.request(path(id), { method: "GET" }),
1249
+ "Agent response",
1250
+ errors
1251
+ );
1252
+ },
1253
+ async create(input) {
1254
+ return expectAgentDefinition(
1255
+ await functionsTransport.request("/api/v1/agents", {
1256
+ method: "POST",
1257
+ body: input
1258
+ }),
1259
+ "Create agent response",
1260
+ errors
1261
+ );
1262
+ },
1263
+ async update(id, input) {
1264
+ return expectAgentDefinition(
1265
+ await functionsTransport.request(path(id), { method: "PUT", body: input }),
1266
+ "Update agent response",
1267
+ errors
1268
+ );
1269
+ },
1270
+ async delete(id) {
1271
+ expectEmpty(
1272
+ await functionsTransport.request(path(id), { method: "DELETE" }),
1273
+ "Delete agent response",
1274
+ errors
1275
+ );
1276
+ },
1277
+ async bulkCreate(inputs) {
1278
+ requireBatchSize(inputs, "agents", MAX_AGENTS, errors);
1279
+ return expectObjectArray(
1280
+ await functionsTransport.request("/api/v1/agents/bulk", {
1281
+ method: "POST",
1282
+ body: { agents: inputs }
1283
+ }),
1284
+ "Bulk create agents response",
1285
+ errors,
1286
+ expectAgentDefinition
1287
+ );
1288
+ },
1289
+ async bulkUpdate(items) {
1290
+ requireBatchSize(items, "agents", MAX_AGENTS, errors);
1291
+ return expectObjectArray(
1292
+ await functionsTransport.request("/api/v1/agents/bulk", {
1293
+ method: "PUT",
1294
+ body: { agents: items }
1295
+ }),
1296
+ "Bulk update agents response",
1297
+ errors,
1298
+ expectAgentDefinition
1299
+ );
1300
+ },
1301
+ async bulkDelete(ids) {
1302
+ requireBatchSize(ids, "ids", MAX_AGENTS, errors);
1303
+ return expectAgentBulkDeleteResult(
1304
+ await functionsTransport.request("/api/v1/agents/bulk-delete", {
1305
+ method: "POST",
1306
+ body: { ids }
1307
+ }),
1308
+ "Bulk delete agents response",
1309
+ errors
1310
+ );
1311
+ },
1312
+ async listModels(agentId) {
1313
+ return expectObjectArray(
1314
+ await copilotTransport.request("/api/v1/models", {
1315
+ method: "GET",
1316
+ params: { agentId }
1317
+ }),
1318
+ "Agent model response",
1319
+ errors,
1320
+ expectAgentModel
1321
+ );
1322
+ }
1323
+ };
1324
+ }
1325
+
1326
+ // src/modules/agentTasks.ts
1327
+ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory) {
1328
+ const path = (id) => `/api/v1/tasks/${encodePathSegment(id, "task id", errors)}`;
1329
+ return {
1330
+ async list(options = {}) {
1331
+ const params = {
1332
+ page: options.page,
1333
+ size: options.size,
1334
+ sort: options.sort,
1335
+ archived: options.archived,
1336
+ agentId: options.agentId,
1337
+ search: options.search,
1338
+ userId: options.userId
1339
+ };
1340
+ return expectPage(
1341
+ await transport.request("/api/v1/tasks", { method: "GET", params }),
1342
+ "Agent task page response",
1343
+ errors,
1344
+ expectAgentTask
1345
+ );
1346
+ },
1347
+ async get(id) {
1348
+ return expectAgentTask(
1349
+ await transport.request(path(id), { method: "GET" }),
1350
+ "Agent task response",
1351
+ errors
1352
+ );
1353
+ },
1354
+ async create(input) {
1355
+ return expectAgentTask(
1356
+ await transport.request("/api/v1/tasks", { method: "POST", body: input }),
1357
+ "Create agent task response",
1358
+ errors
1359
+ );
1360
+ },
1361
+ async rename(id, title) {
1362
+ return expectAgentTask(
1363
+ await transport.request(path(id), { method: "PATCH", body: { title } }),
1364
+ "Rename agent task response",
1365
+ errors
1366
+ );
1367
+ },
1368
+ async archive(id) {
1369
+ expectEmpty(
1370
+ await transport.request(`${path(id)}/archive`, { method: "PATCH" }),
1371
+ "Archive agent task response",
1372
+ errors
1373
+ );
1374
+ },
1375
+ async sendInput(id, input) {
1376
+ expectEmpty(
1377
+ await transport.request(`${path(id)}/inputs`, { method: "POST", body: input }),
1378
+ "Agent task input response",
1379
+ errors
1380
+ );
1381
+ },
1382
+ async listMessages(id, options = {}) {
1383
+ return expectPage(
1384
+ await transport.request(`${path(id)}/messages`, {
1385
+ method: "GET",
1386
+ params: { page: options.page, size: options.size, sort: options.sort }
1387
+ }),
1388
+ "Agent message page response",
1389
+ errors,
1390
+ expectAgentMessage
1391
+ );
1392
+ }
1393
+ };
1394
+ }
1395
+
1396
+ // src/modules/apps.ts
1397
+ function createAppsModule(transport, errors = defaultSdkCoreErrorFactory) {
1398
+ const appPath = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}`;
1399
+ const params = (options = {}, defaultSort) => ({
1400
+ page: options.page,
1401
+ size: options.size,
1402
+ sort: options.sort ?? defaultSort
1403
+ });
1404
+ return {
1405
+ async list(options = {}) {
1406
+ return expectPage(
1407
+ await transport.request("/api/v1/apps", {
1408
+ method: "GET",
1409
+ params: {
1410
+ ...params(options, "createdAt,desc"),
1411
+ search: options.search,
1412
+ version: options.version,
1413
+ brand: options.brand
1414
+ }
1415
+ }),
1416
+ "App page response",
1417
+ errors,
1418
+ expectAppSummary
1419
+ );
1420
+ },
1421
+ async get(appId, options = {}) {
1422
+ return expectAppDefinition(
1423
+ await transport.request(appPath(appId), {
1424
+ method: "GET",
1425
+ params: { version: options.version }
1426
+ }),
1427
+ "App response",
1428
+ errors
1429
+ );
1430
+ },
1431
+ async create(input) {
1432
+ return expectAppDefinition(
1433
+ await transport.request("/api/v1/apps", { method: "POST", body: input }),
1434
+ "Create app response",
1435
+ errors
1436
+ );
1437
+ },
1438
+ async delete(appId) {
1439
+ expectEmpty(
1440
+ await transport.request(appPath(appId), { method: "DELETE" }),
1441
+ "Delete app response",
1442
+ errors
1443
+ );
1444
+ },
1445
+ async update(appId, input) {
1446
+ return expectAppDefinition(
1447
+ await transport.request(appPath(appId), { method: "PATCH", body: input }),
1448
+ "Update app response",
1449
+ errors
1450
+ );
1451
+ },
1452
+ async getFiles(appId) {
1453
+ return expectFiles(
1454
+ await transport.request(`${appPath(appId)}/files`, { method: "GET" }),
1455
+ errors
1456
+ );
1457
+ },
1458
+ async replaceFiles(appId, files) {
1459
+ return expectFiles(
1460
+ await transport.request(`${appPath(appId)}/files`, {
1461
+ method: "PUT",
1462
+ body: { files }
1463
+ }),
1464
+ errors
1465
+ );
1466
+ },
1467
+ async mergeFiles(appId, files) {
1468
+ return expectFiles(
1469
+ await transport.request(`${appPath(appId)}/files`, {
1470
+ method: "PATCH",
1471
+ body: { files }
1472
+ }),
1473
+ errors
1474
+ );
1475
+ },
1476
+ async build(appId) {
1477
+ return expectAppDeploy(
1478
+ await transport.request(`${appPath(appId)}/build`, { method: "POST" }),
1479
+ "Build app deploy response",
1480
+ errors
1481
+ );
1482
+ },
1483
+ async publish(appId, options = {}) {
1484
+ return expectAppDefinition(
1485
+ await transport.request(`${appPath(appId)}/publish`, {
1486
+ method: "POST",
1487
+ body: options.externalAccess === void 0 ? void 0 : options
1488
+ }),
1489
+ "Publish app response",
1490
+ errors
1491
+ );
1492
+ },
1493
+ async getDeploy(appId, deployId) {
1494
+ return expectAppDeploy(
1495
+ await transport.request(
1496
+ `${appPath(appId)}/deploys/${encodePathSegment(deployId, "deploy id", errors)}`,
1497
+ { method: "GET" }
1498
+ ),
1499
+ "App deploy response",
1500
+ errors
1501
+ );
1502
+ },
1503
+ async getCurrentDeploy(appId) {
1504
+ const response = await transport.request(`${appPath(appId)}/deploys/current`, {
1505
+ method: "GET"
1506
+ });
1507
+ return response === null || response === void 0 ? null : expectAppDeploy(response, "Current app deploy response", errors);
1508
+ },
1509
+ async cancelBuild(appId, deployId) {
1510
+ return expectAppDeploy(
1511
+ await transport.request(
1512
+ `${appPath(appId)}/deploys/${encodePathSegment(deployId, "deploy id", errors)}/cancel`,
1513
+ { method: "POST" }
1514
+ ),
1515
+ "Cancel app build response",
1516
+ errors
1517
+ );
1518
+ },
1519
+ async rollback(appId, targetVersionId) {
1520
+ return expectAppDefinition(
1521
+ await transport.request(`${appPath(appId)}/rollback`, {
1522
+ method: "POST",
1523
+ body: { targetVersionId }
1524
+ }),
1525
+ "Rollback app response",
1526
+ errors
1527
+ );
1528
+ },
1529
+ async listDeploys(appId, options = {}) {
1530
+ return expectPage(
1531
+ await transport.request(`${appPath(appId)}/deploys`, {
1532
+ method: "GET",
1533
+ params: params(options, "createdAt,desc")
1534
+ }),
1535
+ "App deploy page response",
1536
+ errors,
1537
+ expectAppDeploy
1538
+ );
1539
+ },
1540
+ async listVersions(appId, options = {}) {
1541
+ return expectPage(
1542
+ await transport.request(`${appPath(appId)}/versions`, {
1543
+ method: "GET",
1544
+ params: params(options, "createdAt,desc")
1545
+ }),
1546
+ "App version page response",
1547
+ errors,
1548
+ expectAppVersion
1549
+ );
1550
+ }
1551
+ };
1552
+ }
1553
+ function expectFiles(value, errors) {
1554
+ const response = expectObject(value, "App files response", errors);
1555
+ if (response.files === null || typeof response.files !== "object" || Array.isArray(response.files) || Object.values(response.files).some((content) => typeof content !== "string")) {
1556
+ throw errors.invalidResponse("App files response has an invalid files field");
1557
+ }
1558
+ return response;
1559
+ }
1560
+
1561
+ // src/modules/auth.ts
1562
+ function createAuthModule(transport, errors = defaultSdkCoreErrorFactory) {
1563
+ return {
1564
+ async me() {
1565
+ return expectUser(
1566
+ await transport.request("/api/v1/auth/me", { method: "GET" }),
1567
+ "Current user response",
1568
+ errors
1569
+ );
1570
+ },
1571
+ async listUserPlans() {
1572
+ return expectObjectArray(
1573
+ await transport.request("/api/v1/user-plans", { method: "GET" }),
1574
+ "User plan response",
1575
+ errors,
1576
+ expectUserPlan
1577
+ );
1578
+ }
1579
+ };
1580
+ }
1581
+
1582
+ // src/modules/context.ts
1583
+ var SUMMARY_PAGE_SIZE = 2e3;
1584
+ function createContextModule(dependencies, errors = defaultSdkCoreErrorFactory) {
1585
+ return {
1586
+ async getAppContext() {
1587
+ const appId = dependencies.getAppId?.();
1588
+ if (!appId) {
1589
+ configurationError("An appId is required for app context", errors);
1590
+ }
1591
+ const app = await dependencies.apps.get(appId);
1592
+ const tables = await dependencies.schema.listTables({ scope: "APP", includeColumns: true });
1593
+ const functionsPage = await dependencies.functionsAdmin.list({
1594
+ page: 0,
1595
+ size: SUMMARY_PAGE_SIZE,
1596
+ sort: "name"
1597
+ });
1598
+ const agentsPage = await dependencies.agents.list({
1599
+ page: 0,
1600
+ size: SUMMARY_PAGE_SIZE,
1601
+ sort: "name"
1602
+ });
1603
+ const fileResponse = await dependencies.apps.getFiles(appId);
1604
+ const integrationsPage = await dependencies.integrationAdmin.list({
1605
+ page: 0,
1606
+ size: SUMMARY_PAGE_SIZE,
1607
+ sort: "alias"
1608
+ });
1609
+ const connections = await dependencies.agentConnections.list();
1610
+ return {
1611
+ appId,
1612
+ app,
1613
+ tables,
1614
+ functions: functionsPage.content,
1615
+ functionsTotal: functionsPage.page.totalElements,
1616
+ functionsTruncated: functionsPage.content.length < functionsPage.page.totalElements,
1617
+ agents: agentsPage.content,
1618
+ agentsTotal: agentsPage.page.totalElements,
1619
+ agentsTruncated: agentsPage.content.length < agentsPage.page.totalElements,
1620
+ files: Object.keys(fileResponse.files).sort(),
1621
+ integrations: integrationsPage.content,
1622
+ integrationsTotal: integrationsPage.totalElements,
1623
+ integrationsTruncated: integrationsPage.content.length < integrationsPage.totalElements,
1624
+ connections
1625
+ };
1626
+ }
1627
+ };
1628
+ }
1629
+
1630
+ // src/modules/customQueries.ts
1631
+ function createCustomQueriesModule(transport, errors = defaultSdkCoreErrorFactory) {
1632
+ const path = (id) => `/api/v1/custom-queries/${encodePathSegment(id, "query id", errors)}`;
1633
+ return {
1634
+ async list(options = {}) {
1635
+ const params = {
1636
+ page: options.page,
1637
+ size: options.size ?? 20,
1638
+ sort: options.sort ?? "name"
1639
+ };
1640
+ return expectPage(
1641
+ await transport.request("/api/v1/custom-queries", { method: "GET", params }),
1642
+ "Custom query page response",
1643
+ errors,
1644
+ expectCustomQuerySummary
1645
+ );
1646
+ },
1647
+ async get(id) {
1648
+ return expectCustomQueryDefinition(
1649
+ await transport.request(path(id), { method: "GET" }),
1650
+ "Custom query response",
1651
+ errors
1652
+ );
1653
+ },
1654
+ async create(input) {
1655
+ return expectCustomQueryDefinition(
1656
+ await transport.request("/api/v1/custom-queries", { method: "POST", body: input }),
1657
+ "Create custom query response",
1658
+ errors
1659
+ );
1660
+ },
1661
+ async update(id, input) {
1662
+ return expectCustomQueryDefinition(
1663
+ await transport.request(path(id), { method: "PUT", body: input }),
1664
+ "Update custom query response",
1665
+ errors
1666
+ );
1667
+ },
1668
+ async delete(id) {
1669
+ expectEmpty(
1670
+ await transport.request(path(id), { method: "DELETE" }),
1671
+ "Delete custom query response",
1672
+ errors
1673
+ );
1674
+ },
1675
+ async execute(id, parameters = {}) {
1676
+ return expectQueryResult(
1677
+ await transport.request(`${path(id)}/execute`, {
1678
+ method: "POST",
1679
+ body: { parameters }
1680
+ }),
1681
+ "Custom query execution response",
1682
+ errors
1683
+ );
1684
+ }
1685
+ };
1686
+ }
1687
+
1688
+ // src/modules/dataSources.ts
1689
+ var MAX_DATA_SOURCES = 100;
1690
+ function bulkFailure(index, dataSourceId, error) {
1691
+ const errorCode2 = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
1692
+ return {
1693
+ index,
1694
+ success: false,
1695
+ dataSourceId,
1696
+ errorCode: errorCode2,
1697
+ message: error instanceof Error ? error.message : "Data Source operation failed"
1698
+ };
1699
+ }
1700
+ function bulkResult(results) {
1701
+ const succeededCount = results.filter(({ success }) => success).length;
1702
+ return {
1703
+ results,
1704
+ processedCount: results.length,
1705
+ succeededCount,
1706
+ failedCount: results.length - succeededCount
1707
+ };
1708
+ }
1709
+ function createDataSourcesModule(transport, errors = defaultSdkCoreErrorFactory) {
1710
+ const path = (id) => `/api/v1/data-sources/${encodePathSegment(id, "data source id", errors)}`;
1711
+ const createOne = async (input) => expectDataSourceDefinition(
1712
+ await transport.request("/api/v1/data-sources", { method: "POST", body: input }),
1713
+ "Create Data Source response",
1714
+ errors
1715
+ );
1716
+ const updateOne = async (id, input) => expectDataSourceDefinition(
1717
+ await transport.request(path(id), { method: "PUT", body: input }),
1718
+ "Update Data Source response",
1719
+ errors
1720
+ );
1721
+ const deleteOne = async (id) => {
1722
+ expectEmpty(
1723
+ await transport.request(path(id), { method: "DELETE" }),
1724
+ "Delete Data Source response",
1725
+ errors
1726
+ );
1727
+ };
1728
+ return {
1729
+ async list(options = {}) {
1730
+ const params = {
1731
+ page: options.page,
1732
+ size: options.size,
1733
+ sort: options.sort
1734
+ };
1735
+ return expectPage(
1736
+ await transport.request("/api/v1/data-sources", { method: "GET", params }),
1737
+ "Data Source page response",
1738
+ errors,
1739
+ expectDataSourceDefinition
1740
+ );
1741
+ },
1742
+ async get(id) {
1743
+ return expectDataSourceDefinition(
1744
+ await transport.request(path(id), { method: "GET" }),
1745
+ "Data Source response",
1746
+ errors
1747
+ );
1748
+ },
1749
+ async create(input) {
1750
+ return createOne(input);
1751
+ },
1752
+ async update(id, input) {
1753
+ return updateOne(id, input);
1754
+ },
1755
+ async delete(id) {
1756
+ return deleteOne(id);
1757
+ },
1758
+ async bulkCreate(dataSources) {
1759
+ requireBatchSize(dataSources, "dataSources", MAX_DATA_SOURCES, errors);
1760
+ const results = [];
1761
+ for (const [index, input] of dataSources.entries()) {
1762
+ try {
1763
+ const created = await createOne(input);
1764
+ results.push({
1765
+ index,
1766
+ success: true,
1767
+ dataSourceId: created.id,
1768
+ errorCode: null,
1769
+ message: null
1770
+ });
1771
+ } catch (error) {
1772
+ results.push(bulkFailure(index, null, error));
1773
+ }
1774
+ }
1775
+ return bulkResult(results);
1776
+ },
1777
+ async bulkUpdate(dataSources) {
1778
+ requireBatchSize(dataSources, "dataSources", MAX_DATA_SOURCES, errors);
1779
+ const paths = dataSources.map(({ dataSourceId }) => path(dataSourceId));
1780
+ const results = [];
1781
+ for (const [index, { dataSourceId, ...input }] of dataSources.entries()) {
1782
+ try {
1783
+ const updated = expectDataSourceDefinition(
1784
+ await transport.request(paths[index], { method: "PUT", body: input }),
1785
+ "Update Data Source response",
1786
+ errors
1787
+ );
1788
+ results.push({
1789
+ index,
1790
+ success: true,
1791
+ dataSourceId: updated.id,
1792
+ errorCode: null,
1793
+ message: null
1794
+ });
1795
+ } catch (error) {
1796
+ results.push(bulkFailure(index, dataSourceId, error));
1797
+ }
1798
+ }
1799
+ return bulkResult(results);
1800
+ },
1801
+ async bulkDelete(dataSourceIds) {
1802
+ requireBatchSize(dataSourceIds, "dataSourceIds", MAX_DATA_SOURCES, errors);
1803
+ const paths = dataSourceIds.map((id) => path(id));
1804
+ const results = [];
1805
+ for (const [index, dataSourceId] of dataSourceIds.entries()) {
1806
+ try {
1807
+ expectEmpty(
1808
+ await transport.request(paths[index], { method: "DELETE" }),
1809
+ "Delete Data Source response",
1810
+ errors
1811
+ );
1812
+ results.push({ index, success: true, dataSourceId, errorCode: null, message: null });
1813
+ } catch (error) {
1814
+ results.push(bulkFailure(index, dataSourceId, error));
1815
+ }
1816
+ }
1817
+ return bulkResult(results);
1818
+ }
1819
+ };
1820
+ }
1821
+
1822
+ // src/modules/entities.ts
1823
+ var DefaultEntitiesModule = class {
1824
+ constructor(transport, errors) {
1825
+ this.transport = transport;
1826
+ this.errors = errors;
1827
+ }
1828
+ tables = /* @__PURE__ */ new Map();
1829
+ getTable(tableName) {
1830
+ if (!this.tables.has(tableName)) {
1831
+ this.tables.set(tableName, this.createTable(tableName));
1832
+ }
1833
+ return this.tables.get(tableName);
1834
+ }
1835
+ createTable(tableName) {
1836
+ const basePath = `/api/v1/tables/${encodePathSegment(tableName, "tableName", this.errors)}/records`;
1837
+ return {
1838
+ list: async (sortOrOptions, limit, skip, fields) => {
1839
+ const options = typeof sortOrOptions === "object" ? sortOrOptions : void 0;
1840
+ const params = {
1841
+ sort: options?.sort ?? (typeof sortOrOptions === "string" ? sortOrOptions : void 0),
1842
+ limit: options?.limit ?? limit,
1843
+ skip: options?.skip ?? skip,
1844
+ fields: (options?.fields ?? fields)?.join(",")
1845
+ };
1846
+ return expectEntityListResponse(
1847
+ await this.transport.request(basePath, { method: "GET", params }),
1848
+ "Entity list response",
1849
+ this.errors
1850
+ );
1851
+ },
1852
+ filter: async (query, sort, limit, skip, fields) => {
1853
+ return expectEntityListResponse(
1854
+ await this.transport.request(basePath, {
1855
+ method: "GET",
1856
+ params: {
1857
+ q: JSON.stringify(query),
1858
+ sort,
1859
+ limit,
1860
+ skip,
1861
+ fields: fields?.join(",")
1862
+ }
1863
+ }),
1864
+ "Entity list response",
1865
+ this.errors
1866
+ );
1867
+ },
1868
+ get: async (id) => expectObject(
1869
+ await this.transport.request(
1870
+ `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
1871
+ { method: "GET" }
1872
+ ),
1873
+ "Entity response",
1874
+ this.errors
1875
+ ),
1876
+ create: async (data) => expectObject(
1877
+ await this.transport.request(basePath, { method: "POST", body: data }),
1878
+ "Created entity response",
1879
+ this.errors
1880
+ ),
1881
+ bulkCreate: async (data) => expectObjectArray(
1882
+ await this.transport.request(`${basePath}/bulk`, {
1883
+ method: "POST",
1884
+ body: data
1885
+ }),
1886
+ "Bulk create response",
1887
+ this.errors
1888
+ ),
1889
+ update: async (id, data) => expectObject(
1890
+ await this.transport.request(
1891
+ `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
1892
+ { method: "PUT", body: data }
1893
+ ),
1894
+ "Updated entity response",
1895
+ this.errors
1896
+ ),
1897
+ delete: (id) => this.transport.request(`${basePath}/${encodePathSegment(id, "id", this.errors)}`, {
1898
+ method: "DELETE"
1899
+ }).then((response) => expectEmpty(response, "Delete entity response", this.errors)),
1900
+ deleteMany: async (query) => {
1901
+ if (Object.keys(query).length === 0) {
1902
+ configurationError("query must not be empty for deleteMany", this.errors);
1903
+ }
1904
+ const response = expectObject(
1905
+ await this.transport.request(basePath, {
1906
+ method: "DELETE",
1907
+ params: { q: JSON.stringify(query) }
1908
+ }),
1909
+ "Delete many response",
1910
+ this.errors
1911
+ );
1912
+ if (!Number.isInteger(response.deleted)) {
1913
+ return invalidResponse(
1914
+ "Delete many response must include an integer deleted count",
1915
+ this.errors
1916
+ );
1917
+ }
1918
+ return { deleted: response.deleted };
1919
+ }
1920
+ };
1921
+ }
1922
+ };
1923
+ function expectEntityListResponse(value, context, errors) {
1924
+ const response = expectObject(value, context, errors);
1925
+ expectObjectArray(response.data, `${context} data`, errors);
1926
+ if (!Number.isInteger(response.limit))
1927
+ invalidResponse(`${context} has an invalid limit field`, errors);
1928
+ if (!Number.isInteger(response.skip))
1929
+ invalidResponse(`${context} has an invalid skip field`, errors);
1930
+ if (!Number.isInteger(response.total))
1931
+ invalidResponse(`${context} has an invalid total field`, errors);
1932
+ if (typeof response.hasMore !== "boolean") {
1933
+ invalidResponse(`${context} has an invalid hasMore field`, errors);
1934
+ }
1935
+ return response;
1936
+ }
1937
+ function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
1938
+ const instance = new DefaultEntitiesModule(transport, errors);
1939
+ return new Proxy(instance, {
1940
+ get(target, property, receiver) {
1941
+ if (typeof property !== "string" || property in target) {
1942
+ return Reflect.get(target, property, receiver);
1943
+ }
1944
+ return target.getTable(property);
1945
+ }
1946
+ });
1947
+ }
1948
+
1949
+ // src/modules/functions.ts
1950
+ var DefaultFunctionsModule = class {
1951
+ constructor(transport, errors, options) {
1952
+ this.transport = transport;
1953
+ this.errors = errors;
1954
+ this.options = options;
1955
+ }
1956
+ execute(id, input) {
1957
+ return this.executeWithType(id, this.options.executeInvocationType, input);
1958
+ }
1959
+ executeAsync(id, input) {
1960
+ return this.executeWithType(id, "async", input);
1961
+ }
1962
+ getExecution(id) {
1963
+ return this.transport.request(
1964
+ `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}`,
1965
+ { method: "GET" }
1966
+ ).then(
1967
+ (response) => expectFunctionExecution(response, "Function execution response", this.errors)
1968
+ );
1969
+ }
1970
+ cancelExecution(id) {
1971
+ return this.transport.request(
1972
+ `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}/cancel`,
1973
+ { method: "POST" }
1974
+ ).then((response) => expectEmpty(response, "Cancel execution response", this.errors));
1975
+ }
1976
+ executeWithType(id, invocationType, input) {
1977
+ const request = {
1978
+ method: "POST",
1979
+ ...input !== void 0 || this.options.emptyInput !== "omit-body" ? { body: { input: input ?? {} } } : {},
1980
+ ...invocationType === void 0 ? {} : { headers: { "X-Invocation-Type": invocationType } }
1981
+ };
1982
+ return this.transport.request(
1983
+ `/api/v1/functions/${encodePathSegment(id, "function id", this.errors)}/execute`,
1984
+ request
1985
+ ).then(
1986
+ (response) => expectFunctionExecution(response, "Function execution response", this.errors)
1987
+ );
1988
+ }
1989
+ };
1990
+ function createFunctionsModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
1991
+ return new DefaultFunctionsModule(transport, errors, options);
1992
+ }
1993
+
1994
+ // src/modules/functionsAdmin.ts
1995
+ var MAX_FUNCTIONS = 100;
1996
+ var COMPOSED_SCHEDULE_FIELDS = ["cronExpression", "cronInputJson", "cronEnabled"];
1997
+ function rejectBulkScheduleFields(value, operation, errors) {
1998
+ if (typeof value !== "object" || value === null) return;
1999
+ const field = COMPOSED_SCHEDULE_FIELDS.find((candidate) => Object.hasOwn(value, candidate));
2000
+ if (field) {
2001
+ configurationError(
2002
+ `functionsAdmin.${operation} does not support ${field}; composed scheduling is supported only by single-Function create and patch`,
2003
+ errors
2004
+ );
2005
+ }
2006
+ }
2007
+ function bulkPatchUpdate(value) {
2008
+ return typeof value === "object" && value !== null && Object.hasOwn(value, "update") ? value.update : void 0;
2009
+ }
2010
+ function createFunctionsAdminModule(transport, errors = defaultSdkCoreErrorFactory) {
2011
+ const functionPath = (id) => `/api/v1/functions/${encodePathSegment(id, "function id", errors)}`;
2012
+ const pageParams = (options = {}) => ({
2013
+ page: options.page,
2014
+ size: options.size,
2015
+ sort: options.sort
2016
+ });
2017
+ return {
2018
+ async list(options = {}) {
2019
+ return expectPage(
2020
+ await transport.request("/api/v1/functions", {
2021
+ method: "GET",
2022
+ params: { ...pageParams(options), search: options.search }
2023
+ }),
2024
+ "Function page response",
2025
+ errors,
2026
+ expectFunctionSummary
2027
+ );
2028
+ },
2029
+ async get(id) {
2030
+ return expectFunctionDefinition(
2031
+ await transport.request(functionPath(id), { method: "GET" }),
2032
+ "Function response",
2033
+ errors
2034
+ );
2035
+ },
2036
+ async create(input) {
2037
+ return expectFunctionDefinition(
2038
+ await transport.request("/api/v1/functions", { method: "POST", body: input }),
2039
+ "Create Function response",
2040
+ errors
2041
+ );
2042
+ },
2043
+ async patch(id, input) {
2044
+ return expectFunctionDefinition(
2045
+ await transport.request(functionPath(id), { method: "PATCH", body: input }),
2046
+ "Patch Function response",
2047
+ errors
2048
+ );
2049
+ },
2050
+ async delete(id) {
2051
+ expectEmpty(
2052
+ await transport.request(functionPath(id), { method: "DELETE" }),
2053
+ "Delete Function response",
2054
+ errors
2055
+ );
2056
+ },
2057
+ async bulkCreate(functions) {
2058
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2059
+ functions.forEach((input) => rejectBulkScheduleFields(input, "bulkCreate", errors));
2060
+ return expectFunctionDefinitions(
2061
+ await transport.request("/api/v1/functions/bulk", {
2062
+ method: "POST",
2063
+ body: { functions }
2064
+ }),
2065
+ "Function bulk create response",
2066
+ errors
2067
+ );
2068
+ },
2069
+ async bulkUpdate(functions) {
2070
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2071
+ return expectFunctionDefinitions(
2072
+ await transport.request("/api/v1/functions/bulk", {
2073
+ method: "PUT",
2074
+ body: { functions }
2075
+ }),
2076
+ "Function bulk update response",
2077
+ errors
2078
+ );
2079
+ },
2080
+ async bulkPatch(functions) {
2081
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2082
+ functions.forEach(
2083
+ (item) => rejectBulkScheduleFields(bulkPatchUpdate(item), "bulkPatch", errors)
2084
+ );
2085
+ return expectFunctionDefinitions(
2086
+ await transport.request("/api/v1/functions/bulk", {
2087
+ method: "PATCH",
2088
+ body: { functions }
2089
+ }),
2090
+ "Function bulk patch response",
2091
+ errors
2092
+ );
2093
+ },
2094
+ // POST, not DELETE: the selector travels in a body, and some proxies drop a DELETE body.
2095
+ async bulkDelete(selector) {
2096
+ const body = selectorBody(selector, errors);
2097
+ return expectFunctionBulkDeleteResult(
2098
+ await transport.request("/api/v1/functions/bulk-delete", {
2099
+ method: "POST",
2100
+ body
2101
+ }),
2102
+ "Function bulk delete response",
2103
+ errors
2104
+ );
2105
+ },
2106
+ async publish(id) {
2107
+ return expectFunctionDefinition(
2108
+ await transport.request(`${functionPath(id)}/publish`, { method: "POST" }),
2109
+ "Publish Function response",
2110
+ errors
2111
+ );
2112
+ },
2113
+ async rollback(id, versionId) {
2114
+ return expectFunctionDefinition(
2115
+ await transport.request(`${functionPath(id)}/rollback`, {
2116
+ method: "POST",
2117
+ body: { targetVersionId: versionId }
2118
+ }),
2119
+ "Rollback Function response",
2120
+ errors
2121
+ );
2122
+ },
2123
+ async listVersions(id, options = {}) {
2124
+ return expectPage(
2125
+ await transport.request(`${functionPath(id)}/versions`, {
2126
+ method: "GET",
2127
+ params: pageParams(options)
2128
+ }),
2129
+ "Function version page response",
2130
+ errors,
2131
+ expectFunctionVersionResponse
2132
+ );
2133
+ },
2134
+ async setVisibility(id, visibility) {
2135
+ return expectFunctionDefinition(
2136
+ await transport.request(`${functionPath(id)}/visibility`, {
2137
+ method: "PATCH",
2138
+ body: { visibility }
2139
+ }),
2140
+ "Function visibility response",
2141
+ errors
2142
+ );
2143
+ },
2144
+ async listExecutions(id, options = {}) {
2145
+ return expectPage(
2146
+ await transport.request(`${functionPath(id)}/executions`, {
2147
+ method: "GET",
2148
+ params: pageParams(options)
2149
+ }),
2150
+ "Function execution page response",
2151
+ errors,
2152
+ expectFunctionExecution
2153
+ );
2154
+ },
2155
+ async getExecution(functionId, executionId) {
2156
+ return expectFunctionExecution(
2157
+ await transport.request(
2158
+ `${functionPath(functionId)}/executions/${encodePathSegment(
2159
+ executionId,
2160
+ "execution id",
2161
+ errors
2162
+ )}`,
2163
+ { method: "GET" }
2164
+ ),
2165
+ "Function execution response",
2166
+ errors
2167
+ );
2168
+ },
2169
+ async listSecrets(id) {
2170
+ return expectFunctionSecrets(
2171
+ await transport.request(`${functionPath(id)}/secrets`, { method: "GET" }),
2172
+ "Function secrets response",
2173
+ errors
2174
+ );
2175
+ },
2176
+ async createSecret(id, name, value) {
2177
+ expectEmpty(
2178
+ await transport.request(`${functionPath(id)}/secrets`, {
2179
+ method: "POST",
2180
+ body: { name, value }
2181
+ }),
2182
+ "Create Function secret response",
2183
+ errors
2184
+ );
2185
+ },
2186
+ async deleteSecret(id, name) {
2187
+ expectEmpty(
2188
+ await transport.request(
2189
+ `${functionPath(id)}/secrets/${encodePathSegment(name, "secret name", errors)}`,
2190
+ { method: "DELETE" }
2191
+ ),
2192
+ "Delete Function secret response",
2193
+ errors
2194
+ );
2195
+ }
2196
+ };
2197
+ }
2198
+ function selectorBody(selector, errors) {
2199
+ const hasIds = selector.ids !== void 0;
2200
+ if (hasIds === (selector.allInApp === true)) {
2201
+ configurationError("Provide either ids or allInApp, not both", errors);
2202
+ }
2203
+ if (selector.ids !== void 0) {
2204
+ requireBatchSize(selector.ids, "ids", MAX_FUNCTIONS, errors);
2205
+ return { ids: selector.ids };
2206
+ }
2207
+ return { allInApp: true };
2208
+ }
2209
+
2210
+ // src/modules/imports.ts
2211
+ function createImportsModule(transport, errors = defaultSdkCoreErrorFactory) {
2212
+ const path = (id) => `/api/v1/data-imports/${encodePathSegment(id, "import id", errors)}`;
2213
+ const pageParams = (options = {}) => ({
2214
+ page: options.page,
2215
+ size: options.size,
2216
+ sort: options.sort
2217
+ });
2218
+ return {
2219
+ async list(options = {}) {
2220
+ return expectPage(
2221
+ await transport.request("/api/v1/data-imports", {
2222
+ method: "GET",
2223
+ params: pageParams(options)
2224
+ }),
2225
+ "Import page response",
2226
+ errors,
2227
+ expectImportDefinition
2228
+ );
2229
+ },
2230
+ async get(id) {
2231
+ return expectImportDefinition(
2232
+ await transport.request(path(id), { method: "GET" }),
2233
+ "Import response",
2234
+ errors
2235
+ );
2236
+ },
2237
+ async create(input) {
2238
+ return expectImportDefinition(
2239
+ await transport.request("/api/v1/data-imports", { method: "POST", body: input }),
2240
+ "Create import response",
2241
+ errors
2242
+ );
2243
+ },
2244
+ async update(id, input) {
2245
+ return expectImportDefinition(
2246
+ await transport.request(path(id), { method: "PUT", body: input }),
2247
+ "Update import response",
2248
+ errors
2249
+ );
2250
+ },
2251
+ async delete(id) {
2252
+ expectEmpty(
2253
+ await transport.request(path(id), { method: "DELETE" }),
2254
+ "Delete import response",
2255
+ errors
2256
+ );
2257
+ },
2258
+ async execute(id) {
2259
+ return expectImportExecution(
2260
+ await transport.request(`${path(id)}/execute`, { method: "POST" }),
2261
+ "Import execution response",
2262
+ errors
2263
+ );
2264
+ },
2265
+ async listExecutions(options) {
2266
+ return expectPage(
2267
+ await transport.request("/api/v1/data-imports/executions", {
2268
+ method: "GET",
2269
+ params: {
2270
+ definitionId: options.definitionId,
2271
+ page: options.page,
2272
+ size: options.size,
2273
+ sort: options.sort ?? "queuedAt,desc"
2274
+ }
2275
+ }),
2276
+ "Import execution page response",
2277
+ errors,
2278
+ expectImportExecution
2279
+ );
2280
+ },
2281
+ async cancelExecution(executionId) {
2282
+ return expectImportExecution(
2283
+ await transport.request(
2284
+ `/api/v1/data-imports/executions/${encodePathSegment(executionId, "execution id", errors)}/cancel`,
2285
+ { method: "POST" }
2286
+ ),
2287
+ "Cancel import execution response",
2288
+ errors
2289
+ );
2290
+ }
2291
+ };
2292
+ }
2293
+
2294
+ // src/modules/integration.ts
328
2295
  function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory) {
329
2296
  return {
330
2297
  async executeResource(resourceId, params = {}) {
@@ -337,13 +2304,356 @@ function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory)
337
2304
  errors
338
2305
  );
339
2306
  },
340
- async execute(configId, request) {
341
- return expectProxyResult(
2307
+ async execute(configId, request) {
2308
+ return expectProxyResult(
2309
+ await transport.request(
2310
+ `/api/v1/proxy/template-configs/${encodePathSegment(configId, "config id", errors)}/execute`,
2311
+ { method: "POST", body: { ...request, source: "SDK" } }
2312
+ ),
2313
+ "Integration proxy response",
2314
+ errors
2315
+ );
2316
+ },
2317
+ async executeByAlias(alias, request) {
2318
+ return expectProxyResult(
2319
+ await transport.request(
2320
+ `/api/v1/proxy/template-configs/by-alias/${encodePathSegment(alias, "alias", errors)}/execute`,
2321
+ { method: "POST", body: { ...request, source: "SDK" } }
2322
+ ),
2323
+ "Integration proxy response",
2324
+ errors
2325
+ );
2326
+ }
2327
+ };
2328
+ }
2329
+
2330
+ // src/modules/integrationAdmin.ts
2331
+ var MAX_CONFIGS = 100;
2332
+ function createIntegrationAdminModule(transport, errors = defaultSdkCoreErrorFactory) {
2333
+ const path = (id) => `/api/v1/template-configs/${encodePathSegment(id, "config id", errors)}`;
2334
+ return {
2335
+ async create(input) {
2336
+ return expectTemplateConfig(
2337
+ await transport.request("/api/v1/template-configs", {
2338
+ method: "POST",
2339
+ body: input
2340
+ }),
2341
+ "Create integration config response",
2342
+ errors
2343
+ );
2344
+ },
2345
+ async update(id, input) {
2346
+ return expectTemplateConfig(
2347
+ await transport.request(path(id), { method: "PUT", body: input }),
2348
+ "Update integration config response",
2349
+ errors
2350
+ );
2351
+ },
2352
+ async delete(id) {
2353
+ expectEmpty(
2354
+ await transport.request(path(id), { method: "DELETE" }),
2355
+ "Delete integration config response",
2356
+ errors
2357
+ );
2358
+ },
2359
+ async bulkCreate(configs) {
2360
+ requireBatchSize(configs, "configs", MAX_CONFIGS, errors);
2361
+ return expectTemplateConfigBulkResult(
2362
+ await transport.request("/api/v1/template-configs/bulk", {
2363
+ method: "POST",
2364
+ body: { configs }
2365
+ }),
2366
+ "Template config bulk create response",
2367
+ errors
2368
+ );
2369
+ },
2370
+ async bulkUpdate(configs) {
2371
+ requireBatchSize(configs, "configs", MAX_CONFIGS, errors);
2372
+ return expectTemplateConfigBulkResult(
2373
+ await transport.request("/api/v1/template-configs/bulk", {
2374
+ method: "PUT",
2375
+ body: { configs }
2376
+ }),
2377
+ "Template config bulk update response",
2378
+ errors
2379
+ );
2380
+ },
2381
+ // POST, not DELETE: the id list travels in a body, and some proxies drop a DELETE body.
2382
+ async bulkDelete(configIds) {
2383
+ requireBatchSize(configIds, "configIds", MAX_CONFIGS, errors);
2384
+ return expectTemplateConfigBulkResult(
2385
+ await transport.request("/api/v1/template-configs/bulk-delete", {
2386
+ method: "POST",
2387
+ body: { configIds }
2388
+ }),
2389
+ "Template config bulk delete response",
2390
+ errors
2391
+ );
2392
+ },
2393
+ async testCredentials(request) {
2394
+ return expectConnectionTestResult(
2395
+ await transport.request("/api/v1/template-configs/test", {
2396
+ method: "POST",
2397
+ body: request
2398
+ }),
2399
+ "Integration credentials test response",
2400
+ errors
2401
+ );
2402
+ },
2403
+ async testConfig(configId) {
2404
+ return expectConnectionTestResult(
2405
+ await transport.request(`${path(configId)}/test`, { method: "POST" }),
2406
+ "Integration config test response",
2407
+ errors
2408
+ );
2409
+ },
2410
+ async list(options = {}) {
2411
+ const params = {
2412
+ page: options.page,
2413
+ size: options.size,
2414
+ sort: options.sort
2415
+ };
2416
+ return expectTemplateConfigPage(
2417
+ await transport.request("/api/v1/template-configs", { method: "GET", params }),
2418
+ "Template config page response",
2419
+ errors
2420
+ );
2421
+ },
2422
+ async listExecutions(configId, options = {}) {
2423
+ return expectLegacyPage(
2424
+ await transport.request(`${path(configId)}/executions`, {
2425
+ method: "GET",
2426
+ params: {
2427
+ page: options.page,
2428
+ size: options.size,
2429
+ sort: options.sort ?? "createdAt,desc"
2430
+ }
2431
+ }),
2432
+ "Integration execution page response",
2433
+ errors,
2434
+ expectIntegrationExecution
2435
+ );
2436
+ },
2437
+ async getExecution(configId, executionId) {
2438
+ return expectIntegrationExecution(
2439
+ await transport.request(
2440
+ `${path(configId)}/executions/${encodePathSegment(executionId, "execution id", errors)}`,
2441
+ { method: "GET" }
2442
+ ),
2443
+ "Integration execution response",
2444
+ errors
2445
+ );
2446
+ }
2447
+ };
2448
+ }
2449
+
2450
+ // src/modules/integrationResources.ts
2451
+ function createIntegrationResourcesModule(transport, errors = defaultSdkCoreErrorFactory) {
2452
+ const path = (id) => `/api/v1/integration-resources/${encodePathSegment(id, "resource id", errors)}`;
2453
+ return {
2454
+ async list(options = {}) {
2455
+ const params = {
2456
+ page: options.page,
2457
+ size: options.size,
2458
+ sort: options.sort
2459
+ };
2460
+ return expectLegacyPage(
2461
+ await transport.request("/api/v1/integration-resources", {
2462
+ method: "GET",
2463
+ params
2464
+ }),
2465
+ "Integration resource page response",
2466
+ errors,
2467
+ expectIntegrationResourceSummary
2468
+ );
2469
+ },
2470
+ async get(id) {
2471
+ return expectIntegrationResource(
2472
+ await transport.request(path(id), { method: "GET" }),
2473
+ "Integration resource response",
2474
+ errors
2475
+ );
2476
+ },
2477
+ async create(input) {
2478
+ return expectIntegrationResource(
2479
+ await transport.request("/api/v1/integration-resources", {
2480
+ method: "POST",
2481
+ body: input
2482
+ }),
2483
+ "Create integration resource response",
2484
+ errors
2485
+ );
2486
+ },
2487
+ async update(id, input) {
2488
+ return expectIntegrationResource(
2489
+ await transport.request(path(id), { method: "PUT", body: input }),
2490
+ "Update integration resource response",
2491
+ errors
2492
+ );
2493
+ },
2494
+ async delete(id) {
2495
+ expectEmpty(
2496
+ await transport.request(path(id), { method: "DELETE" }),
2497
+ "Delete integration resource response",
2498
+ errors
2499
+ );
2500
+ }
2501
+ };
2502
+ }
2503
+
2504
+ // src/modules/integrationTemplates.ts
2505
+ function createIntegrationTemplatesModule(transport, errors = defaultSdkCoreErrorFactory) {
2506
+ const params = (options = {}, sort) => ({
2507
+ page: options.page,
2508
+ size: options.size ?? 20,
2509
+ sort: options.sort ?? sort
2510
+ });
2511
+ return {
2512
+ async list(options = {}) {
2513
+ return expectLegacyPage(
2514
+ await transport.request("/api/v1/templates", {
2515
+ method: "GET",
2516
+ params: params(options, "name")
2517
+ }),
2518
+ "Integration template page response",
2519
+ errors,
2520
+ expectIntegrationTemplateSummary
2521
+ );
2522
+ },
2523
+ async get(id) {
2524
+ return expectIntegrationTemplate(
2525
+ await transport.request(
2526
+ `/api/v1/templates/${encodePathSegment(id, "template id", errors)}`,
2527
+ { method: "GET" }
2528
+ ),
2529
+ "Integration template response",
2530
+ errors
2531
+ );
2532
+ },
2533
+ async listConfigs(options = {}) {
2534
+ return expectLegacyPage(
2535
+ await transport.request("/api/v1/template-configs", {
2536
+ method: "GET",
2537
+ params: params(options, "alias")
2538
+ }),
2539
+ "Integration config page response",
2540
+ errors,
2541
+ expectTemplateConfigSummary
2542
+ );
2543
+ },
2544
+ async getConfig(id) {
2545
+ return expectTemplateConfig(
2546
+ await transport.request(
2547
+ `/api/v1/template-configs/${encodePathSegment(id, "config id", errors)}`,
2548
+ { method: "GET" }
2549
+ ),
2550
+ "Integration config response",
2551
+ errors
2552
+ );
2553
+ }
2554
+ };
2555
+ }
2556
+
2557
+ // src/modules/members.ts
2558
+ var MAX_APP_USERS = 100;
2559
+ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2560
+ const path = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}/users`;
2561
+ return {
2562
+ async list() {
2563
+ return expectAppMembers(
2564
+ await transport.request("/api/v1/members/current-app", { method: "GET" }),
2565
+ "App members response",
2566
+ errors
2567
+ );
2568
+ },
2569
+ async invite(appId, input) {
2570
+ expectEmpty(
2571
+ await transport.request(path(appId), { method: "POST", body: input }),
2572
+ "Invite app user response",
2573
+ errors
2574
+ );
2575
+ },
2576
+ async unsubscribe(appId, userId) {
2577
+ expectEmpty(
342
2578
  await transport.request(
343
- `/api/v1/proxy/template-configs/${encodePathSegment(configId, "config id", errors)}/execute`,
344
- { method: "POST", body: { ...request, source: "SDK" } }
2579
+ `${path(appId)}/${encodePathSegment(userId, "user id", errors)}`,
2580
+ { method: "DELETE" }
345
2581
  ),
346
- "Integration proxy response",
2582
+ "Unsubscribe app user response",
2583
+ errors
2584
+ );
2585
+ },
2586
+ async bulkInvite(appId, users) {
2587
+ requireBatchSize(users, "users", MAX_APP_USERS, errors);
2588
+ expectEmpty(
2589
+ await transport.request(`${path(appId)}/bulk`, {
2590
+ method: "POST",
2591
+ body: { users }
2592
+ }),
2593
+ "Bulk invite app users response",
2594
+ errors
2595
+ );
2596
+ },
2597
+ async bulkUnsubscribe(appId, userIds) {
2598
+ requireBatchSize(userIds, "userIds", MAX_APP_USERS, errors);
2599
+ return expectBulkUnsubscribeResult(
2600
+ await transport.request(`${path(appId)}/bulk-unsubscribe`, {
2601
+ method: "POST",
2602
+ body: { userIds }
2603
+ }),
2604
+ "Bulk unsubscribe app users response",
2605
+ errors
2606
+ );
2607
+ }
2608
+ };
2609
+ }
2610
+
2611
+ // src/modules/messenger.ts
2612
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2613
+ return {
2614
+ async notify(content) {
2615
+ return expectMessageAccepted(
2616
+ await transport.request("/api/v1/messages/notify", {
2617
+ method: "POST",
2618
+ body: { content }
2619
+ }),
2620
+ "Notify user response",
2621
+ errors
2622
+ );
2623
+ }
2624
+ };
2625
+ }
2626
+
2627
+ // src/modules/publicFunctions.ts
2628
+ function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
2629
+ const execute = async (id, input, mode) => {
2630
+ if (!transport) {
2631
+ configurationError(
2632
+ "A separate publicFunctions transport is required so anonymous requests do not inherit authorization headers",
2633
+ errors
2634
+ );
2635
+ }
2636
+ return transport.request(
2637
+ `/public/v1/functions/${encodePathSegment(id, "function id", errors)}/execute`,
2638
+ {
2639
+ method: "POST",
2640
+ headers: { "X-Invocation-Type": mode },
2641
+ body: { input: input ?? {} }
2642
+ }
2643
+ );
2644
+ };
2645
+ return {
2646
+ async execute(id, input) {
2647
+ return expectPublicFunctionResult(
2648
+ await execute(id, input, "sync"),
2649
+ "Public Function execution response",
2650
+ errors
2651
+ );
2652
+ },
2653
+ async executeAsync(id, input) {
2654
+ return expectPublicFunctionAsyncResult(
2655
+ await execute(id, input, "async"),
2656
+ "Public async Function execution response",
347
2657
  errors
348
2658
  );
349
2659
  }
@@ -351,22 +2661,15 @@ function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory)
351
2661
  }
352
2662
 
353
2663
  // src/modules/queries.ts
354
- function createQueriesModule(transport, getDataSourceId, errors = defaultSdkCoreErrorFactory) {
2664
+ function createQueriesModule(transport, errors = defaultSdkCoreErrorFactory) {
355
2665
  return {
356
2666
  async execute(id, parameters = {}) {
357
- const dataSourceId = getDataSourceId();
358
- if (!dataSourceId) {
359
- configurationError(
360
- "A dataSourceId is required for queries. Call client.init() first or configure dataSourceId.",
361
- errors
362
- );
363
- }
364
2667
  return expectQueryResult(
365
2668
  await transport.request(
366
2669
  `/api/v1/custom-queries/${encodePathSegment(id, "query id", errors)}/execute`,
367
2670
  {
368
2671
  method: "POST",
369
- body: { dataSourceId, parameters }
2672
+ body: { parameters }
370
2673
  }
371
2674
  ),
372
2675
  "Query execution response",
@@ -376,29 +2679,974 @@ function createQueriesModule(transport, getDataSourceId, errors = defaultSdkCore
376
2679
  };
377
2680
  }
378
2681
 
2682
+ // src/modules/schema.ts
2683
+ function createSchemaModule(transport, errors = defaultSdkCoreErrorFactory) {
2684
+ const tablePath = (name) => `/api/v1/tables/${encodePathSegment(name, "table name", errors)}`;
2685
+ const list = async (options = {}) => {
2686
+ const params = {
2687
+ scope: options.scope,
2688
+ includeColumns: options.includeColumns
2689
+ };
2690
+ return expectSchemaTables(
2691
+ await transport.request("/api/v1/tables", { method: "GET", params }),
2692
+ "Schema tables response",
2693
+ errors
2694
+ );
2695
+ };
2696
+ return {
2697
+ async createTable(tableName, columns) {
2698
+ expectEmpty(
2699
+ await transport.request("/api/v1/tables", {
2700
+ method: "POST",
2701
+ body: { tableName, columns }
2702
+ }),
2703
+ "Create table response",
2704
+ errors
2705
+ );
2706
+ },
2707
+ listTables: list,
2708
+ listAppTables(options = {}) {
2709
+ return list({
2710
+ scope: "APP",
2711
+ ...options.includeColumns === void 0 ? {} : { includeColumns: options.includeColumns }
2712
+ });
2713
+ },
2714
+ async getTable(tableName) {
2715
+ return expectTableDefinition(
2716
+ await transport.request(tablePath(tableName), { method: "GET" }),
2717
+ "Table details response",
2718
+ errors
2719
+ );
2720
+ },
2721
+ async dropTable(tableName) {
2722
+ expectEmpty(
2723
+ await transport.request(tablePath(tableName), { method: "DELETE" }),
2724
+ "Drop table response",
2725
+ errors
2726
+ );
2727
+ },
2728
+ async truncateTable(tableName) {
2729
+ expectEmpty(
2730
+ await transport.request(`${tablePath(tableName)}/truncate`, { method: "POST" }),
2731
+ "Truncate table response",
2732
+ errors
2733
+ );
2734
+ },
2735
+ async addColumn(tableName, column) {
2736
+ expectEmpty(
2737
+ await transport.request(`${tablePath(tableName)}/columns`, {
2738
+ method: "POST",
2739
+ body: column
2740
+ }),
2741
+ "Add column response",
2742
+ errors
2743
+ );
2744
+ },
2745
+ async dropColumn(tableName, columnName) {
2746
+ expectEmpty(
2747
+ await transport.request(
2748
+ `${tablePath(tableName)}/columns/${encodePathSegment(columnName, "column name", errors)}`,
2749
+ { method: "DELETE" }
2750
+ ),
2751
+ "Drop column response",
2752
+ errors
2753
+ );
2754
+ }
2755
+ };
2756
+ }
2757
+
2758
+ // src/modules/sql.ts
2759
+ var MAX_STATEMENTS = 20;
2760
+ function createSqlModule(transport, errors = defaultSdkCoreErrorFactory) {
2761
+ return {
2762
+ async executeQuery(sql, parameters = {}) {
2763
+ return expectQueryResult(
2764
+ await transport.request("/api/v1/sql/execute", {
2765
+ method: "POST",
2766
+ body: { sql, parameters }
2767
+ }),
2768
+ "SQL execution response",
2769
+ errors
2770
+ );
2771
+ },
2772
+ async executeDdl(statements) {
2773
+ requireBatchSize(statements, "statements", MAX_STATEMENTS, errors);
2774
+ return expectBatchExecution(
2775
+ await transport.request("/api/v1/sql/ddl/execute", {
2776
+ method: "POST",
2777
+ body: { statements }
2778
+ }),
2779
+ "DDL batch response",
2780
+ errors
2781
+ );
2782
+ },
2783
+ async executeDml(statements) {
2784
+ requireBatchSize(statements, "statements", MAX_STATEMENTS, errors);
2785
+ return expectBatchExecution(
2786
+ await transport.request("/api/v1/sql/dml/execute", {
2787
+ method: "POST",
2788
+ body: { statements }
2789
+ }),
2790
+ "DML batch response",
2791
+ errors
2792
+ );
2793
+ },
2794
+ async listTables(options = {}) {
2795
+ const params = {
2796
+ scope: options.scope,
2797
+ includeColumns: options.includeColumns
2798
+ };
2799
+ return expectSchemaTables(
2800
+ await transport.request("/api/v1/tables", { method: "GET", params }),
2801
+ "Schema tables response",
2802
+ errors
2803
+ );
2804
+ }
2805
+ };
2806
+ }
2807
+
2808
+ // src/modules/workflows.ts
2809
+ function createWorkflowsModule(transport, errors = defaultSdkCoreErrorFactory) {
2810
+ const path = (id) => `/api/v1/workflows/${encodePathSegment(id, "workflow id", errors)}`;
2811
+ const params = (options = {}) => ({
2812
+ page: options.page,
2813
+ size: options.size,
2814
+ sort: options.sort
2815
+ });
2816
+ const executionPath = (workflowId, executionId) => `${path(workflowId)}/executions${executionId === void 0 ? "" : `/${encodePathSegment(executionId, "workflow execution id", errors)}`}`;
2817
+ return {
2818
+ async list(options = {}) {
2819
+ return expectPage(
2820
+ await transport.request("/api/v1/workflows", {
2821
+ method: "GET",
2822
+ params: params(options)
2823
+ }),
2824
+ "Workflow page response",
2825
+ errors,
2826
+ expectWorkflowSummary
2827
+ );
2828
+ },
2829
+ async get(id) {
2830
+ return expectWorkflowDefinition(
2831
+ await transport.request(path(id), { method: "GET" }),
2832
+ "Workflow response",
2833
+ errors
2834
+ );
2835
+ },
2836
+ async create(input) {
2837
+ return expectWorkflowDefinition(
2838
+ await transport.request("/api/v1/workflows", {
2839
+ method: "POST",
2840
+ body: input
2841
+ }),
2842
+ "Create workflow response",
2843
+ errors
2844
+ );
2845
+ },
2846
+ async update(id, input) {
2847
+ return expectWorkflowDefinition(
2848
+ await transport.request(path(id), { method: "PUT", body: input }),
2849
+ "Update workflow response",
2850
+ errors
2851
+ );
2852
+ },
2853
+ async delete(id) {
2854
+ expectEmpty(
2855
+ await transport.request(path(id), { method: "DELETE" }),
2856
+ "Delete workflow response",
2857
+ errors
2858
+ );
2859
+ },
2860
+ async execute(id, input = {}) {
2861
+ return expectWorkflowExecution(
2862
+ await transport.request(`${path(id)}/execute`, {
2863
+ method: "POST",
2864
+ body: { input }
2865
+ }),
2866
+ "Workflow execution response",
2867
+ errors
2868
+ );
2869
+ },
2870
+ async listExecutions(workflowId, options = {}) {
2871
+ return expectPage(
2872
+ await transport.request(executionPath(workflowId), {
2873
+ method: "GET",
2874
+ params: params(options)
2875
+ }),
2876
+ "Workflow execution page response",
2877
+ errors,
2878
+ expectWorkflowExecution
2879
+ );
2880
+ },
2881
+ async getExecution(workflowId, executionId) {
2882
+ return expectWorkflowExecution(
2883
+ await transport.request(executionPath(workflowId, executionId), { method: "GET" }),
2884
+ "Workflow execution response",
2885
+ errors
2886
+ );
2887
+ },
2888
+ async cancelExecution(workflowId, executionId) {
2889
+ expectEmpty(
2890
+ await transport.request(`${executionPath(workflowId, executionId)}/cancel`, {
2891
+ method: "POST"
2892
+ }),
2893
+ "Cancel workflow execution response",
2894
+ errors
2895
+ );
2896
+ }
2897
+ };
2898
+ }
2899
+
379
2900
  // src/core.ts
380
2901
  function createSdkCore(options) {
381
2902
  const errors = options.errors ?? defaultSdkCoreErrorFactory;
2903
+ const codeStudio = options.transports.codeStudio ?? unavailableTransport("codeStudio", errors);
2904
+ const copilot = options.transports.copilot ?? unavailableTransport("copilot", errors);
2905
+ const messengerTransport = options.transports.messenger ?? unavailableTransport("messenger", errors);
2906
+ const apps = createAppsModule(codeStudio, errors);
2907
+ const schema = createSchemaModule(options.transports.dataManager, errors);
2908
+ const functionsAdmin = createFunctionsAdminModule(options.transports.functions, errors);
2909
+ const agents = createAgentsModule(options.transports.functions, copilot, errors);
2910
+ const integrationAdmin = createIntegrationAdminModule(options.transports.integration, errors);
2911
+ const agentConnections = createAgentConnectionsModule(copilot, errors);
2912
+ const members = createMembersModule(options.transports.auth, errors);
382
2913
  return {
2914
+ agentConnections,
2915
+ agentCredentials: createAgentCredentialsModule(copilot, errors),
2916
+ agents,
2917
+ agentTasks: createAgentTasksModule(copilot, errors),
2918
+ apps,
383
2919
  auth: createAuthModule(options.transports.auth, errors),
2920
+ context: createContextModule(
2921
+ {
2922
+ apps,
2923
+ schema,
2924
+ functionsAdmin,
2925
+ agents,
2926
+ integrationAdmin,
2927
+ agentConnections,
2928
+ getAppId: options.getAppId
2929
+ },
2930
+ errors
2931
+ ),
2932
+ customQueries: createCustomQueriesModule(options.transports.dataManager, errors),
2933
+ dataSources: createDataSourcesModule(options.transports.dataManager, errors),
384
2934
  entities: createEntitiesModule(options.transports.dataManager, errors),
385
2935
  functions: createFunctionsModule(options.transports.functions, options.functions, errors),
2936
+ functionsAdmin,
2937
+ imports: createImportsModule(options.transports.dataManager, errors),
386
2938
  integration: createIntegrationModule(options.transports.integration, errors),
387
- queries: createQueriesModule(options.transports.dataManager, options.getDataSourceId, errors)
2939
+ integrationAdmin,
2940
+ integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
2941
+ integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
2942
+ members,
2943
+ messenger: createMessengerModule(messengerTransport, errors),
2944
+ publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
2945
+ queries: createQueriesModule(options.transports.dataManager, errors),
2946
+ sql: createSqlModule(options.transports.dataManager, errors),
2947
+ schema,
2948
+ workflows: createWorkflowsModule(options.transports.functions, errors)
2949
+ };
2950
+ }
2951
+ function unavailableTransport(name, errors) {
2952
+ return {
2953
+ request() {
2954
+ return Promise.reject(errors.configuration(`The ${name} transport is not configured`));
2955
+ }
2956
+ };
2957
+ }
2958
+
2959
+ // src/agentSession.ts
2960
+ var AGENT_QUEUE_LIMIT = 10;
2961
+ var CANCEL_SAFETY_MS = 1e4;
2962
+ var RECONCILE_DELAY_MS = 1e3;
2963
+ var AgentTaskTurnError = class extends Error {
2964
+ code;
2965
+ constructor(message, code) {
2966
+ super(message);
2967
+ this.name = "AgentTaskTurnError";
2968
+ this.code = code;
2969
+ }
2970
+ };
2971
+ function asObject(value) {
2972
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
2973
+ }
2974
+ function errorMessage(error) {
2975
+ if (error instanceof Error) return error.message;
2976
+ if (error && typeof error === "object" && "message" in error) {
2977
+ return String(error.message);
2978
+ }
2979
+ return String(error);
2980
+ }
2981
+ function errorCode(error) {
2982
+ if (!error || typeof error !== "object") return void 0;
2983
+ const candidate = error;
2984
+ const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
2985
+ return typeof code === "string" ? code : void 0;
2986
+ }
2987
+ function delay(milliseconds) {
2988
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
2989
+ }
2990
+ function toAgentTimelineItem(message) {
2991
+ if (message.type === "TOOL_USE") {
2992
+ try {
2993
+ const payload = JSON.parse(message.content);
2994
+ if (payload && typeof payload === "object") {
2995
+ return {
2996
+ id: message.id,
2997
+ kind: "tool",
2998
+ tool: {
2999
+ tool: typeof payload.name === "string" ? payload.name : "",
3000
+ ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
3001
+ ...payload.input !== void 0 ? { input: payload.input } : {},
3002
+ ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
3003
+ phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
3004
+ },
3005
+ at: message.createdAt
3006
+ };
3007
+ }
3008
+ } catch {
3009
+ }
3010
+ }
3011
+ return {
3012
+ id: message.id,
3013
+ kind: message.sender === "USER" ? "user" : "agent",
3014
+ text: message.content,
3015
+ at: message.createdAt
3016
+ };
3017
+ }
3018
+ function createAgentTaskSessionManager(options) {
3019
+ const sessions = /* @__PURE__ */ new Map();
3020
+ return {
3021
+ session(sessionOptions) {
3022
+ if ("taskId" in sessionOptions) {
3023
+ const current = sessions.get(sessionOptions.taskId);
3024
+ if (current && current.status !== "closed") return current;
3025
+ }
3026
+ const session = new CoreAgentTaskSession(sessionOptions, {
3027
+ ...options,
3028
+ onTaskId: (taskId, value) => sessions.set(taskId, value),
3029
+ onClose: (taskId, value) => {
3030
+ if (sessions.get(taskId) === value) sessions.delete(taskId);
3031
+ }
3032
+ });
3033
+ if ("taskId" in sessionOptions) sessions.set(sessionOptions.taskId, session);
3034
+ return session;
3035
+ }
388
3036
  };
389
3037
  }
3038
+ function withAgentTaskSessions(tasks, manager) {
3039
+ return { ...tasks, session: (options) => manager.session(options) };
3040
+ }
3041
+ var CoreAgentTaskSession = class {
3042
+ constructor(options, dependencies) {
3043
+ this.options = options;
3044
+ this.dependencies = dependencies;
3045
+ this.isNewSession = "create" in options;
3046
+ if ("taskId" in options) {
3047
+ this._taskId = options.taskId;
3048
+ this.openingPromise = this.openExisting();
3049
+ } else {
3050
+ this._status = "idle";
3051
+ }
3052
+ }
3053
+ _taskId = null;
3054
+ _task = null;
3055
+ _status = "opening";
3056
+ _history = [];
3057
+ _content = "";
3058
+ _queue = [];
3059
+ isNewSession;
3060
+ listeners = /* @__PURE__ */ new Map();
3061
+ connection = null;
3062
+ connectionAbort = null;
3063
+ connectionPromise = null;
3064
+ openingPromise = null;
3065
+ createPromise = null;
3066
+ dispatching = false;
3067
+ recoveryUsed = false;
3068
+ recoveryPromise = null;
3069
+ recoveryGeneration = 0;
3070
+ recoveredTerminalReason;
3071
+ cancelTimer = null;
3072
+ queueSequence = 0;
3073
+ activeWaiter;
3074
+ turnBaselineIds = /* @__PURE__ */ new Set();
3075
+ get taskId() {
3076
+ return this._taskId;
3077
+ }
3078
+ get task() {
3079
+ return this._task;
3080
+ }
3081
+ get isNew() {
3082
+ return this.isNewSession;
3083
+ }
3084
+ get status() {
3085
+ return this._status;
3086
+ }
3087
+ get history() {
3088
+ return [...this._history];
3089
+ }
3090
+ get content() {
3091
+ return this._content;
3092
+ }
3093
+ get queue() {
3094
+ return this._queue.map((item) => ({
3095
+ id: item.id,
3096
+ text: item.text,
3097
+ createdAt: item.createdAt,
3098
+ ...item.agentType ? { agentType: item.agentType } : {},
3099
+ ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
3100
+ }));
3101
+ }
3102
+ send(prompt, options = {}) {
3103
+ this.requireOpen();
3104
+ if (!prompt.trim()) return;
3105
+ if (this.isBusy()) {
3106
+ this.enqueue(prompt, options);
3107
+ return;
3108
+ }
3109
+ this.startDispatch(prompt, options);
3110
+ }
3111
+ sendAndWait(prompt, options = {}) {
3112
+ this.requireOpen();
3113
+ if (!prompt.trim()) return Promise.reject(new Error("Agent prompt must not be blank."));
3114
+ const waiter = this.createWaiter(options);
3115
+ if (waiter.settled) return waiter.promise;
3116
+ const sendOptions = {
3117
+ ...options.agentType ? { agentType: options.agentType } : {},
3118
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
3119
+ };
3120
+ if (this.isBusy()) {
3121
+ const queueId = this.enqueue(prompt, sendOptions, waiter);
3122
+ if (queueId) waiter.queueId = queueId;
3123
+ return waiter.promise;
3124
+ }
3125
+ this.startDispatch(prompt, sendOptions, waiter);
3126
+ return waiter.promise;
3127
+ }
3128
+ async cancel() {
3129
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3130
+ try {
3131
+ await this.sendInput({ type: "interrupt" });
3132
+ this.setStatus("cancelled");
3133
+ this.emit("cancelled", {});
3134
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3135
+ this.cancelTimer = setTimeout(() => {
3136
+ this.cancelTimer = null;
3137
+ if (this._status === "cancelled") {
3138
+ const error = new AgentTaskTurnError(
3139
+ "Agent turn cancellation was not acknowledged before the safety timeout."
3140
+ );
3141
+ this.emit("error", { error: error.message });
3142
+ this.failTurn(error);
3143
+ }
3144
+ }, CANCEL_SAFETY_MS);
3145
+ } catch (error) {
3146
+ this.emitError("Failed to cancel Agent task", error);
3147
+ throw error;
3148
+ }
3149
+ }
3150
+ respondApproval(approved) {
3151
+ void this.sendInput({ type: "approval_response", approved }).catch((error) => {
3152
+ this.emitError("Failed to answer Agent approval", error);
3153
+ });
3154
+ }
3155
+ async loadHistory(options = {}) {
3156
+ if (!this._taskId) return [];
3157
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3158
+ ...options.limit !== void 0 ? { size: options.limit } : {},
3159
+ sort: "createdAt,desc"
3160
+ });
3161
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
3162
+ const history = this.history;
3163
+ this.emit("historyLoaded", { history });
3164
+ return history;
3165
+ }
3166
+ editQueueItem(id, text) {
3167
+ if (!text.trim()) {
3168
+ this.removeQueueItem(id);
3169
+ return;
3170
+ }
3171
+ this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
3172
+ this.emitQueue();
3173
+ }
3174
+ removeQueueItem(id) {
3175
+ const removed = this._queue.find((item) => item.id === id);
3176
+ this._queue = this._queue.filter((item) => item.id !== id);
3177
+ removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
3178
+ this.emitQueue();
3179
+ }
3180
+ clearQueue() {
3181
+ if (!this._queue.length) return;
3182
+ const removed = this._queue;
3183
+ this._queue = [];
3184
+ for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
3185
+ this.emitQueue();
3186
+ }
3187
+ on(event, handler) {
3188
+ let listeners = this.listeners.get(event);
3189
+ if (!listeners) {
3190
+ listeners = /* @__PURE__ */ new Set();
3191
+ this.listeners.set(event, listeners);
3192
+ }
3193
+ const callback = handler;
3194
+ listeners.add(callback);
3195
+ return () => listeners?.delete(callback);
3196
+ }
3197
+ close() {
3198
+ if (this._status === "closed") return;
3199
+ this.setStatus("closed");
3200
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3201
+ this.cancelTimer = null;
3202
+ this.connectionAbort?.abort();
3203
+ this.connectionAbort = null;
3204
+ this.connection?.close();
3205
+ this.connection = null;
3206
+ this.recoveryGeneration += 1;
3207
+ const closedError = new Error("Agent task session is closed.");
3208
+ this.activeWaiter?.reject(closedError);
3209
+ this.activeWaiter = void 0;
3210
+ for (const item of this._queue) item.waiter?.reject(closedError);
3211
+ this._queue = [];
3212
+ if (this._taskId) this.dependencies.onClose(this._taskId, this);
3213
+ for (const listeners of this.listeners.values()) listeners.clear();
3214
+ }
3215
+ async openExisting() {
3216
+ try {
3217
+ this._task = await this.dependencies.tasks.get(this._taskId);
3218
+ if (this.isClosed()) return false;
3219
+ await this.loadHistory();
3220
+ if (this.isClosed()) return false;
3221
+ await this.ensureChannel();
3222
+ if (this.isClosed()) return false;
3223
+ this.setStatus("idle");
3224
+ return true;
3225
+ } catch (error) {
3226
+ if (this.isClosed()) return false;
3227
+ this.emitError("Failed to open Agent task", error);
3228
+ this.setStatus("error");
3229
+ return false;
3230
+ }
3231
+ }
3232
+ startDispatch(prompt, options, waiter) {
3233
+ this.dispatching = true;
3234
+ void this.dispatchSend(prompt, options, waiter).catch((error) => {
3235
+ waiter?.reject(error);
3236
+ this.emitError("Failed to send Agent prompt", error);
3237
+ if (this._status === "streaming") this.setStatus("idle");
3238
+ this.flushQueue();
3239
+ }).finally(() => {
3240
+ this.dispatching = false;
3241
+ if (this._status === "idle") this.flushQueue();
3242
+ });
3243
+ }
3244
+ async dispatchSend(prompt, options, waiter) {
3245
+ if (this.openingPromise && !await this.openingPromise) {
3246
+ throw new Error("Agent task session could not be opened.");
3247
+ }
3248
+ if (this.isClosed() || waiter?.settled) return;
3249
+ await this.ensureTask();
3250
+ if (this.isClosed() || waiter?.settled) return;
3251
+ await this.ensureChannel();
3252
+ if (this.isClosed() || waiter?.settled) return;
3253
+ await this.captureTurnBaseline();
3254
+ this._content = "";
3255
+ this.recoveryUsed = false;
3256
+ this.recoveredTerminalReason = void 0;
3257
+ this.recoveryGeneration += 1;
3258
+ this.activeWaiter = waiter;
3259
+ this.setStatus("streaming");
3260
+ this.emit("turnStart", {});
3261
+ await this.sendInput({
3262
+ type: "message",
3263
+ content: prompt,
3264
+ ...options.agentType ? { agentType: options.agentType } : {},
3265
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
3266
+ });
3267
+ }
3268
+ async ensureTask() {
3269
+ if (this._taskId) return;
3270
+ if (!("create" in this.options)) throw new Error("Agent task session has no task.");
3271
+ const createOptions = this.options;
3272
+ if (this.createPromise) return this.createPromise;
3273
+ this.createPromise = (async () => {
3274
+ const task = await this.dependencies.tasks.create({
3275
+ agentType: createOptions.agentType,
3276
+ ...createOptions.title ? { title: createOptions.title } : {},
3277
+ ...createOptions.agentId ? { agentId: createOptions.agentId } : {},
3278
+ ...createOptions.reasoningEffort ? { reasoningEffort: createOptions.reasoningEffort } : {},
3279
+ ...createOptions.userId ? { userId: createOptions.userId } : {}
3280
+ });
3281
+ this._task = task;
3282
+ this._taskId = task.id;
3283
+ this.dependencies.onTaskId(task.id, this);
3284
+ this.emit("taskCreated", { task });
3285
+ })().finally(() => {
3286
+ this.createPromise = null;
3287
+ });
3288
+ return this.createPromise;
3289
+ }
3290
+ ensureChannel() {
3291
+ if (this.connection) return Promise.resolve();
3292
+ if (this.connectionPromise) return this.connectionPromise;
3293
+ if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3294
+ const abort = new AbortController();
3295
+ this.connectionAbort = abort;
3296
+ this.connectionPromise = this.dependencies.eventSource.open(
3297
+ this._taskId,
3298
+ {
3299
+ onEvent: (event) => this.handleEvent(event),
3300
+ onDisconnect: (error) => this.handleDisconnect(error)
3301
+ },
3302
+ abort.signal,
3303
+ this.options.transport
3304
+ ).then((connection) => {
3305
+ if (this.isClosed() || this._status === "error") {
3306
+ connection.close();
3307
+ return;
3308
+ }
3309
+ this.connection = connection;
3310
+ }).finally(() => {
3311
+ this.connectionPromise = null;
3312
+ });
3313
+ return this.connectionPromise;
3314
+ }
3315
+ handleDisconnect(error) {
3316
+ this.connection = null;
3317
+ this.connectionAbort = null;
3318
+ if (this.isClosed()) return;
3319
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3320
+ if (this.recoveryUsed) {
3321
+ const disconnectError = new Error("Agent live channel disconnected after one recovery.");
3322
+ this.failLiveChannel(error ?? disconnectError, disconnectError);
3323
+ return;
3324
+ }
3325
+ this.recoveryUsed = true;
3326
+ const generation = ++this.recoveryGeneration;
3327
+ this.recoveryPromise = this.recoverTurn(generation).finally(() => {
3328
+ this.recoveryPromise = null;
3329
+ });
3330
+ }
3331
+ async recoverTurn(generation) {
3332
+ try {
3333
+ await this.ensureChannel();
3334
+ while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
3335
+ if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
3336
+ return;
3337
+ }
3338
+ if (this.activeWaiter?.settled) return;
3339
+ await delay(RECONCILE_DELAY_MS);
3340
+ }
3341
+ } catch (error) {
3342
+ if (this.isClosed()) return;
3343
+ const recoveryError = error instanceof Error ? error : new Error(errorMessage(error));
3344
+ this.failLiveChannel(error, recoveryError);
3345
+ }
3346
+ }
3347
+ async captureTurnBaseline() {
3348
+ if (!this._taskId) return;
3349
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3350
+ size: 100,
3351
+ sort: "createdAt,desc"
3352
+ });
3353
+ this.turnBaselineIds = new Set(page.content.map((message) => message.id));
3354
+ }
3355
+ async reconcilePersistedTurn(reason) {
3356
+ if (!this._taskId) return false;
3357
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3358
+ size: 100,
3359
+ sort: "createdAt,desc"
3360
+ });
3361
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
3362
+ this.emit("historyLoaded", { history: this.history });
3363
+ const recovered = page.content.find(
3364
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
3365
+ );
3366
+ if (!recovered) return false;
3367
+ if (recovered.type === "ERROR") {
3368
+ const error = new AgentTaskTurnError(recovered.content);
3369
+ this.emit("error", { error: error.message });
3370
+ this.failTurn(error);
3371
+ return true;
3372
+ }
3373
+ this._content = recovered.content;
3374
+ this.finishTurn(reason);
3375
+ return true;
3376
+ }
3377
+ sendInput(input) {
3378
+ if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3379
+ return this.dependencies.tasks.sendInput(this._taskId, input);
3380
+ }
3381
+ handleEvent(event) {
3382
+ this.emit("raw", event);
3383
+ const payload = asObject(event.payload);
3384
+ switch (event.type) {
3385
+ case "textDelta":
3386
+ this.consumeDelta(payload, "text");
3387
+ break;
3388
+ case "thinking":
3389
+ this.consumeDelta(payload, "thinking");
3390
+ break;
3391
+ case "toolCall":
3392
+ this.emitTool(payload, "call", event.timestamp);
3393
+ break;
3394
+ case "toolResult":
3395
+ this.emitTool(payload, "result", event.timestamp);
3396
+ break;
3397
+ case "workspace":
3398
+ this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
3399
+ break;
3400
+ case "stepFinish": {
3401
+ const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
3402
+ if (reason === "stop" || reason === "endTurn") {
3403
+ if (this.recoveryUsed) {
3404
+ this.recoveredTerminalReason = reason;
3405
+ if (!this.recoveryPromise) {
3406
+ const generation = this.recoveryGeneration;
3407
+ this.recoveryPromise = this.recoverTurn(generation).finally(() => {
3408
+ this.recoveryPromise = null;
3409
+ });
3410
+ }
3411
+ } else {
3412
+ this.finishTurn(reason);
3413
+ }
3414
+ }
3415
+ break;
3416
+ }
3417
+ case "error": {
3418
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
3419
+ const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
3420
+ this.emit("error", { ...code ? { code } : {}, error: message });
3421
+ if (this._status === "streaming" || this._status === "cancelled") {
3422
+ this.failTurn(new AgentTaskTurnError(message, code));
3423
+ }
3424
+ break;
3425
+ }
3426
+ default:
3427
+ break;
3428
+ }
3429
+ }
3430
+ consumeDelta(payload, kind) {
3431
+ const text = typeof payload?.text === "string" ? payload.text : "";
3432
+ if (this._status !== "streaming" && this._status !== "cancelled") {
3433
+ this.setStatus("streaming");
3434
+ this.emit("turnStart", {});
3435
+ }
3436
+ if (kind === "text") this._content += text;
3437
+ this.emit("delta", { delta: text, kind });
3438
+ }
3439
+ emitTool(payload, phase, timestamp) {
3440
+ this.emit("tool", {
3441
+ tool: typeof payload?.name === "string" ? payload.name : "",
3442
+ phase,
3443
+ timestamp,
3444
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
3445
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
3446
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
3447
+ });
3448
+ }
3449
+ finishTurn(reason) {
3450
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3451
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3452
+ this.cancelTimer = null;
3453
+ this.recoveryGeneration += 1;
3454
+ const task = this._task;
3455
+ if (!task) {
3456
+ const error = new Error("Agent turn ended before task metadata was available.");
3457
+ this.activeWaiter?.reject(error);
3458
+ this.activeWaiter = void 0;
3459
+ this.emitError("Failed to finish Agent turn", error);
3460
+ this.setStatus("error");
3461
+ return;
3462
+ }
3463
+ const result = { task, content: this._content, reason };
3464
+ this.emit("turnEnd", result);
3465
+ this.activeWaiter?.resolve(result);
3466
+ this.activeWaiter = void 0;
3467
+ this.setStatus("idle");
3468
+ this.flushQueue();
3469
+ }
3470
+ failTurn(error) {
3471
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3472
+ this.cancelTimer = null;
3473
+ this.recoveryGeneration += 1;
3474
+ this.activeWaiter?.reject(error);
3475
+ this.activeWaiter = void 0;
3476
+ this.setStatus("idle");
3477
+ this.flushQueue();
3478
+ }
3479
+ failLiveChannel(observed, waiterError) {
3480
+ this.recoveryGeneration += 1;
3481
+ this.emitError("Agent live channel failed", observed);
3482
+ this.activeWaiter?.reject(waiterError);
3483
+ this.activeWaiter = void 0;
3484
+ for (const item of this._queue) item.waiter?.reject(waiterError);
3485
+ this._queue = [];
3486
+ this.emitQueue();
3487
+ this.setStatus("error");
3488
+ }
3489
+ enqueue(text, options, waiter) {
3490
+ if (this._queue.length >= AGENT_QUEUE_LIMIT) {
3491
+ const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
3492
+ waiter?.reject(error);
3493
+ this.emit("error", { error: error.message });
3494
+ return void 0;
3495
+ }
3496
+ const id = `q-${++this.queueSequence}`;
3497
+ this._queue = [
3498
+ ...this._queue,
3499
+ { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
3500
+ ];
3501
+ this.emitQueue();
3502
+ return id;
3503
+ }
3504
+ flushQueue() {
3505
+ if (this.isBusy()) return;
3506
+ let next = this._queue[0];
3507
+ while (next?.waiter?.settled) {
3508
+ this._queue = this._queue.slice(1);
3509
+ next = this._queue[0];
3510
+ }
3511
+ if (!next) {
3512
+ this.emitQueue();
3513
+ return;
3514
+ }
3515
+ this._queue = this._queue.slice(1);
3516
+ this.emitQueue();
3517
+ this.startDispatch(
3518
+ next.text,
3519
+ {
3520
+ ...next.agentType ? { agentType: next.agentType } : {},
3521
+ ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
3522
+ },
3523
+ next.waiter
3524
+ );
3525
+ }
3526
+ createWaiter(options) {
3527
+ let resolvePromise;
3528
+ let rejectPromise;
3529
+ let timer;
3530
+ let abortListener;
3531
+ const waiter = {
3532
+ promise: new Promise((resolve, reject) => {
3533
+ resolvePromise = resolve;
3534
+ rejectPromise = reject;
3535
+ }),
3536
+ settled: false,
3537
+ resolve: (result) => {
3538
+ if (waiter.settled) return;
3539
+ waiter.settled = true;
3540
+ waiter.cleanup();
3541
+ resolvePromise(result);
3542
+ },
3543
+ reject: (error) => {
3544
+ if (waiter.settled) return;
3545
+ waiter.settled = true;
3546
+ waiter.cleanup();
3547
+ if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
3548
+ rejectPromise(error);
3549
+ },
3550
+ cleanup: () => {
3551
+ if (timer) clearTimeout(timer);
3552
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener);
3553
+ }
3554
+ };
3555
+ if (options.timeoutMs !== void 0) {
3556
+ if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
3557
+ waiter.reject(new Error("Agent turn timeoutMs must be a positive number."));
3558
+ return waiter;
3559
+ }
3560
+ timer = setTimeout(
3561
+ () => waiter.reject(new Error(`Agent turn timed out after ${options.timeoutMs} ms.`)),
3562
+ options.timeoutMs
3563
+ );
3564
+ }
3565
+ if (options.signal) {
3566
+ abortListener = () => waiter.reject(options.signal?.reason ?? new Error("Agent turn aborted."));
3567
+ if (options.signal.aborted) abortListener();
3568
+ else options.signal.addEventListener("abort", abortListener, { once: true });
3569
+ }
3570
+ return waiter;
3571
+ }
3572
+ removeQueuedWaiter(id) {
3573
+ const size = this._queue.length;
3574
+ this._queue = this._queue.filter((item) => item.id !== id);
3575
+ if (this._queue.length !== size) this.emitQueue();
3576
+ }
3577
+ emitQueue() {
3578
+ this.emit("queueChange", { queue: this.queue });
3579
+ }
3580
+ emitError(prefix, error) {
3581
+ const code = errorCode(error);
3582
+ this.emit("error", {
3583
+ ...code ? { code } : {},
3584
+ error: `${prefix}: ${errorMessage(error)}`
3585
+ });
3586
+ }
3587
+ setStatus(status) {
3588
+ if (this._status === status) return;
3589
+ this._status = status;
3590
+ this.emit("statusChange", { status });
3591
+ }
3592
+ requireOpen() {
3593
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
3594
+ }
3595
+ isClosed() {
3596
+ return this._status === "closed";
3597
+ }
3598
+ isBusy() {
3599
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled";
3600
+ }
3601
+ emit(event, payload) {
3602
+ const listeners = this.listeners.get(event);
3603
+ for (const listener of listeners ?? []) {
3604
+ try {
3605
+ listener(payload);
3606
+ } catch {
3607
+ }
3608
+ }
3609
+ }
3610
+ };
390
3611
  export {
3612
+ AgentTaskTurnError,
391
3613
  SdkCoreConfigurationError,
392
3614
  SdkCoreResponseError,
3615
+ createAgentConnectionsModule,
3616
+ createAgentCredentialsModule,
3617
+ createAgentTaskSessionManager,
3618
+ createAgentTasksModule,
3619
+ createAgentsModule,
3620
+ createAppsModule,
393
3621
  createAuthModule,
3622
+ createContextModule,
3623
+ createCustomQueriesModule,
3624
+ createDataSourcesModule,
394
3625
  createEntitiesModule,
3626
+ createFunctionsAdminModule,
395
3627
  createFunctionsModule,
3628
+ createImportsModule,
3629
+ createIntegrationAdminModule,
396
3630
  createIntegrationModule,
3631
+ createIntegrationResourcesModule,
3632
+ createIntegrationTemplatesModule,
3633
+ createMembersModule,
3634
+ createMessengerModule,
3635
+ createPublicFunctionsModule,
397
3636
  createQueriesModule,
3637
+ createSchemaModule,
398
3638
  createSdkCore,
3639
+ createSqlModule,
3640
+ createWorkflowsModule,
399
3641
  defaultSdkCoreErrorFactory,
400
3642
  encodePathSegment,
401
3643
  expectEmpty,
3644
+ expectLegacyPage,
3645
+ expectNullableObject,
402
3646
  expectObject,
403
- expectObjectArray
3647
+ expectObjectArray,
3648
+ expectPage,
3649
+ expectStringArray,
3650
+ toAgentTimelineItem,
3651
+ withAgentTaskSessions
404
3652
  };