@xylex-group/athena 2.9.0 → 2.11.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 +112 -28
  2. package/dist/browser.cjs +865 -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 +862 -75
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +785 -40
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.js +785 -40
  11. package/dist/cli/index.js.map +1 -1
  12. package/dist/{client-D6EIJdQS.d.ts → client-DD_UeF3Q.d.ts} +508 -22
  13. package/dist/{client-CfAE_QOj.d.cts → client-WqBuu60O.d.cts} +508 -22
  14. package/dist/index.cjs +865 -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 +862 -75
  19. package/dist/index.js.map +1 -1
  20. package/dist/{react-email-BvJ3fj_F.d.cts → module-BFMyVmwX.d.cts} +97 -2
  21. package/dist/{react-email-PLAJuZuO.d.ts → module-DRkIHtY-.d.ts} +97 -2
  22. package/dist/next/client.cjs +793 -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 +793 -40
  27. package/dist/next/client.js.map +1 -1
  28. package/dist/next/server.cjs +793 -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 +793 -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-B1ueL-Ox.d.cts} +3 -1
  41. package/dist/{shared-BiJvoURI.d.ts → shared-GPAprhBb.d.ts} +3 -1
  42. package/package.json +2 -2
package/dist/index.cjs CHANGED
@@ -666,8 +666,8 @@ function deleteSessionCookie(ctx, skipDontRememberMe) {
666
666
  expireCookie(ctx, ctx.context.authCookies.dontRememberToken);
667
667
  }
668
668
  }
