@mitralab.io/sdk-core 0.1.1 → 0.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,6 +60,21 @@ 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
79
  return Object.hasOwn(value, property);
45
80
  }
@@ -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,2083 @@ 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
+ expectIntegrationFieldsSchema(template.fieldsSchema, `${context} fieldsSchema`, errors);
787
+ if (!isNullableString(template.documentationUrl)) {
788
+ invalidField(context, "documentationUrl", errors);
789
+ }
790
+ return template;
791
+ }
792
+ function expectIntegrationFieldsSchema(value, context, errors) {
793
+ expectObjectArray(value, context, errors).forEach((field, position) => {
794
+ const fieldContext = `${context} field ${position}`;
795
+ if (typeof field.key !== "string") invalidField(fieldContext, "key", errors);
796
+ if (typeof field.label !== "string") invalidField(fieldContext, "label", errors);
797
+ if (!isOneOf(field.type, ["url", "text", "secret"])) {
798
+ invalidField(fieldContext, "type", errors);
799
+ }
800
+ if (typeof field.required !== "boolean") invalidField(fieldContext, "required", errors);
801
+ if (!isNullableString(field.placeholder)) invalidField(fieldContext, "placeholder", errors);
802
+ if (!isNullableString(field.default)) invalidField(fieldContext, "default", errors);
803
+ });
804
+ }
805
+ function expectIntegrationLoginConfig(value, context, errors) {
806
+ const config = expectObject(value, context, errors);
807
+ if (!isNullableString(config.url)) invalidField(context, "url", errors);
808
+ if (!isNullableString(config.method)) invalidField(context, "method", errors);
809
+ for (const field of ["headers", "query_params", "body_form", "body"]) {
810
+ if (config[field] !== null && !isJsonRecord(config[field])) {
811
+ invalidField(context, field, errors);
812
+ }
813
+ }
814
+ if (config.token_extraction !== null) {
815
+ const extraction = expectObject(
816
+ config.token_extraction,
817
+ `${context} token_extraction`,
818
+ errors
819
+ );
820
+ for (const field of ["source", "path", "name"]) {
821
+ if (!isNullableString(extraction[field])) {
822
+ invalidField(`${context} token_extraction`, field, errors);
823
+ }
824
+ }
825
+ }
826
+ if (!isNullableInteger(config.token_ttl_seconds)) {
827
+ invalidField(context, "token_ttl_seconds", errors);
828
+ }
829
+ }
830
+ function expectIntegrationRequestConfig(value, context, errors) {
831
+ const config = expectObject(value, context, errors);
832
+ if (config.headers !== null && !isJsonRecord(config.headers)) {
833
+ invalidField(context, "headers", errors);
834
+ }
835
+ if (config.credential_rules !== null) {
836
+ expectObjectArray(
837
+ config.credential_rules,
838
+ `${context} credential_rules`,
839
+ errors
840
+ ).forEach((rule, position) => {
841
+ const ruleContext = `${context} credential rule ${position}`;
842
+ if (rule.placement !== null && !isOneOf(rule.placement, ["HEADER", "QUERY", "COOKIE", "BODY", "BASIC"])) {
843
+ invalidField(ruleContext, "placement", errors);
844
+ }
845
+ for (const field of ["name", "path", "value"]) {
846
+ if (!isNullableString(rule[field])) invalidField(ruleContext, field, errors);
847
+ }
848
+ });
849
+ }
850
+ }
851
+ function expectInlineDefinition(config, context, errors) {
852
+ if (hasOwn(config, "fieldsSchemaInline") && config.fieldsSchemaInline !== null) {
853
+ expectIntegrationFieldsSchema(
854
+ config.fieldsSchemaInline,
855
+ `${context} fieldsSchemaInline`,
856
+ errors
857
+ );
858
+ }
859
+ if (hasOwn(config, "requestConfigInline") && config.requestConfigInline !== null) {
860
+ expectIntegrationRequestConfig(
861
+ config.requestConfigInline,
862
+ `${context} requestConfigInline`,
863
+ errors
864
+ );
865
+ }
866
+ if (hasOwn(config, "loginConfigInline") && config.loginConfigInline !== null) {
867
+ expectIntegrationLoginConfig(config.loginConfigInline, `${context} loginConfigInline`, errors);
868
+ }
869
+ }
870
+ function expectTemplateConfigSummary(value, context, errors = defaultSdkCoreErrorFactory) {
871
+ const config = expectObject(value, context, errors);
872
+ if (typeof config.id !== "string") invalidField(context, "id", errors);
873
+ if (!isNullableString(config.appId)) invalidField(context, "appId", errors);
874
+ if (!isNullableInteger(config.legacyId)) invalidField(context, "legacyId", errors);
875
+ if (!isNullableString(config.templateId)) invalidField(context, "templateId", errors);
876
+ if (typeof config.alias !== "string") invalidField(context, "alias", errors);
877
+ expectInlineDefinition(config, context, errors);
878
+ if (config.status !== null && !isOneOf(config.status, ["unchecked", "connected", "error"])) {
879
+ invalidField(context, "status", errors);
880
+ }
881
+ if (!isNullableString(config.lastCheckedAt)) invalidField(context, "lastCheckedAt", errors);
882
+ return config;
883
+ }
884
+ function expectTemplateConfig(value, context, errors = defaultSdkCoreErrorFactory) {
885
+ const config = expectTemplateConfigSummary(value, context, errors);
886
+ if (typeof config.tenantId !== "string") invalidField(context, "tenantId", errors);
887
+ if (!isJsonRecord(config.config)) invalidField(context, "config", errors);
888
+ if (!isNullableString(config.lastCheckMessage)) {
889
+ invalidField(context, "lastCheckMessage", errors);
890
+ }
891
+ if (typeof config.createdAt !== "string") invalidField(context, "createdAt", errors);
892
+ if (typeof config.updatedAt !== "string") invalidField(context, "updatedAt", errors);
893
+ return config;
894
+ }
895
+ function expectIntegrationExecution(value, context, errors = defaultSdkCoreErrorFactory) {
896
+ const execution = expectObject(value, context, errors);
897
+ if (typeof execution.id !== "string") invalidField(context, "id", errors);
898
+ if (typeof execution.templateConfigId !== "string") {
899
+ invalidField(context, "templateConfigId", errors);
900
+ }
901
+ if (!isNullableString(execution.appId)) invalidField(context, "appId", errors);
902
+ if (typeof execution.method !== "string") invalidField(context, "method", errors);
903
+ if (typeof execution.endpoint !== "string") invalidField(context, "endpoint", errors);
904
+ if (!hasOwn(execution, "requestBody") || !isJsonValue(execution.requestBody)) {
905
+ invalidField(context, "requestBody", errors);
906
+ }
907
+ if (!isNullableInteger(execution.responseStatus)) {
908
+ invalidField(context, "responseStatus", errors);
909
+ }
910
+ if (!hasOwn(execution, "responseBody") || !isJsonValue(execution.responseBody)) {
911
+ invalidField(context, "responseBody", errors);
912
+ }
913
+ if (!isNullableInteger(execution.durationMs)) invalidField(context, "durationMs", errors);
914
+ if (typeof execution.success !== "boolean") invalidField(context, "success", errors);
915
+ if (!isNullableString(execution.errorMessage)) invalidField(context, "errorMessage", errors);
916
+ if (!isNullableString(execution.source)) invalidField(context, "source", errors);
917
+ if (typeof execution.createdAt !== "string") invalidField(context, "createdAt", errors);
918
+ return execution;
919
+ }
920
+ function expectAgentTask(value, context, errors = defaultSdkCoreErrorFactory) {
921
+ const task = expectObject(value, context, errors);
922
+ if (typeof task.id !== "string") invalidField(context, "id", errors);
923
+ for (const field of ["appId", "agentId", "userId", "title", "reasoningEffort"]) {
924
+ if (!isNullableString(task[field])) invalidField(context, field, errors);
925
+ }
926
+ if (typeof task.agentType !== "string") invalidField(context, "agentType", errors);
927
+ if (typeof task.archived !== "boolean") invalidField(context, "archived", errors);
928
+ if (!isNullableString(task.createdAt)) invalidField(context, "createdAt", errors);
929
+ if (typeof task.updatedAt !== "string") invalidField(context, "updatedAt", errors);
930
+ return task;
931
+ }
932
+ function expectAgentMessage(value, context, errors = defaultSdkCoreErrorFactory) {
933
+ const message = expectObject(value, context, errors);
934
+ for (const field of ["id", "sender", "type", "content", "createdAt"]) {
935
+ if (typeof message[field] !== "string") invalidField(context, field, errors);
936
+ }
937
+ return message;
938
+ }
939
+ function expectAgentModel(value, context, errors = defaultSdkCoreErrorFactory) {
940
+ const model = expectObject(value, context, errors);
941
+ for (const field of ["model", "name", "provider", "agentType"]) {
942
+ if (typeof model[field] !== "string") invalidField(context, field, errors);
943
+ }
944
+ if (!isStringArray(model.reasoningOptions)) invalidField(context, "reasoningOptions", errors);
945
+ return model;
946
+ }
947
+ function expectCredentialStatus(value, context, errors = defaultSdkCoreErrorFactory) {
948
+ const status = expectObject(value, context, errors);
949
+ if (typeof status.provider !== "string") invalidField(context, "provider", errors);
950
+ if (typeof status.connected !== "boolean") invalidField(context, "connected", errors);
951
+ for (const field of ["credentialType", "accountEmail", "maskedApiKey"]) {
952
+ if (!isNullableString(status[field])) invalidField(context, field, errors);
953
+ }
954
+ return status;
955
+ }
956
+ function expectOAuthStartResult(value, context, errors = defaultSdkCoreErrorFactory) {
957
+ const result = expectObject(value, context, errors);
958
+ if (typeof result.authUrl !== "string") invalidField(context, "authUrl", errors);
959
+ if (typeof result.state !== "string") invalidField(context, "state", errors);
960
+ return result;
961
+ }
962
+ function expectAuthenticationResult(value, context, errors = defaultSdkCoreErrorFactory) {
963
+ const result = expectObject(value, context, errors);
964
+ if (typeof result.connected !== "boolean") invalidField(context, "connected", errors);
965
+ if (!isNullableString(result.email)) invalidField(context, "email", errors);
966
+ return result;
967
+ }
968
+ function expectDeviceAuthorization(value, context, errors = defaultSdkCoreErrorFactory) {
969
+ const result = expectObject(value, context, errors);
970
+ for (const field of ["deviceAuthId", "userCode", "verificationUri"]) {
971
+ if (typeof result[field] !== "string") invalidField(context, field, errors);
972
+ }
973
+ if (!isInteger(result.intervalSeconds)) invalidField(context, "intervalSeconds", errors);
974
+ return result;
975
+ }
976
+ function expectProviderCredentialStatus(value, context, errors) {
977
+ const status = expectObject(value, context, errors);
978
+ if (typeof status.provider !== "string") invalidField(context, "provider", errors);
979
+ if (typeof status.connected !== "boolean") invalidField(context, "connected", errors);
980
+ if (!isNullableString(status.credentialType)) invalidField(context, "credentialType", errors);
981
+ if (!isNullableString(status.accountEmail)) invalidField(context, "accountEmail", errors);
982
+ return status;
983
+ }
984
+ function expectAgentConnection(value, context, errors = defaultSdkCoreErrorFactory) {
985
+ const connection = expectObject(value, context, errors);
986
+ if (typeof connection.id !== "string") invalidField(context, "id", errors);
987
+ if (typeof connection.name !== "string") invalidField(context, "name", errors);
988
+ if (typeof connection.createdAt !== "string") invalidField(context, "createdAt", errors);
989
+ if (typeof connection.updatedAt !== "string") invalidField(context, "updatedAt", errors);
990
+ expectObjectArray(
991
+ connection.credentials,
992
+ `${context} credentials`,
993
+ errors,
994
+ expectProviderCredentialStatus
995
+ );
996
+ return connection;
997
+ }
998
+ function expectTableDefinition(value, context, errors = defaultSdkCoreErrorFactory) {
999
+ const wrapped = expectSchemaTables([{ schema: "validation", tables: [value] }], context, errors);
1000
+ return wrapped[0].tables[0];
1001
+ }
1002
+ function expectFunctionSummary(value, context, errors = defaultSdkCoreErrorFactory) {
1003
+ const summary = expectObject(value, context, errors);
1004
+ if (typeof summary.id !== "string") invalidField(context, "id", errors);
1005
+ if (typeof summary.tenantId !== "string") invalidField(context, "tenantId", errors);
1006
+ if (!isNullableString(summary.appId)) invalidField(context, "appId", errors);
1007
+ if (!isNullableInteger(summary.legacyId)) invalidField(context, "legacyId", errors);
1008
+ if (typeof summary.name !== "string") invalidField(context, "name", errors);
1009
+ if (!isNullableString(summary.description)) invalidField(context, "description", errors);
1010
+ if (typeof summary.runtime !== "string") invalidField(context, "runtime", errors);
1011
+ if (!isNullableString(summary.dataSourceId)) invalidField(context, "dataSourceId", errors);
1012
+ if (typeof summary.visibility !== "string") invalidField(context, "visibility", errors);
1013
+ if (!isNullableString(summary.cronExpression)) invalidField(context, "cronExpression", errors);
1014
+ if (summary.cronInputJson !== null && !isJsonRecord(summary.cronInputJson)) {
1015
+ invalidField(context, "cronInputJson", errors);
1016
+ }
1017
+ if (!isNullableBoolean(summary.cronEnabled)) invalidField(context, "cronEnabled", errors);
1018
+ if (typeof summary.createdAt !== "string") invalidField(context, "createdAt", errors);
1019
+ if (typeof summary.updatedAt !== "string") invalidField(context, "updatedAt", errors);
1020
+ return summary;
1021
+ }
1022
+ function expectFunctionVersionResponse(value, context, errors = defaultSdkCoreErrorFactory) {
1023
+ expectFunctionVersion(value, context, errors);
1024
+ return value;
1025
+ }
1026
+ function expectFunctionSecrets(value, context, errors = defaultSdkCoreErrorFactory) {
1027
+ const result = expectObject(value, context, errors);
1028
+ if (!isStringArray(result.secrets)) invalidField(context, "secrets", errors);
1029
+ return result;
1030
+ }
1031
+ function expectPublicFunctionResult(value, context, errors = defaultSdkCoreErrorFactory) {
1032
+ const result = expectObject(value, context, errors);
1033
+ if (typeof result.success !== "boolean") invalidField(context, "success", errors);
1034
+ if (result.output !== null && !isObject(result.output)) invalidField(context, "output", errors);
1035
+ if (!isNullableString(result.error)) invalidField(context, "error", errors);
1036
+ return result;
1037
+ }
1038
+ function expectPublicFunctionAsyncResult(value, context, errors = defaultSdkCoreErrorFactory) {
1039
+ const result = expectObject(value, context, errors);
1040
+ if (typeof result.id !== "string") invalidField(context, "id", errors);
1041
+ if (typeof result.status !== "string") invalidField(context, "status", errors);
1042
+ return result;
1043
+ }
1044
+ function expectEmpty(value, context, errors = defaultSdkCoreErrorFactory) {
1045
+ if (value !== void 0) invalidResponse(`${context} must be empty`, errors);
1046
+ }
1047
+
1048
+ // src/modules/agentConnections.ts
1049
+ var MAX_CONNECTIONS = 100;
1050
+ function createAgentConnectionsModule(transport, errors = defaultSdkCoreErrorFactory) {
1051
+ const path = (id) => `/api/v1/connections/${encodePathSegment(id, "connection id", errors)}`;
1052
+ const providerPath = (id, provider) => `${path(id)}/providers/${encodePathSegment(provider, "provider", errors)}`;
1053
+ return {
1054
+ async list() {
1055
+ return expectObjectArray(
1056
+ await transport.request("/api/v1/connections", { method: "GET" }),
1057
+ "Connection response",
1058
+ errors,
1059
+ expectAgentConnection
1060
+ );
1061
+ },
1062
+ async get(id) {
1063
+ return expectAgentConnection(
1064
+ await transport.request(path(id), { method: "GET" }),
1065
+ "Connection response",
1066
+ errors
1067
+ );
1068
+ },
1069
+ async create(name) {
1070
+ return expectAgentConnection(
1071
+ await transport.request("/api/v1/connections", {
1072
+ method: "POST",
1073
+ body: { name }
1074
+ }),
1075
+ "Create connection response",
1076
+ errors
1077
+ );
1078
+ },
1079
+ async bulkCreate(inputs) {
1080
+ requireBatchSize(inputs, "connections", MAX_CONNECTIONS, errors);
1081
+ return expectObjectArray(
1082
+ await transport.request("/api/v1/connections/bulk", {
1083
+ method: "POST",
1084
+ body: { connections: inputs }
1085
+ }),
1086
+ "Bulk create connections response",
1087
+ errors,
1088
+ expectAgentConnection
1089
+ );
1090
+ },
1091
+ async delete(id) {
1092
+ expectEmpty(
1093
+ await transport.request(path(id), { method: "DELETE" }),
1094
+ "Delete connection response",
1095
+ errors
1096
+ );
1097
+ },
1098
+ async saveApiKey(id, provider, apiKey) {
1099
+ expectEmpty(
1100
+ await transport.request(`${providerPath(id, provider)}/api-key`, {
1101
+ method: "PUT",
1102
+ body: { apiKey }
1103
+ }),
1104
+ "Save connection API key response",
1105
+ errors
1106
+ );
1107
+ },
1108
+ async disconnectProvider(id, provider) {
1109
+ expectEmpty(
1110
+ await transport.request(providerPath(id, provider), { method: "DELETE" }),
1111
+ "Disconnect connection provider response",
1112
+ errors
1113
+ );
1114
+ },
1115
+ async startOAuth(id, provider) {
1116
+ return expectOAuthStartResult(
1117
+ await transport.request(`${providerPath(id, provider)}/oauth/start`, {
1118
+ method: "POST"
1119
+ }),
1120
+ "Connection OAuth start response",
1121
+ errors
1122
+ );
1123
+ },
1124
+ async exchangeOAuth(id, provider, input) {
1125
+ return expectAuthenticationResult(
1126
+ await transport.request(`${providerPath(id, provider)}/oauth/exchange`, {
1127
+ method: "POST",
1128
+ body: input
1129
+ }),
1130
+ "Connection OAuth exchange response",
1131
+ errors
1132
+ );
1133
+ },
1134
+ async startDeviceAuthorization(id, provider) {
1135
+ return expectDeviceAuthorization(
1136
+ await transport.request(`${providerPath(id, provider)}/device-authorizations`, {
1137
+ method: "POST"
1138
+ }),
1139
+ "Connection device authorization response",
1140
+ errors
1141
+ );
1142
+ },
1143
+ async pollDeviceAuthorization(id, provider, deviceAuthId) {
1144
+ return expectAuthenticationResult(
1145
+ await transport.request(
1146
+ `${providerPath(id, provider)}/device-authorizations/${encodePathSegment(
1147
+ deviceAuthId,
1148
+ "device authorization id",
1149
+ errors
1150
+ )}/poll`,
1151
+ { method: "POST" }
1152
+ ),
1153
+ "Connection device authorization poll response",
1154
+ errors
1155
+ );
1156
+ }
1157
+ };
1158
+ }
1159
+
1160
+ // src/modules/agentCredentials.ts
1161
+ function createAgentCredentialsModule(transport, errors = defaultSdkCoreErrorFactory) {
1162
+ const providerSegment = (provider) => encodePathSegment(provider, "provider", errors);
1163
+ return {
1164
+ async list() {
1165
+ return expectObjectArray(
1166
+ await transport.request("/api/v1/credentials", { method: "GET" }),
1167
+ "Credential status response",
1168
+ errors,
1169
+ expectCredentialStatus
1170
+ );
1171
+ },
1172
+ async listModels(agentId) {
1173
+ return expectObjectArray(
1174
+ await transport.request("/api/v1/models", {
1175
+ method: "GET",
1176
+ params: { agentId }
1177
+ }),
1178
+ "Agent model response",
1179
+ errors,
1180
+ expectAgentModel
1181
+ );
1182
+ },
1183
+ async saveApiKey(provider, apiKey) {
1184
+ expectEmpty(
1185
+ await transport.request(
1186
+ `/api/v1/credentials/${providerSegment(provider)}/api-key`,
1187
+ { method: "PUT", body: { apiKey } }
1188
+ ),
1189
+ "Save API key response",
1190
+ errors
1191
+ );
1192
+ },
1193
+ async remove(provider) {
1194
+ expectEmpty(
1195
+ await transport.request(`/api/v1/credentials/${providerSegment(provider)}`, {
1196
+ method: "DELETE"
1197
+ }),
1198
+ "Remove credential response",
1199
+ errors
1200
+ );
1201
+ },
1202
+ async startOAuth(provider) {
1203
+ return expectOAuthStartResult(
1204
+ await transport.request("/api/v1/oauth/start", {
1205
+ method: "POST",
1206
+ body: { provider }
1207
+ }),
1208
+ "OAuth start response",
1209
+ errors
1210
+ );
1211
+ },
1212
+ async exchangeOAuth(provider, input) {
1213
+ return expectAuthenticationResult(
1214
+ await transport.request("/api/v1/oauth/exchange", {
1215
+ method: "POST",
1216
+ body: { provider, ...input }
1217
+ }),
1218
+ "OAuth exchange response",
1219
+ errors
1220
+ );
1221
+ },
1222
+ async startDeviceAuthorization(provider) {
1223
+ return expectDeviceAuthorization(
1224
+ await transport.request(
1225
+ `/api/v1/credentials/${providerSegment(provider)}/device-authorizations`,
1226
+ { method: "POST" }
1227
+ ),
1228
+ "Device authorization response",
1229
+ errors
1230
+ );
1231
+ },
1232
+ async pollDeviceAuthorization(provider, deviceAuthId) {
1233
+ return expectAuthenticationResult(
1234
+ await transport.request(
1235
+ `/api/v1/credentials/${providerSegment(provider)}/device-authorizations/${encodePathSegment(
1236
+ deviceAuthId,
1237
+ "device authorization id",
1238
+ errors
1239
+ )}/poll`,
1240
+ { method: "POST" }
1241
+ ),
1242
+ "Device authorization poll response",
1243
+ errors
1244
+ );
1245
+ }
1246
+ };
1247
+ }
1248
+
1249
+ // src/modules/agents.ts
1250
+ var MAX_AGENTS = 100;
1251
+ function createAgentsModule(functionsTransport, copilotTransport, errors = defaultSdkCoreErrorFactory) {
1252
+ const path = (id) => `/api/v1/agents/${encodePathSegment(id, "agent id", errors)}`;
1253
+ return {
1254
+ async list(options = {}) {
1255
+ const params = {
1256
+ page: options.page,
1257
+ size: options.size,
1258
+ sort: options.sort
1259
+ };
1260
+ return expectPage(
1261
+ await functionsTransport.request("/api/v1/agents", { method: "GET", params }),
1262
+ "Agent page response",
1263
+ errors,
1264
+ expectAgentDefinition
1265
+ );
1266
+ },
1267
+ async get(id) {
1268
+ return expectAgentDefinition(
1269
+ await functionsTransport.request(path(id), { method: "GET" }),
1270
+ "Agent response",
1271
+ errors
1272
+ );
1273
+ },
1274
+ async create(input) {
1275
+ return expectAgentDefinition(
1276
+ await functionsTransport.request("/api/v1/agents", {
1277
+ method: "POST",
1278
+ body: input
1279
+ }),
1280
+ "Create agent response",
1281
+ errors
1282
+ );
1283
+ },
1284
+ async update(id, input) {
1285
+ return expectAgentDefinition(
1286
+ await functionsTransport.request(path(id), { method: "PUT", body: input }),
1287
+ "Update agent response",
1288
+ errors
1289
+ );
1290
+ },
1291
+ async delete(id) {
1292
+ expectEmpty(
1293
+ await functionsTransport.request(path(id), { method: "DELETE" }),
1294
+ "Delete agent response",
1295
+ errors
1296
+ );
1297
+ },
1298
+ async bulkCreate(inputs) {
1299
+ requireBatchSize(inputs, "agents", MAX_AGENTS, errors);
1300
+ return expectObjectArray(
1301
+ await functionsTransport.request("/api/v1/agents/bulk", {
1302
+ method: "POST",
1303
+ body: { agents: inputs }
1304
+ }),
1305
+ "Bulk create agents response",
1306
+ errors,
1307
+ expectAgentDefinition
1308
+ );
1309
+ },
1310
+ async bulkUpdate(items) {
1311
+ requireBatchSize(items, "agents", MAX_AGENTS, errors);
1312
+ return expectObjectArray(
1313
+ await functionsTransport.request("/api/v1/agents/bulk", {
1314
+ method: "PUT",
1315
+ body: { agents: items }
1316
+ }),
1317
+ "Bulk update agents response",
1318
+ errors,
1319
+ expectAgentDefinition
1320
+ );
1321
+ },
1322
+ async bulkDelete(ids) {
1323
+ requireBatchSize(ids, "ids", MAX_AGENTS, errors);
1324
+ return expectAgentBulkDeleteResult(
1325
+ await functionsTransport.request("/api/v1/agents/bulk-delete", {
1326
+ method: "POST",
1327
+ body: { ids }
1328
+ }),
1329
+ "Bulk delete agents response",
1330
+ errors
1331
+ );
1332
+ },
1333
+ async listModels(agentId) {
1334
+ return expectObjectArray(
1335
+ await copilotTransport.request("/api/v1/models", {
1336
+ method: "GET",
1337
+ params: { agentId }
1338
+ }),
1339
+ "Agent model response",
1340
+ errors,
1341
+ expectAgentModel
1342
+ );
1343
+ }
1344
+ };
1345
+ }
1346
+
1347
+ // src/modules/agentTasks.ts
1348
+ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory) {
1349
+ const path = (id) => `/api/v1/tasks/${encodePathSegment(id, "task id", errors)}`;
1350
+ return {
1351
+ async list(options = {}) {
1352
+ const params = {
1353
+ page: options.page,
1354
+ size: options.size,
1355
+ sort: options.sort,
1356
+ archived: options.archived,
1357
+ agentId: options.agentId,
1358
+ search: options.search,
1359
+ userId: options.userId
1360
+ };
1361
+ return expectPage(
1362
+ await transport.request("/api/v1/tasks", { method: "GET", params }),
1363
+ "Agent task page response",
1364
+ errors,
1365
+ expectAgentTask
1366
+ );
1367
+ },
1368
+ async get(id) {
1369
+ return expectAgentTask(
1370
+ await transport.request(path(id), { method: "GET" }),
1371
+ "Agent task response",
1372
+ errors
1373
+ );
1374
+ },
1375
+ async create(input) {
1376
+ return expectAgentTask(
1377
+ await transport.request("/api/v1/tasks", { method: "POST", body: input }),
1378
+ "Create agent task response",
1379
+ errors
1380
+ );
1381
+ },
1382
+ async rename(id, title) {
1383
+ return expectAgentTask(
1384
+ await transport.request(path(id), { method: "PATCH", body: { title } }),
1385
+ "Rename agent task response",
1386
+ errors
1387
+ );
1388
+ },
1389
+ async archive(id) {
1390
+ expectEmpty(
1391
+ await transport.request(`${path(id)}/archive`, { method: "PATCH" }),
1392
+ "Archive agent task response",
1393
+ errors
1394
+ );
1395
+ },
1396
+ async sendInput(id, input) {
1397
+ expectEmpty(
1398
+ await transport.request(`${path(id)}/inputs`, { method: "POST", body: input }),
1399
+ "Agent task input response",
1400
+ errors
1401
+ );
1402
+ },
1403
+ async listMessages(id, options = {}) {
1404
+ return expectPage(
1405
+ await transport.request(`${path(id)}/messages`, {
1406
+ method: "GET",
1407
+ params: { page: options.page, size: options.size, sort: options.sort }
1408
+ }),
1409
+ "Agent message page response",
1410
+ errors,
1411
+ expectAgentMessage
1412
+ );
1413
+ }
1414
+ };
1415
+ }
1416
+
1417
+ // src/modules/apps.ts
1418
+ function createAppsModule(transport, errors = defaultSdkCoreErrorFactory) {
1419
+ const appPath = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}`;
1420
+ const params = (options = {}, defaultSort) => ({
1421
+ page: options.page,
1422
+ size: options.size,
1423
+ sort: options.sort ?? defaultSort
1424
+ });
1425
+ return {
1426
+ async list(options = {}) {
1427
+ return expectPage(
1428
+ await transport.request("/api/v1/apps", {
1429
+ method: "GET",
1430
+ params: {
1431
+ ...params(options, "createdAt,desc"),
1432
+ search: options.search,
1433
+ version: options.version,
1434
+ brand: options.brand
1435
+ }
1436
+ }),
1437
+ "App page response",
1438
+ errors,
1439
+ expectAppSummary
1440
+ );
1441
+ },
1442
+ async get(appId, options = {}) {
1443
+ return expectAppDefinition(
1444
+ await transport.request(appPath(appId), {
1445
+ method: "GET",
1446
+ params: { version: options.version }
1447
+ }),
1448
+ "App response",
1449
+ errors
1450
+ );
1451
+ },
1452
+ async create(input) {
1453
+ return expectAppDefinition(
1454
+ await transport.request("/api/v1/apps", { method: "POST", body: input }),
1455
+ "Create app response",
1456
+ errors
1457
+ );
1458
+ },
1459
+ async delete(appId) {
1460
+ expectEmpty(
1461
+ await transport.request(appPath(appId), { method: "DELETE" }),
1462
+ "Delete app response",
1463
+ errors
1464
+ );
1465
+ },
1466
+ async update(appId, input) {
1467
+ return expectAppDefinition(
1468
+ await transport.request(appPath(appId), { method: "PATCH", body: input }),
1469
+ "Update app response",
1470
+ errors
1471
+ );
1472
+ },
1473
+ async getFiles(appId) {
1474
+ return expectFiles(
1475
+ await transport.request(`${appPath(appId)}/files`, { method: "GET" }),
1476
+ errors
1477
+ );
1478
+ },
1479
+ async replaceFiles(appId, files) {
1480
+ return expectFiles(
1481
+ await transport.request(`${appPath(appId)}/files`, {
1482
+ method: "PUT",
1483
+ body: { files }
1484
+ }),
1485
+ errors
1486
+ );
1487
+ },
1488
+ async mergeFiles(appId, files) {
1489
+ return expectFiles(
1490
+ await transport.request(`${appPath(appId)}/files`, {
1491
+ method: "PATCH",
1492
+ body: { files }
1493
+ }),
1494
+ errors
1495
+ );
1496
+ },
1497
+ async build(appId) {
1498
+ return expectAppDeploy(
1499
+ await transport.request(`${appPath(appId)}/build`, { method: "POST" }),
1500
+ "Build app deploy response",
1501
+ errors
1502
+ );
1503
+ },
1504
+ async publish(appId, options = {}) {
1505
+ return expectAppDefinition(
1506
+ await transport.request(`${appPath(appId)}/publish`, {
1507
+ method: "POST",
1508
+ body: options.externalAccess === void 0 ? void 0 : options
1509
+ }),
1510
+ "Publish app response",
1511
+ errors
1512
+ );
1513
+ },
1514
+ async getDeploy(appId, deployId) {
1515
+ return expectAppDeploy(
1516
+ await transport.request(
1517
+ `${appPath(appId)}/deploys/${encodePathSegment(deployId, "deploy id", errors)}`,
1518
+ { method: "GET" }
1519
+ ),
1520
+ "App deploy response",
1521
+ errors
1522
+ );
1523
+ },
1524
+ async getCurrentDeploy(appId) {
1525
+ const response = await transport.request(`${appPath(appId)}/deploys/current`, {
1526
+ method: "GET"
1527
+ });
1528
+ return response === null || response === void 0 ? null : expectAppDeploy(response, "Current app deploy response", errors);
1529
+ },
1530
+ async cancelBuild(appId, deployId) {
1531
+ return expectAppDeploy(
1532
+ await transport.request(
1533
+ `${appPath(appId)}/deploys/${encodePathSegment(deployId, "deploy id", errors)}/cancel`,
1534
+ { method: "POST" }
1535
+ ),
1536
+ "Cancel app build response",
1537
+ errors
1538
+ );
1539
+ },
1540
+ async rollback(appId, targetVersionId) {
1541
+ return expectAppDefinition(
1542
+ await transport.request(`${appPath(appId)}/rollback`, {
1543
+ method: "POST",
1544
+ body: { targetVersionId }
1545
+ }),
1546
+ "Rollback app response",
1547
+ errors
1548
+ );
1549
+ },
1550
+ async listDeploys(appId, options = {}) {
1551
+ return expectPage(
1552
+ await transport.request(`${appPath(appId)}/deploys`, {
1553
+ method: "GET",
1554
+ params: params(options, "createdAt,desc")
1555
+ }),
1556
+ "App deploy page response",
1557
+ errors,
1558
+ expectAppDeploy
1559
+ );
1560
+ },
1561
+ async listVersions(appId, options = {}) {
1562
+ return expectPage(
1563
+ await transport.request(`${appPath(appId)}/versions`, {
1564
+ method: "GET",
1565
+ params: params(options, "createdAt,desc")
1566
+ }),
1567
+ "App version page response",
1568
+ errors,
1569
+ expectAppVersion
1570
+ );
1571
+ }
1572
+ };
1573
+ }
1574
+ function expectFiles(value, errors) {
1575
+ const response = expectObject(value, "App files response", errors);
1576
+ if (response.files === null || typeof response.files !== "object" || Array.isArray(response.files) || Object.values(response.files).some((content) => typeof content !== "string")) {
1577
+ throw errors.invalidResponse("App files response has an invalid files field");
1578
+ }
1579
+ return response;
1580
+ }
1581
+
1582
+ // src/modules/auth.ts
1583
+ function createAuthModule(transport, errors = defaultSdkCoreErrorFactory) {
1584
+ return {
1585
+ async me() {
1586
+ return expectUser(
1587
+ await transport.request("/api/v1/auth/me", { method: "GET" }),
1588
+ "Current user response",
1589
+ errors
1590
+ );
1591
+ },
1592
+ async listUserPlans() {
1593
+ return expectObjectArray(
1594
+ await transport.request("/api/v1/user-plans", { method: "GET" }),
1595
+ "User plan response",
1596
+ errors,
1597
+ expectUserPlan
1598
+ );
1599
+ }
1600
+ };
1601
+ }
1602
+
1603
+ // src/modules/context.ts
1604
+ var SUMMARY_PAGE_SIZE = 2e3;
1605
+ function createContextModule(dependencies, errors = defaultSdkCoreErrorFactory) {
1606
+ return {
1607
+ async getAppContext() {
1608
+ const appId = dependencies.getAppId?.();
1609
+ if (!appId) {
1610
+ configurationError("An appId is required for app context", errors);
1611
+ }
1612
+ const app = await dependencies.apps.get(appId);
1613
+ const tables = await dependencies.schema.listTables({ scope: "APP", includeColumns: true });
1614
+ const functionsPage = await dependencies.functionsAdmin.list({
1615
+ page: 0,
1616
+ size: SUMMARY_PAGE_SIZE,
1617
+ sort: "name"
1618
+ });
1619
+ const agentsPage = await dependencies.agents.list({
1620
+ page: 0,
1621
+ size: SUMMARY_PAGE_SIZE,
1622
+ sort: "name"
1623
+ });
1624
+ const fileResponse = await dependencies.apps.getFiles(appId);
1625
+ const integrationsPage = await dependencies.integrationAdmin.list({
1626
+ page: 0,
1627
+ size: SUMMARY_PAGE_SIZE,
1628
+ sort: "alias"
1629
+ });
1630
+ const connections = await dependencies.agentConnections.list();
1631
+ return {
1632
+ appId,
1633
+ app,
1634
+ tables,
1635
+ functions: functionsPage.content,
1636
+ functionsTotal: functionsPage.page.totalElements,
1637
+ functionsTruncated: functionsPage.content.length < functionsPage.page.totalElements,
1638
+ agents: agentsPage.content,
1639
+ agentsTotal: agentsPage.page.totalElements,
1640
+ agentsTruncated: agentsPage.content.length < agentsPage.page.totalElements,
1641
+ files: Object.keys(fileResponse.files).sort(),
1642
+ integrations: integrationsPage.content,
1643
+ integrationsTotal: integrationsPage.totalElements,
1644
+ integrationsTruncated: integrationsPage.content.length < integrationsPage.totalElements,
1645
+ connections
1646
+ };
1647
+ }
1648
+ };
1649
+ }
1650
+
1651
+ // src/modules/customQueries.ts
1652
+ function createCustomQueriesModule(transport, errors = defaultSdkCoreErrorFactory) {
1653
+ const path = (id) => `/api/v1/custom-queries/${encodePathSegment(id, "query id", errors)}`;
1654
+ return {
1655
+ async list(options = {}) {
1656
+ const params = {
1657
+ page: options.page,
1658
+ size: options.size ?? 20,
1659
+ sort: options.sort ?? "name"
1660
+ };
1661
+ return expectPage(
1662
+ await transport.request("/api/v1/custom-queries", { method: "GET", params }),
1663
+ "Custom query page response",
1664
+ errors,
1665
+ expectCustomQuerySummary
1666
+ );
1667
+ },
1668
+ async get(id) {
1669
+ return expectCustomQueryDefinition(
1670
+ await transport.request(path(id), { method: "GET" }),
1671
+ "Custom query response",
1672
+ errors
1673
+ );
1674
+ },
1675
+ async create(input) {
1676
+ return expectCustomQueryDefinition(
1677
+ await transport.request("/api/v1/custom-queries", { method: "POST", body: input }),
1678
+ "Create custom query response",
1679
+ errors
1680
+ );
1681
+ },
1682
+ async update(id, input) {
1683
+ return expectCustomQueryDefinition(
1684
+ await transport.request(path(id), { method: "PUT", body: input }),
1685
+ "Update custom query response",
1686
+ errors
1687
+ );
1688
+ },
1689
+ async delete(id) {
1690
+ expectEmpty(
1691
+ await transport.request(path(id), { method: "DELETE" }),
1692
+ "Delete custom query response",
1693
+ errors
1694
+ );
1695
+ },
1696
+ async execute(id, parameters = {}) {
1697
+ return expectQueryResult(
1698
+ await transport.request(`${path(id)}/execute`, {
1699
+ method: "POST",
1700
+ body: { parameters }
1701
+ }),
1702
+ "Custom query execution response",
1703
+ errors
1704
+ );
1705
+ }
1706
+ };
1707
+ }
1708
+
1709
+ // src/modules/dataSources.ts
1710
+ var MAX_DATA_SOURCES = 100;
1711
+ function bulkFailure(index, dataSourceId, error) {
1712
+ const errorCode2 = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
1713
+ return {
1714
+ index,
1715
+ success: false,
1716
+ dataSourceId,
1717
+ errorCode: errorCode2,
1718
+ message: error instanceof Error ? error.message : "Data Source operation failed"
1719
+ };
1720
+ }
1721
+ function bulkResult(results) {
1722
+ const succeededCount = results.filter(({ success }) => success).length;
1723
+ return {
1724
+ results,
1725
+ processedCount: results.length,
1726
+ succeededCount,
1727
+ failedCount: results.length - succeededCount
1728
+ };
1729
+ }
1730
+ function createDataSourcesModule(transport, errors = defaultSdkCoreErrorFactory) {
1731
+ const path = (id) => `/api/v1/data-sources/${encodePathSegment(id, "data source id", errors)}`;
1732
+ const createOne = async (input) => expectDataSourceDefinition(
1733
+ await transport.request("/api/v1/data-sources", { method: "POST", body: input }),
1734
+ "Create Data Source response",
1735
+ errors
1736
+ );
1737
+ const updateOne = async (id, input) => expectDataSourceDefinition(
1738
+ await transport.request(path(id), { method: "PUT", body: input }),
1739
+ "Update Data Source response",
1740
+ errors
1741
+ );
1742
+ const deleteOne = async (id) => {
1743
+ expectEmpty(
1744
+ await transport.request(path(id), { method: "DELETE" }),
1745
+ "Delete Data Source response",
1746
+ errors
1747
+ );
1748
+ };
1749
+ return {
1750
+ async list(options = {}) {
1751
+ const params = {
1752
+ page: options.page,
1753
+ size: options.size,
1754
+ sort: options.sort
1755
+ };
1756
+ return expectPage(
1757
+ await transport.request("/api/v1/data-sources", { method: "GET", params }),
1758
+ "Data Source page response",
1759
+ errors,
1760
+ expectDataSourceDefinition
1761
+ );
1762
+ },
1763
+ async get(id) {
1764
+ return expectDataSourceDefinition(
1765
+ await transport.request(path(id), { method: "GET" }),
1766
+ "Data Source response",
1767
+ errors
1768
+ );
1769
+ },
1770
+ async create(input) {
1771
+ return createOne(input);
1772
+ },
1773
+ async update(id, input) {
1774
+ return updateOne(id, input);
1775
+ },
1776
+ async delete(id) {
1777
+ return deleteOne(id);
1778
+ },
1779
+ async bulkCreate(dataSources) {
1780
+ requireBatchSize(dataSources, "dataSources", MAX_DATA_SOURCES, errors);
1781
+ const results = [];
1782
+ for (const [index, input] of dataSources.entries()) {
1783
+ try {
1784
+ const created = await createOne(input);
1785
+ results.push({
1786
+ index,
1787
+ success: true,
1788
+ dataSourceId: created.id,
1789
+ errorCode: null,
1790
+ message: null
1791
+ });
1792
+ } catch (error) {
1793
+ results.push(bulkFailure(index, null, error));
1794
+ }
1795
+ }
1796
+ return bulkResult(results);
1797
+ },
1798
+ async bulkUpdate(dataSources) {
1799
+ requireBatchSize(dataSources, "dataSources", MAX_DATA_SOURCES, errors);
1800
+ const paths = dataSources.map(({ dataSourceId }) => path(dataSourceId));
1801
+ const results = [];
1802
+ for (const [index, { dataSourceId, ...input }] of dataSources.entries()) {
1803
+ try {
1804
+ const updated = expectDataSourceDefinition(
1805
+ await transport.request(paths[index], { method: "PUT", body: input }),
1806
+ "Update Data Source response",
1807
+ errors
1808
+ );
1809
+ results.push({
1810
+ index,
1811
+ success: true,
1812
+ dataSourceId: updated.id,
1813
+ errorCode: null,
1814
+ message: null
1815
+ });
1816
+ } catch (error) {
1817
+ results.push(bulkFailure(index, dataSourceId, error));
1818
+ }
1819
+ }
1820
+ return bulkResult(results);
1821
+ },
1822
+ async bulkDelete(dataSourceIds) {
1823
+ requireBatchSize(dataSourceIds, "dataSourceIds", MAX_DATA_SOURCES, errors);
1824
+ const paths = dataSourceIds.map((id) => path(id));
1825
+ const results = [];
1826
+ for (const [index, dataSourceId] of dataSourceIds.entries()) {
1827
+ try {
1828
+ expectEmpty(
1829
+ await transport.request(paths[index], { method: "DELETE" }),
1830
+ "Delete Data Source response",
1831
+ errors
1832
+ );
1833
+ results.push({ index, success: true, dataSourceId, errorCode: null, message: null });
1834
+ } catch (error) {
1835
+ results.push(bulkFailure(index, dataSourceId, error));
1836
+ }
1837
+ }
1838
+ return bulkResult(results);
1839
+ }
1840
+ };
1841
+ }
1842
+
1843
+ // src/modules/entities.ts
1844
+ var DefaultEntitiesModule = class {
1845
+ constructor(transport, errors) {
1846
+ this.transport = transport;
1847
+ this.errors = errors;
1848
+ }
1849
+ tables = /* @__PURE__ */ new Map();
1850
+ getTable(tableName) {
1851
+ if (!this.tables.has(tableName)) {
1852
+ this.tables.set(tableName, this.createTable(tableName));
1853
+ }
1854
+ return this.tables.get(tableName);
1855
+ }
1856
+ createTable(tableName) {
1857
+ const basePath = `/api/v1/tables/${encodePathSegment(tableName, "tableName", this.errors)}/records`;
1858
+ return {
1859
+ list: async (sortOrOptions, limit, skip, fields) => {
1860
+ const options = typeof sortOrOptions === "object" ? sortOrOptions : void 0;
1861
+ const params = {
1862
+ sort: options?.sort ?? (typeof sortOrOptions === "string" ? sortOrOptions : void 0),
1863
+ limit: options?.limit ?? limit,
1864
+ skip: options?.skip ?? skip,
1865
+ fields: (options?.fields ?? fields)?.join(",")
1866
+ };
1867
+ return expectEntityListResponse(
1868
+ await this.transport.request(basePath, { method: "GET", params }),
1869
+ "Entity list response",
1870
+ this.errors
1871
+ );
1872
+ },
1873
+ filter: async (query, sort, limit, skip, fields) => {
1874
+ return expectEntityListResponse(
1875
+ await this.transport.request(basePath, {
1876
+ method: "GET",
1877
+ params: {
1878
+ q: JSON.stringify(query),
1879
+ sort,
1880
+ limit,
1881
+ skip,
1882
+ fields: fields?.join(",")
1883
+ }
1884
+ }),
1885
+ "Entity list response",
1886
+ this.errors
1887
+ );
1888
+ },
1889
+ get: async (id) => expectObject(
1890
+ await this.transport.request(
1891
+ `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
1892
+ { method: "GET" }
1893
+ ),
1894
+ "Entity response",
1895
+ this.errors
1896
+ ),
1897
+ create: async (data) => expectObject(
1898
+ await this.transport.request(basePath, { method: "POST", body: data }),
1899
+ "Created entity response",
1900
+ this.errors
1901
+ ),
1902
+ bulkCreate: async (data) => expectObjectArray(
1903
+ await this.transport.request(`${basePath}/bulk`, {
1904
+ method: "POST",
1905
+ body: data
1906
+ }),
1907
+ "Bulk create response",
1908
+ this.errors
1909
+ ),
1910
+ update: async (id, data) => expectObject(
1911
+ await this.transport.request(
1912
+ `${basePath}/${encodePathSegment(id, "id", this.errors)}`,
1913
+ { method: "PUT", body: data }
1914
+ ),
1915
+ "Updated entity response",
1916
+ this.errors
1917
+ ),
1918
+ delete: (id) => this.transport.request(`${basePath}/${encodePathSegment(id, "id", this.errors)}`, {
1919
+ method: "DELETE"
1920
+ }).then((response) => expectEmpty(response, "Delete entity response", this.errors)),
1921
+ deleteMany: async (query) => {
1922
+ if (Object.keys(query).length === 0) {
1923
+ configurationError("query must not be empty for deleteMany", this.errors);
1924
+ }
1925
+ const response = expectObject(
1926
+ await this.transport.request(basePath, {
1927
+ method: "DELETE",
1928
+ params: { q: JSON.stringify(query) }
1929
+ }),
1930
+ "Delete many response",
1931
+ this.errors
1932
+ );
1933
+ if (!Number.isInteger(response.deleted)) {
1934
+ return invalidResponse(
1935
+ "Delete many response must include an integer deleted count",
1936
+ this.errors
1937
+ );
1938
+ }
1939
+ return { deleted: response.deleted };
1940
+ }
1941
+ };
1942
+ }
1943
+ };
1944
+ function expectEntityListResponse(value, context, errors) {
1945
+ const response = expectObject(value, context, errors);
1946
+ expectObjectArray(response.data, `${context} data`, errors);
1947
+ if (!Number.isInteger(response.limit))
1948
+ invalidResponse(`${context} has an invalid limit field`, errors);
1949
+ if (!Number.isInteger(response.skip))
1950
+ invalidResponse(`${context} has an invalid skip field`, errors);
1951
+ if (!Number.isInteger(response.total))
1952
+ invalidResponse(`${context} has an invalid total field`, errors);
1953
+ if (typeof response.hasMore !== "boolean") {
1954
+ invalidResponse(`${context} has an invalid hasMore field`, errors);
1955
+ }
1956
+ return response;
1957
+ }
1958
+ function createEntitiesModule(transport, errors = defaultSdkCoreErrorFactory) {
1959
+ const instance = new DefaultEntitiesModule(transport, errors);
1960
+ return new Proxy(instance, {
1961
+ get(target, property, receiver) {
1962
+ if (typeof property !== "string" || property in target) {
1963
+ return Reflect.get(target, property, receiver);
1964
+ }
1965
+ return target.getTable(property);
1966
+ }
1967
+ });
1968
+ }
1969
+
1970
+ // src/modules/functions.ts
1971
+ var DefaultFunctionsModule = class {
1972
+ constructor(transport, errors, options) {
1973
+ this.transport = transport;
1974
+ this.errors = errors;
1975
+ this.options = options;
1976
+ }
1977
+ execute(id, input) {
1978
+ return this.executeWithType(id, this.options.executeInvocationType, input);
1979
+ }
1980
+ executeAsync(id, input) {
1981
+ return this.executeWithType(id, "async", input);
1982
+ }
1983
+ getExecution(id) {
1984
+ return this.transport.request(
1985
+ `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}`,
1986
+ { method: "GET" }
1987
+ ).then(
1988
+ (response) => expectFunctionExecution(response, "Function execution response", this.errors)
1989
+ );
1990
+ }
1991
+ cancelExecution(id) {
1992
+ return this.transport.request(
1993
+ `/api/v1/executions/${encodePathSegment(id, "execution id", this.errors)}/cancel`,
1994
+ { method: "POST" }
1995
+ ).then((response) => expectEmpty(response, "Cancel execution response", this.errors));
1996
+ }
1997
+ executeWithType(id, invocationType, input) {
1998
+ const request = {
1999
+ method: "POST",
2000
+ ...input !== void 0 || this.options.emptyInput !== "omit-body" ? { body: { input: input ?? {} } } : {},
2001
+ ...invocationType === void 0 ? {} : { headers: { "X-Invocation-Type": invocationType } }
2002
+ };
2003
+ return this.transport.request(
2004
+ `/api/v1/functions/${encodePathSegment(id, "function id", this.errors)}/execute`,
2005
+ request
2006
+ ).then(
2007
+ (response) => expectFunctionExecution(response, "Function execution response", this.errors)
2008
+ );
2009
+ }
2010
+ };
2011
+ function createFunctionsModule(transport, options = {}, errors = defaultSdkCoreErrorFactory) {
2012
+ return new DefaultFunctionsModule(transport, errors, options);
2013
+ }
2014
+
2015
+ // src/modules/functionsAdmin.ts
2016
+ var MAX_FUNCTIONS = 100;
2017
+ var COMPOSED_SCHEDULE_FIELDS = ["cronExpression", "cronInputJson", "cronEnabled"];
2018
+ function rejectBulkScheduleFields(value, operation, errors) {
2019
+ if (typeof value !== "object" || value === null) return;
2020
+ const field = COMPOSED_SCHEDULE_FIELDS.find((candidate) => Object.hasOwn(value, candidate));
2021
+ if (field) {
2022
+ configurationError(
2023
+ `functionsAdmin.${operation} does not support ${field}; composed scheduling is supported only by single-Function create and patch`,
2024
+ errors
2025
+ );
2026
+ }
2027
+ }
2028
+ function bulkPatchUpdate(value) {
2029
+ return typeof value === "object" && value !== null && Object.hasOwn(value, "update") ? value.update : void 0;
2030
+ }
2031
+ function createFunctionsAdminModule(transport, errors = defaultSdkCoreErrorFactory) {
2032
+ const functionPath = (id) => `/api/v1/functions/${encodePathSegment(id, "function id", errors)}`;
2033
+ const pageParams = (options = {}) => ({
2034
+ page: options.page,
2035
+ size: options.size,
2036
+ sort: options.sort
2037
+ });
2038
+ return {
2039
+ async list(options = {}) {
2040
+ return expectPage(
2041
+ await transport.request("/api/v1/functions", {
2042
+ method: "GET",
2043
+ params: { ...pageParams(options), search: options.search }
2044
+ }),
2045
+ "Function page response",
2046
+ errors,
2047
+ expectFunctionSummary
2048
+ );
2049
+ },
2050
+ async get(id) {
2051
+ return expectFunctionDefinition(
2052
+ await transport.request(functionPath(id), { method: "GET" }),
2053
+ "Function response",
2054
+ errors
2055
+ );
2056
+ },
2057
+ async create(input) {
2058
+ return expectFunctionDefinition(
2059
+ await transport.request("/api/v1/functions", { method: "POST", body: input }),
2060
+ "Create Function response",
2061
+ errors
2062
+ );
2063
+ },
2064
+ async patch(id, input) {
2065
+ return expectFunctionDefinition(
2066
+ await transport.request(functionPath(id), { method: "PATCH", body: input }),
2067
+ "Patch Function response",
2068
+ errors
2069
+ );
2070
+ },
2071
+ async delete(id) {
2072
+ expectEmpty(
2073
+ await transport.request(functionPath(id), { method: "DELETE" }),
2074
+ "Delete Function response",
2075
+ errors
2076
+ );
2077
+ },
2078
+ async bulkCreate(functions) {
2079
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2080
+ functions.forEach((input) => rejectBulkScheduleFields(input, "bulkCreate", errors));
2081
+ return expectFunctionDefinitions(
2082
+ await transport.request("/api/v1/functions/bulk", {
2083
+ method: "POST",
2084
+ body: { functions }
2085
+ }),
2086
+ "Function bulk create response",
2087
+ errors
2088
+ );
2089
+ },
2090
+ async bulkUpdate(functions) {
2091
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2092
+ return expectFunctionDefinitions(
2093
+ await transport.request("/api/v1/functions/bulk", {
2094
+ method: "PUT",
2095
+ body: { functions }
2096
+ }),
2097
+ "Function bulk update response",
2098
+ errors
2099
+ );
2100
+ },
2101
+ async bulkPatch(functions) {
2102
+ requireBatchSize(functions, "functions", MAX_FUNCTIONS, errors);
2103
+ functions.forEach(
2104
+ (item) => rejectBulkScheduleFields(bulkPatchUpdate(item), "bulkPatch", errors)
2105
+ );
2106
+ return expectFunctionDefinitions(
2107
+ await transport.request("/api/v1/functions/bulk", {
2108
+ method: "PATCH",
2109
+ body: { functions }
2110
+ }),
2111
+ "Function bulk patch response",
2112
+ errors
2113
+ );
2114
+ },
2115
+ // POST, not DELETE: the selector travels in a body, and some proxies drop a DELETE body.
2116
+ async bulkDelete(selector) {
2117
+ const body = selectorBody(selector, errors);
2118
+ return expectFunctionBulkDeleteResult(
2119
+ await transport.request("/api/v1/functions/bulk-delete", {
2120
+ method: "POST",
2121
+ body
2122
+ }),
2123
+ "Function bulk delete response",
2124
+ errors
2125
+ );
2126
+ },
2127
+ async publish(id) {
2128
+ return expectFunctionDefinition(
2129
+ await transport.request(`${functionPath(id)}/publish`, { method: "POST" }),
2130
+ "Publish Function response",
2131
+ errors
2132
+ );
2133
+ },
2134
+ async rollback(id, versionId) {
2135
+ return expectFunctionDefinition(
2136
+ await transport.request(`${functionPath(id)}/rollback`, {
2137
+ method: "POST",
2138
+ body: { targetVersionId: versionId }
2139
+ }),
2140
+ "Rollback Function response",
2141
+ errors
2142
+ );
2143
+ },
2144
+ async listVersions(id, options = {}) {
2145
+ return expectPage(
2146
+ await transport.request(`${functionPath(id)}/versions`, {
2147
+ method: "GET",
2148
+ params: pageParams(options)
2149
+ }),
2150
+ "Function version page response",
2151
+ errors,
2152
+ expectFunctionVersionResponse
2153
+ );
2154
+ },
2155
+ async setVisibility(id, visibility) {
2156
+ return expectFunctionDefinition(
2157
+ await transport.request(`${functionPath(id)}/visibility`, {
2158
+ method: "PATCH",
2159
+ body: { visibility }
2160
+ }),
2161
+ "Function visibility response",
2162
+ errors
2163
+ );
2164
+ },
2165
+ async listExecutions(id, options = {}) {
2166
+ return expectPage(
2167
+ await transport.request(`${functionPath(id)}/executions`, {
2168
+ method: "GET",
2169
+ params: pageParams(options)
2170
+ }),
2171
+ "Function execution page response",
2172
+ errors,
2173
+ expectFunctionExecution
2174
+ );
2175
+ },
2176
+ async getExecution(functionId, executionId) {
2177
+ return expectFunctionExecution(
2178
+ await transport.request(
2179
+ `${functionPath(functionId)}/executions/${encodePathSegment(
2180
+ executionId,
2181
+ "execution id",
2182
+ errors
2183
+ )}`,
2184
+ { method: "GET" }
2185
+ ),
2186
+ "Function execution response",
2187
+ errors
2188
+ );
2189
+ },
2190
+ async listSecrets(id) {
2191
+ return expectFunctionSecrets(
2192
+ await transport.request(`${functionPath(id)}/secrets`, { method: "GET" }),
2193
+ "Function secrets response",
2194
+ errors
2195
+ );
2196
+ },
2197
+ async createSecret(id, name, value) {
2198
+ expectEmpty(
2199
+ await transport.request(`${functionPath(id)}/secrets`, {
2200
+ method: "POST",
2201
+ body: { name, value }
2202
+ }),
2203
+ "Create Function secret response",
2204
+ errors
2205
+ );
2206
+ },
2207
+ async deleteSecret(id, name) {
2208
+ expectEmpty(
2209
+ await transport.request(
2210
+ `${functionPath(id)}/secrets/${encodePathSegment(name, "secret name", errors)}`,
2211
+ { method: "DELETE" }
2212
+ ),
2213
+ "Delete Function secret response",
2214
+ errors
2215
+ );
2216
+ }
2217
+ };
2218
+ }
2219
+ function selectorBody(selector, errors) {
2220
+ const hasIds = selector.ids !== void 0;
2221
+ if (hasIds === (selector.allInApp === true)) {
2222
+ configurationError("Provide either ids or allInApp, not both", errors);
2223
+ }
2224
+ if (selector.ids !== void 0) {
2225
+ requireBatchSize(selector.ids, "ids", MAX_FUNCTIONS, errors);
2226
+ return { ids: selector.ids };
2227
+ }
2228
+ return { allInApp: true };
2229
+ }
2230
+
2231
+ // src/modules/imports.ts
2232
+ function createImportsModule(transport, errors = defaultSdkCoreErrorFactory) {
2233
+ const path = (id) => `/api/v1/data-imports/${encodePathSegment(id, "import id", errors)}`;
2234
+ const pageParams = (options = {}) => ({
2235
+ page: options.page,
2236
+ size: options.size,
2237
+ sort: options.sort
2238
+ });
2239
+ return {
2240
+ async list(options = {}) {
2241
+ return expectPage(
2242
+ await transport.request("/api/v1/data-imports", {
2243
+ method: "GET",
2244
+ params: pageParams(options)
2245
+ }),
2246
+ "Import page response",
2247
+ errors,
2248
+ expectImportDefinition
2249
+ );
2250
+ },
2251
+ async get(id) {
2252
+ return expectImportDefinition(
2253
+ await transport.request(path(id), { method: "GET" }),
2254
+ "Import response",
2255
+ errors
2256
+ );
2257
+ },
2258
+ async create(input) {
2259
+ return expectImportDefinition(
2260
+ await transport.request("/api/v1/data-imports", { method: "POST", body: input }),
2261
+ "Create import response",
2262
+ errors
2263
+ );
2264
+ },
2265
+ async update(id, input) {
2266
+ return expectImportDefinition(
2267
+ await transport.request(path(id), { method: "PUT", body: input }),
2268
+ "Update import response",
2269
+ errors
2270
+ );
2271
+ },
2272
+ async delete(id) {
2273
+ expectEmpty(
2274
+ await transport.request(path(id), { method: "DELETE" }),
2275
+ "Delete import response",
2276
+ errors
2277
+ );
2278
+ },
2279
+ async execute(id) {
2280
+ return expectImportExecution(
2281
+ await transport.request(`${path(id)}/execute`, { method: "POST" }),
2282
+ "Import execution response",
2283
+ errors
2284
+ );
2285
+ },
2286
+ async listExecutions(options) {
2287
+ return expectPage(
2288
+ await transport.request("/api/v1/data-imports/executions", {
2289
+ method: "GET",
2290
+ params: {
2291
+ definitionId: options.definitionId,
2292
+ page: options.page,
2293
+ size: options.size,
2294
+ sort: options.sort ?? "queuedAt,desc"
2295
+ }
2296
+ }),
2297
+ "Import execution page response",
2298
+ errors,
2299
+ expectImportExecution
2300
+ );
2301
+ },
2302
+ async cancelExecution(executionId) {
2303
+ return expectImportExecution(
2304
+ await transport.request(
2305
+ `/api/v1/data-imports/executions/${encodePathSegment(executionId, "execution id", errors)}/cancel`,
2306
+ { method: "POST" }
2307
+ ),
2308
+ "Cancel import execution response",
2309
+ errors
2310
+ );
2311
+ }
2312
+ };
2313
+ }
2314
+
2315
+ // src/modules/integration.ts
328
2316
  function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory) {
329
2317
  return {
330
2318
  async executeResource(resourceId, params = {}) {
@@ -337,13 +2325,356 @@ function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory)
337
2325
  errors
338
2326
  );
339
2327
  },
