@mitralab.io/functions-sdk 0.1.0 → 0.2.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,19 +17,92 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ AgentTaskTurnError: () => import_sdk_core3.AgentTaskTurnError,
23
34
  MitraApiError: () => MitraApiError,
24
35
  MitraConfigurationError: () => MitraConfigurationError,
36
+ callIntegrationMitra: () => callIntegrationMitra2,
37
+ configureSdkMitra: () => configureSdkMitra3,
38
+ createAgentMitra: () => createAgentMitra2,
25
39
  createClient: () => createClient,
26
- createClientFromEnvironment: () => createClientFromEnvironment
40
+ createClientFromEnvironment: () => createClientFromEnvironment,
41
+ createIntegrationMitra: () => createIntegrationMitra2,
42
+ createJdbcConnectionMitra: () => createJdbcConnectionMitra2,
43
+ createMitraSdkInstance: () => createMitraSdkInstance2,
44
+ createOnlineTableMitra: () => createOnlineTableMitra2,
45
+ createProjectMitra: () => createProjectMitra2,
46
+ createRecordMitra: () => createRecordMitra2,
47
+ createRecordsBatchMitra: () => createRecordsBatchMitra2,
48
+ createServerFunctionMitra: () => createServerFunctionMitra2,
49
+ deleteAgentMitra: () => deleteAgentMitra2,
50
+ deleteIntegrationMitra: () => deleteIntegrationMitra2,
51
+ deleteJdbcConnectionMitra: () => deleteJdbcConnectionMitra2,
52
+ deleteOnlineTableMitra: () => deleteOnlineTableMitra2,
53
+ deleteRecordMitra: () => deleteRecordMitra2,
54
+ deleteServerFunctionMitra: () => deleteServerFunctionMitra2,
55
+ deployToS3Mitra: () => deployToS3Mitra2,
56
+ executePublicServerFunctionAsyncMitra: () => executePublicServerFunctionAsyncMitra2,
57
+ executeServerFunctionAsyncMitra: () => executeServerFunctionAsyncMitra2,
58
+ executeServerFunctionMitra: () => executeServerFunctionMitra2,
59
+ getAgentTaskMitra: () => getAgentTaskMitra2,
60
+ getDeployStatusMitra: () => getDeployStatusMitra2,
61
+ getGitConfigMitra: () => getGitConfigMitra2,
62
+ getIntegrationTemplateMitra: () => getIntegrationTemplateMitra2,
63
+ getProjectContextMitra: () => getProjectContextMitra2,
64
+ getProjectsMitra: () => getProjectsMitra2,
65
+ getRecordMitra: () => getRecordMitra2,
66
+ getServerFunctionExecutionMitra: () => getServerFunctionExecutionMitra2,
67
+ inviteUserMitra: () => inviteUserMitra2,
68
+ listAgentsMitra: () => listAgentsMitra2,
69
+ listIntegrationTemplatesMitra: () => listIntegrationTemplatesMitra2,
70
+ listIntegrationsMitra: () => listIntegrationsMitra2,
71
+ listJdbcConnectionsMitra: () => listJdbcConnectionsMitra2,
72
+ listOnlineTablesMitra: () => listOnlineTablesMitra2,
73
+ listProjectsMitra: () => listProjectsMitra2,
74
+ listRecordsMitra: () => listRecordsMitra2,
75
+ listServerFunctionsMitra: () => listServerFunctionsMitra2,
76
+ listTablesMitra: () => listTablesMitra2,
77
+ manageAgentChatMitra: () => manageAgentChatMitra2,
78
+ manageAgentConnectionMitra: () => manageAgentConnectionMitra2,
79
+ manageAgentCredentialMitra: () => manageAgentCredentialMitra2,
80
+ patchRecordMitra: () => patchRecordMitra2,
81
+ readAgentMitra: () => readAgentMitra2,
82
+ readServerFunctionMitra: () => readServerFunctionMitra2,
83
+ resolveProjectId: () => resolveProjectId2,
84
+ runDdlMitra: () => runDdlMitra2,
85
+ runDmlMitra: () => runDmlMitra2,
86
+ runQueryMitra: () => runQueryMitra2,
87
+ stopServerFunctionExecutionMitra: () => stopServerFunctionExecutionMitra2,
88
+ testIntegrationByIdMitra: () => testIntegrationByIdMitra2,
89
+ testIntegrationMitra: () => testIntegrationMitra2,
90
+ togglePublicExecutionMitra: () => togglePublicExecutionMitra2,
91
+ unsubscribeUserMitra: () => unsubscribeUserMitra2,
92
+ updateAgentMitra: () => updateAgentMitra2,
93
+ updateIntegrationMitra: () => updateIntegrationMitra2,
94
+ updateJdbcConnectionMitra: () => updateJdbcConnectionMitra2,
95
+ updateOnlineTableMitra: () => updateOnlineTableMitra2,
96
+ updateProjectSettingsMitra: () => updateProjectSettingsMitra2,
97
+ updateRecordMitra: () => updateRecordMitra2,
98
+ updateServerFunctionMitra: () => updateServerFunctionMitra2
27
99
  });
28
100
  module.exports = __toCommonJS(index_exports);
29
101
 
30
102
  // src/client.ts
103
+ var import_sdk_core2 = require("@mitralab.io/sdk-core");
104
+
105
+ // src/agent-task-sse.ts
31
106
  var import_sdk_core = require("@mitralab.io/sdk-core");
32
107
 
33
108
  // src/errors.ts
@@ -54,69 +129,11 @@ var MitraApiError = class extends Error {
54
129
  }
55
130
  };
56
131
 
