@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
@@ -688,6 +688,77 @@ function resolveProviderSchemas(providerConfig) {
688
688
  return [...DEFAULT_POSTGRES_SCHEMAS];
689
689
  }
690
690
 
691
+ // src/generator/table-selection.ts
692
+ function normalizeTableSelector(value) {
693
+ const trimmed = value.trim();
694
+ return trimmed.length > 0 ? trimmed : void 0;
695
+ }
696
+ function normalizeTableSelection(value) {
697
+ if (typeof value === "string") {
698
+ return Array.from(
699
+ new Set(
700
+ value.split(",").map(normalizeTableSelector).filter((entry) => Boolean(entry))
701
+ )
702
+ );
703
+ }
704
+ if (Array.isArray(value)) {
705
+ return Array.from(
706
+ new Set(
707
+ value.map((entry) => typeof entry === "string" ? normalizeTableSelector(entry) : void 0).filter((entry) => Boolean(entry))
708
+ )
709
+ );
710
+ }
711
+ return [];
712
+ }
713
+ function matchesTableSelector(schemaName, tableName, selector) {
714
+ const separatorIndex = selector.indexOf(".");
715
+ if (separatorIndex < 0) {
716
+ return tableName === selector;
717
+ }
718
+ const selectorSchema = selector.slice(0, separatorIndex).trim();
719
+ const selectorTable = selector.slice(separatorIndex + 1).trim();
720
+ return selectorSchema === schemaName && selectorTable === tableName;
721
+ }
722
+ function shouldKeepTable(schemaName, tableName, filter) {
723
+ const included = filter.includeTables.length === 0 || filter.includeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
724
+ if (!included) {
725
+ return false;
726
+ }
727
+ return !filter.excludeTables.some((selector) => matchesTableSelector(schemaName, tableName, selector));
728
+ }
729
+ function hasTableFilters(filter) {
730
+ return filter.includeTables.length > 0 || filter.excludeTables.length > 0;
731
+ }
732
+ function filterIntrospectionSnapshot(snapshot, filter) {
733
+ if (!hasTableFilters(filter)) {
734
+ return snapshot;
735
+ }
736
+ const schemas = {};
737
+ for (const [schemaName, schema] of Object.entries(snapshot.schemas)) {
738
+ const tables = Object.fromEntries(
739
+ Object.entries(schema.tables).filter(([tableName]) => shouldKeepTable(schemaName, tableName, filter))
740
+ );
741
+ if (Object.keys(tables).length === 0) {
742
+ continue;
743
+ }
744
+ schemas[schemaName] = {
745
+ ...schema,
746
+ tables
747
+ };
748
+ }
749
+ if (Object.keys(schemas).length === 0) {
750
+ const includeLabel = filter.includeTables.length > 0 ? ` includeTables=${filter.includeTables.join(", ")}` : "";
751
+ const excludeLabel = filter.excludeTables.length > 0 ? ` excludeTables=${filter.excludeTables.join(", ")}` : "";
752
+ throw new Error(
753
+ `Generator table filters matched no tables after schema selection.${includeLabel}${excludeLabel}`
754
+ );
755
+ }
756
+ return {
757
+ ...snapshot,
758
+ schemas
759
+ };
760
+ }
761
+
691
762
  // src/generator/config.ts
692
763
  var POSTGRES_PROTOCOLS = /* @__PURE__ */ new Set(["postgres:", "postgresql:"]);