340
- async execute(configId, request) {
341
- return expectProxyResult(
2328
+ async execute(configId, request) {
2329
+ return expectProxyResult(
2330
+ await transport.request(
2331
+ `/api/v1/proxy/template-configs/${encodePathSegment(configId, "config id", errors)}/execute`,
2332
+ { method: "POST", body: { ...request, source: "SDK" } }
2333
+ ),
2334
+ "Integration proxy response",
2335
+ errors
2336
+ );
2337
+ },
2338
+ async executeByAlias(alias, request) {
2339
+ return expectProxyResult(
2340
+ await transport.request(
2341
+ `/api/v1/proxy/template-configs/by-alias/${encodePathSegment(alias, "alias", errors)}/execute`,
2342
+ { method: "POST", body: { ...request, source: "SDK" } }
2343
+ ),
2344
+ "Integration proxy response",
2345
+ errors
2346
+ );
2347
+ }
2348
+ };
2349
+ }
2350
+
2351
+ // src/modules/integrationAdmin.ts
2352
+ var MAX_CONFIGS = 100;
2353
+ function createIntegrationAdminModule(transport, errors = defaultSdkCoreErrorFactory) {
2354
+ const path = (id) => `/api/v1/template-configs/${encodePathSegment(id, "config id", errors)}`;
2355
+ return {
2356
+ async create(input) {
2357
+ return expectTemplateConfig(
2358
+ await transport.request("/api/v1/template-configs", {
2359
+ method: "POST",
2360
+ body: input
2361
+ }),
2362
+ "Create integration config response",
2363
+ errors
2364
+ );
2365
+ },
2366
+ async update(id, input) {
2367
+ return expectTemplateConfig(
2368
+ await transport.request(path(id), { method: "PUT", body: input }),
2369
+ "Update integration config response",
2370
+ errors
2371
+ );
2372
+ },
2373
+ async delete(id) {
2374
+ expectEmpty(
2375
+ await transport.request(path(id), { method: "DELETE" }),
2376
+ "Delete integration config response",
2377
+ errors
2378
+ );
2379
+ },
2380
+ async bulkCreate(configs) {
2381
+ requireBatchSize(configs, "configs", MAX_CONFIGS, errors);
2382
+ return expectTemplateConfigBulkResult(
2383
+ await transport.request("/api/v1/template-configs/bulk", {
2384
+ method: "POST",
2385
+ body: { configs }
2386
+ }),
2387
+ "Template config bulk create response",
2388
+ errors
2389
+ );
2390
+ },
2391
+ async bulkUpdate(configs) {
2392
+ requireBatchSize(configs, "configs", MAX_CONFIGS, errors);
2393
+ return expectTemplateConfigBulkResult(
2394
+ await transport.request("/api/v1/template-configs/bulk", {
2395
+ method: "PUT",
2396
+ body: { configs }
2397
+ }),
2398
+ "Template config bulk update response",
2399
+ errors
2400
+ );
2401
+ },
2402
+ // POST, not DELETE: the id list travels in a body, and some proxies drop a DELETE body.
2403
+ async bulkDelete(configIds) {
2404
+ requireBatchSize(configIds, "configIds", MAX_CONFIGS, errors);
2405
+ return expectTemplateConfigBulkResult(
2406
+ await transport.request("/api/v1/template-configs/bulk-delete", {
2407
+ method: "POST",
2408
+ body: { configIds }
2409
+ }),
2410
+ "Template config bulk delete response",
2411
+ errors
2412
+ );
2413
+ },
2414
+ async testCredentials(request) {
2415
+ return expectConnectionTestResult(
2416
+ await transport.request("/api/v1/template-configs/test", {
2417
+ method: "POST",
2418
+ body: request
2419
+ }),
2420
+ "Integration credentials test response",
2421
+ errors
2422
+ );
2423
+ },
2424
+ async testConfig(configId) {
2425
+ return expectConnectionTestResult(
2426
+ await transport.request(`${path(configId)}/test`, { method: "POST" }),
2427
+ "Integration config test response",
2428
+ errors
2429
+ );
2430
+ },
2431
+ async list(options = {}) {
2432
+ const params = {
2433
+ page: options.page,
2434
+ size: options.size,
2435
+ sort: options.sort
2436
+ };
2437
+ return expectTemplateConfigPage(
2438
+ await transport.request("/api/v1/template-configs", { method: "GET", params }),
2439
+ "Template config page response",
2440
+ errors
2441
+ );
2442
+ },
2443
+ async listExecutions(configId, options = {}) {
2444
+ return expectLegacyPage(
2445
+ await transport.request(`${path(configId)}/executions`, {
2446
+ method: "GET",
2447
+ params: {
2448
+ page: options.page,
2449
+ size: options.size,
2450
+ sort: options.sort ?? "createdAt,desc"
2451
+ }
2452
+ }),
2453
+ "Integration execution page response",
2454
+ errors,
2455
+ expectIntegrationExecution
2456
+ );
2457
+ },
2458
+ async getExecution(configId, executionId) {
2459
+ return expectIntegrationExecution(
2460
+ await transport.request(
2461
+ `${path(configId)}/executions/${encodePathSegment(executionId, "execution id", errors)}`,
2462
+ { method: "GET" }
2463
+ ),
2464
+ "Integration execution response",
2465
+ errors
2466
+ );
2467
+ }
2468
+ };
2469
+ }
2470
+
2471
+ // src/modules/integrationResources.ts
2472
+ function createIntegrationResourcesModule(transport, errors = defaultSdkCoreErrorFactory) {
2473
+ const path = (id) => `/api/v1/integration-resources/${encodePathSegment(id, "resource id", errors)}`;
2474
+ return {
2475
+ async list(options = {}) {
2476
+ const params = {
2477
+ page: options.page,
2478
+ size: options.size,
2479
+ sort: options.sort
2480
+ };
2481
+ return expectLegacyPage(
2482
+ await transport.request("/api/v1/integration-resources", {
2483
+ method: "GET",
2484
+ params
2485
+ }),
2486
+ "Integration resource page response",
2487
+ errors,
2488
+ expectIntegrationResourceSummary
2489
+ );
2490
+ },
2491
+ async get(id) {
2492
+ return expectIntegrationResource(
2493
+ await transport.request(path(id), { method: "GET" }),
2494
+ "Integration resource response",
2495
+ errors
2496
+ );
2497
+ },
2498
+ async create(input) {
2499
+ return expectIntegrationResource(
2500
+ await transport.request("/api/v1/integration-resources", {
2501
+ method: "POST",
2502
+ body: input
2503
+ }),
2504
+ "Create integration resource response",
2505
+ errors
2506
+ );
2507
+ },
2508
+ async update(id, input) {
2509
+ return expectIntegrationResource(
2510
+ await transport.request(path(id), { method: "PUT", body: input }),
2511
+ "Update integration resource response",
2512
+ errors
2513
+ );
2514
+ },
2515
+ async delete(id) {
2516
+ expectEmpty(
2517
+ await transport.request(path(id), { method: "DELETE" }),
2518
+ "Delete integration resource response",
2519
+ errors
2520
+ );
2521
+ }
2522
+ };
2523
+ }
2524
+
2525
+ // src/modules/integrationTemplates.ts
2526
+ function createIntegrationTemplatesModule(transport, errors = defaultSdkCoreErrorFactory) {
2527
+ const params = (options = {}, sort) => ({
2528
+ page: options.page,
2529
+ size: options.size ?? 20,
2530
+ sort: options.sort ?? sort
2531
+ });
2532
+ return {
2533
+ async list(options = {}) {
2534
+ return expectLegacyPage(
2535
+ await transport.request("/api/v1/templates", {
2536
+ method: "GET",
2537
+ params: params(options, "name")
2538
+ }),
2539
+ "Integration template page response",
2540
+ errors,
2541
+ expectIntegrationTemplateSummary
2542
+ );
2543
+ },
2544
+ async get(id) {
2545
+ return expectIntegrationTemplate(
2546
+ await transport.request(
2547
+ `/api/v1/templates/${encodePathSegment(id, "template id", errors)}`,
2548
+ { method: "GET" }
2549
+ ),
2550
+ "Integration template response",
2551
+ errors
2552
+ );
2553
+ },
2554
+ async listConfigs(options = {}) {
2555
+ return expectLegacyPage(
2556
+ await transport.request("/api/v1/template-configs", {
2557
+ method: "GET",
2558
+ params: params(options, "alias")
2559
+ }),
2560
+ "Integration config page response",
2561
+ errors,
2562
+ expectTemplateConfigSummary
2563
+ );
2564
+ },
2565
+ async getConfig(id) {
2566
+ return expectTemplateConfig(
2567
+ await transport.request(
2568
+ `/api/v1/template-configs/${encodePathSegment(id, "config id", errors)}`,
2569
+ { method: "GET" }
2570
+ ),
2571
+ "Integration config response",
2572
+ errors
2573
+ );
2574
+ }
2575
+ };
2576
+ }
2577
+
2578
+ // src/modules/members.ts
2579
+ var MAX_APP_USERS = 100;
2580
+ function createMembersModule(transport, errors = defaultSdkCoreErrorFactory) {
2581
+ const path = (appId) => `/api/v1/apps/${encodePathSegment(appId, "app id", errors)}/users`;
2582
+ return {
2583
+ async list() {
2584
+ return expectAppMembers(
2585
+ await transport.request("/api/v1/members/current-app", { method: "GET" }),
2586
+ "App members response",
2587
+ errors
2588
+ );
2589
+ },
2590
+ async invite(appId, input) {
2591
+ expectEmpty(
2592
+ await transport.request(path(appId), { method: "POST", body: input }),
2593
+ "Invite app user response",
2594
+ errors
2595
+ );
2596
+ },
2597
+ async unsubscribe(appId, userId) {
2598
+ expectEmpty(
342
2599
  await transport.request(
343
- `/api/v1/proxy/template-configs/${encodePathSegment(configId, "config id", errors)}/execute`,
344
- { method: "POST", body: { ...request, source: "SDK" } }
2600
+ `${path(appId)}/${encodePathSegment(userId, "user id", errors)}`,
2601
+ { method: "DELETE" }
345
2602
  ),
346
- "Integration proxy response",
2603
+ "Unsubscribe app user response",
2604
+ errors
2605
+ );
2606
+ },
2607
+ async bulkInvite(appId, users) {
2608
+ requireBatchSize(users, "users", MAX_APP_USERS, errors);
2609
+ expectEmpty(
2610
+ await transport.request(`${path(appId)}/bulk`, {
2611
+ method: "POST",
2612
+ body: { users }
2613
+ }),
2614
+ "Bulk invite app users response",
2615
+ errors
2616
+ );
2617
+ },
2618
+ async bulkUnsubscribe(appId, userIds) {
2619
+ requireBatchSize(userIds, "userIds", MAX_APP_USERS, errors);
2620
+ return expectBulkUnsubscribeResult(
2621
+ await transport.request(`${path(appId)}/bulk-unsubscribe`, {
2622
+ method: "POST",
2623
+ body: { userIds }
2624
+ }),
2625
+ "Bulk unsubscribe app users response",
2626
+ errors
2627
+ );
2628
+ }
2629
+ };
2630
+ }
2631
+
2632
+ // src/modules/messenger.ts
2633
+ function createMessengerModule(transport, errors = defaultSdkCoreErrorFactory) {
2634
+ return {
2635
+ async notify(content) {
2636
+ return expectMessageAccepted(
2637
+ await transport.request("/api/v1/messages/notify", {
2638
+ method: "POST",
2639
+ body: { content }
2640
+ }),
2641
+ "Notify user response",
2642
+ errors
2643
+ );
2644
+ }
2645
+ };
2646
+ }
2647
+
2648
+ // src/modules/publicFunctions.ts
2649
+ function createPublicFunctionsModule(transport, errors = defaultSdkCoreErrorFactory) {
2650
+ const execute = async (id, input, mode) => {
2651
+ if (!transport) {
2652
+ configurationError(
2653
+ "A separate publicFunctions transport is required so anonymous requests do not inherit authorization headers",
2654
+ errors
2655
+ );
2656
+ }
2657
+ return transport.request(
2658
+ `/public/v1/functions/${encodePathSegment(id, "function id", errors)}/execute`,
2659
+ {
2660
+ method: "POST",
2661
+ headers: { "X-Invocation-Type": mode },
2662
+ body: { input: input ?? {} }
2663
+ }
2664
+ );
2665
+ };
2666
+ return {
2667
+ async execute(id, input) {
2668
+ return expectPublicFunctionResult(
2669
+ await execute(id, input, "sync"),
2670
+ "Public Function execution response",
2671
+ errors
2672
+ );
2673
+ },
2674
+ async executeAsync(id, input) {
2675
+ return expectPublicFunctionAsyncResult(
2676
+ await execute(id, input, "async"),
2677
+ "Public async Function execution response",
347
2678
  errors
348
2679
  );
349
2680
  }
@@ -351,22 +2682,15 @@ function createIntegrationModule(transport, errors = defaultSdkCoreErrorFactory)
351
2682
  }
352
2683
 
353
2684
  // src/modules/queries.ts
354
- function createQueriesModule(transport, getDataSourceId, errors = defaultSdkCoreErrorFactory) {
2685
+ function createQueriesModule(transport, errors = defaultSdkCoreErrorFactory) {
355
2686
  return {
356
2687
  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
2688
  return expectQueryResult(
365
2689
  await transport.request(
366
2690
  `/api/v1/custom-queries/${encodePathSegment(id, "query id", errors)}/execute`,
367
2691
  {
368
2692
  method: "POST",
369
- body: { dataSourceId, parameters }
2693
+ body: { parameters }
370
2694
  }
371
2695
  ),
372
2696
  "Query execution response",
@@ -376,29 +2700,974 @@ function createQueriesModule(transport, getDataSourceId, errors = defaultSdkCore
376
2700
  };
377
2701
  }
378
2702
 
2703
+ // src/modules/schema.ts
2704
+ function createSchemaModule(transport, errors = defaultSdkCoreErrorFactory) {
2705
+ const tablePath = (name) => `/api/v1/tables/${encodePathSegment(name, "table name", errors)}`;
2706
+ const list = async (options = {}) => {
2707
+ const params = {
2708
+ scope: options.scope,
2709
+ includeColumns: options.includeColumns
2710
+ };
2711
+ return expectSchemaTables(
2712
+ await transport.request("/api/v1/tables", { method: "GET", params }),
2713
+ "Schema tables response",
2714
+ errors
2715
+ );
2716
+ };
2717
+ return {
2718
+ async createTable(tableName, columns) {
2719
+ expectEmpty(
2720
+ await transport.request("/api/v1/tables", {
2721
+ method: "POST",
2722
+ body: { tableName, columns }
2723
+ }),
2724
+ "Create table response",
2725
+ errors
2726
+ );
2727
+ },
2728
+ listTables: list,
2729
+ listAppTables(options = {}) {
2730
+ return list({
2731
+ scope: "APP",
2732
+ ...options.includeColumns === void 0 ? {} : { includeColumns: options.includeColumns }
2733
+ });
2734
+ },
2735
+ async getTable(tableName) {
2736
+ return expectTableDefinition(
2737
+ await transport.request(tablePath(tableName), { method: "GET" }),
2738
+ "Table details response",
2739
+ errors
2740
+ );
2741
+ },
2742
+ async dropTable(tableName) {
2743
+ expectEmpty(
2744
+ await transport.request(tablePath(tableName), { method: "DELETE" }),
2745
+ "Drop table response",
2746
+ errors
2747
+ );
2748
+ },
2749
+ async truncateTable(tableName) {
2750
+ expectEmpty(
2751
+ await transport.request(`${tablePath(tableName)}/truncate`, { method: "POST" }),
2752
+ "Truncate table response",
2753
+ errors
2754
+ );
2755
+ },
2756
+ async addColumn(tableName, column) {
2757
+ expectEmpty(
2758
+ await transport.request(`${tablePath(tableName)}/columns`, {
2759
+ method: "POST",
2760
+ body: column
2761
+ }),
2762
+ "Add column response",
2763
+ errors
2764
+ );
2765
+ },
2766
+ async dropColumn(tableName, columnName) {
2767
+ expectEmpty(
2768
+ await transport.request(
2769
+ `${tablePath(tableName)}/columns/${encodePathSegment(columnName, "column name", errors)}`,
2770
+ { method: "DELETE" }
2771
+ ),
2772
+ "Drop column response",
2773
+ errors
2774
+ );
2775
+ }
2776
+ };
2777
+ }
2778
+
2779
+ // src/modules/sql.ts
2780
+ var MAX_STATEMENTS = 20;
2781
+ function createSqlModule(transport, errors = defaultSdkCoreErrorFactory) {
2782
+ return {
2783
+ async executeQuery(sql, parameters = {}) {
2784
+ return expectQueryResult(
2785
+ await transport.request("/api/v1/sql/execute", {
2786
+ method: "POST",
2787
+ body: { sql, parameters }
2788
+ }),
2789
+ "SQL execution response",
2790
+ errors
2791
+ );
2792
+ },
2793
+ async executeDdl(statements) {
2794
+ requireBatchSize(statements, "statements", MAX_STATEMENTS, errors);
2795
+ return expectBatchExecution(
2796
+ await transport.request("/api/v1/sql/ddl/execute", {
2797
+ method: "POST",
2798
+ body: { statements }
2799
+ }),
2800
+ "DDL batch response",
2801
+ errors
2802
+ );
2803
+ },
2804
+ async executeDml(statements) {
2805
+ requireBatchSize(statements, "statements", MAX_STATEMENTS, errors);
2806
+ return expectBatchExecution(
2807
+ await transport.request("/api/v1/sql/dml/execute", {
2808
+ method: "POST",
2809
+ body: { statements }
2810
+ }),
2811
+ "DML batch response",
2812
+ errors
2813
+ );
2814
+ },
2815
+ async listTables(options = {}) {
2816
+ const params = {
2817
+ scope: options.scope,
2818
+ includeColumns: options.includeColumns
2819
+ };
2820
+ return expectSchemaTables(
2821
+ await transport.request("/api/v1/tables", { method: "GET", params }),
2822
+ "Schema tables response",
2823
+ errors
2824
+ );
2825
+ }
2826
+ };
2827
+ }
2828
+
2829
+ // src/modules/workflows.ts
2830
+ function createWorkflowsModule(transport, errors = defaultSdkCoreErrorFactory) {
2831
+ const path = (id) => `/api/v1/workflows/${encodePathSegment(id, "workflow id", errors)}`;
2832
+ const params = (options = {}) => ({
2833
+ page: options.page,
2834
+ size: options.size,
2835
+ sort: options.sort
2836
+ });
2837
+ const executionPath = (workflowId, executionId) => `${path(workflowId)}/executions${executionId === void 0 ? "" : `/${encodePathSegment(executionId, "workflow execution id", errors)}`}`;
2838
+ return {
2839
+ async list(options = {}) {
2840
+ return expectPage(
2841
+ await transport.request("/api/v1/workflows", {
2842
+ method: "GET",
2843
+ params: params(options)
2844
+ }),
2845
+ "Workflow page response",
2846
+ errors,
2847
+ expectWorkflowSummary
2848
+ );
2849
+ },
2850
+ async get(id) {
2851
+ return expectWorkflowDefinition(
2852
+ await transport.request(path(id), { method: "GET" }),
2853
+ "Workflow response",
2854
+ errors
2855
+ );
2856
+ },
2857
+ async create(input) {
2858
+ return expectWorkflowDefinition(
2859
+ await transport.request("/api/v1/workflows", {
2860
+ method: "POST",
2861
+ body: input
2862
+ }),
2863
+ "Create workflow response",
2864
+ errors
2865
+ );
2866
+ },
2867
+ async update(id, input) {
2868
+ return expectWorkflowDefinition(
2869
+ await transport.request(path(id), { method: "PUT", body: input }),
2870
+ "Update workflow response",
2871
+ errors
2872
+ );
2873
+ },
2874
+ async delete(id) {
2875
+ expectEmpty(
2876
+ await transport.request(path(id), { method: "DELETE" }),
2877
+ "Delete workflow response",
2878
+ errors
2879
+ );
2880
+ },
2881
+ async execute(id, input = {}) {
2882
+ return expectWorkflowExecution(
2883
+ await transport.request(`${path(id)}/execute`, {
2884
+ method: "POST",
2885
+ body: { input }
2886
+ }),
2887
+ "Workflow execution response",
2888
+ errors
2889
+ );
2890
+ },
2891
+ async listExecutions(workflowId, options = {}) {
2892
+ return expectPage(
2893
+ await transport.request(executionPath(workflowId), {
2894
+ method: "GET",
2895
+ params: params(options)
2896
+ }),
2897
+ "Workflow execution page response",
2898
+ errors,
2899
+ expectWorkflowExecution
2900
+ );
2901
+ },
2902
+ async getExecution(workflowId, executionId) {
2903
+ return expectWorkflowExecution(
2904
+ await transport.request(executionPath(workflowId, executionId), { method: "GET" }),
2905
+ "Workflow execution response",
2906
+ errors
2907
+ );
2908
+ },
2909
+ async cancelExecution(workflowId, executionId) {
2910
+ expectEmpty(
2911
+ await transport.request(`${executionPath(workflowId, executionId)}/cancel`, {
2912
+ method: "POST"
2913
+ }),
2914
+ "Cancel workflow execution response",
2915
+ errors
2916
+ );
2917
+ }
2918
+ };
2919
+ }
2920
+
379
2921
  // src/core.ts
380
2922
  function createSdkCore(options) {
381
2923
  const errors = options.errors ?? defaultSdkCoreErrorFactory;
2924
+ const codeStudio = options.transports.codeStudio ?? unavailableTransport("codeStudio", errors);
2925
+ const copilot = options.transports.copilot ?? unavailableTransport("copilot", errors);
2926
+ const messengerTransport = options.transports.messenger ?? unavailableTransport("messenger", errors);
2927
+ const apps = createAppsModule(codeStudio, errors);
2928
+ const schema = createSchemaModule(options.transports.dataManager, errors);
2929
+ const functionsAdmin = createFunctionsAdminModule(options.transports.functions, errors);
2930
+ const agents = createAgentsModule(options.transports.functions, copilot, errors);
2931
+ const integrationAdmin = createIntegrationAdminModule(options.transports.integration, errors);
2932
+ const agentConnections = createAgentConnectionsModule(copilot, errors);
2933
+ const members = createMembersModule(options.transports.auth, errors);
382
2934
  return {
2935
+ agentConnections,
2936
+ agentCredentials: createAgentCredentialsModule(copilot, errors),
2937
+ agents,
2938
+ agentTasks: createAgentTasksModule(copilot, errors),
2939
+ apps,
383
2940
  auth: createAuthModule(options.transports.auth, errors),
2941
+ context: createContextModule(
2942
+ {
2943
+ apps,
2944
+ schema,
2945
+ functionsAdmin,
2946
+ agents,
2947
+ integrationAdmin,
2948
+ agentConnections,
2949
+ getAppId: options.getAppId
2950
+ },
2951
+ errors
2952
+ ),
2953
+ customQueries: createCustomQueriesModule(options.transports.dataManager, errors),
2954
+ dataSources: createDataSourcesModule(options.transports.dataManager, errors),
384
2955
  entities: createEntitiesModule(options.transports.dataManager, errors),
385
2956
  functions: createFunctionsModule(options.transports.functions, options.functions, errors),
2957
+ functionsAdmin,
2958
+ imports: createImportsModule(options.transports.dataManager, errors),
386
2959
  integration: createIntegrationModule(options.transports.integration, errors),
387
- queries: createQueriesModule(options.transports.dataManager, options.getDataSourceId, errors)
2960
+ integrationAdmin,
2961
+ integrationResources: createIntegrationResourcesModule(options.transports.integration, errors),
2962
+ integrationTemplates: createIntegrationTemplatesModule(options.transports.integration, errors),
2963
+ members,
2964
+ messenger: createMessengerModule(messengerTransport, errors),
2965
+ publicFunctions: createPublicFunctionsModule(options.transports.publicFunctions, errors),
2966
+ queries: createQueriesModule(options.transports.dataManager, errors),
2967
+ sql: createSqlModule(options.transports.dataManager, errors),
2968
+ schema,
2969
+ workflows: createWorkflowsModule(options.transports.functions, errors)
2970
+ };
2971
+ }
2972
+ function unavailableTransport(name, errors) {
2973
+ return {
2974
+ request() {
2975
+ return Promise.reject(errors.configuration(`The ${name} transport is not configured`));
2976
+ }
2977
+ };
2978
+ }
2979
+
2980
+ // src/agentSession.ts
2981
+ var AGENT_QUEUE_LIMIT = 10;
2982
+ var CANCEL_SAFETY_MS = 1e4;
2983
+ var RECONCILE_DELAY_MS = 1e3;
2984
+ var AgentTaskTurnError = class extends Error {
2985
+ code;
2986
+ constructor(message, code) {
2987
+ super(message);
2988
+ this.name = "AgentTaskTurnError";
2989
+ this.code = code;
2990
+ }
2991
+ };
2992
+ function asObject(value) {
2993
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
2994
+ }
2995
+ function errorMessage(error) {
2996
+ if (error instanceof Error) return error.message;
2997
+ if (error && typeof error === "object" && "message" in error) {
2998
+ return String(error.message);
2999
+ }
3000
+ return String(error);
3001
+ }
3002
+ function errorCode(error) {
3003
+ if (!error || typeof error !== "object") return void 0;
3004
+ const candidate = error;
3005
+ const code = candidate.code ?? candidate.details?.code ?? candidate.details?.error_code;
3006
+ return typeof code === "string" ? code : void 0;
3007
+ }
3008
+ function delay(milliseconds) {
3009
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
3010
+ }
3011
+ function toAgentTimelineItem(message) {
3012
+ if (message.type === "TOOL_USE") {
3013
+ try {
3014
+ const payload = JSON.parse(message.content);
3015
+ if (payload && typeof payload === "object") {
3016
+ return {
3017
+ id: message.id,
3018
+ kind: "tool",
3019
+ tool: {
3020
+ tool: typeof payload.name === "string" ? payload.name : "",
3021
+ ...typeof payload.toolId === "string" ? { toolId: payload.toolId } : {},
3022
+ ...payload.input !== void 0 ? { input: payload.input } : {},
3023
+ ...payload.content !== void 0 ? { content: payload.content } : payload.output !== void 0 ? { content: payload.output } : {},
3024
+ phase: payload.output !== void 0 || payload.content !== void 0 ? "result" : "call"
3025
+ },
3026
+ at: message.createdAt
3027
+ };
3028
+ }
3029
+ } catch {
3030
+ }
3031
+ }
3032
+ return {
3033
+ id: message.id,
3034
+ kind: message.sender === "USER" ? "user" : "agent",
3035
+ text: message.content,
3036
+ at: message.createdAt
3037
+ };
3038
+ }
3039
+ function createAgentTaskSessionManager(options) {
3040
+ const sessions = /* @__PURE__ */ new Map();
3041
+ return {
3042
+ session(sessionOptions) {
3043
+ if ("taskId" in sessionOptions) {
3044
+ const current = sessions.get(sessionOptions.taskId);
3045
+ if (current && current.status !== "closed") return current;
3046
+ }
3047
+ const session = new CoreAgentTaskSession(sessionOptions, {
3048
+ ...options,
3049
+ onTaskId: (taskId, value) => sessions.set(taskId, value),
3050
+ onClose: (taskId, value) => {
3051
+ if (sessions.get(taskId) === value) sessions.delete(taskId);
3052
+ }
3053
+ });
3054
+ if ("taskId" in sessionOptions) sessions.set(sessionOptions.taskId, session);
3055
+ return session;
3056
+ }
388
3057
  };
389
3058
  }
3059
+ function withAgentTaskSessions(tasks, manager) {
3060
+ return { ...tasks, session: (options) => manager.session(options) };
3061
+ }
3062
+ var CoreAgentTaskSession = class {
3063
+ constructor(options, dependencies) {
3064
+ this.options = options;
3065
+ this.dependencies = dependencies;
3066
+ this.isNewSession = "create" in options;
3067
+ if ("taskId" in options) {
3068
+ this._taskId = options.taskId;
3069
+ this.openingPromise = this.openExisting();
3070
+ } else {
3071
+ this._status = "idle";
3072
+ }
3073
+ }
3074
+ _taskId = null;
3075
+ _task = null;
3076
+ _status = "opening";
3077
+ _history = [];
3078
+ _content = "";
3079
+ _queue = [];
3080
+ isNewSession;
3081
+ listeners = /* @__PURE__ */ new Map();
3082
+ connection = null;
3083
+ connectionAbort = null;
3084
+ connectionPromise = null;
3085
+ openingPromise = null;
3086
+ createPromise = null;
3087
+ dispatching = false;
3088
+ recoveryUsed = false;
3089
+ recoveryPromise = null;
3090
+ recoveryGeneration = 0;
3091
+ recoveredTerminalReason;
3092
+ cancelTimer = null;
3093
+ queueSequence = 0;
3094
+ activeWaiter;
3095
+ turnBaselineIds = /* @__PURE__ */ new Set();
3096
+ get taskId() {
3097
+ return this._taskId;
3098
+ }
3099
+ get task() {
3100
+ return this._task;
3101
+ }
3102
+ get isNew() {
3103
+ return this.isNewSession;
3104
+ }
3105
+ get status() {
3106
+ return this._status;
3107
+ }
3108
+ get history() {
3109
+ return [...this._history];
3110
+ }
3111
+ get content() {
3112
+ return this._content;
3113
+ }
3114
+ get queue() {
3115
+ return this._queue.map((item) => ({
3116
+ id: item.id,
3117
+ text: item.text,
3118
+ createdAt: item.createdAt,
3119
+ ...item.agentType ? { agentType: item.agentType } : {},
3120
+ ...item.reasoningEffort ? { reasoningEffort: item.reasoningEffort } : {}
3121
+ }));
3122
+ }
3123
+ send(prompt, options = {}) {
3124
+ this.requireOpen();
3125
+ if (!prompt.trim()) return;
3126
+ if (this.isBusy()) {
3127
+ this.enqueue(prompt, options);
3128
+ return;
3129
+ }
3130
+ this.startDispatch(prompt, options);
3131
+ }
3132
+ sendAndWait(prompt, options = {}) {
3133
+ this.requireOpen();
3134
+ if (!prompt.trim()) return Promise.reject(new Error("Agent prompt must not be blank."));
3135
+ const waiter = this.createWaiter(options);
3136
+ if (waiter.settled) return waiter.promise;
3137
+ const sendOptions = {
3138
+ ...options.agentType ? { agentType: options.agentType } : {},
3139
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
3140
+ };
3141
+ if (this.isBusy()) {
3142
+ const queueId = this.enqueue(prompt, sendOptions, waiter);
3143
+ if (queueId) waiter.queueId = queueId;
3144
+ return waiter.promise;
3145
+ }
3146
+ this.startDispatch(prompt, sendOptions, waiter);
3147
+ return waiter.promise;
3148
+ }
3149
+ async cancel() {
3150
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3151
+ try {
3152
+ await this.sendInput({ type: "interrupt" });
3153
+ this.setStatus("cancelled");
3154
+ this.emit("cancelled", {});
3155
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3156
+ this.cancelTimer = setTimeout(() => {
3157
+ this.cancelTimer = null;
3158
+ if (this._status === "cancelled") {
3159
+ const error = new AgentTaskTurnError(
3160
+ "Agent turn cancellation was not acknowledged before the safety timeout."
3161
+ );
3162
+ this.emit("error", { error: error.message });
3163
+ this.failTurn(error);
3164
+ }
3165
+ }, CANCEL_SAFETY_MS);
3166
+ } catch (error) {
3167
+ this.emitError("Failed to cancel Agent task", error);
3168
+ throw error;
3169
+ }
3170
+ }
3171
+ respondApproval(approved) {
3172
+ void this.sendInput({ type: "approval_response", approved }).catch((error) => {
3173
+ this.emitError("Failed to answer Agent approval", error);
3174
+ });
3175
+ }
3176
+ async loadHistory(options = {}) {
3177
+ if (!this._taskId) return [];
3178
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3179
+ ...options.limit !== void 0 ? { size: options.limit } : {},
3180
+ sort: "createdAt,desc"
3181
+ });
3182
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
3183
+ const history = this.history;
3184
+ this.emit("historyLoaded", { history });
3185
+ return history;
3186
+ }
3187
+ editQueueItem(id, text) {
3188
+ if (!text.trim()) {
3189
+ this.removeQueueItem(id);
3190
+ return;
3191
+ }
3192
+ this._queue = this._queue.map((item) => item.id === id ? { ...item, text } : item);
3193
+ this.emitQueue();
3194
+ }
3195
+ removeQueueItem(id) {
3196
+ const removed = this._queue.find((item) => item.id === id);
3197
+ this._queue = this._queue.filter((item) => item.id !== id);
3198
+ removed?.waiter?.reject(new Error("Queued Agent prompt was removed."));
3199
+ this.emitQueue();
3200
+ }
3201
+ clearQueue() {
3202
+ if (!this._queue.length) return;
3203
+ const removed = this._queue;
3204
+ this._queue = [];
3205
+ for (const item of removed) item.waiter?.reject(new Error("Agent prompt queue was cleared."));
3206
+ this.emitQueue();
3207
+ }
3208
+ on(event, handler) {
3209
+ let listeners = this.listeners.get(event);
3210
+ if (!listeners) {
3211
+ listeners = /* @__PURE__ */ new Set();
3212
+ this.listeners.set(event, listeners);
3213
+ }
3214
+ const callback = handler;
3215
+ listeners.add(callback);
3216
+ return () => listeners?.delete(callback);
3217
+ }
3218
+ close() {
3219
+ if (this._status === "closed") return;
3220
+ this.setStatus("closed");
3221
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3222
+ this.cancelTimer = null;
3223
+ this.connectionAbort?.abort();
3224
+ this.connectionAbort = null;
3225
+ this.connection?.close();
3226
+ this.connection = null;
3227
+ this.recoveryGeneration += 1;
3228
+ const closedError = new Error("Agent task session is closed.");
3229
+ this.activeWaiter?.reject(closedError);
3230
+ this.activeWaiter = void 0;
3231
+ for (const item of this._queue) item.waiter?.reject(closedError);
3232
+ this._queue = [];
3233
+ if (this._taskId) this.dependencies.onClose(this._taskId, this);
3234
+ for (const listeners of this.listeners.values()) listeners.clear();
3235
+ }
3236
+ async openExisting() {
3237
+ try {
3238
+ this._task = await this.dependencies.tasks.get(this._taskId);
3239
+ if (this.isClosed()) return false;
3240
+ await this.loadHistory();
3241
+ if (this.isClosed()) return false;
3242
+ await this.ensureChannel();
3243
+ if (this.isClosed()) return false;
3244
+ this.setStatus("idle");
3245
+ return true;
3246
+ } catch (error) {
3247
+ if (this.isClosed()) return false;
3248
+ this.emitError("Failed to open Agent task", error);
3249
+ this.setStatus("error");
3250
+ return false;
3251
+ }
3252
+ }
3253
+ startDispatch(prompt, options, waiter) {
3254
+ this.dispatching = true;
3255
+ void this.dispatchSend(prompt, options, waiter).catch((error) => {
3256
+ waiter?.reject(error);
3257
+ this.emitError("Failed to send Agent prompt", error);
3258
+ if (this._status === "streaming") this.setStatus("idle");
3259
+ this.flushQueue();
3260
+ }).finally(() => {
3261
+ this.dispatching = false;
3262
+ if (this._status === "idle") this.flushQueue();
3263
+ });
3264
+ }
3265
+ async dispatchSend(prompt, options, waiter) {
3266
+ if (this.openingPromise && !await this.openingPromise) {
3267
+ throw new Error("Agent task session could not be opened.");
3268
+ }
3269
+ if (this.isClosed() || waiter?.settled) return;
3270
+ await this.ensureTask();
3271
+ if (this.isClosed() || waiter?.settled) return;
3272
+ await this.ensureChannel();
3273
+ if (this.isClosed() || waiter?.settled) return;
3274
+ await this.captureTurnBaseline();
3275
+ this._content = "";
3276
+ this.recoveryUsed = false;
3277
+ this.recoveredTerminalReason = void 0;
3278
+ this.recoveryGeneration += 1;
3279
+ this.activeWaiter = waiter;
3280
+ this.setStatus("streaming");
3281
+ this.emit("turnStart", {});
3282
+ await this.sendInput({
3283
+ type: "message",
3284
+ content: prompt,
3285
+ ...options.agentType ? { agentType: options.agentType } : {},
3286
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {}
3287
+ });
3288
+ }
3289
+ async ensureTask() {
3290
+ if (this._taskId) return;
3291
+ if (!("create" in this.options)) throw new Error("Agent task session has no task.");
3292
+ const createOptions = this.options;
3293
+ if (this.createPromise) return this.createPromise;
3294
+ this.createPromise = (async () => {
3295
+ const task = await this.dependencies.tasks.create({
3296
+ agentType: createOptions.agentType,
3297
+ ...createOptions.title ? { title: createOptions.title } : {},
3298
+ ...createOptions.agentId ? { agentId: createOptions.agentId } : {},
3299
+ ...createOptions.reasoningEffort ? { reasoningEffort: createOptions.reasoningEffort } : {},
3300
+ ...createOptions.userId ? { userId: createOptions.userId } : {}
3301
+ });
3302
+ this._task = task;
3303
+ this._taskId = task.id;
3304
+ this.dependencies.onTaskId(task.id, this);
3305
+ this.emit("taskCreated", { task });
3306
+ })().finally(() => {
3307
+ this.createPromise = null;
3308
+ });
3309
+ return this.createPromise;
3310
+ }
3311
+ ensureChannel() {
3312
+ if (this.connection) return Promise.resolve();
3313
+ if (this.connectionPromise) return this.connectionPromise;
3314
+ if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3315
+ const abort = new AbortController();
3316
+ this.connectionAbort = abort;
3317
+ this.connectionPromise = this.dependencies.eventSource.open(
3318
+ this._taskId,
3319
+ {
3320
+ onEvent: (event) => this.handleEvent(event),
3321
+ onDisconnect: (error) => this.handleDisconnect(error)
3322
+ },
3323
+ abort.signal,
3324
+ this.options.transport
3325
+ ).then((connection) => {
3326
+ if (this.isClosed() || this._status === "error") {
3327
+ connection.close();
3328
+ return;
3329
+ }
3330
+ this.connection = connection;
3331
+ }).finally(() => {
3332
+ this.connectionPromise = null;
3333
+ });
3334
+ return this.connectionPromise;
3335
+ }
3336
+ handleDisconnect(error) {
3337
+ this.connection = null;
3338
+ this.connectionAbort = null;
3339
+ if (this.isClosed()) return;
3340
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3341
+ if (this.recoveryUsed) {
3342
+ const disconnectError = new Error("Agent live channel disconnected after one recovery.");
3343
+ this.failLiveChannel(error ?? disconnectError, disconnectError);
3344
+ return;
3345
+ }
3346
+ this.recoveryUsed = true;
3347
+ const generation = ++this.recoveryGeneration;
3348
+ this.recoveryPromise = this.recoverTurn(generation).finally(() => {
3349
+ this.recoveryPromise = null;
3350
+ });
3351
+ }
3352
+ async recoverTurn(generation) {
3353
+ try {
3354
+ await this.ensureChannel();
3355
+ while (generation === this.recoveryGeneration && !this.isClosed() && (this._status === "streaming" || this._status === "cancelled")) {
3356
+ if (await this.reconcilePersistedTurn(this.recoveredTerminalReason ?? "reconciled")) {
3357
+ return;
3358
+ }
3359
+ if (this.activeWaiter?.settled) return;
3360
+ await delay(RECONCILE_DELAY_MS);
3361
+ }
3362
+ } catch (error) {
3363
+ if (this.isClosed()) return;
3364
+ const recoveryError = error instanceof Error ? error : new Error(errorMessage(error));
3365
+ this.failLiveChannel(error, recoveryError);
3366
+ }
3367
+ }
3368
+ async captureTurnBaseline() {
3369
+ if (!this._taskId) return;
3370
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3371
+ size: 100,
3372
+ sort: "createdAt,desc"
3373
+ });
3374
+ this.turnBaselineIds = new Set(page.content.map((message) => message.id));
3375
+ }
3376
+ async reconcilePersistedTurn(reason) {
3377
+ if (!this._taskId) return false;
3378
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
3379
+ size: 100,
3380
+ sort: "createdAt,desc"
3381
+ });
3382
+ this._history = [...page.content].reverse().map(toAgentTimelineItem);
3383
+ this.emit("historyLoaded", { history: this.history });
3384
+ const recovered = page.content.find(
3385
+ (message) => !this.turnBaselineIds.has(message.id) && message.sender !== "USER" && message.type !== "TOOL_USE"
3386
+ );
3387
+ if (!recovered) return false;
3388
+ if (recovered.type === "ERROR") {
3389
+ const error = new AgentTaskTurnError(recovered.content);
3390
+ this.emit("error", { error: error.message });
3391
+ this.failTurn(error);
3392
+ return true;
3393
+ }
3394
+ this._content = recovered.content;
3395
+ this.finishTurn(reason);
3396
+ return true;
3397
+ }
3398
+ sendInput(input) {
3399
+ if (!this._taskId) return Promise.reject(new Error("Agent task has not been created."));
3400
+ return this.dependencies.tasks.sendInput(this._taskId, input);
3401
+ }
3402
+ handleEvent(event) {
3403
+ this.emit("raw", event);
3404
+ const payload = asObject(event.payload);
3405
+ switch (event.type) {
3406
+ case "textDelta":
3407
+ this.consumeDelta(payload, "text");
3408
+ break;
3409
+ case "thinking":
3410
+ this.consumeDelta(payload, "thinking");
3411
+ break;
3412
+ case "toolCall":
3413
+ this.emitTool(payload, "call", event.timestamp);
3414
+ break;
3415
+ case "toolResult":
3416
+ this.emitTool(payload, "result", event.timestamp);
3417
+ break;
3418
+ case "workspace":
3419
+ this.emit("workspace", { payload: event.payload, timestamp: event.timestamp });
3420
+ break;
3421
+ case "stepFinish": {
3422
+ const reason = typeof payload?.reason === "string" ? payload.reason : "unknown";
3423
+ if (reason === "stop" || reason === "endTurn") {
3424
+ if (this.recoveryUsed) {
3425
+ this.recoveredTerminalReason = reason;
3426
+ if (!this.recoveryPromise) {
3427
+ const generation = this.recoveryGeneration;
3428
+ this.recoveryPromise = this.recoverTurn(generation).finally(() => {
3429
+ this.recoveryPromise = null;
3430
+ });
3431
+ }
3432
+ } else {
3433
+ this.finishTurn(reason);
3434
+ }
3435
+ }
3436
+ break;
3437
+ }
3438
+ case "error": {
3439
+ const code = typeof payload?.code === "string" ? payload.code : void 0;
3440
+ const message = typeof payload?.message === "string" ? payload.message : "Agent returned an error.";
3441
+ this.emit("error", { ...code ? { code } : {}, error: message });
3442
+ if (this._status === "streaming" || this._status === "cancelled") {
3443
+ this.failTurn(new AgentTaskTurnError(message, code));
3444
+ }
3445
+ break;
3446
+ }
3447
+ default:
3448
+ break;
3449
+ }
3450
+ }
3451
+ consumeDelta(payload, kind) {
3452
+ const text = typeof payload?.text === "string" ? payload.text : "";
3453
+ if (this._status !== "streaming" && this._status !== "cancelled") {
3454
+ this.setStatus("streaming");
3455
+ this.emit("turnStart", {});
3456
+ }
3457
+ if (kind === "text") this._content += text;
3458
+ this.emit("delta", { delta: text, kind });
3459
+ }
3460
+ emitTool(payload, phase, timestamp) {
3461
+ this.emit("tool", {
3462
+ tool: typeof payload?.name === "string" ? payload.name : "",
3463
+ phase,
3464
+ timestamp,
3465
+ ...typeof payload?.toolId === "string" ? { toolId: payload.toolId } : {},
3466
+ ...phase === "call" && payload?.input !== void 0 ? { input: payload.input } : {},
3467
+ ...phase === "result" ? { content: payload?.content ?? payload?.output } : {}
3468
+ });
3469
+ }
3470
+ finishTurn(reason) {
3471
+ if (this._status !== "streaming" && this._status !== "cancelled") return;
3472
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3473
+ this.cancelTimer = null;
3474
+ this.recoveryGeneration += 1;
3475
+ const task = this._task;
3476
+ if (!task) {
3477
+ const error = new Error("Agent turn ended before task metadata was available.");
3478
+ this.activeWaiter?.reject(error);
3479
+ this.activeWaiter = void 0;
3480
+ this.emitError("Failed to finish Agent turn", error);
3481
+ this.setStatus("error");
3482
+ return;
3483
+ }
3484
+ const result = { task, content: this._content, reason };
3485
+ this.emit("turnEnd", result);
3486
+ this.activeWaiter?.resolve(result);
3487
+ this.activeWaiter = void 0;
3488
+ this.setStatus("idle");
3489
+ this.flushQueue();
3490
+ }
3491
+ failTurn(error) {
3492
+ if (this.cancelTimer) clearTimeout(this.cancelTimer);
3493
+ this.cancelTimer = null;
3494
+ this.recoveryGeneration += 1;
3495
+ this.activeWaiter?.reject(error);
3496
+ this.activeWaiter = void 0;
3497
+ this.setStatus("idle");
3498
+ this.flushQueue();
3499
+ }
3500
+ failLiveChannel(observed, waiterError) {
3501
+ this.recoveryGeneration += 1;
3502
+ this.emitError("Agent live channel failed", observed);
3503
+ this.activeWaiter?.reject(waiterError);
3504
+ this.activeWaiter = void 0;
3505
+ for (const item of this._queue) item.waiter?.reject(waiterError);
3506
+ this._queue = [];
3507
+ this.emitQueue();
3508
+ this.setStatus("error");
3509
+ }
3510
+ enqueue(text, options, waiter) {
3511
+ if (this._queue.length >= AGENT_QUEUE_LIMIT) {
3512
+ const error = new Error(`Agent message queue is full (maximum ${AGENT_QUEUE_LIMIT}).`);
3513
+ waiter?.reject(error);
3514
+ this.emit("error", { error: error.message });
3515
+ return void 0;
3516
+ }
3517
+ const id = `q-${++this.queueSequence}`;
3518
+ this._queue = [
3519
+ ...this._queue,
3520
+ { id, text, createdAt: Date.now(), ...options, ...waiter ? { waiter } : {} }
3521
+ ];
3522
+ this.emitQueue();
3523
+ return id;
3524
+ }
3525
+ flushQueue() {
3526
+ if (this.isBusy()) return;
3527
+ let next = this._queue[0];
3528
+ while (next?.waiter?.settled) {
3529
+ this._queue = this._queue.slice(1);
3530
+ next = this._queue[0];
3531
+ }
3532
+ if (!next) {
3533
+ this.emitQueue();
3534
+ return;
3535
+ }
3536
+ this._queue = this._queue.slice(1);
3537
+ this.emitQueue();
3538
+ this.startDispatch(
3539
+ next.text,
3540
+ {
3541
+ ...next.agentType ? { agentType: next.agentType } : {},
3542
+ ...next.reasoningEffort ? { reasoningEffort: next.reasoningEffort } : {}
3543
+ },
3544
+ next.waiter
3545
+ );
3546
+ }
3547
+ createWaiter(options) {
3548
+ let resolvePromise;
3549
+ let rejectPromise;
3550
+ let timer;
3551
+ let abortListener;
3552
+ const waiter = {
3553
+ promise: new Promise((resolve, reject) => {
3554
+ resolvePromise = resolve;
3555
+ rejectPromise = reject;
3556
+ }),
3557
+ settled: false,
3558
+ resolve: (result) => {
3559
+ if (waiter.settled) return;
3560
+ waiter.settled = true;
3561
+ waiter.cleanup();
3562
+ resolvePromise(result);
3563
+ },
3564
+ reject: (error) => {
3565
+ if (waiter.settled) return;
3566
+ waiter.settled = true;
3567
+ waiter.cleanup();
3568
+ if (waiter.queueId) this.removeQueuedWaiter(waiter.queueId);
3569
+ rejectPromise(error);
3570
+ },
3571
+ cleanup: () => {
3572
+ if (timer) clearTimeout(timer);
3573
+ if (abortListener) options.signal?.removeEventListener("abort", abortListener);
3574
+ }
3575
+ };
3576
+ if (options.timeoutMs !== void 0) {
3577
+ if (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0) {
3578
+ waiter.reject(new Error("Agent turn timeoutMs must be a positive number."));
3579
+ return waiter;
3580
+ }
3581
+ timer = setTimeout(
3582
+ () => waiter.reject(new Error(`Agent turn timed out after ${options.timeoutMs} ms.`)),
3583
+ options.timeoutMs
3584
+ );
3585
+ }
3586
+ if (options.signal) {
3587
+ abortListener = () => waiter.reject(options.signal?.reason ?? new Error("Agent turn aborted."));
3588
+ if (options.signal.aborted) abortListener();
3589
+ else options.signal.addEventListener("abort", abortListener, { once: true });
3590
+ }
3591
+ return waiter;
3592
+ }
3593
+ removeQueuedWaiter(id) {
3594
+ const size = this._queue.length;
3595
+ this._queue = this._queue.filter((item) => item.id !== id);
3596
+ if (this._queue.length !== size) this.emitQueue();
3597
+ }
3598
+ emitQueue() {
3599
+ this.emit("queueChange", { queue: this.queue });
3600
+ }
3601
+ emitError(prefix, error) {
3602
+ const code = errorCode(error);
3603
+ this.emit("error", {
3604
+ ...code ? { code } : {},
3605
+ error: `${prefix}: ${errorMessage(error)}`
3606
+ });
3607
+ }
3608
+ setStatus(status) {
3609
+ if (this._status === status) return;
3610
+ this._status = status;
3611
+ this.emit("statusChange", { status });
3612
+ }
3613
+ requireOpen() {
3614
+ if (this.isClosed()) throw new Error("Agent task session is closed.");
3615
+ }
3616
+ isClosed() {
3617
+ return this._status === "closed";
3618
+ }
3619
+ isBusy() {
3620
+ return this.dispatching || this._status === "streaming" || this._status === "cancelled";
3621
+ }
3622
+ emit(event, payload) {
3623
+ const listeners = this.listeners.get(event);
3624
+ for (const listener of listeners ?? []) {
3625
+ try {
3626
+ listener(payload);
3627
+ } catch {
3628
+ }
3629
+ }
3630
+ }
3631
+ };
390
3632
  export {
3633
+ AgentTaskTurnError,
391
3634
  SdkCoreConfigurationError,
392
3635
  SdkCoreResponseError,
3636
+ createAgentConnectionsModule,
3637
+ createAgentCredentialsModule,
3638
+ createAgentTaskSessionManager,
3639
+ createAgentTasksModule,
3640
+ createAgentsModule,
3641
+ createAppsModule,
393
3642
  createAuthModule,
3643
+ createContextModule,
3644
+ createCustomQueriesModule,
3645
+ createDataSourcesModule,
394
3646
  createEntitiesModule,
3647
+ createFunctionsAdminModule,
395
3648
  createFunctionsModule,
3649
+ createImportsModule,
3650
+ createIntegrationAdminModule,
396
3651
  createIntegrationModule,
3652
+ createIntegrationResourcesModule,
3653
+ createIntegrationTemplatesModule,
3654
+ createMembersModule,
3655
+ createMessengerModule,
3656
+ createPublicFunctionsModule,
397
3657
  createQueriesModule,
3658
+ createSchemaModule,
398
3659
  createSdkCore,
3660
+ createSqlModule,
3661
+ createWorkflowsModule,
399
3662
  defaultSdkCoreErrorFactory,
400
3663
  encodePathSegment,
401
3664
  expectEmpty,
3665
+ expectLegacyPage,
3666
+ expectNullableObject,
402
3667
  expectObject,
403
- expectObjectArray
3668
+ expectObjectArray,
3669
+ expectPage,
3670
+ expectStringArray,
3671
+ toAgentTimelineItem,
3672
+ withAgentTaskSessions
404
3673
  };