57
- // src/config.ts
58
- var DEFAULT_TIMEOUT_MS = 1e4;
59
- function readDefaultEnvironment() {
60
- return typeof process === "undefined" ? {} : process.env;
61
- }
62
- function requiredValue(value, name) {
63
- if (!value?.trim()) {
64
- throw new MitraConfigurationError(`${name} is required`);
65
- }
66
- return value.trim();
67
- }
68
- function normalizeApiUrl(value) {
69
- let parsed;
70
- try {
71
- parsed = new URL(value);
72
- } catch {
73
- throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
74
- }
75
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
76
- throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
77
- }
78
- if (parsed.username || parsed.password || parsed.search || parsed.hash || value.includes("?") || value.includes("#")) {
79
- throw new MitraConfigurationError(
80
- "apiUrl must not include credentials, query parameters, or a fragment"
81
- );
82
- }
83
- return parsed.toString().replace(/\/+$/, "");
84
- }
85
- function resolveConfig(config = {}, environment = readDefaultEnvironment()) {
86
- const apiUrl = normalizeApiUrl(
87
- requiredValue(config.apiUrl ?? environment.MITRA_API_URL, "apiUrl")
88
- );
89
- const accessToken = requiredValue(
90
- config.accessToken ?? environment.MITRA_PLATFORM_ACCESS_TOKEN,
91
- "accessToken"
92
- );
93
- const appId = requiredValue(config.appId ?? environment.MITRA_APP_ID, "appId");
94
- const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
95
- const fetchImplementation = config.fetch ?? globalThis.fetch;
96
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
97
- throw new MitraConfigurationError("timeoutMs must be a positive number");
98
- }
99
- if (typeof fetchImplementation !== "function") {
100
- throw new MitraConfigurationError("A fetch implementation is required");
101
- }
102
- const dataSourceId = config.dataSourceId ?? environment.MITRA_DATA_SOURCE_ID;
103
- if (dataSourceId !== void 0 && !dataSourceId.trim()) {
104
- throw new MitraConfigurationError("dataSourceId must not be empty when provided");
105
- }
106
- return {
107
- apiUrl,
108
- accessToken,
109
- appId,
110
- ...dataSourceId === void 0 ? {} : { dataSourceId: dataSourceId.trim() },
111
- timeoutMs,
112
- fetch: fetchImplementation
113
- };
114
- }
115
-
116
132
  // src/http-client.ts
117
133
  var bearerCredentialPattern = /(\bBearer\s+)\S+/gi;
118
134
  function redactText(value, accessToken) {
119
- return value.replace(bearerCredentialPattern, "$1[REDACTED]").split(accessToken).join("[REDACTED]");
135
+ const bearerRedacted = value.replace(bearerCredentialPattern, "$1[REDACTED]");
136
+ return accessToken ? bearerRedacted.split(accessToken).join("[REDACTED]") : bearerRedacted;
120
137
  }
