@xylex-group/athena 2.7.0 → 2.8.2

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 (36) hide show
  1. package/README.md +218 -18
  2. package/dist/browser.cjs +2173 -675
  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 +2167 -676
  7. package/dist/browser.js.map +1 -1
  8. package/dist/cli/index.cjs +2068 -559
  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 +2068 -559
  13. package/dist/cli/index.js.map +1 -1
  14. package/dist/index.cjs +2815 -945
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +8 -7
  17. package/dist/index.d.ts +8 -7
  18. package/dist/index.js +2809 -946
  19. package/dist/index.js.map +1 -1
  20. package/dist/{model-form-AKYrgede.d.ts → model-form-Cx3wtvi8.d.ts} +963 -93
  21. package/dist/{model-form-ehfqLuG7.d.cts → model-form-_ugfOXao.d.cts} +963 -93
  22. package/dist/{pipeline-BfCWSRYl.d.cts → pipeline-BtD-Uo5X.d.cts} +1 -1
  23. package/dist/{pipeline-BUsR9XlO.d.ts → pipeline-yCIZNJHE.d.ts} +1 -1
  24. package/dist/{react-email-BQzmXBDE.d.cts → react-email-CiiSVa9F.d.cts} +121 -10
  25. package/dist/{react-email-BrVRp80B.d.ts → react-email-WN8UU3AL.d.ts} +121 -10
  26. package/dist/react.cjs +1 -1
  27. package/dist/react.cjs.map +1 -1
  28. package/dist/react.d.cts +4 -4
  29. package/dist/react.d.ts +4 -4
  30. package/dist/react.js +1 -1
  31. package/dist/react.js.map +1 -1
  32. package/dist/{types-t_TVqnmp.d.ts → types-89EfjLjV.d.cts} +48 -5
  33. package/dist/{types-BSIsyss1.d.cts → types-C2kiTt6-.d.ts} +48 -5
  34. package/dist/{types-BsyRW49r.d.cts → types-g8G6J0xE.d.cts} +26 -1
  35. package/dist/{types-BsyRW49r.d.ts → types-g8G6J0xE.d.ts} +26 -1
  36. package/package.json +28 -57
