mitra-interactions-sdk 1.0.60-beta.2 → 1.0.60-beta.21

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
@@ -107,9 +107,6 @@ async function doLogin(method, options) {
107
107
  autoConfigureFromLogin(response, authUrl, projectId);
108
108
  return response;
109
109
  }
110
- async function loginWithEmailMitra(options) {
111
- return doLogin("email", options);
112
- }
113
110
  async function loginWithGoogleMitra(options) {
114
111
  return doLogin("google", options);
115
112
  }
@@ -163,102 +160,12 @@ async function refreshTokenSilently(authUrl, projectId) {
163
160
  })();
164
161
  return _refreshPromise;
165
162
  }
166
- var SILENT_TIMEOUT_MS = 2e4;
167
- var AUTH_READY_TYPE = "mitra-auth-ready";
168
- var AUTH_CREDENTIALS_TYPE = "mitra-auth-credentials";
169
- function openSilentAuthIframe(authUrl, projectId, credentials) {
170
- return new Promise((resolve, reject) => {
171
- const origin = getOriginFromUrl(authUrl);
172
- const base = authUrl.endsWith("/") ? authUrl : authUrl + "/";
173
- const separator = base.includes("?") ? "&" : "?";
174
- let url = `${base}${separator}mode=silent&projectId=${encodeURIComponent(projectId)}`;
175
- if (typeof window !== "undefined") {
176
- url += `&originUrl=${encodeURIComponent(window.location.href)}`;
177
- }
178
- const iframe = document.createElement("iframe");
179
- iframe.style.display = "none";
180
- const timer = setTimeout(() => {
181
- cleanup();
182
- reject(new Error("Timeout na autentica\xE7\xE3o silenciosa"));
183
- }, SILENT_TIMEOUT_MS);
184
- function onMessage(event) {
185
- var _a, _b, _c;
186
- if (event.origin !== origin) return;
187
- if (((_a = event.data) == null ? void 0 : _a.type) === AUTH_READY_TYPE) {
188
- (_b = iframe.contentWindow) == null ? void 0 : _b.postMessage({
189
- type: AUTH_CREDENTIALS_TYPE,
190
- ...credentials
191
- }, origin);
192
- return;
193
- }
194
- if (((_c = event.data) == null ? void 0 : _c.type) !== AUTH_MESSAGE_TYPE) return;
195
- cleanup();
196
- if (event.data.success) {
197
- resolve(event.data.data);
198
- } else {
199
- reject(new Error(event.data.error || "Erro na autentica\xE7\xE3o"));
200
- }
201
- }
202
- function cleanup() {
203
- window.removeEventListener("message", onMessage);
204
- clearTimeout(timer);
205
- if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
206
- }
207
- window.addEventListener("message", onMessage);
208
- iframe.src = url;
209
- document.body.appendChild(iframe);
210
- });
211
- }
212
- async function emailSignupMitra(options) {
213
- const { authUrl, projectId } = resolveLoginOptions(options);
214
- const result = await openSilentAuthIframe(authUrl, projectId, {
215
- action: "signup",
216
- name: options.name,
217
- email: options.email,
218
- password: options.password
219
- });
220
- if (!result.needsVerification) {
221
- throw new Error("Resposta inesperada do signup");
222
- }
223
- }
224
- async function emailVerifyCodeMitra(options) {
225
- const { authUrl, projectId } = resolveLoginOptions(options);
226
- const response = await openSilentAuthIframe(authUrl, projectId, {
227
- action: "verifyCode",
228
- email: options.email,
229
- code: options.code,
230
- password: options.password
231
- });
232
- autoConfigureFromLogin(response, authUrl, projectId);
233
- return response;
234
- }
235
- async function emailResendCodeMitra(options) {
236
- const { authUrl, projectId } = resolveLoginOptions(options);
237
- await openSilentAuthIframe(authUrl, projectId, {
238
- action: "resendCode",
239
- email: options.email
240
- });
241
- }
242
- async function emailLoginMitra(options) {
243
- const { authUrl, projectId } = resolveLoginOptions(options);
244
- const response = await openSilentAuthIframe(authUrl, projectId, {
245
- action: "login",
246
- email: options.email,
247
- password: options.password
248
- });
249
- autoConfigureFromLogin(response, authUrl, projectId);
250
- return response;
251
- }
252
163
 
253
164
  // src/auth-new.ts
254
165
  function getFetch() {
255
166
  if (typeof globalThis.fetch === "function") return globalThis.fetch;
256
167
  throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
257
168
  }
258
- function buildEndpoint(authUrl, path) {
259
- const base = authUrl.replace(/\/+$/, "");
260
- return `${base}/iam/api/v1/auth${path}`;
261
- }
262
169
  function buildBffAuthEndpoint(gateway, path) {
263
170
  const base = gateway.replace(/\/+$/, "");
264
171
  return `${base}/auth${path}`;
@@ -287,25 +194,6 @@ function autoConfigureFromLogin2(response, authUrl, projectId) {
287
194
  ...response.integrationURL ? { integrationURL: response.integrationURL } : {}
288
195
  });
289
196
  }
