@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/index.cjs CHANGED
@@ -666,8 +666,8 @@ function deleteSessionCookie(ctx, skipDontRememberMe) {
666
666
  expireCookie(ctx, ctx.context.authCookies.dontRememberToken);
667
667
  }
668
668
  }
669
- var getSessionCookie = (request, config) => {
670
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
669
+ var getSessionCookie = (request2, config) => {
670
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
671
671
  if (!cookies) {
672
672
  return null;
673
673
  }
@@ -687,8 +687,8 @@ var getSessionCookie = (request, config) => {
687
687
  }
688
688
  return null;
689
689
  };
690
- var getCookieCache = async (request, config) => {
691
- const headers = request instanceof Headers || !("headers" in request) ? request : request.headers;
690
+ var getCookieCache = async (request2, config) => {
691
+ const headers = request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers;
692
692
  const cookieHeader = headers.get("cookie");
693
693
  if (!cookieHeader) {
694
694
  return null;
@@ -806,7 +806,7 @@ var getCookieCache = async (request, config) => {
806
806
 
807
807
  // package.json
808
808
  var package_default = {
809
- version: "2.8.2"
809
+ version: "2.10.0"
810
810
  };
811
811
 
812
812
  // src/sdk-version.ts
@@ -819,6 +819,7 @@ function buildSdkHeaderValue(sdkName) {
819
819
  var DEFAULT_CLIENT = "railway_direct";
820
820
  var SDK_NAME = "xylex-group/athena";
821
821
  var SDK_HEADER_VALUE = buildSdkHeaderValue(SDK_NAME);
822
+ var NO_CACHE_HEADER_VALUE = "no-cache";
822
823
  function parseResponseBody(rawText, contentType) {
823
824
  if (!rawText) {
824
825
  return { parsed: null, parseFailed: false };
@@ -837,6 +838,9 @@ function parseResponseBody(rawText, contentType) {
837
838
  function normalizeHeaderValue(value) {
838
839
  return value ? value : void 0;
839
840
  }
841
+ function isCacheControlHeaderName(name) {
842
+ return name.toLowerCase() === "cache-control";
843
+ }
840
844
  function resolveHeaderValue(headers, candidates) {
841
845
  for (const candidate of candidates) {
842
846
  const direct = normalizeHeaderValue(headers[candidate]);
@@ -995,6 +999,7 @@ function buildRpcGetEndpoint(payload) {
995
999
  }
996
1000
  function buildHeaders(config, options) {
997
1001
  const mergedStripNulls = options?.stripNulls ?? true;
1002
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
998
1003
  const extraHeaders = {
999
1004
  ...config.headers ?? {},
1000
1005
  ...options?.headers ?? {}
@@ -1048,11 +1053,15 @@ function buildHeaders(config, options) {
1048
1053
  const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
1049
1054
  Object.entries(extraHeaders).forEach(([key, value]) => {
1050
1055
  if (athenaClientKeys.includes(key)) return;
1056
+ if (forceNoCache && isCacheControlHeaderName(key)) return;
1051
1057
  const normalized = normalizeHeaderValue(value);
1052
1058
  if (normalized) {
1053
1059
  headers[key] = normalized;
1054
1060
  }
1055
1061
  });
1062
+ if (forceNoCache) {
1063
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE;
1064
+ }
1056
1065
  return headers;
1057
1066
  }
1058
1067
  function toInvalidUrlResponse(error, endpoint, method) {
@@ -1513,6 +1522,45 @@ function identifier(...segments) {
1513
1522
  return new SqlIdentifierPath(expandedSegments);
1514
1523
  }
1515
1524
 
1525
+ // src/auth/limits.ts
1526
+ var ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = 32 * 1024;
1527
+ var ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = 8;
1528
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = 64;
1529
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = 128;
1530
+ var ATHENA_AUTH_ADMIN_LIMITS = {
1531
+ maxAdminJsonBytes: ATHENA_AUTH_MAX_ADMIN_JSON_BYTES,
1532
+ maxAdminJsonDepth: ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH,
1533
+ maxTemplateVariables: ATHENA_AUTH_MAX_TEMPLATE_VARIABLES,
1534
+ maxTemplateVariableLength: ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH
1535
+ };
1536
+ function describeTemplateVariableTarget(target) {
1537
+ const normalized = target?.trim();
1538
+ return normalized && normalized.length > 0 ? normalized : "Athena auth admin email template variables";
1539
+ }
1540
+ function assertAthenaAuthTemplateVariables(variables, target) {
1541
+ const label = describeTemplateVariableTarget(target);
1542
+ if (!Array.isArray(variables)) {
1543
+ throw new Error(`${label} must be an array of strings.`);
1544
+ }
1545
+ if (variables.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLES) {
1546
+ throw new Error(
1547
+ `${label} cannot contain more than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLES} entries.`
1548
+ );
1549
+ }
1550
+ variables.forEach((variable, index) => {
1551
+ if (typeof variable !== "string") {
1552
+ throw new Error(
1553
+ `${label} must contain only strings. Received ${typeof variable} at index ${index}.`
1554
+ );
1555
+ }
1556
+ if (variable.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH) {
1557
+ throw new Error(
1558
+ `${label} cannot contain entries longer than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH} characters. Received ${variable.length} characters at index ${index}.`
1559
+ );
1560
+ }
1561
+ });
1562
+ }
1563
+
1516
1564
  // src/auth/react-email.ts
1517
1565
  var reactEmailRenderModulePromise;
1518
1566
  function isRecord2(value) {
@@ -1742,6 +1790,7 @@ async function resolveReactEmailPayloadFields(input, fields, options) {
1742
1790
  var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
1743
1791
  var SDK_NAME2 = "xylex-group/athena-auth";
1744
1792
  var SDK_HEADER_VALUE2 = buildSdkHeaderValue(SDK_NAME2);
1793
+ var NO_CACHE_HEADER_VALUE2 = "no-cache";
1745
1794
  function normalizeBaseUrl(baseUrl) {
1746
1795
  return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
1747
1796
  }
@@ -1751,6 +1800,9 @@ function isRecord3(value) {
1751
1800
  function normalizeHeaderValue2(value) {
1752
1801
  return value ? value : void 0;
1753
1802
  }
1803
+ function isCacheControlHeaderName2(name) {
1804
+ return name.toLowerCase() === "cache-control";
1805
+ }
1754
1806
  function parseResponseBody2(rawText, contentType) {
1755
1807
  if (!rawText) {
1756
1808
  return { parsed: null, parseFailed: false };
@@ -1806,6 +1858,98 @@ function mergeCallOptions(base, override) {
1806
1858
  }
1807
1859
  };
1808
1860
  }
1861
+ function copyDefinedField(target, source, targetKey, sourceKey) {
1862
+ if (!(sourceKey in source)) {
1863
+ return;
1864
+ }
1865
+ const value = source[sourceKey];
1866
+ if (value !== void 0) {
1867
+ target[targetKey] = value;
1868
+ }
1869
+ }
1870
+ function normalizeAdminEmailTemplatePayload(payload) {
1871
+ const normalized = { ...payload };
1872
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
1873
+ copyDefinedField(normalized, payload, "event_type", "eventType");
1874
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
1875
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
1876
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
1877
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
1878
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
1879
+ copyDefinedField(normalized, payload, "is_active", "isActive");
1880
+ return normalized;
1881
+ }
1882
+ function toReactEmailTemplateCompatibilityInput(input) {
1883
+ const payload = input;
1884
+ const compatibility = { ...payload };
1885
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
1886
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
1887
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
1888
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
1889
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
1890
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
1891
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
1892
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
1893
+ return compatibility;
1894
+ }
1895
+ function normalizeAdminEmailTemplateSendPayload(payload) {
1896
+ const normalized = { ...payload };
1897
+ copyDefinedField(normalized, payload, "template_id", "templateId");
1898
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
1899
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
1900
+ copyDefinedField(normalized, payload, "user_id", "userId");
1901
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
1902
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
1903
+ return normalized;
1904
+ }
1905
+ function toSessionGuardFailure(sessionResult) {
1906
+ if (sessionResult.status === 401 || sessionResult.data == null) {
1907
+ return {
1908
+ ok: false,
1909
+ reason: "unauthorized",
1910
+ status: 401,
1911
+ error: sessionResult.error ?? "Unauthorized",
1912
+ sessionResult
1913
+ };
1914
+ }
1915
+ return {
1916
+ ok: false,
1917
+ reason: "upstream_error",
1918
+ status: sessionResult.status,
1919
+ error: sessionResult.error ?? "Failed to resolve current session",
1920
+ sessionResult
1921
+ };
1922
+ }
1923
+ function toPermissionGuardFailure(permissionResult, sessionResult) {
1924
+ if (permissionResult.status === 401) {
1925
+ return {
1926
+ ok: false,
1927
+ reason: "unauthorized",
1928
+ status: 401,
1929
+ error: permissionResult.error ?? "Unauthorized",
1930
+ sessionResult,
1931
+ permissionResult
1932
+ };
1933
+ }
1934
+ if (permissionResult.status === 403) {
1935
+ return {
1936
+ ok: false,
1937
+ reason: "forbidden",
1938
+ status: 403,
1939
+ error: permissionResult.error ?? "Forbidden",
1940
+ sessionResult,
1941
+ permissionResult
1942
+ };
1943
+ }
1944
+ return {
1945
+ ok: false,
1946
+ reason: "upstream_error",
1947
+ status: permissionResult.status,
1948
+ error: permissionResult.error ?? "Failed to resolve permission check",
1949
+ sessionResult,
1950
+ permissionResult
1951
+ };
1952
+ }
1809
1953
  function extractFetchOptions(input) {
1810
1954
  if (!input) {
1811
1955
  return {
@@ -1821,6 +1965,7 @@ function extractFetchOptions(input) {
1821
1965
  };
1822
1966
  }
1823
1967
  function buildHeaders2(config, options) {
1968
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
1824
1969
  const headers = {
1825
1970
  "Content-Type": "application/json",
1826
1971
  "X-Athena-Sdk": SDK_HEADER_VALUE2
@@ -1834,16 +1979,30 @@ function buildHeaders2(config, options) {
1834
1979
  if (bearerToken) {
1835
1980
  headers.Authorization = `Bearer ${bearerToken}`;
1836
1981
  }
1982
+ const cookie = options?.cookie ?? config.cookie;
1983
+ if (cookie) {
1984
+ headers.Cookie = cookie;
1985
+ }
1986
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
1987
+ if (sessionToken) {
1988
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
1989
+ }
1837
1990
  const mergedExtraHeaders = {
1838
1991
  ...config.headers ?? {},
1839
1992
  ...options?.headers ?? {}
1840
1993
  };
1841
1994
  Object.entries(mergedExtraHeaders).forEach(([key, value]) => {
1995
+ if (forceNoCache && isCacheControlHeaderName2(key)) {
1996
+ return;
1997
+ }
1842
1998
  const normalized = normalizeHeaderValue2(value);
1843
1999
  if (normalized) {
1844
2000
  headers[key] = normalized;
1845
2001
  }
1846
2002
  });
2003
+ if (forceNoCache) {
2004
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE2;
2005
+ }
1847
2006
  return headers;
1848
2007
  }
1849
2008
  function appendQueryParam(searchParams, key, value) {
@@ -2049,7 +2208,7 @@ function createAuthClient(config = {}) {
2049
2208
  ...config,
2050
2209
  baseUrl: normalizedBaseUrl
2051
2210
  };
2052
- const request = (input, options) => {
2211
+ const request2 = (input, options) => {
2053
2212
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
2054
2213
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
2055
2214
  return callAuthEndpoint(
@@ -2062,7 +2221,7 @@ function createAuthClient(config = {}) {
2062
2221
  };
2063
2222
  const postGeneric = (endpoint, input, options) => {
2064
2223
  const { payload, fetchOptions } = extractFetchOptions(input);
2065
- return request(
2224
+ return request2(
2066
2225
  {
2067
2226
  endpoint,
2068
2227
  method: "POST",
@@ -2074,7 +2233,7 @@ function createAuthClient(config = {}) {
2074
2233
  };
2075
2234
  const getGeneric = (endpoint, input, options) => {
2076
2235
  const { fetchOptions } = extractFetchOptions(input);
2077
- return request(
2236
+ return request2(
2078
2237
  {
2079
2238
  endpoint,
2080
2239
  method: "GET",
@@ -2086,7 +2245,7 @@ function createAuthClient(config = {}) {
2086
2245
  const getWithQuery = (endpoint, input, options) => {
2087
2246
  const { payload, fetchOptions } = extractFetchOptions(input);
2088
2247
  const query = payload?.query;
2089
- return request(
2248
+ return request2(
2090
2249
  {
2091
2250
  endpoint,
2092
2251
  method: "GET",
@@ -2104,11 +2263,96 @@ function createAuthClient(config = {}) {
2104
2263
  htmlField: "htmlBody",
2105
2264
  textField: "textBody"
2106
2265
  }, withReactEmailRoute(route));
2107
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
2266
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
2108
2267
  htmlField: "htmlTemplate",
2109
2268
  textField: "textTemplate",
2110
2269
  variablesField: "variables"
2111
- }, withReactEmailRoute(route));
2270
+ }, withReactEmailRoute(route)).then((payload) => {
2271
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
2272
+ if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
2273
+ assertAthenaAuthTemplateVariables(
2274
+ payload.variables,
2275
+ `${route} variables`
2276
+ );
2277
+ }
2278
+ return normalizedPayload;
2279
+ });
2280
+ const requireSession = async (input, options) => {
2281
+ const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
2282
+ const sessionResult = await getGeneric(
2283
+ "/get-session",
2284
+ sessionInput,
2285
+ options
2286
+ );
2287
+ if (!sessionResult.ok || sessionResult.data == null) {
2288
+ return toSessionGuardFailure(sessionResult);
2289
+ }
2290
+ return {
2291
+ ok: true,
2292
+ session: sessionResult.data
2293
+ };
2294
+ };
2295
+ const getUser = async (input, options) => {
2296
+ const sessionResult = await getGeneric(
2297
+ "/get-session",
2298
+ input,
2299
+ options
2300
+ );
2301
+ if (!sessionResult.ok) {
2302
+ return {
2303
+ ...sessionResult,
2304
+ data: null
2305
+ };
2306
+ }
2307
+ return {
2308
+ ...sessionResult,
2309
+ data: {
2310
+ user: sessionResult.data?.user ?? null
2311
+ }
2312
+ };
2313
+ };
2314
+ const requirePermission = async (endpoint, input, options) => {
2315
+ const sessionGuard = await requireSession(
2316
+ input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0,
2317
+ options
2318
+ );
2319
+ if (!sessionGuard.ok) {
2320
+ return sessionGuard;
2321
+ }
2322
+ const permissionResult = await postGeneric(
2323
+ endpoint,
2324
+ input,
2325
+ options
2326
+ );
2327
+ if (!permissionResult.ok) {
2328
+ return toPermissionGuardFailure(permissionResult, {
2329
+ ok: true,
2330
+ status: 200,
2331
+ data: sessionGuard.session,
2332
+ error: null,
2333
+ errorDetails: null,
2334
+ raw: sessionGuard.session
2335
+ });
2336
+ }
2337
+ if (!permissionResult.data?.success) {
2338
+ return {
2339
+ ok: false,
2340
+ reason: "forbidden",
2341
+ status: 403,
2342
+ error: permissionResult.data?.error ?? "Forbidden",
2343
+ sessionResult: {
2344
+ ok: true,
2345
+ status: 200,
2346
+ data: sessionGuard.session,
2347
+ error: null,
2348
+ errorDetails: null,
2349
+ raw: sessionGuard.session
2350
+ },
2351
+ permissionResult
2352
+ };
2353
+ }
2354
+ return sessionGuard;
2355
+ };
2112
2356
  const listUserEmailsWithFallback = async (input, options) => {
2113
2357
  const primary = await getWithQuery(
2114
2358
  "/email/list",
@@ -2270,6 +2514,7 @@ function createAuthClient(config = {}) {
2270
2514
  input,
2271
2515
  options
2272
2516
  ),
2517
+ requirePermission: (input, options) => requirePermission("/organization/has-permission", input, options),
2273
2518
  invitation: {
2274
2519
  cancel: (input, options) => executePostWithCompatibleInput(
2275
2520
  resolvedConfig,
@@ -2465,6 +2710,8 @@ function createAuthClient(config = {}) {
2465
2710
  };
2466
2711
  const auth = {
2467
2712
  getSession: (input, options) => getGeneric("/get-session", input, options),
2713
+ getUser,
2714
+ requireSession,
2468
2715
  signOut,
2469
2716
  forgetPassword: (input, options) => postGeneric("/forget-password", input, options),
2470
2717
  resetPassword: authResetPassword,
@@ -2559,6 +2806,7 @@ function createAuthClient(config = {}) {
2559
2806
  }
2560
2807
  },
2561
2808
  hasPermission: (input, options) => postGeneric("/admin/has-permission", input, options),
2809
+ requirePermission: (input, options) => requirePermission("/admin/has-permission", input, options),
2562
2810
  apiKey: {
2563
2811
  create: (input, options) => postGeneric("/admin/api-key/create", input, options)
2564
2812
  },
@@ -2603,7 +2851,15 @@ function createAuthClient(config = {}) {
2603
2851
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2604
2852
  options
2605
2853
  ),
2606
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
2854
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
2855
+ send: (input, options) => postGeneric(
2856
+ "/admin/email-template/send",
2857
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2858
+ options
2859
+ )
2860
+ },
2861
+ eventType: {
2862
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2607
2863
  }
2608
2864
  },
2609
2865
  emailTemplate: {
@@ -2619,7 +2875,15 @@ function createAuthClient(config = {}) {
2619
2875
  "/admin/email-template/update",
2620
2876
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
2621
2877
  options
2878
+ ),
2879
+ send: (input, options) => postGeneric(
2880
+ "/admin/email-template/send",
2881
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
2882
+ options
2622
2883
  )
2884
+ },
2885
+ emailEventType: {
2886
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
2623
2887
  }
2624
2888
  },
2625
2889
  apiKey: {
@@ -2659,7 +2923,7 @@ function createAuthClient(config = {}) {
2659
2923
  throw new Error("callback.provider requires non-empty code and state values");
2660
2924
  }
2661
2925
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
2662
- return request({
2926
+ return request2({
2663
2927
  endpoint,
2664
2928
  method: "GET",
2665
2929
  query: {
@@ -2673,7 +2937,7 @@ function createAuthClient(config = {}) {
2673
2937
  };
2674
2938
  return {
2675
2939
  baseUrl: normalizedBaseUrl,
2676
- request,
2940
+ request: request2,
2677
2941
  signIn: {
2678
2942
  email: (input, options) => executePostWithCompatibleInput(
2679
2943
  resolvedConfig,
@@ -2710,6 +2974,8 @@ function createAuthClient(config = {}) {
2710
2974
  input,
2711
2975
  options
2712
2976
  ),
2977
+ getUser,
2978
+ requireSession,
2713
2979
  listSessions: (input, options) => executeGetWithCompatibleInput(
2714
2980
  resolvedConfig,
2715
2981
  { endpoint: "/list-sessions", method: "GET" },
@@ -3412,16 +3678,16 @@ function createStorageFileModule(base, config = {}) {
3412
3678
  };
3413
3679
  });
3414
3680
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3415
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
3681
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
3416
3682
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3417
3683
  const uploaded = [];
3418
3684
  for (let index = 0; index < uploadRequests.length; index += 1) {
3419
- const request = uploadRequests[index];
3685
+ const request2 = uploadRequests[index];
3420
3686
  const uploadUrl = uploadUrls[index];
3421
3687
  const response = await putUploadBody(
3422
3688
  uploadUrl.upload.url,
3423
3689
  uploadUrl.upload.headers ?? {},
3424
- request.source,
3690
+ request2.source,
3425
3691
  input,
3426
3692
  options,
3427
3693
  (progress) => {
@@ -3432,13 +3698,13 @@ function createStorageFileModule(base, config = {}) {
3432
3698
  uploaded.push({
3433
3699
  file: uploadUrl.file,
3434
3700
  upload: uploadUrl.upload,
3435
- source: request.source.source,
3436
- fileName: request.source.fileName,
3437
- storage_key: request.uploadRequest.storage_key,
3701
+ source: request2.source.source,
3702
+ fileName: request2.source.fileName,
3703
+ storage_key: request2.uploadRequest.storage_key,
3438
3704
  response
3439
3705
  });
3440
- aggregateLoaded[index] = request.source.sizeBytes;
3441
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
3706
+ aggregateLoaded[index] = request2.source.sizeBytes;
3707
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
3442
3708
  }
3443
3709
  return {
3444
3710
  files: uploaded,
@@ -5413,6 +5679,517 @@ function createStorageModule(gateway, runtimeOptions) {
5413
5679
  };
5414
5680
  }
5415
5681
 
5682
+ // src/chat/module.ts
5683
+ var SDK_NAME3 = "xylex-group/athena-chat";
5684
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
5685
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
5686
+ var AthenaChatError = class extends Error {
5687
+ status;
5688
+ endpoint;
5689
+ method;
5690
+ requestId;
5691
+ body;
5692
+ constructor(input) {
5693
+ super(input.message);
5694
+ this.name = "AthenaChatError";
5695
+ this.status = input.status;
5696
+ this.endpoint = input.endpoint;
5697
+ this.method = input.method;
5698
+ this.requestId = input.requestId;
5699
+ this.body = input.body;
5700
+ }
5701
+ };
5702
+ function deriveRealtimeInfoUrl(wsUrl) {
5703
+ if (!wsUrl) {
5704
+ return void 0;
5705
+ }
5706
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
5707
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
5708
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
5709
+ return parsed.toString();
5710
+ }
5711
+ function normalizeWsUrl(value, label) {
5712
+ const normalized = value.trim();
5713
+ if (!normalized) {
5714
+ throw new Error(`${label} is required.`);
5715
+ }
5716
+ let parsed;
5717
+ try {
5718
+ parsed = new URL(normalized);
5719
+ } catch {
5720
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
5721
+ }
5722
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
5723
+ throw new Error(`${label} must use ws or wss.`);
5724
+ }
5725
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
5726
+ return parsed.toString().replace(/\/$/, "");
5727
+ }
5728
+ function isRecord7(value) {
5729
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5730
+ }
5731
+ function normalizeHeaderValue3(value) {
5732
+ return value ? value : void 0;
5733
+ }
5734
+ function parseResponseBody4(rawText, contentType) {
5735
+ if (!rawText) {
5736
+ return { parsed: null, parseFailed: false };
5737
+ }
5738
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
5739
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
5740
+ if (!looksJson) {
5741
+ return { parsed: rawText, parseFailed: false };
5742
+ }
5743
+ try {
5744
+ return { parsed: JSON.parse(rawText), parseFailed: false };
5745
+ } catch {
5746
+ return { parsed: rawText, parseFailed: true };
5747
+ }
5748
+ }
5749
+ function resolveRequestId3(headers) {
5750
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
5751
+ }
5752
+ function resolveErrorMessage4(payload, fallback) {
5753
+ if (isRecord7(payload)) {
5754
+ for (const candidate of [payload.error, payload.message, payload.details]) {
5755
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
5756
+ return candidate.trim();
5757
+ }
5758
+ }
5759
+ }
5760
+ if (typeof payload === "string" && payload.trim().length > 0) {
5761
+ return payload.trim();
5762
+ }
5763
+ return fallback;
5764
+ }
5765
+ function encodePathSegment(value, label) {
5766
+ const normalized = value.trim();
5767
+ if (!normalized) {
5768
+ throw new Error(`${label} is required.`);
5769
+ }
5770
+ return encodeURIComponent(normalized);
5771
+ }
5772
+ function encodeQuery(query) {
5773
+ if (!query) {
5774
+ return "";
5775
+ }
5776
+ const params = new URLSearchParams();
5777
+ for (const [key, value] of Object.entries(query)) {
5778
+ if (value === void 0 || value === null) {
5779
+ continue;
5780
+ }
5781
+ if (Array.isArray(value)) {
5782
+ for (const item of value) {
5783
+ if (item !== void 0 && item !== null) {
5784
+ params.append(key, String(item));
5785
+ }
5786
+ }
5787
+ continue;
5788
+ }
5789
+ params.set(key, String(value));
5790
+ }
5791
+ const encoded = params.toString();
5792
+ return encoded ? `?${encoded}` : "";
5793
+ }
5794
+ function createSocket(factory, url, protocols) {
5795
+ try {
5796
+ return new factory(url, protocols);
5797
+ } catch (error) {
5798
+ if (error instanceof TypeError) {
5799
+ return factory(url, protocols);
5800
+ }
5801
+ throw error;
5802
+ }
5803
+ }
5804
+ function buildHeaders3(config, options) {
5805
+ const headers = {
5806
+ Accept: "application/json",
5807
+ apikey: config.apiKey,
5808
+ "x-api-key": config.apiKey,
5809
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
5810
+ };
5811
+ if (config.client || options?.client) {
5812
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
5813
+ }
5814
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
5815
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
5816
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
5817
+ }
5818
+ const cookie = options?.cookie ?? config.cookie;
5819
+ if (typeof cookie === "string" && cookie.trim()) {
5820
+ headers.Cookie = cookie;
5821
+ }
5822
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
5823
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
5824
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
5825
+ }
5826
+ if (config.forceNoCache || options?.forceNoCache) {
5827
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
5828
+ }
5829
+ for (const source of [config.headers, options?.headers]) {
5830
+ for (const [key, value] of Object.entries(source ?? {})) {
5831
+ const normalized = normalizeHeaderValue3(value);
5832
+ if (normalized) {
5833
+ headers[key] = normalized;
5834
+ }
5835
+ }
5836
+ }
5837
+ return headers;
5838
+ }
5839
+ function withJsonBody(init, body) {
5840
+ return {
5841
+ ...init,
5842
+ body: body === void 0 ? void 0 : JSON.stringify(body),
5843
+ headers: {
5844
+ "Content-Type": "application/json",
5845
+ ...init.headers
5846
+ }
5847
+ };
5848
+ }
5849
+ async function request(config, method, endpoint, options, body) {
5850
+ if (!config.baseUrl) {
5851
+ throw new Error(
5852
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
5853
+ );
5854
+ }
5855
+ const url = `${config.baseUrl}${endpoint}`;
5856
+ const init = {
5857
+ method,
5858
+ headers: buildHeaders3(config, options),
5859
+ signal: options?.signal
5860
+ };
5861
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
5862
+ const response = await fetch(url, finalInit);
5863
+ const rawText = await response.text();
5864
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
5865
+ if (!response.ok) {
5866
+ throw new AthenaChatError({
5867
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
5868
+ status: response.status,
5869
+ endpoint,
5870
+ method,
5871
+ requestId: resolveRequestId3(response.headers),
5872
+ body: parsed
5873
+ });
5874
+ }
5875
+ return parsed;
5876
+ }
5877
+ function unwrapEnvelopeData(payload) {
5878
+ return payload.data;
5879
+ }
5880
+ function createRealtimeConnection(config, options) {
5881
+ if (!config.wsUrl) {
5882
+ throw new Error(
5883
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
5884
+ );
5885
+ }
5886
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
5887
+ if (!wsFactory) {
5888
+ throw new Error(
5889
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
5890
+ );
5891
+ }
5892
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
5893
+ const send = (command) => {
5894
+ socket.send(JSON.stringify(command));
5895
+ };
5896
+ if (options?.onMessage) {
5897
+ const listener = (event) => {
5898
+ const messageEvent = event;
5899
+ const raw = messageEvent?.data;
5900
+ if (typeof raw !== "string") {
5901
+ return;
5902
+ }
5903
+ try {
5904
+ options.onMessage?.(JSON.parse(raw));
5905
+ } catch {
5906
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
5907
+ }
5908
+ };
5909
+ if (typeof socket.addEventListener === "function") {
5910
+ socket.addEventListener("message", listener);
5911
+ } else {
5912
+ socket.onmessage = listener;
5913
+ }
5914
+ }
5915
+ const hello = (command) => {
5916
+ send({
5917
+ type: "auth.hello",
5918
+ token: command?.token,
5919
+ room_subscriptions: command?.room_subscriptions
5920
+ });
5921
+ };
5922
+ if (options?.hello) {
5923
+ const onOpen = () => hello({
5924
+ token: options.hello?.token ?? void 0,
5925
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
5926
+ });
5927
+ if (typeof socket.addEventListener === "function") {
5928
+ socket.addEventListener("open", onOpen);
5929
+ } else {
5930
+ socket.onopen = onOpen;
5931
+ }
5932
+ }
5933
+ return {
5934
+ socket,
5935
+ send,
5936
+ hello,
5937
+ subscribe(roomId, fromSeq) {
5938
+ send({
5939
+ type: "chat.subscribe",
5940
+ room_id: roomId,
5941
+ from_seq: fromSeq ?? void 0
5942
+ });
5943
+ },
5944
+ unsubscribe(roomId) {
5945
+ send({
5946
+ type: "chat.unsubscribe",
5947
+ room_id: roomId
5948
+ });
5949
+ },
5950
+ resume(rooms) {
5951
+ send({
5952
+ type: "chat.resume",
5953
+ rooms
5954
+ });
5955
+ },
5956
+ typingStart(roomId) {
5957
+ send({
5958
+ type: "chat.typing.start",
5959
+ room_id: roomId
5960
+ });
5961
+ },
5962
+ typingStop(roomId) {
5963
+ send({
5964
+ type: "chat.typing.stop",
5965
+ room_id: roomId
5966
+ });
5967
+ },
5968
+ presenceHeartbeat(activeRoomId) {
5969
+ send({
5970
+ type: "chat.presence.heartbeat",
5971
+ active_room_id: activeRoomId ?? void 0
5972
+ });
5973
+ },
5974
+ readUpTo(roomId, input) {
5975
+ send({
5976
+ type: "chat.read.up_to",
5977
+ room_id: roomId,
5978
+ message_id: input?.message_id ?? void 0,
5979
+ seq: input?.seq ?? void 0
5980
+ });
5981
+ },
5982
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
5983
+ send({
5984
+ type: "ping",
5985
+ at
5986
+ });
5987
+ },
5988
+ close(code, reason) {
5989
+ socket.close(code, reason);
5990
+ }
5991
+ };
5992
+ }
5993
+ function createChatModule(config) {
5994
+ const realtime = {
5995
+ info(options) {
5996
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
5997
+ if (!realtimeInfoUrl) {
5998
+ throw new Error(
5999
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
6000
+ );
6001
+ }
6002
+ return request(
6003
+ {
6004
+ ...config,
6005
+ baseUrl: realtimeInfoUrl
6006
+ },
6007
+ "GET",
6008
+ "",
6009
+ options
6010
+ );
6011
+ },
6012
+ connect(options) {
6013
+ return createRealtimeConnection(config, options);
6014
+ }
6015
+ };
6016
+ return {
6017
+ room: {
6018
+ list(query, options) {
6019
+ return request(
6020
+ config,
6021
+ "GET",
6022
+ `/rooms${encodeQuery(query)}`,
6023
+ options
6024
+ );
6025
+ },
6026
+ create(input, options) {
6027
+ return request(config, "POST", "/rooms", options, input);
6028
+ },
6029
+ get(roomId, options) {
6030
+ return request(
6031
+ config,
6032
+ "GET",
6033
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6034
+ options
6035
+ );
6036
+ },
6037
+ update(roomId, input, options) {
6038
+ return request(
6039
+ config,
6040
+ "PATCH",
6041
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6042
+ options,
6043
+ input
6044
+ );
6045
+ },
6046
+ archive(roomId, options) {
6047
+ return request(
6048
+ config,
6049
+ "POST",
6050
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
6051
+ options
6052
+ );
6053
+ },
6054
+ readCursor: {
6055
+ upTo(roomId, input, options) {
6056
+ return request(
6057
+ config,
6058
+ "POST",
6059
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
6060
+ options,
6061
+ input ?? {}
6062
+ );
6063
+ }
6064
+ },
6065
+ member: {
6066
+ list(roomId, options) {
6067
+ return request(
6068
+ config,
6069
+ "GET",
6070
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6071
+ options
6072
+ );
6073
+ },
6074
+ add(roomId, input, options) {
6075
+ return request(
6076
+ config,
6077
+ "POST",
6078
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6079
+ options,
6080
+ input
6081
+ );
6082
+ },
6083
+ remove(roomId, userId, options) {
6084
+ return request(
6085
+ config,
6086
+ "DELETE",
6087
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
6088
+ options
6089
+ );
6090
+ }
6091
+ },
6092
+ message: {
6093
+ list(roomId, query, options) {
6094
+ return request(
6095
+ config,
6096
+ "GET",
6097
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
6098
+ options
6099
+ );
6100
+ },
6101
+ send(roomId, input, options) {
6102
+ return request(
6103
+ config,
6104
+ "POST",
6105
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
6106
+ options,
6107
+ input
6108
+ );
6109
+ },
6110
+ update(roomId, messageId, input, options) {
6111
+ return request(
6112
+ config,
6113
+ "PATCH",
6114
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6115
+ options,
6116
+ input
6117
+ );
6118
+ },
6119
+ delete(roomId, messageId, options) {
6120
+ return request(
6121
+ config,
6122
+ "DELETE",
6123
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6124
+ options
6125
+ );
6126
+ }
6127
+ }
6128
+ },
6129
+ message: {
6130
+ reaction: {
6131
+ add(messageId, input, options) {
6132
+ return request(
6133
+ config,
6134
+ "POST",
6135
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
6136
+ options,
6137
+ input
6138
+ );
6139
+ },
6140
+ remove(messageId, emoji, options) {
6141
+ return request(
6142
+ config,
6143
+ "DELETE",
6144
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
6145
+ options
6146
+ );
6147
+ }
6148
+ },
6149
+ search(input, options) {
6150
+ return request(
6151
+ config,
6152
+ "POST",
6153
+ "/messages/search",
6154
+ options,
6155
+ input
6156
+ );
6157
+ }
6158
+ },
6159
+ realtime
6160
+ };
6161
+ }
6162
+ var chatSdkManifest = {
6163
+ namespace: "chat",
6164
+ basePath: "/chat",
6165
+ methods: [
6166
+ { name: "listRooms", method: "GET", path: "/chat/rooms" },
6167
+ { name: "createRoom", method: "POST", path: "/chat/rooms" },
6168
+ { name: "getRoom", method: "GET", path: "/chat/rooms/{room_id}" },
6169
+ { name: "updateRoom", method: "PATCH", path: "/chat/rooms/{room_id}" },
6170
+ { name: "archiveRoom", method: "POST", path: "/chat/rooms/{room_id}/archive" },
6171
+ { name: "listRoomMessages", method: "GET", path: "/chat/rooms/{room_id}/messages" },
6172
+ { name: "sendRoomMessage", method: "POST", path: "/chat/rooms/{room_id}/messages" },
6173
+ { name: "updateRoomMessage", method: "PATCH", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6174
+ { name: "deleteRoomMessage", method: "DELETE", path: "/chat/rooms/{room_id}/messages/{message_id}" },
6175
+ { name: "advanceReadCursor", method: "POST", path: "/chat/rooms/{room_id}/read-cursor" },
6176
+ { name: "listRoomMembers", method: "GET", path: "/chat/rooms/{room_id}/members" },
6177
+ { name: "addRoomMembers", method: "POST", path: "/chat/rooms/{room_id}/members" },
6178
+ { name: "removeRoomMember", method: "DELETE", path: "/chat/rooms/{room_id}/members/{user_id}" },
6179
+ { name: "addReaction", method: "POST", path: "/chat/messages/{message_id}/reactions" },
6180
+ { name: "removeReaction", method: "DELETE", path: "/chat/messages/{message_id}/reactions/{emoji}" },
6181
+ { name: "searchMessages", method: "POST", path: "/chat/messages/search" },
6182
+ { name: "getRealtimeInfo", method: "GET", path: "/wss/info" },
6183
+ { name: "connectRealtime", method: "GET", path: "/wss/gateway" }
6184
+ ]
6185
+ };
6186
+ function unwrapChatRoom(payload) {
6187
+ return unwrapEnvelopeData(payload);
6188
+ }
6189
+ function unwrapChatMessage(payload) {
6190
+ return unwrapEnvelopeData(payload);
6191
+ }
6192
+
5416
6193
  // src/client-builder.ts
5417
6194
  var DEFAULT_BACKEND = { type: "athena" };
5418
6195
  function toBackendConfig(value) {
@@ -5465,6 +6242,9 @@ var AthenaClientBuilderImpl = class {
5465
6242
  apiKey;
5466
6243
  backendConfig = DEFAULT_BACKEND;
5467
6244
  clientName;
6245
+ defaultUserId;
6246
+ defaultOrganizationId;
6247
+ forceNoCacheEnabled = false;
5468
6248
  defaultHeaders;
5469
6249
  authConfig;
5470
6250
  dbUrlOverride;
@@ -5513,6 +6293,15 @@ var AthenaClientBuilderImpl = class {
5513
6293
  if (options.client !== void 0) {
5514
6294
  this.clientName = options.client;
5515
6295
  }
6296
+ if (options.userId !== void 0) {
6297
+ this.defaultUserId = options.userId;
6298
+ }
6299
+ if (options.organizationId !== void 0) {
6300
+ this.defaultOrganizationId = options.organizationId;
6301
+ }
6302
+ if (options.forceNoCache !== void 0) {
6303
+ this.forceNoCacheEnabled = options.forceNoCache;
6304
+ }
5516
6305
  if (options.backend !== void 0) {
5517
6306
  this.backendConfig = toBackendConfig(options.backend);
5518
6307
  }
@@ -5567,6 +6356,9 @@ var AthenaClientBuilderImpl = class {
5567
6356
  url: this.rootUrl,
5568
6357
  key: this.apiKey,
5569
6358
  client: this.clientName,
6359
+ userId: this.defaultUserId,
6360
+ organizationId: this.defaultOrganizationId,
6361
+ forceNoCache: this.forceNoCacheEnabled,
5570
6362
  backend: this.backendConfig,
5571
6363
  headers: this.defaultHeaders,
5572
6364
  db: this.dbUrlOverride ? { url: this.dbUrlOverride } : void 0,
@@ -5610,7 +6402,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
5610
6402
  "ilike",
5611
6403
  "is"
5612
6404
  ]);
5613
- function isRecord7(value) {
6405
+ function isRecord8(value) {
5614
6406
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5615
6407
  }
5616
6408
  function isUuidString(value) {
@@ -5623,7 +6415,7 @@ function shouldUseUuidTextComparison(column, value) {
5623
6415
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
5624
6416
  }
5625
6417
  function isRelationSelectNode(value) {
5626
- return isRecord7(value) && isRecord7(value.select);
6418
+ return isRecord8(value) && isRecord8(value.select);
5627
6419
  }
5628
6420
  function normalizeIdentifier(value, label) {
5629
6421
  const normalized = value.trim();
@@ -5679,7 +6471,7 @@ function compileRelationToken(key, node) {
5679
6471
  return `${prefix}${relationToken}(${nested})`;
5680
6472
  }
5681
6473
  function compileSelectShape(select) {
5682
- if (!isRecord7(select)) {
6474
+ if (!isRecord8(select)) {
5683
6475
  throw new Error("findMany select must be an object");
5684
6476
  }
5685
6477
  const tokens = [];
@@ -5703,7 +6495,7 @@ function compileSelectShape(select) {
5703
6495
  return tokens.join(",");
5704
6496
  }
5705
6497
  function selectShapeUsesRelationSchema(select) {
5706
- if (!isRecord7(select)) {
6498
+ if (!isRecord8(select)) {
5707
6499
  return false;
5708
6500
  }
5709
6501
  for (const rawValue of Object.values(select)) {
@@ -5721,7 +6513,7 @@ function selectShapeUsesRelationSchema(select) {
5721
6513
  }
5722
6514
  function compileColumnWhere(column, input) {
5723
6515
  const normalizedColumn = normalizeIdentifier(column, "where column");
5724
- if (!isRecord7(input)) {
6516
+ if (!isRecord8(input)) {
5725
6517
  return [buildGatewayCondition("eq", normalizedColumn, input)];
5726
6518
  }
5727
6519
  const conditions = [];
@@ -5749,7 +6541,7 @@ function compileColumnWhere(column, input) {
5749
6541
  return conditions;
5750
6542
  }
5751
6543
  function compileBooleanExpressionTerms(clause, label) {
5752
- if (!isRecord7(clause)) {
6544
+ if (!isRecord8(clause)) {
5753
6545
  throw new Error(`findMany where.${label} clauses must be objects`);
5754
6546
  }
5755
6547
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -5758,7 +6550,7 @@ function compileBooleanExpressionTerms(clause, label) {
5758
6550
  }
5759
6551
  const [rawColumn, rawValue] = entries[0];
5760
6552
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
5761
- if (!isRecord7(rawValue)) {
6553
+ if (!isRecord8(rawValue)) {
5762
6554
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
5763
6555
  }
5764
6556
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -5782,7 +6574,7 @@ function compileWhere(where) {
5782
6574
  if (where === void 0) {
5783
6575
  return void 0;
5784
6576
  }
5785
- if (!isRecord7(where)) {
6577
+ if (!isRecord8(where)) {
5786
6578
  throw new Error("findMany where must be an object");
5787
6579
  }
5788
6580
  const conditions = [];
@@ -5832,7 +6624,7 @@ function compileOrderBy(orderBy) {
5832
6624
  if (orderBy === void 0) {
5833
6625
  return void 0;
5834
6626
  }
5835
- if (!isRecord7(orderBy)) {
6627
+ if (!isRecord8(orderBy)) {
5836
6628
  throw new Error("findMany orderBy must be an object");
5837
6629
  }
5838
6630
  if ("column" in orderBy) {
@@ -6007,11 +6799,11 @@ function toFindManyAstOrder(order) {
6007
6799
  ascending: order.direction !== "descending"
6008
6800
  };
6009
6801
  }
6010
- function isRecord8(value) {
6802
+ function isRecord9(value) {
6011
6803
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6012
6804
  }
6013
6805
  function normalizeFindManyAstColumnPredicate(value) {
6014
- if (!isRecord8(value)) {
6806
+ if (!isRecord9(value)) {
6015
6807
  return {
6016
6808
  eq: value
6017
6809
  };
@@ -6035,7 +6827,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6035
6827
  return normalized;
6036
6828
  }
6037
6829
  function normalizeFindManyAstWhere(where) {
6038
- if (!where || !isRecord8(where)) {
6830
+ if (!where || !isRecord9(where)) {
6039
6831
  return where;
6040
6832
  }
6041
6833
  const normalized = {};
@@ -6049,7 +6841,7 @@ function normalizeFindManyAstWhere(where) {
6049
6841
  );
6050
6842
  continue;
6051
6843
  }
6052
- if (key === "not" && isRecord8(value)) {
6844
+ if (key === "not" && isRecord9(value)) {
6053
6845
  normalized.not = normalizeFindManyAstBooleanOperand(
6054
6846
  value
6055
6847
  );
@@ -6060,7 +6852,7 @@ function normalizeFindManyAstWhere(where) {
6060
6852
  return normalized;
6061
6853
  }
6062
6854
  function predicateRequiresUuidQueryFallback(column, value) {
6063
- if (!isRecord8(value)) {
6855
+ if (!isRecord9(value)) {
6064
6856
  return shouldUseUuidTextComparison(column, value);
6065
6857
  }
6066
6858
  const eqValue = value.eq;
@@ -6078,7 +6870,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6078
6870
  return false;
6079
6871
  }
6080
6872
  function findManyAstWhereRequiresLegacyTransport(where) {
6081
- if (!where || !isRecord8(where)) {
6873
+ if (!where || !isRecord9(where)) {
6082
6874
  return false;
6083
6875
  }
6084
6876
  for (const [key, value] of Object.entries(where)) {
@@ -6093,7 +6885,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6093
6885
  }
6094
6886
  continue;
6095
6887
  }
6096
- if (key === "not" && isRecord8(value)) {
6888
+ if (key === "not" && isRecord9(value)) {
6097
6889
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6098
6890
  return true;
6099
6891
  }
@@ -6642,6 +7434,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
6642
7434
  var DEFAULT_COLUMNS = "*";
6643
7435
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6644
7436
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7437
+ var SDK_NAME4 = "xylex-group/athena";
6645
7438
  function formatResult(response) {
6646
7439
  const result = {
6647
7440
  data: response.data ?? null,
@@ -6718,7 +7511,7 @@ async function executeExperimentalRead(experimental, runner) {
6718
7511
  throw error;
6719
7512
  }
6720
7513
  }
6721
- function isRecord9(value) {
7514
+ function isRecord10(value) {
6722
7515
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6723
7516
  }
6724
7517
  function firstNonEmptyString2(...values) {
@@ -6730,8 +7523,8 @@ function firstNonEmptyString2(...values) {
6730
7523
  return void 0;
6731
7524
  }
6732
7525
  function resolveStructuredErrorPayload2(raw) {
6733
- if (!isRecord9(raw)) return null;
6734
- return isRecord9(raw.error) ? raw.error : raw;
7526
+ if (!isRecord10(raw)) return null;
7527
+ return isRecord10(raw.error) ? raw.error : raw;
6735
7528
  }
6736
7529
  function resolveStructuredErrorDetails(payload, message) {
6737
7530
  if (!payload || !("details" in payload)) {
@@ -6747,7 +7540,7 @@ function resolveStructuredErrorDetails(payload, message) {
6747
7540
  return details;
6748
7541
  }
6749
7542
  function createResultError(response, result, normalized) {
6750
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7543
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
6751
7544
  const payload = resolveStructuredErrorPayload2(response.raw);
6752
7545
  const message = firstNonEmptyString2(
6753
7546
  response.error,
@@ -6810,6 +7603,43 @@ function asAthenaJsonObject(value) {
6810
7603
  function asAthenaJsonObjectArray(values) {
6811
7604
  return values;
6812
7605
  }
7606
+ function parseArbitraryResponseBody(rawText, contentType) {
7607
+ if (!rawText) {
7608
+ return null;
7609
+ }
7610
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
7611
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
7612
+ if (!looksJson) {
7613
+ return rawText;
7614
+ }
7615
+ try {
7616
+ return JSON.parse(rawText);
7617
+ } catch {
7618
+ return rawText;
7619
+ }
7620
+ }
7621
+ function toRequestQueryString(query) {
7622
+ if (!query) {
7623
+ return "";
7624
+ }
7625
+ const params = new URLSearchParams();
7626
+ for (const [key, value] of Object.entries(query)) {
7627
+ if (value === void 0 || value === null) {
7628
+ continue;
7629
+ }
7630
+ if (Array.isArray(value)) {
7631
+ for (const item of value) {
7632
+ if (item !== void 0 && item !== null) {
7633
+ params.append(key, String(item));
7634
+ }
7635
+ }
7636
+ continue;
7637
+ }
7638
+ params.set(key, String(value));
7639
+ }
7640
+ const encoded = params.toString();
7641
+ return encoded ? `?${encoded}` : "";
7642
+ }
6813
7643
  function normalizeSelectColumnsInput(columns) {
6814
7644
  if (columns === void 0) {
6815
7645
  return void 0;
@@ -8109,6 +8939,85 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
8109
8939
  );
8110
8940
  };
8111
8941
  }
8942
+ var ATHENA_ENV_URL_KEYS = ["ATHENA_URL", "NEXT_PUBLIC_ATHENA_URL"];
8943
+ var ATHENA_ENV_GATEWAY_URL_KEYS = [
8944
+ "ATHENA_DB_URL",
8945
+ "ATHENA_GATEWAY_URL",
8946
+ "NEXT_PUBLIC_ATHENA_DB_API_URL"
8947
+ ];
8948
+ var ATHENA_ENV_AUTH_URL_KEYS = ["ATHENA_AUTH_URL", "NEXT_PUBLIC_ATHENA_AUTH_URL"];
8949
+ var ATHENA_ENV_CHAT_URL_KEYS = ["ATHENA_CHAT_URL", "NEXT_PUBLIC_ATHENA_CHAT_URL"];
8950
+ var ATHENA_ENV_CHAT_WS_URL_KEYS = ["ATHENA_CHAT_WS_URL", "NEXT_PUBLIC_ATHENA_CHAT_WS_URL"];
8951
+ var ATHENA_ENV_STORAGE_URL_KEYS = ["ATHENA_STORAGE_URL", "NEXT_PUBLIC_ATHENA_STORAGE_URL"];
8952
+ var ATHENA_ENV_KEY_KEYS = [
8953
+ "ATHENA_API_KEY",
8954
+ "NEXT_PUBLIC_ATHENA_API_KEY",
8955
+ "ATHENA_GATEWAY_API_KEY",
8956
+ "X_API_KEY"
8957
+ ];
8958
+ var ATHENA_ENV_CLIENT_KEYS = ["ATHENA_CLIENT", "NEXT_PUBLIC_ATHENA_CLIENT"];
8959
+ function normalizeOptionalString(value) {
8960
+ if (typeof value !== "string") {
8961
+ return void 0;
8962
+ }
8963
+ const normalizedValue = value.trim();
8964
+ return normalizedValue ? normalizedValue : void 0;
8965
+ }
8966
+ function readFirstEnvValue(env, keys) {
8967
+ for (const key of keys) {
8968
+ const value = normalizeOptionalString(env[key]);
8969
+ if (value) {
8970
+ return value;
8971
+ }
8972
+ }
8973
+ return void 0;
8974
+ }
8975
+ function readHeaderBagValue(headers, targetKey) {
8976
+ if (!headers) {
8977
+ return void 0;
8978
+ }
8979
+ if (typeof headers.get === "function") {
8980
+ return normalizeOptionalString(headers.get(targetKey));
8981
+ }
8982
+ const normalizedTargetKey = targetKey.toLowerCase();
8983
+ for (const [key, value] of Object.entries(headers)) {
8984
+ if (key.toLowerCase() !== normalizedTargetKey) {
8985
+ continue;
8986
+ }
8987
+ if (typeof value === "string") {
8988
+ return normalizeOptionalString(value);
8989
+ }
8990
+ return void 0;
8991
+ }
8992
+ return void 0;
8993
+ }
8994
+ function resolveSessionContextOptions(session, options) {
8995
+ const sessionToken = normalizeOptionalString(session?.session?.token);
8996
+ const requestCookie = readHeaderBagValue(options?.requestHeaders, "cookie") ?? readHeaderBagValue(options?.headers, "cookie");
8997
+ const authInput = options?.auth;
8998
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
8999
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
9000
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
9001
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
9002
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
9003
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9004
+ ...authInput ?? {},
9005
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9006
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9007
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9008
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9009
+ } : void 0;
9010
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9011
+ return void 0;
9012
+ }
9013
+ return {
9014
+ userId: resolvedUserId,
9015
+ organizationId: resolvedOrganizationId,
9016
+ forceNoCache: options?.forceNoCache,
9017
+ headers: options?.headers ? { ...options.headers } : void 0,
9018
+ auth
9019
+ };
9020
+ }
8112
9021
  function resolveClientServiceBaseUrl(value, label) {
8113
9022
  if (value === void 0 || value === null) {
8114
9023
  return void 0;
@@ -8119,6 +9028,15 @@ function appendServicePath(baseUrl, segment) {
8119
9028
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8120
9029
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8121
9030
  }
9031
+ function appendRealtimeGatewayPath(baseUrl) {
9032
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
9033
+ const wsUrl = new URL(normalizedBaseUrl);
9034
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
9035
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
9036
+ wsUrl.search = "";
9037
+ wsUrl.hash = "";
9038
+ return wsUrl.toString();
9039
+ }
8122
9040
  function resolveServiceUrlOverride(value, label) {
8123
9041
  return resolveClientServiceBaseUrl(value, label);
8124
9042
  }
@@ -8127,6 +9045,8 @@ function resolveServiceUrls(config) {
8127
9045
  return {
8128
9046
  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),
8129
9047
  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),
9048
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
9049
+ chatWsUrl: normalizeOptionalString(config.chat?.wsUrl) ?? normalizeOptionalString(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
8130
9050
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8131
9051
  };
8132
9052
  }
@@ -8151,6 +9071,89 @@ function resolveRequiredClientApiKey(value) {
8151
9071
  }
8152
9072
  return normalizedValue;
8153
9073
  }
9074
+ function hasHeaderIgnoreCase(headers, targetKey) {
9075
+ const normalizedTargetKey = targetKey.toLowerCase();
9076
+ return Object.keys(headers).some((key) => key.toLowerCase() === normalizedTargetKey);
9077
+ }
9078
+ function mergeClientHeaders(current, next) {
9079
+ if (!current && !next) {
9080
+ return void 0;
9081
+ }
9082
+ return {
9083
+ ...current ?? {},
9084
+ ...next ?? {}
9085
+ };
9086
+ }
9087
+ function mergeDefinedObject(current, next) {
9088
+ if (!current && !next) {
9089
+ return void 0;
9090
+ }
9091
+ const merged = {
9092
+ ...current ?? {}
9093
+ };
9094
+ const mutableMerged = merged;
9095
+ for (const [key, value] of Object.entries(next ?? {})) {
9096
+ if (value !== void 0) {
9097
+ mutableMerged[key] = value;
9098
+ }
9099
+ }
9100
+ return merged;
9101
+ }
9102
+ function mergeAuthClientOptions(current, next) {
9103
+ const merged = mergeDefinedObject(current, next);
9104
+ if (!merged) {
9105
+ return void 0;
9106
+ }
9107
+ const mergedHeaders = mergeClientHeaders(current?.headers, next?.headers);
9108
+ if (mergedHeaders) {
9109
+ merged.headers = mergedHeaders;
9110
+ }
9111
+ return merged;
9112
+ }
9113
+ function mergeServiceUrlOverrides(current, next) {
9114
+ return mergeDefinedObject(current, next);
9115
+ }
9116
+ function toClientContextOverrides(context) {
9117
+ if (!context) {
9118
+ return void 0;
9119
+ }
9120
+ return {
9121
+ userId: context.userId,
9122
+ organizationId: context.organizationId,
9123
+ forceNoCache: context.forceNoCache,
9124
+ headers: context.headers,
9125
+ auth: context.auth ? {
9126
+ ...context.auth,
9127
+ headers: context.auth.headers ? { ...context.auth.headers } : void 0
9128
+ } : void 0
9129
+ };
9130
+ }
9131
+ function mergeClientOverrideOptions(base, overrides) {
9132
+ if (!overrides) {
9133
+ return {
9134
+ ...base,
9135
+ headers: base.headers ? { ...base.headers } : void 0,
9136
+ auth: base.auth ? {
9137
+ ...base.auth,
9138
+ headers: base.auth.headers ? { ...base.auth.headers } : void 0
9139
+ } : void 0,
9140
+ db: base.db ? { ...base.db } : void 0,
9141
+ gateway: base.gateway ? { ...base.gateway } : void 0,
9142
+ chat: base.chat ? { ...base.chat } : void 0,
9143
+ storage: base.storage ? { ...base.storage } : void 0
9144
+ };
9145
+ }
9146
+ const merged = mergeDefinedObject(base, overrides) ?? { ...base };
9147
+ return {
9148
+ ...merged,
9149
+ headers: mergeClientHeaders(base.headers, overrides.headers),
9150
+ auth: mergeAuthClientOptions(base.auth, overrides.auth),
9151
+ db: mergeServiceUrlOverrides(base.db, overrides.db),
9152
+ gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9153
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
9154
+ storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
9155
+ };
9156
+ }
8154
9157
  function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8155
9158
  if (!auth && defaultBaseUrl === void 0) {
8156
9159
  return void 0;
@@ -8160,6 +9163,8 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8160
9163
  baseUrl,
8161
9164
  apiKey,
8162
9165
  bearerToken,
9166
+ cookie,
9167
+ sessionToken,
8163
9168
  ...rest
8164
9169
  } = auth ?? {};
8165
9170
  const normalized = {
@@ -8178,6 +9183,12 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8178
9183
  if (typeof bearerToken === "string") {
8179
9184
  normalized.bearerToken = bearerToken;
8180
9185
  }
9186
+ if (typeof cookie === "string") {
9187
+ normalized.cookie = cookie;
9188
+ }
9189
+ if (typeof sessionToken === "string") {
9190
+ normalized.sessionToken = sessionToken;
9191
+ }
8181
9192
  return normalized;
8182
9193
  }
8183
9194
  function resolveCreateClientConfig(config) {
@@ -8191,31 +9202,53 @@ function resolveCreateClientConfig(config) {
8191
9202
  baseUrl: resolvedUrls.dbUrl,
8192
9203
  apiKey: resolveRequiredClientApiKey(config.key),
8193
9204
  client: resolveOptionalClientName(config.client),
9205
+ userId: config.userId,
9206
+ organizationId: config.organizationId,
9207
+ forceNoCache: config.forceNoCache,
8194
9208
  backend: toBackendConfig(config.backend),
8195
9209
  headers: config.headers,
8196
9210
  auth: config.auth,
8197
9211
  authUrl: resolvedUrls.authUrl,
9212
+ chat: config.chat,
9213
+ chatUrl: resolvedUrls.chatUrl,
9214
+ chatWsUrl: resolvedUrls.chatWsUrl,
8198
9215
  storageUrl: resolvedUrls.storageUrl,
8199
9216
  experimental: config.experimental
8200
9217
  };
8201
9218
  }
8202
- function createClientFromConfig(config) {
9219
+ function createClientFromInput(sourceConfig) {
9220
+ return createClientFromConfig(resolveCreateClientConfig(sourceConfig), sourceConfig);
9221
+ }
9222
+ function createClientFromConfig(config, sourceConfig) {
9223
+ const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
8203
9224
  const gatewayHeaders = {
8204
9225
  ...config.headers ?? {}
8205
9226
  };
8206
- if (config.auth?.bearerToken && gatewayHeaders["X-Athena-Auth-Bearer-Token"] === void 0 && gatewayHeaders["x-athena-auth-bearer-token"] === void 0) {
8207
- gatewayHeaders["X-Athena-Auth-Bearer-Token"] = config.auth.bearerToken;
9227
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Bearer-Token")) {
9228
+ gatewayHeaders["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9229
+ }
9230
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(gatewayHeaders, "Cookie")) {
9231
+ gatewayHeaders.Cookie = normalizedAuthConfig.cookie;
9232
+ }
9233
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Session-Token")) {
9234
+ gatewayHeaders["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
8208
9235
  }
8209
9236
  const gateway = createAthenaGatewayClient({
8210
9237
  baseUrl: config.baseUrl,
8211
9238
  apiKey: config.apiKey,
8212
9239
  client: config.client,
9240
+ userId: config.userId,
9241
+ organizationId: config.organizationId,
9242
+ forceNoCache: config.forceNoCache,
8213
9243
  backend: config.backend,
8214
9244
  headers: gatewayHeaders
8215
9245
  });
8216
9246
  const formatGatewayResult = createResultFormatter(config.experimental);
8217
9247
  const queryTracer = createQueryTracer(config.experimental);
8218
- const auth = createAuthClient(normalizeAuthClientConfig(config.auth, config.authUrl));
9248
+ const auth = createAuthClient({
9249
+ ...normalizedAuthConfig ?? {},
9250
+ ...config.forceNoCache ? { forceNoCache: true } : {}
9251
+ });
8219
9252
  function from(tableOrModel, options) {
8220
9253
  if (isAthenaModelTarget(tableOrModel)) {
8221
9254
  if (options?.schema !== void 0) {
@@ -8263,17 +9296,160 @@ function createClientFromConfig(config) {
8263
9296
  queryTracer
8264
9297
  );
8265
9298
  const db = createDbModule({ from, rpc, query });
9299
+ const chat = createChatModule({
9300
+ baseUrl: config.chatUrl,
9301
+ apiKey: config.apiKey,
9302
+ client: config.client,
9303
+ headers: config.headers,
9304
+ bearerToken: normalizedAuthConfig?.bearerToken,
9305
+ cookie: normalizedAuthConfig?.cookie,
9306
+ sessionToken: normalizedAuthConfig?.sessionToken,
9307
+ forceNoCache: config.forceNoCache,
9308
+ wsUrl: config.chatWsUrl,
9309
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
9310
+ });
9311
+ const request2 = async (options) => {
9312
+ const method = options.method ?? "GET";
9313
+ const responseType = options.responseType ?? "json";
9314
+ const service = options.service ?? "db";
9315
+ const baseUrlByService = {
9316
+ db: config.baseUrl,
9317
+ auth: config.authUrl,
9318
+ chat: config.chatUrl,
9319
+ storage: config.storageUrl
9320
+ };
9321
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
9322
+ if (!resolvedBaseUrl) {
9323
+ throw new Error(
9324
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
9325
+ );
9326
+ }
9327
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
9328
+ label: `Athena ${service} base URL`
9329
+ });
9330
+ const normalizedPath = options.url ? "" : (() => {
9331
+ const path = options.path?.trim();
9332
+ if (!path) {
9333
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
9334
+ }
9335
+ return path.startsWith("/") ? path : `/${path}`;
9336
+ })();
9337
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
9338
+ const headers = {
9339
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
9340
+ ...config.headers ?? {},
9341
+ ...options.headers ?? {}
9342
+ };
9343
+ if (service !== "auth") {
9344
+ headers.apikey = headers.apikey ?? config.apiKey;
9345
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
9346
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
9347
+ headers["X-Athena-Client"] = config.client;
9348
+ }
9349
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
9350
+ headers["X-User-Id"] = config.userId;
9351
+ }
9352
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
9353
+ headers["X-Organization-Id"] = config.organizationId;
9354
+ }
9355
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9356
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9357
+ }
9358
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
9359
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9360
+ }
9361
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9362
+ headers.Cookie = normalizedAuthConfig.cookie;
9363
+ }
9364
+ } else {
9365
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
9366
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
9367
+ headers.apikey = headers.apikey ?? authApiKey;
9368
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
9369
+ }
9370
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
9371
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
9372
+ }
9373
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9374
+ headers.Cookie = normalizedAuthConfig.cookie;
9375
+ }
9376
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9377
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9378
+ }
9379
+ }
9380
+ 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";
9381
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
9382
+ headers["Content-Type"] = "application/json";
9383
+ }
9384
+ const response = await fetch(targetUrl, {
9385
+ method,
9386
+ headers,
9387
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
9388
+ signal: options.signal,
9389
+ credentials: options.credentials
9390
+ });
9391
+ if (responseType === "response") {
9392
+ return {
9393
+ ok: response.ok,
9394
+ status: response.status,
9395
+ statusText: response.statusText,
9396
+ headers: response.headers,
9397
+ data: null,
9398
+ raw: response
9399
+ };
9400
+ }
9401
+ const rawText = await response.text();
9402
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
9403
+ return {
9404
+ ok: response.ok,
9405
+ status: response.status,
9406
+ statusText: response.statusText,
9407
+ headers: response.headers,
9408
+ data: parsed,
9409
+ raw: response
9410
+ };
9411
+ };
9412
+ const withContext = (context) => createClientFromInput(
9413
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9414
+ );
9415
+ const withSession = (session, options) => createClientFromInput(
9416
+ mergeClientOverrideOptions(
9417
+ sourceConfig,
9418
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9419
+ )
9420
+ );
9421
+ const authWithOptions = (options) => createClientFromInput(mergeClientOverrideOptions(sourceConfig, options));
8266
9422
  const sdkClient = {
8267
9423
  from,
8268
9424
  db,
8269
9425
  rpc,
8270
9426
  query,
9427
+ request: request2,
8271
9428
  verifyConnection: gateway.verifyConnection,
8272
- auth: auth.auth
9429
+ auth: auth.auth,
9430
+ chat,
9431
+ withContext,
9432
+ withSession,
9433
+ withOptions: authWithOptions
8273
9434
  };
8274
9435
  if (config.experimental?.athenaStorageBackend) {
9436
+ const storageWithContext = (context) => createClientFromInput(
9437
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9438
+ );
9439
+ const storageWithSession = (session, options) => createClientFromInput(
9440
+ mergeClientOverrideOptions(
9441
+ sourceConfig,
9442
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9443
+ )
9444
+ );
9445
+ const storageWithOptions = (options) => createClientFromInput(
9446
+ mergeClientOverrideOptions(sourceConfig, options)
9447
+ );
8275
9448
  const storageClient = {
8276
9449
  ...sdkClient,
9450
+ withContext: storageWithContext,
9451
+ withSession: storageWithSession,
9452
+ withOptions: storageWithOptions,
8277
9453
  storage: createStorageModule(gateway, {
8278
9454
  ...config.experimental.storage,
8279
9455
  ...config.storageUrl ? {
@@ -8289,38 +9465,46 @@ function createClientFromConfig(config) {
8289
9465
  var AthenaClient = class {
8290
9466
  /** Create a fluent builder for a strongly-typed Athena SDK client. */
8291
9467
  static builder() {
8292
- return createAthenaClientBuilder((config) => createClientFromConfig(resolveCreateClientConfig(config)));
8293
- }
8294
- /** Build a client from process environment variables. */
8295
- static fromEnvironment() {
8296
- const url = process.env.ATHENA_URL;
8297
- const gatewayUrl = process.env.ATHENA_DB_URL ?? process.env.ATHENA_GATEWAY_URL;
8298
- const authUrl = process.env.ATHENA_AUTH_URL;
8299
- const storageUrl = process.env.ATHENA_STORAGE_URL;
8300
- const key = process.env.ATHENA_API_KEY ?? process.env.ATHENA_GATEWAY_API_KEY;
9468
+ return createAthenaClientBuilder((config) => createClientFromInput(config));
9469
+ }
9470
+ static fromEnvironment(options = {}) {
9471
+ const env = options.env ?? process.env;
9472
+ const url = options.url ?? readFirstEnvValue(env, ATHENA_ENV_URL_KEYS);
9473
+ const gatewayUrl = options.gatewayUrl ?? readFirstEnvValue(env, ATHENA_ENV_GATEWAY_URL_KEYS);
9474
+ const authUrl = options.authUrl ?? readFirstEnvValue(env, ATHENA_ENV_AUTH_URL_KEYS);
9475
+ const chatUrl = options.chatUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_URL_KEYS);
9476
+ const chatWsUrl = options.chatWsUrl ?? readFirstEnvValue(env, ATHENA_ENV_CHAT_WS_URL_KEYS);
9477
+ const storageUrl = options.storageUrl ?? readFirstEnvValue(env, ATHENA_ENV_STORAGE_URL_KEYS);
9478
+ const key = options.key ?? readFirstEnvValue(env, ATHENA_ENV_KEY_KEYS);
9479
+ const client = options.client ?? readFirstEnvValue(env, ATHENA_ENV_CLIENT_KEYS);
8301
9480
  if (!url && !gatewayUrl || !key) {
8302
9481
  throw new Error(
8303
- "ATHENA_API_KEY plus ATHENA_URL or ATHENA_GATEWAY_URL (optionally ATHENA_DB_URL, ATHENA_AUTH_URL, ATHENA_STORAGE_URL) are required"
9482
+ "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."
8304
9483
  );
8305
9484
  }
9485
+ const { env: _env, ...clientOptions } = options;
8306
9486
  return createClient({
9487
+ ...clientOptions,
8307
9488
  url,
8308
9489
  gatewayUrl,
8309
9490
  authUrl,
9491
+ chatUrl,
9492
+ chatWsUrl,
8310
9493
  storageUrl,
8311
- key
9494
+ key,
9495
+ client
8312
9496
  });
8313
9497
  }
8314
9498
  };
8315
9499
  function createClient(configOrUrl, apiKey, options) {
8316
9500
  if (typeof configOrUrl === "string" || configOrUrl === null || configOrUrl === void 0) {
8317
- return createClientFromConfig(resolveCreateClientConfig({
9501
+ return createClientFromInput({
8318
9502
  url: configOrUrl,
8319
9503
  key: apiKey ?? "",
8320
9504
  ...options
8321
- }));
9505
+ });
8322
9506
  }
8323
- return createClientFromConfig(resolveCreateClientConfig(configOrUrl));
9507
+ return createClientFromInput(configOrUrl);
8324
9508
  }
8325
9509
 
8326
9510
  // src/gateway/types.ts
@@ -8351,7 +9535,7 @@ function resolveNullishValue(mode) {
8351
9535
  if (mode === "null") return null;
8352
9536
  return "";
8353
9537
  }
8354
- function isRecord10(value) {
9538
+ function isRecord11(value) {
8355
9539
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8356
9540
  }
8357
9541
  function isNullableColumn(model, key) {
@@ -8360,7 +9544,7 @@ function isNullableColumn(model, key) {
8360
9544
  }
8361
9545
  function toModelFormDefaults(model, values, options) {
8362
9546
  const source = values;
8363
- if (!isRecord10(source)) {
9547
+ if (!isRecord11(source)) {
8364
9548
  return {};
8365
9549
  }
8366
9550
  const mode = options?.nullishMode ?? "empty-string";
@@ -8686,6 +9870,9 @@ function createColumnsBuilder(name, mappedName, schemaName, columns) {
8686
9870
  resolveTableTarget(name, mappedName, normalizedSchemaName);
8687
9871
  return createColumnsBuilder(name, mappedName, normalizedSchemaName, columns);
8688
9872
  },
9873
+ withoutPrimaryKey() {
9874
+ return finalizeTable(name, mappedName, schemaName, columns, []);
9875
+ },
8689
9876
  primaryKey(...keys) {
8690
9877
  return finalizeTable(name, mappedName, schemaName, columns, keys);
8691
9878
  }
@@ -8737,6 +9924,59 @@ var TenantHeaderMapper = class {
8737
9924
  return Object.keys(headers).length > 0 ? headers : void 0;
8738
9925
  }
8739
9926
  };
9927
+ function normalizeOptionalString2(value) {
9928
+ if (typeof value !== "string") {
9929
+ return void 0;
9930
+ }
9931
+ const normalizedValue = value.trim();
9932
+ return normalizedValue ? normalizedValue : void 0;
9933
+ }
9934
+ function readHeaderBagValue2(headers, targetKey) {
9935
+ if (!headers) {
9936
+ return void 0;
9937
+ }
9938
+ if (typeof headers.get === "function") {
9939
+ return normalizeOptionalString2(headers.get(targetKey));
9940
+ }
9941
+ const normalizedTargetKey = targetKey.toLowerCase();
9942
+ for (const [key, value] of Object.entries(headers)) {
9943
+ if (key.toLowerCase() !== normalizedTargetKey) {
9944
+ continue;
9945
+ }
9946
+ if (typeof value === "string") {
9947
+ return normalizeOptionalString2(value);
9948
+ }
9949
+ return void 0;
9950
+ }
9951
+ return void 0;
9952
+ }
9953
+ function resolveSessionContextOptions2(session, options) {
9954
+ const sessionToken = normalizeOptionalString2(session?.session?.token);
9955
+ const requestCookie = readHeaderBagValue2(options?.requestHeaders, "cookie") ?? readHeaderBagValue2(options?.headers, "cookie");
9956
+ const authInput = options?.auth;
9957
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
9958
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
9959
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
9960
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
9961
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
9962
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9963
+ ...authInput ?? {},
9964
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9965
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9966
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9967
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9968
+ } : void 0;
9969
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9970
+ return void 0;
9971
+ }
9972
+ return {
9973
+ userId: resolvedUserId,
9974
+ organizationId: resolvedOrganizationId,
9975
+ forceNoCache: options?.forceNoCache,
9976
+ headers: options?.headers ? { ...options.headers } : void 0,
9977
+ auth
9978
+ };
9979
+ }
8740
9980
  var RegistryNavigator = class {
8741
9981
  constructor(registry) {
8742
9982
  this.registry = registry;
@@ -8788,12 +10028,22 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
8788
10028
  backend: input.options?.backend,
8789
10029
  client: input.options?.client,
8790
10030
  headers: input.options?.headers,
10031
+ forceNoCache: input.options?.forceNoCache,
10032
+ userId: input.options?.userId,
10033
+ organizationId: input.options?.organizationId,
10034
+ auth: input.options?.auth,
10035
+ tenantKeyMap,
10036
+ tenantContext,
8791
10037
  experimental: input.options?.experimental
8792
10038
  };
8793
10039
  this.baseClient = createClient(this.url, this.apiKey, {
8794
10040
  backend: this.clientOptions.backend,
8795
10041
  client: this.clientOptions.client,
8796
10042
  headers: this.tenantHeaderMapper.apply(this.clientOptions.headers, tenantContext),
10043
+ forceNoCache: this.clientOptions.forceNoCache,
10044
+ userId: this.clientOptions.userId,
10045
+ organizationId: this.clientOptions.organizationId,
10046
+ auth: this.clientOptions.auth,
8797
10047
  experimental: this.clientOptions.experimental
8798
10048
  });
8799
10049
  this.db = this.baseClient.db;
@@ -8808,9 +10058,46 @@ var TypedAthenaClientImpl = class _TypedAthenaClientImpl {
8808
10058
  query(query, options) {
8809
10059
  return this.baseClient.query(query, options);
8810
10060
  }
10061
+ request(options) {
10062
+ return this.baseClient.request(options);
10063
+ }
8811
10064
  verifyConnection(options) {
8812
10065
  return this.baseClient.verifyConnection(options);
8813
10066
  }
10067
+ withContext(context) {
10068
+ const headers = {
10069
+ ...this.clientOptions.headers ?? {},
10070
+ ...context?.headers ?? {}
10071
+ };
10072
+ const auth = this.clientOptions.auth || context?.auth ? {
10073
+ ...this.clientOptions.auth ?? {},
10074
+ ...context?.auth ?? {},
10075
+ headers: this.clientOptions.auth?.headers || context?.auth?.headers ? {
10076
+ ...this.clientOptions.auth?.headers ?? {},
10077
+ ...context?.auth?.headers ?? {}
10078
+ } : void 0
10079
+ } : void 0;
10080
+ return new _TypedAthenaClientImpl({
10081
+ registry: this.registry,
10082
+ url: this.url,
10083
+ apiKey: this.apiKey,
10084
+ options: {
10085
+ ...this.clientOptions,
10086
+ headers: Object.keys(headers).length > 0 ? headers : void 0,
10087
+ auth,
10088
+ tenantKeyMap: this.tenantKeyMap,
10089
+ tenantContext: {
10090
+ ...this.tenantContext
10091
+ },
10092
+ ...context?.userId !== void 0 ? { userId: context.userId } : {},
10093
+ ...context?.organizationId !== void 0 ? { organizationId: context.organizationId } : {},
10094
+ ...context?.forceNoCache !== void 0 ? { forceNoCache: context.forceNoCache } : {}
10095
+ }
10096
+ });
10097
+ }
10098
+ withSession(session, options) {
10099
+ return this.withContext(resolveSessionContextOptions2(session, options));
10100
+ }
8814
10101
  withTenantContext(context) {
8815
10102
  return new _TypedAthenaClientImpl({
8816
10103
  registry: this.registry,
@@ -9306,6 +10593,77 @@ function resolveProviderSchemas(providerConfig) {
9306
10593
  return [...DEFAULT_POSTGRES_SCHEMAS];
9307
10594
  }
9308
10595
 
10596
+ // src/generator/table-selection.ts
10597
+ function normalizeTableSelector(value) {
10598
+ const trimmed = value.trim();
10599
+ return trimmed.length > 0 ? trimmed : void 0;
10600
+ }
10601
+ function normalizeTableSelection(value) {
10602
+ if (typeof value === "string") {
10603
+ return Array.from(
10604
+ new Set(
10605
+ value.split(",").map(normalizeTableSelector).filter((entry) => Boolean(entry))
10606
+ )
10607
+ );
10608
+ }
10609
+ if (Array.isArray(value)) {
10610
+ return Array.from(
10611
+ new Set(
10612
+ value.map((entry) => typeof entry === "string" ? normalizeTableSelector(entry) : void 0).filter((entry) => Boolean(entry))
10613
+ )
10614
+ );
10615
+ }
10616
+ return [];
10617
+ }
10618
+ function matchesTableSelector(schemaName, tableName, selector) {
10619
+ const separatorIndex = selector.indexOf(".");
10620
+ if (separatorIndex < 0) {
10621
+ return tableName === selector;
10622
+ }
10623
+ const selectorSchema = selector.slice(0, separatorIndex).trim();
10624
+ const selectorTable = selector.slice(separatorIndex + 1).trim();
10625
+ return selectorSchema === schemaName && selectorTable === tableName;
10626
+ }
10627
+ function shouldKeepTable(schemaName, tableName, filter) {
10628
+ const included = filter.includeTables.length === 0 || filter.includeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
10629
+ if (!included) {
10630
+ return false;
10631
+ }
10632
+ return !filter.excludeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
10633
+ }
10634
+ function hasTableFilters(filter) {
10635
+ return filter.includeTables.length > 0 || filter.excludeTables.length > 0;
10636
+ }
10637
+ function filterIntrospectionSnapshot(snapshot, filter) {
10638
+ if (!hasTableFilters(filter)) {
10639
+ return snapshot;
10640
+ }
10641
+ const schemas = {};
10642
+ for (const [schemaName, schema] of Object.entries(snapshot.schemas)) {
10643
+ const tables = Object.fromEntries(
10644
+ Object.entries(schema.tables).filter(([tableName]) => shouldKeepTable(schemaName, tableName, filter))
10645
+ );
10646
+ if (Object.keys(tables).length === 0) {
10647
+ continue;
10648
+ }
10649
+ schemas[schemaName] = {
10650
+ ...schema,
10651
+ tables
10652
+ };
10653
+ }
10654
+ if (Object.keys(schemas).length === 0) {
10655
+ const includeLabel = filter.includeTables.length > 0 ? ` includeTables=${filter.includeTables.join(", ")}` : "";
10656
+ const excludeLabel = filter.excludeTables.length > 0 ? ` excludeTables=${filter.excludeTables.join(", ")}` : "";
10657
+ throw new Error(
10658
+ `Generator table filters matched no tables after schema selection.${includeLabel}${excludeLabel}`
10659
+ );
10660
+ }
10661
+ return {
10662
+ ...snapshot,
10663
+ schemas
10664
+ };
10665
+ }
10666
+
9309
10667
  // src/generator/config.ts
9310
10668
  var POSTGRES_PROTOCOLS = /* @__PURE__ */ new Set(["postgres:", "postgresql:"]);
9311
10669
  var DEFAULT_CONFIG_CANDIDATES = [
@@ -9316,13 +10674,20 @@ var DEFAULT_CONFIG_CANDIDATES = [
9316
10674
  ".athena.config.ts",
9317
10675
  ".athena.config.js"
9318
10676
  ];
9319
- var DEFAULT_TARGETS = {
10677
+ var LEGACY_DEFAULT_TARGETS = {
9320
10678
  model: "athena/models/{schema_kebab}/{model_kebab}.ts",
9321
10679
  schema: "athena/schemas/{schema_kebab}.ts",
9322
10680
  database: "athena/relations.ts",
9323
10681
  registry: "athena/config.ts"
9324
10682
  };
9325
- var DEFAULT_OUTPUT_FORMAT = "define-model";
10683
+ var ATHENA_DIRECT_TARGETS = {
10684
+ model: "athena/models/{schema_kebab}/{model_kebab}.ts",
10685
+ schema: "athena/schemas/{schema_kebab}.ts",
10686
+ database: "athena/relations.ts",
10687
+ registry: "athena/registry.generated.ts"
10688
+ };
10689
+ var DEFAULT_OUTPUT_FORMAT = "table-builder";
10690
+ var DEFAULT_OUTPUT_PRESET = "athena-direct";
9326
10691
  var DEFAULT_NAMING = {
9327
10692
  modelType: "pascal",
9328
10693
  modelConst: "camel",
@@ -9341,6 +10706,10 @@ var DEFAULT_EXPERIMENTAL_FLAGS = {
9341
10706
  var DEFAULT_INTERNAL_CONFIG = {
9342
10707
  schemaVersion: 1
9343
10708
  };
10709
+ var DEFAULT_FILTER_CONFIG = {
10710
+ includeTables: [],
10711
+ excludeTables: []
10712
+ };
9344
10713
  var PROJECT_ENV_FILENAMES = [".env", ".env.local"];
9345
10714
  var DIRECT_CONNECTION_STRING_ENV_KEYS = [
9346
10715
  "ATHENA_GENERATOR_PG_URL",
@@ -9359,10 +10728,13 @@ var GATEWAY_API_KEY_ENV_KEYS = [
9359
10728
  ];
9360
10729
  var GENERATOR_SCHEMA_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMAS"];
9361
10730
  var OUTPUT_FORMAT_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_FORMAT"];
10731
+ var OUTPUT_PRESET_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_PRESET"];
9362
10732
  var MODEL_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TARGET"];
9363
10733
  var SCHEMA_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_TARGET"];
9364
10734
  var DATABASE_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_TARGET"];
9365
10735
  var REGISTRY_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_TARGET"];
10736
+ var TABLES_ENV_KEYS = ["ATHENA_GENERATOR_TABLES"];
10737
+ var EXCLUDE_TABLES_ENV_KEYS = ["ATHENA_GENERATOR_EXCLUDE_TABLES"];
9366
10738
  var PLACEHOLDER_MAP_ENV_KEYS = ["ATHENA_GENERATOR_PLACEHOLDER_MAP"];
9367
10739
  var MODEL_TYPE_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TYPE", "ATHENA_GENERATOR_MODEL_STYLE"];
9368
10740
  var MODEL_CONST_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_CONST"];
@@ -9377,7 +10749,12 @@ var SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS = ["ATHENA_GENERATOR_SCYLLA_PROVIDER_CONT
9377
10749
  var ENV_ONLY_CONFIG_PATH = "[environment defaults]";
9378
10750
  var NAMING_STYLE_VALUES = ["preserve", "camel", "pascal", "snake", "kebab"];
9379
10751
  var OUTPUT_FORMAT_VALUES = ["define-model", "table-builder"];
10752
+ var OUTPUT_PRESET_VALUES = ["legacy", "athena-direct"];
9380
10753
  var BACKEND_TYPE_VALUES = ["athena", "postgrest", "postgresql", "scylladb"];
10754
+ var OUTPUT_PRESET_TARGETS = {
10755
+ legacy: LEGACY_DEFAULT_TARGETS,
10756
+ "athena-direct": ATHENA_DIRECT_TARGETS
10757
+ };
9381
10758
  function normalizeRawEnvValue(rawValue) {
9382
10759
  if (rawValue.startsWith('"') && rawValue.endsWith('"') && rawValue.length >= 2) {
9383
10760
  const inner = rawValue.slice(1, -1);
@@ -9513,7 +10890,7 @@ function deriveDatabaseNameFromConnectionString(connectionString) {
9513
10890
  return void 0;
9514
10891
  }
9515
10892
  }
9516
- function normalizeOptionalString(value, fallbackKeys) {
10893
+ function normalizeOptionalString3(value, fallbackKeys) {
9517
10894
  if (typeof value === "string") {
9518
10895
  const trimmed = value.trim();
9519
10896
  if (trimmed.length > 0) {
@@ -9523,7 +10900,7 @@ function normalizeOptionalString(value, fallbackKeys) {
9523
10900
  return resolveFallbackValue(fallbackKeys);
9524
10901
  }
9525
10902
  function normalizeRequiredString(value, fieldLabel, fallbackKeys) {
9526
- const resolved = normalizeOptionalString(value, fallbackKeys);
10903
+ const resolved = normalizeOptionalString3(value, fallbackKeys);
9527
10904
  if (resolved) {
9528
10905
  return resolved;
9529
10906
  }
@@ -9584,11 +10961,19 @@ function normalizeExperimentalFlags(input) {
9584
10961
  )
9585
10962
  };
9586
10963
  }
10964
+ function normalizeFilterConfig(input) {
10965
+ return {
10966
+ includeTables: normalizeTableSelection(input?.includeTables),
10967
+ excludeTables: normalizeTableSelection(input?.excludeTables)
10968
+ };
10969
+ }
9587
10970
  function normalizeOutputConfig(output) {
10971
+ const preset = output?.preset ?? DEFAULT_OUTPUT_PRESET;
9588
10972
  return {
9589
10973
  format: output?.format ?? DEFAULT_OUTPUT_FORMAT,
10974
+ preset,
9590
10975
  targets: {
9591
- ...DEFAULT_TARGETS,
10976
+ ...OUTPUT_PRESET_TARGETS[preset],
9592
10977
  ...output?.targets ?? {}
9593
10978
  },
9594
10979
  placeholderMap: {
@@ -9603,7 +10988,7 @@ function normalizeProviderConfig(provider) {
9603
10988
  "provider.connectionString",
9604
10989
  DIRECT_CONNECTION_STRING_ENV_KEYS
9605
10990
  );
9606
- const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? deriveDatabaseNameFromConnectionString(connectionString);
10991
+ const database = normalizeOptionalString3(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? deriveDatabaseNameFromConnectionString(connectionString);
9607
10992
  return {
9608
10993
  ...provider,
9609
10994
  connectionString: applyPostgresPasswordFallback(connectionString),
@@ -9622,7 +11007,7 @@ function normalizeProviderConfig(provider) {
9622
11007
  "provider.apiKey",
9623
11008
  GATEWAY_API_KEY_ENV_KEYS
9624
11009
  );
9625
- const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? "postgres";
11010
+ const database = normalizeOptionalString3(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? "postgres";
9626
11011
  return {
9627
11012
  ...provider,
9628
11013
  gatewayUrl,
@@ -9637,7 +11022,7 @@ function normalizeProviderConfig(provider) {
9637
11022
  "Generator config is missing provider.contactPoints for scylla direct mode."
9638
11023
  );
9639
11024
  }
9640
- const keyspace = normalizeOptionalString(provider.keyspace, []);
11025
+ const keyspace = normalizeOptionalString3(provider.keyspace, []);
9641
11026
  if (!keyspace) {
9642
11027
  throw new Error(
9643
11028
  "Generator config is missing provider.keyspace for scylla direct mode."
@@ -9648,7 +11033,7 @@ function normalizeProviderConfig(provider) {
9648
11033
  mode: "direct",
9649
11034
  contactPoints: provider.contactPoints.slice(),
9650
11035
  keyspace,
9651
- datacenter: normalizeOptionalString(provider.datacenter, [])
11036
+ datacenter: normalizeOptionalString3(provider.datacenter, [])
9652
11037
  };
9653
11038
  }
9654
11039
  return provider;
@@ -9668,6 +11053,10 @@ function normalizeGeneratorConfig(input) {
9668
11053
  ...DEFAULT_NAMING,
9669
11054
  ...input.naming ?? {}
9670
11055
  },
11056
+ filter: {
11057
+ ...DEFAULT_FILTER_CONFIG,
11058
+ ...normalizeFilterConfig(input.filter)
11059
+ },
9671
11060
  features: normalizeFeatureFlags(input.features),
9672
11061
  experimental: normalizeExperimentalFlags(input.experimental),
9673
11062
  internal: {
@@ -9731,16 +11120,18 @@ function importConfigModule(moduleSpecifier) {
9731
11120
  }
9732
11121
  function buildEnvironmentOutputConfig() {
9733
11122
  const format = resolveOptionalOneOf(OUTPUT_FORMAT_ENV_KEYS, OUTPUT_FORMAT_VALUES);
11123
+ const preset = resolveOptionalOneOf(OUTPUT_PRESET_ENV_KEYS, OUTPUT_PRESET_VALUES);
9734
11124
  const modelTarget = resolveFallbackValue(MODEL_TARGET_ENV_KEYS);
9735
11125
  const schemaTarget = resolveFallbackValue(SCHEMA_TARGET_ENV_KEYS);
9736
11126
  const databaseTarget = resolveFallbackValue(DATABASE_TARGET_ENV_KEYS);
9737
11127
  const registryTarget = resolveFallbackValue(REGISTRY_TARGET_ENV_KEYS);
9738
11128
  const placeholderMap = resolveOptionalJson(PLACEHOLDER_MAP_ENV_KEYS);
9739
- if (format === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
11129
+ if (format === void 0 && preset === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
9740
11130
  return void 0;
9741
11131
  }
9742
11132
  return {
9743
11133
  format,
11134
+ preset,
9744
11135
  targets: {
9745
11136
  ...modelTarget ? { model: modelTarget } : {},
9746
11137
  ...schemaTarget ? { schema: schemaTarget } : {},
@@ -9750,6 +11141,17 @@ function buildEnvironmentOutputConfig() {
9750
11141
  placeholderMap
9751
11142
  };
9752
11143
  }
11144
+ function buildEnvironmentFilterConfig() {
11145
+ const includeTables = resolveFallbackValue(TABLES_ENV_KEYS);
11146
+ const excludeTables = resolveFallbackValue(EXCLUDE_TABLES_ENV_KEYS);
11147
+ if (includeTables === void 0 && excludeTables === void 0) {
11148
+ return void 0;
11149
+ }
11150
+ return {
11151
+ ...includeTables !== void 0 ? { includeTables } : {},
11152
+ ...excludeTables !== void 0 ? { excludeTables } : {}
11153
+ };
11154
+ }
9753
11155
  function buildEnvironmentNamingConfig() {
9754
11156
  const modelType = resolveOptionalOneOf(MODEL_TYPE_ENV_KEYS, NAMING_STYLE_VALUES);
9755
11157
  const modelConst = resolveOptionalOneOf(MODEL_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
@@ -9796,7 +11198,7 @@ function buildEnvironmentProviderConfig() {
9796
11198
  kind: "postgres",
9797
11199
  mode: "direct",
9798
11200
  connectionString: directConnectionString,
9799
- database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
11201
+ database: normalizeOptionalString3(void 0, POSTGRES_DATABASE_ENV_KEYS),
9800
11202
  schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS))
9801
11203
  };
9802
11204
  }
@@ -9809,7 +11211,7 @@ function buildEnvironmentProviderConfig() {
9809
11211
  mode: "gateway",
9810
11212
  gatewayUrl,
9811
11213
  apiKey,
9812
- database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
11214
+ database: normalizeOptionalString3(void 0, POSTGRES_DATABASE_ENV_KEYS),
9813
11215
  schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS)),
9814
11216
  backend
9815
11217
  };
@@ -9825,6 +11227,7 @@ function createEnvironmentGeneratorConfig() {
9825
11227
  provider,
9826
11228
  output: buildEnvironmentOutputConfig(),
9827
11229
  naming: buildEnvironmentNamingConfig(),
11230
+ filter: buildEnvironmentFilterConfig(),
9828
11231
  features: buildEnvironmentFeatureFlags(),
9829
11232
  experimental: buildEnvironmentExperimentalFlags()
9830
11233
  };
@@ -10310,7 +11713,7 @@ ${schemaEntries}
10310
11713
  content
10311
11714
  };
10312
11715
  }
10313
- function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputFormat, schemaVersion) {
11716
+ function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputPreset, outputFormat, schemaVersion) {
10314
11717
  const databaseImportPath = toModuleImportPath(registryPath, databasePath);
10315
11718
  const content = `import { defineRegistry } from '@xylex-group/athena'
10316
11719
  import { ${databaseConstName} } from '${databaseImportPath}'
@@ -10319,6 +11722,7 @@ export const __athena_schema_meta = {
10319
11722
  schemaVersion: ${schemaVersion},
10320
11723
  generatedAt: ${escapeStringLiteral(generatedAt)},
10321
11724
  database: ${escapeStringLiteral(databaseName)},
11725
+ outputPreset: ${escapeStringLiteral(outputPreset)},
10322
11726
  outputFormat: ${escapeStringLiteral(outputFormat)},
10323
11727
  } as const
10324
11728
 
@@ -10488,6 +11892,7 @@ function composeGeneratorArtifacts(input) {
10488
11892
  toSafeIdentifier("registry", config.naming.registryConst, "registry"),
10489
11893
  databaseName,
10490
11894
  snapshot.generatedAt,
11895
+ config.output.preset,
10491
11896
  config.output.format,
10492
11897
  config.internal.schemaVersion
10493
11898
  )
@@ -10593,7 +11998,7 @@ export const ${descriptor.tableConstName} = table(${escapeStringLiteral(descript
10593
11998
  .columns({
10594
11999
  ${columnLines}
10595
12000
  })
10596
- .primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})
12001
+ ${descriptor.table.primaryKey.length > 0 ? `.primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})` : ".withoutPrimaryKey()"}
10597
12002
  ${relationsAssignment ? `${relationsAssignment}` : ""}
10598
12003
  export type ${descriptor.rowTypeName} = RowOf<typeof ${descriptor.tableConstName}>
10599
12004
  export type ${descriptor.insertTypeName} = InsertOf<typeof ${descriptor.tableConstName}>
@@ -10690,11 +12095,12 @@ ${nullableLines}
10690
12095
  }
10691
12096
  function generateArtifactsFromSnapshot(snapshot, config) {
10692
12097
  const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
12098
+ const filteredSnapshot = filterIntrospectionSnapshot(snapshot, normalizedConfig.filter);
10693
12099
  if (normalizedConfig.output.format === "table-builder") {
10694
- return generateTableBuilderArtifactsFromSnapshot(snapshot, normalizedConfig);
12100
+ return generateTableBuilderArtifactsFromSnapshot(filteredSnapshot, normalizedConfig);
10695
12101
  }
10696
12102
  return composeGeneratorArtifacts({
10697
- snapshot,
12103
+ snapshot: filteredSnapshot,
10698
12104
  config: normalizedConfig,
10699
12105
  createModelDescriptor({ providerName, databaseName, schemaName, tableName, table: table2 }) {
10700
12106
  const modelConstName = toSafeIdentifier(
@@ -10724,7 +12130,7 @@ function generateArtifactsFromSnapshot(snapshot, config) {
10724
12130
  table: table2
10725
12131
  };
10726
12132
  },
10727
- renderModelArtifact: (descriptor) => renderModelArtifact2(snapshot.database, descriptor, normalizedConfig)
12133
+ renderModelArtifact: (descriptor) => renderModelArtifact2(filteredSnapshot.database, descriptor, normalizedConfig)
10728
12134
  });
10729
12135
  }
10730
12136
 
@@ -10844,16 +12250,25 @@ async function fileExists(path) {
10844
12250
  }
10845
12251
  async function writeArtifacts(files, cwd) {
10846
12252
  const writtenFiles = [];
12253
+ const skippedFiles = [];
10847
12254
  for (const file of files) {
10848
12255
  const absolutePath = path.resolve(cwd, file.path);
10849
12256
  if (!canOverwriteArtifact(file) && await fileExists(absolutePath)) {
12257
+ skippedFiles.push({
12258
+ kind: file.kind,
12259
+ path: file.path,
12260
+ reason: "protected-existing-file"
12261
+ });
10850
12262
  continue;
10851
12263
  }
10852
12264
  await promises.mkdir(path.dirname(absolutePath), { recursive: true });
10853
12265
  await promises.writeFile(absolutePath, file.content, "utf8");
10854
12266
  writtenFiles.push(file.path);
10855
12267
  }
10856
- return writtenFiles;
12268
+ return {
12269
+ writtenFiles,
12270
+ skippedFiles
12271
+ };
10857
12272
  }
10858
12273
  async function runSchemaGenerator(options = {}) {
10859
12274
  const cwd = options.cwd ?? process.cwd();
@@ -10867,12 +12282,13 @@ async function runSchemaGenerator(options = {}) {
10867
12282
  schemas: resolveProviderSchemas(config.provider)
10868
12283
  });
10869
12284
  const generated = generateArtifactsFromSnapshot(snapshot, config);
10870
- const writtenFiles = options.dryRun ? [] : await writeArtifacts(generated.files, cwd);
12285
+ const writeResult = options.dryRun ? { writtenFiles: [], skippedFiles: [] } : await writeArtifacts(generated.files, cwd);
10871
12286
  return {
10872
12287
  ...generated,
10873
12288
  configPath,
10874
12289
  config,
10875
- writtenFiles
12290
+ writtenFiles: writeResult.writtenFiles,
12291
+ skippedFiles: writeResult.skippedFiles
10876
12292
  };
10877
12293
  }
10878
12294
 
@@ -10941,15 +12357,15 @@ function readCookieFromHeaders(headers, name) {
10941
12357
  }
10942
12358
  return parseCookies(cookieHeader).get(name);
10943
12359
  }
10944
- function isRecord11(value) {
12360
+ function isRecord12(value) {
10945
12361
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
10946
12362
  }
10947
12363
  function resolveSessionCandidate(value) {
10948
- if (!isRecord11(value)) {
12364
+ if (!isRecord12(value)) {
10949
12365
  return null;
10950
12366
  }
10951
- const session = isRecord11(value.session) ? value.session : void 0;
10952
- const user = isRecord11(value.user) ? value.user : void 0;
12367
+ const session = isRecord12(value.session) ? value.session : void 0;
12368
+ const user = isRecord12(value.user) ? value.user : void 0;
10953
12369
  if (session && typeof session.token === "string" && session.token.length > 0 && user) {
10954
12370
  return {
10955
12371
  session,
@@ -10959,7 +12375,7 @@ function resolveSessionCandidate(value) {
10959
12375
  return null;
10960
12376
  }
10961
12377
  function inferSessionPair(returned) {
10962
- return resolveSessionCandidate(returned) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord11(returned) ? resolveSessionCandidate(returned.session) : null);
12378
+ return resolveSessionCandidate(returned) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.data) : null) ?? (isRecord12(returned) ? resolveSessionCandidate(returned.session) : null);
10963
12379
  }
10964
12380
  function resolveResponseHeaders(ctx) {
10965
12381
  if (ctx.context.responseHeaders instanceof Headers) {
@@ -10982,23 +12398,23 @@ function normalizeBasePath(basePath) {
10982
12398
  function isDynamicBaseURLConfig2(baseURL) {
10983
12399
  return typeof baseURL === "object" && baseURL !== null && "allowedHosts" in baseURL && Array.isArray(baseURL.allowedHosts);
10984
12400
  }
10985
- function getRequestUrl(request) {
12401
+ function getRequestUrl(request2) {
10986
12402
  try {
10987
- return new URL(request.url);
12403
+ return new URL(request2.url);
10988
12404
  } catch {
10989
12405
  return new URL("http://localhost");
10990
12406
  }
10991
12407
  }
10992
- function getRequestHost(request, url) {
10993
- const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
10994
- const host = forwardedHost || request.headers.get("host") || url.host;
12408
+ function getRequestHost(request2, url) {
12409
+ const forwardedHost = request2.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
12410
+ const host = forwardedHost || request2.headers.get("host") || url.host;
10995
12411
  return host || null;
10996
12412
  }
10997
- function getRequestProtocol(request, configuredProtocol, url) {
12413
+ function getRequestProtocol(request2, configuredProtocol, url) {
10998
12414
  if (configuredProtocol === "http" || configuredProtocol === "https") {
10999
12415
  return configuredProtocol;
11000
12416
  }
11001
- const forwardedProto = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
12417
+ const forwardedProto = request2.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
11002
12418
  if (forwardedProto === "http" || forwardedProto === "https") {
11003
12419
  return forwardedProto;
11004
12420
  }
@@ -11007,12 +12423,12 @@ function getRequestProtocol(request, configuredProtocol, url) {
11007
12423
  }
11008
12424
  return "http";
11009
12425
  }
11010
- function resolveRequestBaseURL(baseURL, request) {
12426
+ function resolveRequestBaseURL(baseURL, request2) {
11011
12427
  if (typeof baseURL === "string") {
11012
12428
  return normalizeBaseURL(baseURL);
11013
12429
  }
11014
- const requestUrl = getRequestUrl(request);
11015
- const host = getRequestHost(request, requestUrl);
12430
+ const requestUrl = getRequestUrl(request2);
12431
+ const host = getRequestHost(request2, requestUrl);
11016
12432
  if (!host) {
11017
12433
  return null;
11018
12434
  }
@@ -11022,7 +12438,7 @@ function resolveRequestBaseURL(baseURL, request) {
11022
12438
  return null;
11023
12439
  }
11024
12440
  }
11025
- const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request, baseURL.protocol, requestUrl) : getRequestProtocol(request, void 0, requestUrl);
12441
+ const protocol = typeof baseURL === "object" && baseURL !== null ? getRequestProtocol(request2, baseURL.protocol, requestUrl) : getRequestProtocol(request2, void 0, requestUrl);
11026
12442
  return `${protocol}://${host}`;
11027
12443
  }
11028
12444
  function getOrigin(baseURL) {
@@ -11035,16 +12451,16 @@ function getOrigin(baseURL) {
11035
12451
  return void 0;
11036
12452
  }
11037
12453
  }
11038
- async function resolveTrustedOrigins(config, baseURL, request) {
11039
- const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request) : config.trustedOrigins ?? [];
12454
+ async function resolveTrustedOrigins(config, baseURL, request2) {
12455
+ const resolved = typeof config.trustedOrigins === "function" ? await config.trustedOrigins(request2) : config.trustedOrigins ?? [];
11040
12456
  const values = [
11041
12457
  getOrigin(baseURL),
11042
12458
  ...resolved
11043
12459
  ];
11044
12460
  return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
11045
12461
  }
11046
- async function resolveTrustedProviders(config, request) {
11047
- const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request) : config.trustedProviders ?? [];
12462
+ async function resolveTrustedProviders(config, request2) {
12463
+ const configured = typeof config.trustedProviders === "function" ? await config.trustedProviders(request2) : config.trustedProviders ?? [];
11048
12464
  const values = [
11049
12465
  ...Object.keys(config.socialProviders ?? {}),
11050
12466
  ...configured
@@ -11169,9 +12585,9 @@ function athenaAuth(config) {
11169
12585
  }
11170
12586
  return ctx;
11171
12587
  };
11172
- const resolveRequestContext = async (request) => {
11173
- const requestUrl = getRequestUrl(request);
11174
- const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request);
12588
+ const resolveRequestContext = async (request2) => {
12589
+ const requestUrl = getRequestUrl(request2);
12590
+ const resolvedBaseURL = resolveRequestBaseURL(config.baseURL, request2);
11175
12591
  if (!resolvedBaseURL) {
11176
12592
  throw new Error(
11177
12593
  isDynamicBaseURLConfig2(config.baseURL) ? "Could not resolve base URL from request. Check allowedHosts/baseURL." : "Could not resolve base URL from request."
@@ -11182,17 +12598,17 @@ function athenaAuth(config) {
11182
12598
  session: config.session,
11183
12599
  advanced: config.advanced
11184
12600
  });
11185
- const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request);
11186
- const trustedProviders = await resolveTrustedProviders(config, request);
12601
+ const trustedOrigins = await resolveTrustedOrigins(config, resolvedBaseURL, request2);
12602
+ const trustedProviders = await resolveTrustedProviders(config, request2);
11187
12603
  return {
11188
12604
  auth,
11189
- request,
12605
+ request: request2,
11190
12606
  url: requestUrl,
11191
12607
  path: requestUrl.pathname,
11192
12608
  basePath: normalizedBasePath,
11193
12609
  baseURL: resolvedBaseURL,
11194
12610
  origin: getOrigin(resolvedBaseURL) ?? resolvedBaseURL,
11195
- headers: request.headers,
12611
+ headers: request2.headers,
11196
12612
  cookies: requestCookies,
11197
12613
  trustedOrigins,
11198
12614
  trustedProviders,
@@ -11205,8 +12621,8 @@ function athenaAuth(config) {
11205
12621
  socialProviders: auth.socialProviders
11206
12622
  };
11207
12623
  };
11208
- const handler = async (request) => {
11209
- const requestContext = await resolveRequestContext(request);
12624
+ const handler = async (request2) => {
12625
+ const requestContext = await resolveRequestContext(request2);
11210
12626
  if (typeof config.handler !== "function") {
11211
12627
  return createJsonResponse(
11212
12628
  {
@@ -11227,7 +12643,7 @@ function athenaAuth(config) {
11227
12643
  const responseHeaders = new Headers(response.headers);
11228
12644
  await runAfterHooks({
11229
12645
  path: requestContext.path,
11230
- headers: request.headers,
12646
+ headers: request2.headers,
11231
12647
  context: {
11232
12648
  responseHeaders,
11233
12649
  returned: result.returned,
@@ -11303,7 +12719,13 @@ function athenaAuth(config) {
11303
12719
  return auth;
11304
12720
  }
11305
12721
 
12722
+ exports.ATHENA_AUTH_ADMIN_LIMITS = ATHENA_AUTH_ADMIN_LIMITS;
11306
12723
  exports.ATHENA_AUTH_BASE_ERROR_CODES = ATHENA_AUTH_BASE_ERROR_CODES;
12724
+ exports.ATHENA_AUTH_MAX_ADMIN_JSON_BYTES = ATHENA_AUTH_MAX_ADMIN_JSON_BYTES;
12725
+ exports.ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH = ATHENA_AUTH_MAX_ADMIN_JSON_DEPTH;
12726
+ exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = ATHENA_AUTH_MAX_TEMPLATE_VARIABLES;
12727
+ exports.ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH;
12728
+ exports.AthenaChatError = AthenaChatError;
11307
12729
  exports.AthenaClient = AthenaClient;
11308
12730
  exports.AthenaError = AthenaError;
11309
12731
  exports.AthenaErrorCategory = AthenaErrorCategory;
@@ -11317,6 +12739,7 @@ exports.DEFAULT_POSTGRES_SCHEMAS = DEFAULT_POSTGRES_SCHEMAS;
11317
12739
  exports.assertInt = assertInt;
11318
12740
  exports.athenaAuth = athenaAuth;
11319
12741
  exports.boolean = boolean;
12742
+ exports.chatSdkManifest = chatSdkManifest;
11320
12743
  exports.coerceInt = coerceInt;
11321
12744
  exports.createAthenaStorageError = createAthenaStorageError;
11322
12745
  exports.createAuthClient = createAuthClient;
@@ -11333,6 +12756,7 @@ exports.defineModel = defineModel;
11333
12756
  exports.defineRegistry = defineRegistry;
11334
12757
  exports.defineSchema = defineSchema;
11335
12758
  exports.enumeration = enumeration;
12759
+ exports.filterIntrospectionSnapshot = filterIntrospectionSnapshot;
11336
12760
  exports.findGeneratorConfigPath = findGeneratorConfigPath;
11337
12761
  exports.generateArtifactsFromSnapshot = generateArtifactsFromSnapshot;
11338
12762
  exports.generatorEnv = generatorEnv;
@@ -11346,6 +12770,7 @@ exports.normalizeAthenaError = normalizeAthenaError;
11346
12770
  exports.normalizeAthenaGatewayBaseUrl = normalizeAthenaGatewayBaseUrl;
11347
12771
  exports.normalizeGeneratorConfig = normalizeGeneratorConfig;
11348
12772
  exports.normalizeSchemaSelection = normalizeSchemaSelection;
12773
+ exports.normalizeTableSelection = normalizeTableSelection;
11349
12774
  exports.number = number;
11350
12775
  exports.parseBooleanFlag = parseBooleanFlag2;
11351
12776
  exports.renderAthenaReactEmail = renderAthenaReactEmail;
@@ -11361,6 +12786,8 @@ exports.table = table;
11361
12786
  exports.toModelFormDefaults = toModelFormDefaults;
11362
12787
  exports.toModelPayload = toModelPayload;
11363
12788
  exports.unwrap = unwrap;
12789
+ exports.unwrapChatMessage = unwrapChatMessage;
12790
+ exports.unwrapChatRoom = unwrapChatRoom;
11364
12791
  exports.unwrapOne = unwrapOne;
11365
12792
  exports.unwrapRows = unwrapRows;
11366
12793
  exports.verifyAthenaGatewayUrl = verifyAthenaGatewayUrl;