693
764
  var DEFAULT_CONFIG_CANDIDATES = [
@@ -698,13 +769,20 @@ var DEFAULT_CONFIG_CANDIDATES = [
698
769
  ".athena.config.ts",
699
770
  ".athena.config.js"
700
771
  ];
701
- var DEFAULT_TARGETS = {
772
+ var LEGACY_DEFAULT_TARGETS = {
702
773
  model: "athena/models/{schema_kebab}/{model_kebab}.ts",
703
774
  schema: "athena/schemas/{schema_kebab}.ts",
704
775
  database: "athena/relations.ts",
705
776
  registry: "athena/config.ts"
706
777
  };
707
- var DEFAULT_OUTPUT_FORMAT = "define-model";
778
+ var ATHENA_DIRECT_TARGETS = {
779
+ model: "athena/models/{schema_kebab}/{model_kebab}.ts",
780
+ schema: "athena/schemas/{schema_kebab}.ts",
781
+ database: "athena/relations.ts",
782
+ registry: "athena/registry.generated.ts"
783
+ };
784
+ var DEFAULT_OUTPUT_FORMAT = "table-builder";
785
+ var DEFAULT_OUTPUT_PRESET = "athena-direct";
708
786
  var DEFAULT_NAMING = {
709
787
  modelType: "pascal",
710
788
  modelConst: "camel",
@@ -723,6 +801,10 @@ var DEFAULT_EXPERIMENTAL_FLAGS = {
723
801
  var DEFAULT_INTERNAL_CONFIG = {
724
802
  schemaVersion: 1
725
803
  };
804
+ var DEFAULT_FILTER_CONFIG = {
805
+ includeTables: [],
806
+ excludeTables: []
807
+ };
726
808
  var PROJECT_ENV_FILENAMES = [".env", ".env.local"];
727
809
  var DIRECT_CONNECTION_STRING_ENV_KEYS = [
728
810
  "ATHENA_GENERATOR_PG_URL",
@@ -741,10 +823,13 @@ var GATEWAY_API_KEY_ENV_KEYS = [
741
823
  ];
742
824
  var GENERATOR_SCHEMA_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMAS"];
743
825
  var OUTPUT_FORMAT_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_FORMAT"];
826
+ var OUTPUT_PRESET_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_PRESET"];
744
827
  var MODEL_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TARGET"];
745
828
  var SCHEMA_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_TARGET"];
746
829
  var DATABASE_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_TARGET"];
747
830
  var REGISTRY_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_TARGET"];
831
+ var TABLES_ENV_KEYS = ["ATHENA_GENERATOR_TABLES"];
832
+ var EXCLUDE_TABLES_ENV_KEYS = ["ATHENA_GENERATOR_EXCLUDE_TABLES"];
748
833
  var PLACEHOLDER_MAP_ENV_KEYS = ["ATHENA_GENERATOR_PLACEHOLDER_MAP"];
749
834
  var MODEL_TYPE_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TYPE", "ATHENA_GENERATOR_MODEL_STYLE"];
750
835
  var MODEL_CONST_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_CONST"];
@@ -759,7 +844,12 @@ var SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS = ["ATHENA_GENERATOR_SCYLLA_PROVIDER_CONT
759
844
  var ENV_ONLY_CONFIG_PATH = "[environment defaults]";
760
845
  var NAMING_STYLE_VALUES = ["preserve", "camel", "pascal", "snake", "kebab"];
761
846
  var OUTPUT_FORMAT_VALUES = ["define-model", "table-builder"];
847
+ var OUTPUT_PRESET_VALUES = ["legacy", "athena-direct"];
762
848
  var BACKEND_TYPE_VALUES = ["athena", "postgrest", "postgresql", "scylladb"];
849
+ var OUTPUT_PRESET_TARGETS = {
850
+ legacy: LEGACY_DEFAULT_TARGETS,
851
+ "athena-direct": ATHENA_DIRECT_TARGETS
852
+ };
763
853
  function normalizeRawEnvValue(rawValue) {
764
854
  if (rawValue.startsWith('"') && rawValue.endsWith('"') && rawValue.length >= 2) {
765
855
  const inner = rawValue.slice(1, -1);
@@ -966,11 +1056,19 @@ function normalizeExperimentalFlags(input) {
966
1056
  )
967
1057
  };
968
1058
  }
1059
+ function normalizeFilterConfig(input) {
1060
+ return {
1061
+ includeTables: normalizeTableSelection(input?.includeTables),
1062
+ excludeTables: normalizeTableSelection(input?.excludeTables)
1063
+ };
1064
+ }
969
1065
  function normalizeOutputConfig(output) {
1066
+ const preset = output?.preset ?? DEFAULT_OUTPUT_PRESET;
970
1067
  return {
971
1068
  format: output?.format ?? DEFAULT_OUTPUT_FORMAT,
1069
+ preset,
972
1070
  targets: {
973
- ...DEFAULT_TARGETS,
1071
+ ...OUTPUT_PRESET_TARGETS[preset],
974
1072
  ...output?.targets ?? {}
975
1073
  },
976
1074
  placeholderMap: {
@@ -1050,6 +1148,10 @@ function normalizeGeneratorConfig(input) {
1050
1148
  ...DEFAULT_NAMING,
1051
1149
  ...input.naming ?? {}
1052
1150
  },
1151
+ filter: {
1152
+ ...DEFAULT_FILTER_CONFIG,
1153
+ ...normalizeFilterConfig(input.filter)
1154
+ },
1053
1155
  features: normalizeFeatureFlags(input.features),
1054
1156
  experimental: normalizeExperimentalFlags(input.experimental),
1055
1157
  internal: {
@@ -1110,16 +1212,18 @@ function importConfigModule(moduleSpecifier) {
1110
1212
  }
1111
1213
  function buildEnvironmentOutputConfig() {
1112
1214
  const format = resolveOptionalOneOf(OUTPUT_FORMAT_ENV_KEYS, OUTPUT_FORMAT_VALUES);
1215
+ const preset = resolveOptionalOneOf(OUTPUT_PRESET_ENV_KEYS, OUTPUT_PRESET_VALUES);
1113
1216
  const modelTarget = resolveFallbackValue(MODEL_TARGET_ENV_KEYS);
1114
1217
  const schemaTarget = resolveFallbackValue(SCHEMA_TARGET_ENV_KEYS);
1115
1218
  const databaseTarget = resolveFallbackValue(DATABASE_TARGET_ENV_KEYS);
1116
1219
  const registryTarget = resolveFallbackValue(REGISTRY_TARGET_ENV_KEYS);
1117
1220
  const placeholderMap = resolveOptionalJson(PLACEHOLDER_MAP_ENV_KEYS);
1118
- if (format === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
1221
+ if (format === void 0 && preset === void 0 && modelTarget === void 0 && schemaTarget === void 0 && databaseTarget === void 0 && registryTarget === void 0 && placeholderMap === void 0) {
1119
1222
  return void 0;
1120
1223
  }
1121
1224
  return {
1122
1225
  format,
1226
+ preset,
1123
1227
  targets: {
1124
1228
  ...modelTarget ? { model: modelTarget } : {},
1125
1229
  ...schemaTarget ? { schema: schemaTarget } : {},
@@ -1129,6 +1233,17 @@ function buildEnvironmentOutputConfig() {
1129
1233
  placeholderMap
1130
1234
  };
1131
1235
  }
1236
+ function buildEnvironmentFilterConfig() {
1237
+ const includeTables = resolveFallbackValue(TABLES_ENV_KEYS);
1238
+ const excludeTables = resolveFallbackValue(EXCLUDE_TABLES_ENV_KEYS);
1239
+ if (includeTables === void 0 && excludeTables === void 0) {
1240
+ return void 0;
1241
+ }
1242
+ return {
1243
+ ...includeTables !== void 0 ? { includeTables } : {},
1244
+ ...excludeTables !== void 0 ? { excludeTables } : {}
1245
+ };
1246
+ }
1132
1247
  function buildEnvironmentNamingConfig() {
1133
1248
  const modelType = resolveOptionalOneOf(MODEL_TYPE_ENV_KEYS, NAMING_STYLE_VALUES);
1134
1249
  const modelConst = resolveOptionalOneOf(MODEL_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
@@ -1204,6 +1319,7 @@ function createEnvironmentGeneratorConfig() {
1204
1319
  provider,
1205
1320
  output: buildEnvironmentOutputConfig(),
1206
1321
  naming: buildEnvironmentNamingConfig(),
1322
+ filter: buildEnvironmentFilterConfig(),
1207
1323
  features: buildEnvironmentFeatureFlags(),
1208
1324
  experimental: buildEnvironmentExperimentalFlags()
1209
1325
  };
@@ -1365,7 +1481,7 @@ ${schemaEntries}
1365
1481
  content
1366
1482
  };
1367
1483
  }
1368
- function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputFormat, schemaVersion) {
1484
+ function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputPreset, outputFormat, schemaVersion) {
1369
1485
  const databaseImportPath = toModuleImportPath(registryPath, databasePath);
1370
1486
  const content = `import { defineRegistry } from '@xylex-group/athena'
1371
1487
  import { ${databaseConstName} } from '${databaseImportPath}'
@@ -1374,6 +1490,7 @@ export const __athena_schema_meta = {
1374
1490
  schemaVersion: ${schemaVersion},
1375
1491
  generatedAt: ${escapeStringLiteral(generatedAt)},
1376
1492
  database: ${escapeStringLiteral(databaseName)},
1493
+ outputPreset: ${escapeStringLiteral(outputPreset)},
1377
1494
  outputFormat: ${escapeStringLiteral(outputFormat)},
1378
1495
  } as const
1379
1496
 
@@ -1543,6 +1660,7 @@ function composeGeneratorArtifacts(input) {
1543
1660
  toSafeIdentifier("registry", config.naming.registryConst, "registry"),
1544
1661
  databaseName,
1545
1662
  snapshot.generatedAt,
1663
+ config.output.preset,
1546
1664
  config.output.format,
1547
1665
  config.internal.schemaVersion
1548
1666
  )
@@ -1648,7 +1766,7 @@ export const ${descriptor.tableConstName} = table(${escapeStringLiteral(descript
1648
1766
  .columns({
1649
1767
  ${columnLines}
1650
1768
  })
1651
- .primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})
1769
+ ${descriptor.table.primaryKey.length > 0 ? `.primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})` : ".withoutPrimaryKey()"}
1652
1770
  ${relationsAssignment ? `${relationsAssignment}` : ""}
1653
1771
  export type ${descriptor.rowTypeName} = RowOf<typeof ${descriptor.tableConstName}>
1654
1772
  export type ${descriptor.insertTypeName} = InsertOf<typeof ${descriptor.tableConstName}>
@@ -1745,11 +1863,12 @@ ${nullableLines}
1745
1863
  }
1746
1864
  function generateArtifactsFromSnapshot(snapshot, config) {
1747
1865
  const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
1866
+ const filteredSnapshot = filterIntrospectionSnapshot(snapshot, normalizedConfig.filter);
1748
1867
  if (normalizedConfig.output.format === "table-builder") {
1749
- return generateTableBuilderArtifactsFromSnapshot(snapshot, normalizedConfig);
1868
+ return generateTableBuilderArtifactsFromSnapshot(filteredSnapshot, normalizedConfig);
1750
1869
  }
1751
1870
  return composeGeneratorArtifacts({
1752
- snapshot,
1871
+ snapshot: filteredSnapshot,
1753
1872
  config: normalizedConfig,
1754
1873
  createModelDescriptor({ providerName, databaseName, schemaName, tableName, table }) {
1755
1874
  const modelConstName = toSafeIdentifier(
@@ -1779,7 +1898,7 @@ function generateArtifactsFromSnapshot(snapshot, config) {
1779
1898
  table
1780
1899
  };
1781
1900
  },
1782
- renderModelArtifact: (descriptor) => renderModelArtifact2(snapshot.database, descriptor, normalizedConfig)
1901
+ renderModelArtifact: (descriptor) => renderModelArtifact2(filteredSnapshot.database, descriptor, normalizedConfig)
1783
1902
  });
1784
1903
  }
1785
1904
 
@@ -1861,8 +1980,8 @@ function parseCookies(cookieHeader) {
1861
1980
  });
1862
1981
  return cookieMap;
1863
1982
  }
1864
- var getSessionCookie = (request, config) => {
1865
- const cookies = (request instanceof Headers || !("headers" in request) ? request : request.headers).get("cookie");
1983
+ var getSessionCookie = (request2, config) => {
1984
+ const cookies = (request2 instanceof Headers || !("headers" in request2) ? request2 : request2.headers).get("cookie");
1866
1985
  if (!cookies) {
1867
1986
  return null;
1868
1987
  }
@@ -1885,7 +2004,7 @@ var getSessionCookie = (request, config) => {
1885
2004
 
1886
2005
  // package.json
1887
2006
  var package_default = {
1888
- version: "2.8.2"
2007
+ version: "2.10.0"
1889
2008
  };
1890
2009
 
1891
2010
  // src/sdk-version.ts
@@ -1898,6 +2017,7 @@ function buildSdkHeaderValue(sdkName) {
1898
2017
  var DEFAULT_CLIENT = "railway_direct";
1899
2018
  var SDK_NAME = "xylex-group/athena";
1900
2019
  var SDK_HEADER_VALUE = buildSdkHeaderValue(SDK_NAME);
2020
+ var NO_CACHE_HEADER_VALUE = "no-cache";
1901
2021
  function parseResponseBody(rawText, contentType) {
1902
2022
  if (!rawText) {
1903
2023
  return { parsed: null, parseFailed: false };
@@ -1916,6 +2036,9 @@ function parseResponseBody(rawText, contentType) {
1916
2036
  function normalizeHeaderValue(value) {
1917
2037
  return value ? value : void 0;
1918
2038
  }
2039
+ function isCacheControlHeaderName(name) {
2040
+ return name.toLowerCase() === "cache-control";
2041
+ }
1919
2042
  function resolveHeaderValue(headers, candidates) {
1920
2043
  for (const candidate of candidates) {
1921
2044
  const direct = normalizeHeaderValue(headers[candidate]);
@@ -2074,6 +2197,7 @@ function buildRpcGetEndpoint(payload) {
2074
2197
  }
2075
2198
  function buildHeaders(config, options) {
2076
2199
  const mergedStripNulls = options?.stripNulls ?? true;
2200
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
2077
2201
  const extraHeaders = {
2078
2202
  ...config.headers ?? {},
2079
2203
  ...options?.headers ?? {}
@@ -2127,11 +2251,15 @@ function buildHeaders(config, options) {
2127
2251
  const athenaClientKeys = ["x-athena-client", "X-Athena-Client"];
2128
2252
  Object.entries(extraHeaders).forEach(([key, value]) => {
2129
2253
  if (athenaClientKeys.includes(key)) return;
2254
+ if (forceNoCache && isCacheControlHeaderName(key)) return;
2130
2255
  const normalized = normalizeHeaderValue(value);
2131
2256
  if (normalized) {
2132
2257
  headers[key] = normalized;
2133
2258
  }
2134
2259
  });
2260
+ if (forceNoCache) {
2261
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE;
2262
+ }
2135
2263
  return headers;
2136
2264
  }
2137
2265
  function toInvalidUrlResponse(error, endpoint, method) {
@@ -2571,6 +2699,35 @@ function quoteSelectColumnsExpression(columns) {
2571
2699
  }
2572
2700
  return tokens.map(quoteSelectToken).join(", ");
2573
2701
  }
2702
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLES = 64;
2703
+ var ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH = 128;
2704
+ function describeTemplateVariableTarget(target) {
2705
+ const normalized = target?.trim();
2706
+ return normalized && normalized.length > 0 ? normalized : "Athena auth admin email template variables";
2707
+ }
2708
+ function assertAthenaAuthTemplateVariables(variables, target) {
2709
+ const label = describeTemplateVariableTarget(target);
2710
+ if (!Array.isArray(variables)) {
2711
+ throw new Error(`${label} must be an array of strings.`);
2712
+ }
2713
+ if (variables.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLES) {
2714
+ throw new Error(
2715
+ `${label} cannot contain more than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLES} entries.`
2716
+ );
2717
+ }
2718
+ variables.forEach((variable, index) => {
2719
+ if (typeof variable !== "string") {
2720
+ throw new Error(
2721
+ `${label} must contain only strings. Received ${typeof variable} at index ${index}.`
2722
+ );
2723
+ }
2724
+ if (variable.length > ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH) {
2725
+ throw new Error(
2726
+ `${label} cannot contain entries longer than ${ATHENA_AUTH_MAX_TEMPLATE_VARIABLE_LENGTH} characters. Received ${variable.length} characters at index ${index}.`
2727
+ );
2728
+ }
2729
+ });
2730
+ }
2574
2731
 
2575
2732
  // src/auth/react-email.ts
2576
2733
  var reactEmailRenderModulePromise;
@@ -2760,6 +2917,7 @@ async function resolveReactEmailPayloadFields(input, fields, options) {
2760
2917
  var DEFAULT_AUTH_BASE_URL = "http://localhost:3001/api/auth";
2761
2918
  var SDK_NAME2 = "xylex-group/athena-auth";
2762
2919
  var SDK_HEADER_VALUE2 = buildSdkHeaderValue(SDK_NAME2);
2920
+ var NO_CACHE_HEADER_VALUE2 = "no-cache";
2763
2921
  function normalizeBaseUrl(baseUrl) {
2764
2922
  return (baseUrl ?? DEFAULT_AUTH_BASE_URL).replace(/\/$/, "");
2765
2923
  }
@@ -2769,6 +2927,9 @@ function isRecord4(value) {
2769
2927
  function normalizeHeaderValue2(value) {
2770
2928
  return value ? value : void 0;
2771
2929
  }
2930
+ function isCacheControlHeaderName2(name) {
2931
+ return name.toLowerCase() === "cache-control";
2932
+ }
2772
2933
  function parseResponseBody2(rawText, contentType) {
2773
2934
  if (!rawText) {
2774
2935
  return { parsed: null, parseFailed: false };
@@ -2824,6 +2985,98 @@ function mergeCallOptions(base, override) {
2824
2985
  }
2825
2986
  };
2826
2987
  }
2988
+ function copyDefinedField(target, source, targetKey, sourceKey) {
2989
+ if (!(sourceKey in source)) {
2990
+ return;
2991
+ }
2992
+ const value = source[sourceKey];
2993
+ if (value !== void 0) {
2994
+ target[targetKey] = value;
2995
+ }
2996
+ }
2997
+ function normalizeAdminEmailTemplatePayload(payload) {
2998
+ const normalized = { ...payload };
2999
+ copyDefinedField(normalized, payload, "template_key", "templateKey");
3000
+ copyDefinedField(normalized, payload, "event_type", "eventType");
3001
+ copyDefinedField(normalized, payload, "subject_template", "subjectTemplate");
3002
+ copyDefinedField(normalized, payload, "text_template", "textTemplate");
3003
+ copyDefinedField(normalized, payload, "html_template", "htmlTemplate");
3004
+ copyDefinedField(normalized, payload, "variable_bindings", "variableBindings");
3005
+ copyDefinedField(normalized, payload, "attachment_failure_mode", "attachmentFailureMode");
3006
+ copyDefinedField(normalized, payload, "is_active", "isActive");
3007
+ return normalized;
3008
+ }
3009
+ function toReactEmailTemplateCompatibilityInput(input) {
3010
+ const payload = input;
3011
+ const compatibility = { ...payload };
3012
+ copyDefinedField(compatibility, payload, "templateKey", "template_key");
3013
+ copyDefinedField(compatibility, payload, "eventType", "event_type");
3014
+ copyDefinedField(compatibility, payload, "subjectTemplate", "subject_template");
3015
+ copyDefinedField(compatibility, payload, "textTemplate", "text_template");
3016
+ copyDefinedField(compatibility, payload, "htmlTemplate", "html_template");
3017
+ copyDefinedField(compatibility, payload, "variableBindings", "variable_bindings");
3018
+ copyDefinedField(compatibility, payload, "attachmentFailureMode", "attachment_failure_mode");
3019
+ copyDefinedField(compatibility, payload, "isActive", "is_active");
3020
+ return compatibility;
3021
+ }
3022
+ function normalizeAdminEmailTemplateSendPayload(payload) {
3023
+ const normalized = { ...payload };
3024
+ copyDefinedField(normalized, payload, "template_id", "templateId");
3025
+ copyDefinedField(normalized, payload, "recipient_email", "recipientEmail");
3026
+ copyDefinedField(normalized, payload, "render_variables", "renderVariables");
3027
+ copyDefinedField(normalized, payload, "user_id", "userId");
3028
+ copyDefinedField(normalized, payload, "organization_id", "organizationId");
3029
+ copyDefinedField(normalized, payload, "session_token", "sessionToken");
3030
+ return normalized;
3031
+ }
3032
+ function toSessionGuardFailure(sessionResult) {
3033
+ if (sessionResult.status === 401 || sessionResult.data == null) {
3034
+ return {
3035
+ ok: false,
3036
+ reason: "unauthorized",
3037
+ status: 401,
3038
+ error: sessionResult.error ?? "Unauthorized",
3039
+ sessionResult
3040
+ };
3041
+ }
3042
+ return {
3043
+ ok: false,
3044
+ reason: "upstream_error",
3045
+ status: sessionResult.status,
3046
+ error: sessionResult.error ?? "Failed to resolve current session",
3047
+ sessionResult
3048
+ };
3049
+ }
3050
+ function toPermissionGuardFailure(permissionResult, sessionResult) {
3051
+ if (permissionResult.status === 401) {
3052
+ return {
3053
+ ok: false,
3054
+ reason: "unauthorized",
3055
+ status: 401,
3056
+ error: permissionResult.error ?? "Unauthorized",
3057
+ sessionResult,
3058
+ permissionResult
3059
+ };
3060
+ }
3061
+ if (permissionResult.status === 403) {
3062
+ return {
3063
+ ok: false,
3064
+ reason: "forbidden",
3065
+ status: 403,
3066
+ error: permissionResult.error ?? "Forbidden",
3067
+ sessionResult,
3068
+ permissionResult
3069
+ };
3070
+ }
3071
+ return {
3072
+ ok: false,
3073
+ reason: "upstream_error",
3074
+ status: permissionResult.status,
3075
+ error: permissionResult.error ?? "Failed to resolve permission check",
3076
+ sessionResult,
3077
+ permissionResult
3078
+ };
3079
+ }
2827
3080
  function extractFetchOptions(input) {
2828
3081
  if (!input) {
2829
3082
  return {
@@ -2839,6 +3092,7 @@ function extractFetchOptions(input) {
2839
3092
  };
2840
3093
  }
2841
3094
  function buildHeaders2(config, options) {
3095
+ const forceNoCache = Boolean(config.forceNoCache || options?.forceNoCache);
2842
3096
  const headers = {
2843
3097
  "Content-Type": "application/json",
2844
3098
  "X-Athena-Sdk": SDK_HEADER_VALUE2
@@ -2852,16 +3106,30 @@ function buildHeaders2(config, options) {
2852
3106
  if (bearerToken) {
2853
3107
  headers.Authorization = `Bearer ${bearerToken}`;
2854
3108
  }
3109
+ const cookie = options?.cookie ?? config.cookie;
3110
+ if (cookie) {
3111
+ headers.Cookie = cookie;
3112
+ }
3113
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
3114
+ if (sessionToken) {
3115
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
3116
+ }
2855
3117
  const mergedExtraHeaders = {
2856
3118
  ...config.headers ?? {},
2857
3119
  ...options?.headers ?? {}
2858
3120
  };
2859
3121
  Object.entries(mergedExtraHeaders).forEach(([key, value]) => {
3122
+ if (forceNoCache && isCacheControlHeaderName2(key)) {
3123
+ return;
3124
+ }
2860
3125
  const normalized = normalizeHeaderValue2(value);
2861
3126
  if (normalized) {
2862
3127
  headers[key] = normalized;
2863
3128
  }
2864
3129
  });
3130
+ if (forceNoCache) {
3131
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE2;
3132
+ }
2865
3133
  return headers;
2866
3134
  }
2867
3135
  function appendQueryParam(searchParams, key, value) {
@@ -3067,7 +3335,7 @@ function createAuthClient(config = {}) {
3067
3335
  ...config,
3068
3336
  baseUrl: normalizedBaseUrl
3069
3337
  };
3070
- const request = (input, options) => {
3338
+ const request2 = (input, options) => {
3071
3339
  const method = input.method ?? (input.body !== void 0 ? "POST" : inferDefaultMethod(input.endpoint));
3072
3340
  const mergedOptions = mergeCallOptions(input.fetchOptions, options);
3073
3341
  return callAuthEndpoint(
@@ -3080,7 +3348,7 @@ function createAuthClient(config = {}) {
3080
3348
  };
3081
3349
  const postGeneric = (endpoint, input, options) => {
3082
3350
  const { payload, fetchOptions } = extractFetchOptions(input);
3083
- return request(
3351
+ return request2(
3084
3352
  {
3085
3353
  endpoint,
3086
3354
  method: "POST",
@@ -3092,7 +3360,7 @@ function createAuthClient(config = {}) {
3092
3360
  };
3093
3361
  const getGeneric = (endpoint, input, options) => {
3094
3362
  const { fetchOptions } = extractFetchOptions(input);
3095
- return request(
3363
+ return request2(
3096
3364
  {
3097
3365
  endpoint,
3098
3366
  method: "GET",
@@ -3104,7 +3372,7 @@ function createAuthClient(config = {}) {
3104
3372
  const getWithQuery = (endpoint, input, options) => {
3105
3373
  const { payload, fetchOptions } = extractFetchOptions(input);
3106
3374
  const query = payload?.query;
3107
- return request(
3375
+ return request2(
3108
3376
  {
3109
3377
  endpoint,
3110
3378
  method: "GET",
@@ -3122,11 +3390,96 @@ function createAuthClient(config = {}) {
3122
3390
  htmlField: "htmlBody",
3123
3391
  textField: "textBody"
3124
3392
  }, withReactEmailRoute(route));
3125
- const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(input, {
3393
+ const resolveAdminEmailTemplatePayload = (route, input) => resolveReactEmailPayloadFields(toReactEmailTemplateCompatibilityInput(input), {
3126
3394
  htmlField: "htmlTemplate",
3127
3395
  textField: "textTemplate",
3128
3396
  variablesField: "variables"
3129
- }, withReactEmailRoute(route));
3397
+ }, withReactEmailRoute(route)).then((payload) => {
3398
+ const normalizedPayload = normalizeAdminEmailTemplatePayload(payload);
3399
+ if ("variables" in payload && payload.variables !== void 0 && payload.variables !== null) {
3400
+ assertAthenaAuthTemplateVariables(
3401
+ payload.variables,
3402
+ `${route} variables`
3403
+ );
3404
+ }
3405
+ return normalizedPayload;
3406
+ });
3407
+ const requireSession = async (input, options) => {
3408
+ const sessionInput = input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0;
3409
+ const sessionResult = await getGeneric(
3410
+ "/get-session",
3411
+ sessionInput,
3412
+ options
3413
+ );
3414
+ if (!sessionResult.ok || sessionResult.data == null) {
3415
+ return toSessionGuardFailure(sessionResult);
3416
+ }
3417
+ return {
3418
+ ok: true,
3419
+ session: sessionResult.data
3420
+ };
3421
+ };
3422
+ const getUser = async (input, options) => {
3423
+ const sessionResult = await getGeneric(
3424
+ "/get-session",
3425
+ input,
3426
+ options
3427
+ );
3428
+ if (!sessionResult.ok) {
3429
+ return {
3430
+ ...sessionResult,
3431
+ data: null
3432
+ };
3433
+ }
3434
+ return {
3435
+ ...sessionResult,
3436
+ data: {
3437
+ user: sessionResult.data?.user ?? null
3438
+ }
3439
+ };
3440
+ };
3441
+ const requirePermission = async (endpoint, input, options) => {
3442
+ const sessionGuard = await requireSession(
3443
+ input?.fetchOptions ? { fetchOptions: input.fetchOptions } : void 0,
3444
+ options
3445
+ );
3446
+ if (!sessionGuard.ok) {
3447
+ return sessionGuard;
3448
+ }
3449
+ const permissionResult = await postGeneric(
3450
+ endpoint,
3451
+ input,
3452
+ options
3453
+ );
3454
+ if (!permissionResult.ok) {
3455
+ return toPermissionGuardFailure(permissionResult, {
3456
+ ok: true,
3457
+ status: 200,
3458
+ data: sessionGuard.session,
3459
+ error: null,
3460
+ errorDetails: null,
3461
+ raw: sessionGuard.session
3462
+ });
3463
+ }
3464
+ if (!permissionResult.data?.success) {
3465
+ return {
3466
+ ok: false,
3467
+ reason: "forbidden",
3468
+ status: 403,
3469
+ error: permissionResult.data?.error ?? "Forbidden",
3470
+ sessionResult: {
3471
+ ok: true,
3472
+ status: 200,
3473
+ data: sessionGuard.session,
3474
+ error: null,
3475
+ errorDetails: null,
3476
+ raw: sessionGuard.session
3477
+ },
3478
+ permissionResult
3479
+ };
3480
+ }
3481
+ return sessionGuard;
3482
+ };
3130
3483
  const listUserEmailsWithFallback = async (input, options) => {
3131
3484
  const primary = await getWithQuery(
3132
3485
  "/email/list",
@@ -3288,6 +3641,7 @@ function createAuthClient(config = {}) {
3288
3641
  input,
3289
3642
  options
3290
3643
  ),
3644
+ requirePermission: (input, options) => requirePermission("/organization/has-permission", input, options),
3291
3645
  invitation: {
3292
3646
  cancel: (input, options) => executePostWithCompatibleInput(
3293
3647
  resolvedConfig,
@@ -3483,6 +3837,8 @@ function createAuthClient(config = {}) {
3483
3837
  };
3484
3838
  const auth = {
3485
3839
  getSession: (input, options) => getGeneric("/get-session", input, options),
3840
+ getUser,
3841
+ requireSession,
3486
3842
  signOut,
3487
3843
  forgetPassword: (input, options) => postGeneric("/forget-password", input, options),
3488
3844
  resetPassword: authResetPassword,
@@ -3577,6 +3933,7 @@ function createAuthClient(config = {}) {
3577
3933
  }
3578
3934
  },
3579
3935
  hasPermission: (input, options) => postGeneric("/admin/has-permission", input, options),
3936
+ requirePermission: (input, options) => requirePermission("/admin/has-permission", input, options),
3580
3937
  apiKey: {
3581
3938
  create: (input, options) => postGeneric("/admin/api-key/create", input, options)
3582
3939
  },
@@ -3621,7 +3978,15 @@ function createAuthClient(config = {}) {
3621
3978
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
3622
3979
  options
3623
3980
  ),
3624
- delete: (input, options) => postGeneric("/admin/email-template/delete", input, options)
3981
+ delete: (input, options) => postGeneric("/admin/email-template/delete", input, options),
3982
+ send: (input, options) => postGeneric(
3983
+ "/admin/email-template/send",
3984
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
3985
+ options
3986
+ )
3987
+ },
3988
+ eventType: {
3989
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
3625
3990
  }
3626
3991
  },
3627
3992
  emailTemplate: {
@@ -3637,7 +4002,15 @@ function createAuthClient(config = {}) {
3637
4002
  "/admin/email-template/update",
3638
4003
  await resolveAdminEmailTemplatePayload("/admin/email-template/update", input),
3639
4004
  options
4005
+ ),
4006
+ send: (input, options) => postGeneric(
4007
+ "/admin/email-template/send",
4008
+ normalizeAdminEmailTemplateSendPayload(extractFetchOptions(input).payload),
4009
+ options
3640
4010
  )
4011
+ },
4012
+ emailEventType: {
4013
+ list: (input, options) => getWithQuery("/admin/email-event-type/list", input, options)
3641
4014
  }
3642
4015
  },
3643
4016
  apiKey: {
@@ -3677,7 +4050,7 @@ function createAuthClient(config = {}) {
3677
4050
  throw new Error("callback.provider requires non-empty code and state values");
3678
4051
  }
3679
4052
  const endpoint = `/callback/${encodeURIComponent(provider)}`;
3680
- return request({
4053
+ return request2({
3681
4054
  endpoint,
3682
4055
  method: "GET",
3683
4056
  query: {
@@ -3691,7 +4064,7 @@ function createAuthClient(config = {}) {
3691
4064
  };
3692
4065
  return {
3693
4066
  baseUrl: normalizedBaseUrl,
3694
- request,
4067
+ request: request2,
3695
4068
  signIn: {
3696
4069
  email: (input, options) => executePostWithCompatibleInput(
3697
4070
  resolvedConfig,
@@ -3728,6 +4101,8 @@ function createAuthClient(config = {}) {
3728
4101
  input,
3729
4102
  options
3730
4103
  ),
4104
+ getUser,
4105
+ requireSession,
3731
4106
  listSessions: (input, options) => executeGetWithCompatibleInput(
3732
4107
  resolvedConfig,
3733
4108
  { endpoint: "/list-sessions", method: "GET" },
@@ -3891,16 +4266,16 @@ function createStorageFileModule(base, config = {}) {
3891
4266
  };
3892
4267
  });
3893
4268
  input.onProgress?.(createProgressSnapshot("preparing", sources, 0, 0, 0));
3894
- const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request) => request.uploadRequest) }, options)).files;
4269
+ const uploadUrls = uploadRequests.length === 1 ? [await base.createStorageUploadUrl(uploadRequests[0].uploadRequest, options)] : (await base.createStorageUploadUrls({ files: uploadRequests.map((request2) => request2.uploadRequest) }, options)).files;
3895
4270
  const aggregateLoaded = new Array(uploadRequests.length).fill(0);
3896
4271
  const uploaded = [];
3897
4272
  for (let index = 0; index < uploadRequests.length; index += 1) {
3898
- const request = uploadRequests[index];
4273
+ const request2 = uploadRequests[index];
3899
4274
  const uploadUrl = uploadUrls[index];
3900
4275
  const response = await putUploadBody(
3901
4276
  uploadUrl.upload.url,
3902
4277
  uploadUrl.upload.headers ?? {},
3903
- request.source,
4278
+ request2.source,
3904
4279
  input,
3905
4280
  options,
3906
4281
  (progress) => {
@@ -3911,13 +4286,13 @@ function createStorageFileModule(base, config = {}) {
3911
4286
  uploaded.push({
3912
4287
  file: uploadUrl.file,
3913
4288
  upload: uploadUrl.upload,
3914
- source: request.source.source,
3915
- fileName: request.source.fileName,
3916
- storage_key: request.uploadRequest.storage_key,
4289
+ source: request2.source.source,
4290
+ fileName: request2.source.fileName,
4291
+ storage_key: request2.uploadRequest.storage_key,
3917
4292
  response
3918
4293
  });
3919
- aggregateLoaded[index] = request.source.sizeBytes;
3920
- input.onProgress?.(createProgressSnapshot("complete", sources, index, request.source.sizeBytes, sum(aggregateLoaded)));
4294
+ aggregateLoaded[index] = request2.source.sizeBytes;
4295
+ input.onProgress?.(createProgressSnapshot("complete", sources, index, request2.source.sizeBytes, sum(aggregateLoaded)));
3921
4296
  }
3922
4297
  return {
3923
4298
  files: uploaded,
@@ -5878,6 +6253,484 @@ function createStorageModule(gateway, runtimeOptions) {
5878
6253
  };
5879
6254
  }
5880
6255
 
6256
+ // src/chat/module.ts
6257
+ var SDK_NAME3 = "xylex-group/athena-chat";
6258
+ var SDK_HEADER_VALUE3 = buildSdkHeaderValue(SDK_NAME3);
6259
+ var NO_CACHE_HEADER_VALUE3 = "no-cache";
6260
+ var AthenaChatError = class extends Error {
6261
+ status;
6262
+ endpoint;
6263
+ method;
6264
+ requestId;
6265
+ body;
6266
+ constructor(input) {
6267
+ super(input.message);
6268
+ this.name = "AthenaChatError";
6269
+ this.status = input.status;
6270
+ this.endpoint = input.endpoint;
6271
+ this.method = input.method;
6272
+ this.requestId = input.requestId;
6273
+ this.body = input.body;
6274
+ }
6275
+ };
6276
+ function deriveRealtimeInfoUrl(wsUrl) {
6277
+ if (!wsUrl) {
6278
+ return void 0;
6279
+ }
6280
+ const parsed = new URL(normalizeWsUrl(wsUrl, "Athena chat WebSocket URL"));
6281
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
6282
+ parsed.pathname = parsed.pathname.replace(/\/wss\/gateway$/, "/wss/info");
6283
+ return parsed.toString();
6284
+ }
6285
+ function normalizeWsUrl(value, label) {
6286
+ const normalized = value.trim();
6287
+ if (!normalized) {
6288
+ throw new Error(`${label} is required.`);
6289
+ }
6290
+ let parsed;
6291
+ try {
6292
+ parsed = new URL(normalized);
6293
+ } catch {
6294
+ throw new Error(`${label} must be a valid absolute ws(s) URL.`);
6295
+ }
6296
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
6297
+ throw new Error(`${label} must use ws or wss.`);
6298
+ }
6299
+ parsed.pathname = parsed.pathname.replace(/\/+$/, "");
6300
+ return parsed.toString().replace(/\/$/, "");
6301
+ }
6302
+ function isRecord7(value) {
6303
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6304
+ }
6305
+ function normalizeHeaderValue3(value) {
6306
+ return value ? value : void 0;
6307
+ }
6308
+ function parseResponseBody4(rawText, contentType) {
6309
+ if (!rawText) {
6310
+ return { parsed: null, parseFailed: false };
6311
+ }
6312
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
6313
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
6314
+ if (!looksJson) {
6315
+ return { parsed: rawText, parseFailed: false };
6316
+ }
6317
+ try {
6318
+ return { parsed: JSON.parse(rawText), parseFailed: false };
6319
+ } catch {
6320
+ return { parsed: rawText, parseFailed: true };
6321
+ }
6322
+ }
6323
+ function resolveRequestId3(headers) {
6324
+ return headers.get("x-request-id") ?? headers.get("x-correlation-id") ?? headers.get("x-athena-request-id") ?? void 0;
6325
+ }
6326
+ function resolveErrorMessage4(payload, fallback) {
6327
+ if (isRecord7(payload)) {
6328
+ for (const candidate of [payload.error, payload.message, payload.details]) {
6329
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
6330
+ return candidate.trim();
6331
+ }
6332
+ }
6333
+ }
6334
+ if (typeof payload === "string" && payload.trim().length > 0) {
6335
+ return payload.trim();
6336
+ }
6337
+ return fallback;
6338
+ }
6339
+ function encodePathSegment(value, label) {
6340
+ const normalized = value.trim();
6341
+ if (!normalized) {
6342
+ throw new Error(`${label} is required.`);
6343
+ }
6344
+ return encodeURIComponent(normalized);
6345
+ }
6346
+ function encodeQuery(query) {
6347
+ if (!query) {
6348
+ return "";
6349
+ }
6350
+ const params = new URLSearchParams();
6351
+ for (const [key, value] of Object.entries(query)) {
6352
+ if (value === void 0 || value === null) {
6353
+ continue;
6354
+ }
6355
+ if (Array.isArray(value)) {
6356
+ for (const item of value) {
6357
+ if (item !== void 0 && item !== null) {
6358
+ params.append(key, String(item));
6359
+ }
6360
+ }
6361
+ continue;
6362
+ }
6363
+ params.set(key, String(value));
6364
+ }
6365
+ const encoded = params.toString();
6366
+ return encoded ? `?${encoded}` : "";
6367
+ }
6368
+ function createSocket(factory, url, protocols) {
6369
+ try {
6370
+ return new factory(url, protocols);
6371
+ } catch (error) {
6372
+ if (error instanceof TypeError) {
6373
+ return factory(url, protocols);
6374
+ }
6375
+ throw error;
6376
+ }
6377
+ }
6378
+ function buildHeaders3(config, options) {
6379
+ const headers = {
6380
+ Accept: "application/json",
6381
+ apikey: config.apiKey,
6382
+ "x-api-key": config.apiKey,
6383
+ "X-Athena-Sdk": SDK_HEADER_VALUE3
6384
+ };
6385
+ if (config.client || options?.client) {
6386
+ headers["X-Athena-Client"] = options?.client ?? config.client ?? "";
6387
+ }
6388
+ const bearerToken = options?.bearerToken ?? config.bearerToken;
6389
+ if (typeof bearerToken === "string" && bearerToken.trim()) {
6390
+ headers.Authorization = bearerToken.startsWith("Bearer ") ? bearerToken : `Bearer ${bearerToken}`;
6391
+ }
6392
+ const cookie = options?.cookie ?? config.cookie;
6393
+ if (typeof cookie === "string" && cookie.trim()) {
6394
+ headers.Cookie = cookie;
6395
+ }
6396
+ const sessionToken = options?.sessionToken ?? config.sessionToken;
6397
+ if (typeof sessionToken === "string" && sessionToken.trim()) {
6398
+ headers["X-Athena-Auth-Session-Token"] = sessionToken;
6399
+ }
6400
+ if (config.forceNoCache || options?.forceNoCache) {
6401
+ headers["Cache-Control"] = NO_CACHE_HEADER_VALUE3;
6402
+ }
6403
+ for (const source of [config.headers, options?.headers]) {
6404
+ for (const [key, value] of Object.entries(source ?? {})) {
6405
+ const normalized = normalizeHeaderValue3(value);
6406
+ if (normalized) {
6407
+ headers[key] = normalized;
6408
+ }
6409
+ }
6410
+ }
6411
+ return headers;
6412
+ }
6413
+ function withJsonBody(init, body) {
6414
+ return {
6415
+ ...init,
6416
+ body: body === void 0 ? void 0 : JSON.stringify(body),
6417
+ headers: {
6418
+ "Content-Type": "application/json",
6419
+ ...init.headers
6420
+ }
6421
+ };
6422
+ }
6423
+ async function request(config, method, endpoint, options, body) {
6424
+ if (!config.baseUrl) {
6425
+ throw new Error(
6426
+ "Athena chat base URL is not configured. Pass createClient({ url }) for unified routing or set chat.url / chatUrl explicitly."
6427
+ );
6428
+ }
6429
+ const url = `${config.baseUrl}${endpoint}`;
6430
+ const init = {
6431
+ method,
6432
+ headers: buildHeaders3(config, options),
6433
+ signal: options?.signal
6434
+ };
6435
+ const finalInit = body === void 0 || method === "GET" ? init : withJsonBody(init, body);
6436
+ const response = await fetch(url, finalInit);
6437
+ const rawText = await response.text();
6438
+ const { parsed } = parseResponseBody4(rawText, response.headers.get("content-type"));
6439
+ if (!response.ok) {
6440
+ throw new AthenaChatError({
6441
+ message: resolveErrorMessage4(parsed, `Athena chat ${method} ${endpoint} failed with ${response.status}`),
6442
+ status: response.status,
6443
+ endpoint,
6444
+ method,
6445
+ requestId: resolveRequestId3(response.headers),
6446
+ body: parsed
6447
+ });
6448
+ }
6449
+ return parsed;
6450
+ }
6451
+ function createRealtimeConnection(config, options) {
6452
+ if (!config.wsUrl) {
6453
+ throw new Error(
6454
+ "Athena chat WebSocket URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
6455
+ );
6456
+ }
6457
+ const wsFactory = config.webSocketFactory ?? globalThis.WebSocket;
6458
+ if (!wsFactory) {
6459
+ throw new Error(
6460
+ "No WebSocket implementation is available. Provide chat.webSocketFactory in createClient(...) or run in a runtime with global WebSocket support."
6461
+ );
6462
+ }
6463
+ const socket = createSocket(wsFactory, config.wsUrl, options?.protocols);
6464
+ const send = (command) => {
6465
+ socket.send(JSON.stringify(command));
6466
+ };
6467
+ if (options?.onMessage) {
6468
+ const listener = (event) => {
6469
+ const messageEvent = event;
6470
+ const raw = messageEvent?.data;
6471
+ if (typeof raw !== "string") {
6472
+ return;
6473
+ }
6474
+ try {
6475
+ options.onMessage?.(JSON.parse(raw));
6476
+ } catch {
6477
+ options.onMessage?.({ type: "error", error: "Invalid JSON message from Athena chat realtime gateway." });
6478
+ }
6479
+ };
6480
+ if (typeof socket.addEventListener === "function") {
6481
+ socket.addEventListener("message", listener);
6482
+ } else {
6483
+ socket.onmessage = listener;
6484
+ }
6485
+ }
6486
+ const hello = (command) => {
6487
+ send({
6488
+ type: "auth.hello",
6489
+ token: command?.token,
6490
+ room_subscriptions: command?.room_subscriptions
6491
+ });
6492
+ };
6493
+ if (options?.hello) {
6494
+ const onOpen = () => hello({
6495
+ token: options.hello?.token ?? void 0,
6496
+ room_subscriptions: options.hello?.room_subscriptions ?? void 0
6497
+ });
6498
+ if (typeof socket.addEventListener === "function") {
6499
+ socket.addEventListener("open", onOpen);
6500
+ } else {
6501
+ socket.onopen = onOpen;
6502
+ }
6503
+ }
6504
+ return {
6505
+ socket,
6506
+ send,
6507
+ hello,
6508
+ subscribe(roomId, fromSeq) {
6509
+ send({
6510
+ type: "chat.subscribe",
6511
+ room_id: roomId,
6512
+ from_seq: fromSeq ?? void 0
6513
+ });
6514
+ },
6515
+ unsubscribe(roomId) {
6516
+ send({
6517
+ type: "chat.unsubscribe",
6518
+ room_id: roomId
6519
+ });
6520
+ },
6521
+ resume(rooms) {
6522
+ send({
6523
+ type: "chat.resume",
6524
+ rooms
6525
+ });
6526
+ },
6527
+ typingStart(roomId) {
6528
+ send({
6529
+ type: "chat.typing.start",
6530
+ room_id: roomId
6531
+ });
6532
+ },
6533
+ typingStop(roomId) {
6534
+ send({
6535
+ type: "chat.typing.stop",
6536
+ room_id: roomId
6537
+ });
6538
+ },
6539
+ presenceHeartbeat(activeRoomId) {
6540
+ send({
6541
+ type: "chat.presence.heartbeat",
6542
+ active_room_id: activeRoomId ?? void 0
6543
+ });
6544
+ },
6545
+ readUpTo(roomId, input) {
6546
+ send({
6547
+ type: "chat.read.up_to",
6548
+ room_id: roomId,
6549
+ message_id: input?.message_id ?? void 0,
6550
+ seq: input?.seq ?? void 0
6551
+ });
6552
+ },
6553
+ ping(at = (/* @__PURE__ */ new Date()).toISOString()) {
6554
+ send({
6555
+ type: "ping",
6556
+ at
6557
+ });
6558
+ },
6559
+ close(code, reason) {
6560
+ socket.close(code, reason);
6561
+ }
6562
+ };
6563
+ }
6564
+ function createChatModule(config) {
6565
+ const realtime = {
6566
+ info(options) {
6567
+ const realtimeInfoUrl = config.realtimeInfoUrl ?? deriveRealtimeInfoUrl(config.wsUrl);
6568
+ if (!realtimeInfoUrl) {
6569
+ throw new Error(
6570
+ "Athena chat realtime info URL is not configured. Pass createClient({ url }) for unified routing or set chat.wsUrl / chatWsUrl explicitly."
6571
+ );
6572
+ }
6573
+ return request(
6574
+ {
6575
+ ...config,
6576
+ baseUrl: realtimeInfoUrl
6577
+ },
6578
+ "GET",
6579
+ "",
6580
+ options
6581
+ );
6582
+ },
6583
+ connect(options) {
6584
+ return createRealtimeConnection(config, options);
6585
+ }
6586
+ };
6587
+ return {
6588
+ room: {
6589
+ list(query, options) {
6590
+ return request(
6591
+ config,
6592
+ "GET",
6593
+ `/rooms${encodeQuery(query)}`,
6594
+ options
6595
+ );
6596
+ },
6597
+ create(input, options) {
6598
+ return request(config, "POST", "/rooms", options, input);
6599
+ },
6600
+ get(roomId, options) {
6601
+ return request(
6602
+ config,
6603
+ "GET",
6604
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6605
+ options
6606
+ );
6607
+ },
6608
+ update(roomId, input, options) {
6609
+ return request(
6610
+ config,
6611
+ "PATCH",
6612
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}`,
6613
+ options,
6614
+ input
6615
+ );
6616
+ },
6617
+ archive(roomId, options) {
6618
+ return request(
6619
+ config,
6620
+ "POST",
6621
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/archive`,
6622
+ options
6623
+ );
6624
+ },
6625
+ readCursor: {
6626
+ upTo(roomId, input, options) {
6627
+ return request(
6628
+ config,
6629
+ "POST",
6630
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/read-cursor`,
6631
+ options,
6632
+ input ?? {}
6633
+ );
6634
+ }
6635
+ },
6636
+ member: {
6637
+ list(roomId, options) {
6638
+ return request(
6639
+ config,
6640
+ "GET",
6641
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6642
+ options
6643
+ );
6644
+ },
6645
+ add(roomId, input, options) {
6646
+ return request(
6647
+ config,
6648
+ "POST",
6649
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members`,
6650
+ options,
6651
+ input
6652
+ );
6653
+ },
6654
+ remove(roomId, userId, options) {
6655
+ return request(
6656
+ config,
6657
+ "DELETE",
6658
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/members/${encodePathSegment(userId, "chat user ID")}`,
6659
+ options
6660
+ );
6661
+ }
6662
+ },
6663
+ message: {
6664
+ list(roomId, query, options) {
6665
+ return request(
6666
+ config,
6667
+ "GET",
6668
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages${encodeQuery(query)}`,
6669
+ options
6670
+ );
6671
+ },
6672
+ send(roomId, input, options) {
6673
+ return request(
6674
+ config,
6675
+ "POST",
6676
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages`,
6677
+ options,
6678
+ input
6679
+ );
6680
+ },
6681
+ update(roomId, messageId, input, options) {
6682
+ return request(
6683
+ config,
6684
+ "PATCH",
6685
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6686
+ options,
6687
+ input
6688
+ );
6689
+ },
6690
+ delete(roomId, messageId, options) {
6691
+ return request(
6692
+ config,
6693
+ "DELETE",
6694
+ `/rooms/${encodePathSegment(roomId, "chat room ID")}/messages/${encodePathSegment(messageId, "chat message ID")}`,
6695
+ options
6696
+ );
6697
+ }
6698
+ }
6699
+ },
6700
+ message: {
6701
+ reaction: {
6702
+ add(messageId, input, options) {
6703
+ return request(
6704
+ config,
6705
+ "POST",
6706
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions`,
6707
+ options,
6708
+ input
6709
+ );
6710
+ },
6711
+ remove(messageId, emoji, options) {
6712
+ return request(
6713
+ config,
6714
+ "DELETE",
6715
+ `/messages/${encodePathSegment(messageId, "chat message ID")}/reactions/${encodePathSegment(emoji, "reaction emoji")}`,
6716
+ options
6717
+ );
6718
+ }
6719
+ },
6720
+ search(input, options) {
6721
+ return request(
6722
+ config,
6723
+ "POST",
6724
+ "/messages/search",
6725
+ options,
6726
+ input
6727
+ );
6728
+ }
6729
+ },
6730
+ realtime
6731
+ };
6732
+ }
6733
+
5881
6734
  // src/client-builder.ts
5882
6735
  var DEFAULT_BACKEND = { type: "athena" };
5883
6736
  function toBackendConfig(value) {
@@ -5912,7 +6765,7 @@ var BOOLEAN_SAFE_OPERATORS = /* @__PURE__ */ new Set([
5912
6765
  "ilike",
5913
6766
  "is"
5914
6767
  ]);
5915
- function isRecord7(value) {
6768
+ function isRecord8(value) {
5916
6769
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
5917
6770
  }
5918
6771
  function isUuidString(value) {
@@ -5925,7 +6778,7 @@ function shouldUseUuidTextComparison(column, value) {
5925
6778
  return typeof value === "string" && isUuidString(value) && isUuidIdentifierColumn(column);
5926
6779
  }
5927
6780
  function isRelationSelectNode(value) {
5928
- return isRecord7(value) && isRecord7(value.select);
6781
+ return isRecord8(value) && isRecord8(value.select);
5929
6782
  }
5930
6783
  function normalizeIdentifier(value, label) {
5931
6784
  const normalized = value.trim();
@@ -5981,7 +6834,7 @@ function compileRelationToken(key, node) {
5981
6834
  return `${prefix}${relationToken}(${nested})`;
5982
6835
  }
5983
6836
  function compileSelectShape(select) {
5984
- if (!isRecord7(select)) {
6837
+ if (!isRecord8(select)) {
5985
6838
  throw new Error("findMany select must be an object");
5986
6839
  }
5987
6840
  const tokens = [];
@@ -6005,7 +6858,7 @@ function compileSelectShape(select) {
6005
6858
  return tokens.join(",");
6006
6859
  }
6007
6860
  function selectShapeUsesRelationSchema(select) {
6008
- if (!isRecord7(select)) {
6861
+ if (!isRecord8(select)) {
6009
6862
  return false;
6010
6863
  }
6011
6864
  for (const rawValue of Object.values(select)) {
@@ -6023,7 +6876,7 @@ function selectShapeUsesRelationSchema(select) {
6023
6876
  }
6024
6877
  function compileColumnWhere(column, input) {
6025
6878
  const normalizedColumn = normalizeIdentifier(column, "where column");
6026
- if (!isRecord7(input)) {
6879
+ if (!isRecord8(input)) {
6027
6880
  return [buildGatewayCondition("eq", normalizedColumn, input)];
6028
6881
  }
6029
6882
  const conditions = [];
@@ -6051,7 +6904,7 @@ function compileColumnWhere(column, input) {
6051
6904
  return conditions;
6052
6905
  }
6053
6906
  function compileBooleanExpressionTerms(clause, label) {
6054
- if (!isRecord7(clause)) {
6907
+ if (!isRecord8(clause)) {
6055
6908
  throw new Error(`findMany where.${label} clauses must be objects`);
6056
6909
  }
6057
6910
  const entries = Object.entries(clause).filter(([, value]) => value !== void 0);
@@ -6060,7 +6913,7 @@ function compileBooleanExpressionTerms(clause, label) {
6060
6913
  }
6061
6914
  const [rawColumn, rawValue] = entries[0];
6062
6915
  const column = normalizeIdentifier(rawColumn, `where.${label} column`);
6063
- if (!isRecord7(rawValue)) {
6916
+ if (!isRecord8(rawValue)) {
6064
6917
  return [`${column}.eq.${stringifyFilterValue(rawValue)}`];
6065
6918
  }
6066
6919
  const operatorEntries = Object.entries(rawValue).filter(([, value]) => value !== void 0);
@@ -6084,7 +6937,7 @@ function compileWhere(where) {
6084
6937
  if (where === void 0) {
6085
6938
  return void 0;
6086
6939
  }
6087
- if (!isRecord7(where)) {
6940
+ if (!isRecord8(where)) {
6088
6941
  throw new Error("findMany where must be an object");
6089
6942
  }
6090
6943
  const conditions = [];
@@ -6134,7 +6987,7 @@ function compileOrderBy(orderBy) {
6134
6987
  if (orderBy === void 0) {
6135
6988
  return void 0;
6136
6989
  }
6137
- if (!isRecord7(orderBy)) {
6990
+ if (!isRecord8(orderBy)) {
6138
6991
  throw new Error("findMany orderBy must be an object");
6139
6992
  }
6140
6993
  if ("column" in orderBy) {
@@ -6309,11 +7162,11 @@ function toFindManyAstOrder(order) {
6309
7162
  ascending: order.direction !== "descending"
6310
7163
  };
6311
7164
  }
6312
- function isRecord8(value) {
7165
+ function isRecord9(value) {
6313
7166
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
6314
7167
  }
6315
7168
  function normalizeFindManyAstColumnPredicate(value) {
6316
- if (!isRecord8(value)) {
7169
+ if (!isRecord9(value)) {
6317
7170
  return {
6318
7171
  eq: value
6319
7172
  };
@@ -6337,7 +7190,7 @@ function normalizeFindManyAstBooleanOperand(clause) {
6337
7190
  return normalized;
6338
7191
  }
6339
7192
  function normalizeFindManyAstWhere(where) {
6340
- if (!where || !isRecord8(where)) {
7193
+ if (!where || !isRecord9(where)) {
6341
7194
  return where;
6342
7195
  }
6343
7196
  const normalized = {};
@@ -6351,7 +7204,7 @@ function normalizeFindManyAstWhere(where) {
6351
7204
  );
6352
7205
  continue;
6353
7206
  }
6354
- if (key === "not" && isRecord8(value)) {
7207
+ if (key === "not" && isRecord9(value)) {
6355
7208
  normalized.not = normalizeFindManyAstBooleanOperand(
6356
7209
  value
6357
7210
  );
@@ -6362,7 +7215,7 @@ function normalizeFindManyAstWhere(where) {
6362
7215
  return normalized;
6363
7216
  }
6364
7217
  function predicateRequiresUuidQueryFallback(column, value) {
6365
- if (!isRecord8(value)) {
7218
+ if (!isRecord9(value)) {
6366
7219
  return shouldUseUuidTextComparison(column, value);
6367
7220
  }
6368
7221
  const eqValue = value.eq;
@@ -6380,7 +7233,7 @@ function booleanOperandRequiresUuidQueryFallback(clause) {
6380
7233
  return false;
6381
7234
  }
6382
7235
  function findManyAstWhereRequiresLegacyTransport(where) {
6383
- if (!where || !isRecord8(where)) {
7236
+ if (!where || !isRecord9(where)) {
6384
7237
  return false;
6385
7238
  }
6386
7239
  for (const [key, value] of Object.entries(where)) {
@@ -6395,7 +7248,7 @@ function findManyAstWhereRequiresLegacyTransport(where) {
6395
7248
  }
6396
7249
  continue;
6397
7250
  }
6398
- if (key === "not" && isRecord8(value)) {
7251
+ if (key === "not" && isRecord9(value)) {
6399
7252
  if (booleanOperandRequiresUuidQueryFallback(value)) {
6400
7253
  return true;
6401
7254
  }
@@ -6938,6 +7791,7 @@ function resolveAthenaModelTargetTableName(target, options = {}) {
6938
7791
  var DEFAULT_COLUMNS = "*";
6939
7792
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
6940
7793
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
7794
+ var SDK_NAME4 = "xylex-group/athena";
6941
7795
  function formatResult(response) {
6942
7796
  const result = {
6943
7797
  data: response.data ?? null,
@@ -7014,7 +7868,7 @@ async function executeExperimentalRead(experimental, runner) {
7014
7868
  throw error;
7015
7869
  }
7016
7870
  }
7017
- function isRecord9(value) {
7871
+ function isRecord10(value) {
7018
7872
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
7019
7873
  }
7020
7874
  function firstNonEmptyString2(...values) {
@@ -7026,8 +7880,8 @@ function firstNonEmptyString2(...values) {
7026
7880
  return void 0;
7027
7881
  }
7028
7882
  function resolveStructuredErrorPayload2(raw) {
7029
- if (!isRecord9(raw)) return null;
7030
- return isRecord9(raw.error) ? raw.error : raw;
7883
+ if (!isRecord10(raw)) return null;
7884
+ return isRecord10(raw.error) ? raw.error : raw;
7031
7885
  }
7032
7886
  function resolveStructuredErrorDetails(payload, message) {
7033
7887
  if (!payload || !("details" in payload)) {
@@ -7043,7 +7897,7 @@ function resolveStructuredErrorDetails(payload, message) {
7043
7897
  return details;
7044
7898
  }
7045
7899
  function createResultError(response, result, normalized) {
7046
- const rawRecord = isRecord9(response.raw) ? response.raw : null;
7900
+ const rawRecord = isRecord10(response.raw) ? response.raw : null;
7047
7901
  const payload = resolveStructuredErrorPayload2(response.raw);
7048
7902
  const message = firstNonEmptyString2(
7049
7903
  response.error,
@@ -7106,6 +7960,43 @@ function asAthenaJsonObject(value) {
7106
7960
  function asAthenaJsonObjectArray(values) {
7107
7961
  return values;
7108
7962
  }
7963
+ function parseArbitraryResponseBody(rawText, contentType) {
7964
+ if (!rawText) {
7965
+ return null;
7966
+ }
7967
+ const contentTypeSuggestsJson = contentType?.toLowerCase().includes("application/json") ?? false;
7968
+ const looksJson = contentTypeSuggestsJson || rawText.startsWith("{") || rawText.startsWith("[");
7969
+ if (!looksJson) {
7970
+ return rawText;
7971
+ }
7972
+ try {
7973
+ return JSON.parse(rawText);
7974
+ } catch {
7975
+ return rawText;
7976
+ }
7977
+ }
7978
+ function toRequestQueryString(query) {
7979
+ if (!query) {
7980
+ return "";
7981
+ }
7982
+ const params = new URLSearchParams();
7983
+ for (const [key, value] of Object.entries(query)) {
7984
+ if (value === void 0 || value === null) {
7985
+ continue;
7986
+ }
7987
+ if (Array.isArray(value)) {
7988
+ for (const item of value) {
7989
+ if (item !== void 0 && item !== null) {
7990
+ params.append(key, String(item));
7991
+ }
7992
+ }
7993
+ continue;
7994
+ }
7995
+ params.set(key, String(value));
7996
+ }
7997
+ const encoded = params.toString();
7998
+ return encoded ? `?${encoded}` : "";
7999
+ }
7109
8000
  function normalizeSelectColumnsInput(columns) {
7110
8001
  if (columns === void 0) {
7111
8002
  return void 0;
@@ -8405,6 +9296,59 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
8405
9296
  );
8406
9297
  };
8407
9298
  }
9299
+ function normalizeOptionalString2(value) {
9300
+ if (typeof value !== "string") {
9301
+ return void 0;
9302
+ }
9303
+ const normalizedValue = value.trim();
9304
+ return normalizedValue ? normalizedValue : void 0;
9305
+ }
9306
+ function readHeaderBagValue(headers, targetKey) {
9307
+ if (!headers) {
9308
+ return void 0;
9309
+ }
9310
+ if (typeof headers.get === "function") {
9311
+ return normalizeOptionalString2(headers.get(targetKey));
9312
+ }
9313
+ const normalizedTargetKey = targetKey.toLowerCase();
9314
+ for (const [key, value] of Object.entries(headers)) {
9315
+ if (key.toLowerCase() !== normalizedTargetKey) {
9316
+ continue;
9317
+ }
9318
+ if (typeof value === "string") {
9319
+ return normalizeOptionalString2(value);
9320
+ }
9321
+ return void 0;
9322
+ }
9323
+ return void 0;
9324
+ }
9325
+ function resolveSessionContextOptions(session, options) {
9326
+ const sessionToken = normalizeOptionalString2(session?.session?.token);
9327
+ const requestCookie = readHeaderBagValue(options?.requestHeaders, "cookie") ?? readHeaderBagValue(options?.headers, "cookie");
9328
+ const authInput = options?.auth;
9329
+ const resolvedUserId = options?.userId !== void 0 ? options.userId : session?.user?.id;
9330
+ const resolvedOrganizationId = options?.organizationId !== void 0 ? options.organizationId : session?.session?.activeOrganizationId;
9331
+ const resolvedBearerToken = authInput?.bearerToken !== void 0 ? authInput.bearerToken : sessionToken;
9332
+ const resolvedSessionToken = authInput?.sessionToken !== void 0 ? authInput.sessionToken : sessionToken;
9333
+ const resolvedCookie = authInput?.cookie !== void 0 ? authInput.cookie : requestCookie;
9334
+ const auth = authInput !== void 0 || resolvedBearerToken !== void 0 || resolvedSessionToken !== void 0 || resolvedCookie !== void 0 ? {
9335
+ ...authInput ?? {},
9336
+ ...resolvedBearerToken !== void 0 ? { bearerToken: resolvedBearerToken } : {},
9337
+ ...resolvedSessionToken !== void 0 ? { sessionToken: resolvedSessionToken } : {},
9338
+ ...resolvedCookie !== void 0 ? { cookie: resolvedCookie } : {},
9339
+ headers: authInput?.headers ? { ...authInput.headers } : void 0
9340
+ } : void 0;
9341
+ if (resolvedUserId === void 0 && resolvedOrganizationId === void 0 && options?.forceNoCache === void 0 && !options?.headers && !auth) {
9342
+ return void 0;
9343
+ }
9344
+ return {
9345
+ userId: resolvedUserId,
9346
+ organizationId: resolvedOrganizationId,
9347
+ forceNoCache: options?.forceNoCache,
9348
+ headers: options?.headers ? { ...options.headers } : void 0,
9349
+ auth
9350
+ };
9351
+ }
8408
9352
  function resolveClientServiceBaseUrl(value, label) {
8409
9353
  if (value === void 0 || value === null) {
8410
9354
  return void 0;
@@ -8415,6 +9359,15 @@ function appendServicePath(baseUrl, segment) {
8415
9359
  const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8416
9360
  return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8417
9361
  }
9362
+ function appendRealtimeGatewayPath(baseUrl) {
9363
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
9364
+ const wsUrl = new URL(normalizedBaseUrl);
9365
+ wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
9366
+ wsUrl.pathname = `${wsUrl.pathname.replace(/\/+$/, "")}/wss/gateway`;
9367
+ wsUrl.search = "";
9368
+ wsUrl.hash = "";
9369
+ return wsUrl.toString();
9370
+ }
8418
9371
  function resolveServiceUrlOverride(value, label) {
8419
9372
  return resolveClientServiceBaseUrl(value, label);
8420
9373
  }
@@ -8423,6 +9376,8 @@ function resolveServiceUrls(config) {
8423
9376
  return {
8424
9377
  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),
8425
9378
  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),
9379
+ chatUrl: resolveServiceUrlOverride(config.chat?.url, "Athena chat base URL") ?? resolveServiceUrlOverride(config.chatUrl, "Athena chat base URL") ?? (baseUrl ? appendServicePath(baseUrl, "chat") : void 0),
9380
+ chatWsUrl: normalizeOptionalString2(config.chat?.wsUrl) ?? normalizeOptionalString2(config.chatWsUrl) ?? (baseUrl ? appendRealtimeGatewayPath(baseUrl) : void 0),
8426
9381
  storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8427
9382
  };
8428
9383
  }
@@ -8447,6 +9402,89 @@ function resolveRequiredClientApiKey(value) {
8447
9402
  }
8448
9403
  return normalizedValue;
8449
9404
  }
9405
+ function hasHeaderIgnoreCase(headers, targetKey) {
9406
+ const normalizedTargetKey = targetKey.toLowerCase();
9407
+ return Object.keys(headers).some((key) => key.toLowerCase() === normalizedTargetKey);
9408
+ }
9409
+ function mergeClientHeaders(current, next) {
9410
+ if (!current && !next) {
9411
+ return void 0;
9412
+ }
9413
+ return {
9414
+ ...current ?? {},
9415
+ ...next ?? {}
9416
+ };
9417
+ }
9418
+ function mergeDefinedObject(current, next) {
9419
+ if (!current && !next) {
9420
+ return void 0;
9421
+ }
9422
+ const merged = {
9423
+ ...current ?? {}
9424
+ };
9425
+ const mutableMerged = merged;
9426
+ for (const [key, value] of Object.entries(next ?? {})) {
9427
+ if (value !== void 0) {
9428
+ mutableMerged[key] = value;
9429
+ }
9430
+ }
9431
+ return merged;
9432
+ }
9433
+ function mergeAuthClientOptions(current, next) {
9434
+ const merged = mergeDefinedObject(current, next);
9435
+ if (!merged) {
9436
+ return void 0;
9437
+ }
9438
+ const mergedHeaders = mergeClientHeaders(current?.headers, next?.headers);
9439
+ if (mergedHeaders) {
9440
+ merged.headers = mergedHeaders;
9441
+ }
9442
+ return merged;
9443
+ }
9444
+ function mergeServiceUrlOverrides(current, next) {
9445
+ return mergeDefinedObject(current, next);
9446
+ }
9447
+ function toClientContextOverrides(context) {
9448
+ if (!context) {
9449
+ return void 0;
9450
+ }
9451
+ return {
9452
+ userId: context.userId,
9453
+ organizationId: context.organizationId,
9454
+ forceNoCache: context.forceNoCache,
9455
+ headers: context.headers,
9456
+ auth: context.auth ? {
9457
+ ...context.auth,
9458
+ headers: context.auth.headers ? { ...context.auth.headers } : void 0
9459
+ } : void 0
9460
+ };
9461
+ }
9462
+ function mergeClientOverrideOptions(base, overrides) {
9463
+ if (!overrides) {
9464
+ return {
9465
+ ...base,
9466
+ headers: base.headers ? { ...base.headers } : void 0,
9467
+ auth: base.auth ? {
9468
+ ...base.auth,
9469
+ headers: base.auth.headers ? { ...base.auth.headers } : void 0
9470
+ } : void 0,
9471
+ db: base.db ? { ...base.db } : void 0,
9472
+ gateway: base.gateway ? { ...base.gateway } : void 0,
9473
+ chat: base.chat ? { ...base.chat } : void 0,
9474
+ storage: base.storage ? { ...base.storage } : void 0
9475
+ };
9476
+ }
9477
+ const merged = mergeDefinedObject(base, overrides) ?? { ...base };
9478
+ return {
9479
+ ...merged,
9480
+ headers: mergeClientHeaders(base.headers, overrides.headers),
9481
+ auth: mergeAuthClientOptions(base.auth, overrides.auth),
9482
+ db: mergeServiceUrlOverrides(base.db, overrides.db),
9483
+ gateway: mergeServiceUrlOverrides(base.gateway, overrides.gateway),
9484
+ chat: mergeServiceUrlOverrides(base.chat, overrides.chat),
9485
+ storage: mergeServiceUrlOverrides(base.storage, overrides.storage)
9486
+ };
9487
+ }
8450
9488
  function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8451
9489
  if (!auth && defaultBaseUrl === void 0) {
8452
9490
  return void 0;
@@ -8456,6 +9494,8 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8456
9494
  baseUrl,
8457
9495
  apiKey,
8458
9496
  bearerToken,
9497
+ cookie,
9498
+ sessionToken,
8459
9499
  ...rest
8460
9500
  } = auth ?? {};
8461
9501
  const normalized = {
@@ -8474,6 +9514,12 @@ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8474
9514
  if (typeof bearerToken === "string") {
8475
9515
  normalized.bearerToken = bearerToken;
8476
9516
  }
9517
+ if (typeof cookie === "string") {
9518
+ normalized.cookie = cookie;
9519
+ }
9520
+ if (typeof sessionToken === "string") {
9521
+ normalized.sessionToken = sessionToken;
9522
+ }
8477
9523
  return normalized;
8478
9524
  }
8479
9525
  function resolveCreateClientConfig(config) {
@@ -8487,31 +9533,53 @@ function resolveCreateClientConfig(config) {
8487
9533
  baseUrl: resolvedUrls.dbUrl,
8488
9534
  apiKey: resolveRequiredClientApiKey(config.key),
8489
9535
  client: resolveOptionalClientName(config.client),
9536
+ userId: config.userId,
9537
+ organizationId: config.organizationId,
9538
+ forceNoCache: config.forceNoCache,
8490
9539
  backend: toBackendConfig(config.backend),
8491
9540
  headers: config.headers,
8492
9541
  auth: config.auth,
8493
9542
  authUrl: resolvedUrls.authUrl,
9543
+ chat: config.chat,
9544
+ chatUrl: resolvedUrls.chatUrl,
9545
+ chatWsUrl: resolvedUrls.chatWsUrl,
8494
9546
  storageUrl: resolvedUrls.storageUrl,
8495
9547
  experimental: config.experimental
8496
9548
  };
8497
9549
  }
8498
- function createClientFromConfig(config) {
9550
+ function createClientFromInput(sourceConfig) {
9551
+ return createClientFromConfig(resolveCreateClientConfig(sourceConfig), sourceConfig);
9552
+ }
9553
+ function createClientFromConfig(config, sourceConfig) {
9554
+ const normalizedAuthConfig = normalizeAuthClientConfig(config.auth, config.authUrl);
8499
9555
  const gatewayHeaders = {
8500
9556
  ...config.headers ?? {}
8501
9557
  };
8502
- if (config.auth?.bearerToken && gatewayHeaders["X-Athena-Auth-Bearer-Token"] === void 0 && gatewayHeaders["x-athena-auth-bearer-token"] === void 0) {
8503
- gatewayHeaders["X-Athena-Auth-Bearer-Token"] = config.auth.bearerToken;
9558
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Bearer-Token")) {
9559
+ gatewayHeaders["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9560
+ }
9561
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(gatewayHeaders, "Cookie")) {
9562
+ gatewayHeaders.Cookie = normalizedAuthConfig.cookie;
9563
+ }
9564
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(gatewayHeaders, "X-Athena-Auth-Session-Token")) {
9565
+ gatewayHeaders["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
8504
9566
  }
8505
9567
  const gateway = createAthenaGatewayClient({
8506
9568
  baseUrl: config.baseUrl,
8507
9569
  apiKey: config.apiKey,
8508
9570
  client: config.client,
9571
+ userId: config.userId,
9572
+ organizationId: config.organizationId,
9573
+ forceNoCache: config.forceNoCache,
8509
9574
  backend: config.backend,
8510
9575
  headers: gatewayHeaders
8511
9576
  });
8512
9577
  const formatGatewayResult = createResultFormatter(config.experimental);
8513
9578
  const queryTracer = createQueryTracer(config.experimental);
8514
- const auth = createAuthClient(normalizeAuthClientConfig(config.auth, config.authUrl));
9579
+ const auth = createAuthClient({
9580
+ ...normalizedAuthConfig ?? {},
9581
+ ...config.forceNoCache ? { forceNoCache: true } : {}
9582
+ });
8515
9583
  function from(tableOrModel, options) {
8516
9584
  if (isAthenaModelTarget(tableOrModel)) {
8517
9585
  if (options?.schema !== void 0) {
@@ -8559,17 +9627,160 @@ function createClientFromConfig(config) {
8559
9627
  queryTracer
8560
9628
  );
8561
9629
  const db = createDbModule({ from, rpc, query });
9630
+ const chat = createChatModule({
9631
+ baseUrl: config.chatUrl,
9632
+ apiKey: config.apiKey,
9633
+ client: config.client,
9634
+ headers: config.headers,
9635
+ bearerToken: normalizedAuthConfig?.bearerToken,
9636
+ cookie: normalizedAuthConfig?.cookie,
9637
+ sessionToken: normalizedAuthConfig?.sessionToken,
9638
+ forceNoCache: config.forceNoCache,
9639
+ wsUrl: config.chatWsUrl,
9640
+ webSocketFactory: config.chat?.webSocketFactory ?? void 0
9641
+ });
9642
+ const request2 = async (options) => {
9643
+ const method = options.method ?? "GET";
9644
+ const responseType = options.responseType ?? "json";
9645
+ const service = options.service ?? "db";
9646
+ const baseUrlByService = {
9647
+ db: config.baseUrl,
9648
+ auth: config.authUrl,
9649
+ chat: config.chatUrl,
9650
+ storage: config.storageUrl
9651
+ };
9652
+ const resolvedBaseUrl = options.url ?? baseUrlByService[service];
9653
+ if (!resolvedBaseUrl) {
9654
+ throw new Error(
9655
+ `Athena ${service} base URL is not configured. Pass createClient({ url }) for unified routing or set the service-specific URL first.`
9656
+ );
9657
+ }
9658
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(resolvedBaseUrl, {
9659
+ label: `Athena ${service} base URL`
9660
+ });
9661
+ const normalizedPath = options.url ? "" : (() => {
9662
+ const path = options.path?.trim();
9663
+ if (!path) {
9664
+ throw new Error("client.request(...) requires either an absolute url or a non-empty path.");
9665
+ }
9666
+ return path.startsWith("/") ? path : `/${path}`;
9667
+ })();
9668
+ const targetUrl = options.url ? `${normalizedBaseUrl}${toRequestQueryString(options.query)}` : `${normalizedBaseUrl}${normalizedPath}${toRequestQueryString(options.query)}`;
9669
+ const headers = {
9670
+ "X-Athena-Sdk": buildSdkHeaderValue(SDK_NAME4),
9671
+ ...config.headers ?? {},
9672
+ ...options.headers ?? {}
9673
+ };
9674
+ if (service !== "auth") {
9675
+ headers.apikey = headers.apikey ?? config.apiKey;
9676
+ headers["x-api-key"] = headers["x-api-key"] ?? config.apiKey;
9677
+ if (config.client && !hasHeaderIgnoreCase(headers, "X-Athena-Client")) {
9678
+ headers["X-Athena-Client"] = config.client;
9679
+ }
9680
+ if (config.userId && !hasHeaderIgnoreCase(headers, "X-User-Id")) {
9681
+ headers["X-User-Id"] = config.userId;
9682
+ }
9683
+ if (config.organizationId && !hasHeaderIgnoreCase(headers, "X-Organization-Id")) {
9684
+ headers["X-Organization-Id"] = config.organizationId;
9685
+ }
9686
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9687
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9688
+ }
9689
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Bearer-Token")) {
9690
+ headers["X-Athena-Auth-Bearer-Token"] = normalizedAuthConfig.bearerToken;
9691
+ }
9692
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9693
+ headers.Cookie = normalizedAuthConfig.cookie;
9694
+ }
9695
+ } else {
9696
+ const authApiKey = normalizedAuthConfig?.apiKey ?? config.apiKey;
9697
+ if (authApiKey && !hasHeaderIgnoreCase(headers, "x-api-key")) {
9698
+ headers.apikey = headers.apikey ?? authApiKey;
9699
+ headers["x-api-key"] = headers["x-api-key"] ?? authApiKey;
9700
+ }
9701
+ if (normalizedAuthConfig?.bearerToken && !hasHeaderIgnoreCase(headers, "Authorization")) {
9702
+ headers.Authorization = `Bearer ${normalizedAuthConfig.bearerToken}`;
9703
+ }
9704
+ if (normalizedAuthConfig?.cookie && !hasHeaderIgnoreCase(headers, "Cookie")) {
9705
+ headers.Cookie = normalizedAuthConfig.cookie;
9706
+ }
9707
+ if (normalizedAuthConfig?.sessionToken && !hasHeaderIgnoreCase(headers, "X-Athena-Auth-Session-Token")) {
9708
+ headers["X-Athena-Auth-Session-Token"] = normalizedAuthConfig.sessionToken;
9709
+ }
9710
+ }
9711
+ 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";
9712
+ if (shouldSendJsonBody && !hasHeaderIgnoreCase(headers, "Content-Type")) {
9713
+ headers["Content-Type"] = "application/json";
9714
+ }
9715
+ const response = await fetch(targetUrl, {
9716
+ method,
9717
+ headers,
9718
+ body: options.body === void 0 || options.body === null ? void 0 : shouldSendJsonBody ? JSON.stringify(options.body) : options.body,
9719
+ signal: options.signal,
9720
+ credentials: options.credentials
9721
+ });
9722
+ if (responseType === "response") {
9723
+ return {
9724
+ ok: response.ok,
9725
+ status: response.status,
9726
+ statusText: response.statusText,
9727
+ headers: response.headers,
9728
+ data: null,
9729
+ raw: response
9730
+ };
9731
+ }
9732
+ const rawText = await response.text();
9733
+ const parsed = responseType === "text" ? rawText : parseArbitraryResponseBody(rawText, response.headers.get("content-type"));
9734
+ return {
9735
+ ok: response.ok,
9736
+ status: response.status,
9737
+ statusText: response.statusText,
9738
+ headers: response.headers,
9739
+ data: parsed,
9740
+ raw: response
9741
+ };
9742
+ };
9743
+ const withContext = (context) => createClientFromInput(
9744
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9745
+ );
9746
+ const withSession = (session, options) => createClientFromInput(
9747
+ mergeClientOverrideOptions(
9748
+ sourceConfig,
9749
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9750
+ )
9751
+ );
9752
+ const authWithOptions = (options) => createClientFromInput(mergeClientOverrideOptions(sourceConfig, options));
8562
9753
  const sdkClient = {
8563
9754
  from,
8564
9755
  db,
8565
9756
  rpc,
8566
9757
  query,
9758
+ request: request2,
8567
9759
  verifyConnection: gateway.verifyConnection,
8568
- auth: auth.auth
9760
+ auth: auth.auth,
9761
+ chat,
9762
+ withContext,
9763
+ withSession,
9764
+ withOptions: authWithOptions
8569
9765
  };
8570
9766
  if (config.experimental?.athenaStorageBackend) {
9767
+ const storageWithContext = (context) => createClientFromInput(
9768
+ mergeClientOverrideOptions(sourceConfig, toClientContextOverrides(context))
9769
+ );
9770
+ const storageWithSession = (session, options) => createClientFromInput(
9771
+ mergeClientOverrideOptions(
9772
+ sourceConfig,
9773
+ toClientContextOverrides(resolveSessionContextOptions(session, options))
9774
+ )
9775
+ );
9776
+ const storageWithOptions = (options) => createClientFromInput(
9777
+ mergeClientOverrideOptions(sourceConfig, options)
9778
+ );
8571
9779
  const storageClient = {
8572
9780
  ...sdkClient,
9781
+ withContext: storageWithContext,
9782
+ withSession: storageWithSession,
9783
+ withOptions: storageWithOptions,
8573
9784
  storage: createStorageModule(gateway, {
8574
9785
  ...config.experimental.storage,
8575
9786
  ...config.storageUrl ? {
@@ -8584,13 +9795,13 @@ function createClientFromConfig(config) {
8584
9795
  }
8585
9796
  function createClient(configOrUrl, apiKey, options) {
8586
9797
  if (typeof configOrUrl === "string" || configOrUrl === null || configOrUrl === void 0) {
8587
- return createClientFromConfig(resolveCreateClientConfig({
9798
+ return createClientFromInput({
8588
9799
  url: configOrUrl,
8589
9800
  key: apiKey ?? "",
8590
9801
  ...options
8591
- }));
9802
+ });
8592
9803
  }
8593
- return createClientFromConfig(resolveCreateClientConfig(configOrUrl));
9804
+ return createClientFromInput(configOrUrl);
8594
9805
  }
8595
9806
 
8596
9807
  // src/schema/postgres-introspection-core.ts
@@ -9146,16 +10357,25 @@ async function fileExists(path) {
9146
10357
  }
9147
10358
  async function writeArtifacts(files, cwd) {
9148
10359
  const writtenFiles = [];
10360
+ const skippedFiles = [];
9149
10361
  for (const file of files) {
9150
10362
  const absolutePath = path.resolve(cwd, file.path);
9151
10363
  if (!canOverwriteArtifact(file) && await fileExists(absolutePath)) {
10364
+ skippedFiles.push({
10365
+ kind: file.kind,
10366
+ path: file.path,
10367
+ reason: "protected-existing-file"
10368
+ });
9152
10369
  continue;
9153
10370
  }
9154
10371
  await promises.mkdir(path.dirname(absolutePath), { recursive: true });
9155
10372
  await promises.writeFile(absolutePath, file.content, "utf8");
9156
10373
  writtenFiles.push(file.path);
9157
10374
  }
9158
- return writtenFiles;
10375
+ return {
10376
+ writtenFiles,
10377
+ skippedFiles
10378
+ };
9159
10379
  }
9160
10380
  async function runSchemaGenerator(options = {}) {
9161
10381
  const cwd = options.cwd ?? process.cwd();
@@ -9169,12 +10389,13 @@ async function runSchemaGenerator(options = {}) {
9169
10389
  schemas: resolveProviderSchemas(config.provider)
9170
10390
  });
9171
10391
  const generated = generateArtifactsFromSnapshot(snapshot, config);
9172
- const writtenFiles = options.dryRun ? [] : await writeArtifacts(generated.files, cwd);
10392
+ const writeResult = options.dryRun ? { writtenFiles: [], skippedFiles: [] } : await writeArtifacts(generated.files, cwd);
9173
10393
  return {
9174
10394
  ...generated,
9175
10395
  configPath,
9176
10396
  config,
9177
- writtenFiles
10397
+ writtenFiles: writeResult.writtenFiles,
10398
+ skippedFiles: writeResult.skippedFiles
9178
10399
  };
9179
10400
  }
9180
10401
 
@@ -9216,24 +10437,64 @@ function generateUsage() {
9216
10437
  " athena-js generate --config ./athena.config.ts --dry-run"
9217
10438
  ].join("\n");
9218
10439
  }
9219
- function usesSchemaScopedModelTarget(target) {
9220
- return /\{schema(?:_[a-z]+)?\}/.test(target);
10440
+ function normalizePath2(pathValue) {
10441
+ return pathValue.replace(/\\/g, "/");
10442
+ }
10443
+ function isLegacyConfigRegistryTarget(target) {
10444
+ return normalizePath2(target) === "athena/config.ts";
10445
+ }
10446
+ function isFlatSchemaTarget(target) {
10447
+ return normalizePath2(target) === "athena/schema.ts";
10448
+ }
10449
+ function formatProviderLine(result) {
10450
+ const { provider } = result.config;
10451
+ if (provider.kind === "postgres") {
10452
+ const schemaList = Array.isArray(provider.schemas) ? provider.schemas.join(",") : typeof provider.schemas === "string" ? provider.schemas : "public";
10453
+ const database = provider.database ? ` database=${provider.database}` : "";
10454
+ const backend = provider.mode === "gateway" && provider.backend ? ` backend=${provider.backend}` : "";
10455
+ return `[provider] kind=${provider.kind} mode=${provider.mode}${database}${backend} schemas=${schemaList}`;
10456
+ }
10457
+ const datacenter = provider.datacenter ? ` datacenter=${provider.datacenter}` : "";
10458
+ return `[provider] kind=${provider.kind} mode=${provider.mode} keyspace=${provider.keyspace} contactPoints=${provider.contactPoints.join(",")}${datacenter}`;
10459
+ }
10460
+ function formatFilterLine(result) {
10461
+ const { includeTables, excludeTables } = result.config.filter;
10462
+ if (includeTables.length === 0 && excludeTables.length === 0) {
10463
+ return void 0;
10464
+ }
10465
+ return `[filter] include=${includeTables.length > 0 ? includeTables.join(",") : "-"} exclude=${excludeTables.length > 0 ? excludeTables.join(",") : "-"}`;
9221
10466
  }
9222
10467
  function formatGeneratorModeLines(result) {
9223
10468
  const lines = [
9224
- `[mode] format=${result.config.output.format} modelTarget=${result.config.output.targets.model}`
10469
+ `[mode] preset=${result.config.output.preset} format=${result.config.output.format} modelTarget=${result.config.output.targets.model}`,
10470
+ formatProviderLine(result),
10471
+ `[targets] schema=${result.config.output.targets.schema} database=${result.config.output.targets.database} registry=${result.config.output.targets.registry}`
9225
10472
  ];
10473
+ const filterLine = formatFilterLine(result);
10474
+ if (filterLine) {
10475
+ lines.push(filterLine);
10476
+ }
9226
10477
  if (result.config.output.format === "define-model") {
9227
10478
  lines.push(
9228
- '[note] Zero-style table-builder files are not active. Set output.format="table-builder" or ATHENA_GENERATOR_OUTPUT_FORMAT=table-builder to emit table(...).schema(...).columns(...).primaryKey(...).'
10479
+ '[note] Legacy define-model compatibility output is active. Set output.format="table-builder" or ATHENA_GENERATOR_OUTPUT_FORMAT=table-builder to emit table(...).schema(...).columns(...).primaryKey(...).'
10480
+ );
10481
+ }
10482
+ if (result.config.output.preset === "legacy") {
10483
+ lines.push(
10484
+ '[note] Legacy preset is active. It keeps registry output on athena/config.ts for compatibility; prefer output.preset="athena-direct" for the default safe direct layout.'
9229
10485
  );
9230
10486
  }
9231
10487
  lines.push(
9232
- "[note] Table-builder generation is stable. experimental.findManyAst only affects runtime findMany(...) transport and does not enable generator table output."
10488
+ "[note] Default generator mode is preset=athena-direct + format=table-builder. experimental.findManyAst only affects runtime findMany(...) transport and does not enable generator table output."
9233
10489
  );
9234
- if (usesSchemaScopedModelTarget(result.config.output.targets.model)) {
10490
+ if (isLegacyConfigRegistryTarget(result.config.output.targets.registry)) {
10491
+ lines.push(
10492
+ '[warn] Registry target points at athena/config.ts. That file is often a handwritten runtime seam; prefer output.preset="athena-direct" or output.targets.registry="athena/registry.generated.ts" unless you intentionally need legacy compatibility.'
10493
+ );
10494
+ }
10495
+ if (isFlatSchemaTarget(result.config.output.targets.schema)) {
9235
10496
  lines.push(
9236
- '[note] Flat athena/models/*.ts output is opt-in. Set output.targets.model="athena/models/{model_kebab}.ts" or ATHENA_GENERATOR_MODEL_TARGET=athena/models/{model_kebab}.ts; multi-schema collisions are still auto-scoped by schema when needed.'
10497
+ "[warn] Schema target points at athena/schema.ts. Prefer schema-scoped output such as athena/schemas/{schema_kebab}.ts."
9237
10498
  );
9238
10499
  }
9239
10500
  return lines;
@@ -9320,6 +10581,12 @@ function formatGeneratorError(error, configPath) {
9320
10581
  }
9321
10582
  return new Error(normalizeErrorMessage(error));
9322
10583
  }
10584
+ function formatSkippedArtifactLine(artifact) {
10585
+ if (artifact.reason === "protected-existing-file") {
10586
+ return ` [skip] ${artifact.path} (existing ${artifact.kind} artifacts are protected from overwrite; delete or retarget the file to regenerate it)`;
10587
+ }
10588
+ return ` [skip] ${artifact.path}`;
10589
+ }
9323
10590
  async function runCLI(argv, runtime = {}) {
9324
10591
  const log = runtime.log ?? console.log;
9325
10592
  const runGenerator = runtime.runGenerator ?? runSchemaGenerator;
@@ -9354,6 +10621,9 @@ async function runCLI(argv, runtime = {}) {
9354
10621
  for (const filePath of result.writtenFiles) {
9355
10622
  log(` - ${filePath}`);
9356
10623
  }
10624
+ for (const artifact of result.skippedFiles) {
10625
+ log(formatSkippedArtifactLine(artifact));
10626
+ }
9357
10627
  }
9358
10628
 
9359
10629
  exports.parseCommand = parseCommand;