290
- async function postNewAuth(url, body) {
291
- const fetchFn = getFetch();
292
- const response = await fetchFn(url, {
293
- method: "POST",
294
- headers: { "Content-Type": "application/json" },
295
- body: JSON.stringify(body)
296
- });
297
- if (!response.ok) {
298
- const text = await response.text().catch(() => "");
299
- let parsed = null;
300
- try {
301
- parsed = text ? JSON.parse(text) : null;
302
- } catch (e) {
303
- }
304
- const msg = (parsed == null ? void 0 : parsed.message) || (parsed == null ? void 0 : parsed.error) || `HTTP ${response.status}`;
305
- throw { message: msg, status: response.status, details: parsed };
306
- }
307
- return response.json();
308
- }
309
197
  async function postBffAuth(url, body) {
310
198
  const fetchFn = getFetch();
311
199
  const response = await fetchFn(url, {
@@ -313,18 +201,14 @@ async function postBffAuth(url, body) {
313
201
  headers: { "Content-Type": "application/json" },
314
202
  body: JSON.stringify(body)
315
203
  });
204
+ const text = await response.text().catch(() => "");
205
+ const { data, isJson } = parseBody(text);
316
206
  if (!response.ok) {
317
- const text2 = await response.text().catch(() => "");
318
- let parsed = null;
319
- try {
320
- parsed = text2 ? JSON.parse(text2) : null;
321
- } catch (e) {
322
- }
323
- const msg = (parsed == null ? void 0 : parsed.message) || (parsed == null ? void 0 : parsed.error) || `HTTP ${response.status}`;
324
- throw { message: msg, status: response.status, details: parsed };
207
+ const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
208
+ const msg = isJson && ((data == null ? void 0 : data.message) || (data == null ? void 0 : data.error)) || fallback;
209
+ throw { message: msg, status: response.status, details: data };
325
210
  }
326
- const text = await response.text().catch(() => "");
327
- return text ? JSON.parse(text) : null;
211
+ return data;
328
212
  }
329
213
  function normalizeResponse(tokens, authUrl) {
330
214
  return {
@@ -333,21 +217,89 @@ function normalizeResponse(tokens, authUrl) {
333
217
  baseURL: authUrl
334
218
  };
335
219
  }
336
- var NOT_SUPPORTED_POPUP = 'Login via popup (loginWithEmailMitra/loginMitra com method "email" ou "mitra") ainda n\xE3o suportado no novo Mitra. Use emailLoginMitra({ email, password }).';
337
- var NOT_SUPPORTED_VERIFY = "emailVerifyCodeMitra n\xE3o existe no novo Mitra (signup \xE9 direto, sem c\xF3digo de verifica\xE7\xE3o).";
338
- var NOT_SUPPORTED_RESEND = "emailResendCodeMitra n\xE3o existe no novo Mitra.";
339
- var NOT_SUPPORTED_REDIRECT = 'mode "redirect" ainda n\xE3o suportado no novo Mitra para SSO. Use mode "popup" (default).';
220
+ var NOT_SUPPORTED_POPUP = 'loginMitra com method "email" ou "mitra" n\xE3o \xE9 suportado no novo Mitra. Use SSO (loginWithGoogleMitra).';
340
221
  var OAUTH_RESULT_TYPE = "mitra-oauth-result";
341
222
  var POPUP_W = 480;
342
223
  var POPUP_H = 600;
343
224
  var POPUP_TIMEOUT_MS = 5 * 60 * 1e3;
344
- var SSO_AUTH_PAGE_URL = "https://d2by6yrxhbu2rl.cloudfront.net/sdk-auth.html";
345
- async function fetchSsoAuthPageUrl(_baseURL) {
346
- return SSO_AUTH_PAGE_URL;
225
+ var SSO_AUTH_PAGE_URL = "https://stg.mitralab.io/sdk-auth.html";
226
+ async function fetchSsoAuthPageUrl(gatewayUrl) {
227
+ const config = isConfigured() ? getConfig() : null;
228
+ if (config == null ? void 0 : config.authPageUrl) return config.authPageUrl;
229
+ try {
230
+ return `${new URL(gatewayUrl).origin}/sdk-auth.html`;
231
+ } catch (e) {
232
+ return SSO_AUTH_PAGE_URL;
233
+ }
234
+ }
235
+ var SSO_ENABLED_PROVIDERS = ["google"];
236
+ function providerLabel(provider) {
237
+ return provider === "microsoft" ? "Microsoft" : provider === "google" ? "Google" : provider;
238
+ }
239
+ function assertProviderAvailable(provider) {
240
+ if (!SSO_ENABLED_PROVIDERS.includes(provider)) {
241
+ throw new Error(`Login com ${providerLabel(provider)} ainda n\xE3o dispon\xEDvel no novo Mitra.`);
242
+ }
243
+ }
244
+ function stripToOriginPath(url) {
245
+ try {
246
+ const u = new URL(url);
247
+ return u.origin + u.pathname;
248
+ } catch (e) {
249
+ return url.split("?")[0].split("#")[0];
250
+ }
251
+ }
252
+ async function exchangeSsoCode(authUrl, provider, code, redirectUri, projectId) {
253
+ const data = await postBffAuth(buildBffAuthEndpoint(authUrl, `/${provider}`), {
254
+ appId: String(projectId),
255
+ code,
256
+ redirectUri
257
+ });
258
+ const response = {
259
+ token: data.token,
260
+ // baseURL = authUrl (gateway); o BFF não devolve URLs de bootstrap.
261
+ baseURL: authUrl,
262
+ ...data.refreshToken ? { refreshToken: data.refreshToken } : {}
263
+ };
264
+ autoConfigureFromLogin2(response, authUrl, projectId);
265
+ return response;
266
+ }
267
+ var SSO_REDIRECT_STORE_KEY = "mitra_sso_redirect";
268
+ function persistRedirectContext(ctx) {
269
+ try {
270
+ sessionStorage.setItem(SSO_REDIRECT_STORE_KEY, JSON.stringify(ctx));
271
+ } catch (e) {
272
+ }
273
+ }
274
+ function readRedirectContext() {
275
+ try {
276
+ const raw = sessionStorage.getItem(SSO_REDIRECT_STORE_KEY);
277
+ return raw ? JSON.parse(raw) : null;
278
+ } catch (e) {
279
+ return null;
280
+ }
281
+ }
282
+ function clearRedirectContext() {
283
+ try {
284
+ sessionStorage.removeItem(SSO_REDIRECT_STORE_KEY);
285
+ } catch (e) {
286
+ }
347
287
  }
348
- function buildStartUrl(authPageUrl, provider, state, appId, apiUrl) {
288
+ function buildStartUrl(authPageUrl, provider, state, appId, apiUrl, returnTo) {
349
289
  const sep = authPageUrl.includes("?") ? "&" : "?";
350
- return authPageUrl + sep + new URLSearchParams({ provider, state, appId, apiUrl }).toString();
290
+ const query = {
291
+ provider,
292
+ state,
293
+ appId,
294
+ apiUrl,
295
+ // origin = origin desta SDK; a página trava o postMessage do result nela.
296
+ origin: window.location.origin,
297
+ // Contrato novo: a página NÃO troca mais o code — devolve o code cru (popup
298
+ // via postMessage, redirect via #codeMitra). A SDK troca no BFF /auth/{provider}.
299
+ responseType: "code"
300
+ };
301
+ if (returnTo) query.returnTo = returnTo;
302
+ return authPageUrl + sep + new URLSearchParams(query).toString();
351
303
  }
352
304
  function getOriginFromUrl2(url) {
353
305
  try {
@@ -404,11 +356,11 @@ function openOAuthPopup(providerUrl, expectedOrigin, expectedState) {
404
356
  reject(new Error(data.error || "Erro na autentica\xE7\xE3o OAuth."));
405
357
  return;
406
358
  }
407
- if (!data.code) {
408
- reject(new Error("Resposta OAuth sem code."));
359
+ if (!data.code && !data.token) {
360
+ reject(new Error("Resposta OAuth sem code nem token."));
409
361
  return;
410
362
  }
411
- resolve({ code: data.code });
363
+ resolve({ code: data.code, token: data.token });
412
364
  }
413
365
  function cleanup() {
414
366
  clearTimeout(timer);
@@ -421,13 +373,14 @@ function openOAuthPopup(providerUrl, expectedOrigin, expectedState) {
421
373
  }
422
374
  var _oauthInFlight = null;
423
375
  async function loginWithProvider(provider, options) {
424
- if (_oauthInFlight) return _oauthInFlight;
376
+ assertProviderAvailable(provider);
425
377
  if (typeof window === "undefined") {
426
378
  throw new Error("SSO s\xF3 funciona em ambiente browser.");
427
379
  }
428
380
  if ((options == null ? void 0 : options.mode) === "redirect") {
429
- throw new Error(NOT_SUPPORTED_REDIRECT);
381
+ return startSsoRedirect(provider, options);
430
382
  }
383
+ if (_oauthInFlight) return _oauthInFlight;
431
384
  _oauthInFlight = (async () => {
432
385
  try {
433
386
  const { authUrl, projectId } = resolveLoginOptions2(options);
@@ -435,15 +388,13 @@ async function loginWithProvider(provider, options) {
435
388
  const appId = String(projectId);
436
389
  const authPageUrl = await fetchSsoAuthPageUrl(authUrl);
437
390
  const pageOrigin = getOriginFromUrl2(authPageUrl);
438
- const redirectUri = authPageUrl;
391
+ const redirectUri = stripToOriginPath(authPageUrl);
439
392
  const startUrl = buildStartUrl(authPageUrl, provider, state, appId, authUrl);
440
- const { code } = await openOAuthPopup(startUrl, pageOrigin, state);
441
- const tokens = await postNewAuth(buildEndpoint(authUrl, `/${provider}`), {
442
- code,
443
- redirectUri,
444
- appId
445
- });
446
- const response = normalizeResponse(tokens, authUrl);
393
+ const { code, token } = await openOAuthPopup(startUrl, pageOrigin, state);
394
+ if (code) {
395
+ return await exchangeSsoCode(authUrl, provider, code, redirectUri, projectId);
396
+ }
397
+ const response = normalizeResponse(token, authUrl);
447
398
  autoConfigureFromLogin2(response, authUrl, projectId);
448
399
  return response;
449
400
  } finally {
@@ -452,8 +403,25 @@ async function loginWithProvider(provider, options) {
452
403
  })();
453
404
  return _oauthInFlight;
454
405
  }
455
- async function loginWithEmailMitra2(_options) {
456
- throw new Error(NOT_SUPPORTED_POPUP);
406
+ async function startSsoRedirect(provider, options) {
407
+ const { authUrl, projectId } = resolveLoginOptions2(options);
408
+ const state = generateState();
409
+ const appId = String(projectId);
410
+ const authPageUrl = await fetchSsoAuthPageUrl(authUrl);
411
+ const redirectUri = stripToOriginPath(authPageUrl);
412
+ persistRedirectContext({ state, provider, authUrl, projectId: appId, redirectUri });
413
+ const startUrl = buildStartUrl(authPageUrl, provider, state, appId, authUrl, window.location.href);
414
+ window.location.assign(startUrl);
415
+ return new Promise(() => {
416
+ });
417
+ }
418
+ async function exchangeSsoCodeMitra(options) {
419
+ const ctx = readRedirectContext();
420
+ clearRedirectContext();
421
+ if (!ctx || ctx.state !== options.state) {
422
+ throw new Error("State inv\xE1lido no retorno do SSO (poss\xEDvel CSRF).");
423
+ }
424
+ return exchangeSsoCode(ctx.authUrl, ctx.provider, options.code, ctx.redirectUri, ctx.projectId);
457
425
  }
458
426
  async function loginWithGoogleMitra2(options) {
459
427
  return loginWithProvider("google", options);
@@ -466,36 +434,6 @@ async function loginMitra2(method, options) {
466
434
  if (method === "microsoft") return loginWithProvider("microsoft", options);
467
435
  throw new Error(NOT_SUPPORTED_POPUP);
468
436
  }
469
- async function emailLoginMitra2(options) {
470
- const { authUrl, projectId } = resolveLoginOptions2(options);
471
- const data = await postBffAuth(buildBffAuthEndpoint(authUrl, "/email/login"), {
472
- projectId: String(projectId),
473
- email: options.email,
474
- password: options.password
475
- });
476
- const response = {
477
- token: data.token,
478
- baseURL: data.baseURL || authUrl,
479
- ...data.integrationURL ? { integrationURL: data.integrationURL } : {}
480
- };
481
- autoConfigureFromLogin2(response, authUrl, projectId);
482
- return response;
483
- }
484
- async function emailSignupMitra2(options) {
485
- const { authUrl, projectId } = resolveLoginOptions2(options);
486
- await postBffAuth(buildBffAuthEndpoint(authUrl, "/email/signup"), {
487
- projectId: String(projectId),
488
- name: options.name,
489
- email: options.email,
490
- password: options.password
491
- });
492
- }
493
- async function emailVerifyCodeMitra2(_options) {
494
- throw new Error(NOT_SUPPORTED_VERIFY);
495
- }
496
- async function emailResendCodeMitra2(_options) {
497
- throw new Error(NOT_SUPPORTED_RESEND);
498
- }
499
437
  var _refreshPromise2 = null;
500
438
  async function refreshTokenSilently2(authUrl, _projectId) {
501
439
  if (_refreshPromise2) return _refreshPromise2;
@@ -504,10 +442,15 @@ async function refreshTokenSilently2(authUrl, _projectId) {
504
442
  const config = isConfigured() ? getConfig() : null;
505
443
  const refreshToken = config == null ? void 0 : config.refreshToken;
506
444
  if (!refreshToken) {
507
- throw new Error("refreshToken n\xE3o dispon\xEDvel para renova\xE7\xE3o no novo Mitra. Fa\xE7a login novamente.");
445
+ throw new Error("refreshToken n\xE3o dispon\xEDvel para renova\xE7\xE3o. Fa\xE7a login novamente.");
508
446
  }
509
- const tokens = await postNewAuth(buildEndpoint(authUrl, "/refresh-token"), { refreshToken });
510
- return normalizeResponse(tokens, authUrl);
447
+ const data = await postBffAuth(buildBffAuthEndpoint(authUrl, "/refresh-token"), { refreshToken });
448
+ return {
449
+ token: data.token,
450
+ // Refresh não muda a base — mantém o authUrl (gateway).
451
+ baseURL: authUrl,
452
+ ...data.refreshToken ? { refreshToken: data.refreshToken } : {}
453
+ };
511
454
  } finally {
512
455
  _refreshPromise2 = null;
513
456
  }
@@ -542,10 +485,6 @@ async function loginMitra3(method, options) {
542
485
  const authUrl = resolveAuthUrlFromOptions(options);
543
486
  return isLegacyAuthUrl(authUrl) ? loginMitra(method, options) : loginMitra2(method, options);
544
487
  }
545
- async function loginWithEmailMitra3(options) {
546
- const authUrl = resolveAuthUrlFromOptions(options);
547
- return isLegacyAuthUrl(authUrl) ? loginWithEmailMitra(options) : loginWithEmailMitra2();
548
- }
549
488
  async function loginWithGoogleMitra3(options) {
550
489
  const authUrl = resolveAuthUrlFromOptions(options);
551
490
  return isLegacyAuthUrl(authUrl) ? loginWithGoogleMitra(options) : loginWithGoogleMitra2(options);
@@ -554,1492 +493,63 @@ async function loginWithMicrosoftMitra3(options) {
554
493
  const authUrl = resolveAuthUrlFromOptions(options);
555
494
  return isLegacyAuthUrl(authUrl) ? loginWithMicrosoftMitra(options) : loginWithMicrosoftMitra2(options);
556
495
  }
557
- async function emailSignupMitra3(options) {
558
- const authUrl = resolveAuthUrlFromOptions(options);
559
- return isLegacyAuthUrl(authUrl) ? emailSignupMitra(options) : emailSignupMitra2(options);
560
- }
561
- async function emailLoginMitra3(options) {
562
- const authUrl = resolveAuthUrlFromOptions(options);
563
- return isLegacyAuthUrl(authUrl) ? emailLoginMitra(options) : emailLoginMitra2(options);
564
- }
565
- async function emailVerifyCodeMitra3(options) {
566
- const authUrl = resolveAuthUrlFromOptions(options);
567
- return isLegacyAuthUrl(authUrl) ? emailVerifyCodeMitra(options) : emailVerifyCodeMitra2();
568
- }
569
- async function emailResendCodeMitra3(options) {
570
- const authUrl = resolveAuthUrlFromOptions(options);
571
- return isLegacyAuthUrl(authUrl) ? emailResendCodeMitra(options) : emailResendCodeMitra2();
572
- }
573
496
  async function refreshTokenSilently3(authUrl, projectId) {
574
497
  return isLegacyAuthUrl(authUrl) ? refreshTokenSilently(authUrl, projectId) : refreshTokenSilently2(authUrl);
575
498
  }
576
-
577
- // src/chat.ts
578
- function openChatMitra() {
579
- if (typeof window === "undefined") return;
580
- const chat = window.__mitraChat;
581
- if (!chat) return;
582
- if (chat.isReady) {
583
- chat.open();
584
- } else {
585
- const iv = setInterval(() => {
586
- if (chat.isReady) {
587
- clearInterval(iv);
588
- chat.open();
589
- }
590
- }, 200);
591
- setTimeout(() => clearInterval(iv), 15e3);
592
- }
593
- }
594
- function closeChatMitra() {
595
- var _a;
596
- if (typeof window === "undefined") return;
597
- (_a = window.__mitraChat) == null ? void 0 : _a.close();
499
+ async function exchangeSsoCodeMitra2(options) {
500
+ return exchangeSsoCodeMitra(options);
598
501
  }
599
502
 
600
- // src/password-reset.ts
601
- var AUTH_API_BY_AUTH_URL = {
602
- "https://coder.mitralab.io/sdk-auth/": "https://api0.mitraecp.com:1005",
603
- "https://agent.mitralab.io/sdk-auth/": "https://api2.mitrasheet.com:4133"
604
- };
605
- function normalizeAuthUrl(url) {
606
- const stripped = url.split("?")[0].split("#")[0];
607
- return stripped.endsWith("/") ? stripped : stripped + "/";
608
- }
609
- var NOT_SUPPORTED_SEND = "sendPasswordResetCodeMitra ainda n\xE3o suportado no novo Mitra.";
610
- var NOT_SUPPORTED_VALIDATE = "validatePasswordResetCodeMitra ainda n\xE3o suportado no novo Mitra.";
611
- var NOT_SUPPORTED_RESET = "resetPasswordMitra ainda n\xE3o suportado no novo Mitra.";
612
- function isNewWorld2(opts) {
613
- var _a;
614
- if (opts.authApiURL) return false;
615
- if (typeof window !== "undefined" && ((_a = window.__mitraEnv) == null ? void 0 : _a.apiBaseURL)) return false;
616
- const authUrl = opts.authUrl || (isConfigured() ? getConfig().authUrl : void 0);
617
- if (!authUrl) return false;
618
- return !(normalizeAuthUrl(authUrl) in AUTH_API_BY_AUTH_URL);
619
- }
620
- function resolveProjectId(opts) {
621
- if (opts.projectId != null) return opts.projectId;
622
- if (isConfigured()) {
623
- const pid = getConfig().projectId;
624
- if (pid != null) return pid;
625
- }
626
- throw new Error(
627
- "projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId })."
628
- );
629
- }
630
- function resolveAuthApiURL(opts) {
631
- var _a;
632
- if (opts.authApiURL) return opts.authApiURL.replace(/\/+$/, "");
633
- if (typeof window !== "undefined") {
634
- const injected = (_a = window.__mitraEnv) == null ? void 0 : _a.apiBaseURL;
635
- if (typeof injected === "string" && injected.length > 0) {
636
- return injected.replace(/\/+$/, "");
637
- }
638
- }
639
- const authUrl = opts.authUrl || (isConfigured() ? getConfig().authUrl : void 0);
640
- if (authUrl) {
641
- const apiURL = AUTH_API_BY_AUTH_URL[normalizeAuthUrl(authUrl)];
642
- if (apiURL) return apiURL;
643
- }
644
- throw new Error(
645
- "N\xE3o foi poss\xEDvel resolver a API base. Configure window.__mitraEnv.apiBaseURL via build-proxy, passe authApiURL nas options, ou use um authUrl conhecido (coder.mitralab.io ou agent.mitralab.io)."
646
- );
503
+ // src/instance.ts
504
+ function formatToken(token) {
505
+ return `Bearer ${stripBearer(token)}`;
647
506
  }
648
507
  function getFetch2() {
649
508
  if (typeof globalThis.fetch === "function") return globalThis.fetch;
650
509
  throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
651
510
  }
652
- async function callAuthApi(url, method, body) {
653
- const fetchFn = getFetch2();
654
- const response = await fetchFn(url, {
655
- method,
656
- headers: { "Content-Type": "application/json", accept: "application/json" },
657
- body: JSON.stringify(body)
658
- });
659
- const text = await response.text();
660
- let data = null;
661
- try {
662
- data = text ? JSON.parse(text) : null;
663
- } catch (e) {
664
- }
665
- if (!response.ok) {
666
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
667
- throw { message: msg, status: response.status, details: data };
668
- }
669
- return data;
670
- }
671
- async function sendPasswordResetCodeMitra(options) {
672
- if (isNewWorld2(options)) throw new Error(NOT_SUPPORTED_SEND);
673
- const apiURL = resolveAuthApiURL(options);
674
- const projectId = resolveProjectId(options);
675
- return callAuthApi(`${apiURL}/mitraspace/auth/resetPassword`, "POST", {
676
- email: options.email,
677
- projectId
678
- });
679
- }
680
- async function validatePasswordResetCodeMitra(options) {
681
- if (isNewWorld2(options)) throw new Error(NOT_SUPPORTED_VALIDATE);
682
- const apiURL = resolveAuthApiURL(options);
683
- const projectId = resolveProjectId(options);
684
- return callAuthApi(`${apiURL}/mitraspace/auth/resetPassword/validateCode`, "POST", {
685
- email: options.email,
686
- code: options.code,
687
- projectId
688
- });
689
- }
690
- async function resetPasswordMitra(options) {
691
- if (isNewWorld2(options)) throw new Error(NOT_SUPPORTED_RESET);
692
- const apiURL = resolveAuthApiURL(options);
693
- const projectId = resolveProjectId(options);
694
- return callAuthApi(`${apiURL}/mitraspace/auth/resetPassword`, "PUT", {
695
- email: options.email,
696
- code: options.code,
697
- newPassword: options.newPassword,
698
- projectId
699
- });
511
+ function buildQuery(params) {
512
+ return Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
700
513
  }
701
-
702
- // src/client.ts
703
- function getFetch3() {
704
- if (typeof globalThis.fetch === "function") {
705
- return globalThis.fetch;
514
+ function createMitraInstance(initialConfig) {
515
+ var _a;
516
+ let _config = {
517
+ baseURL: ((_a = initialConfig.baseURL) == null ? void 0 : _a.replace(/\/+$/, "")) || "",
518
+ token: initialConfig.token ? stripBearer(initialConfig.token) : "",
519
+ refreshToken: initialConfig.refreshToken,
520
+ integrationURL: initialConfig.integrationURL,
521
+ authUrl: initialConfig.authUrl,
522
+ projectId: initialConfig.projectId
523
+ };
524
+ function resolveProjectId2(projectId) {
525
+ if (projectId != null) return projectId;
526
+ if (_config.projectId != null) return _config.projectId;
527
+ throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
706
528
  }
707
- throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
708
- }
709
- function formatToken(token) {
710
- return `Bearer ${stripBearer(token)}`;
711
- }
712
- function buildHeaders() {
713
- const config = getConfig();
714
- const headers = { "Content-Type": "application/json" };
715
- if (config.token) headers["Authorization"] = formatToken(config.token);
716
- return headers;
717
- }
718
- function buildUrl(endpoint, params) {
719
- const config = getConfig();
720
- let url = `${config.baseURL}${endpoint}`;
721
- if (params) {
722
- const query = Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
723
- if (query) url += `?${query}`;
529
+ function authHeaders() {
530
+ const headers = { "Content-Type": "application/json" };
531
+ if (_config.token) headers["Authorization"] = formatToken(_config.token);
532
+ return headers;
724
533
  }
725
- return url;
726
- }
727
- async function tryRefreshToken() {
728
- var _a, _b;
729
- const config = getConfig();
730
- if (!config.token || config.projectId == null) return false;
731
- try {
732
- const baseURL = config.baseURL.replace(/\/+$/, "");
733
- const resp = await getFetch3()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
734
- method: "GET",
735
- headers: { "Authorization": formatToken(config.token) }
736
- });
737
- if (resp.ok) {
738
- const data = await resp.json();
739
- if (data.token) {
740
- const newToken = `Bearer ${stripBearer(data.token)}`;
741
- const session = {
742
- token: newToken,
743
- baseURL: ((_a = data.merge) == null ? void 0 : _a.backURL) || config.baseURL,
744
- ...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
745
- };
746
- updateGlobalToken(session.token);
747
- if (config.onTokenRefresh) config.onTokenRefresh(session);
748
- return true;
749
- }
534
+ async function handleResponse2(response) {
535
+ const text = await response.text();
536
+ const { data, isJson } = parseBody(text);
537
+ if (!response.ok) {
538
+ const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
539
+ const base = isJson && ((data == null ? void 0 : data.message) || (data == null ? void 0 : data.error)) || fallback;
540
+ const msg = isJson && (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
541
+ throw { message: msg, status: response.status, details: data };
750
542
  }
751
- } catch (e) {
752
- }
753
- if (!config.authUrl || typeof window === "undefined") return false;
754
- try {
755
- const session = await refreshTokenSilently3(config.authUrl, config.projectId);
756
- updateGlobalToken(session.token, session.refreshToken);
757
- if (config.onTokenRefresh) config.onTokenRefresh(session);
758
- return true;
759
- } catch (e) {
760
- return false;
761
- }
762
- }
763
- async function handleResponse(response) {
764
- const text = await response.text();
765
- const data = text ? JSON.parse(text) : null;
766
- if (!response.ok) {
767
- const base = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
768
- const msg = (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
769
- throw {
770
- message: msg,
771
- status: response.status,
772
- details: data
773
- };
774
- }
775
- return data;
776
- }
777
- async function fetchWithRefresh(url, init) {
778
- const fetchFn = getFetch3();
779
- const response = await fetchFn(url, init);
780
- if (response.status === 403) {
781
- const refreshed = await tryRefreshToken();
782
- if (refreshed) {
783
- const newHeaders = { ...buildHeaders() };
784
- const oldHeaders = init.headers;
785
- if (oldHeaders) {
786
- for (const [k, v] of Object.entries(oldHeaders)) {
787
- if (k !== "Authorization") newHeaders[k] = v;
788
- }
789
- }
790
- const retryResponse = await fetchFn(url, { ...init, headers: newHeaders });
791
- return handleResponse(retryResponse);
792
- }
793
- }
794
- return handleResponse(response);
795
- }
796
- var http = {
797
- async get(endpoint, params) {
798
- return fetchWithRefresh(buildUrl(endpoint, params), {
799
- method: "GET",
800
- headers: buildHeaders()
801
- });
802
- },
803
- async post(endpoint, body) {
804
- return fetchWithRefresh(buildUrl(endpoint), {
805
- method: "POST",
806
- headers: buildHeaders(),
807
- body: body !== void 0 ? JSON.stringify(body) : void 0
808
- });
809
- },
810
- async put(endpoint, body) {
811
- return fetchWithRefresh(buildUrl(endpoint), {
812
- method: "PUT",
813
- headers: buildHeaders(),
814
- body: body !== void 0 ? JSON.stringify(body) : void 0
815
- });
816
- },
817
- async del(endpoint, params) {
818
- return fetchWithRefresh(buildUrl(endpoint, params), {
819
- method: "DELETE",
820
- headers: buildHeaders()
821
- });
822
- },
823
- async delBody(endpoint, body) {
824
- return fetchWithRefresh(buildUrl(endpoint), {
825
- method: "DELETE",
826
- headers: buildHeaders(),
827
- body: body !== void 0 ? JSON.stringify(body) : void 0
828
- });
829
- },
830
- async upload(endpoint, formData) {
831
- const config = getConfig();
832
- const headers = {};
833
- if (config.token) headers["Authorization"] = formatToken(config.token);
834
- return fetchWithRefresh(buildUrl(endpoint), {
835
- method: "POST",
836
- headers,
837
- body: formData
838
- });
839
- }
840
- };
841
- async function requestWithTenant(method, endpoint, tenantId, options) {
842
- const headers = {
843
- ...buildHeaders(),
844
- "X-TenantID": String(tenantId)
845
- };
846
- return fetchWithRefresh(buildUrl(endpoint, options == null ? void 0 : options.params), {
847
- method,
848
- headers,
849
- body: (options == null ? void 0 : options.body) !== void 0 ? JSON.stringify(options.body) : void 0
850
- });
851
- }
852
- var httpTenant = {
853
- get(endpoint, tenantId, params) {
854
- return requestWithTenant("GET", endpoint, tenantId, { params });
855
- },
856
- post(endpoint, tenantId, body, params) {
857
- return requestWithTenant("POST", endpoint, tenantId, { body, params });
858
- },
859
- put(endpoint, tenantId, body, params) {
860
- return requestWithTenant("PUT", endpoint, tenantId, { body, params });
861
- },
862
- patch(endpoint, tenantId, body, params) {
863
- return requestWithTenant("PATCH", endpoint, tenantId, { body, params });
864
- },
865
- del(endpoint, tenantId, params) {
866
- return requestWithTenant("DELETE", endpoint, tenantId, { params });
867
- }
868
- };
869
-
870
- // src/services.ts
871
- async function executeDataLoaderMitra(options) {
872
- const body = {
873
- projectId: resolveProjectId2(options.projectId),
874
- dataLoaderId: options.dataLoaderId
875
- };
876
- if (options.input !== void 0) body.input = options.input;
877
- return http.post("/interactions/executeDataLoader", body);
878
- }
879
- async function executeDbActionMitra(options) {
880
- const body = {
881
- projectId: resolveProjectId2(options.projectId),
882
- dbActionId: options.dbActionId
883
- };
884
- if (options.input !== void 0) {
885
- body.input = options.input;
886
- }
887
- return http.post("/interactions/executeDbAction", body);
888
- }
889
- async function setFileStatusMitra(options) {
890
- return http.post("/interactions/setFileStatus", {
891
- projectId: resolveProjectId2(options.projectId),
892
- fileName: options.fileName,
893
- targetPath: options.targetPath
894
- });
895
- }
896
- async function setVariableMitra(options) {
897
- const body = {
898
- projectId: resolveProjectId2(options.projectId),
899
- key: options.key
900
- };
901
- if (options.value !== void 0) {
902
- body.value = options.value;
903
- }
904
- return http.post("/interactions/setVariable", body);
905
- }
906
- async function listVariablesMitra(options = {}) {
907
- return http.get("/interactions/listVariables", {
908
- projectId: resolveProjectId2(options.projectId)
909
- });
910
- }
911
- async function getVariableMitra(options) {
912
- return http.get("/interactions/getVariable", {
913
- projectId: resolveProjectId2(options.projectId),
914
- key: options.key
915
- });
916
- }
917
- async function runActionMitra(options) {
918
- const body = {
919
- projectId: resolveProjectId2(options.projectId),
920
- actionId: options.actionId
921
- };
922
- if (options.input !== void 0) {
923
- body.input = options.input;
924
- }
925
- return http.post("/interactions/runAction", body);
926
- }
927
- async function executeServerFunctionMitra(options) {
928
- const body = {
929
- projectId: resolveProjectId2(options.projectId),
930
- serverFunctionId: options.serverFunctionId
931
- };
932
- if (options.input !== void 0) {
933
- body.input = options.input;
934
- }
935
- return http.post("/interactions/executeServerFunction", body);
936
- }
937
- async function executeServerFunctionAsyncMitra(options) {
938
- const body = {
939
- projectId: resolveProjectId2(options.projectId),
940
- serverFunctionId: options.serverFunctionId
941
- };
942
- if (options.input !== void 0) {
943
- body.input = options.input;
944
- }
945
- return http.post("/interactions/executeServerFunctionAsync", body);
946
- }
947
- async function executePublicServerFunctionMitra(options) {
948
- const { projectId, serverFunctionId, input } = options;
949
- const baseURL = getConfig().baseURL;
950
- const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/execute`;
951
- const response = await fetch(url, {
952
- method: "POST",
953
- headers: { "Content-Type": "application/json" },
954
- body: JSON.stringify(input || {})
955
- });
956
- if (!response.ok) {
957
- const data = await response.json().catch(() => null);
958
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
959
- throw { message: msg, status: response.status, details: data };
960
- }
961
- return response.json();
962
- }
963
- async function executePublicServerFunctionAsyncMitra(options) {
964
- const { projectId, serverFunctionId, input } = options;
965
- const baseURL = getConfig().baseURL;
966
- const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/executeAsync`;
967
- const response = await fetch(url, {
968
- method: "POST",
969
- headers: { "Content-Type": "application/json" },
970
- body: JSON.stringify(input || {})
971
- });
972
- if (!response.ok) {
973
- const data = await response.json().catch(() => null);
974
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
975
- throw { message: msg, status: response.status, details: data };
976
- }
977
- return response.json();
978
- }
979
- async function getPublicServerFunctionExecutionMitra(options) {
980
- const { projectId, executionId } = options;
981
- const baseURL = getConfig().baseURL;
982
- const url = `${baseURL}/public/serverFunction/${projectId}/execution/${executionId}`;
983
- const response = await fetch(url, {
984
- method: "GET",
985
- headers: { "Content-Type": "application/json" }
986
- });
987
- if (!response.ok) {
988
- const data = await response.json().catch(() => null);
989
- const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
990
- throw { message: msg, status: response.status, details: data };
991
- }
992
- return response.json();
993
- }
994
- async function listIntegrationsMitra(options = {}) {
995
- return http.get("/interactions/integrations", {
996
- projectId: resolveProjectId2(options.projectId)
997
- });
998
- }
999
- async function callIntegrationMitra(options) {
1000
- const body = {
1001
- integrationSlug: options.connection,
1002
- projectId: resolveProjectId2(options.projectId),
1003
- method: options.method
1004
- };
1005
- if (options.endpoint !== void 0) {
1006
- body.endpoint = options.endpoint;
1007
- }
1008
- if (options.params !== void 0) {
1009
- body.params = options.params;
1010
- }
1011
- if (options.body !== void 0) {
1012
- body.body = options.body;
1013
- }
1014
- return http.post("/interactions/integrations/call", body);
1015
- }
1016
- async function stopServerFunctionExecutionMitra(options) {
1017
- return http.post("/interactions/stopServerFunctionExecution", {
1018
- projectId: resolveProjectId2(options.projectId),
1019
- executionId: options.executionId
1020
- });
1021
- }
1022
- async function uploadFilePublicMitra(options) {
1023
- const formData = new FormData();
1024
- formData.append("file", options.file);
1025
- formData.append("projectId", String(resolveProjectId2(options.projectId)));
1026
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
1027
- return http.upload("/interactions/uploadFilePublic", formData);
1028
- }
1029
- async function uploadFileLoadableMitra(options) {
1030
- const formData = new FormData();
1031
- formData.append("file", options.file);
1032
- formData.append("projectId", String(resolveProjectId2(options.projectId)));
1033
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
1034
- return http.upload("/interactions/uploadFileLoadable", formData);
1035
- }
1036
- async function listRecordsMitra(options) {
1037
- const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
1038
- const pid = resolveProjectId2(options.projectId);
1039
- return httpTenant.get(`/interactions/records/${tableName}`, pid, { page, size, jdbcConnectionConfigId, ...filters });
1040
- }
1041
- async function getRecordMitra(options) {
1042
- const { tableName, id, jdbcConnectionConfigId } = options;
1043
- const pid = resolveProjectId2(options.projectId);
1044
- return httpTenant.get(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1045
- }
1046
- async function createRecordMitra(options) {
1047
- const { tableName, data, jdbcConnectionConfigId } = options;
1048
- const pid = resolveProjectId2(options.projectId);
1049
- return httpTenant.post(`/interactions/records/${tableName}`, pid, data, { jdbcConnectionConfigId });
1050
- }
1051
- async function updateRecordMitra(options) {
1052
- const { tableName, id, data, jdbcConnectionConfigId } = options;
1053
- const pid = resolveProjectId2(options.projectId);
1054
- return httpTenant.put(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1055
- }
1056
- async function patchRecordMitra(options) {
1057
- const { tableName, id, data, jdbcConnectionConfigId } = options;
1058
- const pid = resolveProjectId2(options.projectId);
1059
- return httpTenant.patch(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1060
- }
1061
- async function deleteRecordMitra(options) {
1062
- const { tableName, id, jdbcConnectionConfigId } = options;
1063
- const pid = resolveProjectId2(options.projectId);
1064
- return httpTenant.del(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1065
- }
1066
- async function createRecordsBatchMitra(options) {
1067
- const { tableName, records, jdbcConnectionConfigId } = options;
1068
- const pid = resolveProjectId2(options.projectId);
1069
- return httpTenant.post(`/interactions/records/${tableName}/batch`, pid, records, { jdbcConnectionConfigId });
1070
- }
1071
- async function listProfilesMitra(options = {}) {
1072
- return http.get("/interactions/profiles", { projectId: resolveProjectId2(options.projectId) });
1073
- }
1074
- async function getProfileDetailsMitra(options) {
1075
- return http.get(`/interactions/profiles/${options.profileId}`, { projectId: resolveProjectId2(options.projectId) });
1076
- }
1077
- async function createProfileMitra(options) {
1078
- const body = {
1079
- projectId: resolveProjectId2(options.projectId),
1080
- name: options.name
1081
- };
1082
- if (options.color !== void 0) body.color = options.color;
1083
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
1084
- return http.post("/interactions/profiles", body);
1085
- }
1086
- async function updateProfileMitra(options) {
1087
- const body = {
1088
- projectId: resolveProjectId2(options.projectId),
1089
- profileId: options.profileId
1090
- };
1091
- if (options.name !== void 0) body.name = options.name;
1092
- if (options.color !== void 0) body.color = options.color;
1093
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
1094
- return http.put("/interactions/profiles", body);
1095
- }
1096
- async function deleteProfileMitra(options) {
1097
- return http.delBody("/interactions/profiles", {
1098
- projectId: resolveProjectId2(options.projectId),
1099
- profileId: options.profileId
1100
- });
1101
- }
1102
- async function setProfileUsersMitra(options) {
1103
- return http.post("/interactions/profiles/users", {
1104
- projectId: resolveProjectId2(options.projectId),
1105
- profileId: options.profileId,
1106
- userIds: options.userIds
1107
- });
1108
- }
1109
- async function setProfileSelectTablesMitra(options) {
1110
- const body = {
1111
- projectId: resolveProjectId2(options.projectId),
1112
- profileId: options.profileId,
1113
- tables: options.tables
1114
- };
1115
- if (options.jdbcConnectionConfigId !== void 0) body.jdbcConnectionConfigId = options.jdbcConnectionConfigId;
1116
- return http.post("/interactions/profiles/selectTables", body);
1117
- }
1118
- async function setProfileDmlTablesMitra(options) {
1119
- const body = {
1120
- projectId: resolveProjectId2(options.projectId),
1121
- profileId: options.profileId,
1122
- tables: options.tables
1123
- };
1124
- if (options.jdbcConnectionConfigId !== void 0) body.jdbcConnectionConfigId = options.jdbcConnectionConfigId;
1125
- return http.post("/interactions/profiles/dmlTables", body);
1126
- }
1127
- async function setProfileActionsMitra(options) {
1128
- return http.post("/interactions/profiles/actions", {
1129
- projectId: resolveProjectId2(options.projectId),
1130
- profileId: options.profileId,
1131
- actionIds: options.actionIds
1132
- });
1133
- }
1134
- async function setProfileScreensMitra(options) {
1135
- return http.post("/interactions/profiles/screens", {
1136
- projectId: resolveProjectId2(options.projectId),
1137
- profileId: options.profileId,
1138
- screenIds: options.screenIds
1139
- });
1140
- }
1141
- async function setProfileServerFunctionsMitra(options) {
1142
- return http.post("/interactions/profiles/serverFunctions", {
1143
- projectId: resolveProjectId2(options.projectId),
1144
- profileId: options.profileId,
1145
- serverFunctionIds: options.serverFunctionIds
1146
- });
1147
- }
1148
-
1149
- // src/agent-attachments.ts
1150
- var EXTENSION_MAP = {
1151
- // Images
1152
- png: "image",
1153
- jpg: "image",
1154
- jpeg: "image",
1155
- gif: "image",
1156
- webp: "image",
1157
- svg: "image",
1158
- bmp: "image",
1159
- ico: "image",
1160
- // PDF
1161
- pdf: "pdf",
1162
- // CSV
1163
- csv: "csv",
1164
- tsv: "csv",
1165
- // Excel
1166
- xlsx: "excel",
1167
- xls: "excel",
1168
- xlsm: "excel",
1169
- xlsb: "excel",
1170
- ods: "excel",
1171
- // Word
1172
- docx: "word",
1173
- doc: "word",
1174
- odt: "word",
1175
- rtf: "word",
1176
- // PowerPoint
1177
- pptx: "powerpoint",
1178
- ppt: "powerpoint",
1179
- odp: "powerpoint",
1180
- // Text
1181
- txt: "text",
1182
- md: "text",
1183
- log: "text",
1184
- ini: "text",
1185
- cfg: "text",
1186
- env: "text",
1187
- // Code
1188
- js: "code",
1189
- ts: "code",
1190
- jsx: "code",
1191
- tsx: "code",
1192
- py: "code",
1193
- rb: "code",
1194
- java: "code",
1195
- c: "code",
1196
- cpp: "code",
1197
- h: "code",
1198
- cs: "code",
1199
- go: "code",
1200
- rs: "code",
1201
- php: "code",
1202
- swift: "code",
1203
- kt: "code",
1204
- scala: "code",
1205
- html: "code",
1206
- css: "code",
1207
- scss: "code",
1208
- less: "code",
1209
- sql: "code",
1210
- sh: "code",
1211
- bash: "code",
1212
- zsh: "code",
1213
- yaml: "code",
1214
- yml: "code",
1215
- toml: "code",
1216
- xml: "code",
1217
- vue: "code",
1218
- svelte: "code",
1219
- // JSON
1220
- json: "json",
1221
- jsonl: "json",
1222
- geojson: "json",
1223
- // ZIP
1224
- zip: "zip",
1225
- tar: "zip",
1226
- gz: "zip",
1227
- rar: "zip",
1228
- "7z": "zip",
1229
- // Audio
1230
- mp3: "audio",
1231
- wav: "audio",
1232
- ogg: "audio",
1233
- flac: "audio",
1234
- m4a: "audio",
1235
- aac: "audio",
1236
- wma: "audio"
1237
- };
1238
- function detectAttachmentType(file) {
1239
- var _a, _b;
1240
- const ext = (_b = (_a = file.name.split(".").pop()) == null ? void 0 : _a.toLowerCase()) != null ? _b : "";
1241
- if (EXTENSION_MAP[ext]) return EXTENSION_MAP[ext];
1242
- if (file.type.startsWith("image/")) return "image";
1243
- if (file.type === "application/pdf") return "pdf";
1244
- if (file.type.startsWith("audio/")) return "audio";
1245
- if (file.type.startsWith("text/")) return "text";
1246
- return "unknown";
1247
- }
1248
- async function buildAttachmentsFromFiles(files, projectId) {
1249
- return Promise.all(
1250
- files.map(async (file) => {
1251
- var _a;
1252
- const type = detectAttachmentType(file);
1253
- const res = await uploadFilePublicMitra({ file, projectId });
1254
- const url = (_a = res.result) == null ? void 0 : _a.publicUrl;
1255
- if (!url) {
1256
- throw new Error(`upload sem URL p\xFAblica: ${file.name}`);
1257
- }
1258
- return {
1259
- url,
1260
- name: file.name,
1261
- type,
1262
- mimeType: file.type,
1263
- size: file.size
1264
- };
1265
- })
1266
- );
1267
- }
1268
-
1269
- // src/agent-task-session.ts
1270
- var QUEUE_MAX = 10;
1271
- var TURN_STARTED_SAFETY_MS = 3e4;
1272
- var sessionCounter = 0;
1273
- var AgentTaskSession = class {
1274
- constructor(init, transport2) {
1275
- // ── Identidade ────────────────────────
1276
- this._taskId = null;
1277
- this._task = null;
1278
- // ── Estado ────────────────────────────
1279
- this._status = "opening";
1280
- this._history = [];
1281
- this._content = "";
1282
- this._queue = [];
1283
- // ── Cancel state ──────────────────────
1284
- this._cancelled = false;
1285
- this._awaitingTurnStarted = false;
1286
- this._turnStartedTimer = null;
1287
- this._pendingCancelResolve = null;
1288
- // ── Listeners ─────────────────────────
1289
- this._listeners = /* @__PURE__ */ new Map();
1290
- this._wsUnsubscribe = null;
1291
- this._wsUnsubscribePending = null;
1292
- this._transport = transport2;
1293
- this._sessionId = `sess-${++sessionCounter}-${Date.now()}`;
1294
- this._isNew = init.kind === "new";
1295
- if (init.kind === "new") {
1296
- this._projectId = init.projectId;
1297
- this._agentType = init.agentType;
1298
- this._modelId = init.modelId;
1299
- this._initialName = init.name;
1300
- this._setStatus("idle");
1301
- this._wsUnsubscribePending = this._transport.subscribePending(
1302
- this._sessionId,
1303
- (msg) => this._handleMessage(msg)
1304
- );
1305
- } else {
1306
- this._taskId = init.taskId;
1307
- this._transport.register(init.taskId, this);
1308
- this._wsUnsubscribe = this._transport.subscribe(
1309
- init.taskId,
1310
- (msg) => this._handleMessage(msg)
1311
- );
1312
- this._initExisting(init.taskId);
1313
- }
1314
- }
1315
- // ── Properties públicas ────────────────────────────
1316
- get taskId() {
1317
- return this._taskId;
1318
- }
1319
- get task() {
1320
- return this._task;
1321
- }
1322
- get isNew() {
1323
- return this._isNew;
1324
- }
1325
- get status() {
1326
- return this._status;
1327
- }
1328
- get history() {
1329
- return this._history;
1330
- }
1331
- get content() {
1332
- return this._content;
1333
- }
1334
- get queue() {
1335
- return this._queue;
1336
- }
1337
- // ── Lifecycle ──────────────────────────────────────
1338
- async _initExisting(taskId) {
1339
- try {
1340
- await this._transport.ensureConnected();
1341
- if (this._status === "closed") return;
1342
- if (this._transport.isStreaming(taskId)) {
1343
- this._setStatus("streaming");
1344
- } else {
1345
- this._setStatus("idle");
1346
- }
1347
- } catch (err) {
1348
- this._emitError(err instanceof Error ? err.message : String(err));
1349
- }
1350
- }
1351
- async loadHistory(options) {
1352
- if (this._status === "closed") {
1353
- throw new Error("AgentTaskSession: session fechada.");
1354
- }
1355
- if (!this._taskId) {
1356
- this._history = [];
1357
- this._emit("historyLoaded", []);
1358
- return [];
1359
- }
1360
- await this._transport.ensureConnected();
1361
- const payload = { taskId: this._taskId };
1362
- if ((options == null ? void 0 : options.limit) != null) payload.limit = options.limit;
1363
- const msgs = await this._transport.request("get_history", payload);
1364
- this._history = msgs;
1365
- this._emit("historyLoaded", msgs);
1366
- return msgs;
1367
- }
1368
- close() {
1369
- if (this._status === "closed") return;
1370
- this._setStatus("closed");
1371
- if (this._turnStartedTimer) {
1372
- clearTimeout(this._turnStartedTimer);
1373
- this._turnStartedTimer = null;
1374
- }
1375
- if (this._wsUnsubscribe) {
1376
- this._wsUnsubscribe();
1377
- this._wsUnsubscribe = null;
1378
- }
1379
- if (this._wsUnsubscribePending) {
1380
- this._wsUnsubscribePending();
1381
- this._wsUnsubscribePending = null;
1382
- }
1383
- this._transport.unregister(this._taskId, this._sessionId);
1384
- this._listeners.clear();
1385
- }
1386
- // ── Comandos ───────────────────────────────────────
1387
- send(prompt, options) {
1388
- var _a, _b, _c, _d;
1389
- if (this._status === "closed") {
1390
- throw new Error("AgentTaskSession: session fechada.");
1391
- }
1392
- const files = ((_a = options == null ? void 0 : options.files) == null ? void 0 : _a.length) ? options.files : void 0;
1393
- if (!prompt.trim() && !files) return;
1394
- const agentType = (_c = (_b = options == null ? void 0 : options.agentType) != null ? _b : this._agentType) != null ? _c : "claudecode";
1395
- const modelId = (_d = options == null ? void 0 : options.modelId) != null ? _d : this._modelId;
1396
- if (files) {
1397
- void this._uploadThenDispatch(prompt, agentType, modelId, files);
1398
- return;
1399
- }
1400
- this._dispatchSend(prompt, agentType, modelId, void 0);
1401
- }
1402
- async _uploadThenDispatch(prompt, agentType, modelId, files) {
1403
- const wasStreaming = this._status === "streaming";
1404
- if (!wasStreaming) this._setStatus("uploading");
1405
- let attachments;
1406
- try {
1407
- attachments = await buildAttachmentsFromFiles(files, this._projectId);
1408
- } catch (err) {
1409
- this._emit("error", {
1410
- error: `Falha ao subir anexos: ${err instanceof Error ? err.message : String(err)}`
1411
- });
1412
- if (this._status === "uploading") this._setStatus("idle");
1413
- return;
1414
- }
1415
- if (this._status === "closed") return;
1416
- this._dispatchSend(prompt, agentType, modelId, attachments);
1417
- }
1418
- _dispatchSend(prompt, agentType, modelId, attachments) {
1419
- var _a;
1420
- if (this._status === "streaming") {
1421
- this._enqueue(prompt, agentType);
1422
- if (this._taskId) {
1423
- this._transport.send(
1424
- "send_prompt",
1425
- {
1426
- prompt,
1427
- taskId: this._taskId,
1428
- projectId: this._projectId,
1429
- agentType,
1430
- ...modelId ? { modelId } : {},
1431
- ...attachments ? { attachments } : {},
1432
- midSession: true
1433
- },
1434
- this._taskId
1435
- );
1436
- }
1437
- return;
1438
- }
1439
- if (this._status === "cancelled") {
1440
- this._awaitingTurnStarted = true;
1441
- if (this._turnStartedTimer) clearTimeout(this._turnStartedTimer);
1442
- this._turnStartedTimer = setTimeout(() => {
1443
- this._turnStartedTimer = null;
1444
- if (this._awaitingTurnStarted) {
1445
- this._cancelled = false;
1446
- this._awaitingTurnStarted = false;
1447
- this._setStatus("idle");
1448
- }
1449
- }, TURN_STARTED_SAFETY_MS);
1450
- }
1451
- this._setStatus("streaming");
1452
- this._content = "";
1453
- const payload = {
1454
- prompt,
1455
- projectId: this._projectId,
1456
- agentType
1457
- };
1458
- if (modelId) payload.modelId = modelId;
1459
- if (attachments) payload.attachments = attachments;
1460
- if (this._taskId) payload.taskId = this._taskId;
1461
- if (this._initialName && !this._taskId) {
1462
- payload.name = this._initialName;
1463
- }
1464
- this._transport.send("send_prompt", payload, (_a = this._taskId) != null ? _a : void 0);
1465
- }
1466
- async cancel() {
1467
- if (this._status === "closed") return;
1468
- if (this._status !== "streaming" && this._status !== "cancelled") return;
1469
- this._cancelled = true;
1470
- this._clearQueue();
1471
- if (this._taskId) {
1472
- this._transport.send(
1473
- "task_cancel",
1474
- { source: "sdk_cancel" },
1475
- this._taskId
1476
- );
1477
- }
1478
- this._setStatus("cancelled");
1479
- this._emit("cancelled", void 0);
1480
- return new Promise((resolve) => {
1481
- const previousResolve = this._pendingCancelResolve;
1482
- this._pendingCancelResolve = () => {
1483
- resolve();
1484
- if (previousResolve) previousResolve();
1485
- };
1486
- setTimeout(() => {
1487
- if (this._pendingCancelResolve) {
1488
- this._pendingCancelResolve = null;
1489
- resolve();
1490
- }
1491
- }, TURN_STARTED_SAFETY_MS);
1492
- });
1493
- }
1494
- // ── Manipulação de fila ────────────────────────────
1495
- editQueueItem(itemId, newText) {
1496
- const idx = this._queue.findIndex((q) => q.id === itemId);
1497
- if (idx < 0 || this._queue[idx].status !== "pending") return false;
1498
- this._queue = [
1499
- ...this._queue.slice(0, idx),
1500
- { ...this._queue[idx], text: newText },
1501
- ...this._queue.slice(idx + 1)
1502
- ];
1503
- this._emitQueueChange();
1504
- return true;
1505
- }
1506
- removeQueueItem(itemId) {
1507
- const before = this._queue.length;
1508
- this._queue = this._queue.filter((q) => q.id !== itemId);
1509
- if (this._queue.length === before) return false;
1510
- this._emitQueueChange();
1511
- return true;
1512
- }
1513
- clearQueue() {
1514
- if (this._queue.length === 0) return;
1515
- this._clearQueue();
1516
- }
1517
- // ── Eventos ────────────────────────────────────────
1518
- on(event, handler) {
1519
- if (!this._listeners.has(event)) {
1520
- this._listeners.set(event, /* @__PURE__ */ new Set());
1521
- }
1522
- this._listeners.get(event).add(handler);
1523
- return () => {
1524
- var _a;
1525
- (_a = this._listeners.get(event)) == null ? void 0 : _a.delete(handler);
1526
- };
1527
- }
1528
- // ── Internals: routing de mensagens WS ─────────────
1529
- _handleMessage(msg) {
1530
- var _a, _b, _c, _d, _e, _f;
1531
- if (!(msg == null ? void 0 : msg.type)) return;
1532
- if (this._cancelled && msg.type !== "turn_started" && msg.type !== "error" && msg.type !== "task_update") {
1533
- return;
1534
- }
1535
- const payload = (_a = msg.payload) != null ? _a : {};
1536
- switch (msg.type) {
1537
- case "task_update": {
1538
- if (payload.action !== "created") return;
1539
- const task = payload.task;
1540
- if (!task) return;
1541
- if (!this._taskId) {
1542
- this._taskId = task.id;
1543
- this._task = task;
1544
- this._transport.register(task.id, this);
1545
- if (this._wsUnsubscribePending) {
1546
- this._wsUnsubscribePending();
1547
- this._wsUnsubscribePending = null;
1548
- }
1549
- this._wsUnsubscribe = this._transport.subscribe(
1550
- task.id,
1551
- (m) => this._handleMessage(m)
1552
- );
1553
- this._emit("taskCreated", { task });
1554
- } else if (this._taskId === task.id) {
1555
- this._task = task;
1556
- }
1557
- break;
1558
- }
1559
- case "turn_started": {
1560
- if (this._cancelled) {
1561
- this._cancelled = false;
1562
- this._awaitingTurnStarted = false;
1563
- if (this._turnStartedTimer) {
1564
- clearTimeout(this._turnStartedTimer);
1565
- this._turnStartedTimer = null;
1566
- }
1567
- if (this._pendingCancelResolve) {
1568
- this._pendingCancelResolve();
1569
- this._pendingCancelResolve = null;
1570
- }
1571
- }
1572
- if (this._status !== "streaming") {
1573
- this._setStatus("streaming");
1574
- this._content = "";
1575
- }
1576
- this._emit("turnStart", void 0);
1577
- break;
1578
- }
1579
- case "stream_delta": {
1580
- const kind = payload.subtype === "thinking" ? "tool" : "text";
1581
- const delta = String((_b = payload.delta) != null ? _b : "");
1582
- if (kind === "text") this._content += delta;
1583
- this._emit("delta", { delta, kind });
1584
- break;
1585
- }
1586
- case "stream_tool_activity": {
1587
- this._emit("tool", {
1588
- tool: String((_c = payload.tool) != null ? _c : ""),
1589
- input: payload.input,
1590
- content: payload.content,
1591
- timestamp: Number((_d = msg.timestamp) != null ? _d : Date.now())
1592
- });
1593
- break;
1594
- }
1595
- case "stream_end": {
1596
- const finalContent = this._content;
1597
- this._emit("turnEnd", { content: finalContent });
1598
- this._setStatus("idle");
1599
- this._shiftQueueAndSend();
1600
- break;
1601
- }
1602
- case "error": {
1603
- const error = String((_f = (_e = payload.error) != null ? _e : msg.error) != null ? _f : "Erro desconhecido");
1604
- this._emitError(error);
1605
- break;
1606
- }
1607
- }
1608
- }
1609
- // ── Fila interna ───────────────────────────────────
1610
- _enqueue(text, agentType) {
1611
- if (this._queue.length >= QUEUE_MAX) return;
1612
- const trimmed = text.trim();
1613
- if (this._queue.some((q) => q.text.trim() === trimmed)) return;
1614
- const item = {
1615
- id: `q-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
1616
- text,
1617
- agentType,
1618
- seq: this._transport.nextSeq(),
1619
- createdAt: Date.now(),
1620
- status: "pending"
1621
- };
1622
- this._queue = [...this._queue, item];
1623
- this._emitQueueChange();
1624
- }
1625
- _shiftQueueAndSend() {
1626
- if (this._queue.length === 0) return;
1627
- const [next, ...rest] = this._queue;
1628
- this._queue = rest;
1629
- this._emitQueueChange();
1630
- this.send(next.text, { agentType: next.agentType });
1631
- }
1632
- _clearQueue() {
1633
- if (this._queue.length === 0) return;
1634
- this._queue = [];
1635
- this._emitQueueChange();
1636
- }
1637
- // ── Helpers de emissão ─────────────────────────────
1638
- _emit(event, payload) {
1639
- const set = this._listeners.get(event);
1640
- if (!set) return;
1641
- for (const handler of set) {
1642
- try {
1643
- handler(payload);
1644
- } catch (err) {
1645
- console.error(`[AgentTaskSession] handler de '${event}' lan\xE7ou:`, err);
1646
- }
1647
- }
1648
- }
1649
- _emitError(error) {
1650
- this._emit("error", { error });
1651
- this._setStatus("error");
1652
- }
1653
- _emitQueueChange() {
1654
- this._emit("queueChange", { queue: this._queue });
1655
- }
1656
- _setStatus(next) {
1657
- if (this._status === next) return;
1658
- const previous = this._status;
1659
- this._status = next;
1660
- this._emit("statusChange", { status: next, previous });
1661
- }
1662
- };
1663
-
1664
- // src/agent-chat.ts
1665
- var ws = null;
1666
- var connectPromise = null;
1667
- var requestSeq = 0;
1668
- var queueSeq = 0;
1669
- var pendingRequests = /* @__PURE__ */ new Map();
1670
- var sessionsByTaskId = /* @__PURE__ */ new Map();
1671
- var handlersByTaskId = /* @__PURE__ */ new Map();
1672
- var pendingHandlers = /* @__PURE__ */ new Map();
1673
- var streamingTaskIds = /* @__PURE__ */ new Set();
1674
- function nextRequestId() {
1675
- return `req-${Date.now()}-${++requestSeq}`;
1676
- }
1677
- function nextQueueSeq() {
1678
- return ++queueSeq;
1679
- }
1680
- function getRawToken() {
1681
- const config = getConfig();
1682
- if (!config.token) {
1683
- throw new Error("Agent Chat: token n\xE3o configurado. Fa\xE7a login primeiro ou passe token em configureSdkMitra.");
1684
- }
1685
- return stripBearer(config.token);
1686
- }
1687
- function resolveProjectId3(override) {
1688
- const config = getConfig();
1689
- const pid = override != null ? override : config.projectId;
1690
- if (pid == null) {
1691
- throw new Error("Agent Chat: projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
1692
- }
1693
- return pid;
1694
- }
1695
- function getWsUrl() {
1696
- var _a;
1697
- if (typeof window !== "undefined") {
1698
- const injected = (_a = window.__mitraEnv) == null ? void 0 : _a.agentWsUrl;
1699
- if (typeof injected === "string" && injected) return injected;
1700
- }
1701
- throw new Error("Agent Chat: window.__mitraEnv.agentWsUrl indispon\xEDvel. A SDK precisa rodar em uma app publicada pelo Mitra (build-proxy injeta __mitraEnv).");
1702
- }
1703
- function connect() {
1704
- if (ws && ws.readyState === WebSocket.OPEN) {
1705
- return Promise.resolve(ws);
1706
- }
1707
- if (connectPromise) return connectPromise;
1708
- const baseUrl = getWsUrl();
1709
- const token = getRawToken();
1710
- const separator = baseUrl.includes("?") ? "&" : "?";
1711
- const url = `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
1712
- connectPromise = new Promise((resolve, reject) => {
1713
- const socket = new WebSocket(url);
1714
- let opened = false;
1715
- const timer = setTimeout(() => {
1716
- if (!opened) {
1717
- try {
1718
- socket.close();
1719
- } catch (e) {
1720
- }
1721
- connectPromise = null;
1722
- reject(new Error("Agent Chat: timeout ao conectar no WebSocket"));
1723
- }
1724
- }, 15e3);
1725
- socket.onopen = () => {
1726
- opened = true;
1727
- clearTimeout(timer);
1728
- ws = socket;
1729
- connectPromise = null;
1730
- resolve(socket);
1731
- };
1732
- socket.onerror = () => {
1733
- if (!opened) {
1734
- clearTimeout(timer);
1735
- connectPromise = null;
1736
- reject(new Error("Agent Chat: erro ao conectar no WebSocket"));
1737
- }
1738
- };
1739
- socket.onclose = () => {
1740
- if (ws === socket) ws = null;
1741
- for (const [id, pending] of pendingRequests) {
1742
- pending.reject(new Error("Agent Chat: conex\xE3o fechada"));
1743
- pendingRequests.delete(id);
1744
- }
1745
- streamingTaskIds.clear();
1746
- };
1747
- socket.onmessage = (event) => routeMessage(event.data);
1748
- });
1749
- return connectPromise;
1750
- }
1751
- function routeMessage(raw) {
1752
- var _a, _b;
1753
- let msg;
1754
- try {
1755
- msg = typeof raw === "string" ? JSON.parse(raw) : raw;
1756
- } catch (e) {
1757
- return;
1758
- }
1759
- if (!(msg == null ? void 0 : msg.type)) return;
1760
- if (msg.type === "response" && msg.requestId) {
1761
- const pending = pendingRequests.get(msg.requestId);
1762
- if (!pending) return;
1763
- pendingRequests.delete(msg.requestId);
1764
- if (msg.ok) pending.resolve(msg.data);
1765
- else pending.reject(new Error(msg.error || "Erro desconhecido"));
1766
- return;
1767
- }
1768
- if (msg.type === "streaming_state") {
1769
- streamingTaskIds.clear();
1770
- const ids = (_b = (_a = msg.payload) == null ? void 0 : _a.streamingTaskIds) != null ? _b : [];
1771
- for (const id of ids) streamingTaskIds.add(id);
1772
- return;
1773
- }
1774
- if (msg.type === "turn_started" && msg.taskId) {
1775
- streamingTaskIds.add(msg.taskId);
1776
- } else if (msg.type === "stream_end" && msg.taskId) {
1777
- streamingTaskIds.delete(msg.taskId);
1778
- }
1779
- if (msg.taskId) {
1780
- const set = handlersByTaskId.get(msg.taskId);
1781
- if (set) {
1782
- for (const handler of set) handler(msg);
1783
- }
1784
- }
1785
- if (msg.type === "task_update") {
1786
- for (const handler of pendingHandlers.values()) handler(msg);
1787
- }
1788
- }
1789
- var transport = {
1790
- async ensureConnected() {
1791
- await connect();
1792
- },
1793
- async request(type, payload) {
1794
- const socket = await connect();
1795
- const requestId = nextRequestId();
1796
- return new Promise((resolve, reject) => {
1797
- pendingRequests.set(requestId, {
1798
- resolve: (data) => resolve(data),
1799
- reject
1800
- });
1801
- try {
1802
- socket.send(JSON.stringify({ type, requestId, payload }));
1803
- } catch (err) {
1804
- pendingRequests.delete(requestId);
1805
- reject(err instanceof Error ? err : new Error(String(err)));
1806
- }
1807
- });
1808
- },
1809
- send(type, payload, taskId) {
1810
- connect().then((socket) => {
1811
- const requestId = nextRequestId();
1812
- socket.send(JSON.stringify({ type, requestId, payload, taskId }));
1813
- }).catch((err) => {
1814
- console.error("[agent-chat] send falhou:", err);
1815
- });
1816
- },
1817
- resolveProjectId(override) {
1818
- return resolveProjectId3(override);
1819
- },
1820
- nextSeq() {
1821
- return nextQueueSeq();
1822
- },
1823
- subscribe(taskId, handler) {
1824
- if (!handlersByTaskId.has(taskId)) {
1825
- handlersByTaskId.set(taskId, /* @__PURE__ */ new Set());
1826
- }
1827
- handlersByTaskId.get(taskId).add(handler);
1828
- return () => {
1829
- const set = handlersByTaskId.get(taskId);
1830
- if (!set) return;
1831
- set.delete(handler);
1832
- if (set.size === 0) handlersByTaskId.delete(taskId);
1833
- };
1834
- },
1835
- subscribePending(sessionId, handler) {
1836
- pendingHandlers.set(sessionId, handler);
1837
- return () => {
1838
- pendingHandlers.delete(sessionId);
1839
- };
1840
- },
1841
- isStreaming(taskId) {
1842
- return streamingTaskIds.has(taskId);
1843
- },
1844
- register(taskId, session) {
1845
- sessionsByTaskId.set(taskId, session);
1846
- },
1847
- unregister(taskId, _sessionId) {
1848
- if (taskId) sessionsByTaskId.delete(taskId);
1849
- }
1850
- };
1851
- function getTransport() {
1852
- return transport;
1853
- }
1854
- function manageAgentChatMitra(options) {
1855
- var _a;
1856
- if (isNewWorld()) throw new Error("manageAgentChatMitra ainda n\xE3o suportado no novo Mitra.");
1857
- if (options.action === "list") {
1858
- const projectId = resolveProjectId3(options.projectId);
1859
- return transport.request("chats", { action: "list", projectId });
1860
- }
1861
- if (options.action === "rename") {
1862
- if (!options.taskId) throw new Error("manageAgentChatMitra(rename): taskId obrigat\xF3rio.");
1863
- if (!((_a = options.name) == null ? void 0 : _a.trim())) throw new Error("manageAgentChatMitra(rename): name obrigat\xF3rio.");
1864
- return transport.request("chats", { action: "rename", taskId: options.taskId, name: options.name.trim() });
1865
- }
1866
- if (options.action === "delete") {
1867
- if (!options.taskId) throw new Error("manageAgentChatMitra(delete): taskId obrigat\xF3rio.");
1868
- return transport.request("chats", { action: "delete", taskId: options.taskId });
1869
- }
1870
- throw new Error(`manageAgentChatMitra: action inv\xE1lida (${options.action}).`);
1871
- }
1872
- function getAgentTaskMitra(options) {
1873
- if (isNewWorld()) throw new Error("getAgentTaskMitra ainda n\xE3o suportado no novo Mitra.");
1874
- if ("taskId" in options && options.taskId) {
1875
- const cached = sessionsByTaskId.get(options.taskId);
1876
- if (cached) return cached;
1877
- return new AgentTaskSession(
1878
- { kind: "existing", taskId: options.taskId },
1879
- transport
1880
- );
1881
- }
1882
- if ("create" in options && options.create) {
1883
- return new AgentTaskSession(
1884
- {
1885
- kind: "new",
1886
- projectId: options.projectId,
1887
- agentType: options.agentType,
1888
- modelId: options.modelId,
1889
- name: options.name
1890
- },
1891
- transport
1892
- );
1893
- }
1894
- throw new Error("getAgentTaskMitra: passe { create: true } ou { taskId }.");
1895
- }
1896
-
1897
- // src/agent-credentials.ts
1898
- var pendingVerifiers = /* @__PURE__ */ new Map();
1899
- function manageAgentCredentialMitra(options) {
1900
- if (isNewWorld()) throw new Error("manageAgentCredentialMitra ainda n\xE3o suportado no novo Mitra.");
1901
- if (options.action === "auth") return authSubscription(options);
1902
- if (options.action === "connect") return connectSubscription(options);
1903
- return rpc(options);
1904
- }
1905
- function rpc(options) {
1906
- const transport2 = getTransport();
1907
- const { action, target, ...rest } = options;
1908
- const data = {};
1909
- for (const [k, v] of Object.entries(rest)) {
1910
- if (v !== void 0) data[k] = v;
1911
- }
1912
- return transport2.request("credentials", { action, target, data });
1913
- }
1914
- async function authSubscription(options) {
1915
- const { target } = options;
1916
- if (target === "claude") {
1917
- const start = await rpc({
1918
- action: "oauth_start",
1919
- target: "claude"
1920
- });
1921
- pendingVerifiers.set(start.state, start.codeVerifier);
1922
- return { target: "claude", authUrl: start.authUrl, state: start.state };
1923
- }
1924
- if (target === "codex") {
1925
- const start = await rpc({
1926
- action: "device_start",
1927
- target: "codex"
1928
- });
1929
- return {
1930
- target: "codex",
1931
- userCode: start.userCode,
1932
- verificationUrl: start.verificationUrl,
1933
- pollId: start.pollId
1934
- };
1935
- }
1936
- throw new Error(`manageAgentCredentialMitra(auth): target inv\xE1lido (${target}). Use 'claude' ou 'codex'.`);
1937
- }
1938
- function connectSubscription(options) {
1939
- const { target } = options;
1940
- if (target === "claude") return connectClaude(options);
1941
- if (target === "codex") return connectCodex(options);
1942
- throw new Error(`manageAgentCredentialMitra(connect): target inv\xE1lido (${target}). Use 'claude' ou 'codex'.`);
1943
- }
1944
- async function connectClaude(options) {
1945
- var _a;
1946
- const { code, state } = options;
1947
- if (!code || !state) {
1948
- throw new Error("manageAgentCredentialMitra(connect, claude): code e state s\xE3o obrigat\xF3rios (state vem de auth).");
1949
- }
1950
- const codeVerifier = pendingVerifiers.get(state);
1951
- const exchange = await rpc({
1952
- action: "oauth_exchange",
1953
- target: "claude",
1954
- code,
1955
- state,
1956
- // Se a SDK ainda tem o verifier (mesmo runtime), envia; senão o backend
1957
- // resolve via state (pkceStore). Cobre os dois caminhos.
1958
- ...codeVerifier ? { codeVerifier } : {}
1959
- });
1960
- pendingVerifiers.delete(state);
1961
- return {
1962
- target: "claude",
1963
- success: exchange.success === true,
1964
- expiresAt: exchange.expiresAt,
1965
- account: (_a = exchange.account) != null ? _a : null
1966
- };
1967
- }
1968
- async function connectCodex(options) {
1969
- var _a, _b;
1970
- const { pollId } = options;
1971
- if (!pollId) {
1972
- throw new Error("manageAgentCredentialMitra(connect, codex): pollId \xE9 obrigat\xF3rio (vem de auth).");
1973
- }
1974
- const pollInterval = (_a = options.pollIntervalMs) != null ? _a : 2e3;
1975
- const deadline = Date.now() + ((_b = options.deviceTimeoutMs) != null ? _b : 15 * 6e4);
1976
- while (Date.now() < deadline) {
1977
- const result = await rpc({ action: "device_poll", target: "codex", pollId });
1978
- if (result.status === "completed") {
1979
- return { target: "codex", success: true };
1980
- }
1981
- if (result.status === "failed" || result.status === "expired" || result.status === "not_found") {
1982
- throw new Error(`manageAgentCredentialMitra(connect, codex): ${result.status}${result.error ? ` \u2014 ${result.error}` : ""}`);
1983
- }
1984
- await sleep(pollInterval);
1985
- }
1986
- await rpc({ action: "device_cancel", target: "codex", pollId }).catch(() => {
1987
- });
1988
- throw new Error("manageAgentCredentialMitra(connect, codex): timeout.");
1989
- }
1990
- function sleep(ms) {
1991
- return new Promise((r) => setTimeout(r, ms));
1992
- }
1993
-
1994
- // src/instance.ts
1995
- function formatToken2(token) {
1996
- return `Bearer ${stripBearer(token)}`;
1997
- }
1998
- function getFetch4() {
1999
- if (typeof globalThis.fetch === "function") return globalThis.fetch;
2000
- throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
2001
- }
2002
- function buildQuery(params) {
2003
- return Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
2004
- }
2005
- function createMitraInstance(initialConfig) {
2006
- var _a;
2007
- let _config = {
2008
- baseURL: ((_a = initialConfig.baseURL) == null ? void 0 : _a.replace(/\/+$/, "")) || "",
2009
- token: initialConfig.token ? stripBearer(initialConfig.token) : "",
2010
- refreshToken: initialConfig.refreshToken,
2011
- integrationURL: initialConfig.integrationURL,
2012
- authUrl: initialConfig.authUrl,
2013
- projectId: initialConfig.projectId
2014
- };
2015
- function resolveProjectId4(projectId) {
2016
- if (projectId != null) return projectId;
2017
- if (_config.projectId != null) return _config.projectId;
2018
- throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
2019
- }
2020
- function authHeaders() {
2021
- const headers = { "Content-Type": "application/json" };
2022
- if (_config.token) headers["Authorization"] = formatToken2(_config.token);
2023
- return headers;
2024
- }
2025
- async function handleResponse2(response) {
2026
- const text = await response.text();
2027
- const data = text ? JSON.parse(text) : null;
2028
- if (!response.ok) {
2029
- const base = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
2030
- const msg = (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
2031
- throw { message: msg, status: response.status, details: data };
2032
- }
2033
- return data;
543
+ return data;
2034
544
  }
2035
545
  async function tryRefreshToken2() {
2036
546
  var _a2, _b;
2037
547
  if (!_config.token || _config.projectId == null || !_config.baseURL) return false;
2038
548
  try {
2039
549
  const baseURL = _config.baseURL.replace(/\/+$/, "");
2040
- const resp = await getFetch4()(`${baseURL}/mitraspace/project/refreshedToken/${_config.projectId}`, {
550
+ const resp = await getFetch2()(`${baseURL}/mitraspace/project/refreshedToken/${_config.projectId}`, {
2041
551
  method: "GET",
2042
- headers: { "Authorization": formatToken2(_config.token) }
552
+ headers: { "Authorization": formatToken(_config.token) }
2043
553
  });
2044
554
  if (resp.ok) {
2045
555
  const data = await resp.json();
@@ -2072,7 +582,7 @@ function createMitraInstance(initialConfig) {
2072
582
  }
2073
583
  }
2074
584
  async function fetchWithRefresh2(url, init) {
2075
- const fetchFn = getFetch4();
585
+ const fetchFn = getFetch2();
2076
586
  const response = await fetchFn(url, init);
2077
587
  if (response.status === 403) {
2078
588
  const refreshed = await tryRefreshToken2();
@@ -2102,16 +612,6 @@ function createMitraInstance(initialConfig) {
2102
612
  body: (opts == null ? void 0 : opts.body) !== void 0 ? JSON.stringify(opts.body) : void 0
2103
613
  });
2104
614
  }
2105
- async function requestUpload(endpoint, formData) {
2106
- const url = `${_config.baseURL}${endpoint}`;
2107
- const headers = {};
2108
- if (_config.token) headers["Authorization"] = formatToken2(_config.token);
2109
- return fetchWithRefresh2(url, {
2110
- method: "POST",
2111
- headers,
2112
- body: formData
2113
- });
2114
- }
2115
615
  async function requestTenant(method, endpoint, tenantId, opts) {
2116
616
  let url = `${_config.baseURL}${endpoint}`;
2117
617
  if (opts == null ? void 0 : opts.params) {
@@ -2133,51 +633,20 @@ function createMitraInstance(initialConfig) {
2133
633
  _config = { ..._config, token };
2134
634
  },
2135
635
  // Services
2136
- async executeDataLoader(options) {
2137
- const body = { projectId: resolveProjectId4(options.projectId), dataLoaderId: options.dataLoaderId };
2138
- if (options.input !== void 0) body.input = options.input;
2139
- return request("POST", "/interactions/executeDataLoader", { body });
2140
- },
2141
- async executeDbAction(options) {
2142
- const body = { projectId: resolveProjectId4(options.projectId), dbActionId: options.dbActionId };
2143
- if (options.input !== void 0) body.input = options.input;
2144
- return request("POST", "/interactions/executeDbAction", { body });
2145
- },
2146
- async setFileStatus(options) {
2147
- return request("POST", "/interactions/setFileStatus", {
2148
- body: { projectId: resolveProjectId4(options.projectId), fileName: options.fileName, targetPath: options.targetPath }
2149
- });
2150
- },
2151
- async setVariable(options) {
2152
- const body = { projectId: resolveProjectId4(options.projectId), key: options.key };
2153
- if (options.value !== void 0) body.value = options.value;
2154
- return request("POST", "/interactions/setVariable", { body });
2155
- },
2156
- async listVariables(options = {}) {
2157
- return request("GET", "/interactions/listVariables", { params: { projectId: resolveProjectId4(options.projectId) } });
2158
- },
2159
- async getVariable(options) {
2160
- return request("GET", "/interactions/getVariable", { params: { projectId: resolveProjectId4(options.projectId), key: options.key } });
2161
- },
2162
- async runAction(options) {
2163
- const body = { projectId: resolveProjectId4(options.projectId), actionId: options.actionId };
2164
- if (options.input !== void 0) body.input = options.input;
2165
- return request("POST", "/interactions/runAction", { body });
2166
- },
2167
636
  async executeServerFunction(options) {
2168
- const body = { projectId: resolveProjectId4(options.projectId), serverFunctionId: options.serverFunctionId };
637
+ const body = { projectId: resolveProjectId2(options.projectId), serverFunctionId: options.serverFunctionId };
2169
638
  if (options.input !== void 0) body.input = options.input;
2170
639
  return request("POST", "/interactions/executeServerFunction", { body });
2171
640
  },
2172
641
  async executeServerFunctionAsync(options) {
2173
- const body = { projectId: resolveProjectId4(options.projectId), serverFunctionId: options.serverFunctionId };
642
+ const body = { projectId: resolveProjectId2(options.projectId), serverFunctionId: options.serverFunctionId };
2174
643
  if (options.input !== void 0) body.input = options.input;
2175
644
  return request("POST", "/interactions/executeServerFunctionAsync", { body });
2176
645
  },
2177
646
  async executePublicServerFunction(options) {
2178
647
  const { projectId, serverFunctionId, input } = options;
2179
648
  const url = `${_config.baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/execute`;
2180
- const fetchFn = getFetch4();
649
+ const fetchFn = getFetch2();
2181
650
  const response = await fetchFn(url, {
2182
651
  method: "POST",
2183
652
  headers: { "Content-Type": "application/json" },
@@ -2188,7 +657,7 @@ function createMitraInstance(initialConfig) {
2188
657
  async executePublicServerFunctionAsync(options) {
2189
658
  const { projectId, serverFunctionId, input } = options;
2190
659
  const url = `${_config.baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/executeAsync`;
2191
- const fetchFn = getFetch4();
660
+ const fetchFn = getFetch2();
2192
661
  const response = await fetchFn(url, {
2193
662
  method: "POST",
2194
663
  headers: { "Content-Type": "application/json" },
@@ -2199,7 +668,7 @@ function createMitraInstance(initialConfig) {
2199
668
  async getPublicServerFunctionExecution(options) {
2200
669
  const { projectId, executionId } = options;
2201
670
  const url = `${_config.baseURL}/public/serverFunction/${projectId}/execution/${executionId}`;
2202
- const fetchFn = getFetch4();
671
+ const fetchFn = getFetch2();
2203
672
  const response = await fetchFn(url, {
2204
673
  method: "GET",
2205
674
  headers: { "Content-Type": "application/json" }
@@ -2208,32 +677,17 @@ function createMitraInstance(initialConfig) {
2208
677
  },
2209
678
  async stopServerFunctionExecution(options) {
2210
679
  return request("POST", "/interactions/stopServerFunctionExecution", {
2211
- body: { projectId: resolveProjectId4(options.projectId), executionId: options.executionId }
680
+ body: { projectId: resolveProjectId2(options.projectId), executionId: options.executionId }
2212
681
  });
2213
682
  },
2214
- // Upload de Arquivos
2215
- async uploadFilePublic(options) {
2216
- const formData = new FormData();
2217
- formData.append("file", options.file);
2218
- formData.append("projectId", String(resolveProjectId4(options.projectId)));
2219
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
2220
- return requestUpload("/interactions/uploadFilePublic", formData);
2221
- },
2222
- async uploadFileLoadable(options) {
2223
- const formData = new FormData();
2224
- formData.append("file", options.file);
2225
- formData.append("projectId", String(resolveProjectId4(options.projectId)));
2226
- if (options.debug !== void 0) formData.append("debug", String(options.debug));
2227
- return requestUpload("/interactions/uploadFileLoadable", formData);
2228
- },
2229
683
  // Integrations
2230
684
  async listIntegrations(options = {}) {
2231
- return request("GET", "/interactions/integrations", { params: { projectId: resolveProjectId4(options.projectId) } });
685
+ return request("GET", "/interactions/integrations", { params: { projectId: resolveProjectId2(options.projectId) } });
2232
686
  },
2233
687
  async callIntegration(options) {
2234
688
  const body = {
2235
689
  integrationSlug: options.connection,
2236
- projectId: resolveProjectId4(options.projectId),
690
+ projectId: resolveProjectId2(options.projectId),
2237
691
  method: options.method
2238
692
  };
2239
693
  if (options.endpoint !== void 0) body.endpoint = options.endpoint;
@@ -2244,241 +698,473 @@ function createMitraInstance(initialConfig) {
2244
698
  // Dynamic Schema CRUD
2245
699
  async listRecords(options) {
2246
700
  const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
2247
- const pid = resolveProjectId4(options.projectId);
701
+ const pid = resolveProjectId2(options.projectId);
2248
702
  return requestTenant("GET", `/interactions/records/${tableName}`, pid, { params: { page, size, jdbcConnectionConfigId, ...filters } });
2249
703
  },
2250
704
  async getRecord(options) {
2251
705
  const { tableName, id, jdbcConnectionConfigId } = options;
2252
- const pid = resolveProjectId4(options.projectId);
706
+ const pid = resolveProjectId2(options.projectId);
2253
707
  return requestTenant("GET", `/interactions/records/${tableName}/${id}`, pid, { params: { jdbcConnectionConfigId } });
2254
708
  },
2255
709
  async createRecord(options) {
2256
710
  const { tableName, data, jdbcConnectionConfigId } = options;
2257
- const pid = resolveProjectId4(options.projectId);
711
+ const pid = resolveProjectId2(options.projectId);
2258
712
  return requestTenant("POST", `/interactions/records/${tableName}`, pid, { body: data, params: { jdbcConnectionConfigId } });
2259
713
  },
2260
714
  async updateRecord(options) {
2261
715
  const { tableName, id, data, jdbcConnectionConfigId } = options;
2262
- const pid = resolveProjectId4(options.projectId);
716
+ const pid = resolveProjectId2(options.projectId);
2263
717
  return requestTenant("PUT", `/interactions/records/${tableName}/${id}`, pid, { body: data, params: { jdbcConnectionConfigId } });
2264
718
  },
2265
719
  async patchRecord(options) {
2266
720
  const { tableName, id, data, jdbcConnectionConfigId } = options;
2267
- const pid = resolveProjectId4(options.projectId);
721
+ const pid = resolveProjectId2(options.projectId);
2268
722
  return requestTenant("PATCH", `/interactions/records/${tableName}/${id}`, pid, { body: data, params: { jdbcConnectionConfigId } });
2269
723
  },
2270
724
  async deleteRecord(options) {
2271
725
  const { tableName, id, jdbcConnectionConfigId } = options;
2272
- const pid = resolveProjectId4(options.projectId);
726
+ const pid = resolveProjectId2(options.projectId);
2273
727
  return requestTenant("DELETE", `/interactions/records/${tableName}/${id}`, pid, { params: { jdbcConnectionConfigId } });
2274
728
  },
2275
729
  async createRecordsBatch(options) {
2276
730
  const { tableName, records, jdbcConnectionConfigId } = options;
2277
- const pid = resolveProjectId4(options.projectId);
731
+ const pid = resolveProjectId2(options.projectId);
2278
732
  return requestTenant("POST", `/interactions/records/${tableName}/batch`, pid, { body: records, params: { jdbcConnectionConfigId } });
2279
- },
2280
- // Profile Management
2281
- async listProfiles(options = {}) {
2282
- return request("GET", "/interactions/profiles", { params: { projectId: resolveProjectId4(options.projectId) } });
2283
- },
2284
- async getProfileDetails(options) {
2285
- return request("GET", `/interactions/profiles/${options.profileId}`, { params: { projectId: resolveProjectId4(options.projectId) } });
2286
- },
2287
- async createProfile(options) {
2288
- const body = { projectId: resolveProjectId4(options.projectId), name: options.name };
2289
- if (options.color !== void 0) body.color = options.color;
2290
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
2291
- return request("POST", "/interactions/profiles", { body });
2292
- },
2293
- async updateProfile(options) {
2294
- const body = { projectId: resolveProjectId4(options.projectId), profileId: options.profileId };
2295
- if (options.name !== void 0) body.name = options.name;
2296
- if (options.color !== void 0) body.color = options.color;
2297
- if (options.homeScreenId !== void 0) body.homeScreenId = options.homeScreenId;
2298
- return request("PUT", "/interactions/profiles", { body });
2299
- },
2300
- async deleteProfile(options) {
2301
- return request("DELETE", "/interactions/profiles", { body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId } });
2302
- },
2303
- async setProfileUsers(options) {
2304
- return request("POST", "/interactions/profiles/users", {
2305
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, userIds: options.userIds }
2306
- });
2307
- },
2308
- async setProfileSelectTables(options) {
2309
- return request("POST", "/interactions/profiles/selectTables", {
2310
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, tables: options.tables }
2311
- });
2312
- },
2313
- async setProfileDmlTables(options) {
2314
- return request("POST", "/interactions/profiles/dmlTables", {
2315
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, tables: options.tables }
2316
- });
2317
- },
2318
- async setProfileActions(options) {
2319
- return request("POST", "/interactions/profiles/actions", {
2320
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, actionIds: options.actionIds }
2321
- });
2322
- },
2323
- async setProfileScreens(options) {
2324
- return request("POST", "/interactions/profiles/screens", {
2325
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, screenIds: options.screenIds }
2326
- });
2327
- },
2328
- async setProfileServerFunctions(options) {
2329
- return request("POST", "/interactions/profiles/serverFunctions", {
2330
- body: { projectId: resolveProjectId4(options.projectId), profileId: options.profileId, serverFunctionIds: options.serverFunctionIds }
733
+ }
734
+ };
735
+ return instance;
736
+ }
737
+
738
+ // src/config.ts
739
+ var globalConfig = null;
740
+ function stripBearer(token) {
741
+ let t = token.trim();
742
+ while (/^bearer\s+/i.test(t)) {
743
+ t = t.replace(/^bearer\s+/i, "").trim();
744
+ }
745
+ return t;
746
+ }
747
+ function parseBody(text) {
748
+ if (!text) return { data: null, isJson: true };
749
+ try {
750
+ return { data: JSON.parse(text), isJson: true };
751
+ } catch (e) {
752
+ return { data: text, isJson: false };
753
+ }
754
+ }
755
+ var SESSION_STORE_KEY = "mitra-session";
756
+ function safeLocalStorage() {
757
+ try {
758
+ return typeof localStorage !== "undefined" ? localStorage : null;
759
+ } catch (e) {
760
+ return null;
761
+ }
762
+ }
763
+ function persistRefreshToken(refreshToken) {
764
+ const ls = safeLocalStorage();
765
+ if (!ls) return;
766
+ try {
767
+ const raw = ls.getItem(SESSION_STORE_KEY);
768
+ const obj = raw ? JSON.parse(raw) : {};
769
+ obj.refreshToken = refreshToken;
770
+ ls.setItem(SESSION_STORE_KEY, JSON.stringify(obj));
771
+ } catch (e) {
772
+ }
773
+ }
774
+ function readPersistedRefreshToken() {
775
+ const ls = safeLocalStorage();
776
+ if (!ls) return void 0;
777
+ try {
778
+ const raw = ls.getItem(SESSION_STORE_KEY);
779
+ if (!raw) return void 0;
780
+ const obj = JSON.parse(raw);
781
+ return typeof (obj == null ? void 0 : obj.refreshToken) === "string" && obj.refreshToken ? obj.refreshToken : void 0;
782
+ } catch (e) {
783
+ return void 0;
784
+ }
785
+ }
786
+ function readInjectedEnv() {
787
+ if (typeof window === "undefined") return {};
788
+ const env = window.__mitraEnv;
789
+ if (!env || typeof env !== "object") return {};
790
+ const out = {};
791
+ if (typeof env.apiBaseURL === "string" && env.apiBaseURL) out.baseURL = env.apiBaseURL;
792
+ if (typeof env.integrationURL === "string" && env.integrationURL) out.integrationURL = env.integrationURL;
793
+ if (typeof env.authUrl === "string" && env.authUrl) out.authUrl = env.authUrl;
794
+ if (typeof env.authPageUrl === "string" && env.authPageUrl) out.authPageUrl = env.authPageUrl;
795
+ return out;
796
+ }
797
+ function configureSdkMitra(config = {}) {
798
+ const injected = readInjectedEnv();
799
+ const merged = { ...injected, ...config };
800
+ if (!merged.baseURL) {
801
+ throw new Error("baseURL \xE9 obrigat\xF3rio. Passe em configureSdkMitra({ baseURL }), fa\xE7a login para receber via sdk-auth, ou rode em uma app publicada pelo Mitra (window.__mitraEnv).");
802
+ }
803
+ if (merged.token != null) merged.token = stripBearer(merged.token);
804
+ if (!merged.refreshToken) {
805
+ const persisted = readPersistedRefreshToken();
806
+ if (persisted) merged.refreshToken = persisted;
807
+ } else {
808
+ persistRefreshToken(merged.refreshToken);
809
+ }
810
+ globalConfig = {
811
+ ...merged,
812
+ baseURL: merged.baseURL.replace(/\/+$/, "")
813
+ };
814
+ return createMitraInstance(globalConfig);
815
+ }
816
+ function getConfig() {
817
+ if (!globalConfig) {
818
+ throw new Error("SDK n\xE3o configurado. Chame configureSdkMitra() primeiro.");
819
+ }
820
+ return globalConfig;
821
+ }
822
+ function isConfigured() {
823
+ return globalConfig !== null;
824
+ }
825
+ function updateGlobalToken(token, refreshToken) {
826
+ if (globalConfig) {
827
+ globalConfig = {
828
+ ...globalConfig,
829
+ token: stripBearer(token),
830
+ ...refreshToken !== void 0 ? { refreshToken } : {}
831
+ };
832
+ if (refreshToken) persistRefreshToken(refreshToken);
833
+ }
834
+ }
835
+ function resolveProjectId(projectId) {
836
+ if (projectId != null) return projectId;
837
+ if ((globalConfig == null ? void 0 : globalConfig.projectId) != null) return globalConfig.projectId;
838
+ throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
839
+ }
840
+
841
+ // src/client.ts
842
+ function getFetch3() {
843
+ if (typeof globalThis.fetch === "function") {
844
+ return globalThis.fetch;
845
+ }
846
+ throw new Error("fetch n\xE3o dispon\xEDvel. Use Node.js 18+ ou instale node-fetch.");
847
+ }
848
+ function formatToken2(token) {
849
+ return `Bearer ${stripBearer(token)}`;
850
+ }
851
+ function buildHeaders() {
852
+ const config = getConfig();
853
+ const headers = { "Content-Type": "application/json" };
854
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
855
+ return headers;
856
+ }
857
+ function buildUrl(endpoint, params) {
858
+ const config = getConfig();
859
+ let url = `${config.baseURL}${endpoint}`;
860
+ if (params) {
861
+ const query = Object.entries(params).filter(([, v]) => v !== void 0 && v !== null).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`).join("&");
862
+ if (query) url += `?${query}`;
863
+ }
864
+ return url;
865
+ }
866
+ async function tryRefreshToken() {
867
+ var _a, _b;
868
+ const config = getConfig();
869
+ if (!config.token || config.projectId == null || !config.baseURL) return false;
870
+ if (!isNewWorld()) {
871
+ try {
872
+ const baseURL = config.baseURL.replace(/\/+$/, "");
873
+ const resp = await getFetch3()(`${baseURL}/mitraspace/project/refreshedToken/${config.projectId}`, {
874
+ method: "GET",
875
+ headers: { "Authorization": formatToken2(config.token) }
2331
876
  });
2332
- },
2333
- // Password Reset (pré-login)
2334
- sendPasswordResetCode(options) {
2335
- var _a2;
2336
- return sendPasswordResetCodeMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
2337
- },
2338
- validatePasswordResetCode(options) {
2339
- var _a2;
2340
- return validatePasswordResetCodeMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
2341
- },
2342
- resetPassword(options) {
2343
- var _a2;
2344
- return resetPasswordMitra({ ...options, authUrl: (_a2 = options.authUrl) != null ? _a2 : _config.authUrl });
2345
- },
2346
- // Agent Chat (embedded)
2347
- getAgentTask(options) {
2348
- return getAgentTaskMitra(options);
2349
- },
2350
- manageAgentChat(options) {
2351
- return manageAgentChatMitra(options);
2352
- },
2353
- manageAgentCredential(options) {
2354
- return manageAgentCredentialMitra(options);
2355
- },
2356
- // Chat
2357
- openChat() {
2358
- openChatMitra();
2359
- },
2360
- closeChat() {
2361
- closeChatMitra();
877
+ if (resp.ok) {
878
+ const data = await resp.json();
879
+ if (data.token) {
880
+ const newToken = `Bearer ${stripBearer(data.token)}`;
881
+ const session = {
882
+ token: newToken,
883
+ baseURL: ((_a = data.merge) == null ? void 0 : _a.backURL) || config.baseURL,
884
+ ...((_b = data.merge) == null ? void 0 : _b.integrationURL) ? { integrationURL: data.merge.integrationURL } : {}
885
+ };
886
+ updateGlobalToken(session.token);
887
+ if (config.onTokenRefresh) config.onTokenRefresh(session);
888
+ return true;
889
+ }
890
+ }
891
+ } catch (e) {
892
+ }
893
+ }
894
+ if (!config.authUrl || typeof window === "undefined") return false;
895
+ try {
896
+ const session = await refreshTokenSilently3(config.authUrl, config.projectId);
897
+ updateGlobalToken(session.token, session.refreshToken);
898
+ if (config.onTokenRefresh) config.onTokenRefresh(session);
899
+ return true;
900
+ } catch (e) {
901
+ return false;
902
+ }
903
+ }
904
+ async function handleResponse(response) {
905
+ const text = await response.text();
906
+ const { data, isJson } = parseBody(text);
907
+ if (!response.ok) {
908
+ const fallback = !isJson && text ? `HTTP ${response.status} \u2014 ${text}` : `HTTP ${response.status}`;
909
+ const base = isJson && ((data == null ? void 0 : data.message) || (data == null ? void 0 : data.error)) || fallback;
910
+ const msg = isJson && (data == null ? void 0 : data.hint) ? `${base} \u2014 ${data.hint}` : base;
911
+ throw {
912
+ message: msg,
913
+ status: response.status,
914
+ details: data
915
+ };
916
+ }
917
+ return data;
918
+ }
919
+ async function fetchWithRefresh(url, init) {
920
+ const fetchFn = getFetch3();
921
+ const response = await fetchFn(url, init);
922
+ const expiredStatus = isNewWorld() ? 401 : 403;
923
+ if (response.status === expiredStatus) {
924
+ const refreshed = await tryRefreshToken();
925
+ if (refreshed) {
926
+ const newHeaders = { ...buildHeaders() };
927
+ const oldHeaders = init.headers;
928
+ if (oldHeaders) {
929
+ for (const [k, v] of Object.entries(oldHeaders)) {
930
+ if (k !== "Authorization") newHeaders[k] = v;
931
+ }
932
+ }
933
+ const retryResponse = await fetchFn(url, { ...init, headers: newHeaders });
934
+ return handleResponse(retryResponse);
2362
935
  }
936
+ }
937
+ return handleResponse(response);
938
+ }
939
+ var http = {
940
+ async get(endpoint, params) {
941
+ return fetchWithRefresh(buildUrl(endpoint, params), {
942
+ method: "GET",
943
+ headers: buildHeaders()
944
+ });
945
+ },
946
+ async post(endpoint, body) {
947
+ return fetchWithRefresh(buildUrl(endpoint), {
948
+ method: "POST",
949
+ headers: buildHeaders(),
950
+ body: body !== void 0 ? JSON.stringify(body) : void 0
951
+ });
952
+ },
953
+ async put(endpoint, body) {
954
+ return fetchWithRefresh(buildUrl(endpoint), {
955
+ method: "PUT",
956
+ headers: buildHeaders(),
957
+ body: body !== void 0 ? JSON.stringify(body) : void 0
958
+ });
959
+ },
960
+ async del(endpoint, params) {
961
+ return fetchWithRefresh(buildUrl(endpoint, params), {
962
+ method: "DELETE",
963
+ headers: buildHeaders()
964
+ });
965
+ },
966
+ async delBody(endpoint, body) {
967
+ return fetchWithRefresh(buildUrl(endpoint), {
968
+ method: "DELETE",
969
+ headers: buildHeaders(),
970
+ body: body !== void 0 ? JSON.stringify(body) : void 0
971
+ });
972
+ },
973
+ async upload(endpoint, formData) {
974
+ const config = getConfig();
975
+ const headers = {};
976
+ if (config.token) headers["Authorization"] = formatToken2(config.token);
977
+ return fetchWithRefresh(buildUrl(endpoint), {
978
+ method: "POST",
979
+ headers,
980
+ body: formData
981
+ });
982
+ }
983
+ };
984
+ async function requestWithTenant(method, endpoint, tenantId, options) {
985
+ const headers = {
986
+ ...buildHeaders(),
987
+ "X-TenantID": String(tenantId)
2363
988
  };
2364
- return instance;
989
+ return fetchWithRefresh(buildUrl(endpoint, options == null ? void 0 : options.params), {
990
+ method,
991
+ headers,
992
+ body: (options == null ? void 0 : options.body) !== void 0 ? JSON.stringify(options.body) : void 0
993
+ });
2365
994
  }
995
+ var httpTenant = {
996
+ get(endpoint, tenantId, params) {
997
+ return requestWithTenant("GET", endpoint, tenantId, { params });
998
+ },
999
+ post(endpoint, tenantId, body, params) {
1000
+ return requestWithTenant("POST", endpoint, tenantId, { body, params });
1001
+ },
1002
+ put(endpoint, tenantId, body, params) {
1003
+ return requestWithTenant("PUT", endpoint, tenantId, { body, params });
1004
+ },
1005
+ patch(endpoint, tenantId, body, params) {
1006
+ return requestWithTenant("PATCH", endpoint, tenantId, { body, params });
1007
+ },
1008
+ del(endpoint, tenantId, params) {
1009
+ return requestWithTenant("DELETE", endpoint, tenantId, { params });
1010
+ }
1011
+ };
2366
1012
 
2367
- // src/config.ts
2368
- var globalConfig = null;
2369
- function stripBearer(token) {
2370
- let t = token.trim();
2371
- while (/^bearer\s+/i.test(t)) {
2372
- t = t.replace(/^bearer\s+/i, "").trim();
1013
+ // src/services.ts
1014
+ async function executeServerFunctionMitra(options) {
1015
+ const body = {
1016
+ projectId: resolveProjectId(options.projectId),
1017
+ serverFunctionId: options.serverFunctionId
1018
+ };
1019
+ if (options.input !== void 0) {
1020
+ body.input = options.input;
2373
1021
  }
2374
- return t;
1022
+ return http.post("/interactions/executeServerFunction", body);
2375
1023
  }
2376
- function readInjectedEnv() {
2377
- if (typeof window === "undefined") return {};
2378
- const env = window.__mitraEnv;
2379
- if (!env || typeof env !== "object") return {};
2380
- const out = {};
2381
- if (typeof env.apiBaseURL === "string" && env.apiBaseURL) out.baseURL = env.apiBaseURL;
2382
- if (typeof env.integrationURL === "string" && env.integrationURL) out.integrationURL = env.integrationURL;
2383
- if (typeof env.authUrl === "string" && env.authUrl) out.authUrl = env.authUrl;
2384
- return out;
1024
+ async function executeServerFunctionAsyncMitra(options) {
1025
+ const body = {
1026
+ projectId: resolveProjectId(options.projectId),
1027
+ serverFunctionId: options.serverFunctionId
1028
+ };
1029
+ if (options.input !== void 0) {
1030
+ body.input = options.input;
1031
+ }
1032
+ return http.post("/interactions/executeServerFunctionAsync", body);
2385
1033
  }
2386
- function configureSdkMitra(config = {}) {
2387
- const injected = readInjectedEnv();
2388
- const merged = { ...injected, ...config };
2389
- if (!merged.baseURL) {
2390
- throw new Error("baseURL \xE9 obrigat\xF3rio. Passe em configureSdkMitra({ baseURL }), fa\xE7a login para receber via sdk-auth, ou rode em uma app publicada pelo Mitra (window.__mitraEnv).");
1034
+ async function executePublicServerFunctionMitra(options) {
1035
+ const { projectId, serverFunctionId, input } = options;
1036
+ const baseURL = getConfig().baseURL;
1037
+ const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/execute`;
1038
+ const response = await fetch(url, {
1039
+ method: "POST",
1040
+ headers: { "Content-Type": "application/json" },
1041
+ body: JSON.stringify(input || {})
1042
+ });
1043
+ if (!response.ok) {
1044
+ const data = await response.json().catch(() => null);
1045
+ const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
1046
+ throw { message: msg, status: response.status, details: data };
2391
1047
  }
2392
- if (merged.token != null) merged.token = stripBearer(merged.token);
2393
- globalConfig = {
2394
- ...merged,
2395
- baseURL: merged.baseURL.replace(/\/+$/, "")
2396
- };
2397
- if (merged.token && typeof window !== "undefined") {
2398
- const chat = window.__mitraChat;
2399
- if (chat) chat.init(merged.token);
1048
+ return response.json();
1049
+ }
1050
+ async function executePublicServerFunctionAsyncMitra(options) {
1051
+ const { projectId, serverFunctionId, input } = options;
1052
+ const baseURL = getConfig().baseURL;
1053
+ const url = `${baseURL}/public/serverFunction/${projectId}/${serverFunctionId}/executeAsync`;
1054
+ const response = await fetch(url, {
1055
+ method: "POST",
1056
+ headers: { "Content-Type": "application/json" },
1057
+ body: JSON.stringify(input || {})
1058
+ });
1059
+ if (!response.ok) {
1060
+ const data = await response.json().catch(() => null);
1061
+ const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
1062
+ throw { message: msg, status: response.status, details: data };
2400
1063
  }
2401
- return createMitraInstance(globalConfig);
1064
+ return response.json();
2402
1065
  }
2403
- function getConfig() {
2404
- if (!globalConfig) {
2405
- throw new Error("SDK n\xE3o configurado. Chame configureSdkMitra() primeiro.");
1066
+ async function getPublicServerFunctionExecutionMitra(options) {
1067
+ const { projectId, executionId } = options;
1068
+ const baseURL = getConfig().baseURL;
1069
+ const url = `${baseURL}/public/serverFunction/${projectId}/execution/${executionId}`;
1070
+ const response = await fetch(url, {
1071
+ method: "GET",
1072
+ headers: { "Content-Type": "application/json" }
1073
+ });
1074
+ if (!response.ok) {
1075
+ const data = await response.json().catch(() => null);
1076
+ const msg = (data == null ? void 0 : data.message) || (data == null ? void 0 : data.error) || `HTTP ${response.status}`;
1077
+ throw { message: msg, status: response.status, details: data };
2406
1078
  }
2407
- return globalConfig;
1079
+ return response.json();
2408
1080
  }
2409
- function isConfigured() {
2410
- return globalConfig !== null;
1081
+ async function listIntegrationsMitra(options = {}) {
1082
+ return http.get("/interactions/integrations", {
1083
+ projectId: resolveProjectId(options.projectId)
1084
+ });
2411
1085
  }
2412
- function updateGlobalToken(token, refreshToken) {
2413
- if (globalConfig) {
2414
- globalConfig = {
2415
- ...globalConfig,
2416
- token: stripBearer(token),
2417
- ...refreshToken !== void 0 ? { refreshToken } : {}
2418
- };
1086
+ async function callIntegrationMitra(options) {
1087
+ const body = {
1088
+ integrationSlug: options.connection,
1089
+ projectId: resolveProjectId(options.projectId),
1090
+ method: options.method
1091
+ };
1092
+ if (options.endpoint !== void 0) {
1093
+ body.endpoint = options.endpoint;
1094
+ }
1095
+ if (options.params !== void 0) {
1096
+ body.params = options.params;
1097
+ }
1098
+ if (options.body !== void 0) {
1099
+ body.body = options.body;
2419
1100
  }
1101
+ return http.post("/interactions/integrations/call", body);
2420
1102
  }
2421
- function resolveProjectId2(projectId) {
2422
- if (projectId != null) return projectId;
2423
- if ((globalConfig == null ? void 0 : globalConfig.projectId) != null) return globalConfig.projectId;
2424
- throw new Error("projectId \xE9 obrigat\xF3rio. Passe nas options ou configure via configureSdkMitra({ projectId }).");
1103
+ async function stopServerFunctionExecutionMitra(options) {
1104
+ return http.post("/interactions/stopServerFunctionExecution", {
1105
+ projectId: resolveProjectId(options.projectId),
1106
+ executionId: options.executionId
1107
+ });
1108
+ }
1109
+ async function listRecordsMitra(options) {
1110
+ const { tableName, page, size, filters, jdbcConnectionConfigId } = options;
1111
+ const pid = resolveProjectId(options.projectId);
1112
+ return httpTenant.get(`/interactions/records/${tableName}`, pid, { page, size, jdbcConnectionConfigId, ...filters });
1113
+ }
1114
+ async function getRecordMitra(options) {
1115
+ const { tableName, id, jdbcConnectionConfigId } = options;
1116
+ const pid = resolveProjectId(options.projectId);
1117
+ return httpTenant.get(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1118
+ }
1119
+ async function createRecordMitra(options) {
1120
+ const { tableName, data, jdbcConnectionConfigId } = options;
1121
+ const pid = resolveProjectId(options.projectId);
1122
+ return httpTenant.post(`/interactions/records/${tableName}`, pid, data, { jdbcConnectionConfigId });
1123
+ }
1124
+ async function updateRecordMitra(options) {
1125
+ const { tableName, id, data, jdbcConnectionConfigId } = options;
1126
+ const pid = resolveProjectId(options.projectId);
1127
+ return httpTenant.put(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1128
+ }
1129
+ async function patchRecordMitra(options) {
1130
+ const { tableName, id, data, jdbcConnectionConfigId } = options;
1131
+ const pid = resolveProjectId(options.projectId);
1132
+ return httpTenant.patch(`/interactions/records/${tableName}/${id}`, pid, data, { jdbcConnectionConfigId });
1133
+ }
1134
+ async function deleteRecordMitra(options) {
1135
+ const { tableName, id, jdbcConnectionConfigId } = options;
1136
+ const pid = resolveProjectId(options.projectId);
1137
+ return httpTenant.del(`/interactions/records/${tableName}/${id}`, pid, { jdbcConnectionConfigId });
1138
+ }
1139
+ async function createRecordsBatchMitra(options) {
1140
+ const { tableName, records, jdbcConnectionConfigId } = options;
1141
+ const pid = resolveProjectId(options.projectId);
1142
+ return httpTenant.post(`/interactions/records/${tableName}/batch`, pid, records, { jdbcConnectionConfigId });
2425
1143
  }
2426
1144
 
2427
1145
  exports.callIntegrationMitra = callIntegrationMitra;
2428
- exports.closeChatMitra = closeChatMitra;
2429
1146
  exports.configureSdkMitra = configureSdkMitra;
2430
1147
  exports.createMitraInstance = createMitraInstance;
2431
- exports.createProfileMitra = createProfileMitra;
2432
1148
  exports.createRecordMitra = createRecordMitra;
2433
1149
  exports.createRecordsBatchMitra = createRecordsBatchMitra;
2434
- exports.deleteProfileMitra = deleteProfileMitra;
2435
1150
  exports.deleteRecordMitra = deleteRecordMitra;
2436
- exports.emailLoginMitra = emailLoginMitra3;
2437
- exports.emailResendCodeMitra = emailResendCodeMitra3;
2438
- exports.emailSignupMitra = emailSignupMitra3;
2439
- exports.emailVerifyCodeMitra = emailVerifyCodeMitra3;
2440
- exports.executeDataLoaderMitra = executeDataLoaderMitra;
2441
- exports.executeDbActionMitra = executeDbActionMitra;
1151
+ exports.exchangeSsoCodeMitra = exchangeSsoCodeMitra2;
2442
1152
  exports.executePublicServerFunctionAsyncMitra = executePublicServerFunctionAsyncMitra;
2443
1153
  exports.executePublicServerFunctionMitra = executePublicServerFunctionMitra;
2444
1154
  exports.executeServerFunctionAsyncMitra = executeServerFunctionAsyncMitra;
2445
1155
  exports.executeServerFunctionMitra = executeServerFunctionMitra;
2446
- exports.getAgentTaskMitra = getAgentTaskMitra;
2447
1156
  exports.getConfig = getConfig;
2448
- exports.getProfileDetailsMitra = getProfileDetailsMitra;
2449
1157
  exports.getPublicServerFunctionExecutionMitra = getPublicServerFunctionExecutionMitra;
2450
1158
  exports.getRecordMitra = getRecordMitra;
2451
- exports.getVariableMitra = getVariableMitra;
2452
1159
  exports.listIntegrationsMitra = listIntegrationsMitra;
2453
- exports.listProfilesMitra = listProfilesMitra;
2454
1160
  exports.listRecordsMitra = listRecordsMitra;
2455
- exports.listVariablesMitra = listVariablesMitra;
2456
1161
  exports.loginMitra = loginMitra3;
2457
- exports.loginWithEmailMitra = loginWithEmailMitra3;
2458
1162
  exports.loginWithGoogleMitra = loginWithGoogleMitra3;
2459
1163
  exports.loginWithMicrosoftMitra = loginWithMicrosoftMitra3;
2460
- exports.manageAgentChatMitra = manageAgentChatMitra;
2461
- exports.manageAgentCredentialMitra = manageAgentCredentialMitra;
2462
- exports.openChatMitra = openChatMitra;
2463
1164
  exports.patchRecordMitra = patchRecordMitra;
2464
1165
  exports.refreshTokenSilently = refreshTokenSilently3;
2465
- exports.resetPasswordMitra = resetPasswordMitra;
2466
- exports.resolveProjectId = resolveProjectId2;
2467
- exports.runActionMitra = runActionMitra;
2468
- exports.sendPasswordResetCodeMitra = sendPasswordResetCodeMitra;
2469
- exports.setFileStatusMitra = setFileStatusMitra;
2470
- exports.setProfileActionsMitra = setProfileActionsMitra;
2471
- exports.setProfileDmlTablesMitra = setProfileDmlTablesMitra;
2472
- exports.setProfileScreensMitra = setProfileScreensMitra;
2473
- exports.setProfileSelectTablesMitra = setProfileSelectTablesMitra;
2474
- exports.setProfileServerFunctionsMitra = setProfileServerFunctionsMitra;
2475
- exports.setProfileUsersMitra = setProfileUsersMitra;
2476
- exports.setVariableMitra = setVariableMitra;
1166
+ exports.resolveProjectId = resolveProjectId;
2477
1167
  exports.stopServerFunctionExecutionMitra = stopServerFunctionExecutionMitra;
2478
- exports.updateProfileMitra = updateProfileMitra;
2479
1168
  exports.updateRecordMitra = updateRecordMitra;
2480
- exports.uploadFileLoadableMitra = uploadFileLoadableMitra;
2481
- exports.uploadFilePublicMitra = uploadFilePublicMitra;
2482
- exports.validatePasswordResetCodeMitra = validatePasswordResetCodeMitra;
2483
1169
  //# sourceMappingURL=index.js.map
2484
1170
  //# sourceMappingURL=index.js.map