121
138
  function redactDetails(value, accessToken) {
122
139
  if (typeof value === "string") return redactText(value, accessToken);
@@ -137,7 +154,67 @@ function redactDetails(value, accessToken) {
137
154
  function optionalString(value) {
138
155
  return typeof value === "string" ? value : void 0;
139
156
  }
157
+ function appendQueryParameters(url, params) {
158
+ for (const [key, value] of Object.entries(params)) {
159
+ if (value === void 0) continue;
160
+ const values = Array.isArray(value) ? value : [value];
161
+ for (const item of values) {
162
+ url.searchParams.append(key, typeof item === "string" ? item : item.toString());
163
+ }
164
+ }
165
+ }
166
+ function createRequestHeaders(hasBody, customHeaders, authentication) {
167
+ const safeCustomHeaders = Object.fromEntries(
168
+ Object.entries(customHeaders ?? {}).filter(
169
+ ([name]) => !["authorization", "x-app-id"].includes(name.toLowerCase())
170
+ )
171
+ );
172
+ return {
173
+ Accept: "application/json",
174
+ ...hasBody ? { "Content-Type": "application/json" } : {},
175
+ ...safeCustomHeaders,
176
+ ...authentication.type === "bearer" ? {
177
+ Authorization: `Bearer ${authentication.accessToken}`,
178
+ "X-App-Id": authentication.appId
179
+ } : {}
180
+ };
181
+ }
182
+ async function parsePayload(response) {
183
+ const text = await response.text();
184
+ if (response.ok && !text.trim()) return void 0;
185
+ try {
186
+ return JSON.parse(text);
187
+ } catch {
188
+ if (response.ok) {
189
+ throw new MitraApiError("The Mitra API returned invalid JSON", response.status, {
190
+ code: "INVALID_RESPONSE",
191
+ retryable: false
192
+ });
193
+ }
194
+ return {};
195
+ }
196
+ }
197
+ function createApiError(response, payload, accessToken) {
198
+ const errorPayload = payload && typeof payload === "object" ? payload : {};
199
+ const rawMessage = optionalString(errorPayload.message);
200
+ const message = redactText(
201
+ rawMessage ?? `Request failed with status ${response.status}`,
202
+ accessToken
203
+ );
204
+ const rawRequestId = optionalString(errorPayload.request_id) ?? optionalString(errorPayload.requestId) ?? response.headers.get("X-Request-Id") ?? void 0;
205
+ const rawCode = optionalString(errorPayload.error_code) ?? optionalString(errorPayload.code);
206
+ const requestId = rawRequestId === void 0 ? void 0 : redactText(rawRequestId, accessToken);
207
+ const code = rawCode === void 0 ? void 0 : redactText(rawCode, accessToken);
208
+ const retryable = typeof errorPayload.retryable === "boolean" ? errorPayload.retryable : response.status >= 500;
209
+ return new MitraApiError(message, response.status, {
210
+ ...code === void 0 ? {} : { code },
211
+ ...errorPayload.details === void 0 ? {} : { details: redactDetails(errorPayload.details, accessToken) },
212
+ ...requestId === void 0 ? {} : { requestId },
213
+ ...retryable === void 0 ? {} : { retryable }
214
+ });
215
+ }
140
216
  var HttpClient = class {
217
+ #authentication;
141
218
  #accessToken;
142
219
  baseUrl;
143
220
  appId;
@@ -145,70 +222,38 @@ var HttpClient = class {
145
222
  fetchImplementation;
146
223
  constructor(config) {
147
224
  this.baseUrl = config.baseUrl;
148
- this.#accessToken = config.accessToken;
149
- this.appId = config.appId;
225
+ this.#authentication = config.authentication;
226
+ this.#accessToken = config.authentication === "bearer" ? config.accessToken : void 0;
227
+ this.appId = config.authentication === "bearer" ? config.appId : void 0;
150
228
  this.timeoutMs = config.timeoutMs;
151
229
  this.fetchImplementation = config.fetch;
152
230
  }
153
231
  async request(path, options = {}) {
154
232
  const url = new URL(`${this.baseUrl}${path}`);
155
- for (const [key, value] of Object.entries(options.params ?? {})) {
156
- if (value !== void 0) url.searchParams.append(key, String(value));
157
- }
158
- const controller = new AbortController();
159
- const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
233
+ appendQueryParameters(url, options.params ?? {});
234
+ const controller = this.timeoutMs === void 0 ? void 0 : new AbortController();
235
+ const timeout = controller === void 0 ? void 0 : setTimeout(() => controller.abort(), this.timeoutMs);
160
236
  const hasBody = options.body !== void 0;
237
+ const authentication = this.#authentication === "bearer" ? {
238
+ type: "bearer",
239
+ accessToken: this.#accessToken,
240
+ appId: this.appId
241
+ } : { type: "anonymous" };
161
242
  try {
162
243
  const response = await this.fetchImplementation(url, {
163
244
  method: options.method ?? "GET",
164
- headers: {
165
- Accept: "application/json",
166
- ...hasBody ? { "Content-Type": "application/json" } : {},
167
- Authorization: `Bearer ${this.#accessToken}`,
168
- "X-App-Id": this.appId,
169
- ...options.headers
170
- },
245
+ headers: createRequestHeaders(hasBody, options.headers, authentication),
171
246
  ...hasBody ? { body: JSON.stringify(options.body) } : {},
172
247
  redirect: "manual",
173
- signal: controller.signal
248
+ ...controller === void 0 ? {} : { signal: controller.signal }
174
249
  });
175
250
  if (response.status === 204) return void 0;
176
- const text = await response.text();
177
- let payload;
178
- try {
179
- payload = JSON.parse(text);
180
- } catch {
181
- if (response.ok) {
182
- throw new MitraApiError("The Mitra API returned invalid JSON", response.status, {
183
- code: "INVALID_RESPONSE",
184
- retryable: false
185
- });
186
- }
187
- payload = {};
188
- }
189
- if (!response.ok) {
190
- const errorPayload = payload && typeof payload === "object" ? payload : {};
191
- const rawMessage = optionalString(errorPayload.message);
192
- const message = redactText(
193
- rawMessage ?? `Request failed with status ${response.status}`,
194
- this.#accessToken
195
- );
196
- const rawRequestId = optionalString(errorPayload.request_id) ?? optionalString(errorPayload.requestId) ?? response.headers.get("X-Request-Id") ?? void 0;
197
- const rawCode = optionalString(errorPayload.error_code) ?? optionalString(errorPayload.code);
198
- const requestId = rawRequestId === void 0 ? void 0 : redactText(rawRequestId, this.#accessToken);
199
- const code = rawCode === void 0 ? void 0 : redactText(rawCode, this.#accessToken);
200
- const retryable = typeof errorPayload.retryable === "boolean" ? errorPayload.retryable : response.status >= 500;
201
- throw new MitraApiError(message, response.status, {
202
- ...code === void 0 ? {} : { code },
203
- ...errorPayload.details === void 0 ? {} : { details: redactDetails(errorPayload.details, this.#accessToken) },
204
- ...requestId === void 0 ? {} : { requestId },
205
- ...retryable === void 0 ? {} : { retryable }
206
- });
207
- }
251
+ const payload = await parsePayload(response);
252
+ if (!response.ok) throw createApiError(response, payload, this.#accessToken);
208
253
  return payload;
209
254
  } catch (error) {
210
255
  if (error instanceof MitraApiError) throw error;
211
- if (controller.signal.aborted) {
256
+ if (controller?.signal.aborted) {
212
257
  throw new MitraApiError("Mitra request timed out", 0, {
213
258
  code: "REQUEST_TIMEOUT",
214
259
  retryable: true
@@ -219,7 +264,7 @@ var HttpClient = class {
219
264
  retryable: true
220
265
  });
221
266
  } finally {
222
- clearTimeout(timeout);
267
+ if (timeout !== void 0) clearTimeout(timeout);
223
268
  }
224
269
  }
225
270
  get(path, params) {
@@ -243,17 +288,385 @@ var HttpClient = class {
243
288
  }
244
289
  };
245
290
 
291
+ // src/agent-task-sse.ts
292
+ function invalidResponse(message) {
293
+ return new MitraApiError(message, 200, {
294
+ code: "INVALID_RESPONSE",
295
+ retryable: false
296
+ });
297
+ }
298
+ function parseAgentTaskEvent(data) {
299
+ let value;
300
+ try {
301
+ value = JSON.parse(data);
302
+ } catch {
303
+ throw invalidResponse("The Agent event stream returned invalid JSON");
304
+ }
305
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
306
+ throw invalidResponse("The Agent event stream returned an invalid event");
307
+ }
308
+ const event = value;
309
+ if (typeof event.type !== "string" || typeof event.timestamp !== "number") {
310
+ throw invalidResponse("The Agent event stream returned an invalid event");
311
+ }
312
+ if (event.sequence !== void 0 && typeof event.sequence !== "number") {
313
+ throw invalidResponse("The Agent event stream returned an invalid event sequence");
314
+ }
315
+ return value;
316
+ }
317
+ function consumeEventBlock(block, observer) {
318
+ let eventName = "message";
319
+ const data = [];
320
+ for (const rawLine of block.split(/\r?\n/)) {
321
+ const line = rawLine.replace(/^\uFEFF/, "");
322
+ if (!line || line.startsWith(":")) continue;
323
+ const separator = line.indexOf(":");
324
+ const field = separator === -1 ? line : line.slice(0, separator);
325
+ let value = separator === -1 ? "" : line.slice(separator + 1);
326
+ if (value.startsWith(" ")) value = value.slice(1);
327
+ if (field === "event") eventName = value;
328
+ if (field === "data") data.push(value);
329
+ }
330
+ if (eventName === "hello" || eventName === "ping") return;
331
+ if (eventName !== "message" || data.length === 0) return;
332
+ observer.onEvent(parseAgentTaskEvent(data.join("\n")));
333
+ }
334
+ async function readErrorPayload(response) {
335
+ const text = await response.text();
336
+ try {
337
+ return JSON.parse(text);
338
+ } catch {
339
+ return {};
340
+ }
341
+ }
342
+ var AgentTaskSseEventSource = class {
343
+ constructor(config) {
344
+ this.config = config;
345
+ }
346
+ async open(taskId, observer, signal, transport) {
347
+ if (transport === "websocket") {
348
+ throw new MitraConfigurationError(
349
+ "WebSocket Agent sessions are not available in the Functions runtime"
350
+ );
351
+ }
352
+ if (signal?.aborted) throw signal.reason ?? new Error("Agent event stream was aborted");
353
+ const controller = new AbortController();
354
+ let handshakeTimedOut = false;
355
+ let intentionallyClosed = false;
356
+ let disconnected = false;
357
+ const abortFromCaller = () => controller.abort(signal?.reason);
358
+ signal?.addEventListener("abort", abortFromCaller, { once: true });
359
+ const handshakeTimeout = this.config.timeoutMs === void 0 ? void 0 : setTimeout(() => {
360
+ handshakeTimedOut = true;
361
+ controller.abort();
362
+ }, this.config.timeoutMs);
363
+ const disconnect = (error) => {
364
+ if (disconnected || intentionallyClosed) return;
365
+ disconnected = true;
366
+ observer.onDisconnect(error);
367
+ };
368
+ const cleanup = () => signal?.removeEventListener("abort", abortFromCaller);
369
+ let response;
370
+ try {
371
+ const path = (0, import_sdk_core.encodePathSegment)(taskId, "taskId", this.config.errors);
372
+ response = await this.config.fetch(`${this.config.baseUrl}/api/v1/tasks/${path}/events`, {
373
+ method: "GET",
374
+ headers: {
375
+ Accept: "text/event-stream",
376
+ Authorization: `Bearer ${this.config.accessToken}`,
377
+ "X-App-Id": this.config.appId
378
+ },
379
+ redirect: "manual",
380
+ signal: controller.signal
381
+ });
382
+ } catch {
383
+ if (handshakeTimeout !== void 0) clearTimeout(handshakeTimeout);
384
+ cleanup();
385
+ if (handshakeTimedOut) {
386
+ throw new MitraApiError("Mitra Agent event stream handshake timed out", 0, {
387
+ code: "REQUEST_TIMEOUT",
388
+ retryable: true
389
+ });
390
+ }
391
+ if (signal?.aborted) throw signal.reason ?? new Error("Agent event stream was aborted");
392
+ throw new MitraApiError("The Mitra Agent event stream request failed", 0, {
393
+ code: "NETWORK_ERROR",
394
+ retryable: true
395
+ });
396
+ }
397
+ if (handshakeTimeout !== void 0) clearTimeout(handshakeTimeout);
398
+ if (!response.ok) {
399
+ cleanup();
400
+ throw createApiError(response, await readErrorPayload(response), this.config.accessToken);
401
+ }
402
+ if (!response.body) {
403
+ cleanup();
404
+ throw invalidResponse("The Agent event stream response has no body");
405
+ }
406
+ const contentType = response.headers.get("Content-Type") ?? "";
407
+ if (!contentType.toLowerCase().includes("text/event-stream")) {
408
+ controller.abort();
409
+ cleanup();
410
+ throw invalidResponse("The Agent event stream returned an invalid content type");
411
+ }
412
+ const reader = response.body.getReader();
413
+ const decoder = new TextDecoder();
414
+ let buffer = "";
415
+ void (async () => {
416
+ try {
417
+ while (true) {
418
+ const { done, value } = await reader.read();
419
+ if (done) break;
420
+ buffer += decoder.decode(value, { stream: true });
421
+ let boundary = /\r?\n\r?\n/.exec(buffer);
422
+ while (boundary?.index !== void 0) {
423
+ consumeEventBlock(buffer.slice(0, boundary.index), observer);
424
+ buffer = buffer.slice(boundary.index + boundary[0].length);
425
+ boundary = /\r?\n\r?\n/.exec(buffer);
426
+ }
427
+ }
428
+ buffer += decoder.decode();
429
+ if (buffer.trim()) consumeEventBlock(buffer, observer);
430
+ disconnect();
431
+ } catch (error) {
432
+ if (!controller.signal.aborted) {
433
+ controller.abort();
434
+ await reader.cancel().catch(() => void 0);
435
+ disconnect(error);
436
+ }
437
+ } finally {
438
+ cleanup();
439
+ reader.releaseLock();
440
+ }
441
+ })();
442
+ return {
443
+ close() {
444
+ if (intentionallyClosed) return;
445
+ intentionallyClosed = true;
446
+ cleanup();
447
+ controller.abort();
448
+ void reader.cancel().catch(() => void 0);
449
+ }
450
+ };
451
+ }
452
+ };
453
+
454
+ // src/app-scoped-apps.ts
455
+ function unavailable(operation) {
456
+ throw new MitraConfigurationError(
457
+ `apps.${operation} is not available in an app-scoped Functions runtime`
458
+ );
459
+ }
460
+ function assertCurrentApp(configuredAppId, requestedAppId) {
461
+ if (requestedAppId !== configuredAppId) {
462
+ throw new MitraConfigurationError(
463
+ `Code Studio access is fixed to app ${configuredAppId}; received ${requestedAppId}`
464
+ );
465
+ }
466
+ }
467
+ function createAppScopedAppsModule(apps, appId) {
468
+ const scoped = {
469
+ async list() {
470
+ return unavailable("list");
471
+ },
472
+ async get(requestedAppId, options) {
473
+ assertCurrentApp(appId, requestedAppId);
474
+ return apps.get(appId, options);
475
+ },
476
+ async create() {
477
+ return unavailable("create");
478
+ },
479
+ async delete(requestedAppId) {
480
+ assertCurrentApp(appId, requestedAppId);
481
+ return apps.delete(appId);
482
+ },
483
+ async update(requestedAppId, input) {
484
+ assertCurrentApp(appId, requestedAppId);
485
+ return apps.update(appId, input);
486
+ },
487
+ async getFiles(requestedAppId) {
488
+ assertCurrentApp(appId, requestedAppId);
489
+ return apps.getFiles(appId);
490
+ },
491
+ async replaceFiles(requestedAppId, files) {
492
+ assertCurrentApp(appId, requestedAppId);
493
+ return apps.replaceFiles(appId, files);
494
+ },
495
+ async mergeFiles(requestedAppId, files) {
496
+ assertCurrentApp(appId, requestedAppId);
497
+ return apps.mergeFiles(appId, files);
498
+ },
499
+ async build(requestedAppId) {
500
+ assertCurrentApp(appId, requestedAppId);
501
+ return apps.build(appId);
502
+ },
503
+ async publish(requestedAppId, options) {
504
+ assertCurrentApp(appId, requestedAppId);
505
+ return apps.publish(appId, options);
506
+ },
507
+ async getDeploy(requestedAppId, deployId) {
508
+ assertCurrentApp(appId, requestedAppId);
509
+ return apps.getDeploy(appId, deployId);
510
+ },
511
+ async getCurrentDeploy(requestedAppId) {
512
+ assertCurrentApp(appId, requestedAppId);
513
+ return apps.getCurrentDeploy(appId);
514
+ },
515
+ async cancelBuild(requestedAppId, deployId) {
516
+ assertCurrentApp(appId, requestedAppId);
517
+ return apps.cancelBuild(appId, deployId);
518
+ },
519
+ async rollback(requestedAppId, targetVersionId) {
520
+ assertCurrentApp(appId, requestedAppId);
521
+ return apps.rollback(appId, targetVersionId);
522
+ },
523
+ async listDeploys(requestedAppId, options) {
524
+ assertCurrentApp(appId, requestedAppId);
525
+ return apps.listDeploys(appId, options);
526
+ },
527
+ async listVersions(requestedAppId, options) {
528
+ assertCurrentApp(appId, requestedAppId);
529
+ return apps.listVersions(appId, options);
530
+ }
531
+ };
532
+ return {
533
+ apps: scoped,
534
+ currentApp: {
535
+ get: (options) => scoped.get(appId, options),
536
+ delete: () => scoped.delete(appId),
537
+ update: (input) => scoped.update(appId, input),
538
+ getFiles: () => scoped.getFiles(appId),
539
+ replaceFiles: (files) => scoped.replaceFiles(appId, files),
540
+ mergeFiles: (files) => scoped.mergeFiles(appId, files),
541
+ build: () => scoped.build(appId),
542
+ publish: (options) => scoped.publish(appId, options),
543
+ getDeploy: (deployId) => scoped.getDeploy(appId, deployId),
544
+ getCurrentDeploy: () => scoped.getCurrentDeploy(appId),
545
+ cancelBuild: (deployId) => scoped.cancelBuild(appId, deployId),
546
+ rollback: (targetVersionId) => scoped.rollback(appId, targetVersionId),
547
+ listDeploys: (options) => scoped.listDeploys(appId, options),
548
+ listVersions: (options) => scoped.listVersions(appId, options)
549
+ }
550
+ };
551
+ }
552
+
553
+ // src/config.ts
554
+ function readDefaultEnvironment() {
555
+ return typeof process === "undefined" ? {} : process.env;
556
+ }
557
+ function requiredValue(value, name) {
558
+ if (!value?.trim()) {
559
+ throw new MitraConfigurationError(`${name} is required`);
560
+ }
561
+ return value.trim();
562
+ }
563
+ function removeTrailingSlashes(value) {
564
+ let end = value.length;
565
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
566
+ return value.slice(0, end);
567
+ }
568
+ function normalizeApiUrl(value) {
569
+ let parsed;
570
+ try {
571
+ parsed = new URL(value);
572
+ } catch {
573
+ throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
574
+ }
575
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
576
+ throw new MitraConfigurationError("apiUrl must be a valid HTTP or HTTPS URL");
577
+ }
578
+ if (parsed.username || parsed.password || parsed.search || parsed.hash || value.includes("?") || value.includes("#")) {
579
+ throw new MitraConfigurationError(
580
+ "apiUrl must not include credentials, query parameters, or a fragment"
581
+ );
582
+ }
583
+ return removeTrailingSlashes(parsed.toString());
584
+ }
585
+ function deriveNativeApiUrl(legacyBaseUrl) {
586
+ if (legacyBaseUrl === void 0) return void 0;
587
+ const parsed = new URL(normalizeApiUrl(legacyBaseUrl));
588
+ parsed.pathname = parsed.pathname.replace(/\/legacy\/?$/, "") || "/";
589
+ return removeTrailingSlashes(parsed.toString());
590
+ }
591
+ function resolveConfig(config = {}, environment = readDefaultEnvironment()) {
592
+ const apiUrl = normalizeApiUrl(
593
+ requiredValue(
594
+ config.apiUrl ?? environment.MITRA_API_URL ?? deriveNativeApiUrl(environment.MITRA_BASE_URL),
595
+ "apiUrl"
596
+ )
597
+ );
598
+ const accessToken = requiredValue(
599
+ config.accessToken ?? environment.MITRA_PLATFORM_ACCESS_TOKEN ?? environment.MITRA_TOKEN,
600
+ "accessToken"
601
+ );
602
+ const appId = requiredValue(
603
+ config.appId ?? environment.MITRA_APP_ID ?? environment.MITRA_PROJECT_ID,
604
+ "appId"
605
+ );
606
+ const timeoutMs = config.timeoutMs;
607
+ const fetchImplementation = config.fetch ?? globalThis.fetch;
608
+ if (timeoutMs !== void 0 && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
609
+ throw new MitraConfigurationError("timeoutMs must be a positive number");
610
+ }
611
+ if (typeof fetchImplementation !== "function") {
612
+ throw new MitraConfigurationError("A fetch implementation is required");
613
+ }
614
+ const dataSourceId = config.dataSourceId ?? environment.MITRA_DATA_SOURCE_ID;
615
+ if (dataSourceId !== void 0 && !dataSourceId.trim()) {
616
+ throw new MitraConfigurationError("dataSourceId must not be empty when provided");
617
+ }
618
+ return {
619
+ apiUrl,
620
+ legacyBaseUrl: normalizeApiUrl(config.legacyBaseUrl ?? environment.MITRA_BASE_URL ?? apiUrl),
621
+ accessToken,
622
+ appId,
623
+ ...dataSourceId === void 0 ? {} : { dataSourceId: dataSourceId.trim() },
624
+ ...timeoutMs === void 0 ? {} : { timeoutMs },
625
+ fetch: fetchImplementation
626
+ };
627
+ }
628
+
629
+ // src/legacy/configure.ts
630
+ var import_mitra_sdk = require("mitra-sdk");
631
+ function configureLegacySdk(config) {
632
+ (0, import_mitra_sdk.configureSdkMitra)({
633
+ baseURL: config.legacyBaseUrl,
634
+ token: config.accessToken,
635
+ projectId: config.appId
636
+ });
637
+ }
638
+
246
639
  // src/client.ts
247
640
  var coreErrors = {
248
641
  configuration: (message) => new MitraConfigurationError(message),
249
642
  invalidResponse: (message) => new MitraApiError(message, 200, { code: "INVALID_RESPONSE", retryable: false })
250
643
  };
251
644
  var DefaultMitraClient = class {
645
+ agentConnections;
646
+ agentCredentials;
647
+ agents;
648
+ agentTasks;
649
+ apps;
252
650
  auth;
651
+ context;
652
+ currentApp;
653
+ customQueries;
654
+ dataSources;
253
655
  entities;
254
656
  functions;
657
+ functionsAdmin;
658
+ imports;
255
659
  integration;
660
+ integrationAdmin;
661
+ integrationResources;
662
+ integrationTemplates;
663
+ members;
664
+ messenger;
665
+ publicFunctions;
256
666
  queries;
667
+ schema;
668
+ sql;
669
+ workflows;
257
670
  #dataSourceId;
258
671
  #initPromise;
259
672
  #appId;
@@ -263,27 +676,78 @@ var DefaultMitraClient = class {
263
676
  this.#dataSourceId = config.dataSourceId;
264
677
  const httpClient = (service) => new HttpClient({
265
678
  baseUrl: `${config.apiUrl}/${service}`,
679
+ authentication: "bearer",
266
680
  accessToken: config.accessToken,
267
681
  appId: config.appId,
268
- timeoutMs: config.timeoutMs,
682
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
269
683
  fetch: config.fetch
270
684
  });
271
- const core = (0, import_sdk_core.createSdkCore)({
685
+ const core = (0, import_sdk_core2.createSdkCore)({
272
686
  transports: {
273
687
  auth: httpClient("iam"),
688
+ codeStudio: httpClient("code-studio"),
689
+ copilot: httpClient("copilot"),
274
690
  dataManager: httpClient("data-manager"),
275
691
  functions: httpClient("functions"),
276
- integration: httpClient("integration")
692
+ integration: httpClient("integration"),
693
+ messenger: httpClient("messenger"),
694
+ publicFunctions: new HttpClient({
695
+ baseUrl: `${config.apiUrl}/functions`,
696
+ authentication: "anonymous",
697
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
698
+ fetch: config.fetch
699
+ })
277
700
  },
278
- getDataSourceId: () => this.#dataSourceId,
701
+ getAppId: () => this.#appId,
279
702
  functions: { executeInvocationType: "sync", emptyInput: "empty-object" },
280
703
  errors: coreErrors
281
704
  });
705
+ const appModules = createAppScopedAppsModule(core.apps, this.#appId);
706
+ this.agentConnections = core.agentConnections;
707
+ this.agentCredentials = core.agentCredentials;
708
+ this.agents = core.agents;
709
+ const agentSessionManager = (0, import_sdk_core2.createAgentTaskSessionManager)({
710
+ tasks: core.agentTasks,
711
+ eventSource: new AgentTaskSseEventSource({
712
+ baseUrl: `${config.apiUrl}/copilot`,
713
+ accessToken: config.accessToken,
714
+ appId: config.appId,
715
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
716
+ fetch: config.fetch,
717
+ errors: coreErrors
718
+ })
719
+ });
720
+ this.agentTasks = (0, import_sdk_core2.withAgentTaskSessions)(core.agentTasks, {
721
+ session: (options) => {
722
+ if (options.transport === "websocket") {
723
+ throw new MitraConfigurationError(
724
+ "WebSocket Agent sessions are not available in the Functions runtime; use http or auto"
725
+ );
726
+ }
727
+ return agentSessionManager.session(options);
728
+ }
729
+ });
730
+ this.apps = appModules.apps;
282
731
  this.auth = core.auth;
732
+ this.context = core.context;
733
+ this.currentApp = appModules.currentApp;
734
+ this.customQueries = core.customQueries;
735
+ this.dataSources = core.dataSources;
283
736
  this.entities = core.entities;
284
737
  this.functions = core.functions;
738
+ this.functionsAdmin = core.functionsAdmin;
739
+ this.imports = core.imports;
285
740
  this.integration = core.integration;
741
+ this.integrationAdmin = core.integrationAdmin;
742
+ this.integrationResources = core.integrationResources;
743
+ this.integrationTemplates = core.integrationTemplates;
744
+ this.members = core.members;
745
+ this.messenger = core.messenger;
746
+ this.publicFunctions = core.publicFunctions;
286
747
  this.queries = core.queries;
748
+ this.schema = core.schema;
749
+ this.sql = core.sql;
750
+ this.workflows = core.workflows;
287
751
  this.#codeStudioHttpClient = httpClient("code-studio");
288
752
  }
289
753
  init() {
@@ -297,14 +761,15 @@ var DefaultMitraClient = class {
297
761
  return this.#initPromise;
298
762
  }
299
763
  async resolveDataSourceId() {
300
- const appInfo = (0, import_sdk_core.expectObject)(
764
+ const appInfo = (0, import_sdk_core2.expectObject)(
301
765
  await this.#codeStudioHttpClient.get(
302
- `/api/v1/apps/${(0, import_sdk_core.encodePathSegment)(this.#appId, "appId", coreErrors)}/info`
766
+ `/api/v1/apps/${(0, import_sdk_core2.encodePathSegment)(this.#appId, "appId", coreErrors)}/info`
303
767
  ),
304
768
  "App info response",
305
769
  coreErrors
306
770
  );
307
- if (!appInfo.dataSourceId?.trim()) {
771
+ if (appInfo.dataSourceId === null) return;
772
+ if (typeof appInfo.dataSourceId !== "string" || !appInfo.dataSourceId.trim()) {
308
773
  throw new MitraApiError("The app info response does not include a dataSourceId", 200, {
309
774
  code: "INVALID_RESPONSE",
310
775
  retryable: false
@@ -313,16 +778,149 @@ var DefaultMitraClient = class {
313
778
  this.#dataSourceId = appInfo.dataSourceId;
314
779
  }
315
780
  };
781
+ function createConfiguredClient(config) {
782
+ configureLegacySdk(config);
783
+ return new DefaultMitraClient(config);
784
+ }
316
785
  function createClient(config = {}) {
317
- return new DefaultMitraClient(resolveConfig(config));
786
+ return createConfiguredClient(resolveConfig(config));
318
787
  }
319
788
  function createClientFromEnvironment(environment) {
320
- return new DefaultMitraClient(resolveConfig({}, environment));
789
+ return createConfiguredClient(resolveConfig({}, environment));
321
790
  }
791
+
792
+ // src/index.ts
793
+ var import_sdk_core3 = require("@mitralab.io/sdk-core");
794
+
795
+ // src/legacy/index.ts
796
+ var legacy = __toESM(require("mitra-sdk"), 1);
797
+ var configureSdkMitra3 = legacy.configureSdkMitra;
798
+ var createMitraSdkInstance2 = legacy.createMitraSdkInstance;
799
+ var resolveProjectId2 = legacy.resolveProjectId;
800
+ var createRecordMitra2 = legacy.createRecordMitra;
801
+ var createRecordsBatchMitra2 = legacy.createRecordsBatchMitra;
802
+ var getRecordMitra2 = legacy.getRecordMitra;
803
+ var listRecordsMitra2 = legacy.listRecordsMitra;
804
+ var updateRecordMitra2 = legacy.updateRecordMitra;
805
+ var patchRecordMitra2 = legacy.patchRecordMitra;
806
+ var deleteRecordMitra2 = legacy.deleteRecordMitra;
807
+ var executeServerFunctionMitra2 = legacy.executeServerFunctionMitra;
808
+ var executeServerFunctionAsyncMitra2 = legacy.executeServerFunctionAsyncMitra;
809
+ var getServerFunctionExecutionMitra2 = legacy.getServerFunctionExecutionMitra;
810
+ var stopServerFunctionExecutionMitra2 = legacy.stopServerFunctionExecutionMitra;
811
+ var executePublicServerFunctionAsyncMitra2 = legacy.executePublicServerFunctionAsyncMitra;
812
+ var callIntegrationMitra2 = legacy.callIntegrationMitra;
813
+ var listIntegrationsMitra2 = legacy.listIntegrationsMitra;
814
+ var getProjectsMitra2 = legacy.getProjectsMitra;
815
+ var getProjectContextMitra2 = legacy.getProjectContextMitra;
816
+ var listProjectsMitra2 = legacy.listProjectsMitra;
817
+ var createProjectMitra2 = legacy.createProjectMitra;
818
+ var updateProjectSettingsMitra2 = legacy.updateProjectSettingsMitra;
819
+ var getGitConfigMitra2 = legacy.getGitConfigMitra;
820
+ var createJdbcConnectionMitra2 = legacy.createJdbcConnectionMitra;
821
+ var listJdbcConnectionsMitra2 = legacy.listJdbcConnectionsMitra;
822
+ var updateJdbcConnectionMitra2 = legacy.updateJdbcConnectionMitra;
823
+ var deleteJdbcConnectionMitra2 = legacy.deleteJdbcConnectionMitra;
824
+ var runQueryMitra2 = legacy.runQueryMitra;
825
+ var runDdlMitra2 = legacy.runDdlMitra;
826
+ var runDmlMitra2 = legacy.runDmlMitra;
827
+ var listTablesMitra2 = legacy.listTablesMitra;
828
+ var createOnlineTableMitra2 = legacy.createOnlineTableMitra;
829
+ var listOnlineTablesMitra2 = legacy.listOnlineTablesMitra;
830
+ var updateOnlineTableMitra2 = legacy.updateOnlineTableMitra;
831
+ var deleteOnlineTableMitra2 = legacy.deleteOnlineTableMitra;
832
+ var createServerFunctionMitra2 = legacy.createServerFunctionMitra;
833
+ var readServerFunctionMitra2 = legacy.readServerFunctionMitra;
834
+ var listServerFunctionsMitra2 = legacy.listServerFunctionsMitra;
835
+ var updateServerFunctionMitra2 = legacy.updateServerFunctionMitra;
836
+ var deleteServerFunctionMitra2 = legacy.deleteServerFunctionMitra;
837
+ var togglePublicExecutionMitra2 = legacy.togglePublicExecutionMitra;
838
+ var createIntegrationMitra2 = legacy.createIntegrationMitra;
839
+ var updateIntegrationMitra2 = legacy.updateIntegrationMitra;
840
+ var deleteIntegrationMitra2 = legacy.deleteIntegrationMitra;
841
+ var testIntegrationMitra2 = legacy.testIntegrationMitra;
842
+ var testIntegrationByIdMitra2 = legacy.testIntegrationByIdMitra;
843
+ var listIntegrationTemplatesMitra2 = legacy.listIntegrationTemplatesMitra;
844
+ var getIntegrationTemplateMitra2 = legacy.getIntegrationTemplateMitra;
845
+ var createAgentMitra2 = legacy.createAgentMitra;
846
+ var readAgentMitra2 = legacy.readAgentMitra;
847
+ var listAgentsMitra2 = legacy.listAgentsMitra;
848
+ var updateAgentMitra2 = legacy.updateAgentMitra;
849
+ var deleteAgentMitra2 = legacy.deleteAgentMitra;
850
+ var getAgentTaskMitra2 = legacy.getAgentTaskMitra;
851
+ var manageAgentChatMitra2 = legacy.manageAgentChatMitra;
852
+ var manageAgentCredentialMitra2 = legacy.manageAgentCredentialMitra;
853
+ var manageAgentConnectionMitra2 = legacy.manageAgentConnectionMitra;
854
+ var inviteUserMitra2 = legacy.inviteUserMitra;
855
+ var unsubscribeUserMitra2 = legacy.unsubscribeUserMitra;
856
+ var deployToS3Mitra2 = legacy.deployToS3Mitra;
857
+ var getDeployStatusMitra2 = legacy.getDeployStatusMitra;
322
858
  // Annotate the CommonJS export names for ESM import in node:
323
859
  0 && (module.exports = {
860
+ AgentTaskTurnError,
324
861
  MitraApiError,
325
862
  MitraConfigurationError,
863
+ callIntegrationMitra,
864
+ configureSdkMitra,
865
+ createAgentMitra,
326
866
  createClient,
327
- createClientFromEnvironment
867
+ createClientFromEnvironment,
868
+ createIntegrationMitra,
869
+ createJdbcConnectionMitra,
870
+ createMitraSdkInstance,
871
+ createOnlineTableMitra,
872
+ createProjectMitra,
873
+ createRecordMitra,
874
+ createRecordsBatchMitra,
875
+ createServerFunctionMitra,
876
+ deleteAgentMitra,
877
+ deleteIntegrationMitra,
878
+ deleteJdbcConnectionMitra,
879
+ deleteOnlineTableMitra,
880
+ deleteRecordMitra,
881
+ deleteServerFunctionMitra,
882
+ deployToS3Mitra,
883
+ executePublicServerFunctionAsyncMitra,
884
+ executeServerFunctionAsyncMitra,
885
+ executeServerFunctionMitra,
886
+ getAgentTaskMitra,
887
+ getDeployStatusMitra,
888
+ getGitConfigMitra,
889
+ getIntegrationTemplateMitra,
890
+ getProjectContextMitra,
891
+ getProjectsMitra,
892
+ getRecordMitra,
893
+ getServerFunctionExecutionMitra,
894
+ inviteUserMitra,
895
+ listAgentsMitra,
896
+ listIntegrationTemplatesMitra,
897
+ listIntegrationsMitra,
898
+ listJdbcConnectionsMitra,
899
+ listOnlineTablesMitra,
900
+ listProjectsMitra,
901
+ listRecordsMitra,
902
+ listServerFunctionsMitra,
903
+ listTablesMitra,
904
+ manageAgentChatMitra,
905
+ manageAgentConnectionMitra,
906
+ manageAgentCredentialMitra,
907
+ patchRecordMitra,
908
+ readAgentMitra,
909
+ readServerFunctionMitra,
910
+ resolveProjectId,
911
+ runDdlMitra,
912
+ runDmlMitra,
913
+ runQueryMitra,
914
+ stopServerFunctionExecutionMitra,
915
+ testIntegrationByIdMitra,
916
+ testIntegrationMitra,
917
+ togglePublicExecutionMitra,
918
+ unsubscribeUserMitra,
919
+ updateAgentMitra,
920
+ updateIntegrationMitra,
921
+ updateJdbcConnectionMitra,
922
+ updateOnlineTableMitra,
923
+ updateProjectSettingsMitra,
924
+ updateRecordMitra,
925
+ updateServerFunctionMitra
328
926
  });