@xylex-group/athena 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -63,6 +63,10 @@ function isAthenaGatewayError(error) {
63
63
  // src/gateway/client.ts
64
64
  var DEFAULT_BASE_URL = "https://athena-db.com";
65
65
  var DEFAULT_CLIENT = "railway_direct";
66
+ var FALLBACK_SDK_VERSION = "1.3.0";
67
+ var SDK_NAME = "xylex-group/athena";
68
+ var SDK_VERSION = typeof process !== "undefined" && process?.env?.npm_package_version ? process.env.npm_package_version : FALLBACK_SDK_VERSION;
69
+ var SDK_HEADER_VALUE = `${SDK_NAME} ${SDK_VERSION}`;
66
70
  function parseResponseBody(rawText, contentType) {
67
71
  if (!rawText) {
68
72
  return { parsed: null, parseFailed: false };
@@ -201,7 +205,8 @@ function buildHeaders(config, options) {
201
205
  const finalApiKey = options?.apiKey ?? config.apiKey;
202
206
  const finalPublishEvent = options?.publishEvent ?? config.publishEvent;
203
207
  const headers = {
204
- "Content-Type": "application/json"
208
+ "Content-Type": "application/json",
209
+ "X-Athena-Sdk": SDK_HEADER_VALUE
205
210
  };
206
211
  if (options?.userId ?? config.userId) {
207
212
  headers["X-User-Id"] = options?.userId ?? config.userId ?? "";
@@ -466,6 +471,25 @@ function createFilterMethods(state, addCondition, self) {
466
471
  state.offset = count;
467
472
  return self;
468
473
  },
474
+ currentPage(value) {
475
+ state.currentPage = value;
476
+ return self;
477
+ },
478
+ pageSize(value) {
479
+ state.pageSize = value;
480
+ return self;
481
+ },
482
+ totalPages(value) {
483
+ state.totalPages = value;
484
+ return self;
485
+ },
486
+ order(column, options) {
487
+ state.order = {
488
+ field: column,
489
+ direction: options?.ascending === false ? "descending" : "ascending"
490
+ };
491
+ return self;
492
+ },
469
493
  gt(column, value) {
470
494
  addCondition("gt", column, value);
471
495
  return self;
@@ -680,6 +704,10 @@ function createTableBuilder(tableName, client) {
680
704
  conditions: state.conditions.length ? [...state.conditions] : void 0,
681
705
  limit: state.limit,
682
706
  offset: state.offset,
707
+ current_page: state.currentPage,
708
+ page_size: state.pageSize,
709
+ total_pages: state.totalPages,
710
+ sort_by: state.order,
683
711
  strip_nulls: options?.stripNulls ?? true,
684
712
  count: options?.count,
685
713
  head: options?.head
@@ -715,6 +743,10 @@ function createTableBuilder(tableName, client) {
715
743
  state.conditions = [];
716
744
  state.limit = void 0;
717
745
  state.offset = void 0;
746
+ state.order = void 0;
747
+ state.currentPage = void 0;
748
+ state.pageSize = void 0;
749
+ state.totalPages = void 0;
718
750
  return builder;
719
751
  },
720
752
  select(columns = DEFAULT_COLUMNS, options) {
@@ -806,6 +838,10 @@ function createTableBuilder(tableName, client) {
806
838
  conditions: filters,
807
839
  strip_nulls: mergedOptions?.stripNulls ?? true
808
840
  };
841
+ if (state.order) payload.sort_by = state.order;
842
+ if (state.currentPage !== void 0) payload.current_page = state.currentPage;
843
+ if (state.pageSize !== void 0) payload.page_size = state.pageSize;
844
+ if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
809
845
  if (columns) payload.columns = columns;
810
846
  const response = await client.updateGateway(payload, mergedOptions);
811
847
  return formatResult(response);
@@ -829,6 +865,10 @@ function createTableBuilder(tableName, client) {
829
865
  resource_id: resourceId,
830
866
  conditions: filters
831
867
  };
868
+ if (state.order) payload.sort_by = state.order;
869
+ if (state.currentPage !== void 0) payload.current_page = state.currentPage;
870
+ if (state.pageSize !== void 0) payload.page_size = state.pageSize;
871
+ if (state.totalPages !== void 0) payload.total_pages = state.totalPages;
832
872
  if (columns) payload.columns = columns;
833
873
  const response = await client.deleteGateway(payload, mergedOptions);
834
874
  return formatResult(response);
@@ -964,10 +1004,334 @@ var Backend = {
964
1004
  ScyllaDB: { type: "scylladb" }
965
1005
  };
966
1006
 
1007
+ // src/auxiliaries.ts
1008
+ function isRecord2(value) {
1009
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
1010
+ }
1011
+ function safeStringify(value) {
1012
+ try {
1013
+ const serialized = JSON.stringify(value);
1014
+ return serialized ?? String(value);
1015
+ } catch {
1016
+ return "[unserializable]";
1017
+ }
1018
+ }
1019
+ function contextHint(context) {
1020
+ if (!context?.identity) return void 0;
1021
+ const identity = typeof context.identity === "string" ? context.identity : safeStringify(context.identity);
1022
+ return `Identity: ${identity}`;
1023
+ }
1024
+ function isAthenaResultLike(value) {
1025
+ return isRecord2(value) && "status" in value && "error" in value && "data" in value && typeof value.status === "number";
1026
+ }
1027
+ function operationFromDetails(details) {
1028
+ if (!details?.endpoint) return void 0;
1029
+ if (details.endpoint === "/gateway/fetch" || details.endpoint === "/gateway/query") return "select";
1030
+ if (details.endpoint === "/gateway/insert") return "insert";
1031
+ if (details.endpoint === "/gateway/update") return "update";
1032
+ if (details.endpoint === "/gateway/delete") return "delete";
1033
+ if (details.endpoint === "/gateway/rpc" || details.endpoint.startsWith("/rpc/")) return "rpc";
1034
+ return void 0;
1035
+ }
1036
+ function matchRegex(input, patterns) {
1037
+ for (const pattern of patterns) {
1038
+ const match = pattern.exec(input);
1039
+ if (match?.[1]) return match[1];
1040
+ }
1041
+ return void 0;
1042
+ }
1043
+ function extractConstraint(message) {
1044
+ return matchRegex(message, [
1045
+ /unique constraint\s+["'`]([^"'`]+)["'`]/i,
1046
+ /constraint\s+["'`]([^"'`]+)["'`]/i
1047
+ ]);
1048
+ }
1049
+ function extractTable(message) {
1050
+ return matchRegex(message, [
1051
+ /(?:table|relation)\s+["'`]([^"'`]+)["'`]/i,
1052
+ /on\s+table\s+([a-zA-Z0-9_.]+)/i
1053
+ ]);
1054
+ }
1055
+ function classifyKind(status, code, message) {
1056
+ const lower = message.toLowerCase();
1057
+ const hasUniquePattern = lower.includes("unique constraint") || lower.includes("duplicate key") || lower.includes("already exists") || lower.includes("duplicate");
1058
+ const hasNotFoundPattern = lower.includes("not found") || lower.includes("no rows");
1059
+ const hasValidationPattern = lower.includes("validation") || lower.includes("invalid") || lower.includes("malformed");
1060
+ const hasAuthPattern = lower.includes("unauthorized") || lower.includes("forbidden") || lower.includes("auth");
1061
+ const hasRateLimitPattern = lower.includes("rate limit") || lower.includes("too many requests");
1062
+ const hasTransientPattern = lower.includes("timeout") || lower.includes("temporar") || lower.includes("connection reset") || lower.includes("socket") || lower.includes("deadlock");
1063
+ if (status === 409 || hasUniquePattern) return "unique_violation";
1064
+ if (status === 404 || hasNotFoundPattern) return "not_found";
1065
+ if (status === 401 || status === 403 || hasAuthPattern) return "auth";
1066
+ if (status === 429 || hasRateLimitPattern) return "rate_limit";
1067
+ if (status === 400 || status === 422 || hasValidationPattern) return "validation";
1068
+ if (code === "NETWORK_ERROR" || status === 0 || status !== void 0 && status >= 500 || hasTransientPattern) {
1069
+ return "transient";
1070
+ }
1071
+ return "unknown";
1072
+ }
1073
+ function toGatewayCode(kind, status) {
1074
+ if (kind === "transient" && (status === 0 || status === void 0)) return "NETWORK_ERROR";
1075
+ if (kind === "validation") return "INVALID_JSON";
1076
+ if (status !== void 0 && status >= 400) return "HTTP_ERROR";
1077
+ return "UNKNOWN_ERROR";
1078
+ }
1079
+ function toAthenaGatewayError(source, fallbackMessage, context) {
1080
+ if (isAthenaGatewayError(source)) {
1081
+ return source;
1082
+ }
1083
+ if (isAthenaResultLike(source) && source.errorDetails) {
1084
+ return new AthenaGatewayError({
1085
+ code: source.errorDetails.code,
1086
+ message: source.error ?? source.errorDetails.message,
1087
+ status: source.status,
1088
+ endpoint: source.errorDetails.endpoint,
1089
+ method: source.errorDetails.method,
1090
+ requestId: source.errorDetails.requestId,
1091
+ hint: source.errorDetails.hint,
1092
+ cause: source.errorDetails.cause
1093
+ });
1094
+ }
1095
+ const normalized = normalizeAthenaError(source, context);
1096
+ const message = isAthenaResultLike(source) && source.error == null && source.errorDetails == null ? fallbackMessage : normalized.message || fallbackMessage;
1097
+ return new AthenaGatewayError({
1098
+ code: toGatewayCode(normalized.kind, normalized.status),
1099
+ message,
1100
+ status: normalized.status ?? 0,
1101
+ hint: normalized.constraint != null ? `Constraint: ${normalized.constraint}` : contextHint(context),
1102
+ cause: typeof normalized.raw === "string" ? normalized.raw : safeStringify(normalized.raw)
1103
+ });
1104
+ }
1105
+ function isOk(result) {
1106
+ return result.error == null && result.status >= 200 && result.status < 300;
1107
+ }
1108
+ function normalizeAthenaError(resultOrError, context) {
1109
+ if (isAthenaResultLike(resultOrError)) {
1110
+ const details = resultOrError.errorDetails;
1111
+ const message2 = resultOrError.error ?? details?.message ?? `Athena ${context?.operation ?? operationFromDetails(details) ?? "request"} failed`;
1112
+ const operation = context?.operation ?? operationFromDetails(details);
1113
+ const table = context?.table ?? extractTable(message2);
1114
+ const constraint = extractConstraint(message2);
1115
+ const kind = classifyKind(resultOrError.status, details?.code, message2);
1116
+ return {
1117
+ kind,
1118
+ status: resultOrError.status,
1119
+ constraint,
1120
+ table,
1121
+ operation,
1122
+ message: message2,
1123
+ raw: resultOrError.raw
1124
+ };
1125
+ }
1126
+ if (isAthenaGatewayError(resultOrError)) {
1127
+ const details = resultOrError.toDetails();
1128
+ const operation = context?.operation ?? operationFromDetails(details);
1129
+ const table = context?.table ?? extractTable(resultOrError.message);
1130
+ const constraint = extractConstraint(resultOrError.message);
1131
+ const kind = classifyKind(resultOrError.status, resultOrError.code, resultOrError.message);
1132
+ return {
1133
+ kind,
1134
+ status: resultOrError.status,
1135
+ constraint,
1136
+ table,
1137
+ operation,
1138
+ message: resultOrError.message,
1139
+ raw: resultOrError
1140
+ };
1141
+ }
1142
+ if (resultOrError instanceof Error) {
1143
+ const maybeStatus = isRecord2(resultOrError) && typeof resultOrError.status === "number" ? resultOrError.status : void 0;
1144
+ return {
1145
+ kind: classifyKind(maybeStatus, void 0, resultOrError.message),
1146
+ status: maybeStatus,
1147
+ constraint: extractConstraint(resultOrError.message),
1148
+ table: context?.table ?? extractTable(resultOrError.message),
1149
+ operation: context?.operation,
1150
+ message: resultOrError.message,
1151
+ raw: resultOrError
1152
+ };
1153
+ }
1154
+ const message = typeof resultOrError === "string" ? resultOrError : "Unknown Athena error";
1155
+ return {
1156
+ kind: classifyKind(void 0, void 0, message),
1157
+ status: void 0,
1158
+ constraint: extractConstraint(message),
1159
+ table: context?.table ?? extractTable(message),
1160
+ operation: context?.operation,
1161
+ message,
1162
+ raw: resultOrError
1163
+ };
1164
+ }
1165
+ function unwrapRows(result, options) {
1166
+ if (!isOk(result)) {
1167
+ throw toAthenaGatewayError(result, "Athena request failed", options?.context);
1168
+ }
1169
+ if (result.data == null) return [];
1170
+ return Array.isArray(result.data) ? result.data : [result.data];
1171
+ }
1172
+ function unwrap(result, options) {
1173
+ if (!isOk(result)) {
1174
+ throw toAthenaGatewayError(result, "Athena request failed", options?.context);
1175
+ }
1176
+ if (result.data == null && !options?.allowNull) {
1177
+ throw toAthenaGatewayError(result, "Expected data but received null", options?.context);
1178
+ }
1179
+ return result.data;
1180
+ }
1181
+ function unwrapOne(result, options) {
1182
+ const rows = unwrapRows(result, options);
1183
+ if (!rows.length) {
1184
+ if (options?.allowNull) return null;
1185
+ throw toAthenaGatewayError(result, "Expected one row but received none", options?.context);
1186
+ }
1187
+ if (options?.requireExactlyOne && rows.length !== 1) {
1188
+ throw toAthenaGatewayError(
1189
+ result,
1190
+ `Expected exactly one row but received ${rows.length}`,
1191
+ options.context
1192
+ );
1193
+ }
1194
+ return rows[0];
1195
+ }
1196
+ function requireSuccess(result, context) {
1197
+ if (!isOk(result)) {
1198
+ throw toAthenaGatewayError(
1199
+ result,
1200
+ `Athena ${context?.operation ?? "request"} failed`,
1201
+ context
1202
+ );
1203
+ }
1204
+ return result;
1205
+ }
1206
+ function requireAffected(result, options, context) {
1207
+ requireSuccess(result, context);
1208
+ const minimum = options?.min ?? 1;
1209
+ const count = result.count;
1210
+ if (count == null) {
1211
+ throw new AthenaGatewayError({
1212
+ code: "UNKNOWN_ERROR",
1213
+ status: result.status,
1214
+ message: "Expected affected row count but response.count is missing",
1215
+ hint: 'Set call option { count: "exact" } for mutation postcondition checks.',
1216
+ cause: safeStringify(result.raw)
1217
+ });
1218
+ }
1219
+ if (count < minimum) {
1220
+ throw new AthenaGatewayError({
1221
+ code: "UNKNOWN_ERROR",
1222
+ status: result.status,
1223
+ message: `Expected at least ${minimum} affected rows but received ${count}`,
1224
+ hint: contextHint(context),
1225
+ cause: safeStringify(result.raw)
1226
+ });
1227
+ }
1228
+ return count;
1229
+ }
1230
+ function applyBounds(value, options) {
1231
+ if (options?.min !== void 0 && value < options.min) return null;
1232
+ if (options?.max !== void 0 && value > options.max) return null;
1233
+ return value;
1234
+ }
1235
+ function parseIntegerString(value) {
1236
+ const normalized = value.trim();
1237
+ if (!/^[-+]?\d+$/.test(normalized)) return null;
1238
+ const parsed = Number(normalized);
1239
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;
1240
+ return parsed;
1241
+ }
1242
+ function coerceInt(value, options) {
1243
+ if (value == null) return null;
1244
+ if (typeof value === "number") {
1245
+ if (!Number.isFinite(value) || !Number.isInteger(value)) return null;
1246
+ return applyBounds(value, options);
1247
+ }
1248
+ if (typeof value === "string") {
1249
+ const parsed = parseIntegerString(value);
1250
+ if (parsed == null) return null;
1251
+ return applyBounds(parsed, options);
1252
+ }
1253
+ if (typeof value === "bigint") {
1254
+ if (options?.strictBigInt) {
1255
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
1256
+ return null;
1257
+ }
1258
+ }
1259
+ const parsed = Number(value);
1260
+ if (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;
1261
+ return applyBounds(parsed, options);
1262
+ }
1263
+ return null;
1264
+ }
1265
+ function assertInt(value, label = "value", options) {
1266
+ const parsed = coerceInt(value, options);
1267
+ if (parsed == null) {
1268
+ throw new TypeError(`${label} must be a finite integer`);
1269
+ }
1270
+ return parsed;
1271
+ }
1272
+ function defaultShouldRetry(error) {
1273
+ const normalized = normalizeAthenaError(error);
1274
+ return normalized.kind === "transient" || normalized.kind === "rate_limit";
1275
+ }
1276
+ function computeDelayMs(attempt, error, config) {
1277
+ const baseDelay = config.baseDelayMs;
1278
+ const rawDelay = typeof config.backoff === "function" ? config.backoff(attempt, error) : config.backoff === "linear" ? baseDelay * attempt : baseDelay * Math.pow(2, attempt - 1);
1279
+ const safeDelay = Number.isFinite(rawDelay) ? Math.max(0, rawDelay) : 0;
1280
+ const clamped = Math.min(config.maxDelayMs, safeDelay);
1281
+ const jitterFactor = typeof config.jitter === "number" ? Math.max(0, Math.min(1, config.jitter)) : config.jitter ? 0.2 : 0;
1282
+ if (!jitterFactor) return clamped;
1283
+ const deviation = clamped * jitterFactor;
1284
+ const offset = (Math.random() * 2 - 1) * deviation;
1285
+ return Math.max(0, clamped + offset);
1286
+ }
1287
+ function sleep(ms) {
1288
+ if (ms <= 0) return Promise.resolve();
1289
+ return new Promise((resolve) => {
1290
+ setTimeout(resolve, ms);
1291
+ });
1292
+ }
1293
+ async function withRetry(config, fn) {
1294
+ const retries = Math.max(0, Math.trunc(config.retries));
1295
+ const shouldRetry = config.shouldRetry ?? defaultShouldRetry;
1296
+ const resolvedConfig = {
1297
+ baseDelayMs: config.baseDelayMs ?? 100,
1298
+ maxDelayMs: config.maxDelayMs ?? 1e4,
1299
+ backoff: config.backoff ?? "exponential",
1300
+ jitter: config.jitter ?? false
1301
+ };
1302
+ for (let attempts = 0; attempts <= retries; attempts += 1) {
1303
+ try {
1304
+ return await fn();
1305
+ } catch (error) {
1306
+ if (attempts >= retries) {
1307
+ throw error;
1308
+ }
1309
+ const currentAttempt = attempts + 1;
1310
+ const retry = await shouldRetry(error, currentAttempt);
1311
+ if (!retry) {
1312
+ throw error;
1313
+ }
1314
+ const delay = computeDelayMs(currentAttempt, error, resolvedConfig);
1315
+ await sleep(delay);
1316
+ }
1317
+ }
1318
+ throw new Error("withRetry reached an unexpected state");
1319
+ }
1320
+
967
1321
  exports.AthenaClient = AthenaClient;
968
1322
  exports.AthenaGatewayError = AthenaGatewayError;
969
1323
  exports.Backend = Backend;
1324
+ exports.assertInt = assertInt;
1325
+ exports.coerceInt = coerceInt;
970
1326
  exports.createClient = createClient;
971
1327
  exports.isAthenaGatewayError = isAthenaGatewayError;
1328
+ exports.isOk = isOk;
1329
+ exports.normalizeAthenaError = normalizeAthenaError;
1330
+ exports.requireAffected = requireAffected;
1331
+ exports.requireSuccess = requireSuccess;
1332
+ exports.unwrap = unwrap;
1333
+ exports.unwrapOne = unwrapOne;
1334
+ exports.unwrapRows = unwrapRows;
1335
+ exports.withRetry = withRetry;
972
1336
  //# sourceMappingURL=index.cjs.map
973
1337
  //# sourceMappingURL=index.cjs.map