@xylex-group/athena 2.9.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +1 -1
  2. package/dist/browser.cjs +828 -74
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.cts +3 -3
  5. package/dist/browser.d.ts +3 -3
  6. package/dist/browser.js +825 -75
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +748 -40
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.js +748 -40
  11. package/dist/cli/index.js.map +1 -1
  12. package/dist/{client-CfAE_QOj.d.cts → client-B7EQ_hPV.d.cts} +506 -22
  13. package/dist/{client-D6EIJdQS.d.ts → client-BYii6dU9.d.ts} +506 -22
  14. package/dist/index.cjs +828 -74
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +2 -2
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +825 -75
  19. package/dist/index.js.map +1 -1
  20. package/dist/{react-email-BvJ3fj_F.d.cts → module-DC96HJa3.d.cts} +97 -2
  21. package/dist/{react-email-PLAJuZuO.d.ts → module-DbHlxpeR.d.ts} +97 -2
  22. package/dist/next/client.cjs +756 -40
  23. package/dist/next/client.cjs.map +1 -1
  24. package/dist/next/client.d.cts +3 -4
  25. package/dist/next/client.d.ts +3 -4
  26. package/dist/next/client.js +756 -40
  27. package/dist/next/client.js.map +1 -1
  28. package/dist/next/server.cjs +756 -40
  29. package/dist/next/server.cjs.map +1 -1
  30. package/dist/next/server.d.cts +2 -2
  31. package/dist/next/server.d.ts +2 -2
  32. package/dist/next/server.js +756 -40
  33. package/dist/next/server.js.map +1 -1
  34. package/dist/react.cjs +1 -1
  35. package/dist/react.cjs.map +1 -1
  36. package/dist/react.d.cts +2 -3
  37. package/dist/react.d.ts +2 -3
  38. package/dist/react.js +1 -1
  39. package/dist/react.js.map +1 -1
  40. package/dist/{shared-BW6hoLBY.d.cts → shared-BMVGMnti.d.cts} +3 -1
  41. package/dist/{shared-BiJvoURI.d.ts → shared-DRptGBWP.d.ts} +3 -1
  42. package/package.json +1 -1
package/dist/browser.cjs CHANGED
@@ -662,8 +662,8 @@ function deleteSessionCookie(ctx, skipDontRememberMe) {
662
662
  expireCookie(ctx, ctx.context.authCookies.dontRememberToken);
663
663
  }
664
664
  }