@@ -131,59 +131,6 @@ function escapeStringLiteral(value) {
131
131
  return `'${value.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
132
132
  }
133
133
 
134
- // src/generator/placeholders.ts
135
- function createStyleTokens(prefix, value) {
136
- return {
137
- [prefix]: value,
138
- [`${prefix}_camel`]: applyNamingStyle(value, "camel"),
139
- [`${prefix}_pascal`]: applyNamingStyle(value, "pascal"),
140
- [`${prefix}_snake`]: applyNamingStyle(value, "snake"),
141
- [`${prefix}_kebab`]: applyNamingStyle(value, "kebab")
142
- };
143
- }
144
- function renderTemplate(template, tokenMap) {
145
- return template.replace(/\{([A-Za-z0-9_]+)\}/g, (_match, token) => {
146
- if (!(token in tokenMap)) {
147
- throw new Error(`Unknown placeholder token "${token}" in template "${template}"`);
148
- }
149
- return tokenMap[token];
150
- });
151
- }
152
- function resolvePlaceholderMap(baseTokens, outputConfig) {
153
- const resolved = {
154
- ...baseTokens
155
- };
156
- const reservedTokenKeys = new Set(Object.keys(baseTokens));
157
- const entries = Object.entries(outputConfig.placeholderMap ?? {});
158
- for (let index = 0; index < entries.length; index += 1) {
159
- const [key, value] = entries[index];
160
- if (reservedTokenKeys.has(key)) {
161
- continue;
162
- }
163
- let current = value;
164
- for (let depth = 0; depth < 8; depth += 1) {
165
- const next = renderTemplate(current, resolved);
166
- if (next === current) {
167
- break;
168
- }
169
- current = next;
170
- }
171
- resolved[key] = current;
172
- }
173
- return resolved;
174
- }
175
- function renderOutputPath(template, context, outputConfig) {
176
- const baseTokens = {
177
- provider: context.provider,
178
- kind: context.kind,
179
- ...createStyleTokens("database", context.database),
180
- ...createStyleTokens("schema", context.schema),
181
- ...createStyleTokens("model", context.model)
182
- };
183
- const tokens = resolvePlaceholderMap(baseTokens, outputConfig);
184
- return renderTemplate(template, tokens);
185
- }
186
-
187
134
  // src/generator/postgres-type-mapping.ts
188
135
  var NUMBER_TYPES = /* @__PURE__ */ new Set([
189
136
  "int2",
@@ -757,6 +704,7 @@ var DEFAULT_TARGETS = {
757
704
  database: "athena/relations.ts",
758
705
  registry: "athena/config.ts"
759
706
  };
707
+ var DEFAULT_OUTPUT_FORMAT = "define-model";
760
708
  var DEFAULT_NAMING = {
761
709
  modelType: "pascal",
762
710
  modelConst: "camel",
@@ -772,6 +720,9 @@ var DEFAULT_EXPERIMENTAL_FLAGS = {
772
720
  postgresGatewayIntrospection: false,
773
721
  scyllaProviderContracts: true
774
722
  };
723
+ var DEFAULT_INTERNAL_CONFIG = {
724
+ schemaVersion: 1
725
+ };
775
726
  var PROJECT_ENV_FILENAMES = [".env", ".env.local"];
776
727
  var DIRECT_CONNECTION_STRING_ENV_KEYS = [
777
728
  "ATHENA_GENERATOR_PG_URL",
@@ -788,6 +739,27 @@ var GATEWAY_API_KEY_ENV_KEYS = [
788
739
  "ATHENA_GATEWAY_API_KEY",
789
740
  "ATHENA_GENERATOR_API_KEY"
790
741
  ];
742
+ var GENERATOR_SCHEMA_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMAS"];
743
+ var OUTPUT_FORMAT_ENV_KEYS = ["ATHENA_GENERATOR_OUTPUT_FORMAT"];
744
+ var MODEL_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TARGET"];
745
+ var SCHEMA_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_TARGET"];
746
+ var DATABASE_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_TARGET"];
747
+ var REGISTRY_TARGET_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_TARGET"];
748
+ var PLACEHOLDER_MAP_ENV_KEYS = ["ATHENA_GENERATOR_PLACEHOLDER_MAP"];
749
+ var MODEL_TYPE_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_TYPE", "ATHENA_GENERATOR_MODEL_STYLE"];
750
+ var MODEL_CONST_ENV_KEYS = ["ATHENA_GENERATOR_MODEL_CONST"];
751
+ var SCHEMA_CONST_ENV_KEYS = ["ATHENA_GENERATOR_SCHEMA_CONST"];
752
+ var DATABASE_CONST_ENV_KEYS = ["ATHENA_GENERATOR_DATABASE_CONST"];
753
+ var REGISTRY_CONST_ENV_KEYS = ["ATHENA_GENERATOR_REGISTRY_CONST"];
754
+ var EMIT_RELATIONS_ENV_KEYS = ["ATHENA_GENERATOR_EMIT_RELATIONS"];
755
+ var EMIT_REGISTRY_ENV_KEYS = ["ATHENA_GENERATOR_EMIT_REGISTRY"];
756
+ var GATEWAY_BACKEND_ENV_KEYS = ["ATHENA_GENERATOR_BACKEND"];
757
+ var GATEWAY_EXPERIMENTAL_ENV_KEYS = ["ATHENA_GENERATOR_GATEWAY_EXPERIMENTAL"];
758
+ var SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS = ["ATHENA_GENERATOR_SCYLLA_PROVIDER_CONTRACTS"];
759
+ var ENV_ONLY_CONFIG_PATH = "[environment defaults]";
760
+ var NAMING_STYLE_VALUES = ["preserve", "camel", "pascal", "snake", "kebab"];
761
+ var OUTPUT_FORMAT_VALUES = ["define-model", "table-builder"];
762
+ var BACKEND_TYPE_VALUES = ["athena", "postgrest", "postgresql", "scylladb"];
791
763
  function normalizeRawEnvValue(rawValue) {
792
764
  if (rawValue.startsWith('"') && rawValue.endsWith('"') && rawValue.length >= 2) {
793
765
  const inner = rawValue.slice(1, -1);
@@ -879,6 +851,50 @@ function resolveFallbackValue(fallbackKeys) {
879
851
  }
880
852
  return void 0;
881
853
  }
854
+ function normalizeOneOfValue(rawValue, allowedValues, envKeys) {
855
+ if (!rawValue) {
856
+ return void 0;
857
+ }
858
+ if (allowedValues.includes(rawValue)) {
859
+ return rawValue;
860
+ }
861
+ throw new Error(
862
+ `Generator config env vars ${envKeys.join(", ")} must resolve to one of: ${allowedValues.join(", ")}. Received: ${rawValue}.`
863
+ );
864
+ }
865
+ function resolveOptionalOneOf(envKeys, allowedValues) {
866
+ return normalizeOneOfValue(resolveFallbackValue(envKeys), allowedValues, envKeys);
867
+ }
868
+ function resolveOptionalBoolean(envKeys) {
869
+ const rawValue = resolveFallbackValue(envKeys);
870
+ return rawValue === void 0 ? void 0 : parseBooleanFlag2(rawValue, false);
871
+ }
872
+ function resolveOptionalJson(envKeys) {
873
+ const rawValue = resolveFallbackValue(envKeys);
874
+ if (rawValue === void 0) {
875
+ return void 0;
876
+ }
877
+ try {
878
+ return JSON.parse(rawValue);
879
+ } catch (error) {
880
+ const message = error instanceof Error ? error.message : String(error);
881
+ throw new Error(
882
+ `Generator config env vars ${envKeys.join(", ")} must contain valid JSON. ${message}`
883
+ );
884
+ }
885
+ }
886
+ function deriveDatabaseNameFromConnectionString(connectionString) {
887
+ try {
888
+ const parsedUrl = new URL(connectionString);
889
+ if (!POSTGRES_PROTOCOLS.has(parsedUrl.protocol)) {
890
+ return void 0;
891
+ }
892
+ const pathname = parsedUrl.pathname.replace(/^\/+/, "").trim();
893
+ return pathname.length > 0 ? decodeURIComponent(pathname) : void 0;
894
+ } catch {
895
+ return void 0;
896
+ }
897
+ }
882
898
  function normalizeOptionalString(value, fallbackKeys) {
883
899
  if (typeof value === "string") {
884
900
  const trimmed = value.trim();
@@ -952,12 +968,13 @@ function normalizeExperimentalFlags(input) {
952
968
  }
953
969
  function normalizeOutputConfig(output) {
954
970
  return {
971
+ format: output?.format ?? DEFAULT_OUTPUT_FORMAT,
955
972
  targets: {
956
973
  ...DEFAULT_TARGETS,
957
- ...output.targets ?? {}
974
+ ...output?.targets ?? {}
958
975
  },
959
976
  placeholderMap: {
960
- ...output.placeholderMap ?? {}
977
+ ...output?.placeholderMap ?? {}
961
978
  }
962
979
  };
963
980
  }
@@ -968,7 +985,7 @@ function normalizeProviderConfig(provider) {
968
985
  "provider.connectionString",
969
986
  DIRECT_CONNECTION_STRING_ENV_KEYS
970
987
  );
971
- const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS);
988
+ const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? deriveDatabaseNameFromConnectionString(connectionString);
972
989
  return {
973
990
  ...provider,
974
991
  connectionString: applyPostgresPasswordFallback(connectionString),
@@ -987,11 +1004,7 @@ function normalizeProviderConfig(provider) {
987
1004
  "provider.apiKey",
988
1005
  GATEWAY_API_KEY_ENV_KEYS
989
1006
  );
990
- const database = normalizeRequiredString(
991
- provider.database,
992
- "provider.database",
993
- POSTGRES_DATABASE_ENV_KEYS
994
- );
1007
+ const database = normalizeOptionalString(provider.database, POSTGRES_DATABASE_ENV_KEYS) ?? "postgres";
995
1008
  return {
996
1009
  ...provider,
997
1010
  gatewayUrl,
@@ -1000,6 +1013,26 @@ function normalizeProviderConfig(provider) {
1000
1013
  schemas: normalizeSchemaSelection(provider.schemas)
1001
1014
  };
1002
1015
  }
1016
+ if (provider.kind === "scylla" && provider.mode === "direct") {
1017
+ if (!provider.contactPoints?.length) {
1018
+ throw new Error(
1019
+ "Generator config is missing provider.contactPoints for scylla direct mode."
1020
+ );
1021
+ }
1022
+ const keyspace = normalizeOptionalString(provider.keyspace, []);
1023
+ if (!keyspace) {
1024
+ throw new Error(
1025
+ "Generator config is missing provider.keyspace for scylla direct mode."
1026
+ );
1027
+ }
1028
+ return {
1029
+ kind: "scylla",
1030
+ mode: "direct",
1031
+ contactPoints: provider.contactPoints.slice(),
1032
+ keyspace,
1033
+ datacenter: normalizeOptionalString(provider.datacenter, [])
1034
+ };
1035
+ }
1003
1036
  return provider;
1004
1037
  }
1005
1038
  function isAthenaGeneratorConfig(value) {
@@ -1007,7 +1040,7 @@ function isAthenaGeneratorConfig(value) {
1007
1040
  return false;
1008
1041
  }
1009
1042
  const record = value;
1010
- return Boolean(record.provider && typeof record.provider === "object") && Boolean(record.output && typeof record.output === "object");
1043
+ return Boolean(record.provider && typeof record.provider === "object") && (record.output === void 0 || typeof record.output === "object");
1011
1044
  }
1012
1045
  function normalizeGeneratorConfig(input) {
1013
1046
  return {
@@ -1018,7 +1051,10 @@ function normalizeGeneratorConfig(input) {
1018
1051
  ...input.naming ?? {}
1019
1052
  },
1020
1053
  features: normalizeFeatureFlags(input.features),
1021
- experimental: normalizeExperimentalFlags(input.experimental)
1054
+ experimental: normalizeExperimentalFlags(input.experimental),
1055
+ internal: {
1056
+ ...DEFAULT_INTERNAL_CONFIG
1057
+ }
1022
1058
  };
1023
1059
  }
1024
1060
  function findGeneratorConfigPath(cwd = process.cwd()) {
@@ -1072,16 +1108,123 @@ function importConfigModule(moduleSpecifier) {
1072
1108
  );
1073
1109
  return runtimeImport(moduleSpecifier);
1074
1110
  }
1111
+ function buildEnvironmentOutputConfig() {
1112
+ const format = resolveOptionalOneOf(OUTPUT_FORMAT_ENV_KEYS, OUTPUT_FORMAT_VALUES);
1113
+ const modelTarget = resolveFallbackValue(MODEL_TARGET_ENV_KEYS);
1114
+ const schemaTarget = resolveFallbackValue(SCHEMA_TARGET_ENV_KEYS);
1115
+ const databaseTarget = resolveFallbackValue(DATABASE_TARGET_ENV_KEYS);
1116
+ const registryTarget = resolveFallbackValue(REGISTRY_TARGET_ENV_KEYS);
1117
+ 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) {
1119
+ return void 0;
1120
+ }
1121
+ return {
1122
+ format,
1123
+ targets: {
1124
+ ...modelTarget ? { model: modelTarget } : {},
1125
+ ...schemaTarget ? { schema: schemaTarget } : {},
1126
+ ...databaseTarget ? { database: databaseTarget } : {},
1127
+ ...registryTarget ? { registry: registryTarget } : {}
1128
+ },
1129
+ placeholderMap
1130
+ };
1131
+ }
1132
+ function buildEnvironmentNamingConfig() {
1133
+ const modelType = resolveOptionalOneOf(MODEL_TYPE_ENV_KEYS, NAMING_STYLE_VALUES);
1134
+ const modelConst = resolveOptionalOneOf(MODEL_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
1135
+ const schemaConst = resolveOptionalOneOf(SCHEMA_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
1136
+ const databaseConst = resolveOptionalOneOf(DATABASE_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
1137
+ const registryConst = resolveOptionalOneOf(REGISTRY_CONST_ENV_KEYS, NAMING_STYLE_VALUES);
1138
+ if (modelType === void 0 && modelConst === void 0 && schemaConst === void 0 && databaseConst === void 0 && registryConst === void 0) {
1139
+ return void 0;
1140
+ }
1141
+ return {
1142
+ ...modelType ? { modelType } : {},
1143
+ ...modelConst ? { modelConst } : {},
1144
+ ...schemaConst ? { schemaConst } : {},
1145
+ ...databaseConst ? { databaseConst } : {},
1146
+ ...registryConst ? { registryConst } : {}
1147
+ };
1148
+ }
1149
+ function buildEnvironmentFeatureFlags() {
1150
+ const emitRelations = resolveOptionalBoolean(EMIT_RELATIONS_ENV_KEYS);
1151
+ const emitRegistry = resolveOptionalBoolean(EMIT_REGISTRY_ENV_KEYS);
1152
+ if (emitRelations === void 0 && emitRegistry === void 0) {
1153
+ return void 0;
1154
+ }
1155
+ return {
1156
+ ...emitRelations !== void 0 ? { emitRelations } : {},
1157
+ ...emitRegistry !== void 0 ? { emitRegistry } : {}
1158
+ };
1159
+ }
1160
+ function buildEnvironmentExperimentalFlags() {
1161
+ const postgresGatewayIntrospection = resolveOptionalBoolean(GATEWAY_EXPERIMENTAL_ENV_KEYS);
1162
+ const scyllaProviderContracts = resolveOptionalBoolean(SCYLLA_PROVIDER_CONTRACTS_ENV_KEYS);
1163
+ if (postgresGatewayIntrospection === void 0 && scyllaProviderContracts === void 0) {
1164
+ return void 0;
1165
+ }
1166
+ return {
1167
+ ...postgresGatewayIntrospection !== void 0 ? { postgresGatewayIntrospection } : {},
1168
+ ...scyllaProviderContracts !== void 0 ? { scyllaProviderContracts } : {}
1169
+ };
1170
+ }
1171
+ function buildEnvironmentProviderConfig() {
1172
+ const directConnectionString = resolveFallbackValue(DIRECT_CONNECTION_STRING_ENV_KEYS);
1173
+ if (directConnectionString) {
1174
+ return {
1175
+ kind: "postgres",
1176
+ mode: "direct",
1177
+ connectionString: directConnectionString,
1178
+ database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
1179
+ schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS))
1180
+ };
1181
+ }
1182
+ const gatewayUrl = resolveFallbackValue(GATEWAY_URL_ENV_KEYS);
1183
+ const apiKey = resolveFallbackValue(GATEWAY_API_KEY_ENV_KEYS);
1184
+ if (gatewayUrl && apiKey) {
1185
+ const backend = resolveOptionalOneOf(GATEWAY_BACKEND_ENV_KEYS, BACKEND_TYPE_VALUES);
1186
+ return {
1187
+ kind: "postgres",
1188
+ mode: "gateway",
1189
+ gatewayUrl,
1190
+ apiKey,
1191
+ database: normalizeOptionalString(void 0, POSTGRES_DATABASE_ENV_KEYS),
1192
+ schemas: normalizeSchemaSelection(resolveFallbackValue(GENERATOR_SCHEMA_ENV_KEYS)),
1193
+ backend
1194
+ };
1195
+ }
1196
+ return void 0;
1197
+ }
1198
+ function createEnvironmentGeneratorConfig() {
1199
+ const provider = buildEnvironmentProviderConfig();
1200
+ if (!provider) {
1201
+ return void 0;
1202
+ }
1203
+ return {
1204
+ provider,
1205
+ output: buildEnvironmentOutputConfig(),
1206
+ naming: buildEnvironmentNamingConfig(),
1207
+ features: buildEnvironmentFeatureFlags(),
1208
+ experimental: buildEnvironmentExperimentalFlags()
1209
+ };
1210
+ }
1075
1211
  async function loadGeneratorConfig(options = {}) {
1076
1212
  const cwd = options.cwd ?? process.cwd();
1077
1213
  const restoreProjectEnv = applyProjectEnv(cwd);
1078
- const resolvedPath = options.configPath ? path.resolve(cwd, options.configPath) : findGeneratorConfigPath(cwd);
1079
- if (!resolvedPath) {
1080
- throw new Error(
1081
- `No generator config found in ${cwd}. Expected one of: ${DEFAULT_CONFIG_CANDIDATES.join(", ")}`
1082
- );
1083
- }
1084
1214
  try {
1215
+ const resolvedPath = options.configPath ? path.resolve(cwd, options.configPath) : findGeneratorConfigPath(cwd);
1216
+ if (!resolvedPath) {
1217
+ const environmentConfig = createEnvironmentGeneratorConfig();
1218
+ if (environmentConfig) {
1219
+ return {
1220
+ configPath: ENV_ONLY_CONFIG_PATH,
1221
+ config: normalizeGeneratorConfig(environmentConfig)
1222
+ };
1223
+ }
1224
+ throw new Error(
1225
+ `No generator config found in ${cwd}. Expected one of: ${DEFAULT_CONFIG_CANDIDATES.join(", ")}. To run without a config file, set DATABASE_URL (direct mode) or ATHENA_URL + ATHENA_API_KEY (gateway mode).`
1226
+ );
1227
+ }
1085
1228
  const moduleUrl = url.pathToFileURL(resolvedPath);
1086
1229
  const module = await importConfigModule(`${moduleUrl.href}?cacheBust=${Date.now()}`);
1087
1230
  const rawConfig = extractConfigExport(module);
@@ -1094,7 +1237,60 @@ async function loadGeneratorConfig(options = {}) {
1094
1237
  }
1095
1238
  }
1096
1239
 
1097
- // src/generator/renderer.ts
1240
+ // src/generator/placeholders.ts
1241
+ function createStyleTokens(prefix, value) {
1242
+ return {
1243
+ [prefix]: value,
1244
+ [`${prefix}_camel`]: applyNamingStyle(value, "camel"),
1245
+ [`${prefix}_pascal`]: applyNamingStyle(value, "pascal"),
1246
+ [`${prefix}_snake`]: applyNamingStyle(value, "snake"),
1247
+ [`${prefix}_kebab`]: applyNamingStyle(value, "kebab")
1248
+ };
1249
+ }
1250
+ function renderTemplate(template, tokenMap) {
1251
+ return template.replace(/\{([A-Za-z0-9_]+)\}/g, (_match, token) => {
1252
+ if (!(token in tokenMap)) {
1253
+ throw new Error(`Unknown placeholder token "${token}" in template "${template}"`);
1254
+ }
1255
+ return tokenMap[token];
1256
+ });
1257
+ }
1258
+ function resolvePlaceholderMap(baseTokens, outputConfig) {
1259
+ const resolved = {
1260
+ ...baseTokens
1261
+ };
1262
+ const reservedTokenKeys = new Set(Object.keys(baseTokens));
1263
+ const entries = Object.entries(outputConfig.placeholderMap ?? {});
1264
+ for (let index = 0; index < entries.length; index += 1) {
1265
+ const [key, value] = entries[index];
1266
+ if (reservedTokenKeys.has(key)) {
1267
+ continue;
1268
+ }
1269
+ let current = value;
1270
+ for (let depth = 0; depth < 8; depth += 1) {
1271
+ const next = renderTemplate(current, resolved);
1272
+ if (next === current) {
1273
+ break;
1274
+ }
1275
+ current = next;
1276
+ }
1277
+ resolved[key] = current;
1278
+ }
1279
+ return resolved;
1280
+ }
1281
+ function renderOutputPath(template, context, outputConfig) {
1282
+ const baseTokens = {
1283
+ provider: context.provider,
1284
+ kind: context.kind,
1285
+ ...createStyleTokens("database", context.database),
1286
+ ...createStyleTokens("schema", context.schema),
1287
+ ...createStyleTokens("model", context.model)
1288
+ };
1289
+ const tokens = resolvePlaceholderMap(baseTokens, outputConfig);
1290
+ return renderTemplate(template, tokens);
1291
+ }
1292
+
1293
+ // src/generator/render-shared.ts
1098
1294
  function normalizePath(pathValue) {
1099
1295
  return pathValue.replace(/\\/g, "/");
1100
1296
  }
@@ -1107,11 +1303,13 @@ function toModuleImportPath(fromFile, targetFile) {
1107
1303
  );
1108
1304
  return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1109
1305
  }
1306
+ function resolveOutputPath(target, tokens, config) {
1307
+ return normalizePath(renderOutputPath(target, tokens, config.output));
1308
+ }
1110
1309
  function renderObjectKey(key) {
1111
- const escaped = escapeTypePropertyName(key);
1112
- return escaped.startsWith("'") ? escaped : escaped;
1310
+ return escapeTypePropertyName(key);
1113
1311
  }
1114
- function renderRelation(relation) {
1312
+ function renderRelationLiteral(relation) {
1115
1313
  const through = relation.through ? `,
1116
1314
  through: {
1117
1315
  schema: ${escapeStringLiteral(relation.through.schema)},
@@ -1127,54 +1325,12 @@ function renderRelation(relation) {
1127
1325
  targetColumns: [${relation.targetColumns.map((value) => escapeStringLiteral(value)).join(", ")}]${through}
1128
1326
  }`;
1129
1327
  }
1130
- function renderModelArtifact(snapshot, descriptor, config) {
1131
- const columnLines = Object.values(descriptor.table.columns).map((column) => {
1132
- const propertyName = escapeTypePropertyName(column.name);
1133
- const baseType = resolvePostgresColumnType(column);
1134
- const isOptional = column.isNullable;
1135
- const typeWithNullability = column.isNullable ? `${baseType} | null` : baseType;
1136
- return ` ${propertyName}${isOptional ? "?" : ""}: ${typeWithNullability}`;
1137
- }).join("\n");
1138
- const nullableLines = Object.values(descriptor.table.columns).map((column) => ` ${renderObjectKey(column.name)}: ${column.isNullable ? "true" : "false"}`).join(",\n");
1139
- const relationEntries = Object.entries(descriptor.table.relations);
1140
- const relationBlock = config.features.emitRelations && relationEntries.length > 0 ? `,
1141
- relations: {
1142
- ${relationEntries.map(([relationKey2, relationValue]) => ` ${renderObjectKey(relationKey2)}: ${renderRelation(relationValue)}`).join(",\n")}
1143
- }` : "";
1144
- const content = `import { defineModel } from '@xylex-group/athena'
1145
-
1146
- export interface ${descriptor.rowTypeName} {
1147
- ${columnLines}
1148
- }
1149
-
1150
- export type ${descriptor.insertTypeName} = Partial<${descriptor.rowTypeName}>
1151
- export type ${descriptor.updateTypeName} = Partial<${descriptor.insertTypeName}>
1152
-
1153
- export const ${descriptor.modelConstName} = defineModel<${descriptor.rowTypeName}, ${descriptor.insertTypeName}, ${descriptor.updateTypeName}>({
1154
- meta: {
1155
- database: ${escapeStringLiteral(snapshot.database)},
1156
- schema: ${escapeStringLiteral(descriptor.schemaName)},
1157
- model: ${escapeStringLiteral(descriptor.tableName)},
1158
- tableName: ${escapeStringLiteral(`${descriptor.schemaName}.${descriptor.tableName}`)},
1159
- primaryKey: [${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")}],
1160
- nullable: {
1161
- ${nullableLines}
1162
- }${relationBlock}
1163
- }
1164
- })
1165
- `;
1166
- return {
1167
- kind: "model",
1168
- path: descriptor.filePath,
1169
- content
1170
- };
1171
- }
1172
1328
  function renderSchemaArtifact(descriptor) {
1173
1329
  const importLines = descriptor.models.map((modelDescriptor) => {
1174
1330
  const importPath = toModuleImportPath(descriptor.filePath, modelDescriptor.filePath);
1175
- return `import { ${modelDescriptor.modelConstName} } from '${importPath}'`;
1331
+ return `import { ${modelDescriptor.exportConstName} } from '${importPath}'`;
1176
1332
  }).join("\n");
1177
- const modelEntries = descriptor.models.map((modelDescriptor) => ` ${renderObjectKey(modelDescriptor.tableName)}: ${modelDescriptor.modelConstName}`).join(",\n");
1333
+ const modelEntries = descriptor.models.map((modelDescriptor) => ` ${renderObjectKey(modelDescriptor.tableName)}: ${modelDescriptor.exportConstName}`).join(",\n");
1178
1334
  const content = `import { defineSchema } from '@xylex-group/athena'
1179
1335
  ${importLines ? `
1180
1336
  ${importLines}
@@ -1209,11 +1365,18 @@ ${schemaEntries}
1209
1365
  content
1210
1366
  };
1211
1367
  }
1212
- function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName) {
1368
+ function renderRegistryArtifact(registryPath, databasePath, databaseConstName, registryConstName, databaseName, generatedAt, outputFormat, schemaVersion) {
1213
1369
  const databaseImportPath = toModuleImportPath(registryPath, databasePath);
1214
1370
  const content = `import { defineRegistry } from '@xylex-group/athena'
1215
1371
  import { ${databaseConstName} } from '${databaseImportPath}'
1216
1372
 
1373
+ export const __athena_schema_meta = {
1374
+ schemaVersion: ${schemaVersion},
1375
+ generatedAt: ${escapeStringLiteral(generatedAt)},
1376
+ database: ${escapeStringLiteral(databaseName)},
1377
+ outputFormat: ${escapeStringLiteral(outputFormat)},
1378
+ } as const
1379
+
1217
1380
  export const ${registryConstName} = defineRegistry({
1218
1381
  ${renderObjectKey(databaseName)}: ${databaseConstName}
1219
1382
  })
@@ -1292,123 +1455,332 @@ function scopeDuplicateDescriptorPathsBySchema(descriptors) {
1292
1455
  }
1293
1456
  return nextDescriptors;
1294
1457
  }
1295
- var ArtifactComposer = class {
1296
- constructor(snapshot, config) {
1297
- this.snapshot = snapshot;
1298
- this.config = config;
1299
- }
1300
- compose() {
1301
- const providerName = this.snapshot.backend;
1302
- const databaseName = this.snapshot.database;
1303
- const modelDescriptors = [];
1304
- for (const schemaName of Object.keys(this.snapshot.schemas).sort()) {
1305
- const schema = this.snapshot.schemas[schemaName];
1306
- for (const tableName of Object.keys(schema.tables).sort()) {
1307
- const table = schema.tables[tableName];
1308
- const rowTypeName = `${toSafeIdentifier(`${schemaName} ${tableName}`, this.config.naming.modelType, "Model")}Row`;
1309
- const insertTypeName = `${toSafeIdentifier(`${schemaName} ${tableName}`, this.config.naming.modelType, "Model")}Insert`;
1310
- const updateTypeName = `${toSafeIdentifier(`${schemaName} ${tableName}`, this.config.naming.modelType, "Model")}Update`;
1311
- const modelConstName = `${toSafeIdentifier(`${schemaName} ${tableName} model`, this.config.naming.modelConst, "model")}`;
1312
- const modelPath = normalizePath(
1313
- renderOutputPath(this.config.output.targets.model, {
1314
- provider: providerName,
1315
- kind: "model",
1316
- database: databaseName,
1317
- schema: schemaName,
1318
- model: tableName
1319
- }, this.config.output)
1320
- );
1321
- modelDescriptors.push({
1458
+ function composeGeneratorArtifacts(input) {
1459
+ const { snapshot, config, createModelDescriptor, renderModelArtifact: renderModelArtifact3 } = input;
1460
+ const providerName = snapshot.backend;
1461
+ const databaseName = snapshot.database;
1462
+ const modelDescriptors = [];
1463
+ for (const schemaName of Object.keys(snapshot.schemas).sort()) {
1464
+ const schema = snapshot.schemas[schemaName];
1465
+ for (const tableName of Object.keys(schema.tables).sort()) {
1466
+ modelDescriptors.push(
1467
+ createModelDescriptor({
1468
+ providerName,
1469
+ databaseName,
1322
1470
  schemaName,
1323
1471
  tableName,
1324
- filePath: modelPath,
1325
- rowTypeName,
1326
- insertTypeName,
1327
- updateTypeName,
1328
- modelConstName,
1329
- table
1330
- });
1331
- }
1332
- }
1333
- const scopedModelDescriptors = scopeDuplicateDescriptorPathsBySchema(modelDescriptors);
1334
- let schemaDescriptors = Object.keys(this.snapshot.schemas).sort().map((schemaName) => {
1335
- const schemaPath = normalizePath(
1336
- renderOutputPath(this.config.output.targets.schema, {
1337
- provider: providerName,
1338
- kind: "schema",
1339
- database: databaseName,
1340
- schema: schemaName,
1341
- model: "index"
1342
- }, this.config.output)
1472
+ table: schema.tables[tableName]
1473
+ })
1343
1474
  );
1344
- return {
1345
- schemaName,
1346
- filePath: schemaPath,
1347
- schemaConstName: toSafeIdentifier(
1348
- `${schemaName} schema`,
1349
- this.config.naming.schemaConst,
1350
- "schema"
1351
- ),
1352
- models: scopedModelDescriptors.filter((model) => model.schemaName === schemaName)
1353
- };
1354
- });
1355
- schemaDescriptors = scopeDuplicateDescriptorPathsBySchema(schemaDescriptors);
1356
- const databasePath = normalizePath(
1357
- renderOutputPath(this.config.output.targets.database, {
1475
+ }
1476
+ }
1477
+ const scopedModelDescriptors = scopeDuplicateDescriptorPathsBySchema(modelDescriptors);
1478
+ let schemaDescriptors = Object.keys(snapshot.schemas).sort().map((schemaName) => ({
1479
+ schemaName,
1480
+ filePath: resolveOutputPath(
1481
+ config.output.targets.schema,
1482
+ {
1358
1483
  provider: providerName,
1359
- kind: "database",
1484
+ kind: "schema",
1360
1485
  database: databaseName,
1361
- schema: "index",
1486
+ schema: schemaName,
1362
1487
  model: "index"
1363
- }, this.config.output)
1364
- );
1365
- const databaseDescriptor = {
1366
- filePath: databasePath,
1367
- databaseConstName: toSafeIdentifier(
1368
- `${databaseName} database`,
1369
- this.config.naming.databaseConst,
1370
- "database"
1371
- ),
1372
- schemas: schemaDescriptors
1373
- };
1374
- const files = [];
1375
- for (const modelDescriptor of scopedModelDescriptors) {
1376
- files.push(renderModelArtifact(this.snapshot, modelDescriptor, this.config));
1377
- }
1378
- for (const schemaDescriptor of schemaDescriptors) {
1379
- files.push(renderSchemaArtifact(schemaDescriptor));
1380
- }
1381
- files.push(renderDatabaseArtifact(databaseDescriptor));
1382
- if (this.config.features.emitRegistry) {
1383
- const registryPath = normalizePath(
1384
- renderOutputPath(this.config.output.targets.registry, {
1385
- provider: providerName,
1386
- kind: "registry",
1387
- database: databaseName,
1388
- schema: "index",
1389
- model: "index"
1390
- }, this.config.output)
1391
- );
1392
- files.push(
1393
- renderRegistryArtifact(
1394
- registryPath,
1395
- databaseDescriptor.filePath,
1396
- databaseDescriptor.databaseConstName,
1397
- toSafeIdentifier("registry", this.config.naming.registryConst, "registry"),
1398
- databaseName
1399
- )
1400
- );
1401
- }
1402
- assertNoDuplicatePaths(files);
1403
- return {
1404
- snapshot: this.snapshot,
1405
- files
1406
- };
1488
+ },
1489
+ config
1490
+ ),
1491
+ schemaConstName: toSafeIdentifier(
1492
+ `${schemaName} schema`,
1493
+ config.naming.schemaConst,
1494
+ "schema"
1495
+ ),
1496
+ models: scopedModelDescriptors.filter((model) => model.schemaName === schemaName)
1497
+ }));
1498
+ schemaDescriptors = scopeDuplicateDescriptorPathsBySchema(schemaDescriptors);
1499
+ const databaseDescriptor = {
1500
+ filePath: resolveOutputPath(
1501
+ config.output.targets.database,
1502
+ {
1503
+ provider: providerName,
1504
+ kind: "database",
1505
+ database: databaseName,
1506
+ schema: "index",
1507
+ model: "index"
1508
+ },
1509
+ config
1510
+ ),
1511
+ databaseConstName: toSafeIdentifier(
1512
+ `${databaseName} database`,
1513
+ config.naming.databaseConst,
1514
+ "database"
1515
+ ),
1516
+ schemas: schemaDescriptors
1517
+ };
1518
+ const files = [];
1519
+ for (const modelDescriptor of scopedModelDescriptors) {
1520
+ files.push(renderModelArtifact3(modelDescriptor));
1407
1521
  }
1408
- };
1522
+ for (const schemaDescriptor of schemaDescriptors) {
1523
+ files.push(renderSchemaArtifact(schemaDescriptor));
1524
+ }
1525
+ files.push(renderDatabaseArtifact(databaseDescriptor));
1526
+ if (config.features.emitRegistry) {
1527
+ const registryPath = resolveOutputPath(
1528
+ config.output.targets.registry,
1529
+ {
1530
+ provider: providerName,
1531
+ kind: "registry",
1532
+ database: databaseName,
1533
+ schema: "index",
1534
+ model: "index"
1535
+ },
1536
+ config
1537
+ );
1538
+ files.push(
1539
+ renderRegistryArtifact(
1540
+ registryPath,
1541
+ databaseDescriptor.filePath,
1542
+ databaseDescriptor.databaseConstName,
1543
+ toSafeIdentifier("registry", config.naming.registryConst, "registry"),
1544
+ databaseName,
1545
+ snapshot.generatedAt,
1546
+ config.output.format,
1547
+ config.internal.schemaVersion
1548
+ )
1549
+ );
1550
+ }
1551
+ assertNoDuplicatePaths(files);
1552
+ return {
1553
+ snapshot,
1554
+ files
1555
+ };
1556
+ }
1557
+
1558
+ // src/generator/table-builder-renderer.ts
1559
+ var SAFE_NUMBER_TYPES = /* @__PURE__ */ new Set([
1560
+ "int2",
1561
+ "int4",
1562
+ "float4",
1563
+ "float8",
1564
+ "smallint",
1565
+ "integer",
1566
+ "real",
1567
+ "double precision"
1568
+ ]);
1569
+ var JSON_TYPES = /* @__PURE__ */ new Set(["json", "jsonb"]);
1570
+ var BOOLEAN_TYPES = /* @__PURE__ */ new Set(["bool", "boolean"]);
1571
+ var STRING_TYPES = /* @__PURE__ */ new Set([
1572
+ "int8",
1573
+ "bigint",
1574
+ "serial8",
1575
+ "bigserial",
1576
+ "numeric",
1577
+ "decimal",
1578
+ "money",
1579
+ "bytea"
1580
+ ]);
1581
+ function normalizeTypeLabel2(column) {
1582
+ const preferred = (column.udtName || column.dataType).toLowerCase().trim();
1583
+ if (column.arrayDimensions > 0 && preferred.startsWith("_")) {
1584
+ return preferred.slice(1);
1585
+ }
1586
+ return preferred;
1587
+ }
1588
+ function renderColumnBuilder(column) {
1589
+ const label = normalizeTypeLabel2(column);
1590
+ let helper;
1591
+ let expression;
1592
+ if (column.typeKind === "enum" && column.enumValues && column.enumValues.length > 0) {
1593
+ helper = "enumeration";
1594
+ expression = `enumeration([${column.enumValues.map((value) => escapeStringLiteral(value)).join(", ")}] as const)`;
1595
+ } else if (column.arrayDimensions > 0 || JSON_TYPES.has(label) || column.typeKind === "composite") {
1596
+ helper = "json";
1597
+ expression = `json<${resolvePostgresColumnType(column)}>()`;
1598
+ } else if (BOOLEAN_TYPES.has(label)) {
1599
+ helper = "boolean";
1600
+ expression = "boolean()";
1601
+ } else if (SAFE_NUMBER_TYPES.has(label)) {
1602
+ helper = "number";
1603
+ expression = "number()";
1604
+ } else if (STRING_TYPES.has(label)) {
1605
+ helper = "string";
1606
+ expression = "string()";
1607
+ } else {
1608
+ helper = "string";
1609
+ expression = "string()";
1610
+ }
1611
+ if (column.isNullable) {
1612
+ expression = `${expression}.optional()`;
1613
+ }
1614
+ if (column.hasDefault) {
1615
+ expression = `${expression}.defaulted()`;
1616
+ }
1617
+ if (column.isGenerated) {
1618
+ expression = `${expression}.generated()`;
1619
+ }
1620
+ return { helper, expression };
1621
+ }
1622
+ function renderModelArtifact(descriptor, config) {
1623
+ const helperImports = /* @__PURE__ */ new Set(["table"]);
1624
+ const columnLines = Object.entries(descriptor.table.columns).map(([columnName, column]) => {
1625
+ const propertyName = escapeTypePropertyName(columnName);
1626
+ const rendered = renderColumnBuilder(column);
1627
+ helperImports.add(rendered.helper);
1628
+ return ` ${propertyName}: ${rendered.expression}`;
1629
+ }).join(",\n");
1630
+ const helperImportLine = Array.from(helperImports).sort().join(", ");
1631
+ const rowSchemaConstName = `${descriptor.tableConstName}_row_schema`;
1632
+ const insertSchemaConstName = `${descriptor.tableConstName}_insert_schema`;
1633
+ const updateSchemaConstName = `${descriptor.tableConstName}_update_schema`;
1634
+ const formSchemaConstName = `${descriptor.tableConstName}_form_schema`;
1635
+ const relationEntries = Object.entries(descriptor.table.relations);
1636
+ const relationsAssignment = config.features.emitRelations && relationEntries.length > 0 ? `
1637
+ Object.assign(${descriptor.tableConstName}.meta, {
1638
+ relations: {
1639
+ ${relationEntries.map(([relationKey2, relationValue]) => ` ${renderObjectKey(relationKey2)}: ${renderRelationLiteral(relationValue)}`).join(",\n")}
1640
+ }
1641
+ })
1642
+ ` : "";
1643
+ const content = `import { ${helperImportLine} } from '@xylex-group/athena'
1644
+ import type { FormValuesOf, InsertOf, RowOf, UpdateOf } from '@xylex-group/athena'
1645
+
1646
+ export const ${descriptor.tableConstName} = table(${escapeStringLiteral(descriptor.tableName)})
1647
+ .schema(${escapeStringLiteral(descriptor.schemaName)})
1648
+ .columns({
1649
+ ${columnLines}
1650
+ })
1651
+ .primaryKey(${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")})
1652
+ ${relationsAssignment ? `${relationsAssignment}` : ""}
1653
+ export type ${descriptor.rowTypeName} = RowOf<typeof ${descriptor.tableConstName}>
1654
+ export type ${descriptor.insertTypeName} = InsertOf<typeof ${descriptor.tableConstName}>
1655
+ export type ${descriptor.updateTypeName} = UpdateOf<typeof ${descriptor.tableConstName}>
1656
+ export type ${descriptor.formValuesTypeName} = FormValuesOf<typeof ${descriptor.tableConstName}>
1657
+
1658
+ export const ${rowSchemaConstName} = ${descriptor.tableConstName}.schemas.row
1659
+ export const ${insertSchemaConstName} = ${descriptor.tableConstName}.schemas.insert
1660
+ export const ${updateSchemaConstName} = ${descriptor.tableConstName}.schemas.update
1661
+ export const ${formSchemaConstName} = ${descriptor.tableConstName}.schemas.form
1662
+ `;
1663
+ return {
1664
+ kind: "model",
1665
+ path: descriptor.filePath,
1666
+ content
1667
+ };
1668
+ }
1669
+ function generateTableBuilderArtifactsFromSnapshot(snapshot, config) {
1670
+ const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
1671
+ return composeGeneratorArtifacts({
1672
+ snapshot,
1673
+ config: normalizedConfig,
1674
+ createModelDescriptor({ providerName, databaseName, schemaName, tableName, table }) {
1675
+ const tableConstName = toSafeIdentifier(tableName, "preserve", "table");
1676
+ return {
1677
+ schemaName,
1678
+ tableName,
1679
+ filePath: resolveOutputPath(
1680
+ normalizedConfig.output.targets.model,
1681
+ {
1682
+ provider: providerName,
1683
+ kind: "model",
1684
+ database: databaseName,
1685
+ schema: schemaName,
1686
+ model: tableName
1687
+ },
1688
+ normalizedConfig
1689
+ ),
1690
+ rowTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Row`,
1691
+ insertTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Insert`,
1692
+ updateTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Update`,
1693
+ formValuesTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}FormValues`,
1694
+ tableConstName,
1695
+ exportConstName: tableConstName,
1696
+ table
1697
+ };
1698
+ },
1699
+ renderModelArtifact: (descriptor) => renderModelArtifact(descriptor, normalizedConfig)
1700
+ });
1701
+ }
1702
+
1703
+ // src/generator/renderer.ts
1704
+ function renderModelArtifact2(databaseName, descriptor, config) {
1705
+ const columnLines = Object.values(descriptor.table.columns).map((column) => {
1706
+ const propertyName = escapeTypePropertyName(column.name);
1707
+ const baseType = resolvePostgresColumnType(column);
1708
+ const isOptional = column.isNullable;
1709
+ const typeWithNullability = column.isNullable ? `${baseType} | null` : baseType;
1710
+ return ` ${propertyName}${isOptional ? "?" : ""}: ${typeWithNullability}`;
1711
+ }).join("\n");
1712
+ const nullableLines = Object.values(descriptor.table.columns).map((column) => ` ${renderObjectKey(column.name)}: ${column.isNullable ? "true" : "false"}`).join(",\n");
1713
+ const relationEntries = Object.entries(descriptor.table.relations);
1714
+ const relationBlock = config.features.emitRelations && relationEntries.length > 0 ? `,
1715
+ relations: {
1716
+ ${relationEntries.map(([relationKey2, relationValue]) => ` ${renderObjectKey(relationKey2)}: ${renderRelationLiteral(relationValue)}`).join(",\n")}
1717
+ }` : "";
1718
+ const content = `import { defineModel } from '@xylex-group/athena'
1719
+
1720
+ export interface ${descriptor.rowTypeName} {
1721
+ ${columnLines}
1722
+ }
1723
+
1724
+ export type ${descriptor.insertTypeName} = Partial<${descriptor.rowTypeName}>
1725
+ export type ${descriptor.updateTypeName} = Partial<${descriptor.insertTypeName}>
1726
+
1727
+ export const ${descriptor.modelConstName} = defineModel<${descriptor.rowTypeName}, ${descriptor.insertTypeName}, ${descriptor.updateTypeName}>({
1728
+ meta: {
1729
+ database: ${escapeStringLiteral(databaseName)},
1730
+ schema: ${escapeStringLiteral(descriptor.schemaName)},
1731
+ model: ${escapeStringLiteral(descriptor.tableName)},
1732
+ tableName: ${escapeStringLiteral(`${descriptor.schemaName}.${descriptor.tableName}`)},
1733
+ primaryKey: [${descriptor.table.primaryKey.map((value) => escapeStringLiteral(value)).join(", ")}],
1734
+ nullable: {
1735
+ ${nullableLines}
1736
+ }${relationBlock}
1737
+ }
1738
+ })
1739
+ `;
1740
+ return {
1741
+ kind: "model",
1742
+ path: descriptor.filePath,
1743
+ content
1744
+ };
1745
+ }
1409
1746
  function generateArtifactsFromSnapshot(snapshot, config) {
1410
- const normalizedConfig = "naming" in config && "features" in config && "experimental" in config ? config : normalizeGeneratorConfig(config);
1411
- return new ArtifactComposer(snapshot, normalizedConfig).compose();
1747
+ const normalizedConfig = "internal" in config ? config : normalizeGeneratorConfig(config);
1748
+ if (normalizedConfig.output.format === "table-builder") {
1749
+ return generateTableBuilderArtifactsFromSnapshot(snapshot, normalizedConfig);
1750
+ }
1751
+ return composeGeneratorArtifacts({
1752
+ snapshot,
1753
+ config: normalizedConfig,
1754
+ createModelDescriptor({ providerName, databaseName, schemaName, tableName, table }) {
1755
+ const modelConstName = toSafeIdentifier(
1756
+ `${schemaName} ${tableName} model`,
1757
+ normalizedConfig.naming.modelConst,
1758
+ "model"
1759
+ );
1760
+ return {
1761
+ schemaName,
1762
+ tableName,
1763
+ filePath: resolveOutputPath(
1764
+ normalizedConfig.output.targets.model,
1765
+ {
1766
+ provider: providerName,
1767
+ kind: "model",
1768
+ database: databaseName,
1769
+ schema: schemaName,
1770
+ model: tableName
1771
+ },
1772
+ normalizedConfig
1773
+ ),
1774
+ rowTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Row`,
1775
+ insertTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Insert`,
1776
+ updateTypeName: `${toSafeIdentifier(`${schemaName} ${tableName}`, normalizedConfig.naming.modelType, "Model")}Update`,
1777
+ modelConstName,
1778
+ exportConstName: modelConstName,
1779
+ table
1780
+ };
1781
+ },
1782
+ renderModelArtifact: (descriptor) => renderModelArtifact2(snapshot.database, descriptor, normalizedConfig)
1783
+ });
1412
1784
  }
1413
1785
 
1414
1786
  // src/gateway/url.ts
@@ -1513,7 +1885,7 @@ var getSessionCookie = (request, config) => {
1513
1885
 
1514
1886
  // package.json
1515
1887
  var package_default = {
1516
- version: "2.7.0"
1888
+ version: "2.8.2"
1517
1889
  };
1518
1890
 
1519
1891
  // src/sdk-version.ts
@@ -3460,11 +3832,12 @@ function createAuthClient(config = {}) {
3460
3832
  // src/db/module.ts
3461
3833
  function createDbModule(input) {
3462
3834
  const db = {
3463
- from(table, options) {
3464
- return input.from(table, options);
3465
- },
3466
- select(table, columns, options) {
3467
- return input.from(table).select(columns, options);
3835
+ from: input.from,
3836
+ select(table, first, second) {
3837
+ if (first && typeof first === "object" && !Array.isArray(first)) {
3838
+ return input.from(table).select(void 0, first);
3839
+ }
3840
+ return input.from(table).select(first, second);
3468
3841
  },
3469
3842
  insert(table, values, options) {
3470
3843
  return Array.isArray(values) ? input.from(table).insert(values, options) : input.from(table).insert(values, options);
@@ -3508,7 +3881,12 @@ function createStorageFileModule(base, config = {}) {
3508
3881
  content_type: input.content_type ?? source.contentType,
3509
3882
  size_bytes: source.sizeBytes,
3510
3883
  public: input.public,
3511
- metadata: input.metadata
3884
+ metadata: input.metadata,
3885
+ server_side_encryption: input.server_side_encryption,
3886
+ sse: input.sse,
3887
+ ssekms_key_id: input.ssekms_key_id,
3888
+ kms_key_id: input.kms_key_id,
3889
+ bucket_key_enabled: input.bucket_key_enabled
3512
3890
  }
3513
3891
  };
3514
3892
  });
@@ -3519,10 +3897,17 @@ function createStorageFileModule(base, config = {}) {
3519
3897
  for (let index = 0; index < uploadRequests.length; index += 1) {
3520
3898
  const request = uploadRequests[index];
3521
3899
  const uploadUrl = uploadUrls[index];
3522
- const response = await putUploadBody(uploadUrl.upload.url, request.source, input, options, (progress) => {
3523
- aggregateLoaded[index] = progress.loaded;
3524
- input.onProgress?.(createProgressSnapshot("uploading", sources, index, progress.loaded, sum(aggregateLoaded)));
3525
- });
3900
+ const response = await putUploadBody(
3901
+ uploadUrl.upload.url,
3902
+ uploadUrl.upload.headers ?? {},
3903
+ request.source,
3904
+ input,
3905
+ options,
3906
+ (progress) => {
3907
+ aggregateLoaded[index] = progress.loaded;
3908
+ input.onProgress?.(createProgressSnapshot("uploading", sources, index, progress.loaded, sum(aggregateLoaded)));
3909
+ }
3910
+ );
3526
3911
  uploaded.push({
3527
3912
  file: uploadUrl.file,
3528
3913
  upload: uploadUrl.upload,
@@ -3625,8 +4010,9 @@ function validateUploadConstraints(sources, input) {
3625
4010
  }
3626
4011
  }
3627
4012
  }
3628
- async function putUploadBody(url, source, input, options, onProgress) {
3629
- const headers = new Headers(input.uploadHeaders);
4013
+ async function putUploadBody(url, uploadHeaders, source, input, options, onProgress) {
4014
+ const headers = new Headers(uploadHeaders);
4015
+ new Headers(input.uploadHeaders).forEach((value, key) => headers.set(key, value));
3630
4016
  if (source.contentType && !headers.has("Content-Type")) {
3631
4017
  headers.set("Content-Type", source.contentType);
3632
4018
  }
@@ -3945,6 +4331,23 @@ var storageSdkManifest = {
3945
4331
  responseEnvelope: "athena",
3946
4332
  responseType: "StorageFileMutationResponse"
3947
4333
  },
4334
+ {
4335
+ name: "postStorageFileVisibility",
4336
+ method: "POST",
4337
+ path: "/storage/files/{file_id}/visibility",
4338
+ pathParams: ["file_id"],
4339
+ requestType: "SetStorageFileVisibilityRequest",
4340
+ responseEnvelope: "athena",
4341
+ responseType: "StorageFileMutationResponse"
4342
+ },
4343
+ {
4344
+ name: "setManyStorageFileVisibility",
4345
+ method: "POST",
4346
+ path: "/storage/files/visibility-many",
4347
+ requestType: "SetManyStorageFileVisibilityRequest",
4348
+ responseEnvelope: "athena",
4349
+ responseType: "StorageFileMutationManyResponse"
4350
+ },
3948
4351
  {
3949
4352
  name: "deleteStorageFolder",
3950
4353
  method: "POST",
@@ -3960,103 +4363,581 @@ var storageSdkManifest = {
3960
4363
  requestType: "MoveStorageFolderRequest",
3961
4364
  responseEnvelope: "athena",
3962
4365
  responseType: "StorageFolderMutationResponse"
3963
- }
3964
- ]
3965
- };
3966
- var AthenaStorageError = class extends Error {
3967
- code;
3968
- athenaCode;
3969
- kind;
3970
- category;
3971
- retryable;
3972
- status;
3973
- endpoint;
3974
- method;
3975
- requestId;
3976
- hint;
3977
- causeDetail;
3978
- raw;
3979
- normalized;
3980
- __athenaNormalizedError;
3981
- constructor(input) {
3982
- super(input.message, { cause: input.cause });
3983
- this.name = "AthenaStorageError";
3984
- this.code = input.code;
3985
- this.status = input.status;
3986
- this.endpoint = input.endpoint;
3987
- this.method = input.method;
3988
- this.requestId = input.requestId;
3989
- this.hint = input.hint;
3990
- this.causeDetail = causeToString(input.cause);
3991
- this.raw = input.raw ?? null;
3992
- this.normalized = normalizeStorageErrorInput(input);
3993
- this.__athenaNormalizedError = this.normalized;
3994
- this.athenaCode = this.normalized.code;
3995
- this.kind = this.normalized.kind;
3996
- this.category = this.normalized.category;
3997
- this.retryable = this.normalized.retryable;
3998
- Object.defineProperty(this, "__athenaNormalizedError", {
3999
- value: this.normalized,
4000
- enumerable: false,
4001
- configurable: false,
4002
- writable: false
4003
- });
4004
- }
4005
- toDetails() {
4006
- return {
4007
- code: this.code,
4008
- athenaCode: this.athenaCode,
4009
- kind: this.kind,
4010
- category: this.category,
4011
- retryable: this.retryable,
4012
- message: this.message,
4013
- status: this.status,
4014
- endpoint: this.endpoint,
4015
- method: this.method,
4016
- requestId: this.requestId,
4017
- hint: this.hint,
4018
- cause: this.causeDetail,
4019
- raw: this.raw
4020
- };
4021
- }
4022
- };
4023
- function isRecord6(value) {
4024
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4025
- }
4026
- function causeToString(cause) {
4027
- if (cause === void 0 || cause === null) return void 0;
4028
- if (typeof cause === "string") return cause;
4029
- if (cause instanceof Error && cause.message.trim()) return cause.message.trim();
4030
- try {
4031
- return JSON.stringify(cause);
4032
- } catch {
4033
- return String(cause);
4034
- }
4035
- }
4036
- function storageGatewayCode(code) {
4037
- if (code === "INVALID_URL") return "INVALID_URL";
4038
- if (code === "NETWORK_ERROR") return "NETWORK_ERROR";
4039
- if (code === "INVALID_JSON" || code === "INVALID_ATHENA_ENVELOPE") return "INVALID_JSON";
4040
- if (code === "HTTP_ERROR") return "HTTP_ERROR";
4041
- return "UNKNOWN_ERROR";
4042
- }
4043
- function headerValue(headers, names) {
4044
- for (const name of names) {
4045
- const value = headers.get(name);
4046
- if (value?.trim()) return value.trim();
4047
- }
4048
- return void 0;
4049
- }
4050
- function storageOperationFromEndpoint(endpoint, method) {
4051
- const endpointPath = String(endpoint).split("?")[0];
4052
- for (const candidate of storageSdkManifest.methods) {
4053
- if (candidate.method !== method) continue;
4054
- const pattern = `^${candidate.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{[^/]+\\\}/g, "[^/]+")}$`;
4055
- if (new RegExp(pattern).test(endpointPath)) {
4056
- return candidate.name;
4057
- }
4058
- }
4059
- return `storage:${method.toLowerCase()}`;
4366
+ },
4367
+ {
4368
+ name: "searchStorageFiles",
4369
+ method: "POST",
4370
+ path: "/storage/files/search",
4371
+ requestType: "SearchStorageFilesRequest",
4372
+ responseEnvelope: "athena",
4373
+ responseType: "StorageListFilesResponse"
4374
+ },
4375
+ {
4376
+ name: "confirmStorageUpload",
4377
+ method: "POST",
4378
+ path: "/storage/files/{file_id}/confirm-upload",
4379
+ pathParams: ["file_id"],
4380
+ requestType: "ConfirmStorageUploadRequest",
4381
+ responseEnvelope: "athena",
4382
+ responseType: "StorageFileMutationResponse"
4383
+ },
4384
+ {
4385
+ name: "uploadStorageFileBinary",
4386
+ method: "PUT",
4387
+ path: "/storage/files/{file_id}/upload",
4388
+ pathParams: ["file_id"],
4389
+ responseEnvelope: "athena",
4390
+ responseType: "StorageFileMutationResponse",
4391
+ binary: true
4392
+ },
4393
+ {
4394
+ name: "copyStorageFile",
4395
+ method: "POST",
4396
+ path: "/storage/files/{file_id}/copy",
4397
+ pathParams: ["file_id"],
4398
+ requestType: "CopyStorageFileRequest",
4399
+ responseEnvelope: "athena",
4400
+ responseType: "StorageFileMutationResponse"
4401
+ },
4402
+ {
4403
+ name: "deleteManyStorageFiles",
4404
+ method: "POST",
4405
+ path: "/storage/files/delete-many",
4406
+ requestType: "DeleteManyStorageFilesRequest",
4407
+ responseEnvelope: "athena",
4408
+ responseType: "StorageFileMutationManyResponse"
4409
+ },
4410
+ {
4411
+ name: "updateManyStorageFiles",
4412
+ method: "POST",
4413
+ path: "/storage/files/update-many",
4414
+ requestType: "UpdateManyStorageFilesRequest",
4415
+ responseEnvelope: "athena",
4416
+ responseType: "StorageFileMutationManyResponse"
4417
+ },
4418
+ {
4419
+ name: "restoreStorageFile",
4420
+ method: "POST",
4421
+ path: "/storage/files/{file_id}/restore",
4422
+ pathParams: ["file_id"],
4423
+ responseEnvelope: "athena",
4424
+ responseType: "StorageFileMutationResponse"
4425
+ },
4426
+ {
4427
+ name: "purgeStorageFile",
4428
+ method: "DELETE",
4429
+ path: "/storage/files/{file_id}/purge",
4430
+ pathParams: ["file_id"],
4431
+ responseEnvelope: "athena",
4432
+ responseType: "StorageFileMutationResponse"
4433
+ },
4434
+ {
4435
+ name: "getStorageFilePublicUrl",
4436
+ method: "GET",
4437
+ path: "/storage/files/{file_id}/public-url",
4438
+ pathParams: ["file_id"],
4439
+ responseEnvelope: "athena",
4440
+ responseType: "Record<string, unknown>"
4441
+ },
4442
+ {
4443
+ name: "getStorageFileProxyUrl",
4444
+ method: "GET",
4445
+ path: "/storage/files/{file_id}/proxy-url",
4446
+ pathParams: ["file_id"],
4447
+ queryParams: ["purpose"],
4448
+ responseEnvelope: "athena",
4449
+ responseType: "Record<string, unknown>"
4450
+ },
4451
+ {
4452
+ name: "listStorageFileVersions",
4453
+ method: "GET",
4454
+ path: "/storage/files/{file_id}/versions",
4455
+ pathParams: ["file_id"],
4456
+ responseEnvelope: "athena",
4457
+ responseType: "Record<string, unknown>"
4458
+ },
4459
+ {
4460
+ name: "restoreStorageFileVersion",
4461
+ method: "POST",
4462
+ path: "/storage/files/{file_id}/versions/{version_id}/restore",
4463
+ pathParams: ["file_id", "version_id"],
4464
+ responseEnvelope: "athena",
4465
+ responseType: "Record<string, unknown>"
4466
+ },
4467
+ {
4468
+ name: "deleteStorageFileVersion",
4469
+ method: "DELETE",
4470
+ path: "/storage/files/{file_id}/versions/{version_id}",
4471
+ pathParams: ["file_id", "version_id"],
4472
+ responseEnvelope: "athena",
4473
+ responseType: "Record<string, unknown>"
4474
+ },
4475
+ {
4476
+ name: "getStorageFileRetention",
4477
+ method: "GET",
4478
+ path: "/storage/files/{file_id}/retention",
4479
+ pathParams: ["file_id"],
4480
+ queryParams: ["version_id"],
4481
+ responseEnvelope: "athena",
4482
+ responseType: "Record<string, unknown>"
4483
+ },
4484
+ {
4485
+ name: "setStorageFileRetention",
4486
+ method: "POST",
4487
+ path: "/storage/files/{file_id}/retention",
4488
+ pathParams: ["file_id"],
4489
+ requestType: "StorageFileRetentionRequest",
4490
+ responseEnvelope: "athena",
4491
+ responseType: "Record<string, unknown>"
4492
+ },
4493
+ {
4494
+ name: "listStorageFolders",
4495
+ method: "POST",
4496
+ path: "/storage/folders/list",
4497
+ requestType: "ListStorageFoldersRequest",
4498
+ responseEnvelope: "athena",
4499
+ responseType: "Record<string, unknown>"
4500
+ },
4501
+ {
4502
+ name: "treeStorageFolders",
4503
+ method: "POST",
4504
+ path: "/storage/folders/tree",
4505
+ requestType: "TreeStorageFoldersRequest",
4506
+ responseEnvelope: "athena",
4507
+ responseType: "Record<string, unknown>"
4508
+ },
4509
+ {
4510
+ name: "listStoragePermissions",
4511
+ method: "POST",
4512
+ path: "/storage/permissions/list",
4513
+ requestType: "StoragePermissionListRequest",
4514
+ responseEnvelope: "athena",
4515
+ responseType: "StoragePermissionListResponse"
4516
+ },
4517
+ {
4518
+ name: "grantStoragePermission",
4519
+ method: "POST",
4520
+ path: "/storage/permissions/grant",
4521
+ requestType: "StoragePermissionGrantRequest",
4522
+ responseEnvelope: "athena",
4523
+ responseType: "Record<string, unknown>"
4524
+ },
4525
+ {
4526
+ name: "revokeStoragePermission",
4527
+ method: "POST",
4528
+ path: "/storage/permissions/revoke",
4529
+ requestType: "StoragePermissionRevokeRequest",
4530
+ responseEnvelope: "athena",
4531
+ responseType: "Record<string, unknown>"
4532
+ },
4533
+ {
4534
+ name: "checkStoragePermission",
4535
+ method: "POST",
4536
+ path: "/storage/permissions/check",
4537
+ requestType: "StoragePermissionCheckRequest",
4538
+ responseEnvelope: "athena",
4539
+ responseType: "StoragePermissionCheckResponse"
4540
+ },
4541
+ {
4542
+ name: "listStorageObjects",
4543
+ method: "POST",
4544
+ path: "/storage/objects",
4545
+ requestType: "StorageListObjectsRequest",
4546
+ responseEnvelope: "athena",
4547
+ responseType: "Record<string, unknown>"
4548
+ },
4549
+ {
4550
+ name: "headStorageObject",
4551
+ method: "POST",
4552
+ path: "/storage/objects/head",
4553
+ requestType: "StorageObjectRequest",
4554
+ responseEnvelope: "athena",
4555
+ responseType: "Record<string, unknown>"
4556
+ },
4557
+ {
4558
+ name: "existsStorageObject",
4559
+ method: "POST",
4560
+ path: "/storage/objects/exists",
4561
+ requestType: "StorageObjectRequest",
4562
+ responseEnvelope: "athena",
4563
+ responseType: "Record<string, unknown>"
4564
+ },
4565
+ {
4566
+ name: "validateStorageObject",
4567
+ method: "POST",
4568
+ path: "/storage/objects/validate",
4569
+ requestType: "StorageObjectValidateRequest",
4570
+ responseEnvelope: "athena",
4571
+ responseType: "Record<string, unknown>"
4572
+ },
4573
+ {
4574
+ name: "updateStorageObject",
4575
+ method: "POST",
4576
+ path: "/storage/objects/update",
4577
+ requestType: "StorageUpdateObjectRequest",
4578
+ responseEnvelope: "athena",
4579
+ responseType: "Record<string, unknown>"
4580
+ },
4581
+ {
4582
+ name: "copyStorageObject",
4583
+ method: "POST",
4584
+ path: "/storage/objects/copy",
4585
+ requestType: "StorageObjectCopyRequest",
4586
+ responseEnvelope: "athena",
4587
+ responseType: "Record<string, unknown>"
4588
+ },
4589
+ {
4590
+ name: "getStorageObjectUrl",
4591
+ method: "POST",
4592
+ path: "/storage/objects/url",
4593
+ requestType: "StorageObjectRequest",
4594
+ responseEnvelope: "athena",
4595
+ responseType: "Record<string, unknown>"
4596
+ },
4597
+ {
4598
+ name: "getStorageObjectPublicUrl",
4599
+ method: "POST",
4600
+ path: "/storage/objects/public-url",
4601
+ requestType: "StorageObjectPublicUrlRequest",
4602
+ responseEnvelope: "athena",
4603
+ responseType: "Record<string, unknown>"
4604
+ },
4605
+ {
4606
+ name: "deleteStorageObject",
4607
+ method: "POST",
4608
+ path: "/storage/objects/delete",
4609
+ requestType: "StorageObjectRequest",
4610
+ responseEnvelope: "athena",
4611
+ responseType: "Record<string, unknown>"
4612
+ },
4613
+ {
4614
+ name: "createStorageObjectUploadUrl",
4615
+ method: "POST",
4616
+ path: "/storage/objects/upload-url",
4617
+ requestType: "StoragePresignUploadRequest",
4618
+ responseEnvelope: "athena",
4619
+ responseType: "Record<string, unknown>"
4620
+ },
4621
+ {
4622
+ name: "createStorageObjectPostPolicy",
4623
+ method: "POST",
4624
+ path: "/storage/objects/post-policy",
4625
+ requestType: "StorageSignedPostPolicyRequest",
4626
+ responseEnvelope: "athena",
4627
+ responseType: "Record<string, unknown>"
4628
+ },
4629
+ {
4630
+ name: "listStorageObjectVersions",
4631
+ method: "POST",
4632
+ path: "/storage/objects/versions",
4633
+ requestType: "StorageObjectVersionListRequest",
4634
+ responseEnvelope: "athena",
4635
+ responseType: "Record<string, unknown>"
4636
+ },
4637
+ {
4638
+ name: "restoreStorageObjectVersion",
4639
+ method: "POST",
4640
+ path: "/storage/objects/versions/restore",
4641
+ requestType: "StorageObjectVersionMutationRequest",
4642
+ responseEnvelope: "athena",
4643
+ responseType: "Record<string, unknown>"
4644
+ },
4645
+ {
4646
+ name: "deleteStorageObjectVersion",
4647
+ method: "POST",
4648
+ path: "/storage/objects/versions/delete",
4649
+ requestType: "StorageObjectVersionMutationRequest",
4650
+ responseEnvelope: "athena",
4651
+ responseType: "Record<string, unknown>"
4652
+ },
4653
+ {
4654
+ name: "createStorageObjectFolder",
4655
+ method: "POST",
4656
+ path: "/storage/objects/folder",
4657
+ requestType: "StorageObjectFolderCreateRequest",
4658
+ responseEnvelope: "athena",
4659
+ responseType: "Record<string, unknown>"
4660
+ },
4661
+ {
4662
+ name: "deleteStorageObjectFolder",
4663
+ method: "POST",
4664
+ path: "/storage/objects/folder/delete",
4665
+ requestType: "StorageObjectFolderDeleteRequest",
4666
+ responseEnvelope: "athena",
4667
+ responseType: "Record<string, unknown>"
4668
+ },
4669
+ {
4670
+ name: "renameStorageObjectFolder",
4671
+ method: "POST",
4672
+ path: "/storage/objects/folder/rename",
4673
+ requestType: "StorageObjectFolderRenameRequest",
4674
+ responseEnvelope: "athena",
4675
+ responseType: "Record<string, unknown>"
4676
+ },
4677
+ {
4678
+ name: "listStorageBuckets",
4679
+ method: "POST",
4680
+ path: "/storage/buckets/list",
4681
+ requestType: "Omit<StorageObjectBaseRequest, 'bucket'>",
4682
+ responseEnvelope: "athena",
4683
+ responseType: "Record<string, unknown>"
4684
+ },
4685
+ {
4686
+ name: "createStorageBucket",
4687
+ method: "POST",
4688
+ path: "/storage/buckets/create",
4689
+ requestType: "StorageObjectBaseRequest",
4690
+ responseEnvelope: "athena",
4691
+ responseType: "Record<string, unknown>"
4692
+ },
4693
+ {
4694
+ name: "deleteStorageBucket",
4695
+ method: "POST",
4696
+ path: "/storage/buckets/delete",
4697
+ requestType: "StorageObjectBaseRequest",
4698
+ responseEnvelope: "athena",
4699
+ responseType: "Record<string, unknown>"
4700
+ },
4701
+ {
4702
+ name: "getStorageBucketLifecycle",
4703
+ method: "POST",
4704
+ path: "/storage/buckets/lifecycle",
4705
+ requestType: "StorageBucketLifecycleRequest",
4706
+ responseEnvelope: "athena",
4707
+ responseType: "Record<string, unknown>"
4708
+ },
4709
+ {
4710
+ name: "setStorageBucketLifecycle",
4711
+ method: "POST",
4712
+ path: "/storage/buckets/lifecycle/set",
4713
+ requestType: "StorageSetBucketLifecycleRequest",
4714
+ responseEnvelope: "athena",
4715
+ responseType: "Record<string, unknown>"
4716
+ },
4717
+ {
4718
+ name: "deleteStorageBucketLifecycle",
4719
+ method: "POST",
4720
+ path: "/storage/buckets/lifecycle/delete",
4721
+ requestType: "StorageBucketLifecycleRequest",
4722
+ responseEnvelope: "athena",
4723
+ responseType: "Record<string, unknown>"
4724
+ },
4725
+ {
4726
+ name: "getStorageBucketPolicy",
4727
+ method: "POST",
4728
+ path: "/storage/buckets/policy",
4729
+ requestType: "StorageBucketPolicyRequest",
4730
+ responseEnvelope: "athena",
4731
+ responseType: "Record<string, unknown>"
4732
+ },
4733
+ {
4734
+ name: "setStorageBucketPolicy",
4735
+ method: "POST",
4736
+ path: "/storage/buckets/policy/set",
4737
+ requestType: "StorageSetBucketPolicyRequest",
4738
+ responseEnvelope: "athena",
4739
+ responseType: "Record<string, unknown>"
4740
+ },
4741
+ {
4742
+ name: "deleteStorageBucketPolicy",
4743
+ method: "POST",
4744
+ path: "/storage/buckets/policy/delete",
4745
+ requestType: "StorageBucketPolicyRequest",
4746
+ responseEnvelope: "athena",
4747
+ responseType: "Record<string, unknown>"
4748
+ },
4749
+ {
4750
+ name: "getStorageBucketPublicAccess",
4751
+ method: "POST",
4752
+ path: "/storage/buckets/public-access",
4753
+ requestType: "StoragePublicAccessBlockRequest",
4754
+ responseEnvelope: "athena",
4755
+ responseType: "Record<string, unknown>"
4756
+ },
4757
+ {
4758
+ name: "setStorageBucketPublicAccess",
4759
+ method: "POST",
4760
+ path: "/storage/buckets/public-access/set",
4761
+ requestType: "StorageSetPublicAccessBlockRequest",
4762
+ responseEnvelope: "athena",
4763
+ responseType: "Record<string, unknown>"
4764
+ },
4765
+ {
4766
+ name: "deleteStorageBucketPublicAccess",
4767
+ method: "POST",
4768
+ path: "/storage/buckets/public-access/delete",
4769
+ requestType: "StoragePublicAccessBlockRequest",
4770
+ responseEnvelope: "athena",
4771
+ responseType: "Record<string, unknown>"
4772
+ },
4773
+ {
4774
+ name: "getStorageBucketCors",
4775
+ method: "POST",
4776
+ path: "/storage/buckets/cors",
4777
+ requestType: "StorageBucketCorsRequest",
4778
+ responseEnvelope: "athena",
4779
+ responseType: "Record<string, unknown>"
4780
+ },
4781
+ {
4782
+ name: "setStorageBucketCors",
4783
+ method: "POST",
4784
+ path: "/storage/buckets/cors/set",
4785
+ requestType: "StorageSetBucketCorsRequest",
4786
+ responseEnvelope: "athena",
4787
+ responseType: "Record<string, unknown>"
4788
+ },
4789
+ {
4790
+ name: "deleteStorageBucketCors",
4791
+ method: "POST",
4792
+ path: "/storage/buckets/cors/delete",
4793
+ requestType: "StorageBucketCorsRequest",
4794
+ responseEnvelope: "athena",
4795
+ responseType: "Record<string, unknown>"
4796
+ },
4797
+ {
4798
+ name: "createStorageMultipartUpload",
4799
+ method: "POST",
4800
+ path: "/storage/multipart/create",
4801
+ requestType: "StorageMultipartCreateRequest",
4802
+ responseEnvelope: "athena",
4803
+ responseType: "Record<string, unknown>"
4804
+ },
4805
+ {
4806
+ name: "signStorageMultipartPart",
4807
+ method: "POST",
4808
+ path: "/storage/multipart/sign-part",
4809
+ requestType: "StorageMultipartSignPartRequest",
4810
+ responseEnvelope: "athena",
4811
+ responseType: "Record<string, unknown>"
4812
+ },
4813
+ {
4814
+ name: "completeStorageMultipartUpload",
4815
+ method: "POST",
4816
+ path: "/storage/multipart/complete",
4817
+ requestType: "StorageMultipartCompleteRequest",
4818
+ responseEnvelope: "athena",
4819
+ responseType: "StorageFileMutationResponse"
4820
+ },
4821
+ {
4822
+ name: "abortStorageMultipartUpload",
4823
+ method: "POST",
4824
+ path: "/storage/multipart/abort",
4825
+ requestType: "StorageMultipartAbortRequest",
4826
+ responseEnvelope: "athena",
4827
+ responseType: "Record<string, unknown>"
4828
+ },
4829
+ {
4830
+ name: "listStorageMultipartParts",
4831
+ method: "POST",
4832
+ path: "/storage/multipart/list-parts",
4833
+ requestType: "StorageMultipartListPartsRequest",
4834
+ responseEnvelope: "athena",
4835
+ responseType: "Record<string, unknown>"
4836
+ },
4837
+ {
4838
+ name: "listStorageAuditEvents",
4839
+ method: "POST",
4840
+ path: "/storage/audit/list",
4841
+ requestType: "StorageAuditQueryRequest",
4842
+ responseEnvelope: "athena",
4843
+ responseType: "StorageAuditListResponse"
4844
+ }
4845
+ ]
4846
+ };
4847
+ var AthenaStorageError = class extends Error {
4848
+ code;
4849
+ athenaCode;
4850
+ kind;
4851
+ category;
4852
+ retryable;
4853
+ status;
4854
+ endpoint;
4855
+ method;
4856
+ requestId;
4857
+ hint;
4858
+ causeDetail;
4859
+ raw;
4860
+ normalized;
4861
+ __athenaNormalizedError;
4862
+ constructor(input) {
4863
+ super(input.message, { cause: input.cause });
4864
+ this.name = "AthenaStorageError";
4865
+ this.code = input.code;
4866
+ this.status = input.status;
4867
+ this.endpoint = input.endpoint;
4868
+ this.method = input.method;
4869
+ this.requestId = input.requestId;
4870
+ this.hint = input.hint;
4871
+ this.causeDetail = causeToString(input.cause);
4872
+ this.raw = input.raw ?? null;
4873
+ this.normalized = normalizeStorageErrorInput(input);
4874
+ this.__athenaNormalizedError = this.normalized;
4875
+ this.athenaCode = this.normalized.code;
4876
+ this.kind = this.normalized.kind;
4877
+ this.category = this.normalized.category;
4878
+ this.retryable = this.normalized.retryable;
4879
+ Object.defineProperty(this, "__athenaNormalizedError", {
4880
+ value: this.normalized,
4881
+ enumerable: false,
4882
+ configurable: false,
4883
+ writable: false
4884
+ });
4885
+ }
4886
+ toDetails() {
4887
+ return {
4888
+ code: this.code,
4889
+ athenaCode: this.athenaCode,
4890
+ kind: this.kind,
4891
+ category: this.category,
4892
+ retryable: this.retryable,
4893
+ message: this.message,
4894
+ status: this.status,
4895
+ endpoint: this.endpoint,
4896
+ method: this.method,
4897
+ requestId: this.requestId,
4898
+ hint: this.hint,
4899
+ cause: this.causeDetail,
4900
+ raw: this.raw
4901
+ };
4902
+ }
4903
+ };
4904
+ function isRecord6(value) {
4905
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
4906
+ }
4907
+ function causeToString(cause) {
4908
+ if (cause === void 0 || cause === null) return void 0;
4909
+ if (typeof cause === "string") return cause;
4910
+ if (cause instanceof Error && cause.message.trim()) return cause.message.trim();
4911
+ try {
4912
+ return JSON.stringify(cause);
4913
+ } catch {
4914
+ return String(cause);
4915
+ }
4916
+ }
4917
+ function storageGatewayCode(code) {
4918
+ if (code === "INVALID_URL") return "INVALID_URL";
4919
+ if (code === "NETWORK_ERROR") return "NETWORK_ERROR";
4920
+ if (code === "INVALID_JSON" || code === "INVALID_ATHENA_ENVELOPE") return "INVALID_JSON";
4921
+ if (code === "HTTP_ERROR") return "HTTP_ERROR";
4922
+ return "UNKNOWN_ERROR";
4923
+ }
4924
+ function headerValue(headers, names) {
4925
+ for (const name of names) {
4926
+ const value = headers.get(name);
4927
+ if (value?.trim()) return value.trim();
4928
+ }
4929
+ return void 0;
4930
+ }
4931
+ function storageOperationFromEndpoint(endpoint, method) {
4932
+ const endpointPath = String(endpoint).split("?")[0];
4933
+ for (const candidate of storageSdkManifest.methods) {
4934
+ if (candidate.method !== method) continue;
4935
+ const pattern = `^${candidate.path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\{[^/]+\\\}/g, "[^/]+")}$`;
4936
+ if (new RegExp(pattern).test(endpointPath)) {
4937
+ return candidate.name;
4938
+ }
4939
+ }
4940
+ return `storage:${method.toLowerCase()}`;
4060
4941
  }
4061
4942
  function normalizeStorageErrorInput(input) {
4062
4943
  return normalizeAthenaError(
@@ -4131,6 +5012,15 @@ function appendQuery(path, query) {
4131
5012
  function storagePath(path) {
4132
5013
  return path;
4133
5014
  }
5015
+ function resolveStorageEndpointPath(endpoint, runtimeOptions) {
5016
+ if (!runtimeOptions?.stripBasePath) {
5017
+ return endpoint;
5018
+ }
5019
+ const [pathname, queryText] = String(endpoint).split("?", 2);
5020
+ const trimmedPathname = pathname.startsWith("/storage/") ? pathname.slice("/storage".length) : pathname === "/storage" ? "/" : pathname;
5021
+ const resolvedPath = trimmedPathname.startsWith("/") ? trimmedPathname : `/${trimmedPathname}`;
5022
+ return storagePath(queryText ? `${resolvedPath}?${queryText}` : resolvedPath);
5023
+ }
4134
5024
  function withPathParam(path, name, value) {
4135
5025
  return path.replace(`{${name}}`, encodeURIComponent(value));
4136
5026
  }
@@ -4169,8 +5059,8 @@ async function callStorageEndpoint(gateway, endpoint, method, envelope, payload,
4169
5059
  let url;
4170
5060
  let headers;
4171
5061
  try {
4172
- const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4173
- url = buildAthenaGatewayUrl(baseUrl, endpoint);
5062
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : runtimeOptions?.baseUrl ? normalizeAthenaGatewayBaseUrl(runtimeOptions.baseUrl) : gateway.baseUrl;
5063
+ url = buildAthenaGatewayUrl(baseUrl, resolveStorageEndpointPath(endpoint, runtimeOptions));
4174
5064
  headers = gateway.buildHeaders(options);
4175
5065
  } catch (error) {
4176
5066
  return rejectStorageError(
@@ -4294,8 +5184,8 @@ async function callStorageBinaryEndpoint(gateway, endpoint, method, options, run
4294
5184
  let url;
4295
5185
  let headers;
4296
5186
  try {
4297
- const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4298
- url = buildAthenaGatewayUrl(baseUrl, endpoint);
5187
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : runtimeOptions?.baseUrl ? normalizeAthenaGatewayBaseUrl(runtimeOptions.baseUrl) : gateway.baseUrl;
5188
+ url = buildAthenaGatewayUrl(baseUrl, resolveStorageEndpointPath(endpoint, runtimeOptions));
4299
5189
  headers = gateway.buildHeaders(options);
4300
5190
  } catch (error) {
4301
5191
  return rejectStorageError(
@@ -4403,7 +5293,7 @@ async function putPresignedUploadBody(uploadUrl, uploadHeaders, body, options) {
4403
5293
  return fetch(uploadUrl, init);
4404
5294
  }
4405
5295
  function attachManagedUpload(upload) {
4406
- const headers = {};
5296
+ const headers = { ...upload.headers ?? {} };
4407
5297
  return {
4408
5298
  ...upload,
4409
5299
  method: "PUT",
@@ -4449,15 +5339,20 @@ function normalizeUploadUrlRequest(input) {
4449
5339
  file_id: input.file_id ?? input.fileId,
4450
5340
  public: input.public,
4451
5341
  visibility: input.visibility,
4452
- metadata: input.metadata
5342
+ metadata: input.metadata,
5343
+ server_side_encryption: input.server_side_encryption,
5344
+ sse: input.sse,
5345
+ ssekms_key_id: input.ssekms_key_id,
5346
+ kms_key_id: input.kms_key_id,
5347
+ bucket_key_enabled: input.bucket_key_enabled
4453
5348
  };
4454
5349
  }
4455
5350
  async function callStorageUploadBinaryEndpoint(gateway, endpoint, body, options, runtimeOptions) {
4456
5351
  let url;
4457
5352
  let headers;
4458
5353
  try {
4459
- const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : gateway.baseUrl;
4460
- url = buildAthenaGatewayUrl(baseUrl, endpoint);
5354
+ const baseUrl = options?.baseUrl ? normalizeAthenaGatewayBaseUrl(options.baseUrl) : runtimeOptions?.baseUrl ? normalizeAthenaGatewayBaseUrl(runtimeOptions.baseUrl) : gateway.baseUrl;
5355
+ url = buildAthenaGatewayUrl(baseUrl, resolveStorageEndpointPath(endpoint, runtimeOptions));
4461
5356
  headers = gateway.buildHeaders(options);
4462
5357
  } catch (error) {
4463
5358
  return rejectStorageError(
@@ -4581,6 +5476,7 @@ async function callStorageUploadBinaryEndpoint(gateway, endpoint, body, options,
4581
5476
  return parsedBody.parsed.data;
4582
5477
  }
4583
5478
  function createStorageModule(gateway, runtimeOptions) {
5479
+ const resolvedRuntimeOptions = runtimeOptions;
4584
5480
  const callRaw = (path, method, payload, options) => callStorageEndpoint(
4585
5481
  gateway,
4586
5482
  storagePath(path),
@@ -4588,7 +5484,7 @@ function createStorageModule(gateway, runtimeOptions) {
4588
5484
  "raw",
4589
5485
  payload,
4590
5486
  options,
4591
- runtimeOptions
5487
+ resolvedRuntimeOptions
4592
5488
  );
4593
5489
  const callAthena2 = (path, method, payload, options) => callStorageEndpoint(
4594
5490
  gateway,
@@ -4597,7 +5493,13 @@ function createStorageModule(gateway, runtimeOptions) {
4597
5493
  "athena",
4598
5494
  payload,
4599
5495
  options,
4600
- runtimeOptions
5496
+ resolvedRuntimeOptions
5497
+ );
5498
+ const callStorageFileVisibility = (fileId, method, input, options) => callAthena2(
5499
+ withPathParam("/storage/files/{file_id}/visibility", "file_id", fileId),
5500
+ method,
5501
+ input,
5502
+ options
4601
5503
  );
4602
5504
  const base = {
4603
5505
  listStorageCatalogs(options) {
@@ -4639,7 +5541,7 @@ function createStorageModule(gateway, runtimeOptions) {
4639
5541
  withPathParam("/storage/files/{file_id}/proxy", "file_id", fileId),
4640
5542
  query
4641
5543
  );
4642
- return callStorageBinaryEndpoint(gateway, storagePath(path), "GET", options, runtimeOptions);
5544
+ return callStorageBinaryEndpoint(gateway, storagePath(path), "GET", options, resolvedRuntimeOptions);
4643
5545
  },
4644
5546
  updateStorageFile(fileId, input, options) {
4645
5547
  return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "PATCH", input, options);
@@ -4648,7 +5550,7 @@ function createStorageModule(gateway, runtimeOptions) {
4648
5550
  return callAthena2(withPathParam("/storage/files/{file_id}", "file_id", fileId), "DELETE", void 0, options);
4649
5551
  },
4650
5552
  setStorageFileVisibility(fileId, input, options) {
4651
- return callAthena2(withPathParam("/storage/files/{file_id}/visibility", "file_id", fileId), "PATCH", input, options);
5553
+ return callStorageFileVisibility(fileId, "PATCH", input, options);
4652
5554
  },
4653
5555
  deleteStorageFolder(input, options) {
4654
5556
  return callAthena2("/storage/folders/delete", "POST", input, options);
@@ -4686,7 +5588,7 @@ function createStorageModule(gateway, runtimeOptions) {
4686
5588
  storagePath(withPathParam("/storage/files/{file_id}/upload", "file_id", fileId)),
4687
5589
  body,
4688
5590
  options,
4689
- runtimeOptions
5591
+ resolvedRuntimeOptions
4690
5592
  );
4691
5593
  },
4692
5594
  search(input, options) {
@@ -4720,13 +5622,62 @@ function createStorageModule(gateway, runtimeOptions) {
4720
5622
  publicUrl(fileId, options) {
4721
5623
  return callAthena2(withPathParam("/storage/files/{file_id}/public-url", "file_id", fileId), "GET", void 0, options);
4722
5624
  },
5625
+ proxyUrl(fileId, query, options) {
5626
+ const path = appendQuery(
5627
+ withPathParam("/storage/files/{file_id}/proxy-url", "file_id", fileId),
5628
+ query
5629
+ );
5630
+ return callAthena2(path, "GET", void 0, options);
5631
+ },
4723
5632
  proxy(fileId, query, options) {
4724
5633
  return base.getStorageFileProxy(fileId, query, options);
4725
5634
  },
4726
- visibility: {
5635
+ versions(fileId, options) {
5636
+ return callAthena2(withPathParam("/storage/files/{file_id}/versions", "file_id", fileId), "GET", void 0, options);
5637
+ },
5638
+ restoreVersion(fileId, versionId, options) {
5639
+ return callAthena2(
5640
+ withPathParam(
5641
+ withPathParam("/storage/files/{file_id}/versions/{version_id}/restore", "file_id", fileId),
5642
+ "version_id",
5643
+ versionId
5644
+ ),
5645
+ "POST",
5646
+ {},
5647
+ options
5648
+ );
5649
+ },
5650
+ deleteVersion(fileId, versionId, options) {
5651
+ return callAthena2(
5652
+ withPathParam(
5653
+ withPathParam("/storage/files/{file_id}/versions/{version_id}", "file_id", fileId),
5654
+ "version_id",
5655
+ versionId
5656
+ ),
5657
+ "DELETE",
5658
+ void 0,
5659
+ options
5660
+ );
5661
+ },
5662
+ retention: {
5663
+ get(fileId, query, options) {
5664
+ const path = appendQuery(
5665
+ withPathParam("/storage/files/{file_id}/retention", "file_id", fileId),
5666
+ query
5667
+ );
5668
+ return callAthena2(path, "GET", void 0, options);
5669
+ },
4727
5670
  set(fileId, input, options) {
5671
+ return callAthena2(withPathParam("/storage/files/{file_id}/retention", "file_id", fileId), "POST", input, options);
5672
+ }
5673
+ },
5674
+ visibility: {
5675
+ update(fileId, input, options) {
4728
5676
  return base.setStorageFileVisibility(fileId, input, options);
4729
5677
  },
5678
+ set(fileId, input, options) {
5679
+ return callStorageFileVisibility(fileId, "POST", input, options);
5680
+ },
4730
5681
  setMany(input, options) {
4731
5682
  return callAthena2("/storage/files/visibility-many", "POST", input, options);
4732
5683
  }
@@ -4821,6 +5772,18 @@ function createStorageModule(gateway, runtimeOptions) {
4821
5772
  uploadUrl(input, options) {
4822
5773
  return callAthena2("/storage/objects/upload-url", "POST", input, options);
4823
5774
  },
5775
+ versions(input, options) {
5776
+ return callAthena2("/storage/objects/versions", "POST", input, options);
5777
+ },
5778
+ restoreVersion(input, options) {
5779
+ return callAthena2("/storage/objects/versions/restore", "POST", input, options);
5780
+ },
5781
+ deleteVersion(input, options) {
5782
+ return callAthena2("/storage/objects/versions/delete", "POST", input, options);
5783
+ },
5784
+ postPolicy(input, options) {
5785
+ return callAthena2("/storage/objects/post-policy", "POST", input, options);
5786
+ },
4824
5787
  folder: objectFolder
4825
5788
  };
4826
5789
  const bucket = {
@@ -4833,6 +5796,39 @@ function createStorageModule(gateway, runtimeOptions) {
4833
5796
  delete(input, options) {
4834
5797
  return callAthena2("/storage/buckets/delete", "POST", input, options);
4835
5798
  },
5799
+ lifecycle: {
5800
+ get(input, options) {
5801
+ return callAthena2("/storage/buckets/lifecycle", "POST", input, options);
5802
+ },
5803
+ set(input, options) {
5804
+ return callAthena2("/storage/buckets/lifecycle/set", "POST", input, options);
5805
+ },
5806
+ delete(input, options) {
5807
+ return callAthena2("/storage/buckets/lifecycle/delete", "POST", input, options);
5808
+ }
5809
+ },
5810
+ policy: {
5811
+ get(input, options) {
5812
+ return callAthena2("/storage/buckets/policy", "POST", input, options);
5813
+ },
5814
+ set(input, options) {
5815
+ return callAthena2("/storage/buckets/policy/set", "POST", input, options);
5816
+ },
5817
+ delete(input, options) {
5818
+ return callAthena2("/storage/buckets/policy/delete", "POST", input, options);
5819
+ }
5820
+ },
5821
+ publicAccess: {
5822
+ get(input, options) {
5823
+ return callAthena2("/storage/buckets/public-access", "POST", input, options);
5824
+ },
5825
+ set(input, options) {
5826
+ return callAthena2("/storage/buckets/public-access/set", "POST", input, options);
5827
+ },
5828
+ delete(input, options) {
5829
+ return callAthena2("/storage/buckets/public-access/delete", "POST", input, options);
5830
+ }
5831
+ },
4836
5832
  cors: {
4837
5833
  get(input, options) {
4838
5834
  return callAthena2("/storage/buckets/cors", "POST", input, options);
@@ -4882,6 +5878,13 @@ function createStorageModule(gateway, runtimeOptions) {
4882
5878
  };
4883
5879
  }
4884
5880
 
5881
+ // src/client-builder.ts
5882
+ var DEFAULT_BACKEND = { type: "athena" };
5883
+ function toBackendConfig(value) {
5884
+ if (!value) return DEFAULT_BACKEND;
5885
+ return typeof value === "string" ? { type: value } : value;
5886
+ }
5887
+
4885
5888
  // src/query-ast.ts
4886
5889
  var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
4887
5890
  var FILTER_OPERATORS = /* @__PURE__ */ new Set([
@@ -5504,20 +6507,437 @@ function createSelectTransportPlan(input) {
5504
6507
  };
5505
6508
  }
5506
6509
 
6510
+ // src/query-debug-ast.ts
6511
+ var ATHENA_DEBUG_AST_KEY = "__athenaDebugAst";
6512
+ function cloneConditions(conditions) {
6513
+ return conditions.map((condition) => ({ ...condition }));
6514
+ }
6515
+ function cloneTableBuilderStateAst(state) {
6516
+ return {
6517
+ conditions: cloneConditions(state.conditions),
6518
+ limit: state.limit,
6519
+ offset: state.offset,
6520
+ order: state.order ? { ...state.order } : void 0,
6521
+ currentPage: state.currentPage,
6522
+ pageSize: state.pageSize,
6523
+ totalPages: state.totalPages
6524
+ };
6525
+ }
6526
+ function cloneRpcBuilderStateAst(state) {
6527
+ return {
6528
+ filters: state.filters.map((filter) => ({ ...filter })),
6529
+ limit: state.limit,
6530
+ offset: state.offset,
6531
+ order: state.order ? { ...state.order } : void 0
6532
+ };
6533
+ }
6534
+ function toSelectTransportAst(plan) {
6535
+ if (plan.kind === "query") {
6536
+ return {
6537
+ mode: "typed-query",
6538
+ endpoint: "/gateway/query",
6539
+ payload: plan.payload
6540
+ };
6541
+ }
6542
+ return {
6543
+ mode: plan.payload.select !== void 0 ? "structured-fetch" : "compiled-fetch",
6544
+ endpoint: "/gateway/fetch",
6545
+ payload: plan.payload
6546
+ };
6547
+ }
6548
+ function resolveDebugTableName(tableName) {
6549
+ return tableName ?? "__unknown_table__";
6550
+ }
6551
+ function buildSelectDebugAst(input) {
6552
+ return {
6553
+ version: 1,
6554
+ kind: "select",
6555
+ tableName: input.tableName,
6556
+ input: {
6557
+ columns: input.columns,
6558
+ state: cloneTableBuilderStateAst(input.state)
6559
+ },
6560
+ transport: toSelectTransportAst(input.plan)
6561
+ };
6562
+ }
6563
+ function buildFindManyCompiledDebugAst(input) {
6564
+ return {
6565
+ version: 1,
6566
+ kind: "findMany",
6567
+ tableName: input.tableName,
6568
+ input: {
6569
+ select: input.options.select,
6570
+ where: input.options.where,
6571
+ orderBy: input.options.orderBy,
6572
+ limit: input.options.limit
6573
+ },
6574
+ compiled: {
6575
+ columns: input.compiledColumns,
6576
+ baseState: cloneTableBuilderStateAst(input.baseState),
6577
+ executionState: cloneTableBuilderStateAst(input.executionState)
6578
+ },
6579
+ transport: planToFindManyTransport(input.plan)
6580
+ };
6581
+ }
6582
+ function buildFindManyDirectDebugAst(input) {
6583
+ return {
6584
+ version: 1,
6585
+ kind: "findMany",
6586
+ tableName: input.tableName,
6587
+ input: {
6588
+ select: input.options.select,
6589
+ where: input.options.where,
6590
+ orderBy: input.options.orderBy,
6591
+ limit: input.options.limit
6592
+ },
6593
+ compiled: {
6594
+ columns: input.compiledColumns,
6595
+ baseState: cloneTableBuilderStateAst(input.baseState),
6596
+ executionState: cloneTableBuilderStateAst(input.executionState)
6597
+ },
6598
+ transport: {
6599
+ mode: "direct-ast-fetch",
6600
+ endpoint: "/gateway/fetch",
6601
+ payload: input.payload
6602
+ }
6603
+ };
6604
+ }
6605
+ function planToFindManyTransport(plan) {
6606
+ if (plan.kind === "query") {
6607
+ return {
6608
+ mode: "compiled-query",
6609
+ endpoint: "/gateway/query",
6610
+ payload: plan.payload
6611
+ };
6612
+ }
6613
+ return {
6614
+ mode: plan.payload.select !== void 0 ? "structured-fetch" : "compiled-fetch",
6615
+ endpoint: "/gateway/fetch",
6616
+ payload: plan.payload
6617
+ };
6618
+ }
6619
+ function buildInsertDebugAst(payload) {
6620
+ return {
6621
+ version: 1,
6622
+ kind: "insert",
6623
+ tableName: payload.table_name,
6624
+ input: {
6625
+ values: payload.insert_body,
6626
+ returning: payload.columns,
6627
+ count: payload.count,
6628
+ head: payload.head,
6629
+ defaultToNull: payload.default_to_null
6630
+ },
6631
+ transport: {
6632
+ mode: "insert",
6633
+ endpoint: "/gateway/insert",
6634
+ payload
6635
+ }
6636
+ };
6637
+ }
6638
+ function buildUpsertDebugAst(payload) {
6639
+ return {
6640
+ version: 1,
6641
+ kind: "upsert",
6642
+ tableName: payload.table_name,
6643
+ input: {
6644
+ values: payload.insert_body,
6645
+ updateBody: payload.update_body,
6646
+ onConflict: payload.on_conflict,
6647
+ returning: payload.columns,
6648
+ count: payload.count,
6649
+ head: payload.head,
6650
+ defaultToNull: payload.default_to_null
6651
+ },
6652
+ transport: {
6653
+ mode: "upsert",
6654
+ endpoint: "/gateway/insert",
6655
+ payload
6656
+ }
6657
+ };
6658
+ }
6659
+ function buildUpdateDebugAst(input) {
6660
+ return {
6661
+ version: 1,
6662
+ kind: "update",
6663
+ tableName: resolveDebugTableName(input.payload.table_name),
6664
+ input: {
6665
+ values: input.payload.set,
6666
+ state: cloneTableBuilderStateAst(input.state),
6667
+ returning: input.payload.columns
6668
+ },
6669
+ transport: {
6670
+ mode: "update",
6671
+ endpoint: "/gateway/update",
6672
+ payload: input.payload
6673
+ }
6674
+ };
6675
+ }
6676
+ function buildDeleteDebugAst(input) {
6677
+ return {
6678
+ version: 1,
6679
+ kind: "delete",
6680
+ tableName: input.payload.table_name,
6681
+ input: {
6682
+ resourceId: input.payload.resource_id,
6683
+ state: cloneTableBuilderStateAst(input.state),
6684
+ returning: input.payload.columns
6685
+ },
6686
+ transport: {
6687
+ mode: "delete",
6688
+ endpoint: "/gateway/delete",
6689
+ payload: input.payload
6690
+ }
6691
+ };
6692
+ }
6693
+ function buildRpcDebugAst(input) {
6694
+ return {
6695
+ version: 1,
6696
+ kind: "rpc",
6697
+ functionName: input.functionName,
6698
+ input: {
6699
+ args: input.args,
6700
+ select: input.selectedColumns,
6701
+ state: cloneRpcBuilderStateAst(input.state)
6702
+ },
6703
+ transport: {
6704
+ mode: input.endpoint === "/gateway/rpc" ? "rpc-post" : "rpc-get",
6705
+ endpoint: input.endpoint,
6706
+ payload: input.payload
6707
+ }
6708
+ };
6709
+ }
6710
+ function buildRawQueryDebugAst(query) {
6711
+ return {
6712
+ version: 1,
6713
+ kind: "query",
6714
+ input: {
6715
+ query
6716
+ },
6717
+ transport: {
6718
+ mode: "raw-query",
6719
+ endpoint: "/gateway/query",
6720
+ payload: {
6721
+ query
6722
+ }
6723
+ }
6724
+ };
6725
+ }
6726
+ function attachAthenaDebugAst(target, ast) {
6727
+ if (!ast) {
6728
+ return;
6729
+ }
6730
+ if (!target || typeof target !== "object" && typeof target !== "function") {
6731
+ return;
6732
+ }
6733
+ Object.defineProperty(target, ATHENA_DEBUG_AST_KEY, {
6734
+ value: ast,
6735
+ enumerable: false,
6736
+ configurable: true,
6737
+ writable: false
6738
+ });
6739
+ }
6740
+
6741
+ // src/query-tracing.ts
6742
+ var QUERY_TRACE_STACK_SKIP_PATTERNS = [
6743
+ "src\\client.ts",
6744
+ "src/client.ts",
6745
+ "src\\query-tracing.ts",
6746
+ "src/query-tracing.ts",
6747
+ "dist\\client.",
6748
+ "dist/client.",
6749
+ "dist\\query-tracing.",
6750
+ "dist/query-tracing.",
6751
+ "node_modules\\@xylex-group\\athena",
6752
+ "node_modules/@xylex-group/athena",
6753
+ "node:internal",
6754
+ "internal/process"
6755
+ ];
6756
+ function parseQueryTraceCallsiteFrame(frame) {
6757
+ const trimmed = frame.trim();
6758
+ if (!trimmed) {
6759
+ return null;
6760
+ }
6761
+ let body = trimmed.replace(/^at\s+/, "");
6762
+ if (body.startsWith("async ")) {
6763
+ body = body.slice(6);
6764
+ }
6765
+ let functionName;
6766
+ let location = body;
6767
+ const wrappedMatch = body.match(/^(.*?)\s+\((.*)\)$/);
6768
+ if (wrappedMatch) {
6769
+ functionName = wrappedMatch[1].trim() || void 0;
6770
+ location = wrappedMatch[2].trim();
6771
+ }
6772
+ const locationMatch = location.match(/^(.*):(\d+):(\d+)$/);
6773
+ if (!locationMatch) {
6774
+ return null;
6775
+ }
6776
+ const filePath = locationMatch[1].replace(/^file:\/\//, "");
6777
+ const line = Number(locationMatch[2]);
6778
+ const column = Number(locationMatch[3]);
6779
+ if (!Number.isFinite(line) || !Number.isFinite(column)) {
6780
+ return null;
6781
+ }
6782
+ const normalizedPath = filePath.replace(/\\/g, "/");
6783
+ const fileName = normalizedPath.split("/").at(-1) ?? filePath;
6784
+ return {
6785
+ filePath,
6786
+ fileName,
6787
+ line,
6788
+ column,
6789
+ frame: trimmed,
6790
+ functionName
6791
+ };
6792
+ }
6793
+ function captureQueryTraceCallsite() {
6794
+ const stack = new Error().stack;
6795
+ if (!stack) return null;
6796
+ const frames = stack.split("\n").slice(2).map((frame) => frame.trim()).filter(Boolean);
6797
+ for (const frame of frames) {
6798
+ if (QUERY_TRACE_STACK_SKIP_PATTERNS.some((pattern) => frame.includes(pattern))) {
6799
+ continue;
6800
+ }
6801
+ const callsite = parseQueryTraceCallsiteFrame(frame);
6802
+ if (callsite) return callsite;
6803
+ }
6804
+ const fallback = frames.find((frame) => !frame.includes("captureQueryTraceCallsite"));
6805
+ return fallback ? parseQueryTraceCallsiteFrame(fallback) : null;
6806
+ }
6807
+ function defaultQueryTraceLogger(event) {
6808
+ const target = event.table ?? event.functionName ?? "gateway";
6809
+ const outcomeState = event.outcome?.error ? "error" : "ok";
6810
+ const banner = `[athena-js][trace] ${event.operation.toUpperCase()} ${event.endpoint} ${target} ${event.durationMs}ms ${outcomeState}`;
6811
+ console.info(banner, event);
6812
+ }
6813
+ function captureTraceCallsite(tracer) {
6814
+ return tracer?.captureCallsite() ?? null;
6815
+ }
6816
+ function createTraceCallsiteStore(tracer, initialCallsite) {
6817
+ let storedCallsite = initialCallsite ?? void 0;
6818
+ return {
6819
+ resolve(callsite) {
6820
+ if (callsite) {
6821
+ storedCallsite = callsite;
6822
+ return callsite;
6823
+ }
6824
+ if (storedCallsite !== void 0) {
6825
+ return storedCallsite;
6826
+ }
6827
+ const capturedCallsite = captureTraceCallsite(tracer);
6828
+ if (capturedCallsite) {
6829
+ storedCallsite = capturedCallsite;
6830
+ }
6831
+ return capturedCallsite;
6832
+ }
6833
+ };
6834
+ }
6835
+ function createQueryTracer(experimental) {
6836
+ const traceOption = experimental?.traceQueries;
6837
+ if (!traceOption) {
6838
+ return void 0;
6839
+ }
6840
+ const logger = typeof traceOption === "object" && traceOption.logger ? traceOption.logger : defaultQueryTraceLogger;
6841
+ const emit = (event) => {
6842
+ try {
6843
+ logger(event);
6844
+ } catch (error) {
6845
+ console.warn("[athena-js][trace] logger failed", error);
6846
+ }
6847
+ };
6848
+ return {
6849
+ captureCallsite: captureQueryTraceCallsite,
6850
+ publishSuccess(context, result, durationMs, callsite) {
6851
+ emit({
6852
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
6853
+ durationMs,
6854
+ operation: context.operation,
6855
+ endpoint: context.endpoint,
6856
+ table: context.table,
6857
+ functionName: context.functionName,
6858
+ sql: context.sql,
6859
+ payload: context.payload,
6860
+ ast: context.ast,
6861
+ options: context.options,
6862
+ callsite,
6863
+ outcome: {
6864
+ status: result.status,
6865
+ error: result.error,
6866
+ errorDetails: result.errorDetails ?? null,
6867
+ count: result.count ?? null,
6868
+ data: result.data,
6869
+ raw: result.raw
6870
+ }
6871
+ });
6872
+ },
6873
+ publishFailure(context, error, durationMs, callsite) {
6874
+ emit({
6875
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
6876
+ durationMs,
6877
+ operation: context.operation,
6878
+ endpoint: context.endpoint,
6879
+ table: context.table,
6880
+ functionName: context.functionName,
6881
+ sql: context.sql,
6882
+ payload: context.payload,
6883
+ ast: context.ast,
6884
+ options: context.options,
6885
+ callsite,
6886
+ thrownError: error
6887
+ });
6888
+ }
6889
+ };
6890
+ }
6891
+ async function executeWithQueryTrace(tracer, context, runner, callsiteOverride) {
6892
+ const callsite = tracer ? callsiteOverride ?? tracer.captureCallsite() : null;
6893
+ const startedAt = tracer ? Date.now() : 0;
6894
+ try {
6895
+ const result = await runner();
6896
+ attachAthenaDebugAst(result, context.ast);
6897
+ if (tracer) {
6898
+ tracer.publishSuccess(context, result, Date.now() - startedAt, callsite);
6899
+ }
6900
+ return result;
6901
+ } catch (error) {
6902
+ attachAthenaDebugAst(error, context.ast);
6903
+ if (tracer) {
6904
+ tracer.publishFailure(context, error, Date.now() - startedAt, callsite);
6905
+ }
6906
+ throw error;
6907
+ }
6908
+ }
6909
+
6910
+ // src/schema/model-target.ts
6911
+ function normalizeOptionalName(value) {
6912
+ const normalized = value?.trim();
6913
+ return normalized ? normalized : void 0;
6914
+ }
6915
+ function isAthenaModelTarget(value) {
6916
+ if (!value || typeof value !== "object") {
6917
+ return false;
6918
+ }
6919
+ const candidate = value;
6920
+ return Boolean(candidate.meta && Array.isArray(candidate.meta.primaryKey));
6921
+ }
6922
+ function resolveAthenaModelTargetTableName(target, options = {}) {
6923
+ const explicitTableName = normalizeOptionalName(target.meta.tableName);
6924
+ if (explicitTableName) {
6925
+ return explicitTableName;
6926
+ }
6927
+ const schemaName = normalizeOptionalName(target.meta.schema ?? options.fallbackSchema);
6928
+ const modelName = normalizeOptionalName(target.meta.model ?? options.fallbackModel);
6929
+ if (!modelName) {
6930
+ throw new Error(
6931
+ "Athena model target is missing meta.model or meta.tableName. Provide one of those before calling from(model)."
6932
+ );
6933
+ }
6934
+ return schemaName ? `${schemaName}.${modelName}` : modelName;
6935
+ }
6936
+
5507
6937
  // src/client.ts
5508
6938
  var DEFAULT_COLUMNS = "*";
5509
6939
  var SAFE_CAST_PATTERN = /^[a-z_][a-z0-9_]*(?:\[\])?$/i;
5510
6940
  var ATHENA_NORMALIZED_ERROR_KEY = "__athenaNormalizedError";
5511
- var QUERY_TRACE_STACK_SKIP_PATTERNS = [
5512
- "src\\client.ts",
5513
- "src/client.ts",
5514
- "dist\\client.",
5515
- "dist/client.",
5516
- "node_modules\\@xylex-group\\athena",
5517
- "node_modules/@xylex-group/athena",
5518
- "node:internal",
5519
- "internal/process"
5520
- ];
5521
6941
  function formatResult(response) {
5522
6942
  const result = {
5523
6943
  data: response.data ?? null,
@@ -5659,154 +7079,6 @@ function createResultError(response, result, normalized) {
5659
7079
  raw: result.raw
5660
7080
  };
5661
7081
  }
5662
- function parseQueryTraceCallsiteFrame(frame) {
5663
- const trimmed = frame.trim();
5664
- if (!trimmed) {
5665
- return null;
5666
- }
5667
- let body = trimmed.replace(/^at\s+/, "");
5668
- if (body.startsWith("async ")) {
5669
- body = body.slice(6);
5670
- }
5671
- let functionName;
5672
- let location = body;
5673
- const wrappedMatch = body.match(/^(.*?)\s+\((.*)\)$/);
5674
- if (wrappedMatch) {
5675
- functionName = wrappedMatch[1].trim() || void 0;
5676
- location = wrappedMatch[2].trim();
5677
- }
5678
- const locationMatch = location.match(/^(.*):(\d+):(\d+)$/);
5679
- if (!locationMatch) {
5680
- return null;
5681
- }
5682
- const filePath = locationMatch[1].replace(/^file:\/\//, "");
5683
- const line = Number(locationMatch[2]);
5684
- const column = Number(locationMatch[3]);
5685
- if (!Number.isFinite(line) || !Number.isFinite(column)) {
5686
- return null;
5687
- }
5688
- const normalizedPath = filePath.replace(/\\/g, "/");
5689
- const fileName = normalizedPath.split("/").at(-1) ?? filePath;
5690
- return {
5691
- filePath,
5692
- fileName,
5693
- line,
5694
- column,
5695
- frame: trimmed,
5696
- functionName
5697
- };
5698
- }
5699
- function captureQueryTraceCallsite() {
5700
- const stack = new Error().stack;
5701
- if (!stack) return null;
5702
- const frames = stack.split("\n").slice(2).map((frame) => frame.trim()).filter(Boolean);
5703
- for (const frame of frames) {
5704
- if (QUERY_TRACE_STACK_SKIP_PATTERNS.some((pattern) => frame.includes(pattern))) {
5705
- continue;
5706
- }
5707
- const callsite = parseQueryTraceCallsiteFrame(frame);
5708
- if (callsite) return callsite;
5709
- }
5710
- const fallback = frames.find((frame) => !frame.includes("captureQueryTraceCallsite"));
5711
- return fallback ? parseQueryTraceCallsiteFrame(fallback) : null;
5712
- }
5713
- function defaultQueryTraceLogger(event) {
5714
- const target = event.table ?? event.functionName ?? "gateway";
5715
- const outcomeState = event.outcome?.error ? "error" : "ok";
5716
- const banner = `[athena-js][trace] ${event.operation.toUpperCase()} ${event.endpoint} ${target} ${event.durationMs}ms ${outcomeState}`;
5717
- console.info(banner, event);
5718
- }
5719
- function captureTraceCallsite(tracer) {
5720
- return tracer?.captureCallsite() ?? null;
5721
- }
5722
- function createTraceCallsiteStore(tracer, initialCallsite) {
5723
- let storedCallsite = initialCallsite ?? void 0;
5724
- return {
5725
- resolve(callsite) {
5726
- if (callsite) {
5727
- storedCallsite = callsite;
5728
- return callsite;
5729
- }
5730
- if (storedCallsite !== void 0) {
5731
- return storedCallsite;
5732
- }
5733
- const capturedCallsite = captureTraceCallsite(tracer);
5734
- if (capturedCallsite) {
5735
- storedCallsite = capturedCallsite;
5736
- }
5737
- return capturedCallsite;
5738
- }
5739
- };
5740
- }
5741
- function createQueryTracer(experimental) {
5742
- const traceOption = experimental?.traceQueries;
5743
- if (!traceOption) {
5744
- return void 0;
5745
- }
5746
- const logger = typeof traceOption === "object" && traceOption.logger ? traceOption.logger : defaultQueryTraceLogger;
5747
- const emit = (event) => {
5748
- try {
5749
- logger(event);
5750
- } catch (error) {
5751
- console.warn("[athena-js][trace] logger failed", error);
5752
- }
5753
- };
5754
- return {
5755
- captureCallsite: captureQueryTraceCallsite,
5756
- publishSuccess(context, result, durationMs, callsite) {
5757
- emit({
5758
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5759
- durationMs,
5760
- operation: context.operation,
5761
- endpoint: context.endpoint,
5762
- table: context.table,
5763
- functionName: context.functionName,
5764
- sql: context.sql,
5765
- payload: context.payload,
5766
- options: context.options,
5767
- callsite,
5768
- outcome: {
5769
- status: result.status,
5770
- error: result.error,
5771
- errorDetails: result.errorDetails ?? null,
5772
- count: result.count ?? null,
5773
- data: result.data,
5774
- raw: result.raw
5775
- }
5776
- });
5777
- },
5778
- publishFailure(context, error, durationMs, callsite) {
5779
- emit({
5780
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5781
- durationMs,
5782
- operation: context.operation,
5783
- endpoint: context.endpoint,
5784
- table: context.table,
5785
- functionName: context.functionName,
5786
- sql: context.sql,
5787
- payload: context.payload,
5788
- options: context.options,
5789
- callsite,
5790
- thrownError: error
5791
- });
5792
- }
5793
- };
5794
- }
5795
- async function executeWithQueryTrace(tracer, context, runner, callsiteOverride) {
5796
- if (!tracer) {
5797
- return runner();
5798
- }
5799
- const callsite = callsiteOverride ?? tracer.captureCallsite();
5800
- const startedAt = Date.now();
5801
- try {
5802
- const result = await runner();
5803
- tracer.publishSuccess(context, result, Date.now() - startedAt, callsite);
5804
- return result;
5805
- } catch (error) {
5806
- tracer.publishFailure(context, error, Date.now() - startedAt, callsite);
5807
- throw error;
5808
- }
5809
- }
5810
7082
  function toSingleResult(response) {
5811
7083
  const payload = response.data;
5812
7084
  const singleData = Array.isArray(payload) ? payload.length ? payload[0] : null : payload ?? null;
@@ -5834,6 +7106,15 @@ function asAthenaJsonObject(value) {
5834
7106
  function asAthenaJsonObjectArray(values) {
5835
7107
  return values;
5836
7108
  }
7109
+ function normalizeSelectColumnsInput(columns) {
7110
+ if (columns === void 0) {
7111
+ return void 0;
7112
+ }
7113
+ if (typeof columns === "string") {
7114
+ return columns;
7115
+ }
7116
+ return [...columns];
7117
+ }
5837
7118
  function createMutationQuery(executor, defaultColumns = DEFAULT_COLUMNS, tracer, initialCallsite) {
5838
7119
  let selectedColumns = defaultColumns === null ? void 0 : defaultColumns;
5839
7120
  let selectedOptions;
@@ -5843,25 +7124,29 @@ function createMutationQuery(executor, defaultColumns = DEFAULT_COLUMNS, tracer,
5843
7124
  const payloadColumns = columns ?? selectedColumns;
5844
7125
  const payloadOptions = options ?? selectedOptions;
5845
7126
  if (!promise) {
5846
- promise = executor(payloadColumns, payloadOptions, callsiteStore.resolve(callsite));
7127
+ promise = executor(
7128
+ normalizeSelectColumnsInput(payloadColumns),
7129
+ payloadOptions,
7130
+ callsiteStore.resolve(callsite)
7131
+ );
5847
7132
  }
5848
7133
  return promise;
5849
7134
  };
5850
7135
  const mutationQuery = {
5851
- select(columns = selectedColumns, options) {
7136
+ select(columns, options) {
5852
7137
  selectedColumns = columns;
5853
7138
  selectedOptions = options ?? selectedOptions;
5854
7139
  return run(columns, options, captureTraceCallsite(tracer));
5855
7140
  },
5856
- returning(columns = selectedColumns, options) {
7141
+ returning(columns, options) {
5857
7142
  return mutationQuery.select(columns, options);
5858
7143
  },
5859
- single(columns = selectedColumns, options) {
7144
+ single(columns, options) {
5860
7145
  selectedColumns = columns;
5861
7146
  selectedOptions = options ?? selectedOptions;
5862
7147
  return run(columns, options, captureTraceCallsite(tracer)).then(toSingleResult);
5863
7148
  },
5864
- maybeSingle(columns = selectedColumns, options) {
7149
+ maybeSingle(columns, options) {
5865
7150
  return mutationQuery.single(columns, options);
5866
7151
  },
5867
7152
  then(onfulfilled, onrejected) {
@@ -6418,7 +7703,10 @@ function createFilterMethods(state, addCondition, self) {
6418
7703
  }
6419
7704
  function toRpcSelect(columns) {
6420
7705
  if (!columns) return void 0;
6421
- return Array.isArray(columns) ? columns.join(",") : columns;
7706
+ if (typeof columns === "string") {
7707
+ return columns;
7708
+ }
7709
+ return columns.join(",");
6422
7710
  }
6423
7711
  function createRpcFilterMethods(filters, self) {
6424
7712
  const addFilter = (operator, column, value) => {
@@ -6467,7 +7755,7 @@ function createRpcFilterMethods(filters, self) {
6467
7755
  }
6468
7756
  };
6469
7757
  }
6470
- function createRpcBuilder(functionName, args, baseOptions, client, formatGatewayResult, tracer, initialCallsite) {
7758
+ function createRpcBuilder(functionName, args, baseOptions, client, formatGatewayResult, tracer, initialCallsite, debugAstEnabled = false) {
6471
7759
  const state = {
6472
7760
  filters: []
6473
7761
  };
@@ -6477,6 +7765,7 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
6477
7765
  const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
6478
7766
  const executeRpc = async (columns, options, callsite) => {
6479
7767
  const mergedOptions = mergeOptions(baseOptions, options);
7768
+ const normalizedSelectedColumns = normalizeSelectColumnsInput(columns);
6480
7769
  const payload = {
6481
7770
  function: functionName,
6482
7771
  args,
@@ -6491,6 +7780,14 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
6491
7780
  };
6492
7781
  const endpoint = mergedOptions?.get ? `/rpc/${functionName}` : "/gateway/rpc";
6493
7782
  const sql = buildRpcDebugSql(payload);
7783
+ const debugAst = debugAstEnabled ? buildRpcDebugAst({
7784
+ functionName,
7785
+ args,
7786
+ selectedColumns: normalizedSelectedColumns,
7787
+ state,
7788
+ payload,
7789
+ endpoint
7790
+ }) : void 0;
6494
7791
  return executeWithQueryTrace(
6495
7792
  tracer,
6496
7793
  {
@@ -6499,6 +7796,7 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
6499
7796
  functionName,
6500
7797
  sql,
6501
7798
  payload,
7799
+ ast: debugAst,
6502
7800
  options: mergedOptions
6503
7801
  },
6504
7802
  async () => {
@@ -6519,7 +7817,7 @@ function createRpcBuilder(functionName, args, baseOptions, client, formatGateway
6519
7817
  const builder = {};
6520
7818
  const filterMethods = createRpcFilterMethods(state.filters, builder);
6521
7819
  Object.assign(builder, filterMethods, {
6522
- select(columns = selectedColumns, options) {
7820
+ select(columns, options) {
6523
7821
  selectedColumns = columns;
6524
7822
  selectedOptions = options ?? selectedOptions;
6525
7823
  return run(columns, options, captureTraceCallsite(tracer));
@@ -6564,6 +7862,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6564
7862
  const state = {
6565
7863
  conditions: []
6566
7864
  };
7865
+ const debugAstEnabled = Boolean(experimental?.debugAst);
6567
7866
  const addCondition = (operator, column, value, hints) => {
6568
7867
  const condition = { operator };
6569
7868
  if (column) {
@@ -6607,15 +7906,27 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6607
7906
  addCondition,
6608
7907
  builder
6609
7908
  );
6610
- const runSelect = async (columns = DEFAULT_COLUMNS, options, executionState = snapshotState(), callsite) => {
7909
+ const runSelect = async (columns = DEFAULT_COLUMNS, options, executionState = snapshotState(), callsite, debugAstFactory) => {
7910
+ const runtimeColumns = normalizeSelectColumnsInput(columns) ?? DEFAULT_COLUMNS;
6611
7911
  const resolvedTableName = resolveTableNameForCall(tableName, options?.schema);
6612
7912
  const plan = createSelectTransportPlan({
6613
7913
  tableName: resolvedTableName,
6614
- columns,
7914
+ columns: runtimeColumns,
6615
7915
  state: executionState,
6616
7916
  options,
6617
7917
  buildTypedSelectQuery
6618
7918
  });
7919
+ const debugAst = debugAstEnabled ? debugAstFactory?.({
7920
+ tableName: resolvedTableName,
7921
+ columns: runtimeColumns,
7922
+ executionState,
7923
+ plan
7924
+ }) ?? buildSelectDebugAst({
7925
+ tableName: resolvedTableName,
7926
+ columns: runtimeColumns,
7927
+ state: executionState,
7928
+ plan
7929
+ }) : void 0;
6619
7930
  if (plan.kind === "query") {
6620
7931
  return executeExperimentalRead(
6621
7932
  experimental,
@@ -6627,6 +7938,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6627
7938
  table: resolvedTableName,
6628
7939
  sql: plan.query,
6629
7940
  payload: plan.payload,
7941
+ ast: debugAst,
6630
7942
  options
6631
7943
  },
6632
7944
  async () => {
@@ -6651,6 +7963,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6651
7963
  table: resolvedTableName,
6652
7964
  sql,
6653
7965
  payload: plan.payload,
7966
+ ast: debugAst,
6654
7967
  options
6655
7968
  },
6656
7969
  async () => {
@@ -6664,7 +7977,11 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6664
7977
  const createSelectChain = (columns, options, initialCallsite) => {
6665
7978
  const chain = {};
6666
7979
  const callsiteStore = createTraceCallsiteStore(tracer, initialCallsite);
6667
- const filterMethods2 = createFilterMethods(state, addCondition, chain);
7980
+ const filterMethods2 = createFilterMethods(
7981
+ state,
7982
+ addCondition,
7983
+ chain
7984
+ );
6668
7985
  Object.assign(chain, filterMethods2, {
6669
7986
  async single(cols, opts) {
6670
7987
  const r = await runSelect(
@@ -6751,6 +8068,14 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6751
8068
  limit: executionState.limit,
6752
8069
  order: executionState.order
6753
8070
  });
8071
+ const debugAst = debugAstEnabled ? buildFindManyDirectDebugAst({
8072
+ tableName: resolvedTableName,
8073
+ options,
8074
+ compiledColumns: columns,
8075
+ baseState,
8076
+ executionState,
8077
+ payload
8078
+ }) : void 0;
6754
8079
  return executeExperimentalRead(
6755
8080
  experimental,
6756
8081
  () => executeWithQueryTrace(
@@ -6760,7 +8085,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6760
8085
  endpoint: "/gateway/fetch",
6761
8086
  table: resolvedTableName,
6762
8087
  sql,
6763
- payload
8088
+ payload,
8089
+ ast: debugAst
6764
8090
  },
6765
8091
  async () => {
6766
8092
  const response = await client.fetchGateway(
@@ -6776,7 +8102,15 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6776
8102
  columns,
6777
8103
  void 0,
6778
8104
  executionState,
6779
- callsite
8105
+ callsite,
8106
+ debugAstEnabled ? ({ tableName: resolvedTableName, executionState: tracedState, plan }) => buildFindManyCompiledDebugAst({
8107
+ tableName: resolvedTableName,
8108
+ options,
8109
+ compiledColumns: columns,
8110
+ baseState,
8111
+ executionState: tracedState,
8112
+ plan
8113
+ }) : void 0
6780
8114
  );
6781
8115
  },
6782
8116
  insert(values, options) {
@@ -6796,6 +8130,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6796
8130
  payload.default_to_null = mergedOptions.defaultToNull;
6797
8131
  }
6798
8132
  const sql = buildInsertDebugSql(payload);
8133
+ const debugAst = debugAstEnabled ? buildInsertDebugAst(payload) : void 0;
6799
8134
  return executeWithQueryTrace(
6800
8135
  tracer,
6801
8136
  {
@@ -6804,6 +8139,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6804
8139
  table: resolvedTableName,
6805
8140
  sql,
6806
8141
  payload,
8142
+ ast: debugAst,
6807
8143
  options: mergedOptions
6808
8144
  },
6809
8145
  async () => {
@@ -6829,6 +8165,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6829
8165
  payload.default_to_null = mergedOptions.defaultToNull;
6830
8166
  }
6831
8167
  const sql = buildInsertDebugSql(payload);
8168
+ const debugAst = debugAstEnabled ? buildInsertDebugAst(payload) : void 0;
6832
8169
  return executeWithQueryTrace(
6833
8170
  tracer,
6834
8171
  {
@@ -6837,6 +8174,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6837
8174
  table: resolvedTableName,
6838
8175
  sql,
6839
8176
  payload,
8177
+ ast: debugAst,
6840
8178
  options: mergedOptions
6841
8179
  },
6842
8180
  async () => {
@@ -6867,6 +8205,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6867
8205
  payload.default_to_null = mergedOptions.defaultToNull;
6868
8206
  }
6869
8207
  const sql = buildInsertDebugSql(payload);
8208
+ const debugAst = debugAstEnabled ? buildUpsertDebugAst(payload) : void 0;
6870
8209
  return executeWithQueryTrace(
6871
8210
  tracer,
6872
8211
  {
@@ -6875,6 +8214,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6875
8214
  table: resolvedTableName,
6876
8215
  sql,
6877
8216
  payload,
8217
+ ast: debugAst,
6878
8218
  options: mergedOptions
6879
8219
  },
6880
8220
  async () => {
@@ -6902,6 +8242,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6902
8242
  payload.default_to_null = mergedOptions.defaultToNull;
6903
8243
  }
6904
8244
  const sql = buildInsertDebugSql(payload);
8245
+ const debugAst = debugAstEnabled ? buildUpsertDebugAst(payload) : void 0;
6905
8246
  return executeWithQueryTrace(
6906
8247
  tracer,
6907
8248
  {
@@ -6910,6 +8251,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6910
8251
  table: resolvedTableName,
6911
8252
  sql,
6912
8253
  payload,
8254
+ ast: debugAst,
6913
8255
  options: mergedOptions
6914
8256
  },
6915
8257
  async () => {
@@ -6924,7 +8266,8 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6924
8266
  update(values, options) {
6925
8267
  const mutationCallsite = captureTraceCallsite(tracer);
6926
8268
  const executeUpdate = async (columns, selectOptions, callsite) => {
6927
- const filters = state.conditions.length ? [...state.conditions] : void 0;
8269
+ const executionState = snapshotState();
8270
+ const filters = executionState.conditions.length ? [...executionState.conditions] : void 0;
6928
8271
  const mergedOptions = mergeOptions(options, selectOptions);
6929
8272
  const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
6930
8273
  const payload = {
@@ -6933,12 +8276,16 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6933
8276
  conditions: filters,
6934
8277
  strip_nulls: mergedOptions?.stripNulls ?? true
6935
8278
  };
6936
- if (state.order) payload.sort_by = state.order;
6937
- if (state.currentPage !== void 0) payload.current_page = state.currentPage;
6938
- if (state.pageSize !== void 0) payload.page_size = state.pageSize;
6939
- if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
8279
+ if (executionState.order) payload.sort_by = executionState.order;
8280
+ if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
8281
+ if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
8282
+ if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
6940
8283
  if (columns) payload.columns = columns;
6941
8284
  const sql = buildUpdateDebugSql(payload);
8285
+ const debugAst = debugAstEnabled ? buildUpdateDebugAst({
8286
+ state: executionState,
8287
+ payload
8288
+ }) : void 0;
6942
8289
  return executeWithQueryTrace(
6943
8290
  tracer,
6944
8291
  {
@@ -6947,6 +8294,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6947
8294
  table: resolvedTableName,
6948
8295
  sql,
6949
8296
  payload,
8297
+ ast: debugAst,
6950
8298
  options: mergedOptions
6951
8299
  },
6952
8300
  async () => {
@@ -6970,6 +8318,11 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6970
8318
  }
6971
8319
  const mutationCallsite = captureTraceCallsite(tracer);
6972
8320
  const executeDelete = async (columns, selectOptions, callsite) => {
8321
+ const executionState = snapshotState();
8322
+ const debugState = {
8323
+ ...executionState,
8324
+ conditions: filters ? filters.map((condition) => ({ ...condition })) : []
8325
+ };
6973
8326
  const mergedOptions = mergeOptions(options, selectOptions);
6974
8327
  const resolvedTableName = resolveTableNameForCall(tableName, mergedOptions?.schema);
6975
8328
  const payload = {
@@ -6977,12 +8330,16 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6977
8330
  resource_id: resourceId,
6978
8331
  conditions: filters
6979
8332
  };
6980
- if (state.order) payload.sort_by = state.order;
6981
- if (state.currentPage !== void 0) payload.current_page = state.currentPage;
6982
- if (state.pageSize !== void 0) payload.page_size = state.pageSize;
6983
- if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
8333
+ if (executionState.order) payload.sort_by = executionState.order;
8334
+ if (executionState.currentPage !== void 0) payload.current_page = executionState.currentPage;
8335
+ if (executionState.pageSize !== void 0) payload.page_size = executionState.pageSize;
8336
+ if (executionState.totalPages !== void 0) payload.total_pages = executionState.totalPages;
6984
8337
  if (columns) payload.columns = columns;
6985
8338
  const sql = buildDeleteDebugSql(payload);
8339
+ const debugAst = debugAstEnabled ? buildDeleteDebugAst({
8340
+ state: debugState,
8341
+ payload
8342
+ }) : void 0;
6986
8343
  return executeWithQueryTrace(
6987
8344
  tracer,
6988
8345
  {
@@ -6991,6 +8348,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
6991
8348
  table: resolvedTableName,
6992
8349
  sql,
6993
8350
  payload,
8351
+ ast: debugAst,
6994
8352
  options: mergedOptions
6995
8353
  },
6996
8354
  async () => {
@@ -7018,6 +8376,7 @@ function createTableBuilder(tableName, client, formatGatewayResult, tracer, expe
7018
8376
  return builder;
7019
8377
  }
7020
8378
  function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
8379
+ const debugAstEnabled = Boolean(experimental?.debugAst);
7021
8380
  return async function query(query, options) {
7022
8381
  const normalizedQuery = query.trim();
7023
8382
  if (!normalizedQuery) {
@@ -7034,6 +8393,7 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
7034
8393
  endpoint: "/gateway/query",
7035
8394
  sql: normalizedQuery,
7036
8395
  payload,
8396
+ ast: debugAstEnabled ? buildRawQueryDebugAst(normalizedQuery) : void 0,
7037
8397
  options
7038
8398
  },
7039
8399
  async () => {
@@ -7045,6 +8405,96 @@ function createQueryBuilder(client, formatGatewayResult, experimental, tracer) {
7045
8405
  );
7046
8406
  };
7047
8407
  }
8408
+ function resolveClientServiceBaseUrl(value, label) {
8409
+ if (value === void 0 || value === null) {
8410
+ return void 0;
8411
+ }
8412
+ return normalizeAthenaGatewayBaseUrl(value, { label });
8413
+ }
8414
+ function appendServicePath(baseUrl, segment) {
8415
+ const normalizedBaseUrl = normalizeAthenaGatewayBaseUrl(baseUrl, { label: "Athena public base URL" });
8416
+ return `${normalizedBaseUrl}/${segment.replace(/^\/+/, "")}`;
8417
+ }
8418
+ function resolveServiceUrlOverride(value, label) {
8419
+ return resolveClientServiceBaseUrl(value, label);
8420
+ }
8421
+ function resolveServiceUrls(config) {
8422
+ const baseUrl = resolveClientServiceBaseUrl(config.url, "Athena public base URL");
8423
+ return {
8424
+ 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
+ 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),
8426
+ storageUrl: resolveServiceUrlOverride(config.storage?.url, "Athena storage base URL") ?? resolveServiceUrlOverride(config.storageUrl, "Athena storage base URL") ?? (baseUrl ? appendServicePath(baseUrl, "storage") : void 0)
8427
+ };
8428
+ }
8429
+ function resolveOptionalClientName(value) {
8430
+ if (value === void 0 || value === null) {
8431
+ return void 0;
8432
+ }
8433
+ const normalizedValue = value.trim();
8434
+ return normalizedValue ? normalizedValue : void 0;
8435
+ }
8436
+ function resolveRequiredClientApiKey(value) {
8437
+ if (value === void 0 || value === null) {
8438
+ throw new Error(
8439
+ "Athena API key is required. Pass createClient(url, key) with a real API key, or set key in the config object."
8440
+ );
8441
+ }
8442
+ const normalizedValue = value.trim();
8443
+ if (!normalizedValue) {
8444
+ throw new Error(
8445
+ "Athena API key is required. Pass createClient(url, key) with a real API key, or set key in the config object."
8446
+ );
8447
+ }
8448
+ return normalizedValue;
8449
+ }
8450
+ function normalizeAuthClientConfig(auth, defaultBaseUrl) {
8451
+ if (!auth && defaultBaseUrl === void 0) {
8452
+ return void 0;
8453
+ }
8454
+ const {
8455
+ url,
8456
+ baseUrl,
8457
+ apiKey,
8458
+ bearerToken,
8459
+ ...rest
8460
+ } = auth ?? {};
8461
+ const normalized = {
8462
+ ...rest
8463
+ };
8464
+ const resolvedBaseUrl = resolveClientServiceBaseUrl(
8465
+ url ?? baseUrl ?? defaultBaseUrl,
8466
+ "Athena auth base URL"
8467
+ );
8468
+ if (resolvedBaseUrl !== void 0) {
8469
+ normalized.baseUrl = resolvedBaseUrl;
8470
+ }
8471
+ if (typeof apiKey === "string") {
8472
+ normalized.apiKey = apiKey;
8473
+ }
8474
+ if (typeof bearerToken === "string") {
8475
+ normalized.bearerToken = bearerToken;
8476
+ }
8477
+ return normalized;
8478
+ }
8479
+ function resolveCreateClientConfig(config) {
8480
+ const resolvedUrls = resolveServiceUrls(config);
8481
+ if (!resolvedUrls.dbUrl) {
8482
+ throw new Error(
8483
+ "Athena DB base URL is required. Pass createClient(url, key) for a unified root, or set db.url / gateway.url / gatewayUrl explicitly."
8484
+ );
8485
+ }
8486
+ return {
8487
+ baseUrl: resolvedUrls.dbUrl,
8488
+ apiKey: resolveRequiredClientApiKey(config.key),
8489
+ client: resolveOptionalClientName(config.client),
8490
+ backend: toBackendConfig(config.backend),
8491
+ headers: config.headers,
8492
+ auth: config.auth,
8493
+ authUrl: resolvedUrls.authUrl,
8494
+ storageUrl: resolvedUrls.storageUrl,
8495
+ experimental: config.experimental
8496
+ };
8497
+ }
7048
8498
  function createClientFromConfig(config) {
7049
8499
  const gatewayHeaders = {
7050
8500
  ...config.headers ?? {}
@@ -7059,16 +8509,33 @@ function createClientFromConfig(config) {
7059
8509
  backend: config.backend,
7060
8510
  headers: gatewayHeaders
7061
8511
  });
7062
- const formatGatewayResult = createResultFormatter();
8512
+ const formatGatewayResult = createResultFormatter(config.experimental);
7063
8513
  const queryTracer = createQueryTracer(config.experimental);
7064
- const auth = createAuthClient(config.auth);
7065
- const from = (table, options) => createTableBuilder(
7066
- resolveTableNameForCall(table, options?.schema),
7067
- gateway,
7068
- formatGatewayResult,
7069
- queryTracer,
7070
- config.experimental
7071
- );
8514
+ const auth = createAuthClient(normalizeAuthClientConfig(config.auth, config.authUrl));
8515
+ function from(tableOrModel, options) {
8516
+ if (isAthenaModelTarget(tableOrModel)) {
8517
+ if (options?.schema !== void 0) {
8518
+ throw new Error(
8519
+ "from(model) does not accept a schema override because the model already defines its target."
8520
+ );
8521
+ }
8522
+ return createTableBuilder(
8523
+ resolveAthenaModelTargetTableName(tableOrModel),
8524
+ gateway,
8525
+ formatGatewayResult,
8526
+ queryTracer,
8527
+ config.experimental
8528
+ );
8529
+ }
8530
+ const resolvedTableName = resolveTableNameForCall(tableOrModel, options?.schema);
8531
+ return createTableBuilder(
8532
+ resolvedTableName,
8533
+ gateway,
8534
+ formatGatewayResult,
8535
+ queryTracer,
8536
+ config.experimental
8537
+ );
8538
+ }
7072
8539
  const rpc = (fn, args, options) => {
7073
8540
  const normalizedFn = fn.trim();
7074
8541
  if (!normalizedFn) {
@@ -7081,10 +8548,16 @@ function createClientFromConfig(config) {
7081
8548
  gateway,
7082
8549
  formatGatewayResult,
7083
8550
  queryTracer,
7084
- captureTraceCallsite(queryTracer)
8551
+ captureTraceCallsite(queryTracer),
8552
+ Boolean(config.experimental?.debugAst)
7085
8553
  );
7086
8554
  };
7087
- const query = createQueryBuilder(gateway, formatGatewayResult, config.experimental, queryTracer);
8555
+ const query = createQueryBuilder(
8556
+ gateway,
8557
+ formatGatewayResult,
8558
+ config.experimental,
8559
+ queryTracer
8560
+ );
7088
8561
  const db = createDbModule({ from, rpc, query });
7089
8562
  const sdkClient = {
7090
8563
  from,
@@ -7097,27 +8570,27 @@ function createClientFromConfig(config) {
7097
8570
  if (config.experimental?.athenaStorageBackend) {
7098
8571
  const storageClient = {
7099
8572
  ...sdkClient,
7100
- storage: createStorageModule(gateway, config.experimental.storage)
8573
+ storage: createStorageModule(gateway, {
8574
+ ...config.experimental.storage,
8575
+ ...config.storageUrl ? {
8576
+ baseUrl: config.storageUrl,
8577
+ stripBasePath: true
8578
+ } : {}
8579
+ })
7101
8580
  };
7102
8581
  return storageClient;
7103
8582
  }
7104
8583
  return sdkClient;
7105
8584
  }
7106
- var DEFAULT_BACKEND = { type: "athena" };
7107
- function toBackendConfig(b) {
7108
- if (!b) return DEFAULT_BACKEND;
7109
- return typeof b === "string" ? { type: b } : b;
7110
- }
7111
- function createClient(url, apiKey, options) {
7112
- return createClientFromConfig({
7113
- baseUrl: url,
7114
- apiKey,
7115
- client: options?.client,
7116
- backend: toBackendConfig(options?.backend),
7117
- headers: options?.headers,
7118
- auth: options?.auth,
7119
- experimental: options?.experimental
7120
- });
8585
+ function createClient(configOrUrl, apiKey, options) {
8586
+ if (typeof configOrUrl === "string" || configOrUrl === null || configOrUrl === void 0) {
8587
+ return createClientFromConfig(resolveCreateClientConfig({
8588
+ url: configOrUrl,
8589
+ key: apiKey ?? "",
8590
+ ...options
8591
+ }));
8592
+ }
8593
+ return createClientFromConfig(resolveCreateClientConfig(configOrUrl));
7121
8594
  }
7122
8595
 
7123
8596
  // src/schema/postgres-introspection-core.ts
@@ -7700,6 +9173,7 @@ async function runSchemaGenerator(options = {}) {
7700
9173
  return {
7701
9174
  ...generated,
7702
9175
  configPath,
9176
+ config,
7703
9177
  writtenFiles
7704
9178
  };
7705
9179
  }
@@ -7714,6 +9188,7 @@ function rootUsage() {
7714
9188
  "",
7715
9189
  "Examples:",
7716
9190
  " athena-js generate",
9191
+ " DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/app_db athena-js generate --dry-run",
7717
9192
  " athena-js generate --config ./athena.config.ts --dry-run",
7718
9193
  " athena-js generate --help"
7719
9194
  ].join("\n");
@@ -7727,14 +9202,42 @@ function generateUsage() {
7727
9202
  "",
7728
9203
  "Options:",
7729
9204
  " --config <path> Explicit path to athena.config.ts or athena-js.config.ts",
7730
- " --dry-run Build generated files in memory without writing them to disk",
9205
+ " --dry-run Build generated files in memory without writing them to disk and print mode/target hints",
7731
9206
  " -h, --help Show help for generate",
7732
9207
  "",
9208
+ "Config resolution:",
9209
+ " - uses athena.config.* discovery first",
9210
+ " - falls back to env-only direct mode when DATABASE_URL/PG_URL is present",
9211
+ " - falls back to env-only gateway mode when ATHENA_URL + ATHENA_API_KEY are present",
9212
+ "",
7733
9213
  "Examples:",
7734
9214
  " athena-js generate",
9215
+ " DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/app_db athena-js generate --dry-run",
7735
9216
  " athena-js generate --config ./athena.config.ts --dry-run"
7736
9217
  ].join("\n");
7737
9218
  }
9219
+ function usesSchemaScopedModelTarget(target) {
9220
+ return /\{schema(?:_[a-z]+)?\}/.test(target);
9221
+ }
9222
+ function formatGeneratorModeLines(result) {
9223
+ const lines = [
9224
+ `[mode] format=${result.config.output.format} modelTarget=${result.config.output.targets.model}`
9225
+ ];
9226
+ if (result.config.output.format === "define-model") {
9227
+ 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(...).'
9229
+ );
9230
+ }
9231
+ lines.push(
9232
+ "[note] Table-builder generation is stable. experimental.findManyAst only affects runtime findMany(...) transport and does not enable generator table output."
9233
+ );
9234
+ if (usesSchemaScopedModelTarget(result.config.output.targets.model)) {
9235
+ 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.'
9237
+ );
9238
+ }
9239
+ return lines;
9240
+ }
7738
9241
  function usage(topic = "root") {
7739
9242
  return topic === "generate" ? generateUsage() : rootUsage();
7740
9243
  }
@@ -7836,12 +9339,18 @@ async function runCLI(argv, runtime = {}) {
7836
9339
  }
7837
9340
  if (parsed.dryRun) {
7838
9341
  log(`[dry-run] Generated ${result.files.length} files from ${result.configPath}`);
9342
+ for (const line of formatGeneratorModeLines(result)) {
9343
+ log(line);
9344
+ }
7839
9345
  for (const file of result.files) {
7840
9346
  log(` - ${file.path}`);
7841
9347
  }
7842
9348
  return;
7843
9349
  }
7844
9350
  log(`Generated ${result.writtenFiles.length} files from ${result.configPath}`);
9351
+ for (const line of formatGeneratorModeLines(result)) {
9352
+ log(line);
9353
+ }
7845
9354
  for (const filePath of result.writtenFiles) {
7846
9355
  log(` - ${filePath}`);
7847
9356
  }