@xylex-group/athena 2.8.2 → 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 (52) hide show
  1. package/README.md +154 -64
  2. package/dist/browser.cjs +1550 -181
  3. package/dist/browser.cjs.map +1 -1
  4. package/dist/browser.d.cts +8 -7
  5. package/dist/browser.d.ts +8 -7
  6. package/dist/browser.js +1540 -182
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +1337 -67
  9. package/dist/cli/index.cjs.map +1 -1
  10. package/dist/cli/index.d.cts +3 -3
  11. package/dist/cli/index.d.ts +3 -3
  12. package/dist/cli/index.js +1337 -67
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/{model-form-Cx3wtvi8.d.ts → client-B7EQ_hPV.d.cts} +606 -118
  15. package/dist/{model-form-_ugfOXao.d.cts → client-BYii6dU9.d.ts} +606 -118
  16. package/dist/index.cjs +1540 -113
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +8 -7
  19. package/dist/index.d.ts +8 -7
  20. package/dist/index.js +1530 -114
  21. package/dist/index.js.map +1 -1
  22. package/dist/model-form-ByvyyvxB.d.ts +96 -0
  23. package/dist/model-form-DACdBLYG.d.cts +96 -0
  24. package/dist/{react-email-CiiSVa9F.d.cts → module-DC96HJa3.d.cts} +130 -5
  25. package/dist/{react-email-WN8UU3AL.d.ts → module-DbHlxpeR.d.ts} +130 -5
  26. package/dist/next/client.cjs +8591 -0
  27. package/dist/next/client.cjs.map +1 -0
  28. package/dist/next/client.d.cts +24 -0
  29. package/dist/next/client.d.ts +24 -0
  30. package/dist/next/client.js +8589 -0
  31. package/dist/next/client.js.map +1 -0
  32. package/dist/next/server.cjs +8709 -0
  33. package/dist/next/server.cjs.map +1 -0
  34. package/dist/next/server.d.cts +52 -0
  35. package/dist/next/server.d.ts +52 -0
  36. package/dist/next/server.js +8706 -0
  37. package/dist/next/server.js.map +1 -0
  38. package/dist/{pipeline-BtD-Uo5X.d.cts → pipeline-CmUZsXsi.d.cts} +1 -1
  39. package/dist/{pipeline-yCIZNJHE.d.ts → pipeline-DZMsPxUg.d.ts} +1 -1
  40. package/dist/react.cjs +30 -1
  41. package/dist/react.cjs.map +1 -1
  42. package/dist/react.d.cts +38 -10
  43. package/dist/react.d.ts +38 -10
  44. package/dist/react.js +30 -2
  45. package/dist/react.js.map +1 -1
  46. package/dist/shared-BMVGMnti.d.cts +35 -0
  47. package/dist/shared-DRptGBWP.d.ts +35 -0
  48. package/dist/{types-g8G6J0xE.d.cts → types-BeZIHduP.d.cts} +2 -1
  49. package/dist/{types-g8G6J0xE.d.ts → types-BeZIHduP.d.ts} +2 -1
  50. package/dist/{types-C2kiTt6-.d.ts → types-C-YvfgYh.d.cts} +26 -2
  51. package/dist/{types-89EfjLjV.d.cts → types-CRjDwmtJ.d.ts} +26 -2
  52. package/package.json +32 -14
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.8.2"
805
+ version: "2.10.0"
806
806
  };
807
807
 
808
808
  // src/sdk-version.ts