665
- var getSessionCookie = (request, config) => {
666
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
665
+ var getSessionCookie = (request2, config) => {
666
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
667
667
  if (!cookies) {
668
668
  return null;
669
669
  }
@@ -683,8 +683,8 @@ var getSessionCookie = (request, config) => {
683
683
  }
684
684
  return null;
685
685
  };
686
- var getCookieCache = async (request, config) => {
687
- const headers = request instanceof Headers || !("headers" in request) ? request : request.headers;
686
+ var getCookieCache = async (request2, config) => {
687
+ const headers = request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers;
688
688
  const cookieHeader = headers.get("cookie");
689
689
  if (!cookieHeader) {
690
690
  return null;
@@ -802,7 +802,7 @@ var getCookieCache = async (request, config) => {
802
802
 
803
803
  // package.json
804
804
  var package_default = {
805
- version: "2.9.0"
805
+ version: "2.10.0"
806
806
  };
807
807
 
808
808
  // src/sdk-version.ts
@@ -1854,6 +1854,50 @@ function mergeCallOptions(base, override) {
1854
1854
  }
1855
1855
  };
1856
1856
  }
1857
+ function copyDefinedField(target, source, targetKey, sourceKey) {
1858
+ if (!(sourceKey in source)) {
1859
+ return;
1860
+ }
1861
+ const value = source[sourceKey];
1862
+ if (value !== void 0) {
1863
+ target[targetKey] = value;
1864
+ }
1865
+ }
1866
+ function normalizeAdminEmailTemplatePayload(payload) {
1867
+ const normalized = { ...payload };
1868
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
1869
+ copyDefinedField(normalized, payload, "event_type", "eventType");
1870
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
1871
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
1872
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
1873
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
1874
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1875
+ copyDefinedField(normalized, payload, "is_active", "isActive");
1876
+ return normalized;
1877
+ }
1878
+ function toReactEmailTemplateCompatibilityInput(input) {
1879
+ const payload = input;
1880
+ const compatibility = { ...payload };
1881
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
1882
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
1883
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
1884
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
1885
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
1886
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
1887
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
1888
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
1889
+ return compatibility;
1890
+ }
1891
+ function normalizeAdminEmailTemplateSendPayload(payload) {
1892
+ const normalized = { ...payload };
1893
+ copyDefinedField(normalized, payload, "template_id", "templateId");
1894
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
1895
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
1896
+ copyDefinedField(normalized, payload, "user_id", "userId");
1897
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
1898
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
1899
+ return normalized;
1900
+ }
1857
1901
  function toSessionGuardFailure(sessionResult) {
1858
1902
  if (sessionResult.status === 401 || sessionResult.data == null) {
1859
1903
  return {
@@ -2160,7 +2204,7 @@ function createAuthClient(config = {}) {
2160
2204
  ...config,
2161
2205
  baseUrl: normalizedBaseUrl
2162
2206
  };
2163
- const request = (input, options) => {
2207
+ const request2 = (input, options) => {
2164
2208
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
2165
2209
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
2166
2210
  return callAuthEndpoint(
@@ -2173,7 +2217,7 @@ function createAuthClient(config = {}) {
2173
2217
  };
2174
2218
  const postGeneric = (endpoint, input, options) => {
2175
2219
  const { payload, fetchOptions } = extractFetchOptions(input);
2176
- return request(
2220
+ return request2(
2177
2221
  {
2178
2222
  endpoint,
2179
2223
  method: "POST",
@@ -2185,7 +2229,7 @@ function createAuthClient(config = {}) {
2185
2229
  };
2186
2230
  const getGeneric = (endpoint, input, options) => {
2187
2231
  const { fetchOptions } = extractFetchOptions(input);
2188
- return request(
2232
+ return request2(
2189
2233
  {
2190
2234
  endpoint,
2191
2235
  method: "GET",
@@ -2197,7 +2241,7 @@ function createAuthClient(config = {}) {
2197
2241
  const getWithQuery = (endpoint, input, options) => {
2198
2242
  const { payload, fetchOptions } = extractFetchOptions(input);
2199
2243
  const query = payload?.query;
2200
- return request(
2244
+ return request2(
2201
2245
  {
2202
2246
  endpoint,
2203
2247
  method: "GET",
@@ -2215,18 +2259,19 @@ function createAuthClient(config = {}) {
2215
2259
  htmlField: "htmlBody",
2216
2260
  textField: "textBody"
2217
2261
  }, withReactEmailRoute(route));
2218
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
2262
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
2219
2263
  htmlField: "htmlTemplate",
2220
2264
  textField: "textTemplate",
2221
2265
  variablesField: "variables"
2222
2266
  }, withReactEmailRoute(route)).then((payload) => {
2267
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
2223
2268
  if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
2224
2269
  assertAthenaAuthTemplateVariables(
2225
2270
  payload.variables,
2226
2271
  `${route} variables`
2227
2272
  );
2228
2273
  }
2229
- return payload;
2274
+ return normalizedPayload;
2230
2275
  });
2231
2276
  const requireSession = async (input, options) => {
2232
2277
  const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
@@ -2802,7 +2847,15 @@ function createAuthClient(config = {}) {
2802
2847
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2803
2848
  options
2804
2849
  ),
2805
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
2850
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
2851
+ send: (input, options) => postGeneric(
2852
+ "/admin/email-template/send",
2853
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2854
+ options
2855
+ )
2856
+ },
2857
+ eventType: {
2858
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2806
2859
  }
2807
2860
  },
2808
2861
  emailTemplate: {
@@ -2818,7 +2871,15 @@ function createAuthClient(config = {}) {
2818
2871
  "/admin/email-template/update",
2819
2872
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2820
2873
  options
2874
+ ),
2875
+ send: (input, options) => postGeneric(
2876
+ "/admin/email-template/send",
2877
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2878
+ options
2821
2879
  )
2880
+ },
2881
+ emailEventType: {
2882
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2822
2883
  }
2823
2884
  },
2824
2885
  apiKey: {
@@ -2858,7 +2919,7 @@ function createAuthClient(config = {}) {
2858
2919
  throw new Error("callback.provider requires non-empty code and state values");
2859
2920
  }
2860
2921
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
2861
- return request({
2922
+ return request2({
2862
2923
  endpoint,
2863
2924
  method: "GET",
2864
2925
  query: {
@@ -2872,7 +2933,7 @@ function createAuthClient(config = {}) {
2872
2933
  };
2873
2934
  return {
2874
2935
  baseUrl: normalizedBaseUrl,
2875
- request,
2936
+ request: request2,
2876
2937
  signIn: {
2877
2938
  email: (input, options) => executePostWithCompatibleInput(
2878
2939
  resolvedConfig,
@@ -3613,16 +3674,16 @@ function createStorageFileModule(base, config = {}) {
3613
3674
  };
3614
3675
  });
3615
3676
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3616
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
3677
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
3617
3678
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3618
3679
  const uploaded = [];
3619
3680
  for (let index = 0; index < uploadRequests.length; index += 1) {
3620
- const request = uploadRequests[index];
3681
+ const request2 = uploadRequests[index];
3621
3682
  const uploadUrl = uploadUrls[index];
3622
3683
  const response = await putUploadBody(
3623
3684
  uploadUrl.upload.url,
3624
3685
  uploadUrl.upload.headers ?? {},
3625
- request.source,
3686
+ request2.source,
3626
3687
  input,
3627
3688
  options,
3628
3689
  (progress) => {
@@ -3633,13 +3694,13 @@ function createStorageFileModule(base, config = {}) {
3633
3694
  uploaded.push({
3634
3695
  file: uploadUrl.file,
3635
3696
  upload: uploadUrl.upload,
3636
- source: request.source.source,
3637
- fileName: request.source.fileName,
3638
- storage_key: request.uploadRequest.storage_key,
3697
+ source: request2.source.source,
3698
+ fileName: request2.source.fileName,
3699
+ storage_key: request2.uploadRequest.storage_key,
3639
3700
  response
3640
3701
  });
3641
- aggregateLoaded[index] = request.source.sizeBytes;
3642
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
3702
+ aggregateLoaded[index] = request2.source.sizeBytes;
3703
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
3643
3704
  }
3644
3705
  return {
3645
3706
  files: uploaded,
@@ -5614,6 +5675,517 @@ function createStorageModule(gateway, runtimeOptions) {
5614
5675
  };
5615
5676
  }
5616
5677
 
5678
+ // src/chat/module.ts
5679
+ var SDK_NAME3 = "xylex-group/athena-chat";
5680
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
5681
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
5682
+ var AthenaChatError = class extends Error {
5683
+ status;
5684
+ endpoint;
5685
+ method;
5686
+ requestId;
5687
+ body;
5688
+ constructor(input) {
5689
+ super(input.message);
5690
+ this.name = "AthenaChatError";
5691
+ this.status = input.status;
5692
+ this.endpoint = input.endpoint;
5693
+ this.method = input.method;
5694
+ this.requestId = input.requestId;
5695
+ this.body = input.body;
5696
+ }
5697
+ };
5698
+ function deriveRealtimeInfoUrl(wsUrl) {
5699
+ if (!wsUrl) {
5700
+ return void 0;
5701
+ }
5702
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
5703
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
5704
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
5705
+ return parsed.toString();
5706
+ }
5707
+ function normalizeWsUrl(value, label) {
5708
+ const normalized = value.trim();
5709
+ if (!normalized) {
5710
+ throw new Error(`${label} is required.`);
5711
+ }
5712
+ let parsed;
5713
+ try {
5714
+ parsed = new URL(normalized);
5715
+ } catch {
5716
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
5717
+ }
5718
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
5719
+ throw new Error(`${label} must use ws or wss.`);
5720
+ }
5721
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
5722
+ return parsed.toString().replace(/\/$/, "");
5723
+ }
5724
+ function isRecord7(value) {
5725
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5726
+ }
5727
+ function normalizeHeaderValue3(value) {
5728
+ return value ? value : void 0;
5729
+ }
5730
+ function parseResponseBody4(rawText, contentType) {
5731
+ if (!rawText) {
5732
+ return { parsed: null, parseFailed: false };
5733
+ }
5734
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
5735
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
5736
+ if (!looksJson) {
5737
+ return { parsed: rawText, parseFailed: false };
5738
+ }
5739
+ try {
5740
+ return { parsed: JSON.parse(rawText), parseFailed: false };
5741
+ } catch {
5742
+ return { parsed: rawText, parseFailed: true };
5743
+ }
5744
+ }
5745
+ function resolveRequestId3(headers) {
5746
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
5747
+ }
5748
+ function resolveErrorMessage4(payload, fallback) {
5749
+ if (isRecord7(payload)) {
5750
+ for (const candidate of [payload.error, payload.message, payload.details]) {
5751
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
5752
+ return candidate.trim();
5753
+ }
5754
+ }
5755
+ }
5756
+ if (typeof payload === "string" && payload.trim().length > 0) {
5757
+ return payload.trim();
5758
+ }
5759
+ return fallback;
5760
+ }
5761
+ function encodePathSegment(value, label) {
5762
+ const normalized = value.trim();
5763
+ if (!normalized) {
5764
+ throw new Error(`${label} is required.`);
5765
+ }
5766
+ return encodeURIComponent(normalized);
5767
+ }
5768
+ function encodeQuery(query) {
5769
+ if (!query) {
5770
+ return "";
5771
+ }
5772
+ const params = new URLSearchParams();
5773
+ for (const [key, value] of Object.entries(query)) {
5774
+ if (value === void 0 || value === null) {
5775
+ continue;
5776
+ }
5777
+ if (Array.isArray(value)) {
5778
+ for (const item of value) {
5779
+ if (item !== void 0 && item !== null) {
5780
+ params.append(key, String(item));
5781
+ }
5782
+ }
5783
+ continue;
5784
+ }
5785
+ params.set(key, String(value));
5786
+ }
5787
+ const encoded = params.toString();
5788
+ return encoded ? `?${encoded}` : "";
5789
+ }
5790
+ function createSocket(factory, url, protocols) {
5791
+ try {
5792
+ return new factory(url, protocols);
5793
+ } catch (error) {
5794
+ if (error instanceof TypeError) {
5795
+ return factory(url, protocols);
5796
+ }
5797
+ throw error;
5798
+ }
5799
+ }
5800
+ function buildHeaders3(config, options) {
5801
+ const headers = {
5802
+ Accept: "application/json",
5803
+ apikey: config.apiKey,
5804
+ "x-api-key": config.apiKey,
5805
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
5806
+ };
5807
+ if (config.client || options?.client) {
5808
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
5809
+ }
5810
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
5811
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
5812
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
5813
+ }
5814
+ const cookie = options?.cookie ?? config.cookie;
5815
+ if (typeof cookie === "string" && cookie.trim()) {
5816
+ headers.Cookie = cookie;
5817
+ }
5818
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
5819
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
5820
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
5821
+ }
5822
+ if (config.forceNoCache || options?.forceNoCache) {
5823
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
5824
+ }
5825
+ for (const source of [config.headers, options?.headers]) {
5826
+ for (const [key, value] of Object.entries(source ?? {})) {
5827
+ const normalized = normalizeHeaderValue3(value);
5828
+ if (normalized) {
5829
+ headers[key] = normalized;
5830
+ }
5831
+ }
5832
+ }
5833
+ return headers;
5834
+ }
5835
+ function withJsonBody(init, body) {
5836
+ return {
5837
+ ...init,
5838
+ body: body === void 0 ? void 0 : JSON.stringify(body),
5839
+ headers: {
5840
+ "Content-Type": "application/json",
5841
+ ...init.headers
5842
+ }
5843
+ };
5844
+ }
5845
+ async function request(config, method, endpoint, options, body) {
5846
+ if (!config.baseUrl) {
5847
+ throw new Error(
5848
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
5849
+ );
5850
+ }
5851
+ const url = `${config.baseUrl}${endpoint}`;
5852
+ const init = {
5853
+ method,
5854
+ headers: buildHeaders3(config, options),
5855
+ signal: options?.signal
5856
+ };
5857
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
5858
+ const response = await fetch(url, finalInit);
5859
+ const rawText = await response.text();
5860
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
5861
+ if (!response.ok) {
5862
+ throw new AthenaChatError({
5863
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
5864
+ status: response.status,
5865
+ endpoint,
5866
+ method,
5867
+ requestId: resolveRequestId3(response.headers),
5868
+ body: parsed
5869
+ });
5870
+ }
5871
+ return parsed;
5872
+ }
5873
+ function unwrapEnvelopeData(payload) {
5874
+ return payload.data;
5875
+ }
5876
+ function createRealtimeConnection(config, options) {
5877
+ if (!config.wsUrl) {
5878
+ throw new Error(
5879
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5880
+ );
5881
+ }
5882
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
5883
+ if (!wsFactory) {
5884
+ throw new Error(
5885
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
5886
+ );
5887
+ }
5888
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
5889
+ const send = (command) => {
5890
+ socket.send(JSON.stringify(command));
5891
+ };
5892
+ if (options?.onMessage) {
5893
+ const listener = (event) => {
5894
+ const messageEvent = event;
5895
+ const raw = messageEvent?.data;
5896
+ if (typeof raw !== "string") {
5897
+ return;
5898
+ }
5899
+ try {
5900
+ options.onMessage?.(JSON.parse(raw));
5901
+ } catch {
5902
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
5903
+ }
5904
+ };
5905
+ if (typeof socket.addEventListener === "function") {
5906
+ socket.addEventListener("message", listener);
5907
+ } else {
5908
+ socket.onmessage = listener;
5909
+ }
5910
+ }
5911
+ const hello = (command) => {
5912
+ send({
5913
+ type: "auth.hello",
5914
+ token: command?.token,
5915
+ room_subscriptions: command?.room_subscriptions
5916
+ });
5917
+ };
5918
+ if (options?.hello) {
5919
+ const onOpen = () => hello({
5920
+ token: options.hello?.token ?? void 0,
5921
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
5922
+ });
5923
+ if (typeof socket.addEventListener === "function") {
5924
+ socket.addEventListener("open", onOpen);
5925
+ } else {
5926
+ socket.onopen = onOpen;
5927
+ }
5928
+ }
5929
+ return {
5930
+ socket,
5931
+ send,
5932
+ hello,
5933
+ subscribe(roomId, fromSeq) {
5934
+ send({
5935
+ type: "chat.subscribe",
5936
+ room_id: roomId,
5937
+ from_seq: fromSeq ?? void 0
5938
+ });
5939
+ },
5940
+ unsubscribe(roomId) {
5941
+ send({
5942
+ type: "chat.unsubscribe",
5943
+ room_id: roomId
5944
+ });
5945
+ },
5946
+ resume(rooms) {
5947
+ send({
5948
+ type: "chat.resume",
5949
+ rooms
5950
+ });
5951
+ },
5952
+ typingStart(roomId) {
5953
+ send({
5954
+ type: "chat.typing.start",
5955
+ room_id: roomId
5956
+ });
5957
+ },
5958
+ typingStop(roomId) {
5959
+ send({
5960
+ type: "chat.typing.stop",
5961
+ room_id: roomId
5962
+ });
5963
+ },
5964
+ presenceHeartbeat(activeRoomId) {
5965
+ send({
5966
+ type: "chat.presence.heartbeat",
5967
+ active_room_id: activeRoomId ?? void 0
5968
+ });
5969
+ },
5970
+ readUpTo(roomId, input) {
5971
+ send({
5972
+ type: "chat.read.up_to",
5973
+ room_id: roomId,
5974
+ message_id: input?.message_id ?? void 0,
5975
+ seq: input?.seq ?? void 0
5976
+ });
5977
+ },
5978
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
5979
+ send({
5980
+ type: "ping",
5981
+ at
5982
+ });
5983
+ },
5984
+ close(code, reason) {
5985
+ socket.close(code, reason);
5986
+ }
5987
+ };
5988
+ }
5989
+ function createChatModule(config) {
5990
+ const realtime = {
5991
+ info(options) {
5992
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
5993
+ if (!realtimeInfoUrl) {
5994
+ throw new Error(
5995
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5996
+ );
5997
+ }
5998
+ return request(
5999
+ {
6000
+ ...config,
6001
+ baseUrl: realtimeInfoUrl
6002
+ },
6003
+ "GET",
6004
+ "",
6005
+ options
6006
+ );
6007
+ },
6008
+ connect(options) {
6009
+ return createRealtimeConnection(config, options);
6010
+ }
6011
+ };
6012
+ return {
6013
+ room: {
6014
+ list(query, options) {
6015
+ return request(
6016
+ config,
6017
+ "GET",
6018
+ `/rooms${encodeQuery(query)}`,
6019
+ options
6020
+ );
6021
+ },
6022
+ create(input, options) {
6023
+ return request(config, "POST", "/rooms", options, input);
6024
+ },
6025
+ get(roomId, options) {
6026
+ return request(
6027
+ config,
6028
+ "GET",
6029
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6030
+ options
6031
+ );
6032
+ },
6033
+ update(roomId, input, options) {
6034
+ return request(
6035
+ config,
6036
+ "PATCH",
6037
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6038
+ options,
6039
+ input
6040
+ );
6041
+ },
6042
+ archive(roomId, options) {
6043
+ return request(
6044
+ config,
6045
+ "POST",
6046
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
6047
+ options
6048
+ );
6049
+ },
6050
+ readCursor: {
6051
+ upTo(roomId, input, options) {
6052
+ return request(
6053
+ config,
6054
+ "POST",
6055
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
6056
+ options,
6057
+ input ?? {}
6058
+ );
6059
+ }
6060
+ },
6061
+ member: {
6062
+ list(roomId, options) {
6063
+ return request(
6064
+ config,
6065
+ "GET",
6066
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6067
+ options
6068
+ );
6069
+ },
6070
+ add(roomId, input, options) {
6071
+ return request(
6072
+ config,
6073
+ "POST",
6074
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6075
+ options,
6076
+ input
6077
+ );
6078
+ },
6079
+ remove(roomId, userId, options) {
6080
+ return request(
6081
+ config,
6082
+ "DELETE",
6083
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
6084
+ options
6085
+ );
6086
+ }
6087
+ },
6088
+ message: {
6089
+ list(roomId, query, options) {
6090
+ return request(
6091
+ config,
6092
+ "GET",
6093
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
6094
+ options
6095
+ );
6096
+ },
6097
+ send(roomId, input, options) {
6098
+ return request(
6099
+ config,
6100
+ "POST",
6101
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
6102
+ options,
6103
+ input
6104
+ );
6105
+ },
6106
+ update(roomId, messageId, input, options) {
6107
+ return request(
6108
+ config,
6109
+ "PATCH",
6110
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6111
+ options,
6112
+ input
6113
+ );
6114
+ },
6115
+ delete(roomId, messageId, options) {
6116
+ return request(
6117
+ config,
6118
+ "DELETE",
6119
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6120
+ options
6121
+ );
6122
+ }
6123
+ }
6124
+ },
6125
+ message: {
6126
+ reaction: {
6127
+ add(messageId, input, options) {
6128
+ return request(
6129
+ config,
6130
+ "POST",
6131
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
6132
+ options,
6133
+ input
6134
+ );
6135
+ },
6136
+ remove(messageId, emoji, options) {
6137
+ return request(
6138
+ config,
6139
+ "DELETE",
6140
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
6141
+ options
6142
+ );
6143
+ }
6144
+ },
6145
+ search(input, options) {
6146
+ return request(
6147
+ config,
6148
+ "POST",
6149
+ "/messages/search",
6150
+ options,
6151
+ input
6152
+ );
6153
+ }
6154
+ },
6155
+ realtime
6156
+ };
6157
+ }
6158
+ var chatSdkManifest = {
6159
+ namespace: "chat",
6160
+ basePath: "/chat",
6161
+ methods: [
6162
+ { name: "listRooms", method: "GET", path: "/chat/rooms" },
6163
+ { name: "createRoom", method: "POST", path: "/chat/rooms" },
6164
+ { name: "getRoom", method: "GET", path: "/chat/rooms/{room_id}" },
6165
+ { name: "updateRoom", method: "PATCH", path: "/chat/rooms/{room_id}" },
6166
+ { name: "archiveRoom", method: "POST", path: "/chat/rooms/{room_id}/archive" },
6167
+ { name: "listRoomMessages", method: "GET", path: "/chat/rooms/{room_id}/messages" },
6168
+ { name: "sendRoomMessage", method: "POST", path: "/chat/rooms/{room_id}/messages" },
6169
+ { name: "updateRoomMessage", method: "PATCH", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6170
+ { name: "deleteRoomMessage", method: "DELETE", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6171
+ { name: "advanceReadCursor", method: "POST", path: "/chat/rooms/{room_id}/read-cursor" },
6172
+ { name: "listRoomMembers", method: "GET", path: "/chat/rooms/{room_id}/members" },
6173
+ { name: "addRoomMembers", method: "POST", path: "/chat/rooms/{room_id}/members" },
6174
+ { name: "removeRoomMember", method: "DELETE", path: "/chat/rooms/{room_id}/members/{user_id}" },
6175
+ { name: "addReaction", method: "POST", path: "/chat/messages/{message_id}/reactions" },
6176
+ { name: "removeReaction", method: "DELETE", path: "/chat/messages/{message_id}/reactions/{emoji}" },
6177
+ { name: "searchMessages", method: "POST", path: "/chat/messages/search" },
6178
+ { name: "getRealtimeInfo", method: "GET", path: "/wss/info" },
6179
+ { name: "connectRealtime", method: "GET", path: "/wss/gateway" }
6180
+ ]
6181
+ };
6182
+ function unwrapChatRoom(payload) {
6183
+ return unwrapEnvelopeData(payload);
6184
+ }
6185
+ function unwrapChatMessage(payload) {
6186
+ return unwrapEnvelopeData(payload);
6187
+ }
6188
+
5617
6189
  // src/client-builder.ts
5618
6190
  var DEFAULT_BACKEND = { type: "athena" };
5619
6191
  function toBackendConfig(value) {
@@ -5826,7 +6398,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
5826
6398
  "ilike",
5827
6399
  "is"
5828
6400
  ]);
5829
- function isRecord7(value) {
6401
+ function isRecord8(value) {
5830
6402
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5831
6403
  }
5832
6404
  function isUuidString(value) {
@@ -5839,7 +6411,7 @@ function shouldUseUuidTextComparison(column, value) {
5839
6411
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
5840
6412
  }
5841
6413
  function isRelationSelectNode(value) {
5842
- return isRecord7(value) && isRecord7(value.select);
6414
+ return isRecord8(value) && isRecord8(value.select);
5843
6415
  }
5844
6416
  function normalizeIdentifier(value, label) {
5845
6417
  const normalized = value.trim();
@@ -5895,7 +6467,7 @@ function compileRelationToken(key, node) {
5895
6467
  return `${prefix}${relationToken}(${nested})`;
5896
6468
  }
5897
6469
  function compileSelectShape(select) {
5898
- if (!isRecord7(select)) {
6470
+ if (!isRecord8(select)) {
5899
6471
  throw new Error("findMany select must be an object");
5900
6472
  }
5901
6473
  const tokens = [];
@@ -5919,7 +6491,7 @@ function compileSelectShape(select) {
5919
6491
  return tokens.join(",");
5920
6492
  }
5921
6493
  function selectShapeUsesRelationSchema(select) {
5922
- if (!isRecord7(select)) {
6494
+ if (!isRecord8(select)) {
5923
6495
  return false;
5924
6496
  }
5925
6497
  for (const rawValue of Object.values(select)) {
@@ -5937,7 +6509,7 @@ function selectShapeUsesRelationSchema(select) {
5937
6509
  }
5938
6510
  function compileColumnWhere(column, input) {
5939
6511
  const normalizedColumn = normalizeIdentifier(column, "where column");
5940
- if (!isRecord7(input)) {
6512
+ if (!isRecord8(input)) {
5941
6513
  return [buildGatewayCondition("eq", normalizedColumn, input)];
5942
6514
  }
5943
6515
  const conditions = [];
@@ -5965,7 +6537,7 @@ function compileColumnWhere(column, input) {
5965
6537
  return conditions;
5966
6538
  }
5967
6539
  function compileBooleanExpressionTerms(clause, label) {
5968
- if (!isRecord7(clause)) {
6540
+ if (!isRecord8(clause)) {
5969
6541
  throw new Error(`findMany where.${label} clauses must be objects`);
5970
6542
  }
5971
6543
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -5974,7 +6546,7 @@ function compileBooleanExpressionTerms(clause, label) {
5974
6546
  }
5975
6547
  const [rawColumn, rawValue] = entries[0];
5976
6548
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
5977
- if (!isRecord7(rawValue)) {
6549
+ if (!isRecord8(rawValue)) {
5978
6550
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
5979
6551
  }
5980
6552
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -5998,7 +6570,7 @@ function compileWhere(where) {
5998
6570
  if (where === void 0) {
5999
6571
  return void 0;
6000
6572
  }
6001
- if (!isRecord7(where)) {
6573
+ if (!isRecord8(where)) {
6002
6574
  throw new Error("findMany where must be an object");
6003
6575
  }
6004
6576
  const conditions = [];
@@ -6048,7 +6620,7 @@ function compileOrderBy(orderBy) {
6048
6620
  if (orderBy === void 0) {
6049
6621
  return void 0;
6050
6622
  }
6051
- if (!isRecord7(orderBy)) {
6623
+ if (!isRecord8(orderBy)) {
6052
6624
  throw new Error("findMany orderBy must be an object");
6053
6625
  }
6054
6626
  if ("column" in orderBy) {
@@ -6223,11 +6795,11 @@ function toFindManyAstOrder(order) {
6223
6795
  ascending: order.direction !== "descending"
6224
6796
  };
6225
6797
  }
6226
- function isRecord8(value) {
6798
+ function isRecord9(value) {
6227
6799
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6228
6800
  }
6229
6801
  function normalizeFindManyAstColumnPredicate(value) {
6230
- if (!isRecord8(value)) {
6802
+ if (!isRecord9(value)) {
6231
6803
  return {
6232
6804
  eq: value
6233
6805
  };
@@ -6251,7 +6823,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6251
6823
  return normalized;
6252
6824
  }
6253
6825
  function normalizeFindManyAstWhere(where) {
6254
- if (!where || !isRecord8(where)) {
6826
+ if (!where || !isRecord9(where)) {
6255
6827
  return where;
6256
6828
  }
6257
6829
  const normalized = {};
@@ -6265,7 +6837,7 @@ function normalizeFindManyAstWhere(where) {
6265
6837
  );
6266
6838
  continue;
6267
6839
  }
6268
- if (key === "not" && isRecord8(value)) {
6840
+ if (key === "not" && isRecord9(value)) {
6269
6841
  normalized.not = normalizeFindManyAstBooleanOperand(
6270
6842
  value
6271
6843
  );
@@ -6276,7 +6848,7 @@ function normalizeFindManyAstWhere(where) {
6276
6848
  return normalized;
6277
6849
  }
6278
6850
  function predicateRequiresUuidQueryFallback(column, value) {
6279
- if (!isRecord8(value)) {
6851
+ if (!isRecord9(value)) {
6280
6852
  return shouldUseUuidTextComparison(column, value);
6281
6853
  }
6282
6854
  const eqValue = value.eq;
@@ -6294,7 +6866,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6294
6866
  return false;
6295
6867
  }
6296
6868
  function findManyAstWhereRequiresLegacyTransport(where) {
6297
- if (!where || !isRecord8(where)) {
6869
+ if (!where || !isRecord9(where)) {
6298
6870
  return false;
6299
6871
  }
6300
6872
  for (const [key, value] of Object.entries(where)) {
@@ -6309,7 +6881,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6309
6881
  }
6310
6882
  continue;
6311
6883
  }
6312
- if (key === "not" && isRecord8(value)) {
6884
+ if (key === "not" && isRecord9(value)) {
6313
6885
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6314
6886
  return true;
6315
6887
  }
@@ -6858,6 +7430,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
6858
7430
  var DEFAULT_COLUMNS = "*";
6859
7431
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6860
7432
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7433
+ var SDK_NAME4 = "xylex-group/athena";
6861
7434
  function formatResult(response) {
6862
7435
  const result = {
6863
7436
  data: response.data ?? null,
@@ -6934,7 +7507,7 @@ async function executeExperimentalRead(experimental, runner) {
6934
7507
  throw error;
6935
7508
  }
6936
7509
  }
6937
- function isRecord9(value) {
7510
+ function isRecord10(value) {
6938
7511
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6939
7512
  }
6940
7513
  function firstNonEmptyString2(...values) {
@@ -6946,8 +7519,8 @@ function firstNonEmptyString2(...values) {
6946
7519
  return void 0;
6947
7520
  }
6948
7521
  function resolveStructuredErrorPayload2(raw) {
6949
- if (!isRecord9(raw)) return null;
6950
- return isRecord9(raw.error) ? raw.error : raw;
7522
+ if (!isRecord10(raw)) return null;
7523
+ return isRecord10(raw.error) ? raw.error : raw;
6951
7524
  }
6952
7525
  function resolveStructuredErrorDetails(payload, message) {
6953
7526
  if (!payload || !("details" in payload)) {
@@ -6963,7 +7536,7 @@ function resolveStructuredErrorDetails(payload, message) {
6963
7536
  return details;
6964
7537
  }
6965
7538
  function createResultError(response, result, normalized) {
6966
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7539
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
6967
7540
  const payload = resolveStructuredErrorPayload2(response.raw);
6968
7541
  const message = firstNonEmptyString2(
6969
7542
  response.error,
@@ -7026,6 +7599,43 @@ function asAthenaJsonObject(value) {
7026
7599
  function asAthenaJsonObjectArray(values) {
7027
7600
  return values;
7028
7601
  }
7602
+ function parseArbitraryResponseBody(rawText, contentType) {
7603
+ if (!rawText) {
7604
+ return null;
7605
+ }
7606
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
7607
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
7608
+ if (!looksJson) {
7609
+ return rawText;
7610
+ }
7611
+ try {
7612
+ return JSON.parse(rawText);
7613
+ } catch {
7614
+ return rawText;
7615
+ }
7616
+ }
7617
+ function toRequestQueryString(query) {
7618
+ if (!query) {
7619
+ return "";
7620
+ }
7621
+ const params = new URLSearchParams();
7622
+ for (const [key, value] of Object.entries(query)) {
7623
+ if (value === void 0 || value === null) {
7624
+ continue;
7625
+ }
7626
+ if (Array.isArray(value)) {
7627
+ for (const item of value) {
7628
+ if (item !== void 0 && item !== null) {
7629
+ params.append(key, String(item));
7630
+ }
7631
+ }
7632
+ continue;
7633
+ }
7634
+ params.set(key, String(value));
7635
+ }
7636
+ const encoded = params.toString();
7637
+ return encoded ? `?${encoded}` : "";
7638
+ }
7029
7639
  function normalizeSelectColumnsInput(columns) {
7030
7640
  if (columns === void 0) {
7031
7641
  return void 0;
@@ -8332,6 +8942,8 @@ var ATHENA_ENV_GATEWAY_URL_KEYS = [
8332
8942
  "NEXT_PUBLIC_ATHENA_DB_API_URL"
8333
8943
  ];
8334
8944
  var ATHENA_ENV_AUTH_URL_KEYS = ["ATHENA_AUTH_URL", "NEXT_PUBLIC_ATHENA_AUTH_URL"];
8945
+ var ATHENA_ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
8946
+ var ATHENA_ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
8335
8947
  var ATHENA_ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
8336
8948
  var ATHENA_ENV_KEY_KEYS = [
8337
8949
  "ATHENA_API_KEY",
@@ -8412,6 +9024,15 @@ function appendServicePath(baseUrl, segment) {
8412
9024
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8413
9025
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8414
9026
  }
9027
+ function appendRealtimeGatewayPath(baseUrl) {
9028
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
9029
+ const wsUrl = new URL(normalizedBaseUrl);
9030
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
9031
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
9032
+ wsUrl.search = "";
9033
+ wsUrl.hash = "";
9034
+ return wsUrl.toString();
9035
+ }
8415
9036
  function resolveServiceUrlOverride(value, label) {
8416
9037
  return resolveClientServiceBaseUrl(value, label);
8417
9038
  }
@@ -8420,6 +9041,8 @@ function resolveServiceUrls(config) {
8420
9041
  return {
8421
9042
  dbUrl: resolveServiceUrlOverride(config.db?.url, "Athena DB base URL") ?? resolveServiceUrlOverride(config.gateway?.url, "Athena gateway base URL") ?? resolveServiceUrlOverride(config.dbUrl, "Athena DB base URL") ?? resolveServiceUrlOverride(config.gatewayUrl, "Athena gateway base URL") ?? (baseUrl ? appendServicePath(baseUrl, "db") : void 0),
8422
9043
  authUrl: resolveServiceUrlOverride(config.auth?.url, "Athena auth base URL") ?? resolveServiceUrlOverride(config.auth?.baseUrl, "Athena auth base URL") ?? resolveServiceUrlOverride(config.authUrl, "Athena auth base URL") ?? (baseUrl ? appendServicePath(baseUrl, "auth") : void 0),
9044
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
9045
+ chatWsUrl: normalizeOptionalString(config.chat?.wsUrl) ?? normalizeOptionalString(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
8423
9046
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8424
9047
  };
8425
9048
  }
@@ -8512,6 +9135,7 @@ function mergeClientOverrideOptions(base, overrides) {
8512
9135
  } : void 0,
8513
9136
  db: base.db ? { ...base.db } : void 0,
8514
9137
  gateway: base.gateway ? { ...base.gateway } : void 0,
9138
+ chat: base.chat ? { ...base.chat } : void 0,
8515
9139
  storage: base.storage ? { ...base.storage } : void 0
8516
9140
  };
8517
9141
  }
@@ -8522,6 +9146,7 @@ function mergeClientOverrideOptions(base, overrides) {
8522
9146
  auth: mergeAuthClientOptions(base.auth, overrides.auth),
8523
9147
  db: mergeServiceUrlOverrides(base.db, overrides.db),
8524
9148
  gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9149
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
8525
9150
  storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
8526
9151
  };
8527
9152
  }
@@ -8580,6 +9205,9 @@ function resolveCreateClientConfig(config) {
8580
9205
  headers: config.headers,
8581
9206
  auth: config.auth,
8582
9207
  authUrl: resolvedUrls.authUrl,
9208
+ chat: config.chat,
9209
+ chatUrl: resolvedUrls.chatUrl,
9210
+ chatWsUrl: resolvedUrls.chatWsUrl,
8583
9211
  storageUrl: resolvedUrls.storageUrl,
8584
9212
  experimental: config.experimental
8585
9213
  };
@@ -8664,6 +9292,119 @@ function createClientFromConfig(config, sourceConfig) {
8664
9292
  queryTracer
8665
9293
  );
8666
9294
  const db = createDbModule({ from, rpc, query });
9295
+ const chat = createChatModule({
9296
+ baseUrl: config.chatUrl,
9297
+ apiKey: config.apiKey,
9298
+ client: config.client,
9299
+ headers: config.headers,
9300
+ bearerToken: normalizedAuthConfig?.bearerToken,
9301
+ cookie: normalizedAuthConfig?.cookie,
9302
+ sessionToken: normalizedAuthConfig?.sessionToken,
9303
+ forceNoCache: config.forceNoCache,
9304
+ wsUrl: config.chatWsUrl,
9305
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
9306
+ });
9307
+ const request2 = async (options) => {
9308
+ const method = options.method ?? "GET";
9309
+ const responseType = options.responseType ?? "json";
9310
+ const service = options.service ?? "db";
9311
+ const baseUrlByService = {
9312
+ db: config.baseUrl,
9313
+ auth: config.authUrl,
9314
+ chat: config.chatUrl,
9315
+ storage: config.storageUrl
9316
+ };
9317
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
9318
+ if (!resolvedBaseUrl) {
9319
+ throw new Error(
9320
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
9321
+ );
9322
+ }
9323
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
9324
+ label: `Athena ${service} base URL`
9325
+ });
9326
+ const normalizedPath = options.url ? "" : (() => {
9327
+ const path = options.path?.trim();
9328
+ if (!path) {
9329
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
9330
+ }
9331
+ return path.startsWith("/") ? path : `/${path}`;
9332
+ })();
9333
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
9334
+ const headers = {
9335
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
9336
+ ...config.headers ?? {},
9337
+ ...options.headers ?? {}
9338
+ };
9339
+ if (service !== "auth") {
9340
+ headers.apikey = headers.apikey ?? config.apiKey;
9341
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
9342
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
9343
+ headers["X-Athena-Client"] = config.client;
9344
+ }
9345
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
9346
+ headers["X-User-Id"] = config.userId;
9347
+ }
9348
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
9349
+ headers["X-Organization-Id"] = config.organizationId;
9350
+ }
9351
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9352
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9353
+ }
9354
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
9355
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9356
+ }
9357
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9358
+ headers.Cookie = normalizedAuthConfig.cookie;
9359
+ }
9360
+ } else {
9361
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
9362
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
9363
+ headers.apikey = headers.apikey ?? authApiKey;
9364
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
9365
+ }
9366
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
9367
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
9368
+ }
9369
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9370
+ headers.Cookie = normalizedAuthConfig.cookie;
9371
+ }
9372
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9373
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9374
+ }
9375
+ }
9376
+ const shouldSendJsonBody = options.body !== void 0 && options.body !== null && !(options.body instanceof FormData) && !(options.body instanceof Blob) && !(options.body instanceof URLSearchParams) && !(options.body instanceof ArrayBuffer) && !ArrayBuffer.isView(options.body) && typeof options.body !== "string";
9377
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
9378
+ headers["Content-Type"] = "application/json";
9379
+ }
9380
+ const response = await fetch(targetUrl, {
9381
+ method,
9382
+ headers,
9383
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
9384
+ signal: options.signal,
9385
+ credentials: options.credentials
9386
+ });
9387
+ if (responseType === "response") {
9388
+ return {
9389
+ ok: response.ok,
9390
+ status: response.status,
9391
+ statusText: response.statusText,
9392
+ headers: response.headers,
9393
+ data: null,
9394
+ raw: response
9395
+ };
9396
+ }
9397
+ const rawText = await response.text();
9398
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
9399
+ return {
9400
+ ok: response.ok,
9401
+ status: response.status,
9402
+ statusText: response.statusText,
9403
+ headers: response.headers,
9404
+ data: parsed,
9405
+ raw: response
9406
+ };
9407
+ };
8667
9408
  const withContext = (context) => createClientFromInput(
8668
9409
  mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
8669
9410
  );
@@ -8679,8 +9420,10 @@ function createClientFromConfig(config, sourceConfig) {
8679
9420
  db,
8680
9421
  rpc,
8681
9422
  query,
9423
+ request: request2,
8682
9424
  verifyConnection: gateway.verifyConnection,
8683
9425
  auth: auth.auth,
9426
+ chat,
8684
9427
  withContext,
8685
9428
  withSession,
8686
9429
  withOptions: authWithOptions
@@ -8725,6 +9468,8 @@ var AthenaClient = class {
8725
9468
  const url = options.url ?? readFirstEnvValue(env, ATHENA_ENV_URL_KEYS);
8726
9469
  const gatewayUrl = options.gatewayUrl ?? readFirstEnvValue(env, ATHENA_ENV_GATEWAY_URL_KEYS);
8727
9470
  const authUrl = options.authUrl ?? readFirstEnvValue(env, ATHENA_ENV_AUTH_URL_KEYS);
9471
+ const chatUrl = options.chatUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_URL_KEYS);
9472
+ const chatWsUrl = options.chatWsUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_WS_URL_KEYS);
8728
9473
  const storageUrl = options.storageUrl ?? readFirstEnvValue(env, ATHENA_ENV_STORAGE_URL_KEYS);
8729
9474
  const key = options.key ?? readFirstEnvValue(env, ATHENA_ENV_KEY_KEYS);
8730
9475
  const client = options.client ?? readFirstEnvValue(env, ATHENA_ENV_CLIENT_KEYS);
@@ -8739,6 +9484,8 @@ var AthenaClient = class {
8739
9484
  url,
8740
9485
  gatewayUrl,
8741
9486
  authUrl,
9487
+ chatUrl,
9488
+ chatWsUrl,
8742
9489
  storageUrl,
8743
9490
  key,
8744
9491
  client
@@ -8784,7 +9531,7 @@ function resolveNullishValue(mode) {
8784
9531
  if (mode === "null") return null;
8785
9532
  return "";
8786
9533
  }
8787
- function isRecord10(value) {
9534
+ function isRecord11(value) {
8788
9535
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8789
9536
  }
8790
9537
  function isNullableColumn(model, key) {
@@ -8793,7 +9540,7 @@ function isNullableColumn(model, key) {
8793
9540
  }
8794
9541
  function toModelFormDefaults(model, values, options) {
8795
9542
  const source = values;
8796
- if (!isRecord10(source)) {
9543
+ if (!isRecord11(source)) {
8797
9544
  return {};
8798
9545
  }
8799
9546
  const mode = options?.nullishMode ?? "empty-string";
@@ -9307,6 +10054,9 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
9307
10054
  query(query, options) {
9308
10055
  return this.baseClient.query(query, options);
9309
10056
  }
10057
+ request(options) {
10058
+ return this.baseClient.request(options);
10059
+ }
9310
10060
  verifyConnection(options) {
9311
10061
  return this.baseClient.verifyConnection(options);
9312
10062
  }
@@ -9740,15 +10490,15 @@ function readCookieFromHeaders(headers, name) {
9740
10490
  }
9741
10491
  return parseCookies(cookieHeader).get(name);
9742
10492
  }
9743
- function isRecord11(value) {
10493
+ function isRecord12(value) {
9744
10494
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9745
10495
  }
9746
10496
  function resolveSessionCandidate(value) {
9747
- if (!isRecord11(value)) {
10497
+ if (!isRecord12(value)) {
9748
10498
  return null;
9749
10499
  }
9750
- const session = isRecord11(value.session) ? value.session : void 0;
9751
- const user = isRecord11(value.user) ? value.user : void 0;
10500
+ const session = isRecord12(value.session) ? value.session : void 0;
10501
+ const user = isRecord12(value.user) ? value.user : void 0;
9752
10502
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
9753
10503
  return {
9754
10504
  session,
@@ -9758,7 +10508,7 @@ function resolveSessionCandidate(value) {
9758
10508
  return null;
9759
10509
  }
9760
10510
  function inferSessionPair(returned) {
9761
- return resolveSessionCandidate(returned) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.session) : null);
10511
+ return resolveSessionCandidate(returned) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.session) : null);
9762
10512
  }
9763
10513
  function resolveResponseHeaders(ctx) {
9764
10514
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -9781,23 +10531,23 @@ function normalizeBasePath(basePath) {
9781
10531
  function isDynamicBaseURLConfig2(baseURL) {
9782
10532
  return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
9783
10533
  }
9784
- function getRequestUrl(request) {
10534
+ function getRequestUrl(request2) {
9785
10535
  try {
9786
- return new URL(request.url);
10536
+ return new URL(request2.url);
9787
10537
  } catch {
9788
10538
  return new URL("http://localhost");
9789
10539
  }
9790
10540
  }
9791
- function getRequestHost(request, url) {
9792
- const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
9793
- const host = forwardedHost || request.headers.get("host") || url.host;
10541
+ function getRequestHost(request2, url) {
10542
+ const forwardedHost = request2.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
10543
+ const host = forwardedHost || request2.headers.get("host") || url.host;
9794
10544
  return host || null;
9795
10545
  }
9796
- function getRequestProtocol(request, configuredProtocol, url) {
10546
+ function getRequestProtocol(request2, configuredProtocol, url) {
9797
10547
  if (configuredProtocol === "http" || configuredProtocol === "https") {
9798
10548
  return configuredProtocol;
9799
10549
  }
9800
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
10550
+ const forwardedProto = request2.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
9801
10551
  if (forwardedProto === "http" || forwardedProto === "https") {
9802
10552
  return forwardedProto;
9803
10553
  }
@@ -9806,12 +10556,12 @@ function getRequestProtocol(request, configuredProtocol, url) {
9806
10556
  }
9807
10557
  return "http";
9808
10558
  }
9809
- function resolveRequestBaseURL(baseURL, request) {
10559
+ function resolveRequestBaseURL(baseURL, request2) {
9810
10560
  if (typeof baseURL === "string") {
9811
10561
  return normalizeBaseURL(baseURL);
9812
10562
  }
9813
- const requestUrl = getRequestUrl(request);
9814
- const host = getRequestHost(request, requestUrl);
10563
+ const requestUrl = getRequestUrl(request2);
10564
+ const host = getRequestHost(request2, requestUrl);
9815
10565
  if (!host) {
9816
10566
  return null;
9817
10567
  }
@@ -9821,7 +10571,7 @@ function resolveRequestBaseURL(baseURL, request) {
9821
10571
  return null;
9822
10572
  }
9823
10573
  }
9824
- const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request, baseURL.protocol, requestUrl) : getRequestProtocol(request, void 0, requestUrl);
10574
+ const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request2, baseURL.protocol, requestUrl) : getRequestProtocol(request2, void 0, requestUrl);
9825
10575
  return `${protocol}://${host}`;
9826
10576
  }
9827
10577
  function getOrigin(baseURL) {
@@ -9834,16 +10584,16 @@ function getOrigin(baseURL) {
9834
10584
  return void 0;
9835
10585
  }
9836
10586
  }
9837
- async function resolveTrustedOrigins(config, baseURL, request) {
9838
- const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request) : config.trustedOrigins ?? [];
10587
+ async function resolveTrustedOrigins(config, baseURL, request2) {
10588
+ const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request2) : config.trustedOrigins ?? [];
9839
10589
  const values = [
9840
10590
  getOrigin(baseURL),
9841
10591
  ...resolved
9842
10592
  ];
9843
10593
  return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
9844
10594
  }
9845
- async function resolveTrustedProviders(config, request) {
9846
- const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request) : config.trustedProviders ?? [];
10595
+ async function resolveTrustedProviders(config, request2) {
10596
+ const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request2) : config.trustedProviders ?? [];
9847
10597
  const values = [
9848
10598
  ...Object.keys(config.socialProviders ?? {}),
9849
10599
  ...configured
@@ -9968,9 +10718,9 @@ function athenaAuth(config) {
9968
10718
  }
9969
10719
  return ctx;
9970
10720
  };
9971
- const resolveRequestContext = async (request) => {
9972
- const requestUrl = getRequestUrl(request);
9973
- const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request);
10721
+ const resolveRequestContext = async (request2) => {
10722
+ const requestUrl = getRequestUrl(request2);
10723
+ const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request2);
9974
10724
  if (!resolvedBaseURL) {
9975
10725
  throw new Error(
9976
10726
  isDynamicBaseURLConfig2(config.baseURL) ? "Could not resolve base URL from request. Check allowedHosts/baseURL." : "Could not resolve base URL from request."
@@ -9981,17 +10731,17 @@ function athenaAuth(config) {
9981
10731
  session: config.session,
9982
10732
  advanced: config.advanced
9983
10733
  });
9984
- const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request);
9985
- const trustedProviders = await resolveTrustedProviders(config, request);
10734
+ const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request2);
10735
+ const trustedProviders = await resolveTrustedProviders(config, request2);
9986
10736
  return {
9987
10737
  auth,
9988
- request,
10738
+ request: request2,
9989
10739
  url: requestUrl,
9990
10740
  path: requestUrl.pathname,
9991
10741
  basePath: normalizedBasePath,
9992
10742
  baseURL: resolvedBaseURL,
9993
10743
  origin: getOrigin(resolvedBaseURL) ?? resolvedBaseURL,
9994
- headers: request.headers,
10744
+ headers: request2.headers,
9995
10745
  cookies: requestCookies,
9996
10746
  trustedOrigins,
9997
10747
  trustedProviders,
@@ -10004,8 +10754,8 @@ function athenaAuth(config) {
10004
10754
  socialProviders: auth.socialProviders
10005
10755
  };
10006
10756
  };
10007
- const handler = async (request) => {
10008
- const requestContext = await resolveRequestContext(request);
10757
+ const handler = async (request2) => {
10758
+ const requestContext = await resolveRequestContext(request2);
10009
10759
  if (typeof config.handler !== "function") {
10010
10760
  return createJsonResponse(
10011
10761
  {
@@ -10026,7 +10776,7 @@ function athenaAuth(config) {
10026
10776
  const responseHeaders = new Headers(response.headers);
10027
10777
  await runAfterHooks({
10028
10778
  path: requestContext.path,
10029
- headers: request.headers,
10779
+ headers: request2.headers,
10030
10780
  context: {
10031
10781
  responseHeaders,
10032
10782
  returned: result.returned,
@@ -10139,6 +10889,7 @@ exports.ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = ATHENA_AUTH_MAX_ADMIN_JSON_BYTES;
10139
10889
  exports.ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH;
10140
10890
  exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = ATHENA_AUTH_MAX_TEMPLATE_VARIABLES;
10141
10891
  exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH;
10892
+ exports.AthenaChatError = AthenaChatError;
10142
10893
  exports.AthenaClient = AthenaClient;
10143
10894
  exports.AthenaError = AthenaError;
10144
10895
  exports.AthenaErrorCategory = AthenaErrorCategory;
@@ -10152,6 +10903,7 @@ exports.DEFAULT_POSTGRES_SCHEMAS = DEFAULT_POSTGRES_SCHEMAS;
10152
10903
  exports.assertInt = assertInt;
10153
10904
  exports.athenaAuth = athenaAuth;
10154
10905
  exports.boolean = boolean;
10906
+ exports.chatSdkManifest = chatSdkManifest;
10155
10907
  exports.coerceInt = coerceInt;
10156
10908
  exports.createAthenaStorageError = createAthenaStorageError;
10157
10909
  exports.createAuthClient = createAuthClient;
@@ -10198,6 +10950,8 @@ exports.table = table;
10198
10950
  exports.toModelFormDefaults = toModelFormDefaults;
10199
10951
  exports.toModelPayload = toModelPayload;
10200
10952
  exports.unwrap = unwrap;
10953
+ exports.unwrapChatMessage = unwrapChatMessage;
10954
+ exports.unwrapChatRoom = unwrapChatRoom;
10201
10955
  exports.unwrapOne = unwrapOne;
10202
10956
  exports.unwrapRows = unwrapRows;
10203
10957
  exports.verifyAthenaGatewayUrl = verifyAthenaGatewayUrl;