669
- var getSessionCookie = (request, config) => {
670
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
669
+ var getSessionCookie = (request2, config) => {
670
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
671
671
  if (!cookies) {
672
672
  return null;
673
673
  }
@@ -687,8 +687,8 @@ var getSessionCookie = (request, config) => {
687
687
  }
688
688
  return null;
689
689
  };
690
- var getCookieCache = async (request, config) => {
691
- const headers = request instanceof Headers || !("headers" in request) ? request : request.headers;
690
+ var getCookieCache = async (request2, config) => {
691
+ const headers = request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers;
692
692
  const cookieHeader = headers.get("cookie");
693
693
  if (!cookieHeader) {
694
694
  return null;
@@ -806,7 +806,7 @@ var getCookieCache = async (request, config) => {
806
806
 
807
807
  // package.json
808
808
  var package_default = {
809
- version: "2.9.0"
809
+ version: "2.11.0"
810
810
  };
811
811
 
812
812
  // src/sdk-version.ts
@@ -1858,6 +1858,87 @@ function mergeCallOptions(base, override) {
1858
1858
  }
1859
1859
  };
1860
1860
  }
1861
+ function copyDefinedField(target, source, targetKey, sourceKey) {
1862
+ if (!(sourceKey in source)) {
1863
+ return;
1864
+ }
1865
+ const value = source[sourceKey];
1866
+ if (value !== void 0) {
1867
+ target[targetKey] = value;
1868
+ }
1869
+ }
1870
+ function normalizeEmailTemplateAttachmentsValue(value) {
1871
+ if (typeof value === "string" || value == null) {
1872
+ return value;
1873
+ }
1874
+ if (Array.isArray(value)) {
1875
+ return value.map((item) => normalizeEmailTemplateAttachmentsValue(item));
1876
+ }
1877
+ if (typeof value !== "object") {
1878
+ return value;
1879
+ }
1880
+ const attachment = { ...value };
1881
+ copyDefinedField(attachment, attachment, "file_url", "fileUrl");
1882
+ delete attachment.fileUrl;
1883
+ return attachment;
1884
+ }
1885
+ function normalizeAdminEmailTemplatePayload(payload) {
1886
+ const normalized = { ...payload };
1887
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
1888
+ copyDefinedField(normalized, payload, "event_type", "eventType");
1889
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
1890
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
1891
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
1892
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
1893
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1894
+ copyDefinedField(normalized, payload, "is_active", "isActive");
1895
+ if (Object.hasOwn(payload, "attachments")) {
1896
+ normalized.attachments = normalizeEmailTemplateAttachmentsValue(payload.attachments);
1897
+ }
1898
+ delete normalized.templateKey;
1899
+ delete normalized.eventType;
1900
+ delete normalized.subjectTemplate;
1901
+ delete normalized.textTemplate;
1902
+ delete normalized.htmlTemplate;
1903
+ delete normalized.variableBindings;
1904
+ delete normalized.attachmentFailureMode;
1905
+ delete normalized.isActive;
1906
+ return normalized;
1907
+ }
1908
+ function toReactEmailTemplateCompatibilityInput(input) {
1909
+ const payload = input;
1910
+ const compatibility = { ...payload };
1911
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
1912
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
1913
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
1914
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
1915
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
1916
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
1917
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
1918
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
1919
+ return compatibility;
1920
+ }
1921
+ function normalizeAdminEmailTemplateSendPayload(payload) {
1922
+ const normalized = { ...payload };
1923
+ copyDefinedField(normalized, payload, "template_id", "templateId");
1924
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
1925
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
1926
+ copyDefinedField(normalized, payload, "user_id", "userId");
1927
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
1928
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
1929
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1930
+ if (Object.hasOwn(payload, "attachments")) {
1931
+ normalized.attachments = normalizeEmailTemplateAttachmentsValue(payload.attachments);
1932
+ }
1933
+ delete normalized.templateId;
1934
+ delete normalized.recipientEmail;
1935
+ delete normalized.renderVariables;
1936
+ delete normalized.userId;
1937
+ delete normalized.organizationId;
1938
+ delete normalized.sessionToken;
1939
+ delete normalized.attachmentFailureMode;
1940
+ return normalized;
1941
+ }
1861
1942
  function toSessionGuardFailure(sessionResult) {
1862
1943
  if (sessionResult.status === 401 || sessionResult.data == null) {
1863
1944
  return {
@@ -2164,7 +2245,7 @@ function createAuthClient(config = {}) {
2164
2245
  ...config,
2165
2246
  baseUrl: normalizedBaseUrl
2166
2247
  };
2167
- const request = (input, options) => {
2248
+ const request2 = (input, options) => {
2168
2249
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
2169
2250
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
2170
2251
  return callAuthEndpoint(
@@ -2177,7 +2258,7 @@ function createAuthClient(config = {}) {
2177
2258
  };
2178
2259
  const postGeneric = (endpoint, input, options) => {
2179
2260
  const { payload, fetchOptions } = extractFetchOptions(input);
2180
- return request(
2261
+ return request2(
2181
2262
  {
2182
2263
  endpoint,
2183
2264
  method: "POST",
@@ -2189,7 +2270,7 @@ function createAuthClient(config = {}) {
2189
2270
  };
2190
2271
  const getGeneric = (endpoint, input, options) => {
2191
2272
  const { fetchOptions } = extractFetchOptions(input);
2192
- return request(
2273
+ return request2(
2193
2274
  {
2194
2275
  endpoint,
2195
2276
  method: "GET",
@@ -2201,7 +2282,7 @@ function createAuthClient(config = {}) {
2201
2282
  const getWithQuery = (endpoint, input, options) => {
2202
2283
  const { payload, fetchOptions } = extractFetchOptions(input);
2203
2284
  const query = payload?.query;
2204
- return request(
2285
+ return request2(
2205
2286
  {
2206
2287
  endpoint,
2207
2288
  method: "GET",
@@ -2219,18 +2300,19 @@ function createAuthClient(config = {}) {
2219
2300
  htmlField: "htmlBody",
2220
2301
  textField: "textBody"
2221
2302
  }, withReactEmailRoute(route));
2222
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
2303
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
2223
2304
  htmlField: "htmlTemplate",
2224
2305
  textField: "textTemplate",
2225
2306
  variablesField: "variables"
2226
2307
  }, withReactEmailRoute(route)).then((payload) => {
2308
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
2227
2309
  if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
2228
2310
  assertAthenaAuthTemplateVariables(
2229
2311
  payload.variables,
2230
2312
  `${route} variables`
2231
2313
  );
2232
2314
  }
2233
- return payload;
2315
+ return normalizedPayload;
2234
2316
  });
2235
2317
  const requireSession = async (input, options) => {
2236
2318
  const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
@@ -2806,7 +2888,15 @@ function createAuthClient(config = {}) {
2806
2888
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2807
2889
  options
2808
2890
  ),
2809
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
2891
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
2892
+ send: (input, options) => postGeneric(
2893
+ "/admin/email-template/send",
2894
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2895
+ options
2896
+ )
2897
+ },
2898
+ eventType: {
2899
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2810
2900
  }
2811
2901
  },
2812
2902
  emailTemplate: {
@@ -2822,7 +2912,15 @@ function createAuthClient(config = {}) {
2822
2912
  "/admin/email-template/update",
2823
2913
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2824
2914
  options
2915
+ ),
2916
+ send: (input, options) => postGeneric(
2917
+ "/admin/email-template/send",
2918
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2919
+ options
2825
2920
  )
2921
+ },
2922
+ emailEventType: {
2923
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2826
2924
  }
2827
2925
  },
2828
2926
  apiKey: {
@@ -2862,7 +2960,7 @@ function createAuthClient(config = {}) {
2862
2960
  throw new Error("callback.provider requires non-empty code and state values");
2863
2961
  }
2864
2962
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
2865
- return request({
2963
+ return request2({
2866
2964
  endpoint,
2867
2965
  method: "GET",
2868
2966
  query: {
@@ -2876,7 +2974,7 @@ function createAuthClient(config = {}) {
2876
2974
  };
2877
2975
  return {
2878
2976
  baseUrl: normalizedBaseUrl,
2879
- request,
2977
+ request: request2,
2880
2978
  signIn: {
2881
2979
  email: (input, options) => executePostWithCompatibleInput(
2882
2980
  resolvedConfig,
@@ -3617,16 +3715,16 @@ function createStorageFileModule(base, config = {}) {
3617
3715
  };
3618
3716
  });
3619
3717
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3620
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
3718
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
3621
3719
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3622
3720
  const uploaded = [];
3623
3721
  for (let index = 0; index < uploadRequests.length; index += 1) {
3624
- const request = uploadRequests[index];
3722
+ const request2 = uploadRequests[index];
3625
3723
  const uploadUrl = uploadUrls[index];
3626
3724
  const response = await putUploadBody(
3627
3725
  uploadUrl.upload.url,
3628
3726
  uploadUrl.upload.headers ?? {},
3629
- request.source,
3727
+ request2.source,
3630
3728
  input,
3631
3729
  options,
3632
3730
  (progress) => {
@@ -3637,13 +3735,13 @@ function createStorageFileModule(base, config = {}) {
3637
3735
  uploaded.push({
3638
3736
  file: uploadUrl.file,
3639
3737
  upload: uploadUrl.upload,
3640
- source: request.source.source,
3641
- fileName: request.source.fileName,
3642
- storage_key: request.uploadRequest.storage_key,
3738
+ source: request2.source.source,
3739
+ fileName: request2.source.fileName,
3740
+ storage_key: request2.uploadRequest.storage_key,
3643
3741
  response
3644
3742
  });
3645
- aggregateLoaded[index] = request.source.sizeBytes;
3646
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
3743
+ aggregateLoaded[index] = request2.source.sizeBytes;
3744
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
3647
3745
  }
3648
3746
  return {
3649
3747
  files: uploaded,
@@ -5618,6 +5716,517 @@ function createStorageModule(gateway, runtimeOptions) {
5618
5716
  };
5619
5717
  }
5620
5718
 
5719
+ // src/chat/module.ts
5720
+ var SDK_NAME3 = "xylex-group/athena-chat";
5721
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
5722
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
5723
+ var AthenaChatError = class extends Error {
5724
+ status;
5725
+ endpoint;
5726
+ method;
5727
+ requestId;
5728
+ body;
5729
+ constructor(input) {
5730
+ super(input.message);
5731
+ this.name = "AthenaChatError";
5732
+ this.status = input.status;
5733
+ this.endpoint = input.endpoint;
5734
+ this.method = input.method;
5735
+ this.requestId = input.requestId;
5736
+ this.body = input.body;
5737
+ }
5738
+ };
5739
+ function deriveRealtimeInfoUrl(wsUrl) {
5740
+ if (!wsUrl) {
5741
+ return void 0;
5742
+ }
5743
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
5744
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
5745
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
5746
+ return parsed.toString();
5747
+ }
5748
+ function normalizeWsUrl(value, label) {
5749
+ const normalized = value.trim();
5750
+ if (!normalized) {
5751
+ throw new Error(`${label} is required.`);
5752
+ }
5753
+ let parsed;
5754
+ try {
5755
+ parsed = new URL(normalized);
5756
+ } catch {
5757
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
5758
+ }
5759
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
5760
+ throw new Error(`${label} must use ws or wss.`);
5761
+ }
5762
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
5763
+ return parsed.toString().replace(/\/$/, "");
5764
+ }
5765
+ function isRecord7(value) {
5766
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5767
+ }
5768
+ function normalizeHeaderValue3(value) {
5769
+ return value ? value : void 0;
5770
+ }
5771
+ function parseResponseBody4(rawText, contentType) {
5772
+ if (!rawText) {
5773
+ return { parsed: null, parseFailed: false };
5774
+ }
5775
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
5776
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
5777
+ if (!looksJson) {
5778
+ return { parsed: rawText, parseFailed: false };
5779
+ }
5780
+ try {
5781
+ return { parsed: JSON.parse(rawText), parseFailed: false };
5782
+ } catch {
5783
+ return { parsed: rawText, parseFailed: true };
5784
+ }
5785
+ }
5786
+ function resolveRequestId3(headers) {
5787
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
5788
+ }
5789
+ function resolveErrorMessage4(payload, fallback) {
5790
+ if (isRecord7(payload)) {
5791
+ for (const candidate of [payload.error, payload.message, payload.details]) {
5792
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
5793
+ return candidate.trim();
5794
+ }
5795
+ }
5796
+ }
5797
+ if (typeof payload === "string" && payload.trim().length > 0) {
5798
+ return payload.trim();
5799
+ }
5800
+ return fallback;
5801
+ }
5802
+ function encodePathSegment(value, label) {
5803
+ const normalized = value.trim();
5804
+ if (!normalized) {
5805
+ throw new Error(`${label} is required.`);
5806
+ }
5807
+ return encodeURIComponent(normalized);
5808
+ }
5809
+ function encodeQuery(query) {
5810
+ if (!query) {
5811
+ return "";
5812
+ }
5813
+ const params = new URLSearchParams();
5814
+ for (const [key, value] of Object.entries(query)) {
5815
+ if (value === void 0 || value === null) {
5816
+ continue;
5817
+ }
5818
+ if (Array.isArray(value)) {
5819
+ for (const item of value) {
5820
+ if (item !== void 0 && item !== null) {
5821
+ params.append(key, String(item));
5822
+ }
5823
+ }
5824
+ continue;
5825
+ }
5826
+ params.set(key, String(value));
5827
+ }
5828
+ const encoded = params.toString();
5829
+ return encoded ? `?${encoded}` : "";
5830
+ }
5831
+ function createSocket(factory, url, protocols) {
5832
+ try {
5833
+ return new factory(url, protocols);
5834
+ } catch (error) {
5835
+ if (error instanceof TypeError) {
5836
+ return factory(url, protocols);
5837
+ }
5838
+ throw error;
5839
+ }
5840
+ }
5841
+ function buildHeaders3(config, options) {
5842
+ const headers = {
5843
+ Accept: "application/json",
5844
+ apikey: config.apiKey,
5845
+ "x-api-key": config.apiKey,
5846
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
5847
+ };
5848
+ if (config.client || options?.client) {
5849
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
5850
+ }
5851
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
5852
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
5853
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
5854
+ }
5855
+ const cookie = options?.cookie ?? config.cookie;
5856
+ if (typeof cookie === "string" && cookie.trim()) {
5857
+ headers.Cookie = cookie;
5858
+ }
5859
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
5860
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
5861
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
5862
+ }
5863
+ if (config.forceNoCache || options?.forceNoCache) {
5864
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
5865
+ }
5866
+ for (const source of [config.headers, options?.headers]) {
5867
+ for (const [key, value] of Object.entries(source ?? {})) {
5868
+ const normalized = normalizeHeaderValue3(value);
5869
+ if (normalized) {
5870
+ headers[key] = normalized;
5871
+ }
5872
+ }
5873
+ }
5874
+ return headers;
5875
+ }
5876
+ function withJsonBody(init, body) {
5877
+ return {
5878
+ ...init,
5879
+ body: body === void 0 ? void 0 : JSON.stringify(body),
5880
+ headers: {
5881
+ "Content-Type": "application/json",
5882
+ ...init.headers
5883
+ }
5884
+ };
5885
+ }
5886
+ async function request(config, method, endpoint, options, body) {
5887
+ if (!config.baseUrl) {
5888
+ throw new Error(
5889
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
5890
+ );
5891
+ }
5892
+ const url = `${config.baseUrl}${endpoint}`;
5893
+ const init = {
5894
+ method,
5895
+ headers: buildHeaders3(config, options),
5896
+ signal: options?.signal
5897
+ };
5898
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
5899
+ const response = await fetch(url, finalInit);
5900
+ const rawText = await response.text();
5901
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
5902
+ if (!response.ok) {
5903
+ throw new AthenaChatError({
5904
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
5905
+ status: response.status,
5906
+ endpoint,
5907
+ method,
5908
+ requestId: resolveRequestId3(response.headers),
5909
+ body: parsed
5910
+ });
5911
+ }
5912
+ return parsed;
5913
+ }
5914
+ function unwrapEnvelopeData(payload) {
5915
+ return payload.data;
5916
+ }
5917
+ function createRealtimeConnection(config, options) {
5918
+ if (!config.wsUrl) {
5919
+ throw new Error(
5920
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5921
+ );
5922
+ }
5923
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
5924
+ if (!wsFactory) {
5925
+ throw new Error(
5926
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
5927
+ );
5928
+ }
5929
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
5930
+ const send = (command) => {
5931
+ socket.send(JSON.stringify(command));
5932
+ };
5933
+ if (options?.onMessage) {
5934
+ const listener = (event) => {
5935
+ const messageEvent = event;
5936
+ const raw = messageEvent?.data;
5937
+ if (typeof raw !== "string") {
5938
+ return;
5939
+ }
5940
+ try {
5941
+ options.onMessage?.(JSON.parse(raw));
5942
+ } catch {
5943
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
5944
+ }
5945
+ };
5946
+ if (typeof socket.addEventListener === "function") {
5947
+ socket.addEventListener("message", listener);
5948
+ } else {
5949
+ socket.onmessage = listener;
5950
+ }
5951
+ }
5952
+ const hello = (command) => {
5953
+ send({
5954
+ type: "auth.hello",
5955
+ token: command?.token,
5956
+ room_subscriptions: command?.room_subscriptions
5957
+ });
5958
+ };
5959
+ if (options?.hello) {
5960
+ const onOpen = () => hello({
5961
+ token: options.hello?.token ?? void 0,
5962
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
5963
+ });
5964
+ if (typeof socket.addEventListener === "function") {
5965
+ socket.addEventListener("open", onOpen);
5966
+ } else {
5967
+ socket.onopen = onOpen;
5968
+ }
5969
+ }
5970
+ return {
5971
+ socket,
5972
+ send,
5973
+ hello,
5974
+ subscribe(roomId, fromSeq) {
5975
+ send({
5976
+ type: "chat.subscribe",
5977
+ room_id: roomId,
5978
+ from_seq: fromSeq ?? void 0
5979
+ });
5980
+ },
5981
+ unsubscribe(roomId) {
5982
+ send({
5983
+ type: "chat.unsubscribe",
5984
+ room_id: roomId
5985
+ });
5986
+ },
5987
+ resume(rooms) {
5988
+ send({
5989
+ type: "chat.resume",
5990
+ rooms
5991
+ });
5992
+ },
5993
+ typingStart(roomId) {
5994
+ send({
5995
+ type: "chat.typing.start",
5996
+ room_id: roomId
5997
+ });
5998
+ },
5999
+ typingStop(roomId) {
6000
+ send({
6001
+ type: "chat.typing.stop",
6002
+ room_id: roomId
6003
+ });
6004
+ },
6005
+ presenceHeartbeat(activeRoomId) {
6006
+ send({
6007
+ type: "chat.presence.heartbeat",
6008
+ active_room_id: activeRoomId ?? void 0
6009
+ });
6010
+ },
6011
+ readUpTo(roomId, input) {
6012
+ send({
6013
+ type: "chat.read.up_to",
6014
+ room_id: roomId,
6015
+ message_id: input?.message_id ?? void 0,
6016
+ seq: input?.seq ?? void 0
6017
+ });
6018
+ },
6019
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
6020
+ send({
6021
+ type: "ping",
6022
+ at
6023
+ });
6024
+ },
6025
+ close(code, reason) {
6026
+ socket.close(code, reason);
6027
+ }
6028
+ };
6029
+ }
6030
+ function createChatModule(config) {
6031
+ const realtime = {
6032
+ info(options) {
6033
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
6034
+ if (!realtimeInfoUrl) {
6035
+ throw new Error(
6036
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
6037
+ );
6038
+ }
6039
+ return request(
6040
+ {
6041
+ ...config,
6042
+ baseUrl: realtimeInfoUrl
6043
+ },
6044
+ "GET",
6045
+ "",
6046
+ options
6047
+ );
6048
+ },
6049
+ connect(options) {
6050
+ return createRealtimeConnection(config, options);
6051
+ }
6052
+ };
6053
+ return {
6054
+ room: {
6055
+ list(query, options) {
6056
+ return request(
6057
+ config,
6058
+ "GET",
6059
+ `/rooms${encodeQuery(query)}`,
6060
+ options
6061
+ );
6062
+ },
6063
+ create(input, options) {
6064
+ return request(config, "POST", "/rooms", options, input);
6065
+ },
6066
+ get(roomId, options) {
6067
+ return request(
6068
+ config,
6069
+ "GET",
6070
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6071
+ options
6072
+ );
6073
+ },
6074
+ update(roomId, input, options) {
6075
+ return request(
6076
+ config,
6077
+ "PATCH",
6078
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6079
+ options,
6080
+ input
6081
+ );
6082
+ },
6083
+ archive(roomId, options) {
6084
+ return request(
6085
+ config,
6086
+ "POST",
6087
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
6088
+ options
6089
+ );
6090
+ },
6091
+ readCursor: {
6092
+ upTo(roomId, input, options) {
6093
+ return request(
6094
+ config,
6095
+ "POST",
6096
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
6097
+ options,
6098
+ input ?? {}
6099
+ );
6100
+ }
6101
+ },
6102
+ member: {
6103
+ list(roomId, options) {
6104
+ return request(
6105
+ config,
6106
+ "GET",
6107
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6108
+ options
6109
+ );
6110
+ },
6111
+ add(roomId, input, options) {
6112
+ return request(
6113
+ config,
6114
+ "POST",
6115
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6116
+ options,
6117
+ input
6118
+ );
6119
+ },
6120
+ remove(roomId, userId, options) {
6121
+ return request(
6122
+ config,
6123
+ "DELETE",
6124
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
6125
+ options
6126
+ );
6127
+ }
6128
+ },
6129
+ message: {
6130
+ list(roomId, query, options) {
6131
+ return request(
6132
+ config,
6133
+ "GET",
6134
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
6135
+ options
6136
+ );
6137
+ },
6138
+ send(roomId, input, options) {
6139
+ return request(
6140
+ config,
6141
+ "POST",
6142
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
6143
+ options,
6144
+ input
6145
+ );
6146
+ },
6147
+ update(roomId, messageId, input, options) {
6148
+ return request(
6149
+ config,
6150
+ "PATCH",
6151
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6152
+ options,
6153
+ input
6154
+ );
6155
+ },
6156
+ delete(roomId, messageId, options) {
6157
+ return request(
6158
+ config,
6159
+ "DELETE",
6160
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6161
+ options
6162
+ );
6163
+ }
6164
+ }
6165
+ },
6166
+ message: {
6167
+ reaction: {
6168
+ add(messageId, input, options) {
6169
+ return request(
6170
+ config,
6171
+ "POST",
6172
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
6173
+ options,
6174
+ input
6175
+ );
6176
+ },
6177
+ remove(messageId, emoji, options) {
6178
+ return request(
6179
+ config,
6180
+ "DELETE",
6181
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
6182
+ options
6183
+ );
6184
+ }
6185
+ },
6186
+ search(input, options) {
6187
+ return request(
6188
+ config,
6189
+ "POST",
6190
+ "/messages/search",
6191
+ options,
6192
+ input
6193
+ );
6194
+ }
6195
+ },
6196
+ realtime
6197
+ };
6198
+ }
6199
+ var chatSdkManifest = {
6200
+ namespace: "chat",
6201
+ basePath: "/chat",
6202
+ methods: [
6203
+ { name: "listRooms", method: "GET", path: "/chat/rooms" },
6204
+ { name: "createRoom", method: "POST", path: "/chat/rooms" },
6205
+ { name: "getRoom", method: "GET", path: "/chat/rooms/{room_id}" },
6206
+ { name: "updateRoom", method: "PATCH", path: "/chat/rooms/{room_id}" },
6207
+ { name: "archiveRoom", method: "POST", path: "/chat/rooms/{room_id}/archive" },
6208
+ { name: "listRoomMessages", method: "GET", path: "/chat/rooms/{room_id}/messages" },
6209
+ { name: "sendRoomMessage", method: "POST", path: "/chat/rooms/{room_id}/messages" },
6210
+ { name: "updateRoomMessage", method: "PATCH", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6211
+ { name: "deleteRoomMessage", method: "DELETE", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6212
+ { name: "advanceReadCursor", method: "POST", path: "/chat/rooms/{room_id}/read-cursor" },
6213
+ { name: "listRoomMembers", method: "GET", path: "/chat/rooms/{room_id}/members" },
6214
+ { name: "addRoomMembers", method: "POST", path: "/chat/rooms/{room_id}/members" },
6215
+ { name: "removeRoomMember", method: "DELETE", path: "/chat/rooms/{room_id}/members/{user_id}" },
6216
+ { name: "addReaction", method: "POST", path: "/chat/messages/{message_id}/reactions" },
6217
+ { name: "removeReaction", method: "DELETE", path: "/chat/messages/{message_id}/reactions/{emoji}" },
6218
+ { name: "searchMessages", method: "POST", path: "/chat/messages/search" },
6219
+ { name: "getRealtimeInfo", method: "GET", path: "/wss/info" },
6220
+ { name: "connectRealtime", method: "GET", path: "/wss/gateway" }
6221
+ ]
6222
+ };
6223
+ function unwrapChatRoom(payload) {
6224
+ return unwrapEnvelopeData(payload);
6225
+ }
6226
+ function unwrapChatMessage(payload) {
6227
+ return unwrapEnvelopeData(payload);
6228
+ }
6229
+
5621
6230
  // src/client-builder.ts
5622
6231
  var DEFAULT_BACKEND = { type: "athena" };
5623
6232
  function toBackendConfig(value) {
@@ -5830,7 +6439,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
5830
6439
  "ilike",
5831
6440
  "is"
5832
6441
  ]);
5833
- function isRecord7(value) {
6442
+ function isRecord8(value) {
5834
6443
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5835
6444
  }
5836
6445
  function isUuidString(value) {
@@ -5843,7 +6452,7 @@ function shouldUseUuidTextComparison(column, value) {
5843
6452
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
5844
6453
  }
5845
6454
  function isRelationSelectNode(value) {
5846
- return isRecord7(value) && isRecord7(value.select);
6455
+ return isRecord8(value) && isRecord8(value.select);
5847
6456
  }
5848
6457
  function normalizeIdentifier(value, label) {
5849
6458
  const normalized = value.trim();
@@ -5899,7 +6508,7 @@ function compileRelationToken(key, node) {
5899
6508
  return `${prefix}${relationToken}(${nested})`;
5900
6509
  }
5901
6510
  function compileSelectShape(select) {
5902
- if (!isRecord7(select)) {
6511
+ if (!isRecord8(select)) {
5903
6512
  throw new Error("findMany select must be an object");
5904
6513
  }
5905
6514
  const tokens = [];
@@ -5923,7 +6532,7 @@ function compileSelectShape(select) {
5923
6532
  return tokens.join(",");
5924
6533
  }
5925
6534
  function selectShapeUsesRelationSchema(select) {
5926
- if (!isRecord7(select)) {
6535
+ if (!isRecord8(select)) {
5927
6536
  return false;
5928
6537
  }
5929
6538
  for (const rawValue of Object.values(select)) {
@@ -5941,7 +6550,7 @@ function selectShapeUsesRelationSchema(select) {
5941
6550
  }
5942
6551
  function compileColumnWhere(column, input) {
5943
6552
  const normalizedColumn = normalizeIdentifier(column, "where column");
5944
- if (!isRecord7(input)) {
6553
+ if (!isRecord8(input)) {
5945
6554
  return [buildGatewayCondition("eq", normalizedColumn, input)];
5946
6555
  }
5947
6556
  const conditions = [];
@@ -5969,7 +6578,7 @@ function compileColumnWhere(column, input) {
5969
6578
  return conditions;
5970
6579
  }
5971
6580
  function compileBooleanExpressionTerms(clause, label) {
5972
- if (!isRecord7(clause)) {
6581
+ if (!isRecord8(clause)) {
5973
6582
  throw new Error(`findMany where.${label} clauses must be objects`);
5974
6583
  }
5975
6584
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -5978,7 +6587,7 @@ function compileBooleanExpressionTerms(clause, label) {
5978
6587
  }
5979
6588
  const [rawColumn, rawValue] = entries[0];
5980
6589
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
5981
- if (!isRecord7(rawValue)) {
6590
+ if (!isRecord8(rawValue)) {
5982
6591
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
5983
6592
  }
5984
6593
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -6002,7 +6611,7 @@ function compileWhere(where) {
6002
6611
  if (where === void 0) {
6003
6612
  return void 0;
6004
6613
  }
6005
- if (!isRecord7(where)) {
6614
+ if (!isRecord8(where)) {
6006
6615
  throw new Error("findMany where must be an object");
6007
6616
  }
6008
6617
  const conditions = [];
@@ -6052,7 +6661,7 @@ function compileOrderBy(orderBy) {
6052
6661
  if (orderBy === void 0) {
6053
6662
  return void 0;
6054
6663
  }
6055
- if (!isRecord7(orderBy)) {
6664
+ if (!isRecord8(orderBy)) {
6056
6665
  throw new Error("findMany orderBy must be an object");
6057
6666
  }
6058
6667
  if ("column" in orderBy) {
@@ -6227,11 +6836,11 @@ function toFindManyAstOrder(order) {
6227
6836
  ascending: order.direction !== "descending"
6228
6837
  };
6229
6838
  }
6230
- function isRecord8(value) {
6839
+ function isRecord9(value) {
6231
6840
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6232
6841
  }
6233
6842
  function normalizeFindManyAstColumnPredicate(value) {
6234
- if (!isRecord8(value)) {
6843
+ if (!isRecord9(value)) {
6235
6844
  return {
6236
6845
  eq: value
6237
6846
  };
@@ -6255,7 +6864,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6255
6864
  return normalized;
6256
6865
  }
6257
6866
  function normalizeFindManyAstWhere(where) {
6258
- if (!where || !isRecord8(where)) {
6867
+ if (!where || !isRecord9(where)) {
6259
6868
  return where;
6260
6869
  }
6261
6870
  const normalized = {};
@@ -6269,7 +6878,7 @@ function normalizeFindManyAstWhere(where) {
6269
6878
  );
6270
6879
  continue;
6271
6880
  }
6272
- if (key === "not" && isRecord8(value)) {
6881
+ if (key === "not" && isRecord9(value)) {
6273
6882
  normalized.not = normalizeFindManyAstBooleanOperand(
6274
6883
  value
6275
6884
  );
@@ -6280,7 +6889,7 @@ function normalizeFindManyAstWhere(where) {
6280
6889
  return normalized;
6281
6890
  }
6282
6891
  function predicateRequiresUuidQueryFallback(column, value) {
6283
- if (!isRecord8(value)) {
6892
+ if (!isRecord9(value)) {
6284
6893
  return shouldUseUuidTextComparison(column, value);
6285
6894
  }
6286
6895
  const eqValue = value.eq;
@@ -6298,7 +6907,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6298
6907
  return false;
6299
6908
  }
6300
6909
  function findManyAstWhereRequiresLegacyTransport(where) {
6301
- if (!where || !isRecord8(where)) {
6910
+ if (!where || !isRecord9(where)) {
6302
6911
  return false;
6303
6912
  }
6304
6913
  for (const [key, value] of Object.entries(where)) {
@@ -6313,7 +6922,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6313
6922
  }
6314
6923
  continue;
6315
6924
  }
6316
- if (key === "not" && isRecord8(value)) {
6925
+ if (key === "not" && isRecord9(value)) {
6317
6926
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6318
6927
  return true;
6319
6928
  }
@@ -6862,6 +7471,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
6862
7471
  var DEFAULT_COLUMNS = "*";
6863
7472
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6864
7473
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7474
+ var SDK_NAME4 = "xylex-group/athena";
6865
7475
  function formatResult(response) {
6866
7476
  const result = {
6867
7477
  data: response.data ?? null,
@@ -6938,7 +7548,7 @@ async function executeExperimentalRead(experimental, runner) {
6938
7548
  throw error;
6939
7549
  }
6940
7550
  }
6941
- function isRecord9(value) {
7551
+ function isRecord10(value) {
6942
7552
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6943
7553
  }
6944
7554
  function firstNonEmptyString2(...values) {
@@ -6950,8 +7560,8 @@ function firstNonEmptyString2(...values) {
6950
7560
  return void 0;
6951
7561
  }
6952
7562
  function resolveStructuredErrorPayload2(raw) {
6953
- if (!isRecord9(raw)) return null;
6954
- return isRecord9(raw.error) ? raw.error : raw;
7563
+ if (!isRecord10(raw)) return null;
7564
+ return isRecord10(raw.error) ? raw.error : raw;
6955
7565
  }
6956
7566
  function resolveStructuredErrorDetails(payload, message) {
6957
7567
  if (!payload || !("details" in payload)) {
@@ -6967,7 +7577,7 @@ function resolveStructuredErrorDetails(payload, message) {
6967
7577
  return details;
6968
7578
  }
6969
7579
  function createResultError(response, result, normalized) {
6970
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7580
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
6971
7581
  const payload = resolveStructuredErrorPayload2(response.raw);
6972
7582
  const message = firstNonEmptyString2(
6973
7583
  response.error,
@@ -7030,6 +7640,43 @@ function asAthenaJsonObject(value) {
7030
7640
  function asAthenaJsonObjectArray(values) {
7031
7641
  return values;
7032
7642
  }
7643
+ function parseArbitraryResponseBody(rawText, contentType) {
7644
+ if (!rawText) {
7645
+ return null;
7646
+ }
7647
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
7648
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
7649
+ if (!looksJson) {
7650
+ return rawText;
7651
+ }
7652
+ try {
7653
+ return JSON.parse(rawText);
7654
+ } catch {
7655
+ return rawText;
7656
+ }
7657
+ }
7658
+ function toRequestQueryString(query) {
7659
+ if (!query) {
7660
+ return "";
7661
+ }
7662
+ const params = new URLSearchParams();
7663
+ for (const [key, value] of Object.entries(query)) {
7664
+ if (value === void 0 || value === null) {
7665
+ continue;
7666
+ }
7667
+ if (Array.isArray(value)) {
7668
+ for (const item of value) {
7669
+ if (item !== void 0 && item !== null) {
7670
+ params.append(key, String(item));
7671
+ }
7672
+ }
7673
+ continue;
7674
+ }
7675
+ params.set(key, String(value));
7676
+ }
7677
+ const encoded = params.toString();
7678
+ return encoded ? `?${encoded}` : "";
7679
+ }
7033
7680
  function normalizeSelectColumnsInput(columns) {
7034
7681
  if (columns === void 0) {
7035
7682
  return void 0;
@@ -8336,6 +8983,8 @@ var ATHENA_ENV_GATEWAY_URL_KEYS = [
8336
8983
  "NEXT_PUBLIC_ATHENA_DB_API_URL"
8337
8984
  ];
8338
8985
  var ATHENA_ENV_AUTH_URL_KEYS = ["ATHENA_AUTH_URL", "NEXT_PUBLIC_ATHENA_AUTH_URL"];
8986
+ var ATHENA_ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
8987
+ var ATHENA_ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
8339
8988
  var ATHENA_ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
8340
8989
  var ATHENA_ENV_KEY_KEYS = [
8341
8990
  "ATHENA_API_KEY",
@@ -8416,6 +9065,15 @@ function appendServicePath(baseUrl, segment) {
8416
9065
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8417
9066
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8418
9067
  }
9068
+ function appendRealtimeGatewayPath(baseUrl) {
9069
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
9070
+ const wsUrl = new URL(normalizedBaseUrl);
9071
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
9072
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
9073
+ wsUrl.search = "";
9074
+ wsUrl.hash = "";
9075
+ return wsUrl.toString();
9076
+ }
8419
9077
  function resolveServiceUrlOverride(value, label) {
8420
9078
  return resolveClientServiceBaseUrl(value, label);
8421
9079
  }
@@ -8424,6 +9082,8 @@ function resolveServiceUrls(config) {
8424
9082
  return {
8425
9083
  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),
8426
9084
  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),
9085
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
9086
+ chatWsUrl: normalizeOptionalString(config.chat?.wsUrl) ?? normalizeOptionalString(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
8427
9087
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8428
9088
  };
8429
9089
  }
@@ -8516,6 +9176,7 @@ function mergeClientOverrideOptions(base, overrides) {
8516
9176
  } : void 0,
8517
9177
  db: base.db ? { ...base.db } : void 0,
8518
9178
  gateway: base.gateway ? { ...base.gateway } : void 0,
9179
+ chat: base.chat ? { ...base.chat } : void 0,
8519
9180
  storage: base.storage ? { ...base.storage } : void 0
8520
9181
  };
8521
9182
  }
@@ -8526,6 +9187,7 @@ function mergeClientOverrideOptions(base, overrides) {
8526
9187
  auth: mergeAuthClientOptions(base.auth, overrides.auth),
8527
9188
  db: mergeServiceUrlOverrides(base.db, overrides.db),
8528
9189
  gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9190
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
8529
9191
  storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
8530
9192
  };
8531
9193
  }
@@ -8584,6 +9246,9 @@ function resolveCreateClientConfig(config) {
8584
9246
  headers: config.headers,
8585
9247
  auth: config.auth,
8586
9248
  authUrl: resolvedUrls.authUrl,
9249
+ chat: config.chat,
9250
+ chatUrl: resolvedUrls.chatUrl,
9251
+ chatWsUrl: resolvedUrls.chatWsUrl,
8587
9252
  storageUrl: resolvedUrls.storageUrl,
8588
9253
  experimental: config.experimental
8589
9254
  };
@@ -8668,6 +9333,119 @@ function createClientFromConfig(config, sourceConfig) {
8668
9333
  queryTracer
8669
9334
  );
8670
9335
  const db = createDbModule({ from, rpc, query });
9336
+ const chat = createChatModule({
9337
+ baseUrl: config.chatUrl,
9338
+ apiKey: config.apiKey,
9339
+ client: config.client,
9340
+ headers: config.headers,
9341
+ bearerToken: normalizedAuthConfig?.bearerToken,
9342
+ cookie: normalizedAuthConfig?.cookie,
9343
+ sessionToken: normalizedAuthConfig?.sessionToken,
9344
+ forceNoCache: config.forceNoCache,
9345
+ wsUrl: config.chatWsUrl,
9346
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
9347
+ });
9348
+ const request2 = async (options) => {
9349
+ const method = options.method ?? "GET";
9350
+ const responseType = options.responseType ?? "json";
9351
+ const service = options.service ?? "db";
9352
+ const baseUrlByService = {
9353
+ db: config.baseUrl,
9354
+ auth: config.authUrl,
9355
+ chat: config.chatUrl,
9356
+ storage: config.storageUrl
9357
+ };
9358
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
9359
+ if (!resolvedBaseUrl) {
9360
+ throw new Error(
9361
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
9362
+ );
9363
+ }
9364
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
9365
+ label: `Athena ${service} base URL`
9366
+ });
9367
+ const normalizedPath = options.url ? "" : (() => {
9368
+ const path = options.path?.trim();
9369
+ if (!path) {
9370
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
9371
+ }
9372
+ return path.startsWith("/") ? path : `/${path}`;
9373
+ })();
9374
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
9375
+ const headers = {
9376
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
9377
+ ...config.headers ?? {},
9378
+ ...options.headers ?? {}
9379
+ };
9380
+ if (service !== "auth") {
9381
+ headers.apikey = headers.apikey ?? config.apiKey;
9382
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
9383
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
9384
+ headers["X-Athena-Client"] = config.client;
9385
+ }
9386
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
9387
+ headers["X-User-Id"] = config.userId;
9388
+ }
9389
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
9390
+ headers["X-Organization-Id"] = config.organizationId;
9391
+ }
9392
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9393
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9394
+ }
9395
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
9396
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9397
+ }
9398
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9399
+ headers.Cookie = normalizedAuthConfig.cookie;
9400
+ }
9401
+ } else {
9402
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
9403
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
9404
+ headers.apikey = headers.apikey ?? authApiKey;
9405
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
9406
+ }
9407
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
9408
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
9409
+ }
9410
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9411
+ headers.Cookie = normalizedAuthConfig.cookie;
9412
+ }
9413
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9414
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9415
+ }
9416
+ }
9417
+ 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";
9418
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
9419
+ headers["Content-Type"] = "application/json";
9420
+ }
9421
+ const response = await fetch(targetUrl, {
9422
+ method,
9423
+ headers,
9424
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
9425
+ signal: options.signal,
9426
+ credentials: options.credentials
9427
+ });
9428
+ if (responseType === "response") {
9429
+ return {
9430
+ ok: response.ok,
9431
+ status: response.status,
9432
+ statusText: response.statusText,
9433
+ headers: response.headers,
9434
+ data: null,
9435
+ raw: response
9436
+ };
9437
+ }
9438
+ const rawText = await response.text();
9439
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
9440
+ return {
9441
+ ok: response.ok,
9442
+ status: response.status,
9443
+ statusText: response.statusText,
9444
+ headers: response.headers,
9445
+ data: parsed,
9446
+ raw: response
9447
+ };
9448
+ };
8671
9449
  const withContext = (context) => createClientFromInput(
8672
9450
  mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
8673
9451
  );
@@ -8683,8 +9461,10 @@ function createClientFromConfig(config, sourceConfig) {
8683
9461
  db,
8684
9462
  rpc,
8685
9463
  query,
9464
+ request: request2,
8686
9465
  verifyConnection: gateway.verifyConnection,
8687
9466
  auth: auth.auth,
9467
+ chat,
8688
9468
  withContext,
8689
9469
  withSession,
8690
9470
  withOptions: authWithOptions
@@ -8729,6 +9509,8 @@ var AthenaClient = class {
8729
9509
  const url = options.url ?? readFirstEnvValue(env, ATHENA_ENV_URL_KEYS);
8730
9510
  const gatewayUrl = options.gatewayUrl ?? readFirstEnvValue(env, ATHENA_ENV_GATEWAY_URL_KEYS);
8731
9511
  const authUrl = options.authUrl ?? readFirstEnvValue(env, ATHENA_ENV_AUTH_URL_KEYS);
9512
+ const chatUrl = options.chatUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_URL_KEYS);
9513
+ const chatWsUrl = options.chatWsUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_WS_URL_KEYS);
8732
9514
  const storageUrl = options.storageUrl ?? readFirstEnvValue(env, ATHENA_ENV_STORAGE_URL_KEYS);
8733
9515
  const key = options.key ?? readFirstEnvValue(env, ATHENA_ENV_KEY_KEYS);
8734
9516
  const client = options.client ?? readFirstEnvValue(env, ATHENA_ENV_CLIENT_KEYS);
@@ -8743,6 +9525,8 @@ var AthenaClient = class {
8743
9525
  url,
8744
9526
  gatewayUrl,
8745
9527
  authUrl,
9528
+ chatUrl,
9529
+ chatWsUrl,
8746
9530
  storageUrl,
8747
9531
  key,
8748
9532
  client
@@ -8788,7 +9572,7 @@ function resolveNullishValue(mode) {
8788
9572
  if (mode === "null") return null;
8789
9573
  return "";
8790
9574
  }
8791
- function isRecord10(value) {
9575
+ function isRecord11(value) {
8792
9576
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8793
9577
  }
8794
9578
  function isNullableColumn(model, key) {
@@ -8797,7 +9581,7 @@ function isNullableColumn(model, key) {
8797
9581
  }
8798
9582
  function toModelFormDefaults(model, values, options) {
8799
9583
  const source = values;
8800
- if (!isRecord10(source)) {
9584
+ if (!isRecord11(source)) {
8801
9585
  return {};
8802
9586
  }
8803
9587
  const mode = options?.nullishMode ?? "empty-string";
@@ -9311,6 +10095,9 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
9311
10095
  query(query, options) {
9312
10096
  return this.baseClient.query(query, options);
9313
10097
  }
10098
+ request(options) {
10099
+ return this.baseClient.request(options);
10100
+ }
9314
10101
  verifyConnection(options) {
9315
10102
  return this.baseClient.verifyConnection(options);
9316
10103
  }
@@ -11607,15 +12394,15 @@ function readCookieFromHeaders(headers, name) {
11607
12394
  }
11608
12395
  return parseCookies(cookieHeader).get(name);
11609
12396
  }
11610
- function isRecord11(value) {
12397
+ function isRecord12(value) {
11611
12398
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11612
12399
  }
11613
12400
  function resolveSessionCandidate(value) {
11614
- if (!isRecord11(value)) {
12401
+ if (!isRecord12(value)) {
11615
12402
  return null;
11616
12403
  }
11617
- const session = isRecord11(value.session) ? value.session : void 0;
11618
- const user = isRecord11(value.user) ? value.user : void 0;
12404
+ const session = isRecord12(value.session) ? value.session : void 0;
12405
+ const user = isRecord12(value.user) ? value.user : void 0;
11619
12406
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
11620
12407
  return {
11621
12408
  session,
@@ -11625,7 +12412,7 @@ function resolveSessionCandidate(value) {
11625
12412
  return null;
11626
12413
  }
11627
12414
  function inferSessionPair(returned) {
11628
- return resolveSessionCandidate(returned) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.session) : null);
12415
+ return resolveSessionCandidate(returned) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.session) : null);
11629
12416
  }
11630
12417
  function resolveResponseHeaders(ctx) {
11631
12418
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -11648,23 +12435,23 @@ function normalizeBasePath(basePath) {
11648
12435
  function isDynamicBaseURLConfig2(baseURL) {
11649
12436
  return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
11650
12437
  }
11651
- function getRequestUrl(request) {
12438
+ function getRequestUrl(request2) {
11652
12439
  try {
11653
- return new URL(request.url);
12440
+ return new URL(request2.url);
11654
12441
  } catch {
11655
12442
  return new URL("http://localhost");
11656
12443
  }
11657
12444
  }
11658
- function getRequestHost(request, url) {
11659
- const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
11660
- const host = forwardedHost || request.headers.get("host") || url.host;
12445
+ function getRequestHost(request2, url) {
12446
+ const forwardedHost = request2.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
12447
+ const host = forwardedHost || request2.headers.get("host") || url.host;
11661
12448
  return host || null;
11662
12449
  }
11663
- function getRequestProtocol(request, configuredProtocol, url) {
12450
+ function getRequestProtocol(request2, configuredProtocol, url) {
11664
12451
  if (configuredProtocol === "http" || configuredProtocol === "https") {
11665
12452
  return configuredProtocol;
11666
12453
  }
11667
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
12454
+ const forwardedProto = request2.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
11668
12455
  if (forwardedProto === "http" || forwardedProto === "https") {
11669
12456
  return forwardedProto;
11670
12457
  }
@@ -11673,12 +12460,12 @@ function getRequestProtocol(request, configuredProtocol, url) {
11673
12460
  }
11674
12461
  return "http";
11675
12462
  }
11676
- function resolveRequestBaseURL(baseURL, request) {
12463
+ function resolveRequestBaseURL(baseURL, request2) {
11677
12464
  if (typeof baseURL === "string") {
11678
12465
  return normalizeBaseURL(baseURL);
11679
12466
  }
11680
- const requestUrl = getRequestUrl(request);
11681
- const host = getRequestHost(request, requestUrl);
12467
+ const requestUrl = getRequestUrl(request2);
12468
+ const host = getRequestHost(request2, requestUrl);
11682
12469
  if (!host) {
11683
12470
  return null;
11684
12471
  }
@@ -11688,7 +12475,7 @@ function resolveRequestBaseURL(baseURL, request) {
11688
12475
  return null;
11689
12476
  }
11690
12477
  }
11691
- const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request, baseURL.protocol, requestUrl) : getRequestProtocol(request, void 0, requestUrl);
12478
+ const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request2, baseURL.protocol, requestUrl) : getRequestProtocol(request2, void 0, requestUrl);
11692
12479
  return `${protocol}://${host}`;
11693
12480
  }
11694
12481
  function getOrigin(baseURL) {
@@ -11701,16 +12488,16 @@ function getOrigin(baseURL) {
11701
12488
  return void 0;
11702
12489
  }
11703
12490
  }
11704
- async function resolveTrustedOrigins(config, baseURL, request) {
11705
- const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request) : config.trustedOrigins ?? [];
12491
+ async function resolveTrustedOrigins(config, baseURL, request2) {
12492
+ const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request2) : config.trustedOrigins ?? [];
11706
12493
  const values = [
11707
12494
  getOrigin(baseURL),
11708
12495
  ...resolved
11709
12496
  ];
11710
12497
  return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
11711
12498
  }
11712
- async function resolveTrustedProviders(config, request) {
11713
- const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request) : config.trustedProviders ?? [];
12499
+ async function resolveTrustedProviders(config, request2) {
12500
+ const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request2) : config.trustedProviders ?? [];
11714
12501
  const values = [
11715
12502
  ...Object.keys(config.socialProviders ?? {}),
11716
12503
  ...configured
@@ -11835,9 +12622,9 @@ function athenaAuth(config) {
11835
12622
  }
11836
12623
  return ctx;
11837
12624
  };
11838
- const resolveRequestContext = async (request) => {
11839
- const requestUrl = getRequestUrl(request);
11840
- const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request);
12625
+ const resolveRequestContext = async (request2) => {
12626
+ const requestUrl = getRequestUrl(request2);
12627
+ const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request2);
11841
12628
  if (!resolvedBaseURL) {
11842
12629
  throw new Error(
11843
12630
  isDynamicBaseURLConfig2(config.baseURL) ? "Could not resolve base URL from request. Check allowedHosts/baseURL." : "Could not resolve base URL from request."
@@ -11848,17 +12635,17 @@ function athenaAuth(config) {
11848
12635
  session: config.session,
11849
12636
  advanced: config.advanced
11850
12637
  });
11851
- const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request);
11852
- const trustedProviders = await resolveTrustedProviders(config, request);
12638
+ const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request2);
12639
+ const trustedProviders = await resolveTrustedProviders(config, request2);
11853
12640
  return {
11854
12641
  auth,
11855
- request,
12642
+ request: request2,
11856
12643
  url: requestUrl,
11857
12644
  path: requestUrl.pathname,
11858
12645
  basePath: normalizedBasePath,
11859
12646
  baseURL: resolvedBaseURL,
11860
12647
  origin: getOrigin(resolvedBaseURL) ?? resolvedBaseURL,
11861
- headers: request.headers,
12648
+ headers: request2.headers,
11862
12649
  cookies: requestCookies,
11863
12650
  trustedOrigins,
11864
12651
  trustedProviders,
@@ -11871,8 +12658,8 @@ function athenaAuth(config) {
11871
12658
  socialProviders: auth.socialProviders
11872
12659
  };
11873
12660
  };
11874
- const handler = async (request) => {
11875
- const requestContext = await resolveRequestContext(request);
12661
+ const handler = async (request2) => {
12662
+ const requestContext = await resolveRequestContext(request2);
11876
12663
  if (typeof config.handler !== "function") {
11877
12664
  return createJsonResponse(
11878
12665
  {
@@ -11893,7 +12680,7 @@ function athenaAuth(config) {
11893
12680
  const responseHeaders = new Headers(response.headers);
11894
12681
  await runAfterHooks({
11895
12682
  path: requestContext.path,
11896
- headers: request.headers,
12683
+ headers: request2.headers,
11897
12684
  context: {
11898
12685
  responseHeaders,
11899
12686
  returned: result.returned,
@@ -11975,6 +12762,7 @@ exports.ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = ATHENA_AUTH_MAX_ADMIN_JSON_BYTES;
11975
12762
  exports.ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH;
11976
12763
  exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = ATHENA_AUTH_MAX_TEMPLATE_VARIABLES;
11977
12764
  exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH;
12765
+ exports.AthenaChatError = AthenaChatError;
11978
12766
  exports.AthenaClient = AthenaClient;
11979
12767
  exports.AthenaError = AthenaError;
11980
12768
  exports.AthenaErrorCategory = AthenaErrorCategory;
@@ -11988,6 +12776,7 @@ exports.DEFAULT_POSTGRES_SCHEMAS = DEFAULT_POSTGRES_SCHEMAS;
11988
12776
  exports.assertInt = assertInt;
11989
12777
  exports.athenaAuth = athenaAuth;
11990
12778
  exports.boolean = boolean;
12779
+ exports.chatSdkManifest = chatSdkManifest;
11991
12780
  exports.coerceInt = coerceInt;
11992
12781
  exports.createAthenaStorageError = createAthenaStorageError;
11993
12782
  exports.createAuthClient = createAuthClient;
@@ -12034,6 +12823,8 @@ exports.table = table;
12034
12823
  exports.toModelFormDefaults = toModelFormDefaults;
12035
12824
  exports.toModelPayload = toModelPayload;
12036
12825
  exports.unwrap = unwrap;
12826
+ exports.unwrapChatMessage = unwrapChatMessage;
12827
+ exports.unwrapChatRoom = unwrapChatRoom;
12037
12828
  exports.unwrapOne = unwrapOne;
12038
12829
  exports.unwrapRows = unwrapRows;
12039
12830
  exports.verifyAthenaGatewayUrl = verifyAthenaGatewayUrl;