@@ -815,6 +815,7 @@ function buildSdkHeaderValue(sdkName) {
815
815
  var DEFAULT_CLIENT = "railway_direct";
816
816
  var SDK_NAME = "xylex-group/athena";
817
817
  var SDK_HEADER_VALUE = buildSdkHeaderValue(SDK_NAME);
818
+ var NO_CACHE_HEADER_VALUE = "no-cache";
818
819
  function parseResponseBody(rawText, contentType) {
819
820
  if (!rawText) {
820
821
  return { parsed: null, parseFailed: false };
@@ -833,6 +834,9 @@ function parseResponseBody(rawText, contentType) {
833
834
  function normalizeHeaderValue(value) {
834
835
  return value ? value : void 0;
835
836
  }
837
+ function isCacheControlHeaderName(name) {
838
+ return name.toLowerCase() === "cache-control";
839
+ }
836
840
  function resolveHeaderValue(headers, candidates) {
837
841
  for (const candidate of candidates) {
838
842
  const direct = normalizeHeaderValue(headers[candidate]);
@@ -991,6 +995,7 @@ function buildRpcGetEndpoint(payload) {
991
995
  }
992
996
  function buildHeaders(config, options) {
993
997
  const mergedStripNulls = options?.stripNulls ?? true;
998
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
994
999
  const extraHeaders = {
995
1000
  ...config.headers ?? {},
996
1001
  ...options?.headers ?? {}
@@ -1044,11 +1049,15 @@ function buildHeaders(config, options) {
1044
1049
  const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
1045
1050
  Object.entries(extraHeaders).forEach(([key, value]) => {
1046
1051
  if (athenaClientKeys.includes(key)) return;
1052
+ if (forceNoCache && isCacheControlHeaderName(key)) return;
1047
1053
  const normalized = normalizeHeaderValue(value);
1048
1054
  if (normalized) {
1049
1055
  headers[key] = normalized;
1050
1056
  }
1051
1057
  });
1058
+ if (forceNoCache) {
1059
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE;
1060
+ }
1052
1061
  return headers;
1053
1062
  }
1054
1063
  function toInvalidUrlResponse(error, endpoint, method) {
@@ -1509,6 +1518,45 @@ function identifier(...segments) {
1509
1518
  return new SqlIdentifierPath(expandedSegments);
1510
1519
  }
1511
1520
 
1521
+ // src/auth/limits.ts
1522
+ var ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = 32 * 1024;
1523
+ var ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = 8;
1524
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = 64;
1525
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = 128;
1526
+ var ATHENA_AUTH_ADMIN_LIMITS = {
1527
+ maxAdminJsonBytes: ATHENA_AUTH_MAX_ADMIN_JSON_BYTES,
1528
+ maxAdminJsonDepth: ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH,
1529
+ maxTemplateVariables: ATHENA_AUTH_MAX_TEMPLATE_VARIABLES,
1530
+ maxTemplateVariableLength: ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH
1531
+ };
1532
+ function describeTemplateVariableTarget(target) {
1533
+ const normalized = target?.trim();
1534
+ return normalized && normalized.length > 0 ? normalized : "Athena auth admin email template variables";
1535
+ }
1536
+ function assertAthenaAuthTemplateVariables(variables, target) {
1537
+ const label = describeTemplateVariableTarget(target);
1538
+ if (!Array.isArray(variables)) {
1539
+ throw new Error(`${label} must be an array of strings.`);
1540
+ }
1541
+ if (variables.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLES) {
1542
+ throw new Error(
1543
+ `${label} cannot contain more than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLES} entries.`
1544
+ );
1545
+ }
1546
+ variables.forEach((variable, index) => {
1547
+ if (typeof variable !== "string") {
1548
+ throw new Error(
1549
+ `${label} must contain only strings. Received ${typeof variable} at index ${index}.`
1550
+ );
1551
+ }
1552
+ if (variable.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH) {
1553
+ throw new Error(
1554
+ `${label} cannot contain entries longer than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH} characters. Received ${variable.length} characters at index ${index}.`
1555
+ );
1556
+ }
1557
+ });
1558
+ }
1559
+
1512
1560
  // src/auth/react-email.ts
1513
1561
  var reactEmailRenderModulePromise;
1514
1562
  function isRecord2(value) {
@@ -1738,6 +1786,7 @@ async function resolveReactEmailPayloadFields(input, fields, options) {
1738
1786
  var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
1739
1787
  var SDK_NAME2 = "xylex-group/athena-auth";
1740
1788
  var SDK_HEADER_VALUE2 = buildSdkHeaderValue(SDK_NAME2);
1789
+ var NO_CACHE_HEADER_VALUE2 = "no-cache";
1741
1790
  function normalizeBaseUrl(baseUrl) {
1742
1791
  return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
1743
1792
  }
@@ -1747,6 +1796,9 @@ function isRecord3(value) {
1747
1796
  function normalizeHeaderValue2(value) {
1748
1797
  return value ? value : void 0;
1749
1798
  }
1799
+ function isCacheControlHeaderName2(name) {
1800
+ return name.toLowerCase() === "cache-control";
1801
+ }
1750
1802
  function parseResponseBody2(rawText, contentType) {
1751
1803
  if (!rawText) {
1752
1804
  return { parsed: null, parseFailed: false };
@@ -1802,6 +1854,98 @@ function mergeCallOptions(base, override) {
1802
1854
  }
1803
1855
  };
1804
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
+ }
1901
+ function toSessionGuardFailure(sessionResult) {
1902
+ if (sessionResult.status === 401 || sessionResult.data == null) {
1903
+ return {
1904
+ ok: false,
1905
+ reason: "unauthorized",
1906
+ status: 401,
1907
+ error: sessionResult.error ?? "Unauthorized",
1908
+ sessionResult
1909
+ };
1910
+ }
1911
+ return {
1912
+ ok: false,
1913
+ reason: "upstream_error",
1914
+ status: sessionResult.status,
1915
+ error: sessionResult.error ?? "Failed to resolve current session",
1916
+ sessionResult
1917
+ };
1918
+ }
1919
+ function toPermissionGuardFailure(permissionResult, sessionResult) {
1920
+ if (permissionResult.status === 401) {
1921
+ return {
1922
+ ok: false,
1923
+ reason: "unauthorized",
1924
+ status: 401,
1925
+ error: permissionResult.error ?? "Unauthorized",
1926
+ sessionResult,
1927
+ permissionResult
1928
+ };
1929
+ }
1930
+ if (permissionResult.status === 403) {
1931
+ return {
1932
+ ok: false,
1933
+ reason: "forbidden",
1934
+ status: 403,
1935
+ error: permissionResult.error ?? "Forbidden",
1936
+ sessionResult,
1937
+ permissionResult
1938
+ };
1939
+ }
1940
+ return {
1941
+ ok: false,
1942
+ reason: "upstream_error",
1943
+ status: permissionResult.status,
1944
+ error: permissionResult.error ?? "Failed to resolve permission check",
1945
+ sessionResult,
1946
+ permissionResult
1947
+ };
1948
+ }
1805
1949
  function extractFetchOptions(input) {
1806
1950
  if (!input) {
1807
1951
  return {
@@ -1817,6 +1961,7 @@ function extractFetchOptions(input) {
1817
1961
  };
1818
1962
  }
1819
1963
  function buildHeaders2(config, options) {
1964
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
1820
1965
  const headers = {
1821
1966
  "Content-Type": "application/json",
1822
1967
  "X-Athena-Sdk": SDK_HEADER_VALUE2
@@ -1830,16 +1975,30 @@ function buildHeaders2(config, options) {
1830
1975
  if (bearerToken) {
1831
1976
  headers.Authorization = `Bearer ${bearerToken}`;
1832
1977
  }
1978
+ const cookie = options?.cookie ?? config.cookie;
1979
+ if (cookie) {
1980
+ headers.Cookie = cookie;
1981
+ }
1982
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
1983
+ if (sessionToken) {
1984
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
1985
+ }
1833
1986
  const mergedExtraHeaders = {
1834
1987
  ...config.headers ?? {},
1835
1988
  ...options?.headers ?? {}
1836
1989
  };
1837
1990
  Object.entries(mergedExtraHeaders).forEach(([key, value]) => {
1991
+ if (forceNoCache && isCacheControlHeaderName2(key)) {
1992
+ return;
1993
+ }
1838
1994
  const normalized = normalizeHeaderValue2(value);
1839
1995
  if (normalized) {
1840
1996
  headers[key] = normalized;
1841
1997
  }
1842
1998
  });
1999
+ if (forceNoCache) {
2000
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE2;
2001
+ }
1843
2002
  return headers;
1844
2003
  }
1845
2004
  function appendQueryParam(searchParams, key, value) {
@@ -2045,7 +2204,7 @@ function createAuthClient(config = {}) {
2045
2204
  ...config,
2046
2205
  baseUrl: normalizedBaseUrl
2047
2206
  };
2048
- const request = (input, options) => {
2207
+ const request2 = (input, options) => {
2049
2208
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
2050
2209
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
2051
2210
  return callAuthEndpoint(
@@ -2058,7 +2217,7 @@ function createAuthClient(config = {}) {
2058
2217
  };
2059
2218
  const postGeneric = (endpoint, input, options) => {
2060
2219
  const { payload, fetchOptions } = extractFetchOptions(input);
2061
- return request(
2220
+ return request2(
2062
2221
  {
2063
2222
  endpoint,
2064
2223
  method: "POST",
@@ -2070,7 +2229,7 @@ function createAuthClient(config = {}) {
2070
2229
  };
2071
2230
  const getGeneric = (endpoint, input, options) => {
2072
2231
  const { fetchOptions } = extractFetchOptions(input);
2073
- return request(
2232
+ return request2(
2074
2233
  {
2075
2234
  endpoint,
2076
2235
  method: "GET",
@@ -2082,7 +2241,7 @@ function createAuthClient(config = {}) {
2082
2241
  const getWithQuery = (endpoint, input, options) => {
2083
2242
  const { payload, fetchOptions } = extractFetchOptions(input);
2084
2243
  const query = payload?.query;
2085
- return request(
2244
+ return request2(
2086
2245
  {
2087
2246
  endpoint,
2088
2247
  method: "GET",
@@ -2100,11 +2259,96 @@ function createAuthClient(config = {}) {
2100
2259
  htmlField: "htmlBody",
2101
2260
  textField: "textBody"
2102
2261
  }, withReactEmailRoute(route));
2103
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
2262
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
2104
2263
  htmlField: "htmlTemplate",
2105
2264
  textField: "textTemplate",
2106
2265
  variablesField: "variables"
2107
- }, withReactEmailRoute(route));
2266
+ }, withReactEmailRoute(route)).then((payload) => {
2267
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
2268
+ if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
2269
+ assertAthenaAuthTemplateVariables(
2270
+ payload.variables,
2271
+ `${route} variables`
2272
+ );
2273
+ }
2274
+ return normalizedPayload;
2275
+ });
2276
+ const requireSession = async (input, options) => {
2277
+ const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
2278
+ const sessionResult = await getGeneric(
2279
+ "/get-session",
2280
+ sessionInput,
2281
+ options
2282
+ );
2283
+ if (!sessionResult.ok || sessionResult.data == null) {
2284
+ return toSessionGuardFailure(sessionResult);
2285
+ }
2286
+ return {
2287
+ ok: true,
2288
+ session: sessionResult.data
2289
+ };
2290
+ };
2291
+ const getUser = async (input, options) => {
2292
+ const sessionResult = await getGeneric(
2293
+ "/get-session",
2294
+ input,
2295
+ options
2296
+ );
2297
+ if (!sessionResult.ok) {
2298
+ return {
2299
+ ...sessionResult,
2300
+ data: null
2301
+ };
2302
+ }
2303
+ return {
2304
+ ...sessionResult,
2305
+ data: {
2306
+ user: sessionResult.data?.user ?? null
2307
+ }
2308
+ };
2309
+ };
2310
+ const requirePermission = async (endpoint, input, options) => {
2311
+ const sessionGuard = await requireSession(
2312
+ input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0,
2313
+ options
2314
+ );
2315
+ if (!sessionGuard.ok) {
2316
+ return sessionGuard;
2317
+ }
2318
+ const permissionResult = await postGeneric(
2319
+ endpoint,
2320
+ input,
2321
+ options
2322
+ );
2323
+ if (!permissionResult.ok) {
2324
+ return toPermissionGuardFailure(permissionResult, {
2325
+ ok: true,
2326
+ status: 200,
2327
+ data: sessionGuard.session,
2328
+ error: null,
2329
+ errorDetails: null,
2330
+ raw: sessionGuard.session
2331
+ });
2332
+ }
2333
+ if (!permissionResult.data?.success) {
2334
+ return {
2335
+ ok: false,
2336
+ reason: "forbidden",
2337
+ status: 403,
2338
+ error: permissionResult.data?.error ?? "Forbidden",
2339
+ sessionResult: {
2340
+ ok: true,
2341
+ status: 200,
2342
+ data: sessionGuard.session,
2343
+ error: null,
2344
+ errorDetails: null,
2345
+ raw: sessionGuard.session
2346
+ },
2347
+ permissionResult
2348
+ };
2349
+ }
2350
+ return sessionGuard;
2351
+ };
2108
2352
  const listUserEmailsWithFallback = async (input, options) => {
2109
2353
  const primary = await getWithQuery(
2110
2354
  "/email/list",
@@ -2266,6 +2510,7 @@ function createAuthClient(config = {}) {
2266
2510
  input,
2267
2511
  options
2268
2512
  ),
2513
+ requirePermission: (input, options) => requirePermission("/organization/has-permission", input, options),
2269
2514
  invitation: {
2270
2515
  cancel: (input, options) => executePostWithCompatibleInput(
2271
2516
  resolvedConfig,
@@ -2461,6 +2706,8 @@ function createAuthClient(config = {}) {
2461
2706
  };
2462
2707
  const auth = {
2463
2708
  getSession: (input, options) => getGeneric("/get-session", input, options),
2709
+ getUser,
2710
+ requireSession,
2464
2711
  signOut,
2465
2712
  forgetPassword: (input, options) => postGeneric("/forget-password", input, options),
2466
2713
  resetPassword: authResetPassword,
@@ -2555,6 +2802,7 @@ function createAuthClient(config = {}) {
2555
2802
  }
2556
2803
  },
2557
2804
  hasPermission: (input, options) => postGeneric("/admin/has-permission", input, options),
2805
+ requirePermission: (input, options) => requirePermission("/admin/has-permission", input, options),
2558
2806
  apiKey: {
2559
2807
  create: (input, options) => postGeneric("/admin/api-key/create", input, options)
2560
2808
  },
@@ -2599,7 +2847,15 @@ function createAuthClient(config = {}) {
2599
2847
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2600
2848
  options
2601
2849
  ),
2602
- 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)
2603
2859
  }
2604
2860
  },
2605
2861
  emailTemplate: {
@@ -2615,7 +2871,15 @@ function createAuthClient(config = {}) {
2615
2871
  "/admin/email-template/update",
2616
2872
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2617
2873
  options
2874
+ ),
2875
+ send: (input, options) => postGeneric(
2876
+ "/admin/email-template/send",
2877
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2878
+ options
2618
2879
  )
2880
+ },
2881
+ emailEventType: {
2882
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2619
2883
  }
2620
2884
  },
2621
2885
  apiKey: {
@@ -2655,7 +2919,7 @@ function createAuthClient(config = {}) {
2655
2919
  throw new Error("callback.provider requires non-empty code and state values");
2656
2920
  }
2657
2921
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
2658
- return request({
2922
+ return request2({
2659
2923
  endpoint,
2660
2924
  method: "GET",
2661
2925
  query: {
@@ -2669,7 +2933,7 @@ function createAuthClient(config = {}) {
2669
2933
  };
2670
2934
  return {
2671
2935
  baseUrl: normalizedBaseUrl,
2672
- request,
2936
+ request: request2,
2673
2937
  signIn: {
2674
2938
  email: (input, options) => executePostWithCompatibleInput(
2675
2939
  resolvedConfig,
@@ -2706,6 +2970,8 @@ function createAuthClient(config = {}) {
2706
2970
  input,
2707
2971
  options
2708
2972
  ),
2973
+ getUser,
2974
+ requireSession,
2709
2975
  listSessions: (input, options) => executeGetWithCompatibleInput(
2710
2976
  resolvedConfig,
2711
2977
  { endpoint: "/list-sessions", method: "GET" },
@@ -3408,16 +3674,16 @@ function createStorageFileModule(base, config = {}) {
3408
3674
  };
3409
3675
  });
3410
3676
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3411
- 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;
3412
3678
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3413
3679
  const uploaded = [];
3414
3680
  for (let index = 0; index < uploadRequests.length; index += 1) {
3415
- const request = uploadRequests[index];
3681
+ const request2 = uploadRequests[index];
3416
3682
  const uploadUrl = uploadUrls[index];
3417
3683
  const response = await putUploadBody(
3418
3684
  uploadUrl.upload.url,
3419
3685
  uploadUrl.upload.headers ?? {},
3420
- request.source,
3686
+ request2.source,
3421
3687
  input,
3422
3688
  options,
3423
3689
  (progress) => {
@@ -3428,13 +3694,13 @@ function createStorageFileModule(base, config = {}) {
3428
3694
  uploaded.push({
3429
3695
  file: uploadUrl.file,
3430
3696
  upload: uploadUrl.upload,
3431
- source: request.source.source,
3432
- fileName: request.source.fileName,
3433
- storage_key: request.uploadRequest.storage_key,
3697
+ source: request2.source.source,
3698
+ fileName: request2.source.fileName,
3699
+ storage_key: request2.uploadRequest.storage_key,
3434
3700
  response
3435
3701
  });
3436
- aggregateLoaded[index] = request.source.sizeBytes;
3437
- 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)));
3438
3704
  }
3439
3705
  return {
3440
3706
  files: uploaded,
@@ -5409,113 +5675,636 @@ function createStorageModule(gateway, runtimeOptions) {
5409
5675
  };
5410
5676
  }
5411
5677
 
5412
- // src/client-builder.ts
5413
- var DEFAULT_BACKEND = { type: "athena" };
5414
- function toBackendConfig(value) {
5415
- if (!value) return DEFAULT_BACKEND;
5416
- return typeof value === "string" ? { type: value } : value;
5417
- }
5418
- function mergeHeaders(current, next) {
5419
- return {
5420
- ...current ?? {},
5421
- ...next
5422
- };
5423
- }
5424
- function mergeAuthClientConfig(current, next) {
5425
- const merged = {
5426
- ...current ?? {},
5427
- ...next
5428
- };
5429
- if (current?.headers || next.headers) {
5430
- merged.headers = mergeHeaders(current?.headers, next.headers ?? {});
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;
5431
5696
  }
5432
- return merged;
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();
5433
5706
  }
5434
- function mergeExperimentalOptions(current, next) {
5435
- const merged = {
5436
- ...current ?? {},
5437
- ...next
5438
- };
5439
- if (current?.traceQueries && typeof current.traceQueries === "object" && next.traceQueries && typeof next.traceQueries === "object") {
5440
- merged.traceQueries = {
5441
- ...current.traceQueries,
5442
- ...next.traceQueries
5443
- };
5707
+ function normalizeWsUrl(value, label) {
5708
+ const normalized = value.trim();
5709
+ if (!normalized) {
5710
+ throw new Error(`${label} is required.`);
5444
5711
  }
5445
- if (current?.storage || next.storage) {
5446
- merged.storage = {
5447
- ...current?.storage ?? {},
5448
- ...next.storage ?? {}
5449
- };
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.`);
5450
5717
  }
5451
- return merged;
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(/\/$/, "");
5452
5723
  }
5453
- function resolveBuilderReturn(builder, storageEnabled, strictEnabled) {
5454
- return builder;
5724
+ function isRecord7(value) {
5725
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5455
5726
  }
5456
- var AthenaClientBuilderImpl = class {
5457
- constructor(buildClient) {
5458
- this.buildClient = buildClient;
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 };
5459
5733
  }
5460
- rootUrl;
5461
- apiKey;
5462
- backendConfig = DEFAULT_BACKEND;
5463
- clientName;
5464
- defaultHeaders;
5465
- authConfig;
5466
- dbUrlOverride;
5467
- gatewayUrlOverride;
5468
- authUrlOverride;
5469
- storageUrlOverride;
5470
- experimentalOptions;
5471
- url(url) {
5472
- this.rootUrl = url;
5473
- return this;
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 };
5474
5738
  }
5475
- key(apiKey) {
5476
- this.apiKey = apiKey;
5477
- return this;
5739
+ try {
5740
+ return { parsed: JSON.parse(rawText), parseFailed: false };
5741
+ } catch {
5742
+ return { parsed: rawText, parseFailed: true };
5478
5743
  }
5479
- backend(backend) {
5480
- this.backendConfig = toBackendConfig(backend);
5481
- return this;
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
+ }
5482
5755
  }
5483
- client(clientName) {
5484
- this.clientName = clientName;
5485
- return this;
5756
+ if (typeof payload === "string" && payload.trim().length > 0) {
5757
+ return payload.trim();
5486
5758
  }
5487
- headers(headers) {
5488
- this.defaultHeaders = headers;
5489
- return this;
5759
+ return fallback;
5760
+ }
5761
+ function encodePathSegment(value, label) {
5762
+ const normalized = value.trim();
5763
+ if (!normalized) {
5764
+ throw new Error(`${label} is required.`);
5490
5765
  }
5491
- auth(config) {
5492
- this.authConfig = mergeAuthClientConfig(this.authConfig, config);
5493
- return this;
5766
+ return encodeURIComponent(normalized);
5767
+ }
5768
+ function encodeQuery(query) {
5769
+ if (!query) {
5770
+ return "";
5494
5771
  }
5495
- experimental(options) {
5496
- this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options);
5497
- if (options.athenaStorageBackend && options.typecheckColumns) {
5498
- return resolveBuilderReturn(this);
5499
- }
5500
- if (options.athenaStorageBackend) {
5501
- return resolveBuilderReturn(this);
5772
+ const params = new URLSearchParams();
5773
+ for (const [key, value] of Object.entries(query)) {
5774
+ if (value === void 0 || value === null) {
5775
+ continue;
5502
5776
  }
5503
- if (options.typecheckColumns) {
5504
- return resolveBuilderReturn(this);
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;
5505
5784
  }
5506
- return this;
5785
+ params.set(key, String(value));
5507
5786
  }
5508
- options(options) {
5509
- if (options.client !== void 0) {
5510
- this.clientName = options.client;
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);
5511
5796
  }
5512
- if (options.backend !== void 0) {
5513
- this.backendConfig = toBackendConfig(options.backend);
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
+ }
5514
5831
  }
5515
- if (options.headers !== void 0) {
5516
- this.defaultHeaders = mergeHeaders(this.defaultHeaders, options.headers);
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
5517
5842
  }
5518
- if (options.auth !== void 0) {
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
+
6189
+ // src/client-builder.ts
6190
+ var DEFAULT_BACKEND = { type: "athena" };
6191
+ function toBackendConfig(value) {
6192
+ if (!value) return DEFAULT_BACKEND;
6193
+ return typeof value === "string" ? { type: value } : value;
6194
+ }
6195
+ function mergeHeaders(current, next) {
6196
+ return {
6197
+ ...current ?? {},
6198
+ ...next
6199
+ };
6200
+ }
6201
+ function mergeAuthClientConfig(current, next) {
6202
+ const merged = {
6203
+ ...current ?? {},
6204
+ ...next
6205
+ };
6206
+ if (current?.headers || next.headers) {
6207
+ merged.headers = mergeHeaders(current?.headers, next.headers ?? {});
6208
+ }
6209
+ return merged;
6210
+ }
6211
+ function mergeExperimentalOptions(current, next) {
6212
+ const merged = {
6213
+ ...current ?? {},
6214
+ ...next
6215
+ };
6216
+ if (current?.traceQueries && typeof current.traceQueries === "object" && next.traceQueries && typeof next.traceQueries === "object") {
6217
+ merged.traceQueries = {
6218
+ ...current.traceQueries,
6219
+ ...next.traceQueries
6220
+ };
6221
+ }
6222
+ if (current?.storage || next.storage) {
6223
+ merged.storage = {
6224
+ ...current?.storage ?? {},
6225
+ ...next.storage ?? {}
6226
+ };
6227
+ }
6228
+ return merged;
6229
+ }
6230
+ function resolveBuilderReturn(builder, storageEnabled, strictEnabled) {
6231
+ return builder;
6232
+ }
6233
+ var AthenaClientBuilderImpl = class {
6234
+ constructor(buildClient) {
6235
+ this.buildClient = buildClient;
6236
+ }
6237
+ rootUrl;
6238
+ apiKey;
6239
+ backendConfig = DEFAULT_BACKEND;
6240
+ clientName;
6241
+ defaultUserId;
6242
+ defaultOrganizationId;
6243
+ forceNoCacheEnabled = false;
6244
+ defaultHeaders;
6245
+ authConfig;
6246
+ dbUrlOverride;
6247
+ gatewayUrlOverride;
6248
+ authUrlOverride;
6249
+ storageUrlOverride;
6250
+ experimentalOptions;
6251
+ url(url) {
6252
+ this.rootUrl = url;
6253
+ return this;
6254
+ }
6255
+ key(apiKey) {
6256
+ this.apiKey = apiKey;
6257
+ return this;
6258
+ }
6259
+ backend(backend) {
6260
+ this.backendConfig = toBackendConfig(backend);
6261
+ return this;
6262
+ }
6263
+ client(clientName) {
6264
+ this.clientName = clientName;
6265
+ return this;
6266
+ }
6267
+ headers(headers) {
6268
+ this.defaultHeaders = headers;
6269
+ return this;
6270
+ }
6271
+ auth(config) {
6272
+ this.authConfig = mergeAuthClientConfig(this.authConfig, config);
6273
+ return this;
6274
+ }
6275
+ experimental(options) {
6276
+ this.experimentalOptions = mergeExperimentalOptions(this.experimentalOptions, options);
6277
+ if (options.athenaStorageBackend && options.typecheckColumns) {
6278
+ return resolveBuilderReturn(this);
6279
+ }
6280
+ if (options.athenaStorageBackend) {
6281
+ return resolveBuilderReturn(this);
6282
+ }
6283
+ if (options.typecheckColumns) {
6284
+ return resolveBuilderReturn(this);
6285
+ }
6286
+ return this;
6287
+ }
6288
+ options(options) {
6289
+ if (options.client !== void 0) {
6290
+ this.clientName = options.client;
6291
+ }
6292
+ if (options.userId !== void 0) {
6293
+ this.defaultUserId = options.userId;
6294
+ }
6295
+ if (options.organizationId !== void 0) {
6296
+ this.defaultOrganizationId = options.organizationId;
6297
+ }
6298
+ if (options.forceNoCache !== void 0) {
6299
+ this.forceNoCacheEnabled = options.forceNoCache;
6300
+ }
6301
+ if (options.backend !== void 0) {
6302
+ this.backendConfig = toBackendConfig(options.backend);
6303
+ }
6304
+ if (options.headers !== void 0) {
6305
+ this.defaultHeaders = mergeHeaders(this.defaultHeaders, options.headers);
6306
+ }
6307
+ if (options.auth !== void 0) {
5519
6308
  this.authConfig = mergeAuthClientConfig(this.authConfig, options.auth);
5520
6309
  }
5521
6310
  if (options.db?.url !== void 0 && options.db.url !== null) {
@@ -5563,6 +6352,9 @@ var AthenaClientBuilderImpl = class {
5563
6352
  url: this.rootUrl,
5564
6353
  key: this.apiKey,
5565
6354
  client: this.clientName,
6355
+ userId: this.defaultUserId,
6356
+ organizationId: this.defaultOrganizationId,
6357
+ forceNoCache: this.forceNoCacheEnabled,
5566
6358
  backend: this.backendConfig,
5567
6359
  headers: this.defaultHeaders,
5568
6360
  db: this.dbUrlOverride ? { url: this.dbUrlOverride } : void 0,
@@ -5606,7 +6398,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
5606
6398
  "ilike",
5607
6399
  "is"
5608
6400
  ]);
5609
- function isRecord7(value) {
6401
+ function isRecord8(value) {
5610
6402
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5611
6403
  }
5612
6404
  function isUuidString(value) {
@@ -5619,7 +6411,7 @@ function shouldUseUuidTextComparison(column, value) {
5619
6411
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
5620
6412
  }
5621
6413
  function isRelationSelectNode(value) {
5622
- return isRecord7(value) && isRecord7(value.select);
6414
+ return isRecord8(value) && isRecord8(value.select);
5623
6415
  }
5624
6416
  function normalizeIdentifier(value, label) {
5625
6417
  const normalized = value.trim();
@@ -5675,7 +6467,7 @@ function compileRelationToken(key, node) {
5675
6467
  return `${prefix}${relationToken}(${nested})`;
5676
6468
  }
5677
6469
  function compileSelectShape(select) {
5678
- if (!isRecord7(select)) {
6470
+ if (!isRecord8(select)) {
5679
6471
  throw new Error("findMany select must be an object");
5680
6472
  }
5681
6473
  const tokens = [];
@@ -5699,7 +6491,7 @@ function compileSelectShape(select) {
5699
6491
  return tokens.join(",");
5700
6492
  }
5701
6493
  function selectShapeUsesRelationSchema(select) {
5702
- if (!isRecord7(select)) {
6494
+ if (!isRecord8(select)) {
5703
6495
  return false;
5704
6496
  }
5705
6497
  for (const rawValue of Object.values(select)) {
@@ -5717,7 +6509,7 @@ function selectShapeUsesRelationSchema(select) {
5717
6509
  }
5718
6510
  function compileColumnWhere(column, input) {
5719
6511
  const normalizedColumn = normalizeIdentifier(column, "where column");
5720
- if (!isRecord7(input)) {
6512
+ if (!isRecord8(input)) {
5721
6513
  return [buildGatewayCondition("eq", normalizedColumn, input)];
5722
6514
  }
5723
6515
  const conditions = [];
@@ -5745,7 +6537,7 @@ function compileColumnWhere(column, input) {
5745
6537
  return conditions;
5746
6538
  }
5747
6539
  function compileBooleanExpressionTerms(clause, label) {
5748
- if (!isRecord7(clause)) {
6540
+ if (!isRecord8(clause)) {
5749
6541
  throw new Error(`findMany where.${label} clauses must be objects`);
5750
6542
  }
5751
6543
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -5754,7 +6546,7 @@ function compileBooleanExpressionTerms(clause, label) {
5754
6546
  }
5755
6547
  const [rawColumn, rawValue] = entries[0];
5756
6548
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
5757
- if (!isRecord7(rawValue)) {
6549
+ if (!isRecord8(rawValue)) {
5758
6550
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
5759
6551
  }
5760
6552
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -5778,7 +6570,7 @@ function compileWhere(where) {
5778
6570
  if (where === void 0) {
5779
6571
  return void 0;
5780
6572
  }
5781
- if (!isRecord7(where)) {
6573
+ if (!isRecord8(where)) {
5782
6574
  throw new Error("findMany where must be an object");
5783
6575
  }
5784
6576
  const conditions = [];
@@ -5828,7 +6620,7 @@ function compileOrderBy(orderBy) {
5828
6620
  if (orderBy === void 0) {
5829
6621
  return void 0;
5830
6622
  }
5831
- if (!isRecord7(orderBy)) {
6623
+ if (!isRecord8(orderBy)) {
5832
6624
  throw new Error("findMany orderBy must be an object");
5833
6625
  }
5834
6626
  if ("column" in orderBy) {
@@ -6003,11 +6795,11 @@ function toFindManyAstOrder(order) {
6003
6795
  ascending: order.direction !== "descending"
6004
6796
  };
6005
6797
  }
6006
- function isRecord8(value) {
6798
+ function isRecord9(value) {
6007
6799
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6008
6800
  }
6009
6801
  function normalizeFindManyAstColumnPredicate(value) {
6010
- if (!isRecord8(value)) {
6802
+ if (!isRecord9(value)) {
6011
6803
  return {
6012
6804
  eq: value
6013
6805
  };
@@ -6031,7 +6823,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6031
6823
  return normalized;
6032
6824
  }
6033
6825
  function normalizeFindManyAstWhere(where) {
6034
- if (!where || !isRecord8(where)) {
6826
+ if (!where || !isRecord9(where)) {
6035
6827
  return where;
6036
6828
  }
6037
6829
  const normalized = {};
@@ -6045,7 +6837,7 @@ function normalizeFindManyAstWhere(where) {
6045
6837
  );
6046
6838
  continue;
6047
6839
  }
6048
- if (key === "not" && isRecord8(value)) {
6840
+ if (key === "not" && isRecord9(value)) {
6049
6841
  normalized.not = normalizeFindManyAstBooleanOperand(
6050
6842
  value
6051
6843
  );
@@ -6056,7 +6848,7 @@ function normalizeFindManyAstWhere(where) {
6056
6848
  return normalized;
6057
6849
  }
6058
6850
  function predicateRequiresUuidQueryFallback(column, value) {
6059
- if (!isRecord8(value)) {
6851
+ if (!isRecord9(value)) {
6060
6852
  return shouldUseUuidTextComparison(column, value);
6061
6853
  }
6062
6854
  const eqValue = value.eq;
@@ -6074,7 +6866,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6074
6866
  return false;
6075
6867
  }
6076
6868
  function findManyAstWhereRequiresLegacyTransport(where) {
6077
- if (!where || !isRecord8(where)) {
6869
+ if (!where || !isRecord9(where)) {
6078
6870
  return false;
6079
6871
  }
6080
6872
  for (const [key, value] of Object.entries(where)) {
@@ -6089,7 +6881,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6089
6881
  }
6090
6882
  continue;
6091
6883
  }
6092
- if (key === "not" && isRecord8(value)) {
6884
+ if (key === "not" && isRecord9(value)) {
6093
6885
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6094
6886
  return true;
6095
6887
  }
@@ -6638,6 +7430,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
6638
7430
  var DEFAULT_COLUMNS = "*";
6639
7431
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6640
7432
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7433
+ var SDK_NAME4 = "xylex-group/athena";
6641
7434
  function formatResult(response) {
6642
7435
  const result = {
6643
7436
  data: response.data ?? null,
@@ -6714,7 +7507,7 @@ async function executeExperimentalRead(experimental, runner) {
6714
7507
  throw error;
6715
7508
  }
6716
7509
  }
6717
- function isRecord9(value) {
7510
+ function isRecord10(value) {
6718
7511
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6719
7512
  }
6720
7513
  function firstNonEmptyString2(...values) {
@@ -6726,8 +7519,8 @@ function firstNonEmptyString2(...values) {
6726
7519
  return void 0;
6727
7520
  }
6728
7521
  function resolveStructuredErrorPayload2(raw) {
6729
- if (!isRecord9(raw)) return null;
6730
- return isRecord9(raw.error) ? raw.error : raw;
7522
+ if (!isRecord10(raw)) return null;
7523
+ return isRecord10(raw.error) ? raw.error : raw;
6731
7524
  }
6732
7525
  function resolveStructuredErrorDetails(payload, message) {
6733
7526
  if (!payload || !("details" in payload)) {
@@ -6743,7 +7536,7 @@ function resolveStructuredErrorDetails(payload, message) {
6743
7536
  return details;
6744
7537
  }
6745
7538
  function createResultError(response, result, normalized) {
6746
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7539
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
6747
7540
  const payload = resolveStructuredErrorPayload2(response.raw);
6748
7541
  const message = firstNonEmptyString2(
6749
7542
  response.error,
@@ -6806,6 +7599,43 @@ function asAthenaJsonObject(value) {
6806
7599
  function asAthenaJsonObjectArray(values) {
6807
7600
  return values;
6808
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
+ }
6809
7639
  function normalizeSelectColumnsInput(columns) {
6810
7640
  if (columns === void 0) {
6811
7641
  return void 0;
@@ -8105,6 +8935,85 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
8105
8935
  );
8106
8936
  };
8107
8937
  }
8938
+ var ATHENA_ENV_URL_KEYS = ["ATHENA_URL", "NEXT_PUBLIC_ATHENA_URL"];
8939
+ var ATHENA_ENV_GATEWAY_URL_KEYS = [
8940
+ "ATHENA_DB_URL",
8941
+ "ATHENA_GATEWAY_URL",
8942
+ "NEXT_PUBLIC_ATHENA_DB_API_URL"
8943
+ ];
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"];
8947
+ var ATHENA_ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
8948
+ var ATHENA_ENV_KEY_KEYS = [
8949
+ "ATHENA_API_KEY",
8950
+ "NEXT_PUBLIC_ATHENA_API_KEY",
8951
+ "ATHENA_GATEWAY_API_KEY",
8952
+ "X_API_KEY"
8953
+ ];
8954
+ var ATHENA_ENV_CLIENT_KEYS = ["ATHENA_CLIENT", "NEXT_PUBLIC_ATHENA_CLIENT"];
8955
+ function normalizeOptionalString(value) {
8956
+ if (typeof value !== "string") {
8957
+ return void 0;
8958
+ }
8959
+ const normalizedValue = value.trim();
8960
+ return normalizedValue ? normalizedValue : void 0;
8961
+ }
8962
+ function readFirstEnvValue(env, keys) {
8963
+ for (const key of keys) {
8964
+ const value = normalizeOptionalString(env[key]);
8965
+ if (value) {
8966
+ return value;
8967
+ }
8968
+ }
8969
+ return void 0;
8970
+ }
8971
+ function readHeaderBagValue(headers, targetKey) {
8972
+ if (!headers) {
8973
+ return void 0;
8974
+ }
8975
+ if (typeof headers.get === "function") {
8976
+ return normalizeOptionalString(headers.get(targetKey));
8977
+ }
8978
+ const normalizedTargetKey = targetKey.toLowerCase();
8979
+ for (const [key, value] of Object.entries(headers)) {
8980
+ if (key.toLowerCase() !== normalizedTargetKey) {
8981
+ continue;
8982
+ }
8983
+ if (typeof value === "string") {
8984
+ return normalizeOptionalString(value);
8985
+ }
8986
+ return void 0;
8987
+ }
8988
+ return void 0;
8989
+ }
8990
+ function resolveSessionContextOptions(session, options) {
8991
+ const sessionToken = normalizeOptionalString(session?.session?.token);
8992
+ const requestCookie = readHeaderBagValue(options?.requestHeaders, "cookie") ?? readHeaderBagValue(options?.headers, "cookie");
8993
+ const authInput = options?.auth;
8994
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
8995
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
8996
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
8997
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
8998
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
8999
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9000
+ ...authInput ?? {},
9001
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9002
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9003
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9004
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9005
+ } : void 0;
9006
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9007
+ return void 0;
9008
+ }
9009
+ return {
9010
+ userId: resolvedUserId,
9011
+ organizationId: resolvedOrganizationId,
9012
+ forceNoCache: options?.forceNoCache,
9013
+ headers: options?.headers ? { ...options.headers } : void 0,
9014
+ auth
9015
+ };
9016
+ }
8108
9017
  function resolveClientServiceBaseUrl(value, label) {
8109
9018
  if (value === void 0 || value === null) {
8110
9019
  return void 0;
@@ -8115,6 +9024,15 @@ function appendServicePath(baseUrl, segment) {
8115
9024
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8116
9025
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8117
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
+ }
8118
9036
  function resolveServiceUrlOverride(value, label) {
8119
9037
  return resolveClientServiceBaseUrl(value, label);
8120
9038
  }
@@ -8123,6 +9041,8 @@ function resolveServiceUrls(config) {
8123
9041
  return {
8124
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),
8125
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),
8126
9046
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8127
9047
  };
8128
9048
  }
@@ -8147,6 +9067,89 @@ function resolveRequiredClientApiKey(value) {
8147
9067
  }
8148
9068
  return normalizedValue;
8149
9069
  }
9070
+ function hasHeaderIgnoreCase(headers, targetKey) {
9071
+ const normalizedTargetKey = targetKey.toLowerCase();
9072
+ return Object.keys(headers).some((key) => key.toLowerCase() === normalizedTargetKey);
9073
+ }
9074
+ function mergeClientHeaders(current, next) {
9075
+ if (!current && !next) {
9076
+ return void 0;
9077
+ }
9078
+ return {
9079
+ ...current ?? {},
9080
+ ...next ?? {}
9081
+ };
9082
+ }
9083
+ function mergeDefinedObject(current, next) {
9084
+ if (!current && !next) {
9085
+ return void 0;
9086
+ }
9087
+ const merged = {
9088
+ ...current ?? {}
9089
+ };
9090
+ const mutableMerged = merged;
9091
+ for (const [key, value] of Object.entries(next ?? {})) {
9092
+ if (value !== void 0) {
9093
+ mutableMerged[key] = value;
9094
+ }
9095
+ }
9096
+ return merged;
9097
+ }
9098
+ function mergeAuthClientOptions(current, next) {
9099
+ const merged = mergeDefinedObject(current, next);
9100
+ if (!merged) {
9101
+ return void 0;
9102
+ }
9103
+ const mergedHeaders = mergeClientHeaders(current?.headers, next?.headers);
9104
+ if (mergedHeaders) {
9105
+ merged.headers = mergedHeaders;
9106
+ }
9107
+ return merged;
9108
+ }
9109
+ function mergeServiceUrlOverrides(current, next) {
9110
+ return mergeDefinedObject(current, next);
9111
+ }
9112
+ function toClientContextOverrides(context) {
9113
+ if (!context) {
9114
+ return void 0;
9115
+ }
9116
+ return {
9117
+ userId: context.userId,
9118
+ organizationId: context.organizationId,
9119
+ forceNoCache: context.forceNoCache,
9120
+ headers: context.headers,
9121
+ auth: context.auth ? {
9122
+ ...context.auth,
9123
+ headers: context.auth.headers ? { ...context.auth.headers } : void 0
9124
+ } : void 0
9125
+ };
9126
+ }
9127
+ function mergeClientOverrideOptions(base, overrides) {
9128
+ if (!overrides) {
9129
+ return {
9130
+ ...base,
9131
+ headers: base.headers ? { ...base.headers } : void 0,
9132
+ auth: base.auth ? {
9133
+ ...base.auth,
9134
+ headers: base.auth.headers ? { ...base.auth.headers } : void 0
9135
+ } : void 0,
9136
+ db: base.db ? { ...base.db } : void 0,
9137
+ gateway: base.gateway ? { ...base.gateway } : void 0,
9138
+ chat: base.chat ? { ...base.chat } : void 0,
9139
+ storage: base.storage ? { ...base.storage } : void 0
9140
+ };
9141
+ }
9142
+ const merged = mergeDefinedObject(base, overrides) ?? { ...base };
9143
+ return {
9144
+ ...merged,
9145
+ headers: mergeClientHeaders(base.headers, overrides.headers),
9146
+ auth: mergeAuthClientOptions(base.auth, overrides.auth),
9147
+ db: mergeServiceUrlOverrides(base.db, overrides.db),
9148
+ gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9149
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
9150
+ storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
9151
+ };
9152
+ }
8150
9153
  function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8151
9154
  if (!auth && defaultBaseUrl === void 0) {
8152
9155
  return void 0;
@@ -8156,6 +9159,8 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8156
9159
  baseUrl,
8157
9160
  apiKey,
8158
9161
  bearerToken,
9162
+ cookie,
9163
+ sessionToken,
8159
9164
  ...rest
8160
9165
  } = auth ?? {};
8161
9166
  const normalized = {
@@ -8174,6 +9179,12 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8174
9179
  if (typeof bearerToken === "string") {
8175
9180
  normalized.bearerToken = bearerToken;
8176
9181
  }
9182
+ if (typeof cookie === "string") {
9183
+ normalized.cookie = cookie;
9184
+ }
9185
+ if (typeof sessionToken === "string") {
9186
+ normalized.sessionToken = sessionToken;
9187
+ }
8177
9188
  return normalized;
8178
9189
  }
8179
9190
  function resolveCreateClientConfig(config) {
@@ -8187,31 +9198,53 @@ function resolveCreateClientConfig(config) {
8187
9198
  baseUrl: resolvedUrls.dbUrl,
8188
9199
  apiKey: resolveRequiredClientApiKey(config.key),
8189
9200
  client: resolveOptionalClientName(config.client),
9201
+ userId: config.userId,
9202
+ organizationId: config.organizationId,
9203
+ forceNoCache: config.forceNoCache,
8190
9204
  backend: toBackendConfig(config.backend),
8191
9205
  headers: config.headers,
8192
9206
  auth: config.auth,
8193
9207
  authUrl: resolvedUrls.authUrl,
9208
+ chat: config.chat,
9209
+ chatUrl: resolvedUrls.chatUrl,
9210
+ chatWsUrl: resolvedUrls.chatWsUrl,
8194
9211
  storageUrl: resolvedUrls.storageUrl,
8195
9212
  experimental: config.experimental
8196
9213
  };
8197
9214
  }
8198
- function createClientFromConfig(config) {
9215
+ function createClientFromInput(sourceConfig) {
9216
+ return createClientFromConfig(resolveCreateClientConfig(sourceConfig), sourceConfig);
9217
+ }
9218
+ function createClientFromConfig(config, sourceConfig) {
9219
+ const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
8199
9220
  const gatewayHeaders = {
8200
9221
  ...config.headers ?? {}
8201
9222
  };
8202
- if (config.auth?.bearerToken && gatewayHeaders["X-Athena-Auth-Bearer-Token"] === void 0 && gatewayHeaders["x-athena-auth-bearer-token"] === void 0) {
8203
- gatewayHeaders["X-Athena-Auth-Bearer-Token"] = config.auth.bearerToken;
9223
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Bearer-Token")) {
9224
+ gatewayHeaders["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9225
+ }
9226
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(gatewayHeaders, "Cookie")) {
9227
+ gatewayHeaders.Cookie = normalizedAuthConfig.cookie;
9228
+ }
9229
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Session-Token")) {
9230
+ gatewayHeaders["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
8204
9231
  }
8205
9232
  const gateway = createAthenaGatewayClient({
8206
9233
  baseUrl: config.baseUrl,
8207
9234
  apiKey: config.apiKey,
8208
9235
  client: config.client,
9236
+ userId: config.userId,
9237
+ organizationId: config.organizationId,
9238
+ forceNoCache: config.forceNoCache,
8209
9239
  backend: config.backend,
8210
9240
  headers: gatewayHeaders
8211
9241
  });
8212
9242
  const formatGatewayResult = createResultFormatter(config.experimental);
8213
9243
  const queryTracer = createQueryTracer(config.experimental);
8214
- const auth = createAuthClient(normalizeAuthClientConfig(config.auth, config.authUrl));
9244
+ const auth = createAuthClient({
9245
+ ...normalizedAuthConfig ?? {},
9246
+ ...config.forceNoCache ? { forceNoCache: true } : {}
9247
+ });
8215
9248
  function from(tableOrModel, options) {
8216
9249
  if (isAthenaModelTarget(tableOrModel)) {
8217
9250
  if (options?.schema !== void 0) {
@@ -8259,17 +9292,160 @@ function createClientFromConfig(config) {
8259
9292
  queryTracer
8260
9293
  );
8261
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
+ };
9408
+ const withContext = (context) => createClientFromInput(
9409
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9410
+ );
9411
+ const withSession = (session, options) => createClientFromInput(
9412
+ mergeClientOverrideOptions(
9413
+ sourceConfig,
9414
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9415
+ )
9416
+ );
9417
+ const authWithOptions = (options) => createClientFromInput(mergeClientOverrideOptions(sourceConfig, options));
8262
9418
  const sdkClient = {
8263
9419
  from,
8264
9420
  db,
8265
9421
  rpc,
8266
9422
  query,
9423
+ request: request2,
8267
9424
  verifyConnection: gateway.verifyConnection,
8268
- auth: auth.auth
9425
+ auth: auth.auth,
9426
+ chat,
9427
+ withContext,
9428
+ withSession,
9429
+ withOptions: authWithOptions
8269
9430
  };
8270
9431
  if (config.experimental?.athenaStorageBackend) {
9432
+ const storageWithContext = (context) => createClientFromInput(
9433
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9434
+ );
9435
+ const storageWithSession = (session, options) => createClientFromInput(
9436
+ mergeClientOverrideOptions(
9437
+ sourceConfig,
9438
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9439
+ )
9440
+ );
9441
+ const storageWithOptions = (options) => createClientFromInput(
9442
+ mergeClientOverrideOptions(sourceConfig, options)
9443
+ );
8271
9444
  const storageClient = {
8272
9445
  ...sdkClient,
9446
+ withContext: storageWithContext,
9447
+ withSession: storageWithSession,
9448
+ withOptions: storageWithOptions,
8273
9449
  storage: createStorageModule(gateway, {
8274
9450
  ...config.experimental.storage,
8275
9451
  ...config.storageUrl ? {
@@ -8285,38 +9461,46 @@ function createClientFromConfig(config) {
8285
9461
  var AthenaClient = class {
8286
9462
  /** Create a fluent builder for a strongly-typed Athena SDK client. */
8287
9463
  static builder() {
8288
- return createAthenaClientBuilder((config) => createClientFromConfig(resolveCreateClientConfig(config)));
8289
- }
8290
- /** Build a client from process environment variables. */
8291
- static fromEnvironment() {
8292
- const url = process.env.ATHENA_URL;
8293
- const gatewayUrl = process.env.ATHENA_DB_URL ?? process.env.ATHENA_GATEWAY_URL;
8294
- const authUrl = process.env.ATHENA_AUTH_URL;
8295
- const storageUrl = process.env.ATHENA_STORAGE_URL;
8296
- const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
9464
+ return createAthenaClientBuilder((config) => createClientFromInput(config));
9465
+ }
9466
+ static fromEnvironment(options = {}) {
9467
+ const env = options.env ?? process.env;
9468
+ const url = options.url ?? readFirstEnvValue(env, ATHENA_ENV_URL_KEYS);
9469
+ const gatewayUrl = options.gatewayUrl ?? readFirstEnvValue(env, ATHENA_ENV_GATEWAY_URL_KEYS);
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);
9473
+ const storageUrl = options.storageUrl ?? readFirstEnvValue(env, ATHENA_ENV_STORAGE_URL_KEYS);
9474
+ const key = options.key ?? readFirstEnvValue(env, ATHENA_ENV_KEY_KEYS);
9475
+ const client = options.client ?? readFirstEnvValue(env, ATHENA_ENV_CLIENT_KEYS);
8297
9476
  if (!url && !gatewayUrl || !key) {
8298
9477
  throw new Error(
8299
- "ATHENA_API_KEY plus ATHENA_URL or ATHENA_GATEWAY_URL (optionally ATHENA_DB_URL, ATHENA_AUTH_URL, ATHENA_STORAGE_URL) are required"
9478
+ "AthenaClient.fromEnvironment() requires an API key plus a public or gateway URL. Supported aliases include ATHENA_API_KEY, NEXT_PUBLIC_ATHENA_API_KEY, ATHENA_GATEWAY_API_KEY, X_API_KEY, ATHENA_URL, NEXT_PUBLIC_ATHENA_URL, ATHENA_GATEWAY_URL, and ATHENA_DB_URL."
8300
9479
  );
8301
9480
  }
9481
+ const { env: _env, ...clientOptions } = options;
8302
9482
  return createClient({
9483
+ ...clientOptions,
8303
9484
  url,
8304
9485
  gatewayUrl,
8305
9486
  authUrl,
9487
+ chatUrl,
9488
+ chatWsUrl,
8306
9489
  storageUrl,
8307
- key
9490
+ key,
9491
+ client
8308
9492
  });
8309
9493
  }
8310
9494
  };
8311
9495
  function createClient(configOrUrl, apiKey, options) {
8312
9496
  if (typeof configOrUrl === "string" || configOrUrl === null || configOrUrl === void 0) {
8313
- return createClientFromConfig(resolveCreateClientConfig({
9497
+ return createClientFromInput({
8314
9498
  url: configOrUrl,
8315
9499
  key: apiKey ?? "",
8316
9500
  ...options
8317
- }));
9501
+ });
8318
9502
  }
8319
- return createClientFromConfig(resolveCreateClientConfig(configOrUrl));
9503
+ return createClientFromInput(configOrUrl);
8320
9504
  }
8321
9505
 
8322
9506
  // src/gateway/types.ts
@@ -8347,7 +9531,7 @@ function resolveNullishValue(mode) {
8347
9531
  if (mode === "null") return null;
8348
9532
  return "";
8349
9533
  }
8350
- function isRecord10(value) {
9534
+ function isRecord11(value) {
8351
9535
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8352
9536
  }
8353
9537
  function isNullableColumn(model, key) {
@@ -8356,7 +9540,7 @@ function isNullableColumn(model, key) {
8356
9540
  }
8357
9541
  function toModelFormDefaults(model, values, options) {
8358
9542
  const source = values;
8359
- if (!isRecord10(source)) {
9543
+ if (!isRecord11(source)) {
8360
9544
  return {};
8361
9545
  }
8362
9546
  const mode = options?.nullishMode ?? "empty-string";
@@ -8682,6 +9866,9 @@ function createColumnsBuilder(name, mappedName, schemaName, columns) {
8682
9866
  resolveTableTarget(name, mappedName, normalizedSchemaName);
8683
9867
  return createColumnsBuilder(name, mappedName, normalizedSchemaName, columns);
8684
9868
  },
9869
+ withoutPrimaryKey() {
9870
+ return finalizeTable(name, mappedName, schemaName, columns, []);
9871
+ },
8685
9872
  primaryKey(...keys) {
8686
9873
  return finalizeTable(name, mappedName, schemaName, columns, keys);
8687
9874
  }
@@ -8733,6 +9920,59 @@ var TenantHeaderMapper = class {
8733
9920
  return Object.keys(headers).length > 0 ? headers : void 0;
8734
9921
  }
8735
9922
  };
9923
+ function normalizeOptionalString2(value) {
9924
+ if (typeof value !== "string") {
9925
+ return void 0;
9926
+ }
9927
+ const normalizedValue = value.trim();
9928
+ return normalizedValue ? normalizedValue : void 0;
9929
+ }
9930
+ function readHeaderBagValue2(headers, targetKey) {
9931
+ if (!headers) {
9932
+ return void 0;
9933
+ }
9934
+ if (typeof headers.get === "function") {
9935
+ return normalizeOptionalString2(headers.get(targetKey));
9936
+ }
9937
+ const normalizedTargetKey = targetKey.toLowerCase();
9938
+ for (const [key, value] of Object.entries(headers)) {
9939
+ if (key.toLowerCase() !== normalizedTargetKey) {
9940
+ continue;
9941
+ }
9942
+ if (typeof value === "string") {
9943
+ return normalizeOptionalString2(value);
9944
+ }
9945
+ return void 0;
9946
+ }
9947
+ return void 0;
9948
+ }
9949
+ function resolveSessionContextOptions2(session, options) {
9950
+ const sessionToken = normalizeOptionalString2(session?.session?.token);
9951
+ const requestCookie = readHeaderBagValue2(options?.requestHeaders, "cookie") ?? readHeaderBagValue2(options?.headers, "cookie");
9952
+ const authInput = options?.auth;
9953
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
9954
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
9955
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
9956
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
9957
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
9958
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9959
+ ...authInput ?? {},
9960
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9961
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9962
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9963
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9964
+ } : void 0;
9965
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9966
+ return void 0;
9967
+ }
9968
+ return {
9969
+ userId: resolvedUserId,
9970
+ organizationId: resolvedOrganizationId,
9971
+ forceNoCache: options?.forceNoCache,
9972
+ headers: options?.headers ? { ...options.headers } : void 0,
9973
+ auth
9974
+ };
9975
+ }
8736
9976
  var RegistryNavigator = class {
8737
9977
  constructor(registry) {
8738
9978
  this.registry = registry;
@@ -8784,12 +10024,22 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
8784
10024
  backend: input.options?.backend,
8785
10025
  client: input.options?.client,
8786
10026
  headers: input.options?.headers,
10027
+ forceNoCache: input.options?.forceNoCache,
10028
+ userId: input.options?.userId,
10029
+ organizationId: input.options?.organizationId,
10030
+ auth: input.options?.auth,
10031
+ tenantKeyMap,
10032
+ tenantContext,
8787
10033
  experimental: input.options?.experimental
8788
10034
  };
8789
10035
  this.baseClient = createClient(this.url, this.apiKey, {
8790
10036
  backend: this.clientOptions.backend,
8791
10037
  client: this.clientOptions.client,
8792
10038
  headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext),
10039
+ forceNoCache: this.clientOptions.forceNoCache,
10040
+ userId: this.clientOptions.userId,
10041
+ organizationId: this.clientOptions.organizationId,
10042
+ auth: this.clientOptions.auth,
8793
10043
  experimental: this.clientOptions.experimental
8794
10044
  });
8795
10045
  this.db = this.baseClient.db;
@@ -8804,9 +10054,46 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
8804
10054
  query(query, options) {
8805
10055
  return this.baseClient.query(query, options);
8806
10056
  }
10057
+ request(options) {
10058
+ return this.baseClient.request(options);
10059
+ }
8807
10060
  verifyConnection(options) {
8808
10061
  return this.baseClient.verifyConnection(options);
8809
10062
  }
10063
+ withContext(context) {
10064
+ const headers = {
10065
+ ...this.clientOptions.headers ?? {},
10066
+ ...context?.headers ?? {}
10067
+ };
10068
+ const auth = this.clientOptions.auth || context?.auth ? {
10069
+ ...this.clientOptions.auth ?? {},
10070
+ ...context?.auth ?? {},
10071
+ headers: this.clientOptions.auth?.headers || context?.auth?.headers ? {
10072
+ ...this.clientOptions.auth?.headers ?? {},
10073
+ ...context?.auth?.headers ?? {}
10074
+ } : void 0
10075
+ } : void 0;
10076
+ return new _TypedAthenaClientImpl({
10077
+ registry: this.registry,
10078
+ url: this.url,
10079
+ apiKey: this.apiKey,
10080
+ options: {
10081
+ ...this.clientOptions,
10082
+ headers: Object.keys(headers).length > 0 ? headers : void 0,
10083
+ auth,
10084
+ tenantKeyMap: this.tenantKeyMap,
10085
+ tenantContext: {
10086
+ ...this.tenantContext
10087
+ },
10088
+ ...context?.userId !== void 0 ? { userId: context.userId } : {},
10089
+ ...context?.organizationId !== void 0 ? { organizationId: context.organizationId } : {},
10090
+ ...context?.forceNoCache !== void 0 ? { forceNoCache: context.forceNoCache } : {}
10091
+ }
10092
+ });
10093
+ }
10094
+ withSession(session, options) {
10095
+ return this.withContext(resolveSessionContextOptions2(session, options));
10096
+ }
8810
10097
  withTenantContext(context) {
8811
10098
  return new _TypedAthenaClientImpl({
8812
10099
  registry: this.registry,
@@ -8867,6 +10154,77 @@ function resolveProviderSchemas(providerConfig) {
8867
10154
  return [...DEFAULT_POSTGRES_SCHEMAS];
8868
10155
  }
8869
10156
 
10157
+ // src/generator/table-selection.ts
10158
+ function normalizeTableSelector(value) {
10159
+ const trimmed = value.trim();
10160
+ return trimmed.length > 0 ? trimmed : void 0;
10161
+ }
10162
+ function normalizeTableSelection(value) {
10163
+ if (typeof value === "string") {
10164
+ return Array.from(
10165
+ new Set(
10166
+ value.split(",").map(normalizeTableSelector).filter((entry) => Boolean(entry))
10167
+ )
10168
+ );
10169
+ }
10170
+ if (Array.isArray(value)) {
10171
+ return Array.from(
10172
+ new Set(
10173
+ value.map((entry) => typeof entry === "string" ? normalizeTableSelector(entry) : void 0).filter((entry) => Boolean(entry))
10174
+ )
10175
+ );
10176
+ }
10177
+ return [];
10178
+ }
10179
+ function matchesTableSelector(schemaName, tableName, selector) {
10180
+ const separatorIndex = selector.indexOf(".");
10181
+ if (separatorIndex < 0) {
10182
+ return tableName === selector;
10183
+ }
10184
+ const selectorSchema = selector.slice(0, separatorIndex).trim();
10185
+ const selectorTable = selector.slice(separatorIndex + 1).trim();
10186
+ return selectorSchema === schemaName && selectorTable === tableName;
10187
+ }
10188
+ function shouldKeepTable(schemaName, tableName, filter) {
10189
+ const included = filter.includeTables.length === 0 || filter.includeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
10190
+ if (!included) {
10191
+ return false;
10192
+ }
10193
+ return !filter.excludeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
10194
+ }
10195
+ function hasTableFilters(filter) {
10196
+ return filter.includeTables.length > 0 || filter.excludeTables.length > 0;
10197
+ }
10198
+ function filterIntrospectionSnapshot(snapshot, filter) {
10199
+ if (!hasTableFilters(filter)) {
10200
+ return snapshot;
10201
+ }
10202
+ const schemas = {};
10203
+ for (const [schemaName, schema] of Object.entries(snapshot.schemas)) {
10204
+ const tables = Object.fromEntries(
10205
+ Object.entries(schema.tables).filter(([tableName]) => shouldKeepTable(schemaName, tableName, filter))
10206
+ );
10207
+ if (Object.keys(tables).length === 0) {
10208
+ continue;
10209
+ }
10210
+ schemas[schemaName] = {
10211
+ ...schema,
10212
+ tables
10213
+ };
10214
+ }
10215
+ if (Object.keys(schemas).length === 0) {
10216
+ const includeLabel = filter.includeTables.length > 0 ? ` includeTables=${filter.includeTables.join(", ")}` : "";
10217
+ const excludeLabel = filter.excludeTables.length > 0 ? ` excludeTables=${filter.excludeTables.join(", ")}` : "";
10218
+ throw new Error(
10219
+ `Generator table filters matched no tables after schema selection.${includeLabel}${excludeLabel}`
10220
+ );
10221
+ }
10222
+ return {
10223
+ ...snapshot,
10224
+ schemas
10225
+ };
10226
+ }
10227
+
8870
10228
  // src/generator/env.ts
8871
10229
  function readEnvStringValue(key) {
8872
10230
  if (typeof process === "undefined" || !process.env) {
@@ -9132,15 +10490,15 @@ function readCookieFromHeaders(headers, name) {
9132
10490
  }
9133
10491
  return parseCookies(cookieHeader).get(name);
9134
10492
  }
9135
- function isRecord11(value) {
10493
+ function isRecord12(value) {
9136
10494
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9137
10495
  }
9138
10496
  function resolveSessionCandidate(value) {
9139
- if (!isRecord11(value)) {
10497
+ if (!isRecord12(value)) {
9140
10498
  return null;
9141
10499
  }
9142
- const session = isRecord11(value.session) ? value.session : void 0;
9143
- 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;
9144
10502
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
9145
10503
  return {
9146
10504
  session,
@@ -9150,7 +10508,7 @@ function resolveSessionCandidate(value) {
9150
10508
  return null;
9151
10509
  }
9152
10510
  function inferSessionPair(returned) {
9153
- 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);
9154
10512
  }
9155
10513
  function resolveResponseHeaders(ctx) {
9156
10514
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -9173,23 +10531,23 @@ function normalizeBasePath(basePath) {
9173
10531
  function isDynamicBaseURLConfig2(baseURL) {
9174
10532
  return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
9175
10533
  }
9176
- function getRequestUrl(request) {
10534
+ function getRequestUrl(request2) {
9177
10535
  try {
9178
- return new URL(request.url);
10536
+ return new URL(request2.url);
9179
10537
  } catch {
9180
10538
  return new URL("http://localhost");
9181
10539
  }
9182
10540
  }
9183
- function getRequestHost(request, url) {
9184
- const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
9185
- 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;
9186
10544
  return host || null;
9187
10545
  }
9188
- function getRequestProtocol(request, configuredProtocol, url) {
10546
+ function getRequestProtocol(request2, configuredProtocol, url) {
9189
10547
  if (configuredProtocol === "http" || configuredProtocol === "https") {
9190
10548
  return configuredProtocol;
9191
10549
  }
9192
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
10550
+ const forwardedProto = request2.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
9193
10551
  if (forwardedProto === "http" || forwardedProto === "https") {
9194
10552
  return forwardedProto;
9195
10553
  }
@@ -9198,12 +10556,12 @@ function getRequestProtocol(request, configuredProtocol, url) {
9198
10556
  }
9199
10557
  return "http";
9200
10558
  }
9201
- function resolveRequestBaseURL(baseURL, request) {
10559
+ function resolveRequestBaseURL(baseURL, request2) {
9202
10560
  if (typeof baseURL === "string") {
9203
10561
  return normalizeBaseURL(baseURL);
9204
10562
  }
9205
- const requestUrl = getRequestUrl(request);
9206
- const host = getRequestHost(request, requestUrl);
10563
+ const requestUrl = getRequestUrl(request2);
10564
+ const host = getRequestHost(request2, requestUrl);
9207
10565
  if (!host) {
9208
10566
  return null;
9209
10567
  }
@@ -9213,7 +10571,7 @@ function resolveRequestBaseURL(baseURL, request) {
9213
10571
  return null;
9214
10572
  }
9215
10573
  }
9216
- 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);
9217
10575
  return `${protocol}://${host}`;
9218
10576
  }
9219
10577
  function getOrigin(baseURL) {
@@ -9226,16 +10584,16 @@ function getOrigin(baseURL) {
9226
10584
  return void 0;
9227
10585
  }
9228
10586
  }
9229
- async function resolveTrustedOrigins(config, baseURL, request) {
9230
- 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 ?? [];
9231
10589
  const values = [
9232
10590
  getOrigin(baseURL),
9233
10591
  ...resolved
9234
10592
  ];
9235
10593
  return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
9236
10594
  }
9237
- async function resolveTrustedProviders(config, request) {
9238
- 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 ?? [];
9239
10597
  const values = [
9240
10598
  ...Object.keys(config.socialProviders ?? {}),
9241
10599
  ...configured
@@ -9360,9 +10718,9 @@ function athenaAuth(config) {
9360
10718
  }
9361
10719
  return ctx;
9362
10720
  };
9363
- const resolveRequestContext = async (request) => {
9364
- const requestUrl = getRequestUrl(request);
9365
- const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request);
10721
+ const resolveRequestContext = async (request2) => {
10722
+ const requestUrl = getRequestUrl(request2);
10723
+ const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request2);
9366
10724
  if (!resolvedBaseURL) {
9367
10725
  throw new Error(
9368
10726
  isDynamicBaseURLConfig2(config.baseURL) ? "Could not resolve base URL from request. Check allowedHosts/baseURL." : "Could not resolve base URL from request."
@@ -9373,17 +10731,17 @@ function athenaAuth(config) {
9373
10731
  session: config.session,
9374
10732
  advanced: config.advanced
9375
10733
  });
9376
- const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request);
9377
- const trustedProviders = await resolveTrustedProviders(config, request);
10734
+ const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request2);
10735
+ const trustedProviders = await resolveTrustedProviders(config, request2);
9378
10736
  return {
9379
10737
  auth,
9380
- request,
10738
+ request: request2,
9381
10739
  url: requestUrl,
9382
10740
  path: requestUrl.pathname,
9383
10741
  basePath: normalizedBasePath,
9384
10742
  baseURL: resolvedBaseURL,
9385
10743
  origin: getOrigin(resolvedBaseURL) ?? resolvedBaseURL,
9386
- headers: request.headers,
10744
+ headers: request2.headers,
9387
10745
  cookies: requestCookies,
9388
10746
  trustedOrigins,
9389
10747
  trustedProviders,
@@ -9396,8 +10754,8 @@ function athenaAuth(config) {
9396
10754
  socialProviders: auth.socialProviders
9397
10755
  };
9398
10756
  };
9399
- const handler = async (request) => {
9400
- const requestContext = await resolveRequestContext(request);
10757
+ const handler = async (request2) => {
10758
+ const requestContext = await resolveRequestContext(request2);
9401
10759
  if (typeof config.handler !== "function") {
9402
10760
  return createJsonResponse(
9403
10761
  {
@@ -9418,7 +10776,7 @@ function athenaAuth(config) {
9418
10776
  const responseHeaders = new Headers(response.headers);
9419
10777
  await runAfterHooks({
9420
10778
  path: requestContext.path,
9421
- headers: request.headers,
10779
+ headers: request2.headers,
9422
10780
  context: {
9423
10781
  responseHeaders,
9424
10782
  returned: result.returned,
@@ -9525,7 +10883,13 @@ async function runSchemaGenerator(options = {}) {
9525
10883
  return throwBrowserUnsupported("runSchemaGenerator");
9526
10884
  }
9527
10885
 
10886
+ exports.ATHENA_AUTH_ADMIN_LIMITS = ATHENA_AUTH_ADMIN_LIMITS;
9528
10887
  exports.ATHENA_AUTH_BASE_ERROR_CODES = ATHENA_AUTH_BASE_ERROR_CODES;
10888
+ exports.ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = ATHENA_AUTH_MAX_ADMIN_JSON_BYTES;
10889
+ exports.ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH;
10890
+ exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = ATHENA_AUTH_MAX_TEMPLATE_VARIABLES;
10891
+ exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH;
10892
+ exports.AthenaChatError = AthenaChatError;
9529
10893
  exports.AthenaClient = AthenaClient;
9530
10894
  exports.AthenaError = AthenaError;
9531
10895
  exports.AthenaErrorCategory = AthenaErrorCategory;
@@ -9539,6 +10903,7 @@ exports.DEFAULT_POSTGRES_SCHEMAS = DEFAULT_POSTGRES_SCHEMAS;
9539
10903
  exports.assertInt = assertInt;
9540
10904
  exports.athenaAuth = athenaAuth;
9541
10905
  exports.boolean = boolean;
10906
+ exports.chatSdkManifest = chatSdkManifest;
9542
10907
  exports.coerceInt = coerceInt;
9543
10908
  exports.createAthenaStorageError = createAthenaStorageError;
9544
10909
  exports.createAuthClient = createAuthClient;
@@ -9555,6 +10920,7 @@ exports.defineModel = defineModel;
9555
10920
  exports.defineRegistry = defineRegistry;
9556
10921
  exports.defineSchema = defineSchema;
9557
10922
  exports.enumeration = enumeration;
10923
+ exports.filterIntrospectionSnapshot = filterIntrospectionSnapshot;
9558
10924
  exports.findGeneratorConfigPath = findGeneratorConfigPath;
9559
10925
  exports.generateArtifactsFromSnapshot = generateArtifactsFromSnapshot;
9560
10926
  exports.generatorEnv = generatorEnv;
@@ -9568,6 +10934,7 @@ exports.normalizeAthenaError = normalizeAthenaError;
9568
10934
  exports.normalizeAthenaGatewayBaseUrl = normalizeAthenaGatewayBaseUrl;
9569
10935
  exports.normalizeGeneratorConfig = normalizeGeneratorConfig;
9570
10936
  exports.normalizeSchemaSelection = normalizeSchemaSelection;
10937
+ exports.normalizeTableSelection = normalizeTableSelection;
9571
10938
  exports.number = number;
9572
10939
  exports.parseBooleanFlag = parseBooleanFlag2;
9573
10940
  exports.renderAthenaReactEmail = renderAthenaReactEmail;
@@ -9583,6 +10950,8 @@ exports.table = table;
9583
10950
  exports.toModelFormDefaults = toModelFormDefaults;
9584
10951
  exports.toModelPayload = toModelPayload;
9585
10952
  exports.unwrap = unwrap;
10953
+ exports.unwrapChatMessage = unwrapChatMessage;
10954
+ exports.unwrapChatRoom = unwrapChatRoom;
9586
10955
  exports.unwrapOne = unwrapOne;
9587
10956
  exports.unwrapRows = unwrapRows;
9588
10957
  exports.verifyAthenaGatewayUrl = verifyAthenaGatewayUrl;